branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>tien-novum/BaseFramework<file_sep>/BaseFramework/Collection/Sequence+Sort.swift // // Sequence+Sort.swift // BaseFramework // // Created by <NAME> on 25/07/2021. // import Foundation public struct SortDescriptor<Value> { var comparator: (Value, Value) -> ComparisonResult } extension SortDescriptor { public static func keyPath<T: Comparable>(_ keyPath: KeyPath<Value, T>) -> Self { Self { rootA, rootB in let valueA = rootA[keyPath: keyPath] let valueB = rootB[keyPath: keyPath] guard valueA != valueB else { return .orderedSame } return valueA < valueB ? .orderedAscending : .orderedDescending } } } public enum SortOrder { case ascending case descending } extension Sequence { public func sorted(using descriptors: SortDescriptor<Element>..., order: SortOrder) -> [Element] { sorted { valueA, valueB in for descriptor in descriptors { let result = descriptor.comparator(valueA, valueB) switch result { case .orderedSame: break case .orderedAscending: return order == .ascending case .orderedDescending: return order == .descending } } return false } } } <file_sep>/BaseFramework.podspec Pod::Spec.new do |spec| spec.name = 'BaseFramework' spec.version = '1.0.0' spec.license = { :type => 'BSD' } spec.homepage = 'https://github.com/tonymillion/Reachability' spec.authors = { '<NAME>' => '<EMAIL>' } spec.summary = 'ARC and GCD Compatible Reachability Class for iOS and OS X.' spec.source = { :git => 'https://github.com/tonymillion/Reachability.git', :tag => 'v3.1.0' } spec.source_files = 'BaseFramework/**/*.{swift,h,m}' spec.ios.deployment_target = '12.0' end
ed1be16c84d40be4d4373603bcc593101acc0630
[ "Swift", "Ruby" ]
2
Swift
tien-novum/BaseFramework
ecc42b61ba03aeb9fd2209a974ee6a66e680e0a3
3f46bb02961442043bd6f028d1dde2871c01dbc4
refs/heads/master
<file_sep>using FluentNHibernate.Cfg; using NHibernate; using NHibernate.Cfg; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; namespace BlogWeb.Infra { public class NHibernateHelper { private static ISessionFactory factory = CriaSessionFactory(); private static ISessionFactory CriaSessionFactory() { Configuration cfg = new Configuration(); cfg.Configure(); return Fluently.Configure(cfg) .Mappings(x => x.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())).BuildSessionFactory(); } public static ISession AbreSession() { return factory.OpenSession(); } } }<file_sep>using BlogWeb.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace BlogWeb.ViewModels { public class PostModel { public int Id { get; set; } [StringLength(40, ErrorMessage = "Digite no máximo 40 caracteres para o título")] public string Titulo { get; set; } [StringLength(200, ErrorMessage = "Digite no máximo 200 caracteres para o Conteúdo")] public string Conteudo { get; set; } public bool Publicado { get; set; } public DateTime? DataPublicacao { get; set; } //? para poder ser nulo [Required(ErrorMessage = "Ao menos um usuário deve ser selecionado")] public int AutorId { get; set; } public Post CriaPost() { Post post = new Post() { Id = this.Id, Titulo = this.Titulo, Conteudo = this.Conteudo, Publicado = this.Publicado, DataPublicacao = this.DataPublicacao }; if (this.AutorId != 0) { Usuario autor = new Usuario() { Id = (int)this.AutorId //Convertendo para Inteiro }; post.Autor = autor; } return post; } public PostModel() { } public PostModel (Post post) { this.Id = post.Id; this.Titulo = post.Titulo; this.Conteudo = post.Conteudo; this.Publicado = post.Publicado; this.DataPublicacao = post.DataPublicacao; if(post.Autor != null) { this.AutorId = post.Autor.Id; } } } }<file_sep>using BlogWeb.Models; using FluentNHibernate.Mapping; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BlogWeb.Mapeamentos { public class PostMapping : ClassMap<Post> { public PostMapping() { Id(p => p.Id).GeneratedBy.Identity(); Map(p => p.Titulo); Map(p => p.Conteudo); Map(p => p.DataPublicacao); Map(p => p.Publicado); References(p => p.Autor, "AutorId"); } } }<file_sep>using BlogWeb.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BlogWeb.App_Start { public class FilterConfig { public static void RegisterGlobalFlters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); filters.Add(new AutorizacaoFilterAttribute()); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BlogWeb.Models; using System.ComponentModel.DataAnnotations; namespace BlogWeb.ViewModels { public class UsuarioModel { public int Id { get; set; } [StringLength(20, ErrorMessage = "Digite no máximo 20 caracteres para o Nome")] [Required(ErrorMessage = "O campo Nome é Obrigatório")] public string Nome { get; set; } [StringLength(10, ErrorMessage = "Digite no máximo 10 caracteres para o Usuário")] [Required(ErrorMessage = "O campo Login é Obrigatório")] public string Login { get; set; } public string Password { get; set; } public string Email { get; set; } public UsuarioModel() { } public UsuarioModel(Usuario usuario) { this.Id = usuario.Id; this.Nome = usuario.Nome; this.Login = usuario.Login; this.Password = <PASSWORD>; this.Email = usuario.Email; } } }<file_sep>using BlogWeb.DAO; using BlogWeb.Filters; using BlogWeb.Models; using BlogWeb.ViewModels; using Ninject.Activation; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Security; using WebMatrix.WebData; namespace BlogWeb.Controllers { [AllowAnonymous] public class LoginController : Controller { private UsuarioDAO usuarioDAO; public LoginController(UsuarioDAO usuarioDAO) { this.usuarioDAO = usuarioDAO; if (!WebSecurity.Initialized) { WebSecurity.InitializeDatabaseConnection("blog", "Usuario", "Id", "Login", true); } } // GET: Login [Route("Login", Name = "Login")] public ActionResult Index() { return View(); } /* public ActionResult Autentica(UsuarioModel usuarioModel) { WebSecurity.Login(usuarioModel.Login, usuarioModel.Password); Usuario usuario = usuarioDAO.Busca(usuarioModel.Login, usuarioModel.Password); if (usuario != null) { Session["usuario"] = usuario; return RedirectToAction("Index", "Post"); } else { ModelState.AddModelError("login.Invalido", "Login ou senha incorretos"); return View("Index"); } }*/ public ActionResult Autentica(UsuarioModel usuarioModel, string URL) { string direciona="Home"; if (URL == "/posts") { direciona = "ListaPosts"; } else if (URL == "/Usuario") { direciona = "Usuario"; } //StringBuilder teste= new StringBuilder(); //teste.Append("<b>Capital :</b> " + URLRetorno + "<br/>"); //return Content(teste.ToString()); if (WebSecurity.Login(usuarioModel.Login, usuarioModel.Password)) { // return RedirectToAction("Index", "Post"); return RedirectToRoute(direciona); } else { ModelState.AddModelError("login.Invalido", "Login ou Senha Incorretos"); return View("Index"); } } public ActionResult Logout() { WebSecurity.Logout(); return RedirectToAction("Index", "Login"); } public ActionResult ReturnUrl() { ViewBag.URL = Request.QueryString["ReturnUrl"]; return View(); } } }<file_sep>using BlogWeb.Infra; using BlogWeb.Models; using NHibernate; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WebMatrix.WebData; namespace BlogWeb.DAO { public class UsuarioDAO { private ISession session; public UsuarioDAO(ISession session) { this.session = session; } // GET: UsuarioDao public void Adiciona(Usuario usuario) { ITransaction tx = session.BeginTransaction(); session.Save(usuario); tx.Commit(); } public IList<Usuario> Lista() { string hql = "select p from Usuario p"; IQuery query = session.CreateQuery(hql); return query.List<Usuario>(); } public void Remove(Usuario usuario) { ITransaction tx = session.BeginTransaction(); session.Delete(usuario); tx.Commit(); } public Usuario BuscaPorId(int id) { return session.Get<Usuario>(id); } public void Atualiza(Usuario usuario) { ITransaction tx = session.BeginTransaction(); session.Merge(usuario); tx.Commit(); } public Usuario Busca(string login, string senha) { string hql = "select u from Usuario u where " + "u.Login = :login and u.Password=:<PASSWORD>"; IQuery query = session.CreateQuery(hql); query.SetParameter("login", login); query.SetParameter("senha", senha); return query.UniqueResult<Usuario>();//UniqueResult para retonar apenas um único resultado } } }<file_sep>using BlogWeb.DAO; using BlogWeb.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BlogWeb.Controllers { public class MenuController : Controller { private UsuarioDAO usuarioDAO; private PostDAO postDAO; public MenuController(UsuarioDAO usuarioDAO, PostDAO postDAO) { this.usuarioDAO = usuarioDAO; this.postDAO = postDAO; } // GET: Menu public ActionResult Index() { ViewBag.Autores = usuarioDAO.Lista(); ViewBag.Data = postDAO.PublicacoesPorMes(); return PartialView(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BlogWeb.Models { public class PostsPorMes { public int? Mes { get; set; } public int? Ano { get; set; } public long Quantidade { get; set; } } }<file_sep>using BlogWeb.DAO; using BlogWeb.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BlogWeb.Controllers { public class BuscaController : Controller { private PostDAO postDAO; public BuscaController(PostDAO postDAO) { this.postDAO = postDAO; } [Route("Busca/Autor/{nome}")] public ActionResult BuscaPorAutor(string nome) { IList<Post> resultado = postDAO.ListaPublicadosDoAutor(nome); return View(resultado); } [Route("Busca/Data/{mes}/{ano}")] public ActionResult BuscaPorData(int ano,int mes) { IList<Post> resultado = postDAO.ListaPublicadosPorData(ano,mes); return View(resultado); } // GET: Busca public ActionResult Index() { return View(); } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace BlogWeb.Models { public class Post { public virtual int Id { get; set; } [StringLength(20, ErrorMessage="Digite no máximo 20 caracteres")] [Required(ErrorMessage="O campo título é Obrigatório")] public virtual string Titulo { get; set; } [StringLength(40, ErrorMessage = "Digite no máximo 40 caracteres")] [Required(ErrorMessage = "O campo Conteúdo é Obrigatório")] public virtual string Conteudo { get; set; } public virtual DateTime? DataPublicacao { get; set; } //? para poder ser nulo public virtual bool Publicado { get; set; } public virtual Usuario Autor { get; set; } } }<file_sep>using BlogWeb.Models; using BlogWeb.DAO; using BlogWeb.Infra; using NHibernate; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BlogWeb.ViewModels; using BlogWeb.Filters; using Ninject.Activation; namespace BlogWeb.Controllers { [Authorize] public class PostController : Controller { private PostDAO dao; private UsuarioDAO usuarioDAO; public PostController(PostDAO dao, UsuarioDAO usuarioDAO) { this.dao = dao; this.usuarioDAO = usuarioDAO; } // GET: Post [Route("posts", Name="ListaPosts")] public ActionResult Index() { IList<Post> posts = dao.Lista(); return View(posts); } public ActionResult Form() { // UsuarioDAO usuarioDAO = new UsuarioDAO(); ViewBag.Usuarios = usuarioDAO.Lista(); return View(); } public ActionResult Adiciona(PostModel viewModel) { if (viewModel.Publicado && !viewModel.DataPublicacao.HasValue) { ModelState.AddModelError("post.Invalido", "Posts Publicados Precisam de Data"); } if (ModelState.IsValid) { Post post = viewModel.CriaPost(); // PostDAO postDAO = new PostDAO(); dao.Adiciona(post); return RedirectToAction("Index"); } else { // UsuarioDAO usuarioDAO = new UsuarioDAO(); ViewBag.Usuarios = usuarioDAO.Lista(); return View("Form", viewModel); } } [Route("Remove/{id}", Name = "RemovePost")] public ActionResult Remove(int id) { //PostDAO dao = new PostDAO(); Post post = dao.BuscaPorId(id); dao.Remove(post); //return View(); return RedirectToAction("Index"); } [Route("altera/{id}")] public ActionResult Altera(PostModel viewModel) { if (ModelState.IsValid) { // PostDAO dao = new PostDAO(); Post post = viewModel.CriaPost(); dao.Atualiza(post); return RedirectToAction("Index"); } else { //UsuarioDAO usuarioDAO = new UsuarioDAO(); ViewBag.Usuarios = usuarioDAO.Lista(); return View("Visualiza", viewModel); } } [Route("posts/{id}", Name="VisualizaPost")] public ActionResult Visualiza(int id) { Post post = dao.BuscaPorId(id); PostModel viewModel = new PostModel(post); ViewBag.Usuarios = usuarioDAO.Lista(); return View(viewModel); } //[Route("Estatisticas", Name = "Estatisticas")] public ActionResult Estatisticas() { IList<PostsPorMes> postsporMes = dao.PublicacoesPorMes(); ViewBag.Usuarios = usuarioDAO.Lista(); return View(postsporMes); } } }<file_sep>using BlogWeb.Models; using FluentNHibernate.Mapping; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BlogWeb.Mapeamentos { public class UsuarioMapping : ClassMap<Usuario> { public UsuarioMapping() { Id(u => u.Id).GeneratedBy.Identity(); Map(u => u.Nome); Map(u => u.Login); Map(u => u.Password); Map(u => u.Email); } } } <file_sep>using BlogWeb.DAO; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BlogWeb.Models { public class HomeController : Controller { private PostDAO postDAO; public HomeController(PostDAO postDAO) { this.postDAO = postDAO; } // GET: Home [Route("Home", Name="Home")] public ActionResult Index() { IList<Post> posts = postDAO.ListaPublicados(); return View(posts); } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace BlogWeb.Models { public class Usuario { public virtual int Id { get; set; } [StringLength(20, ErrorMessage = "Digite no máximo 20 caracteres para o Nome")] [Required(ErrorMessage = "O campo Nome é Obrigatório")] public virtual string Nome { get; set; } [StringLength(10, ErrorMessage = "Digite no máximo 10 caracteres para o Usuário")] [Required(ErrorMessage = "O campo Login é Obrigatório")] public virtual string Login { get; set; } public virtual string Password { get; set; } public virtual string Email { get; set; } } }<file_sep>using BlogWeb.DAO; using BlogWeb.Filters; using BlogWeb.Infra; using BlogWeb.Models; using NHibernate; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; using WebMatrix.WebData; namespace BlogWeb.Controllers { [Authorize] public class UsuarioController : Controller { private PostDAO dao; private UsuarioDAO usuarioDAO; public UsuarioController(PostDAO dao, UsuarioDAO usuarioDAO) { this.dao = dao; this.usuarioDAO = usuarioDAO; if (!WebSecurity.Initialized) { WebSecurity.InitializeDatabaseConnection("blog", "Usuario", "Id", "Login", true); } } // GET: Usuario [Route("Usuario", Name = "Usuario")] public ActionResult Index() { //UsuarioDAO usuarioDAO = new UsuarioDAO(); //ViewBag.Posts = dao.Lista(); IList<Usuario> usuarios = usuarioDAO.Lista(); return View(usuarios); // return View(); } // GET: /Usuario/ [Route("NovoUsuario", Name = "Cadastrar")] public ActionResult Form() { return View(); } public ActionResult Adiciona(Usuario usuario) { if (ModelState.IsValid) { try { //Grava o novo usuário no banco de dados WebSecurity.CreateUserAndAccount(usuario.Login, usuario.Password, new { Email = usuario.Email, Nome = usuario.Nome }, false); return RedirectToAction("Index"); } catch (MembershipCreateUserException e) { //Se o usuário já existir, mostra um erro de validação ModelState.AddModelError("usuario.Invalido", e.Message); return View("Form"); } } else { return View("Form", usuario); }; } public ActionResult Remove(int id) { Usuario usuario = usuarioDAO.BuscaPorId(id); usuarioDAO.Remove(usuario); return RedirectToAction("Index"); } public ActionResult Visualiza(int id) { Usuario usuario = usuarioDAO.BuscaPorId(id); return View(usuario); } public ActionResult Altera(Usuario usuario) { if (ModelState.IsValid) { usuarioDAO.Atualiza(usuario); return RedirectToAction("Index"); } else { return View("Visualiza", usuario); }; } } }<file_sep>using BlogWeb.Models; using BlogWeb.Infra; using NHibernate; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using NHibernate.Transform; namespace BlogWeb.DAO { public class PostDAO { private ISession session; public PostDAO(ISession session) { this.session = session; } public IList<Post> Lista() { string hql = "select p from Post p"; IQuery query = session.CreateQuery(hql); return query.List<Post>(); } public void Adiciona(Post post) { ITransaction tx = session.BeginTransaction(); session.Save(post); tx.Commit(); } public Post BuscaPorId(int id) { return session.Get<Post>(id); } public void Remove(Post post) { ITransaction tx = session.BeginTransaction(); session.Delete(post); tx.Commit(); } public void Atualiza(Post post) { ITransaction tx = session.BeginTransaction(); session.Merge(post); tx.Commit(); } public IList<Post> ListaPublicados() { string hql = "select p from Post p where p.Publicado = true " + "order by p.DataPublicacao desc"; IQuery query = session.CreateQuery(hql); return query.List<Post>(); } public IList<Post> ListaPublicadosDoAutor(string nome) { String hql = "select p from Post p where " + "p.Publicado = true and p.Autor.Nome = :nome"; IQuery query = session.CreateQuery(hql); query.SetParameter("nome", nome); return query.List<Post>(); } public IList<Post> ListaPublicadosPorData(int ano,int mes ) { String hql = "select p from Post p where " + "year(p.DataPublicacao)=:ano and month(p.DataPublicacao)=:mes"; IQuery query = session.CreateQuery(hql); query.SetParameter("mes", mes); query.SetParameter("ano", ano); return query.List<Post>(); } public IList<PostsPorMes> PublicacoesPorMes() { String hql = "select " + "month(p.DataPublicacao) as Mes, " + "year(p.DataPublicacao) as Ano, " + "count(p) as Quantidade " + "from Post p " + "where p.Publicado = true " + "group by month(p.DataPublicacao),year(p.DataPublicacao) order by year(p.DataPublicacao) desc"; IQuery query = session.CreateQuery(hql); query.SetResultTransformer(Transformers.AliasToBean<PostsPorMes>()); IList<PostsPorMes> resultado = query.List<PostsPorMes>(); return resultado; } } }
e62449e432e0b88c7a02d3290465de1f2d1b6a4f
[ "C#" ]
17
C#
daniloscipioni/DaniloRep
979bd33a2496ff975d01d6e32bd13b313230cfbf
6af958f1a91f4914258a209560cd16c9fc72258e
refs/heads/master
<repo_name>RookY2K/scripts<file_sep>/launchWorkRDP.js const { exec } = require('child_process'); const argv = require('yargs').argv; const degradeParams = argv.degrade ? '-wallpaper' : ''; exec(`secret-tool lookup domain ${argv.domain} user ${argv.user}`, (err, stdout) => { if (err) { console.log(err); return; } exec( `xfreerdp /g:${argv.gateway} /gu:${argv.user} /gd:${argv.domain} /gp:${stdout} /v:${argv.server}` + ` /u:${argv.user} /p:${stdout} ${degradeParams}` + ' /bpp:32 /multimon +auto-reconnect /auto-reconnect-max-retries:5 +fonts +aero /microphone /sound' + ' /audio-mode:0 /cert:ignore', ); });
9fbc9efa22e78f0c20421a88ed3c47caaa4fa211
[ "JavaScript" ]
1
JavaScript
RookY2K/scripts
d899c151583e06d43647f236c3ef2db619e034ad
b0fe69998c23d49756f1abf879a3f46f421db72b
refs/heads/master
<file_sep>import todos from './modules/todos.js'; import products from './modules/products.js'; export default new Vuex.Store({ modules: { todos, products, } }) <file_sep>export default { namespaced: true, state: { todos: [ { id: 1, name: 'hacer deportes' } ], }, getters: { getTodos(state) { return state.todos } }, mutations: { ADD_TODO(state, newTodo) { state.todos.push(newTodo) }, DELETE_TODO(state, id) { const index = state.todos.findIndex(todo => todo.id == id); state.todos.splice(index, 1); } }, actions: { addTodo({ commit }, text) { const newTodo = { id: Date.now(), name: text } commit('ADD_TODO', newTodo) }, deleteTodo({ commit }, id) { commit('DELETE_TODO', id); } } }; <file_sep>import store from './state/index.js'; new Vue({ el: '#app', store, data() { return { text: '', name: '' } }, computed: { todos() { return this.$store.getters['todos/getTodos'] }, products() { return this.$store.getters['products/getProducts'] } }, methods: { addTodo() { this.$store.dispatch('todos/addTodo', this.text) this.text = ''; }, addProduct() { this.$store.dispatch('products/addProduct', this.name) this.name = ''; }, deleteTodo(id) { this.$store.dispatch('todos/deleteTodo', id); } } });<file_sep>export default { namespaced: true, state: { products: [ { id: 1, name: 'product1' }, { id: 2, name: 'product2' } ] }, getters: { getProducts(state) { return state.products } }, mutations: { ADD_PRODUCT(state, newProduct) { state.products.push(newProduct) } }, actions: { addProduct({ commit }, name) { const newProduct = { id: Date.now(), name } commit('ADD_PRODUCT', newProduct) } } };
7a845370504af3759da902f09f441c4fc5844cf6
[ "JavaScript" ]
4
JavaScript
maty07/example-vuex
f8d5b107ab9cbe20b03cab3d36ffc43d67261a6f
e9576c8e97be6995286529d9376bb1caec50c8e8
refs/heads/master
<repo_name>AdrienDelfosse/TECHNIFUTUR-EVAND1-EXO1-STARTER<file_sep>/app/src/main/java/com/technipixl/evand1/exo1/ShoppingCartActivity.kt package com.technipixl.evand1.exo1 import android.app.Activity import android.os.Bundle import android.view.Menu import android.view.View import android.widget.Button class ShoppingCartActivity : Activity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_shopping_cart) (findViewById<View>(R.id.buttonValidateShoppingCart) as Button).setOnClickListener(this) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.shopping_cart, menu) return true } override fun onClick(v: View) { when (v.id) { R.id.buttonValidateShoppingCart -> finish() else -> { //TODO: Not implemented yet } } } }<file_sep>/app/src/main/java/com/technipixl/evand1/exo1/MainActivity.kt package com.technipixl.evand1.exo1 import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.View class MainActivity : Activity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) findViewById<View>(R.id.buttonAbout).setOnClickListener(this) findViewById<View>(R.id.buttonShop).setOnClickListener(this) findViewById<View>(R.id.buttonShopingLogs).setOnClickListener(this) findViewById<View>(R.id.buttonShoppingCart).setOnClickListener(this) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onClick(v: View) { when (v.id) { R.id.buttonShop -> { val shops = Intent(this, ShopsActivity::class.java) startActivity(shops) } R.id.buttonShopingLogs -> { val shoppingLogs = Intent(this, ShoppingLogsActivity::class.java) startActivity(shoppingLogs) } R.id.buttonShoppingCart -> { val shoppingCartIntent = Intent(this, ShoppingCartActivity::class.java) startActivity(shoppingCartIntent) } R.id.buttonAbout -> { val about = Intent(this, AboutActivity::class.java) startActivity(about) } else -> { //TODO: Not implemented yet } } } }<file_sep>/app/src/main/java/com/technipixl/evand1/exo1/AboutActivity.kt package com.technipixl.evand1.exo1 import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.View class AboutActivity : Activity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) findViewById<View>(R.id.buttonContactUs).setOnClickListener(this) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.about, menu) return true } override fun onClick(view: View) { val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" val mailList = arrayOf("<EMAIL>") intent.putExtra(Intent.EXTRA_EMAIL, mailList) startActivity(Intent.createChooser(intent, "Send Email")) } }<file_sep>/app/src/main/java/com/technipixl/evand1/exo1/ShoppingLogsActivity.kt package com.technipixl.evand1.exo1 import android.app.Activity import android.app.AlertDialog import android.content.DialogInterface import android.os.Bundle import android.view.Menu import java.util.ArrayList class ShoppingLogsActivity : Activity(), DialogInterface.OnClickListener { private var shoppingLogs = mutableListOf<String>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_shopping_logs) } override fun onStart() { super.onStart() testMyLogs() } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.shopping_logs, menu) return true } private fun testMyLogs() { if (shoppingLogs.isEmpty()) { val builder = AlertDialog.Builder(this) builder.setMessage("Aucun historique n'est disponible.").setPositiveButton("Ok", this).setNegativeButton("Annuler", null) val alertDialog = builder.create() alertDialog.show() } } override fun onClick(dialog: DialogInterface, which: Int) { // TODO Auto-generated method stub } }<file_sep>/app/src/main/java/com/technipixl/evand1/exo1/ShopsActivity.kt package com.technipixl.evand1.exo1 import android.app.Activity import android.os.Bundle import android.view.Menu class ShopsActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_shop) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.shop, menu) return true } }
7055188a5340e9b0a04332250f2af0fc4dc69bf8
[ "Kotlin" ]
5
Kotlin
AdrienDelfosse/TECHNIFUTUR-EVAND1-EXO1-STARTER
55e15031a977a89a4568811a396855e77cf77b95
c6a347e7d344c1fbf20eb237298b06b118f7fcdf
refs/heads/master
<file_sep>package com.fino; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; import javax.swing.JOptionPane; import org.apache.commons.io.FileUtils; import org.apache.poi.sl.usermodel.Sheet; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Workbook; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.interactions.HasInputDevices; import org.openqa.selenium.interactions.Mouse; import org.openqa.selenium.internal.Locatable; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Reporter; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.fino.WebDriveCommon;; public class OBCOperativeAccountSummaryTest extends WebDriveCommon { FirefoxDriver driver ; public static String intiatorCorporateID="", intiatorUserID, initiatorPassword, initiatorTransactionPwd; public static String approverCorporateID="", approverUserID, approverPassword, approverTransactionPwd; //private static final String inputFileNameOBC = commPropPSN.getProperty("inputFileNameOBC"); //private static final String txnSrcFromDate = commPropPSN.getProperty("txnSrcFromDateOBC"); //private static final String txnSrcToDate = commPropPSN.getProperty("txnSrcToDateOBC"); @BeforeClass(groups=("Before"),description=("")) public void setUp() throws Exception { if (intiatorCorporateID.isEmpty()) { intiatorCorporateID = JOptionPane.showInputDialog("Enter OBC Initiator Corporate ID:"); intiatorUserID = JOptionPane.showInputDialog("Enter OBC Initiator User ID:"); initiatorPassword = JOptionPane.showInputDialog("Enter OBC Initiator Password:"); // intiatorCorporateID = "FINOFINTECHFOUNDATION"; // intiatorUserID = "SANDIP"; // initiatorPassword = "<PASSWORD>"; } //System.out.println("Hi...."+commPropPSN.getProperty("OBCCorporateURL")); launchWebDriverWithProfile("firefox", commPropPSN.getProperty("OBCCorporateURL")); driver.findElement(By.linkText("Corporate User Login")).click(); driver.findElement(By.id("AuthenticationFG.CORP_CORP_ID")).clear(); driver.findElement(By.id("AuthenticationFG.CORP_CORP_ID")).sendKeys(intiatorCorporateID); driver.findElement(By.id("AuthenticationFG.CORP_USER_ID")).clear(); driver.findElement(By.id("AuthenticationFG.CORP_USER_ID")).sendKeys(intiatorUserID); driver.findElement(By.id("STU_VALIDATE_CREDENTIALS")).click(); driver.findElement(By.id("AuthenticationFG.ACCESS_CODE")).clear(); driver.findElement(By.id("AuthenticationFG.ACCESS_CODE")).sendKeys(initiatorPassword); driver.findElement(By.id("VALIDATE_STU_CREDENTIALS")).click(); // driver.findElement(By.id("chki")).click(); // driver.findElement(By.id("img")).click(); driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS); // driver.findElement(By.xpath("//*[@class='midd-1']/div/div[3]/a[2]")).click(); ////////a[contains(@href, " + ///"'https://www.obconline.co.in/BankAwayCorporate/sgonHttpHandler.aspx?Action.CorpUser.Init.001=Y&AppSignonBankId=022&AppType=Retail')]")).click(); logInPage = PageFactory.initElements(driver, LoginPage.class); } @Test(groups="checkWAlkAway", description = "This test will be done only for one account to check credentials") public void initiateWalkAwayTransactions() throws Exception { //try { /* Check for initiator */ //logInPage.loginOBC(intiatorCorporateID, initiatorPassword, intiatorUserID); //driver.get(baseUrl + "/"); //driver.findElement(By.linkText("Corporate User Login")).click(); //driver.findElement(By.linkText("Operative Accounts")).click(); driver.findElement(By.id("Favourites_Operative-Accounts")).click(); driver.manage().timeouts().pageLoadTimeout(90000, TimeUnit.SECONDS); try { { driver.findElement(By.id("AccountSummaryFG.ACCOUNT_NUMBER")).clear(); driver.findElement(By.id("AccountSummaryFG.ACCOUNT_NUMBER")).sendKeys(); //"765011000615"); } /* File file = new File(inputFileNameOBC); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = bufferedReader.readLine()) != null) { driver.findElement(By.id("AccountSummaryFG.ACCOUNT_NUMBER")).clear(); driver.findElement(By.id("AccountSummaryFG.ACCOUNT_NUMBER")).sendKeys(line);//"765011000615"); driver.findElement(By.id("LOAD_ACCOUNTS")).click(); //driver.findElement(By.id("VIEW_TRANSACTION_HISTORY[0]0")).click(); if (isElementPresent(driver, By.id("VIEW_TRANSACTION_HISTORY[0]0"))) { mouseOverTheObject(logInPage.loadaccounts, By.xpath("//td/div/div/div/ul/li/a")); //WebDriverWait wait = new WebDriverWait(driver, 300); //if(! (wait.until(ExpectedConditions.alertIsPresent())==null)) //{ // Alert alert = driver.switchTo().alert(); // alert.accept(); // driver.switchTo().defaultContent(); //} } mouseOverTheObject(logInPage.loadaccounts, By.id("VIEW_TRANSACTION_HISTORY[0]0")); driver.findElement(By.id("VIEW_TRANSACTION_HISTORY[0]0")).click(); //new Select (driver.findElement(By.linkText("View Transaction History"))).selectByVisibleText("View Transaction History"); //driver.quit(); driver.findElement(By.id("TransactionHistoryFG.FROM_TXN_DATE_Calendar_IMG")).click(); driver.findElement(By.linkText("24")).click(); driver.findElement(By.id("TransactionHistoryFG.TO_TXN_DATE_Calendar_IMG")).click(); driver.findElement(By.linkText("27")).click(); driver.findElement(By.id("SEARCH")).click(); if(isElementPresent(driver, By.name("You have 1 Error Message[ACCTTX0083] [100130] The transactions do not exist for the account with the entered criteria."))) { //driver.manage().timeouts().implicitlyWait(90000, TimeUnit.SECONDS); driver.findElement(By.id("Button16346330")).click(); } else { new Select(driver.findElement(By.id("TransactionHistoryFG.OUTFORMAT"))).selectByVisibleText("CSV file"); driver.findElement(By.id("okButton")).click(); } //System.out.println("Dhiraj - Line: "+line); //stringBuffer.append(line); //stringBuffer.append("\n"); } fileReader.close(); */ //System.out.println("Contents of file:"); //System.out.println(stringBuffer.toString()); /*catch (IOException e) { e.printStackTrace(); }*/ //24-08-2015 //Dhiraj:JOptionPane.showMessageDialog(null, "Credentials are working fine."); }catch(Exception e){ File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File("D:\\Anita\\WorkSpace\\WebDriverDemoSAP\\Reports\\errorCheckReports.png")); Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); Reporter.log("Error occured in trial login." + writer.toString()); driver.quit();} } } /*@Test(groups=("InitiateApprove"),description=("Merge Reports"),dependsOnMethods=("initiateWalkAwayTransactions")) public void initiateTransactions() throws Exception { try { Clean Download Folders File directory = new File("D:\\Anita\\WorkSpace\\WebDriverDemoSAP\\TestData\\Downloads"); if (directory.exists()) try { delete(directory); } catch (IOException e) { e.printStackTrace(); System.exit(0); } Read Account numbers List<String> processedAccList = new ArrayList<String>(); File inputWorkbook = new File(inputFileNameOBC); Workbook w; w = Workbook.getWorkbook(inputWorkbook); // Get the first sheet Sheet sheet = w.getSheet(0); for (int i = 1; i < sheet.getRows(); i++) { Cell cell = sheet.getCell(0, i); processedAccList.add(cell.getContents()); } //new Select(driver.findElement(By.name("Options.SelectList"))).selectByVisibleText("Account Statement"); //driver.findElement(By.name("Action.Go")).click(); List<WebElement> inputs = driver.findElements(By.tagName("input")); for (WebElement input : inputs) {((JavascriptExecutor) driver).executeScript( "arguments[0].removeAttribute('readonly','readonly')",input); } for(String accountName: processedAccList) { driver.findElement(By.id("Favourites_Operative-Accounts")).click(); driver.findElement(By.id("AccountSummaryFG.ACCOUNT_NUMBER")).clear(); driver.findElement(By.id("AccountSummaryFG.ACCOUNT_NUMBER")).sendKeys(accountName); driver.findElement(By.id("LOAD_ACCOUNTS")).click(); WebElement mainMenu = driver.findElement(By.xpath("/*[@id='menu1']/div")); Actions builder = new Actions(driver); builder.moveToElement(mainMenu).build().perform(); WebDriverWait wait = new WebDriverWait(driver, 5); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='VIEW_TRANSACTION_HISTORY[0]0']"))); // until this submenu is found WebElement menuOption = driver.findElement(By.xpath("//*[@id='VIEW_TRANSACTION_HISTORY[0]0']")); menuOption.click(); //String cssLocatorOfTheElement="//*[@id='VIEW_TRANSACTION_HISTORY[0]0']" ; //JavascriptExecutor js = (JavascriptExecutor) driver; //StringBuilder stringBuilder = new StringBuilder(); // stringBuilder.append("var x = $(\'"+cssLocatorOfTheElement+"\');"); //stringBuilder.append("x.click();"); // js.executeScript(stringBuilder.toString()); //Actions action = new Actions(driver); //WebElement mainMenu = driver.findElement(By.xpath("/*[@id='menu1']/div")); //action.moveToElement(mainMenu).moveToElement(driver.findElement(By.xpath("//*[@id='VIEW_TRANSACTION_HISTORY[0]0']"))).click().build().perform(); //WebElement drop= driver.findElement(By.className("menuPullDownHead")); //Select sel=new Select(drop); //sel.selectByValue(""); //sel.selectByIndex(0); //driver.findElement(By.className("menuPullDownHead")).click(); //driver.findElement(By.id("VIEW_TRANSACTION_HISTORY[0]0")).click(); driver.findElement(By.id("TransactionHistoryFG.FROM_TXN_DATE_Calendar_IMG")).sendKeys(txnSrcFromDate); driver.findElement(By.id("TransactionHistoryFG.TO_TXN_DATE_Calendar_IMG")).sendKeys(txnSrcToDate); driver.findElement(By.id("SEARCH")).click(); if (isElementPresent(driver, By.name("Action.Accounts.SaveAs.ExcelFormat"))) driver.findElement(By.name("Action.Accounts.SaveAs.ExcelFormat")).click(); //driver.findElement(By.id("AccountSummaryFG.ACCOUNT_NUMBER")).clear(); //driver.findElement(By.id("AccountSummaryFG.ACCOUNT_NUMBER")).sendKeys(accountName); //driver.findElement(By.id("LOAD_ACCOUNTS")).click(); //mouseOverTheObject(logInPage.loadaccounts, By.xpath("(//a[contains(text(),'View Transaction History')])[2]")); //driver.manage().timeouts().pageLoadTimeout(9000, TimeUnit.SECONDS); //driver.findElement(By.id("VIEW_TRANSACTION_HISTORY[0]0")).click(); //Dhiraj:driver.findElement(By.linkText("VIEW_TRANSACTION_HISTORY[0]0")).click(); //driver.manage().timeouts().pageLoadTimeout(9000, TimeUnit.SECONDS); //driver.findElement(By.id("TransactionHistoryFG.FROM_TXN_DATE_Calendar_IMG")).click(); //driver.findElement(By.linkText("24")).click(); //driver.findElement(By.id("TransactionHistoryFG.TO_TXN_DATE_Calendar_IMG")).click(); //driver.findElement(By.linkText("27")).click(); //driver.findElement(By.id("SEARCH")).click(); driver.findElement(By.name("txnSrchSortOrder")).click(); driver.findElement(By.name("txnSrcFromDate")).clear(); driver.findElement(By.name("txnSrcFromDate")).sendKeys(txnSrcFromDate); driver.findElement(By.name("txnSrcToDate")).clear(); driver.findElement(By.name("txnSrcToDate")).sendKeys(txnSrcToDate); driver.findElement(By.xpath("(//input[@name='accountquery'])[5]")).click(); driver.findElement(By.name("Action.Accounts.QuerySelection.QueryStatement")).click(); if (isElementPresent(driver, By.name("Action.Accounts.SaveAs.ExcelFormat"))) driver.findElement(By.name("Action.Accounts.SaveAs.ExcelFormat")).click(); } isElementPresent(driver, By.name("Action.Accounts.SaveAs.QueryStatement")); boolean b = isElementPresent(driver, By.name("Action.Accounts.SaveAs.QueryStatement")); if(b) { System.out.println("Dhiraj - true"); } { System.out.println("Dhiraj - false"); } Change File Extension File folder = new File("D:\\Anita\\WorkSpace\\WebDriverDemoSAP\\TestData\\Downloads"); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { File f = new File("D:\\Anita\\WorkSpace\\WebDriverDemoSAP\\TestData\\Downloads\\"+listOfFiles[i].getName()); f.renameTo(new File("D:\\Anita\\WorkSpace\\WebDriverDemoSAP\\TestData\\Downloads\\"+i+".txt")); } } Merge Excel files MergeReports.mergeAllReportsForOBC(txnSrcFromDate, txnSrcToDate); }catch (Exception e){ File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File("D:\\Anita\\WorkSpace\\WebDriverDemoSAP\\Reports\\errorReports.png")); Log Out Reporter.log("Error occured:" + e.toString()); }//catch block ends here finally{ driver.quit(); } } private static void delete(File file) throws IOException { if (file.isDirectory()) { directory is empty, then delete it if (file.list().length == 0) { file.delete(); System.out.println("Directory is deleted *: " + file.getAbsolutePath()); } else { list all the directory contents String files[] = file.list(); for (String temp : files) { construct the file structure File fileDelete = new File(file, temp); delete(fileDelete); } } } else { file.delete(); System.out.println("File is deleted : " + file.getAbsolutePath()); } } private void mouseOverTheObject(WebElement element, By byElement) throws Exception { WebDriverWait wait = new WebDriverWait(driver, 200); Locatable hoverItem = (Locatable) element; Mouse mouse = ((HasInputDevices) driver).getMouse(); mouse.mouseMove(hoverItem.getCoordinates()); Thread.sleep(6000); wait.until(ExpectedConditions.visibilityOfElementLocated(byElement)); element.click(); } @AfterClass(groups=("After"),description=("Tear down")) public void tearDown() { driver.quit(); } }*/ } <file_sep>package com.fino; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Obc_Bank { FirefoxDriver driver; @BeforeMethod public void setuo() { driver = new FirefoxDriver(); driver.get("https://www.obconline.co.in/"); } @Test public void Test() { driver.findElement(By.xpath("html/body/div[1]/div[2]/span[2]/a")).click(); driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); driver.findElement(By.id("AuthenticationFG.CORP_CORP_ID")).sendKeys("FINOFINTECHFOUNDATION"); driver.findElement(By.id("AuthenticationFG.CORP_USER_ID")).sendKeys("SUSHMA"); driver.findElement(By.id("STU_VALIDATE_CREDENTIALS")).click(); driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); driver.findElement(By.id("AuthenticationFG.ACCESS_CODE")).clear(); driver.findElement(By.id("AuthenticationFG.ACCESS_CODE")).sendKeys("RA<PASSWORD>"); driver.findElement(By.id("VALIDATE_STU_CREDENTIALS")).click(); driver.findElement(By.id("Favourites_Operative-Accounts")).click(); driver.findElement(By.id("AccountSummaryFG.ACCOUNT_NUMBER")).sendKeys("8425015000012"); driver.findElement(By.id("LOAD_ACCOUNTS")).click(); WebElement menu= driver.findElement(By.xpath("//*[@id='menu1']/div/span")); Actions builder = new Actions(driver); builder.moveToElement(menu).build().perform(); WebDriverWait wait = new WebDriverWait(driver, 5); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='VIEW_TRANSACTION_HISTORY[0]0']"))); WebElement menuOption = driver.findElement(By.xpath("//*[@id='VIEW_TRANSACTION_HISTORY[0]0']")); menuOption.click(); } } <file_sep>#Mon Nov 23 12:16:09 IST 2015 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.1.v20150904-0015
d839c23ba1781ade41511d19c195b0c30f79158e
[ "Java", "INI" ]
3
Java
akhiS/finodesk
57b222d2f656d97a539e1aee61c289efac5efc4b
ce877477777c8f9c5ec616da3a8a692cd9b13fbc
refs/heads/master
<file_sep>import matplotlib.pyplot as plt import math import numpy as np from scipy.interpolate import interp1d from scipy.linalg import block_diag import warnings warnings.simplefilter('ignore', np.RankWarning) # x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) # y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) # z = np.polyfit(x, y, 2) # p = np.poly1d(z) # lin = np.linspace(0, 6, 100) # plt.plot([x for x in lin], [p(x) for x in lin]) # plt.plot(x, y) # plt.show() class StateFusion: last_lidar = [] stereo_his = [] vol = [] trace = [] state = [] state_his = [] state_t = [] # cov = np.zeros([6, 6]) cov = np.diag([1000, 1000, 1000]) t_approx = 0.15 * 1e9 # Q = np.diag([0.5, 0.5, 0.5, 0.5, 0.5, 0.5]) # Q = np.diag([0.001, 0.001, 0.001]) Q = np.diag([1000, 1000, 1000]) # lidar_cov = np.diag([0.5, 0.5, 0.5, 0.5, 0.5, 0.5]) lidar_cov = np.diag([0.2, 0.2, 0.2]) # stereo_cov = np.diag([0.5, 0.5, 0.5, 0.5, 0.5, 0.5]) stereo_cov = np.diag([5, 5, 5]) def A(self, t): return np.array([[1, 0, 0, t, 0, 0], [0, 1, 0, 0, t, 0], [0, 0, 1, 0, 0, t], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]]) def sensor_cb(self, data): if data['type'] == 'stereo': data['cov'] = self.lidar_cov else: data['cov'] = self.stereo_cov if data['type'] == 'stereo': self.stereo_his.append(data) return if len(self.last_lidar) == 0: if data['type'] == 'lidar': self.last_lidar = data return ts = data['t'] # - self.last_lidar['t'] self.predict(ts, data) stereo_2 = [] stereo_1 = [] for stereo in reversed(self.stereo_his): if abs(data['t'] - stereo['t']) < self.t_approx: stereo_2 = stereo break if len(stereo_2): for stereo in reversed(self.stereo_his): if stereo['t'] > self.last_lidar['t']: continue if abs(self.last_lidar['t'] - stereo['t']) < self.t_approx: stereo_1 = stereo break dp_lidar = np.array([data['p']]) - np.array([self.last_lidar['p']]) if len(stereo_2) and len(stereo_1): dp_stereo = np.array([stereo_2['p']]) - np.array([stereo_1['p']]) self.correct(ts, dp_lidar, dp_stereo) # print(data['t'] / float(1e9), stereo_2['t'] / float(1e9), self.last_lidar['t'] / float(1e9), stereo_1['t'] / float(1e9)) else: self.correct(ts, dp_lidar) # print(data['t'] / float(1e9), self.last_lidar['t'] / float(1e9)) if data['type'] == 'lidar': self.last_lidar = data def predict(self, ts, data): buf_len = 5 if len(self.state_his) < buf_len: self.state_his.append(data) return t = np.array([self.state_his[ii]['t'] for ii in range(len(self.state_his) - buf_len, len(self.state_his))]) p = np.array([self.state_his[ii]['p'] for ii in range(len(self.state_his) - buf_len, len(self.state_his))]) # print(t) fitx = np.poly1d(np.polyfit(t, p[:, 0], 1)) fity = np.poly1d(np.polyfit(t, p[:, 1], 1)) fita = np.poly1d(np.polyfit(t, p[:, 2], 1)) if len(self.state) == 0: self.state = {} self.state['p'] = [fitx(data['t']), fity(data['t']), fita(data['t'])] self.cov = self.Q self.wrap_angles(self.state['p']) pass def correct(self, ts, dp_lidar, dp_stereo = []): inf = 1000000 x1 = np.array([[0, 0, 0]]).transpose() q1 = np.diag([inf, inf, inf]) x2 = x1.copy() q2 = q1.copy() x3 = x1.copy() q3 = q1.copy() if len(self.state): x1 = (np.array([self.state['p']]) - np.array([self.state_his[-1]['p']])).transpose() q1 = self.cov pass x2 = dp_lidar.transpose() q2 = self.lidar_cov if len(dp_stereo): x3 = dp_stereo.transpose() q3 = self.stereo_cov x_hat = np.vstack((x1, x2, x3)) P = block_diag(q1, q2, q3) P_inv = np.linalg.inv(P) M = np.vstack((np.identity(3), np.identity(3), np.identity(3))) P_tilde = np.linalg.inv((M.transpose().dot(P_inv)).dot(M)) x_tilde = ((P_tilde.dot(M.transpose())).dot(P_inv)).dot(x_hat) if len(self.state) == 0: self.state = {} ppp = self.state_his[-1]['p'] + x_tilde[:, 0] self.state['p'] = [ppp[0], ppp[1], ppp[2]] self.state['t'] = ts self.state_his.append(self.state) self.cov = P[0:3, 0:3] self.trace.append(self.state['p']) print(self.state['p']) pass # def predict(self, data): # if len(self.state) == 0: # self.state = np.array(data['p'] + data['v']).transpose() # self.state_t = data['t'] # self.cov = self.Q # return # t = data['t'] - self.state_t # self.state_t = data['t'] # A = self.A(t / 10e9) # self.state = A.dot(self.state) # self.wrap_angles(self.state) # self.cov = A.dot(self.cov).dot(A.transpose()) + self.Q # # self.cov = self.Q # # print(self.cov) # pass # def correct(self, data): # x_hat = np.concatenate((self.state, data['p'] + data['v'])) # P = np.zeros((12, 12)) # for c in range(0, 6): # for r in range(0, 6): # P[r, c] = self.cov[r, c] # for c in range(0, 6): # for r in range(0, 6): # P[r + 6, c + 6] = data['cov'][r, c] # P_inv = np.linalg.inv(P) # M = np.vstack((np.identity(6), np.identity(6))) # P_tilde = np.linalg.inv(M.transpose().dot(P_inv).dot(M)) # P_tilde = M.dot(P_tilde).dot(M.transpose()) # x_tilde = P_tilde.dot(P_inv).dot(x_hat) # self.state = x_tilde[0:6] # self.cov = P_tilde[0:6, 0:6] # self.wrap_angles(self.state) # self.trace.append(self.state) # pass def wrap_angles(self, state): while state[2] > math.pi: state[2] = state[2] - math.pi while state[2] < -math.pi: state[2] = state[2] + math.pi ####################################################### state_fusion = StateFusion() stop = 1570543968000000000 filename = "/home/kevin/pf_cpf/data/pamr_pose.txt" lidar_ts = [] lidar_pose = [] with open(filename) as f: for line in f: parse = line.strip().split() if int(parse[0]) > stop: break lidar_ts.append(int(parse[0])) lidar_pose.append([float(parse[1]), float(parse[2]), float(parse[3])]) filename = "/home/kevin/pf_cpf/data/orb_pose.txt" stereo_ts = [] stereo_pose = [] i = -1 with open(filename) as f: for line in f: i = i + 1 if (i % 5) != 0: continue parse = line.strip().split() if int(parse[0]) > stop: break stereo_ts.append(int(parse[0])) stereo_pose.append([float(parse[1]), float(parse[2]), float(parse[3])]) dx = lidar_pose[0][0] - stereo_pose[0][0] dy = lidar_pose[0][1] - stereo_pose[0][1] for i in range(0, len(stereo_pose)): stereo_pose[i][0] += dx stereo_pose[i][1] += dy stereo_idx = 0 lidar_idx = 0 while (stereo_idx < (len(stereo_ts) - 1)) or (lidar_idx < (len(lidar_ts) - 1)): stereo = {'t': stereo_ts[stereo_idx], 'p': [stereo_pose[stereo_idx][0], stereo_pose[stereo_idx][1], stereo_pose[stereo_idx][2]], 'type': 'stereo'} lidar = {'t': lidar_ts[lidar_idx], 'p': [lidar_pose[lidar_idx][0], lidar_pose[lidar_idx][1], lidar_pose[lidar_idx][2]], 'type': 'lidar'} if (stereo['t'] > (stop - 1000000000)) or (lidar['t'] > (stop - 1000000000)): break # print(stereo['t'], lidar['t']) if stereo['t'] < lidar['t']: state_fusion.sensor_cb(stereo) if stereo_idx < (len(stereo_ts) - 1): stereo_idx = stereo_idx + 1 else: state_fusion.sensor_cb(lidar) if lidar_idx < (len(lidar_ts) - 1): lidar_idx = lidar_idx + 1 gth = [] gth.append([0, -164, 90]) gth.append([-14.3, 0, 100]) gth.append([-15.4, 30, 100]) gth.append([-22, 60, 90]) gth.append([-33.8, 90, 45]) gth.append([-30, 105, 30]) gth.append([-13.1, 120, 20]) gth.append([0, 132.5, 10]) gth.append([30, 140, 10]) gth.append([60, 143.8, -5]) gth.append([90, 138.5, -5]) gth.append([120, 136.6, -3]) gth.append([150, 135.1, -2]) gth.append([180, 129.7, -2]) gth.append([210, 126.8, -2]) gth.append([240, 123.1, 0]) gth.append([270, 122.5, 0]) gth.append([300, 122.1, 0]) gth.append([330, 121.6, 0]) gth.append([360, 120.7, 0]) gth.append([390, 123.5, 3]) gth.append([420, 124, 3]) gth.append([450, 125.4, 4]) gth.append([465, 126.9, 5]) gth.append([495, 118.7, 30]) gth.append([525, 118, 50]) gth.append([555, 150, 80]) gth.append([561.9, 180, 90]) gth.append([563, 210, 95]) gth.append([559.8, 240, 100]) gth.append([556.7, 270, 100]) gth.append([555, 300, 105]) gth.append([548.7, 330, 105]) gth.append([542.8, 360, 100]) gth.append([540, 390, 95]) gth.append([538, 420, 93]) gth.append([536.8, 450, 90]) gth.append([536.8, 480, 90]) gth.append([534.5, 510, 85]) gth.append([537.7, 540, 85]) gth.append([537.5, 570, 85]) gth.append([540, 600, 80]) gth.append([542, 630, 75]) gth.append([545.1, 660, 70]) gth.append([549.2, 690, 70]) gth.append([555.6, 720, 70]) gth.append([563.6, 750, 70]) gth.append([567.5, 780, 75]) gth.append([570, 810, 80]) gth.append([572.5, 840, 85]) gth.append([572.3, 870, 90]) gth.append([572.2, 900, 93]) gth.append([570.5, 930, 95]) gth.append([569.5, 960, 95]) gth.append([569.3, 990, 92]) gth.append([568, 1020, 91]) gth.append([566.8, 1050, 90]) gth.append([567.2, 1080, 90]) gth.append([567.6, 1110, 90]) gth.append([566.7, 1140, 90]) gth.append([566.8, 1170, 92]) gth.append([563, 1200, 92]) gth.append([561.6, 1230, 92]) gth.append([558, 1260, 92]) gth.append([557.5, 1290, 90]) gth.append([547.4, 1320, 65]) # gth.append([540, 1335.2, 45]) gth.append([540, 1350, 35]) gth.append([568.8, 1380, 30]) gth.append([600, 1396.4, 10]) gth.append([630, 1404, 5]) gth.append([660, 1406.2, 1]) gth.append([690, 1405.7, -2]) gth.append([720, 1398.1, 0]) gth.append([750, 1397.8, 0]) gth.append([780, 1395.9, 0]) gth.append([810, 1394.5, 0]) gth.append([840, 1392.5, 2]) gth.append([870, 1393, 3]) gth.append([900, 1393, 4]) gth.append([930, 1395, 5]) gth.append([960, 1397.8, 5]) gth.append([990, 1403, 5]) gth.append([1020, 1407, 5]) gth.append([1042.5, 1410, 4]) for i in range(0, len(gth)): x = gth[i][0] + 35 * math.cos(gth[i][2] * math.pi / 180.0) y = gth[i][1] + 35 * math.sin(gth[i][2] * math.pi / 180.0) + 164 - 35 x = x / 100.0 + 2.0 y = y / 100.0 - 2.7 gth[i] = [x, y] for i in range(len(lidar_pose)): if abs(lidar_pose[i][0]) > 10 or abs(lidar_pose[i][1]) > 10: lidar_pose[i][0] = 0 lidar_pose[i][1] = 0 # print(len(stereo_ts), len(lidar_pose)) plt.figure(0) plt.plot([lidar_pose[i][0] for i in range(len(lidar_pose))], [lidar_pose[i][1] for i in range(len(lidar_pose))], '.', label='lidar', markersize=1) plt.plot([stereo_pose[i][0] for i in range(len(stereo_pose))], [stereo_pose[i][1] for i in range(len(stereo_pose))], '.', label='stereo', markersize=1) # plt.plot([gth[i][0] for i in range(len(gth))], # [gth[i][1] for i in range(len(gth))], # '.', label='groundtruth', markersize=1) plt.plot([state_fusion.trace[i][0] for i in range(len(state_fusion.trace))], [state_fusion.trace[i][1] for i in range(len(state_fusion.trace))], '.', label='cpf', markersize=1) plt.legend(loc='upper left') plt.gca().set_aspect('equal') plt.figure(1) plt.plot([i for i in range(len(state_fusion.vol))], [state_fusion.vol[i][0] for i in range(len(state_fusion.vol))], '.', markersize=5) # plt.plot([i for i in range(len(state_fusion.vol))], # [state_fusion.vol[i][1] for i in range(len(state_fusion.vol))], '.', markersize=3) # plt.plot([i for i in range(len(state_fusion.vol))], # [state_fusion.vol[i][2] for i in range(len(state_fusion.vol))], '.', markersize=3) plt.show() # filename = "/home/kevin/KeyFrameTrajectory_TUM_Format.txt" # stereo_ts = [] # stereo_pose = [] # i = -1 # with open(filename) as f: # for line in f: # # i = i + 1 # # if (i % 5) != 0: # # continue # parse = line.strip().split() # # stereo_ts.append(int(parse[0])) # stereo_pose.append([float(parse[1]), float(parse[2]), float(parse[3])]) # plt.figure(2) # plt.plot([stereo_pose[i][0] for i in range(len(stereo_pose))], # [stereo_pose[i][2] for i in range(len(stereo_pose))], # '.', label='stereo', markersize=1) # plt.gca().set_aspect('equal') # plt.show()<file_sep>import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import math import numpy as np from scipy.interpolate import interp1d from scipy.linalg import block_diag import warnings warnings.simplefilter('ignore', np.RankWarning) class StateFusion: def __init__(self): self.last_stereo = None self.last_lidar = None self.state = [] self.ts = [] self.stereo_cov = np.diag([0.0008, 0.0008, 10000000]) self.model_cov = np.diag([100.0001, 100.0001, 10000000]) self.lidar_cov = np.diag([0.0001, 0.0001, 10000000]) self.d = [] self.d9 = 16.9 pass def sensor_cb(self, data): if data['type'] == 'lidar': self.last_lidar = data scale = 0.1 self.lidar_cov[0, 0] = data['cov'][0] * scale self.lidar_cov[1, 1] = data['cov'][1] * scale self.lidar_cov[2, 2] = data['cov'][2] * scale if len(self.state) == 0: self.state.append(np.array([data['p']]).transpose()) self.ts.append(data['t']) self.d.append(0) return if len(self.state) == 0: self.last_stereo = data return if self.last_stereo is None: self.last_stereo = data if self.last_lidar is not None: self.state.append(np.array([self.last_lidar['p']]).transpose()) self.ts.append(data['t']) self.d.append(0) return stereo_state = self.state[-1] + np.array([data['p']]).transpose() - np.array([self.last_stereo['p']]).transpose() model_state = self.model_state(data['t']) if self.last_lidar is None: print('error') lidar_state = np.array([self.last_lidar['p']]).transpose() (state, cov, d) = self.cpf(stereo_state, model_state, lidar_state, True) self.d.append(d) self.state.append(state) self.ts.append(data['t']) self.last_stereo = data self.wrap_angles(self.state[-1]) pass def cpf(self, stereo, model, lidar, test=True): # print(stereo, model, lidar) inf = 10000000 P1 = self.stereo_cov.copy() P2 = self.model_cov.copy() P3 = self.lidar_cov.copy() if stereo is None: stereo = np.array([[0, 0, 0]]).transpose() P1 = np.diag([inf, inf, inf]) if model is None: model = np.array([[0, 0, 0]]).transpose() P2 = np.diag([inf, inf, inf]) if lidar is None: lidar = np.array([[0, 0, 0]]).transpose() P3 = np.diag([inf, inf, inf]) x_hat = np.vstack((stereo, model, lidar)) P = block_diag(P1, P2, P3) # print(x_hat) P_inv = np.linalg.inv(P) M = np.vstack((np.identity(3), np.identity(3), np.identity(3))) P_tilde = np.linalg.inv((M.transpose().dot(P_inv)).dot(M)) x_tilde = ((P_tilde.dot(M.transpose())).dot(P_inv)).dot(x_hat) # print(x_tilde, P_tilde) x_tilde3 = np.vstack((x_tilde, x_tilde, x_tilde)) d = (((x_hat - x_tilde3).transpose()).dot(P_inv)).dot(x_hat - x_tilde3)[0][0] if d > 30: d = 30 if test: if d > self.d9: (state1, cov1, d1) = self.cpf(None, model, lidar, False) (state2, cov2, d2) = self.cpf(stereo, None, lidar, False) (state3, cov3, d3) = self.cpf(stereo, model, None, False) if d1 < d2 and d1 < d3: x_tilde = state1.copy() if d2 < d1 and d2 < d3: x_tilde = state2.copy() if d3 < d1 and d3 < d2: x_tilde = state3.copy() return x_tilde, P_tilde, d pass def model_state(self, ts): buf_len = 10 if len(self.state) < buf_len: return None t = np.array([self.ts[ii] for ii in range(len(self.ts) - buf_len, len(self.ts))]) p = np.array([self.state[ii].transpose()[0] for ii in range(len(self.state) - buf_len, len(self.state))]) # print(p) fitx = np.poly1d(np.polyfit(t, p[:, 0], 1)) fity = np.poly1d(np.polyfit(t, p[:, 1], 1)) fita = np.poly1d(np.polyfit(t, p[:, 2], 1)) return np.array([[fitx(ts), fity(ts), fita(ts)]]).transpose() pass def wrap_angles(self, state): while state[2] > math.pi: state[2] = state[2] - math.pi while state[2] < -math.pi: state[2] = state[2] + math.pi ####################################################### state_fusion = StateFusion() outlier_removal = StateFusion() outlier_removal.d9 = 10000 filename = "./data/orb_pose.txt" stereo_ts = [] stereo_pose = [] i = -1 with open(filename) as f: for line in f: i = i + 1 if (i % 10) != 0: continue parse = line.strip().split() stereo_ts.append(int(parse[0])) measurement = [float(parse[1]) * 0.75, float(parse[2]) * 0.75, float(parse[3])] stereo_pose.append(measurement) filename = "./data/pamr_pose.txt" lidar_ts = [] lidar_pose = [] lidar_cov = [] i = -1 with open(filename) as f: for line in f: # i = i + 1 # if (i % 10) != 0: # continue parse = line.strip().split() # if len(lidar_ts): # if int(parse[0]) == lidar_ts[-1]: # continue lidar_ts.append(int(parse[0])) lidar_cov.append([float(parse[4]), float(parse[5]), float(parse[6])]) # x = -0.3 # y = 0 # phi = float(parse[3]) # h = float(parse[1]) # k = float(parse[2]) # xx = x * math.cos(phi) - y * math.sin(phi) + h # yy = x * math.sin(phi) + y * math.cos(phi) + k xx = float(parse[1]) yy = float(parse[2]) if len(lidar_pose): xx = xx - lidar_pose[0][0] yy = yy - lidar_pose[0][1] else: lidar_pose.append([xx, yy, 0]) continue angle = 180 s = math.sin(angle * math.pi / 180) c = math.cos(angle * math.pi / 180) xxx = xx * c - yy * s yyy = xx * s + yy * c lidar_pose.append([xxx, yyy, float(parse[3])]) del lidar_pose[0] stereo_idx = 0 lidar_idx = 0 while (stereo_idx < (len(stereo_ts) - 1)) and (lidar_idx < (len(lidar_ts) - 1)): stereo = {'t': stereo_ts[stereo_idx], 'p': [stereo_pose[stereo_idx][0], stereo_pose[stereo_idx][1], stereo_pose[stereo_idx][2]], 'type': 'stereo'} lidar = {'t': lidar_ts[lidar_idx], 'p': [lidar_pose[lidar_idx][0], lidar_pose[lidar_idx][1], lidar_pose[lidar_idx][2]], 'cov': lidar_cov[lidar_idx], 'type': 'lidar'} if stereo['t'] < lidar['t']: state_fusion.sensor_cb(stereo.copy()) outlier_removal.sensor_cb(stereo.copy()) if stereo_idx < (len(stereo_ts) - 1): stereo_idx = stereo_idx + 1 else: state_fusion.sensor_cb(lidar.copy()) outlier_removal.sensor_cb(lidar.copy()) if lidar_idx < (len(lidar_ts) - 1): lidar_idx = lidar_idx + 1 plt.figure(0) plt.plot([lidar_pose[i][0] for i in range(len(lidar_pose))], [lidar_pose[i][1] for i in range(len(lidar_pose))], '-', label='lidar', markersize=1, linewidth=1) plt.plot([stereo_pose[i][0] for i in range(len(stereo_pose))], [stereo_pose[i][1] for i in range(len(stereo_pose))], '-', label='camera', markersize=1, linewidth=1) plt.plot([state_fusion.state[i][0] for i in range(len(state_fusion.state))], [state_fusion.state[i][1] for i in range(len(state_fusion.state))], '-', label='cpf', linewidth=3) plt.plot([outlier_removal.state[i][0] for i in range(len(outlier_removal.state))], [outlier_removal.state[i][1] for i in range(len(outlier_removal.state))], '-', label='cpf_outlier', linewidth=1) plt.title('global position / meter') plt.legend(loc='lower right') plt.gca().set_aspect('equal') plt.figure(1) plt.plot([(state_fusion.ts[i] - state_fusion.ts[0]) / 1e11 for i in range(0, len(state_fusion.ts))], [state_fusion.d[i] for i in range(0, len(state_fusion.d))], '-', label='distance', markersize=1) plt.plot([(state_fusion.ts[i] - state_fusion.ts[0]) / 1e11 for i in range(0, len(state_fusion.ts))], [state_fusion.d9 for i in range(0, len(state_fusion.d))], '-', label='threshold', markersize=1) plt.legend(loc='upper right') plt.title('CPF distance (m) over time (sec)') print(state_fusion.state[-1][0], state_fusion.state[-1][1]) plt.show()<file_sep>import matplotlib.pyplot as plt import math import numpy as np from scipy.interpolate import interp1d from scipy.linalg import block_diag import warnings warnings.simplefilter('ignore', np.RankWarning) class StateFusion: def __init__(self): self.last_lidar = [] self.stereo_his = [] self.trace = [] self.state = [] self.state_his = [] self.d = [] # cov = np.diag([0.1, 0.1, 0.1]) self.cov = np.diag([0.1, 0.1, 0.1]) self.t_approx = 0.2 * 1e9 self.Q = np.diag([0.0221, 0.0221, 0.033]) # * 0.3 # Q = np.diag([0.007, 0.007, 0.0733]) self.lidar_cov = np.diag([1.0334, 10.0334, 10.0433]) # * 0.3 self.stereo_cov = np.diag([0.0353, 0.0353, 0.0388]) # * 0.3 # self.stereo_cov = np.diag([0.0203, 0.0103, 0.0388]) * 0.03 self.d9 = 16.9 self.trace_t = [] def sensor_cb(self, data): if data['type'] == 'stereo': self.stereo_his.append(data) return if len(self.last_lidar) == 0: if data['type'] == 'lidar': self.last_lidar = data # return ts = data['t'] self.predict(ts, data) stereo_2 = [] stereo_1 = [] for stereo in reversed(self.stereo_his): if abs(data['t'] - stereo['t']) < self.t_approx: stereo_2 = stereo break if len(stereo_2): for stereo in reversed(self.stereo_his): if stereo['t'] > self.last_lidar['t']: continue if abs(self.last_lidar['t'] - stereo['t']) < self.t_approx: stereo_1 = stereo break dp_lidar = np.array([data['p']]) - np.array([self.last_lidar['p']]) if len(stereo_2) and len(stereo_1): dp_stereo = np.array([stereo_2['p']]) - np.array([stereo_1['p']]) self.correct(ts, dp_lidar, dp_stereo) else: self.correct(ts, dp_lidar) if data['type'] == 'lidar': self.last_lidar = data def predict(self, ts, data): buf_len = 5 if len(self.state_his) < buf_len: self.state_his.append(data) return t = np.array([self.state_his[ii]['t'] for ii in range(len(self.state_his) - buf_len, len(self.state_his))]) p = np.array([self.state_his[ii]['p'] for ii in range(len(self.state_his) - buf_len, len(self.state_his))]) # # print(t) fitx = np.poly1d(np.polyfit(t, p[:, 0], 2)) fity = np.poly1d(np.polyfit(t, p[:, 1], 2)) fita = np.poly1d(np.polyfit(t, p[:, 2], 2)) state = {} state['p'] = [fitx(data['t']), fity(data['t']), fita(data['t'])] self.cov = self.Q self.wrap_angles(state['p']) self.state_his.append(state) pass def correct(self, ts, dp_lidar, dp_stereo = []): inf = 10000000000 x1 = np.array([[0, 0, 0]]).transpose() q1 = np.diag([inf, inf, inf]) x2 = x1.copy() q2 = q1.copy() x3 = x1.copy() q3 = q1.copy() if len(self.state_his) > 2: x1 = (np.array([self.state_his[-1]['p']]) - np.array([self.state_his[-2]['p']])).transpose() q1 = self.cov x2 = dp_lidar.transpose() q2 = self.lidar_cov if len(dp_stereo): x3 = dp_stereo.transpose() q3 = self.stereo_cov x_hat = np.vstack((x1, x2, x3)) P = block_diag(q1, q2, q3) P_inv = np.linalg.inv(P) M = np.vstack((np.identity(3), np.identity(3), np.identity(3))) P_tilde = np.linalg.inv((M.transpose().dot(P_inv)).dot(M)) x_tilde = ((P_tilde.dot(M.transpose())).dot(P_inv)).dot(x_hat) np.set_printoptions(precision=3, suppress=True) if len(self.state_his) < 2: ppp = self.state_his[-1]['p'] + x_tilde[:, 0] else: ppp = self.state_his[-2]['p'] + x_tilde[:, 0] state = {} state['p'] = [ppp[0], ppp[1], ppp[2]] state['t'] = ts self.state_his[-1] = state self.cov = P[0:3, 0:3] self.trace.append(state['p']) self.trace_t.append(ts) x_tilde3 = np.vstack((x_tilde, x_tilde, x_tilde)) d = (((x_hat - x_tilde3).transpose()).dot(P_inv)).dot(x_hat - x_tilde3)[0][0] self.d.append([ts / 1e9, d]) if d > self.d9: ppp = self.state_his[-2]['p'] + x2[:, 0] P[6, 6] = inf P[7, 7] = inf P[8, 8] = inf P_inv = np.linalg.inv(P) P_tilde = np.linalg.inv((M.transpose().dot(P_inv)).dot(M)) x_tilde = ((P_tilde.dot(M.transpose())).dot(P_inv)).dot(x_hat) if len(self.state_his) < 2: ppp = self.state_his[-1]['p'] + x_tilde[:, 0] else: ppp = self.state_his[-2]['p'] + x_tilde[:, 0] state['p'] = [ppp[0], ppp[1], ppp[2]] self.state_his[-1] = state self.trace[-1] = state['p'] pass def wrap_angles(self, state): while state[2] > math.pi: state[2] = state[2] - math.pi while state[2] < -math.pi: state[2] = state[2] + math.pi ####################################################### state_fusion = StateFusion() outlier_removal = StateFusion() outlier_removal.d9 = 10000 filename = "/home/kevin/pf_cpf/data/orb_pose.txt" stereo_ts = [] stereo_pose = [] with open(filename) as f: for line in f: parse = line.strip().split() stereo_ts.append(int(parse[0])) measurement = [float(parse[1]) * 1.06, float(parse[2]) * 1.06, float(parse[3])] stereo_pose.append(measurement) filename = "/home/kevin/pf_cpf/data/pamr_pose.txt" lidar_ts = [] lidar_pose = [] i = -1 with open(filename) as f: for line in f: i = i + 1 if (i % 10) != 0: continue parse = line.strip().split() if len(lidar_ts): if int(parse[0]) == lidar_ts[-1]: continue lidar_ts.append(int(parse[0])) x = -0.3 y = 0 phi = float(parse[3]) h = float(parse[1]) k = float(parse[2]) xx = x * math.cos(phi) - y * math.sin(phi) + h yy = x * math.sin(phi) + y * math.cos(phi) + k if len(lidar_pose): xx = xx - (lidar_pose[0][0] - 0) yy = yy - (lidar_pose[0][1] - 0) lidar_pose.append([xx, yy, float(parse[3])]) stereo_idx = 0 lidar_idx = 0 while (stereo_idx < (len(stereo_ts) - 1)) and (lidar_idx < (len(lidar_ts) - 1)): stereo = {'t': stereo_ts[stereo_idx], 'p': [stereo_pose[stereo_idx][0], stereo_pose[stereo_idx][1], stereo_pose[stereo_idx][2]], 'type': 'stereo'} lidar = {'t': lidar_ts[lidar_idx], 'p': [lidar_pose[lidar_idx][0], lidar_pose[lidar_idx][1], lidar_pose[lidar_idx][2]], 'type': 'lidar'} if stereo['t'] < lidar['t']: state_fusion.sensor_cb(stereo.copy()) outlier_removal.sensor_cb(stereo.copy()) if stereo_idx < (len(stereo_ts) - 1): stereo_idx = stereo_idx + 1 else: state_fusion.sensor_cb(lidar.copy()) outlier_removal.sensor_cb(lidar.copy()) if lidar_idx < (len(lidar_ts) - 1): lidar_idx = lidar_idx + 1 # for i in range(len(lidar_pose)): # if abs(lidar_pose[i][0]) > 10 or abs(lidar_pose[i][1]) > 10: # lidar_pose[i][0] = 0 # lidar_pose[i][1] = 0 # del lidar_pose[-3:] # del lidar_ts[-3:] # del stereo_pose[-2:] # del stereo_ts[-2:] # del state_fusion.trace[-2:] # del state_fusion.trace_t[-2:] # del outlier_removal.trace[-1:] # del outlier_removal.trace_t[-1:] plt.figure(0) plt.plot([lidar_pose[i][0] for i in range(len(lidar_pose))], [lidar_pose[i][1] for i in range(len(lidar_pose))], '-', label='lidar', linewidth=1) plt.plot([stereo_pose[i][0] for i in range(len(stereo_pose))], [stereo_pose[i][1] for i in range(len(stereo_pose))], '-', label='stereo', linewidth=1) plt.plot([state_fusion.trace[i][0] for i in range(len(state_fusion.trace))], [state_fusion.trace[i][1] for i in range(len(state_fusion.trace))], '-', label='cpf', linewidth=1) plt.plot([outlier_removal.trace[i][0] for i in range(len(outlier_removal.trace))], [outlier_removal.trace[i][1] for i in range(len(outlier_removal.trace))], '-', label='cpf_outlier', linewidth=1) plt.title('global position / meter') # ground = np.loadtxt('data/groundtruth.txt') # print("(%f, %f, %f) vs. (%f, %f, %f) " % # (ground[-1, 0], ground[-1, 1], ground[-1, 2], # state_fusion.trace[-1][0], state_fusion.trace[-1][1], state_fusion.trace[-1][2])) # plt.plot(ground[:, 0], ground[:, 1], '-', label='ground-truth', markersize=1) plt.legend(loc='upper right') plt.gca().set_aspect('equal') # for i in range(0, len(state_fusion.d)): # if state_fusion.d[i][0] < 0.1: # print(i) plt.figure(1) plt.plot([state_fusion.d[i][0] for i in range(0, len(state_fusion.d))], [state_fusion.d[i][1] for i in range(0, len(state_fusion.d))], '-', label='d', markersize=1) # plt.plot([state_fusion.d[i][0] for i in range(0, len(state_fusion.d))], # [16.9 for i in range(0, len(state_fusion.d))], '-') plt.legend(loc='upper right') plt.title('CPF distance over time') # plt.figure(2) # plt.plot([lidar_ts[i] for i in range(len(lidar_ts))], # [math.degrees(lidar_pose[i][2]) for i in range(len(lidar_pose))], # '-', label='lidar', markersize=1) # plt.plot([stereo_ts[i] for i in range(len(stereo_pose))], # [math.degrees(stereo_pose[i][2]) for i in range(len(stereo_pose))], # '-', label='stereo', markersize=1) # plt.plot([state_fusion.trace_t[i] for i in range(len(state_fusion.trace_t))], # [math.degrees(state_fusion.trace[i][2]) for i in range(len(state_fusion.trace))], # '-', label='cpf', markersize=1) # plt.plot([outlier_removal.trace_t[i] for i in range(len(outlier_removal.trace_t))], # [math.degrees(outlier_removal.trace[i][2]) for i in range(len(outlier_removal.trace))], # '-', label='cpf_outlier', markersize=1) # # ground = np.delete(ground, -1, 0) # # plt.plot([ground[i][4] for i in range(len(ground))], # # [math.degrees(ground[i][2]) for i in range(len(ground))], # # '-', label='groundtruth', markersize=1) # plt.legend(loc='upper right') # plt.title('global heading (degree) over time') plt.show()<file_sep>import numpy as np import matplotlib.pyplot as plt import math import copy from scipy.interpolate import interp1d bound = (0.0, 20.0) step_size = (bound[1] - bound[0]) / 10 d_threshold = 40 def H(state): # return np.sin(50 * np.deg2rad(state)) x = np.linspace(0, 30, num=11, endpoint=True) y = np.cos(-x ** 2 / 9.0) f = interp1d(x, y, kind='cubic') # f = interp1d([0, 5, 10, 15, 20, 25, 30], 2.0 * np.array([0, 0.1, 0.3, 0.34, 0.5, 0.9, 1.4]), 'cubic') return f(state) class Particle: s = [] m = [] d = float('inf') particles = [] particle_num = 100 for i in range(0, particle_num): particle = Particle() particle.s = np.random.uniform(bound[0], bound[1]) particle.m = H(particle.s) particles.append(particle) ground = Particle() ground.s = (bound[1] - bound[0]) / 20.0 model = copy.deepcopy(ground) # dev_s = step_size * 0.1 # dev_m = 0.3 dev_s = 0.3 dev_m = 0.3 manager = plt.get_current_fig_manager() manager.full_screen_toggle() def cpf(particle, model): x_hat = np.array([model.s, model.m]).transpose() x_tilde = np.array([particle.s, particle.m]).transpose() P = np.array([[math.pow(dev_s, 2), 0], [0, math.pow(dev_m, 2)]]) P_inv = np.linalg.inv(P) return (x_hat - x_tilde).transpose().dot(P_inv).dot(x_hat - x_tilde) for step in range(0, 8): model.s += step_size model.m = H(model.s) ground.s += step_size + np.random.normal(0, dev_s, 1) ground.m = H(ground.s) + np.random.normal(0, dev_m, 1) model.m = ground.m for particle in particles: particle.s += step_size + np.random.normal(0, dev_s, 1)[0] particle.m = H(particle.s) best = Particle() for particle in particles: particle.d = cpf(particle, model) if particle.d < best.d: best = copy.deepcopy(particle) particles.sort(key=lambda p: p.d) index = int(len(particles) * 0.5) for i in range(index, len(particles)): lottery = int(index * np.random.uniform(0.0, 1.0)) particles[i] = copy.deepcopy(particles[lottery]) sin_x = np.arange(bound[0], bound[1], (bound[1] - bound[0]) / 1000) sin_y = [H(x) for x in sin_x] plt.plot(sin_x, sin_y) plt.plot([p.s for p in particles], [p.m for p in particles], 'or', markersize=2) plt.plot(model.s, ground.m, 'ok', markersize=5) plt.plot(best.s, best.m, 'ok', markersize=2) plt.plot([best.s, model.s], [best.m, ground.m]) plt.ylim((-2, 2)) plt.xlim((bound[0], bound[1])) plt.gca().set_aspect('equal') plt.draw() plt.pause(1) plt.clf()
51aa8e6da249415cb66ecaac5ce7dd962817f3a1
[ "Python" ]
4
Python
iamkevinzhao/pf_cpf
03dd4f64585663cb6b24be23f0d801a61691a833
c75961e841e413d4f7fb96f24ae5b2afabc5e196
refs/heads/master
<file_sep>package listeners; import java.util.List; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.ExecutionListener; import logic.Postulacion; public class agregarPostulacionesActualizadas implements ExecutionListener{ @Override public void notify(DelegateExecution execution) { // DelegateExecution execution = task.getExecution(); Postulacion p = (Postulacion) execution.getVariable("postulacion"); List<Postulacion> postulacionesActualizadas = (List<Postulacion>) execution.getVariable("postulacionesActualizadas"); postulacionesActualizadas.add(p); } } <file_sep>package listeners; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.DelegateTask; import org.activiti.engine.delegate.TaskListener; import logic.Postulacion; public class formEvaluacionPostulante implements TaskListener { @Override public void notify(DelegateTask task) { DelegateExecution execution = task.getExecution(); Postulacion p = (Postulacion) task.getVariable("postulacion"); execution.setVariableLocal("cedulapostulante", p.getCedula()); execution.setVariableLocal("nombrepostulante", p.getNombre()); execution.setVariableLocal("carrerapostulante", p.getCarrera()); execution.setVariableLocal("creditospostulante", p.getCreditos()); execution.setVariableLocal("universidadpostulante", p.getUniversidad()); } } <file_sep>package logic; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import logic.Expediente; import java.sql.*; public class Comunicacion_DB { private static Connection getConection(){ Connection conexion = null; String driver = "org.postgresql.Driver"; String base = "jdbc:postgresql://localhost:5432/empresarial"; String usuario = "postgres"; String password = "<PASSWORD>"; try { Class.forName(driver); conexion = DriverManager.getConnection(base, usuario , password); } catch (ClassNotFoundException e){ e.getMessage(); } catch (SQLException e){ e.getMessage(); } return conexion; } public static Usuario usuarioValido(String user, String pass){ Usuario usu = new Usuario(); Connection con = null; System.out.println("User :"+user); System.out.println("Pass :"+pass); try{ con = getConection(); String consulta = "SELECT * FROM usuario WHERE usuario='"+user+"' and password='"+<PASSWORD>+"'"; Statement st=con.createStatement(); ResultSet rs = st.executeQuery(consulta); boolean more = rs.next(); if (!more) { usu.setValido(false); } else { String u = rs.getString("usuario"); String r = rs.getString("rol"); usu.setUser(u); usu.setRol(r); usu.setValido(true); } } catch(Exception ex) { System.out.println("ERROR :"+ex.getMessage()); } return usu; } public static List<Expediente> obtenerExpedientes(){ List<Expediente> expedientes = new ArrayList<Expediente>(); Connection con = null; try { con = getConection(); String consulta = "select * from movilidad mo, universidad u, expediente e where e.estado > 1 and e.movilidadnombre = mo.movilidadnombre and mo.universidadid = u.universidadid"; Statement st=con.createStatement(); ResultSet rs = st.executeQuery(consulta); while(rs.next()){ Expediente exp = new Expediente(); exp.setMovilidadNombre(rs.getString("movilidadNombre")); exp.setConvocatoriaId(rs.getString("convocatoriaId")); exp.setUniversidad(rs.getString("universidadnombre")); exp.setDocenteRef(rs.getString("docenteRefId")); DateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY"); exp.setFechaInicio(dateFormat.format(rs.getDate("fechaInicioPostulacion"))); exp.setFechaFin(dateFormat.format(rs.getDate("fechaFinPostulacion"))); expedientes.add(exp); } System.out.println(consulta); } catch (SQLException e) { System.out.println("ERROR :"+e.getMessage()); } return expedientes; } } <file_sep> truncate table public.estudiante_expediente; truncate table public.docente_expediente; delete from public.expediente; delete from public.movilidad; delete from public.estudiante; -- inserto los estudiantes nuevamente, los iniciales INSERT into estudiante values('48635700','estudiante 1','Ingenieria en Computacion',190,'rutaCV1'); INSERT into estudiante values('12345678','estudiante 2','Ingenieria en Computacion',300,'rutaCV2'); INSERT into estudiante values('48765432','estudiante 3','Ingenieria en Computacion',100,'rutaCV3'); INSERT into estudiante values('34567890','estudiante 4','Ingenieria en Computacion',150,'rutaCV4'); INSERT into estudiante values('21346578','estudiante 5','Ingenieria en Computacion',80,'rutaCV5'); <file_sep>package listeners; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.DelegateTask; import org.activiti.engine.delegate.TaskListener; import java.util.List; import logic.Postulacion; import other.Comunicacion_DB; public class agregarPostulacionesFiltroInicial implements TaskListener { @Override public void notify(DelegateTask task) { DelegateExecution execution = task.getExecution(); List<Postulacion> postulacionesFiltroInicial = (List<Postulacion>) execution.getVariable("postulacionesFiltroInicial"); Boolean postulacionAprobada = ((Boolean) (execution.getVariable("aprobado"))); Postulacion p = (Postulacion) execution.getVariable("postulacion"); if (postulacionAprobada) { System.out.println(p.getCedula()); System.out.println(p.getNombre()); postulacionesFiltroInicial.add(p); } else { Comunicacion_DB.actualizarEstadoPostulacion(p.getCedula(),p.getExpediente(), 1); } execution.setVariableLocal("aprobado", false); System.out.println(postulacionesFiltroInicial.size()); for (int i = 0; i < postulacionesFiltroInicial.size(); i++) { System.out.println(postulacionesFiltroInicial.get(i).getCedula()); }; } } <file_sep>/** * Javascript module for processing form submits */ $(document).ready(function(){ function IngresarMovilidadDGRC(){ var nombre = document.getElementById('nombre').value; var convocatoriaId = document.getElementById('convocatoriaId').value; var fechaInicio = document.getElementById('fechaInicio').value; var fechaFin = document.getElementById('fechaFin').value; var universidadId = document.getElementById('universidadId').value; var duracion = document.getElementById('duracion').value; var bases = document.getElementById('bases').value; var descripcion = document.getElementById('descripcion').value; var electrica = document.getElementById('electrica').value; var civil = document.getElementById('civil').value; var produccion = document.getElementById('produccion').value; var computacion = document.getElementById('computacion').value; if (electrica === 'si') { electrica = true; } else { electrica = false; };; if (civil === 'si') { civil = true; } else { civil = false; }; if (computacion === 'si') { computacion = true; } else { computacion = false; }; if (produccion === 'si') { produccion = true; } else { produccion = false; }; var emailcontacto = document.getElementById('emailcontacto').value; var nombrecontacto = document.getElementById('nombrecontacto').value; // AJAX VARIABLES var processId = ''; var processTaskid = ''; var completeTaskURI = '' var getTaskIdUrls = ''; $.ajax({ url: "http://kermit:kermit@localhost:8080/activiti-rest/service/runtime/process-instances", type: "POST", headers: { 'Accept':'application/json', 'Content-Type':'application/json', 'authorization':'Basic a2VybWl0Omtlcm1pdA==' }, data:'{"processDefinitionKey":"process",'+ '"variables":[{"name":"nombre","value":"'+nombre+'"},' + '{"name":"identificacionconvocatoria","value":"'+convocatoriaId+'"},'+ '{"name":"fechainicio","value":"'+fechaInicio+'"},' + '{"name":"fechafin","value":"'+fechaFin+'"},'+ '{"name":"electrica","value":'+electrica+',"type":"boolean"},' + '{"name":"computacion","value":'+computacion+',"type":"boolean"},'+ '{"name":"civil","value":'+civil+',"type":"boolean"},' + '{"name":"produccion","value":'+produccion+',"type":"boolean"},'+ '{"name":"universidadid","value":"'+universidadId+'"},' + '{"name":"duracion","value":'+duracion+',"type":"long"},'+ '{"name":"descripcion","value":"'+descripcion+'"},' + '{"name":"bases","value":"'+bases+'"},'+ '{"name":"nombrecontacto","value":"'+nombrecontacto+'"},' + '{"name":"emailcontacto","value":"'+emailcontacto+'"}' + ']}', datatype: "json", success: function(resultado) { // alert('Pasa el primer Success::' + resultado.id); processId = resultado.id; getTaskIdUrls = "http://kermit:kermit@localhost:8080/activiti-rest/service/runtime/tasks?processInstanceId=" + processId; $.ajax({ url: getTaskIdUrls, type: "GET", datatype: "json", headers: { 'Accept':'application/json', 'Content-Type':'application/json', 'authorization':'Basic a2VybWl0Omtlcm1pdA==' }, success: function (res2) { processTaskid = res2.data[0].id; // alert('El segundo success perro::' +processTaskid); completeTaskURI = 'http://kermit:kermit@localhost:8080/activiti-rest/service/runtime/tasks/' + processTaskid; $.ajax({ url: completeTaskURI, type: "POST", datatype: "json", headers: { 'Content-Type':'application/json', 'authorization':'Basic a2VybWl0Omtlcm1pdA==' }, data: '{"action":"complete"}', success: function (res3) { window.location.href="index.jsp"; }, error: function (error) { console.log('error3'); alert('Error en tercer ajax'); } }) }, error: function (error) { console.log('error2'); // alert('Error en segundo ajax'); } }) }, error: function(err) { console.log('error1'); console.log(err); alert('error primer ajax'); alert(err); } }); return false; } function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } function Ejecutar(id,i){ var nombre = document.getElementById('nombre').value; var apellido = document.getElementById('apellido').value; var cedula = document.getElementById('cedula').value; var carrera = document.getElementById('carrera').value; var creditos = document.getElementById('creditos').value; var universidad = document.getElementById('universidad').value; var taskId = ""; $.ajax({ url: "http://kermit:kermit@localhost:8080/activiti-rest/service/runtime/tasks", type: "GET", datatype: "json", headers: { 'Accept':'application/json', 'Content-Type':'application/json', 'authorization':'Basic a2VybWl0Omtlcm1pdA==' }, success: function(resultado) { for(var i=0;i<resultado.size;i++){ if (resultado.data[i].processInstanceId == id){ taskId = resultado.data[i].id; } } $.ajax({ url: "http://kermit:kermit@localhost:8080/activiti-rest/service/runtime/tasks/"+taskId+"/variables/nombrepostulante", type: "PUT", datatype: "json", headers: { 'Accept':'application/json', 'Content-Type':'application/json', 'authorization':'Basic a2VybWl0Omtlcm1pdA==' }, data:'{"name":"nombrepostulante","type":"string","value":"'+nombre+'","scope":"global"}', success: function(resultado) { // alert("entra al primer success"); console.log('success postuno'); $.ajax({ url: "http://kermit:kermit@localhost:8080/activiti-rest/service/runtime/tasks/"+taskId+"/variables/apellidopostulante", type: "PUT", datatype: "json", headers: { 'Accept':'application/json', 'Content-Type':'application/json', 'authorization':'Basic a2VybWl0Omtlcm1pdA==' }, data:'{"name":"apellidopostulante","type":"string","value":"'+apellido+'","scope":"global"}', success: function(resultado) { $.ajax({ url: "http://kermit:kermit@localhost:8080/activiti-rest/service/runtime/tasks/"+taskId+"/variables/cedulapostulante", type: "PUT", datatype: "json", headers: { 'Accept':'application/json', 'Content-Type':'application/json', 'authorization':'Basic a2VybWl0Omtlcm1pdA==' }, data:'{"name":"cedulapostulante","type":"string","value":"'+cedula+'","scope":"global"}', success: function(resultado) { $.ajax({ url: "http://kermit:kermit@localhost:8080/activiti-rest/service/runtime/tasks/"+taskId+"/variables/carrerapostulante", type: "PUT", datatype: "json", headers: { 'Accept':'application/json', 'Content-Type':'application/json', 'authorization':'Basic a2VybWl0Omtlcm1pdA==' }, data:'{"name":"carrerapostulante","type":"string","value":"'+carrera+'","scope":"global"}', success: function(resultado) { $.ajax({ url: "http://kermit:kermit@localhost:8080/activiti-rest/service/runtime/tasks/"+taskId+"/variables/creditospostulante", type: "PUT", datatype: "json", headers: { 'Accept':'application/json', 'Content-Type':'application/json', 'authorization':'Basic a2VybWl0Omtlcm1pdA==' }, data:'{"name":"creditospostulante","type":"long","value":'+creditos+',"scope":"global"}', success: function(resultado) { $.ajax({ url: "http://kermit:kermit@localhost:8080/activiti-rest/service/runtime/tasks/"+taskId+"/variables/universidadpostulante", type: "PUT", datatype: "json", headers: { 'Accept':'application/json', 'Content-Type':'application/json', 'authorization':'Basic a2VybWl0Omtlcm1pdA==' }, data:'{"name":"universidadpostulante","type":"string","value":"'+universidad+'","scope":"global"}', success: function(resultado) { /////////////////////////// $.ajax({ url: "http://kermit:kermit@localhost:8080/activiti-rest/service/runtime/tasks/"+taskId, type: "POST", datatype: "json", headers: { 'Accept':'application/json', 'Content-Type':'application/json', 'authorization':'Basic a2VybWl0Omtlcm1pdA==' }, data:'{"action":"complete"}', success: function(resultado) { // alert("entra al segundo success"); console.log('success postdos'); // window.location = "index.jsp"; }, error: function(err) { console.log('error1'); console.log(err); // alert('error segundo ajax'); // alert(err); } }); /////////////////////////// }, error: function(err) { console.log('error1'); console.log(err); // alert('error segundo ajax'); // alert(err); } }); }, error: function(err) { console.log('error1'); console.log(err); // alert('error segundo ajax'); // alert(err); } }); }, error: function(err) { console.log('error1'); console.log(err); // alert('error segundo ajax'); // alert(err); } }); }, error: function(err) { console.log('error1'); console.log(err); // alert('error segundo ajax'); // alert(err); } }); }, error: function(err) { console.log('error1'); console.log(err); // alert('error segundo ajax'); // alert(err); } }); // window.location = "index.jsp"; }, error: function(err) { console.log('error1'); console.log(err); // alert('error primer ajax'); // alert(err); } }); }, error: function() { // alert('error get ajax'); } }); } $("#ingresar-postulacion-form").submit(function(event) { event.preventDefault(); console.log('validar'); var id = getUrlVars().id; var i = getUrlVars().i; Ejecutar(id,i) }); $("#ingresar-movilidad-form").submit(function(event) { event.preventDefault(); IngresarMovilidadDGRC(); }); }); <file_sep>CREATE TABLE public.Docente ( docenteId text NOT NULL,--cedula de identidad nombre text, departamento text, CONSTRAINT "PK_docente" PRIMARY KEY (docenteId) ); CREATE TABLE public.Estudiante ( estudianteId text not null,--cedula de identidad nombre text not null,-- nombre y apellido carrera text not null, creditosAprob integer not null, CV text not null, -- corresponde a la ubicacion del archivo CONSTRAINT "PK_estudiante" PRIMARY KEY (estudianteId) ); CREATE TABLE public.Movilidad ( movilidadNombre text NOT NULL, convocatoriaId text NOT NULL, movilidadNumero serial, fechaInicio date, fechaFin date, descripcion text, duracion numeric, -- en meses bases text, computacion boolean, produccion boolean, civil boolean, electrica boolean, nombreContacto text, emailContacto text, universidadId integer, CONSTRAINT "PK_Movilidad" PRIMARY KEY (movilidadNombre,convocatoriaId) ); CREATE TABLE public.Expediente ( expedienteId text NOT NULL, fechaInicioPostulacion date, fechaFinPostulacion date, docenteRefId text, movilidadNombre text, convocatoriaId text, razon text, estado integer, tieneInforme boolean, informerechazado boolean, CONSTRAINT "PK_Expediente" PRIMARY KEY (expedienteId) ); CREATE TABLE public.Universidad ( universidadId integer NOT NULL, universidadNombre text, paisId integer, CONSTRAINT "PK_Universidad" PRIMARY KEY (universidadId) ); CREATE TABLE public.Pais ( paisId integer NOT NULL, paisNombre text NULL, CONSTRAINT "PK_Pais" PRIMARY KEY (paisId) ); CREATE TABLE public.docente_expediente ( docenteId text not null, expedienteId text not null, CONSTRAINT "PK_doc_exp" PRIMARY KEY (docenteId,expedienteId) ); CREATE TABLE public.estudiante_expediente ( estudianteId text not null, expedienteId text not null, universidadId integer, estado integer, prioridad integer, CONSTRAINT "PK_est_exp" PRIMARY KEY (estudianteId,expedienteId) ); CREATE TABLE public.usuario ( usuario text not null, password text, rol text, CONSTRAINT "PK_usuario" PRIMARY KEY (usuario) ); -- FK de la tabla movilidad ALTER TABLE public.Movilidad ADD CONSTRAINT FK_Universidad_Movilidad FOREIGN KEY(UniversidadId) REFERENCES Universidad (UniversidadId); -- FK expediente ALTER TABLE public.Expediente ADD CONSTRAINT FK_Expediente_Movilidad FOREIGN KEY(movilidadNombre,convocatoriaId) REFERENCES Movilidad (movilidadNombre,convocatoriaId); ALTER TABLE public.Expediente ADD CONSTRAINT FK_Expediente_DocenteRef FOREIGN KEY(docenteRefId) REFERENCES Docente (docenteId); -- FK universidad ALTER TABLE public.Universidad ADD CONSTRAINT FK_Pais_Universidad FOREIGN KEY(paisId) REFERENCES Pais (paisId); -- FK de la tabla estudiante -- FK de la tabla estudiante_expediente ALTER TABLE public.estudiante_expediente ADD CONSTRAINT FK_estudiante_expediente FOREIGN KEY(estudianteId) REFERENCES Estudiante (estudianteId); ALTER TABLE public.estudiante_expediente ADD CONSTRAINT FK_estudiante_expediente2 FOREIGN KEY(expedienteId) REFERENCES expediente (expedienteId); -- FK de la tabla docente_expediente ALTER TABLE public.docente_expediente ADD CONSTRAINT FK_docente_expediente FOREIGN KEY(docenteId) REFERENCES Docente (docenteId); ALTER TABLE public.docente_expediente ADD CONSTRAINT FK_docente_expediente2 FOREIGN KEY(expedienteId) REFERENCES expediente (expedienteId); -- FK de universidad --******************INGRESO DE JUEGO DE DATOS************************** -- docentes INSERT into docente values('11111111','Docente 1','Computacion'); INSERT into docente values('22222222','Docente 2','Computacion'); INSERT into docente values('33333333','Docente 3','Arquitectura'); INSERT into docente values('44444444','Docente 4','Arquitectura'); -- paises INSERT into pais values(1,'Uruguay'); INSERT into pais values(2,'Japon'); INSERT into pais values(3,'Estados Unidos'); INSERT into pais values(4,'Canada'); INSERT into pais values(5,'Portugal'); INSERT into pais values(6,'Brasil'); -- universidades INSERT into universidad values(1,'Universidad de Stanford',3); INSERT into universidad values(2,'Universidad de Toronto',4); INSERT into universidad values(3,'Universidad de Harvard',3); INSERT into universidad values(4,'Universidad de Tokio',2); INSERT into universidad values(5,'Universidad de San Pablo',6); INSERT into universidad values(6,'Universidad de Lisboa',5); INSERT into universidad values(7,'Facultad de Ingenieria Uruguay',1); -- estudiantes INSERT into estudiante values('48635700','estudiante 1','Ingenieria en Computacion',190,'rutaCV1'); INSERT into estudiante values('12345678','estudiante 2','Ingenieria en Computacion',300,'rutaCV2'); INSERT into estudiante values('48765432','estudiante 3','Ingenieria en Computacion',100,'rutaCV3'); INSERT into estudiante values('34567890','estudiante 4','Ingenieria en Computacion',150,'rutaCV4'); INSERT into estudiante values('21346578','estudiante 5','Ingenieria en Computacion',80,'rutaCV5'); -- usuarios INSERT into usuario values('usuario1','1234','DGRC'); INSERT into usuario values('usuario2','1234','DGRC'); INSERT into usuario values('usuario3','1234','<PASSWORD>'); INSERT into usuario values('usuario4','1234','<PASSWORD>'); <file_sep>package listeners; import java.util.List; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.DelegateTask; import org.activiti.engine.delegate.TaskListener; import logic.Postulacion; import other.Comunicacion_DB; public class ActualizarDatosPostulante implements TaskListener { @Override public void notify(DelegateTask task) { DelegateExecution execution = task.getExecution(); Postulacion p = (Postulacion) execution.getVariable("postulacion"); List<Postulacion> postulacionesActualizadas = (List<Postulacion>) execution.getVariable("postulacionesActualizadas"); String nombre = (String) execution.getVariable("nombreactualizado"); Integer creditos = ((Long) execution.getVariable("creditosactualizados")).intValue(); p.setCreditos(creditos); p.setNombre(nombre); postulacionesActualizadas.add(p); execution.setVariableLocal("nombreactualizado", ""); execution.setVariableLocal("creditosactualizados", null); Comunicacion_DB.actualizarDatosEstudiante(creditos, p.getCedula(), nombre); } }<file_sep>$(document).ready(function(){ $(document.getElementById("form-busqueda")).on("keyup", "#criterio", function(e) { if (e.keyCode === 13) { $(document.getElementById("form-busqueda")).submit(); } $.get("AjaxSearchRequest",{criterio : $("#criterio").val()} ,function(responseJson) { var arr =[]; $.each(responseJson, function(index, item) { arr[index] = item; }); $("#criterio").autocomplete({source: arr}); }); }); });<file_sep>package other; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import logic.datosDT; public class Comunicacion_DB { private static Connection getConection(){ Connection conexion = null; String driver = "org.postgresql.Driver"; String base = "jdbc:postgresql://localhost:5432/empresarial"; String usuario = "postgres"; String password = "<PASSWORD>"; try { Class.forName(driver); conexion = DriverManager.getConnection(base, usuario , password); } catch (ClassNotFoundException e){ e.getMessage(); } catch (SQLException e){ e.getMessage(); } return conexion; } public static void crearMovilidad(String nombre, String convocatoriaId, Date fechaInicio, Date fechaFin, Integer universidadId, Boolean electrica, Boolean computacion, Boolean produccion, Boolean civil, Integer duracion, String descripcion, String bases, String nombreContacto, String emailContacto){ Connection con = null; try { con = getConection(); String query = "INSERT INTO movilidad (movilidadNombre,convocatoriaId,fechaInicio,fechaFin,descripcion,duracion,bases,computacion,produccion,civil,electrica,nombreContacto,emailContacto,universidadId)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement preparedStatement = con.prepareStatement(query); preparedStatement.setString(1, nombre); preparedStatement.setString(2, convocatoriaId); preparedStatement.setDate(3, new java.sql.Date(fechaInicio.getTime())); preparedStatement.setDate(4, new java.sql.Date(fechaFin.getTime())); preparedStatement.setString(5, descripcion); preparedStatement.setInt(6, duracion); preparedStatement.setString(7, bases); preparedStatement.setBoolean(8, computacion); preparedStatement.setBoolean(9, produccion); preparedStatement.setBoolean(10, civil); preparedStatement.setBoolean(11, electrica); preparedStatement.setString(12, nombreContacto); preparedStatement.setString(13, emailContacto); preparedStatement.setInt(14, universidadId); preparedStatement.executeUpdate(); System.out.println(query); } catch (SQLException e) { e.printStackTrace(); } } public static List<String> obtenerEstudiantes(){ List<String> estudiantes = new ArrayList<String>(); Connection con = null; try { con = getConection(); String consulta = "SELECT e.estudianteid FROM estudiante e;"; PreparedStatement preparedStatement = con.prepareStatement(consulta); ResultSet rs = preparedStatement.executeQuery(); while(rs.next()){ String estudianteId = rs.getString("estudianteid"); estudiantes.add(estudianteId); } System.out.println(consulta); } catch (SQLException e) { e.getMessage(); } return estudiantes; } public static Boolean ExisteEstudiante(String id1){ Boolean existe = false; Connection con = null; try { con = getConection(); String consulta = "SELECT e.estudianteid FROM estudiante e WHERE e.estudianteid =?;"; PreparedStatement preparedStatement = con.prepareStatement(consulta); preparedStatement.setString(1, id1); ResultSet rs = preparedStatement.executeQuery(); if(rs == null) existe = true; else existe = false; System.out.println(consulta); } catch (SQLException e) { e.getMessage(); } return existe; } public static void crearEstudiante(String nombre, String apellido, String cedula, String carrera, Integer Universidad, String ExpedienteId, Integer creditos){ Connection con = null; nombre = nombre + ' ' + apellido; try { con = getConection(); String query = "INSERT INTO estudiante VALUES (?, ?, ?, ?, ?)"; PreparedStatement preparedStatement = con.prepareStatement(query); preparedStatement.setString(1, cedula); preparedStatement.setString(2, nombre); preparedStatement.setString(3, carrera); preparedStatement.setInt(4, creditos); preparedStatement.setString(5, "lalala"); preparedStatement.executeUpdate(); System.out.println(query); query = "INSERT INTO estudiante_expediente VALUES (?, ?, ?, ?, ?)"; preparedStatement = con.prepareStatement(query); preparedStatement.setString(1, cedula); preparedStatement.setString(2, ExpedienteId); preparedStatement.setInt(3, Universidad); preparedStatement.setInt(4, 0); preparedStatement.setInt(5, 0); preparedStatement.executeUpdate(); System.out.println(query); } catch (SQLException e) { e.printStackTrace(); } } public static void actualizarEstudiante(String carrera, Integer creditos, String cedula, Integer Universidad, String ExpedienteId){ Connection con = null; try { con = getConection(); String consulta = "UPDATE estudiante SET carrera=?, creditosaprob=? WHERE estudianteid=?"; PreparedStatement preparedStatement = con.prepareStatement(consulta); preparedStatement.setString(1,carrera); preparedStatement.setInt(2, creditos); preparedStatement.setString(3,cedula); preparedStatement.executeUpdate(); System.out.println(consulta); consulta = "INSERT INTO estudiante_expediente VALUES (?, ?, ?, ?, ?)"; preparedStatement = con.prepareStatement(consulta); preparedStatement.setString(1, cedula); preparedStatement.setString(2, ExpedienteId); preparedStatement.setInt(3, Universidad); preparedStatement.setInt(4, 0); preparedStatement.setInt(5, 0); preparedStatement.executeUpdate(); System.out.println(consulta); } catch (SQLException e) { e.printStackTrace(); } } public static void crearExpediente(String expedienteid,String movilidadNombre,String convocatoriaId,Date fechaInicioPos,Date fechaFinPos){ Connection con = null; try { con = getConection(); String queryExpediente = "INSERT INTO expediente (expedienteid,fechainiciopostulacion,fechafinpostulacion,movilidadnombre,convocatoriaid,tieneinforme,informerechazado,estado) VALUES (?,?,?,?,?,?,?,?)"; PreparedStatement expediente = con.prepareStatement(queryExpediente); expediente.setString(1, expedienteid); expediente.setDate(2, new java.sql.Date(fechaInicioPos.getTime())); expediente.setDate(3, new java.sql.Date(fechaFinPos.getTime())); expediente.setString(4, movilidadNombre); expediente.setString(5,convocatoriaId); expediente.setBoolean(6, false); // tiene informe expediente.setBoolean(7, false); // informe rechazado expediente.setInt(8, 0); System.out.println(queryExpediente); expediente.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public static void crearDocenteExpediente(String expedienteid,String referente,String docente,String docentedos,String docentetres){ Connection con = null; try { con = getConection(); String queryDocente_Exp = "INSERT INTO docente_expediente VALUES (?,?)"; PreparedStatement docente_exp = con.prepareStatement(queryDocente_Exp); docente_exp.setString(1, docente); docente_exp.setString(2,expedienteid); docente_exp.executeUpdate(); docente_exp = con.prepareStatement(queryDocente_Exp); docente_exp.setString(1, docentedos); docente_exp.setString(2,expedienteid); docente_exp.executeUpdate(); docente_exp = con.prepareStatement(queryDocente_Exp); docente_exp.setString(1, docentetres); docente_exp.setString(2,expedienteid); docente_exp.executeUpdate(); String queryReferente_Exp = "UPDATE expediente set docenterefid = ? where expedienteid = ? "; PreparedStatement referente_exp = con.prepareStatement(queryReferente_Exp); referente_exp.setString(1, referente); referente_exp.setString(2,expedienteid); referente_exp.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public static void actualizarDocenteExpediente(String expedienteid,String referente,String docente,String docentedos,String docentetres){ Connection con = null; try { con = getConection(); String queryDocente_Exp = "UPDATE docente_expediente SET docenteid = ? WHERE expedienteid = ?"; PreparedStatement docente_exp = con.prepareStatement(queryDocente_Exp); docente_exp.setString(1, docente); docente_exp.setString(2,expedienteid); docente_exp.executeUpdate(); docente_exp = con.prepareStatement(queryDocente_Exp); docente_exp.setString(1, docentedos); docente_exp.setString(2,expedienteid); docente_exp.executeUpdate(); docente_exp = con.prepareStatement(queryDocente_Exp); docente_exp.setString(1, docentetres); docente_exp.setString(2,expedienteid); docente_exp.executeUpdate(); String queryReferente_Exp = "UPDATE expediente set docenterefid = ? where expedienteid = ? "; PreparedStatement referente_exp = con.prepareStatement(queryReferente_Exp); referente_exp.setString(1, referente); referente_exp.setString(2,expedienteid); referente_exp.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public static void actualizarExpediente(String expedienteid,String movilidadNombre,String convocatoriaId,Date fechaInicioPos,Date fechaFinPos){ Connection con = null; try { con = getConection(); String queryExpediente = "UPDATE expediente SET fechainiciopostulacion=?, fechafinpostulacion=? WHERE expedienteid=?"; PreparedStatement expediente = con.prepareStatement(queryExpediente); expediente.setDate(1, new java.sql.Date(fechaInicioPos.getTime())); expediente.setDate(2, new java.sql.Date(fechaFinPos.getTime())); expediente.setString(3, expedienteid); expediente.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public static void actualizarEstadoExpediente(String expedienteid,Integer estadoExpediente){ Connection con = null; try { con = getConection(); String queryEstadoExpediente = "UPDATE expediente SET estado=? WHERE expedienteid=?"; PreparedStatement expediente = con.prepareStatement(queryEstadoExpediente); expediente.setInt(1, estadoExpediente); expediente.setString(2, expedienteid); expediente.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public static void actualizarDatosEstudiante(Integer creditos, String cedula, String nombre){ Connection con = null; try { con = getConection(); String consulta = "UPDATE estudiante SET nombre=?, creditosaprob=? WHERE estudianteid=?"; PreparedStatement preparedStatement = con.prepareStatement(consulta); preparedStatement.setString(1,nombre); preparedStatement.setInt(2, creditos); preparedStatement.setString(3,cedula); preparedStatement.executeUpdate(); System.out.println(consulta); } catch (SQLException e) { e.printStackTrace(); } } public static void actualizarEstadoPostulacion(String estudianteId,String expedienteId,Integer estado) {// estado 1 significa rechazado Connection con = null; try { con = getConection(); String consulta = "UPDATE estudiante_expediente SET estado=? WHERE estudianteid=? and expedienteId = ?"; PreparedStatement preparedStatement = con.prepareStatement(consulta); preparedStatement.setInt(1,estado); preparedStatement.setString(2, estudianteId); preparedStatement.setString(3,expedienteId); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public static void actualizarPrioridadPostulacion(String estudianteId,String expedienteId,Integer prioridad) { Connection con = null; try { con = getConection(); String consulta = "UPDATE estudiante_expediente SET prioridad=? WHERE estudianteid=? and expedienteId = ?"; PreparedStatement preparedStatement = con.prepareStatement(consulta); preparedStatement.setInt(1,prioridad); preparedStatement.setString(2, estudianteId); preparedStatement.setString(3,expedienteId); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public static datosDT cargarDatosDecisionTable(String movilidadNombre,String expedienteId) { datosDT datosDT = null ; Connection con = null; try { con = getConection(); String consultaExiste = "SELECT count(*) as convCreadas FROM expediente WHERE movilidadnombre = ? and expedienteid <> ? "; PreparedStatement preparedStatement = con.prepareStatement(consultaExiste); preparedStatement.setString(1,movilidadNombre ); preparedStatement.setString(2,expedienteId); ResultSet r = preparedStatement.executeQuery(); Integer convocatoriasCreadas = 0; boolean existeexpediente = false; boolean tieneinforme = false; boolean informerechazado = false; while(r.next()){ convocatoriasCreadas = r.getInt("convCreadas"); }; if (convocatoriasCreadas == 0) { existeexpediente = false; tieneinforme = false; informerechazado = false; }else { existeexpediente = true; String consultainforme = "SELECT tieneinforme as ti,informerechazado as ir FROM expediente WHERE movilidadnombre = ? and expedienteid <> ? "; boolean cont = true; PreparedStatement ps = con.prepareStatement(consultainforme); ps.setString(1,movilidadNombre ); ps.setString(2,expedienteId); ResultSet res = ps.executeQuery(); while(cont && res.next()){ tieneinforme = res.getBoolean("ti"); informerechazado = res.getBoolean("ir"); cont = (tieneinforme && !informerechazado); }; }; System.out.println("existeExBD: "+existeexpediente+" tieneinfBD: "+tieneinforme+" informeRechBD: "+informerechazado); datosDT = new datosDT(existeexpediente,tieneinforme,informerechazado); } catch (SQLException e) { e.printStackTrace(); } return datosDT; } } <file_sep># TBPM TBPM proyect, work with java and activity workflow. <file_sep>package listeners; import java.util.Arrays; import java.util.*; import org.activiti.engine.delegate.DelegateExecution; import logic.Postulacion; import org.activiti.engine.delegate.DelegateTask; import org.activiti.engine.delegate.TaskListener; import other.Comunicacion_DB; public class CrearPostulacion implements TaskListener { /** * */ private static final long serialVersionUID = 1L; @Override public void notify(DelegateTask task) { DelegateExecution execution = task.getExecution(); String nombreP = (String) execution.getVariable("nombrepostulante"); String apellidoP = (String) execution.getVariable("apellidopostulante"); String cedulaP = (String) execution.getVariable("cedulapostulante"); String carreraP = (String) execution.getVariable("carrerapostulante"); Integer creditosP = ((Long) execution.getVariable("creditospostulante")).intValue(); Integer universidad = Integer.parseInt((String) execution.getVariable("universidadpostulante")); String expedienteId = (String) execution.getVariable("expedienteid"); execution.setVariableLocal("nombrepostulante", ""); execution.setVariableLocal("apellidopostulante", ""); execution.setVariableLocal("cedulapostulante", ""); execution.setVariableLocal("carrerapostulante", ""); execution.setVariableLocal("creditospostulante", null); execution.setVariableLocal("universidadpostulante", null); List<Postulacion> postulaciones = (List<Postulacion>) execution.getVariable("postulaciones"); Boolean existe = Comunicacion_DB.ExisteEstudiante(cedulaP); if(existe) { Comunicacion_DB.actualizarEstudiante(carreraP, creditosP, cedulaP, universidad, expedienteId); }else { System.out.println("ExpedienteId: " + expedienteId); Comunicacion_DB.crearEstudiante(nombreP, apellidoP, cedulaP, carreraP, universidad, expedienteId, creditosP); } Postulacion postulacion = new Postulacion(nombreP, apellidoP, cedulaP, carreraP,creditosP, universidad, "", (Integer) 0, expedienteId,0,""); postulaciones.add(postulacion); System.out.println(postulaciones.size()); // Collections.sort(postulaciones, new Comparator<Postulacion>() { // @Override // public int compare(Postulacion p1, Postulacion p2) // { // // return p1.getEvalEntrevista().compareTo(p2.getEvalEntrevista()); // } // }); // for (int i = 0; i < postulaciones.size(); i++) { // System.out.println(postulaciones.get(i).getEvalEntrevista()); // // } } }<file_sep>package listeners; import java.util.List; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.DelegateTask; import org.activiti.engine.delegate.TaskListener; import logic.Postulacion; import other.Comunicacion_DB; public class agregarPostulacionesFiltroEntrevista implements TaskListener{ @Override public void notify(DelegateTask task) { DelegateExecution execution = task.getExecution(); Postulacion p = (Postulacion) execution.getVariable("postulacion"); List<Postulacion> postulacionesFiltroEntrevista = (List<Postulacion>) execution.getVariable("postulacionesFiltroEntrevista"); String valoracionStr = (String) execution.getVariable("valoracionentrevista"); execution.setVariableLocal("valoracionentrevista", null); execution.setVariableLocal("entrevistarealizada", ""); Integer valoracion = 0;// inicializo en cero como insuficiente if (valoracionStr.equals("Excelente")) { valoracion = 2; } if (valoracionStr.equals("Aceptable")) { valoracion = 1; } p.setEvalEntrevista(valoracion); postulacionesFiltroEntrevista.add(p); Integer ent = (Integer) execution.getVariable("entrevistados"); ent ++; execution.setVariable("entrevistados", ent); execution.setVariable("okfechaentrevista", false); System.out.println("entrevistados: "+ent); } } <file_sep>package modelo; public enum estadoSesion { NO_LOGIN, // nunca intentó iniciar sesión LOGIN_CORRECTO, // tiene la sesión iniciada LOGIN_INCORRECTO // intento de logueo incorrecto }
676ab78451ecf05a44ba73f8a67b6eff2d7a9d63
[ "JavaScript", "Java", "Markdown", "SQL" ]
14
Java
joaquinvillar/TBPM
bb110385b8fd29fc7f75f8cfd2e245e3e833277f
0ce2f615039208abec5415b978d801a79119aedf
refs/heads/master
<file_sep>let pets = ['cat','dog','rat']; let n=pets.length; for (let i =0; i<n;i++){ pets[i]=pets[i]+'s'; //console.log(pets[i]); } console.log(pets);
a5174329b70541aec310e98061c6e8e1210253ec
[ "JavaScript" ]
1
JavaScript
DragonMess/javascripting
0589bb2e93b8ea47791c826069904008505066fe
8539cca869454e86a204f49a1b919fbaa6e005c4
refs/heads/master
<file_sep>require 'mysql2' config = { db: { host: ENV['ISUCONP_DB_HOST'] || 'localhost', port: ENV['ISUCONP_DB_PORT'] && ENV['ISUCONP_DB_PORT'].to_i, username: ENV['ISUCONP_DB_USER'] || 'root', password: ENV['<PASSWORD>'], database: ENV['ISUCONP_DB_NAME'] || 'isuconp', }, } db = Mysql2::Client.new( host: config[:db][:host], port: config[:db][:port], username: config[:db][:username], password: config[:db][:password], database: config[:db][:database], encoding: 'utf8mb4', reconnect: true, ) db.query_options.merge!(symbolize_keys: true, database_timezone: :local, application_timezone: :local) Thread.current[:isuconp_db] = db db.query("select id from posts order by id").to_a.each do |p| print '.' id = p[:id] post = db.query("select imgdata, mime from posts where id = #{id} limit 1").first ext = post[:mime].split('/')[1] ext = 'jpg' if ext == 'jpeg' dist = "../public/image/#{id}.#{ext}" File.write(dist, post[:imgdata]) unless File.exist?(dist) end puts '' puts 'finished.' <file_sep>.DEFAULT_GOAL := help start: ## Run Server @sudo systemctl start isu-ruby stop: ## Stop Server @sudo systemctl stop isu-ruby log: ## log Server @sudo journalctl -u isu-ruby restart: ## Restart Server @sudo systemctl daemon-reload @cd webapp/ruby; bundle 1> /dev/null @sudo systemctl restart isu-ruby @echo 'Restart isu-ruby' mysql-restart: ## Restart mysql @sudo service mysql restart @echo 'Restart mysql' nginx-reset: ## reest log and restart nginx @sudo rm /var/log/nginx/access.log;sudo service nginx restart nginx-log: ## tail nginx access.log @sudo tail -f /var/log/nginx/access.log nginx-error-log: ## tail nginx error.log @sudo tail -f /var/log/nginx/error.log mysql-log: ## tail mysql access.log @sudo tail -f /var/log/mysql/mysql.log myprofiler: ## Run myprofiler @myprofiler -user=root .PHONY: help help: @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
dd509de4e50741ef2a4ace25c21a6e7ac9601a3c
[ "Makefile", "Ruby" ]
2
Ruby
saboyutaka/hcmpl-isu
3c16f412544834157f539324e3d47a69946ca1e6
f1928f9238a0af04e8134c74399036fb3ec98e53
refs/heads/master
<file_sep>import { Route } from '@angular/router'; import { SpreadComponent } from './index'; export const spreadRoute: Route = { path: 'spread', component: SpreadComponent, };<file_sep>package com.web.rest; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.repository.UserRepository; import com.service.serviceInterface.UserServiceDemo; @RestController @RequestMapping("/api/user-demo1") public class UserController { private final Logger log = LoggerFactory.getLogger(UserController.class); @Autowired private UserRepository userService; /*@PostMapping public UserDemo create(@RequestBody UserDemo user){ return userService.create(user); } public UserDemo findOne(@PathVariable("id") int id){ //return userService.findById(id); return null; } @PutMapping("/addUserDetails") public UserDemo update(@RequestBody UserDemo user){ return userService.update(user); } @DeleteMapping(path ={"/delete/{id}"}) public UserDemo delete(@PathVariable("id") int id) { return userService.delete(id); }*/ //@GetMapping("/userDetails") public List findAll(){ return userService.findAll(); } } <file_sep>import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { errorRoute, navbarRoute } from './layouts'; import { DEBUG_INFO_ENABLED } from './app.constants'; import { UserComponent } from './newUserModule/user.compnent'; import { AddUserComponent } from './newUserModule/add-user.component'; import { spreadRoute } from './layouts/spreadjsTutorial/index'; const LAYOUT_ROUTES = [ navbarRoute, { path: 'users1', component: UserComponent }, { path: 'add', component: AddUserComponent }, ...errorRoute ]; @NgModule({ imports: [ RouterModule.forRoot(LAYOUT_ROUTES, { useHash: true , enableTracing: DEBUG_INFO_ENABLED }) ], exports: [ RouterModule ] }) export class EcommerceAppRoutingModule {} <file_sep>import {Injectable} from '@angular/core'; import { HttpClient, HttpHeaders ,HttpResponse } from '@angular/common/http'; import {User} from './user.model' import { SERVER_API_URL } from '../app.constants'; import { Observable } from 'rxjs/Observable'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable() export class UserService { constructor(private http:HttpClient) {} //private userUrl = 'http://localhost:8080/user-portal/api'; public getUsers() :Observable<any> { return this.http.get(SERVER_API_URL + 'api/user-demo/userDetails') .map((res: Response) => { return res; }); } public deleteUser(user) { return this.http.delete(SERVER_API_URL + "api/user-demo/delete/"+ user.id); } public createUser(user) { return this.http.post(SERVER_API_URL + "api/user-demo/add/",user); } /*public updateUser(user) { return this.http.post(SERVER_API_URL + "api/user-demo/delete/"+ user.id); }*/ }<file_sep>package com.service.impl; import java.util.List; import org.springframework.stereotype.Service; import com.domain.UserDemo; import com.repository.UserRepositoryDemo; import com.service.dto.UserDemo1; import com.service.serviceInterface.UserServiceDemo; @Service public class UserServiceImpl implements UserServiceDemo{ //@Autowired private final UserRepositoryDemo repository; public UserServiceImpl(UserRepositoryDemo repository){ this.repository = repository; } @Override public UserDemo create(UserDemo1 user) { return repository.save(user); } /*@Override public UserDemo delete(Long id) { UserDemo user = findById(id); if(user != null){ repository.delete(user); } return user; } @Override public UserDemo findById(Long id) { return repository.findOne(id); }*/ /* */ @Override public List findAll() { return repository.findAll(); } /* @Override public UserDemo update(UserDemo user) { return null; }*/ } <file_sep>package com.service.serviceInterface; import java.util.List; import com.domain.UserDemo; import com.service.dto.UserDemo1; public interface UserServiceDemo { public UserDemo create(UserDemo1 UserDemo); /*public UserDemo delete(Long id); public UserDemo findById(Long id);*/ /* */ public List findAll(); /* public UserDemo update(UserDemo UserDemo);*/ } <file_sep>import { Route } from '@angular/router'; import { HomeComponent } from './'; import { UserComponent } from '../newUserModule/user.compnent'; import { AddUserComponent } from '../newUserModule/add-user.component'; export const HOME_ROUTE: Route = {path: '',component: HomeComponent,data: { authorities: [], pageTitle: 'home.title' } }; <file_sep>import { Component, OnInit} from "@angular/core"; @Component({ selector: 'spread-js', templateUrl: './spread.component.html' }) export class SpreadComponent { title: any; spreadBackColor = 'aliceblue'; sheetName = 'Java 101 Chapters'; hostStyle = { width: '800px', height: '600px' }; data: any; rowOutlineInfo: any; showRowOutline = true; constructor(){ let commands = [ { name: 'Preface', chapter: '1', page: 1, indent: 0 }, { name: 'Java SE5 and SE6', chapter: '1.1', page: 2, indent: 1 }, { name: 'Java SE6', chapter: '1.1.1', page: 2, indent: 2 }, { name: 'The 4th edition', chapter: '1.2', page: 2, indent: 1 }, { name: 'Changes', chapter: '1.2.1', page: 3, indent: 2 }, { name: 'Note on the cover design', chapter: '1.3', page: 4, indent: 1 }, { name: 'Acknowledgements', chapter: '1.4', page: 4, indent: 1 }, { name: 'Introduction', chapter: '2', page: 9, indent: 0 }, { name: 'Prerequisites', chapter: '2.1', page: 9, indent: 1 }, { name: 'Learning Java', chapter: '2.2', page: 10, indent: 1 }, { name: 'Goals', chapter: '2.3', page: 10, indent: 1 }, { name: 'Teaching from this book', chapter: '2.4', page: 11, indent: 1 }, { name: 'JDK HTML documentation', chapter: '2.5', page: 11, indent: 1 }, { name: 'Exercises', chapter: '2.6', page: 12, indent: 1 }, { name: 'Foundations for Java', chapter: '2.7', page: 12, indent: 1 }, { name: 'Source code', chapter: '2.8', page: 12, indent: 1 }, { name: 'Coding standards', chapter: '2.8.1', page: 14, indent: 2 }, { name: 'Errors', chapter: '2.9', page: 14, indent: 1 }, { name: 'Introduction to Objects', chapter: '3', page: 15, indent: 0 }, { name: 'The progress of abstraction', chapter: '3.1', page: 15, indent: 1 }, { name: 'An object has an interface', chapter: '3.2', page: 17, indent: 1 }, { name: 'An object provides services', chapter: '3.3', page: 18, indent: 1 }, { name: 'The hidden implementation', chapter: '3.4', page: 19, indent: 1 }, { name: 'Reusing the implementation', chapter: '3.5', page: 20, indent: 1 }, { name: 'Inheritance', chapter: '3.6', page: 21, indent: 1 }, { name: 'Is-a vs. is-like-a relationships', chapter: '3.6.1', page: 24, indent: 2 }, { name: 'Interchangeable objects with polymorphism', chapter: '3.7', page: 25, indent: 1 }, { name: 'The singly rooted hierarchy', chapter: '3.8', page: 28, indent: 1 }, { name: 'Containers', chapter: '3.9', page: 28, indent: 1 }, { name: 'Parameterized types (Generics)', chapter: '3.10', page: 29, indent: 1 }, { name: 'Object creation & lifetime', chapter: '3.11', page: 30, indent: 1 }, { name: 'Exception handling: dealing with errors', chapter: '3.12', page: 31, indent: 1 }, { name: 'Concurrent programming', chapter: '3.13', page: 32, indent: 1 }, { name: 'Java and the Internet', chapter: '3.14', page: 33, indent: 1 }, { name: 'What is the Web?', chapter: '3.14.1', page: 33, indent: 2 }, { name: 'Client-side programming', chapter: '3.14.2', page: 34, indent: 2 }, { name: 'Server-side programming', chapter: '3.14.3', page: 38, indent: 2 }, { name: 'Summary', chapter: '3.15', page: 38, indent: 1 }, { name: 'End', chapter: '', indent: null } ]; this.data = commands; } ngOnInit() { this.title = "Welcome to spreadjs tutorial"; }; } <file_sep>export * from './spread.component'; export * from './spread.route';
c8fddb87fad91b8406bad8ec34ec4eee32eda3f2
[ "Java", "TypeScript" ]
9
TypeScript
Tariqnawaz/angular5_jhipster_project
a1ee1a33932c34d256fac1d8a740082a7cd32feb
c31b1ef8252e811e767c69662e30e872df4e2117
refs/heads/master
<repo_name>caminale/search-engine<file_sep>/src/app/private/private.component.ts import {Component} from '@angular/core'; import {FormControl} from '@angular/forms'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import ddpClient from '../app.authMeteorDDP'; let ddpObject; @Component({ selector: 'app-private', templateUrl: './private.component.html', styleUrls: ['./private.component.css'] }) export class PrivateComponent { selectedJob: string; auCompletedNumList: Observable<any[]>; numInputCtrl: FormControl; nameInputCtrl: FormControl; selectCtrl: FormControl; auCompletedList: Observable <any[]>; coworkerListFiltering = []; jobs = [ {value: 'cto-0', viewValue: 'CTO'}, {value: 'ceo-1', viewValue: 'CEO'}, {value: 'hr-2', viewValue: 'HR'}, {value: 'all-3', viewValue: 'ALL'}, ]; constructor() { ddpClient.checkConnexion() .then((result) => { ddpObject = result; }); this.nameInputCtrl = new FormControl(); this.selectCtrl = new FormControl(); this.numInputCtrl = new FormControl(); this.numInputCtrl.valueChanges.subscribe(value => { if (value.length !== 0) { this.filteringDataByNum(value); }else { this.auCompletedNumList = null; } }); this.nameInputCtrl.valueChanges.subscribe(value => { if (value.length !== 0) { this.filteringDataByName(value); }else { this.auCompletedList = null; } }); this.selectCtrl.valueChanges.subscribe(value => { if (value) { } }); } filteringDataByName(dataEnter: string) { ddpObject.call( 'getDataAutoComplete', // name of Meteor Method being called [dataEnter], // parameters to send to Meteor Method function (err, result) { // callback which returns the method call results if (!err && result) { this.auCompletedList = result; } }.bind(this), () => {}); } filteringDataByNum(dataEnter: string) { dataEnter = dataEnter.replace(/\s/g, ''); ddpObject.call( 'getNumDataAutoComplete', // name of Meteor Method being called [dataEnter], // parameters to send to Meteor Method function (err, result) { // callback which returns the method call results if (!err && result) { this.auCompletedNumList = result; } }.bind(this), () => {}); } onClickSearch() { let sendedResearch = {}; if (this.numInputCtrl.value !== null) { sendedResearch = Object.assign(sendedResearch, {num: this.numInputCtrl.value.replace(/\s/g, '')}); } if (this.nameInputCtrl.value !== null) { sendedResearch = Object.assign(sendedResearch, {name: this.nameInputCtrl.value}); } if (this.selectCtrl.value !== null) { sendedResearch = Object.assign(sendedResearch, {job: this.selectCtrl.value}); } ddpObject.call( 'getResults', // name of Meteor Method being called [sendedResearch], // parameters to send to Meteor Method function (err, result) { // callback which returns the method call results if (!err && result) { this.coworkerListFiltering = result; } }.bind(this), () => {}); } } <file_sep>/src/app/register/register.component.ts import { Component, OnInit } from '@angular/core'; import { AuthentificationService} from '../authentification.service'; import { Router } from '@angular/router'; import ddpClient from '../app.authMeteorDDP'; let ddpObject; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.css'] }) export class RegisterComponent implements OnInit { constructor(public authService: AuthentificationService, public router: Router) {} ngOnInit() { ddpClient.checkConnexion() .then((result) => { ddpObject = result; }); } submit(user) { ddpObject.call( 'createNewUser', // name of Meteor Method being called [user], // parameters to send to Meteor Method function (err, result) { // callback which returns the method call results if (!err) { } }, function () { // callback which fires when server has finished console.log('updated'); // sending any updated documents as a result of } ); this.authService.register(user['username'], user['password'], user['confirmPassword']); this.router.navigate([ '/private' ]); } } <file_sep>/src/app/view-details/view-details.component.ts import { ActivatedRoute, Router } from '@angular/router'; import { OnInit, Component } from '@angular/core'; import { getUserProfileData } from '../data-manager.service'; import ddpClient from '../app.authMeteorDDP'; import BlueBirdPromise from 'bluebird'; let ddpObject; @Component({ selector: 'app-view-details', templateUrl: './view-details.component.html', styleUrls: ['./view-details.component.css'] }) export class ViewDetailsComponent implements OnInit { public user = ''; public email: string; public isUserDefined = false; constructor( private activatedRoute: ActivatedRoute, public router: Router ) { ddpClient.checkConnexion() .then((result) => { ddpObject = result; getUserProfileData(this.activatedRoute.snapshot.queryParams['userId']) .then((userResult) => { this.user = userResult; this.email = userResult.profile.firstName + '.' + userResult.profile.lastName + '@esme.fr'; this.isUserDefined = true; }) .catch((err) => { }) .finally(() => { }); }) .catch((err) => { }) .finally(() => { }); } ngOnInit() { } onClickBack() { this.router.navigate([ '/private' ]); } } <file_sep>/src/app/login/login.component.ts import { Component, OnInit } from '@angular/core'; import {AuthentificationService} from '../authentification.service'; import { Router } from '@angular/router'; import ddpClient from '../app.authMeteorDDP'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { public ddpObject = null; constructor(public router: Router, public authService: AuthentificationService) { } ngOnInit() { ddpClient.checkConnexion() .then((result) => { this.ddpObject = result; }); } public submit(user) { this.ddpObject.call('login', [ {user: {username: user['username']}, password: <PASSWORD>['<PASSWORD>']} ], function (err, result) { if (!err) { this.router.navigate([ '/private' ]); }else { console.log(err); } }.bind(this)); } } <file_sep>/src/app/app.authMeteorDDP.ts import DDPClient from 'ddp-client'; let ddpclient = null; import BlueBirdPromise from 'bluebird'; import { environment } from '../environments/environment'; export class AuthMeteorDDP { static createDDPObject = () => { ddpclient = new DDPClient({ // All properties optional, defaults shown host : environment.serverUrl, port : environment.port, ssl : false, autoReconnect : true, autoReconnectTimer : 500, maintainCollections : true, ddpVersion : '1', // ['1', 'pre2', 'pre1'] available // Use a full url instead of a set of `host`, `port` and `ssl` socketConstructor: WebSocket // Another constructor to create new WebSockets }); } static checkConnexion = () => { return new BlueBirdPromise((resolve, reject) => { if (ddpclient == null) { AuthMeteorDDP.createDDPObject(); AuthMeteorDDP.connect() .then(() => { resolve(ddpclient); }) .catch((err) => { reject(err); }) .finally(() => { }); } else { resolve(ddpclient); } }); } static disconnect = () => { if (ddpclient != null) { ddpclient.close(); ddpclient = null; } return ddpclient; } static getDDPObject = () => { return ddpclient; } static connect = () => { return new BlueBirdPromise((resolve, reject) => { ddpclient.connect(function (error, wasReconnect) { // If autoReconnect is true, this callback will be invoked each time // a server connection is re-established if (error) { reject() return; } if (wasReconnect) { resolve(); } resolve(); ddpclient.on('message', function (msg) { console.log('ddp message: ' + msg); }); ddpclient.on('socket-close', function (code, message) { console.log('Close: %s %s', code, message); }); ddpclient.on('socket-error', function (error) { console.log('Error: %j', error); }); }); }); } static closeConnection() { ddpclient.close(); } /* * If you need to do something specific on close or errors. * You can also disable autoReconnect and * call ddpclient.connect() when you are ready to re-connect. */ } export default AuthMeteorDDP ; <file_sep>/README.md # Angular 2 / Search Engine # Contents * [overview](#overview) * [installation](#installation) * [results](#results) # overview -This project is an Enterprise directory with autocomplete fields for name and phone number where we can find and see the details about your co-workers. The directory has a registration and authentification sytem (provided by Meteor), to add new co-worker to the directory. # installation ## for client side : ``` cd <your-path/client> npm i ``` if you have angular installed in global : ``` ng build && ng serve ``` else, just launch the app by : ``` npm run build && npm run serve ``` ## for server side : ``` git clone https://github.com/BlackStef/meteor_search_engine.git npm i meteor run ``` # results ![alt text](src/assets/register.png "Registering") Display all users ------------------ ![alt text](src/assets/all_User.png "Display all users") Filtering by name ------------------ ![alt text](src/assets/searchFullText.png "filtering by name") Filtering by job ------------------ ![alt text](src/assets/searchByJob.png "filtering by job") Filtering by number ------------------ ![alt text](src/assets/searchByNumber.png "filtering by number") Profile co-worker ------------------ ![alt text](src/assets/profileData.png "Profile co-worker") <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import {CUSTOM_ELEMENTS_SCHEMA, NgModule} from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MatAutocompleteModule, MatStepperModule, MatSelectModule} from '@angular/material'; import { MatInputModule} from '@angular/material'; import {MatButtonModule} from '@angular/material/button'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import {MatCardModule} from '@angular/material/card'; import { AppComponent } from './app.component'; import { FormComponent } from './form/form.component'; import { LoginComponent } from './login/login.component'; import { RegisterComponent } from './register/register.component'; import { PrivateComponent } from './private/private.component'; import { RomanizePipe } from './romanize.pipe'; import { AuthentificationService } from './authentification.service'; import { DisplayDataComponent } from './display-data/display-data.component'; import { ViewDetailsComponent } from './view-details/view-details.component'; const appRoutes: Routes = [ { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', component: LoginComponent }, { path: 'register', component: RegisterComponent }, { path: 'private', component: PrivateComponent}, {path: 'details/:name', component : ViewDetailsComponent} ]; @NgModule({ declarations: [ AppComponent, FormComponent, LoginComponent, RegisterComponent, PrivateComponent, RomanizePipe, DisplayDataComponent, ViewDetailsComponent ], imports: [ BrowserModule, MatSelectModule, FormsModule, MatButtonModule, ReactiveFormsModule, MatInputModule, BrowserAnimationsModule, MatAutocompleteModule, MatStepperModule, MatCardModule, RouterModule.forRoot( appRoutes, { enableTracing: true } // <-- debugging purposes only ) ], schemas: [CUSTOM_ELEMENTS_SCHEMA], providers: [ AuthentificationService, ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/authentification.service.ts import { Injectable } from '@angular/core'; @Injectable() export class AuthentificationService { private userList: any[]; private isAuth: boolean; public currentUser: object; constructor() { this.userList = []; this.isAuth = false; this.currentUser = {}; } isAuthenticated() { return this.isAuth; } getCurrentUser() { return this.currentUser; } login(username, password, callback) { let found = true; for (const user in this.userList) { if (this.userList[user].username === username) { if (this.userList[user].password === <PASSWORD>) { this.isAuth = true; this.currentUser = this.userList[user]; callback(true); console.log(this.currentUser); found = false; } } } if (found) { callback(false); } } register(username, password, confirmPassword) { if (password === confirmPassword) { this.userList.push({username, password}); } } } <file_sep>/src/app/form/form.component.ts import { Component, EventEmitter, OnInit, Input, Output, ViewChild, ElementRef } from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ templateUrl: './form.component.html', selector: 'app-form', // Name of the HTML element styleUrls: ['./form.component.css'] }) export class FormComponent implements OnInit { jobControler: FormControl; selectedJob: string; jobs = [ {value: 'cto-0', viewValue: 'CTO'}, {value: 'ceo-1', viewValue: 'CEO'}, {value: 'hr-2', viewValue: 'HR'} ]; @Input('title') submitTitle; @Output() onSubmit = new EventEmitter<object>(); @ViewChild('username') username: ElementRef; @ViewChild('password') password: ElementRef; @ViewChild('confirm') confirm: ElementRef; @ViewChild('number') number: ElementRef; @ViewChild('firstName') firstName: ElementRef; @ViewChild('lastName') lastName: ElementRef; @ViewChild('pictureLink') pictureLink: ElementRef; public isRegister = false; constructor() { this.jobControler = new FormControl(); } ngOnInit() { if (this.submitTitle === 'Register') { this.isRegister = true; } } public submit() { const payload = {}; payload['username'] = this.username.nativeElement.value; payload['password'] = this.password.nativeElement.value; if (this.isRegister) { payload['confirmPassword'] = this.confirm.nativeElement.value; payload['number'] = this.number.nativeElement.value; payload['job'] = this.jobControler.value; payload['lastName'] = this.lastName.nativeElement.value; payload['firstName'] = this.firstName.nativeElement.value; payload['pictureLink'] = this.pictureLink.nativeElement.value; } this.onSubmit.emit(payload); } public reset() { this.password.nativeElement.value = ''; this.username.nativeElement.value = ''; if (this.isRegister) { this.confirm.nativeElement.value = ''; } } } <file_sep>/src/app/data-manager.service.ts import { Injectable } from '@angular/core'; import BlueBirdPromise from 'bluebird'; import ddpClient from './app.authMeteorDDP'; let ddpObject; export const getUserProfileData = function(userId) { return new BlueBirdPromise((resolve, reject) => { ddpClient.checkConnexion() .then((result) => { ddpObject = result; ddpObject.call( 'getUserById', // name of Meteor Method being called [userId], // parameters to send to Meteor Method function (err, userResult) { // callback which returns the method call results if (!err && userResult) { console.log('succesful user by userID : ' + JSON.stringify(userResult.profile, null, 2)); resolve(userResult); } else { reject(err); } }, () => { }); }) .catch((err) => { reject(err); }) .finally(() => { console.log('FINALLY promise'); }); }); };
6444eaa34c746a57f3d5208a8b93955ac2686c0a
[ "Markdown", "TypeScript" ]
10
TypeScript
caminale/search-engine
099a6fa722ca563ee2b0a972421c3f20f341825b
ca59fe9276677685268fa040130a224b8b22e6d1
refs/heads/master
<repo_name>devilsuse/contests<file_sep>/src/com/nano/core/exception/ReturnInTry_AndCatch_CheckFinally.java package com.nano.core.exception; /** * So finally runs even in if 1. there is Return in Try or 2. Return in catch * * @author LXMRX * */ public class ReturnInTry_AndCatch_CheckFinally { public static void main(String[] args) { System.out .println("*******************returnInCatch*************************"); returnInCatch(); System.out .println("*******************returnInTry*************************"); returnInTry(); } private String getString() { return "abc"; } private static void returnInCatch() { try { ReturnInTry_AndCatch_CheckFinally obj = new ReturnInTry_AndCatch_CheckFinally(); System.out.println(obj.getString()); // return; throw new Exception(); } catch (Exception e) { System.out.println("In Exception !"); return; } finally { System.out.println("Finally Run ....... returnInCatch"); } } private static void returnInTry() { try { ReturnInTry_AndCatch_CheckFinally obj = new ReturnInTry_AndCatch_CheckFinally(); System.out.println(obj.getString()); return; } catch (Exception e) { System.out.println("In Exception !"); return; } finally { System.out.println("Finally Run ....... returnInTry"); } } } <file_sep>/src/com/nano/core/CloneTest.java package com.nano.core; public class CloneTest { private final Object obj = new Object(); /** * @param args */ public static void main(String[] args) { CloneTest cloneTest = new CloneTest(); try { CloneTest clone2 = (CloneTest) cloneTest.clone(); } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/src/com/nano/core/inheritanceTest/TypeErasureInSubsignature.java package com.nano.core.inheritanceTest; import java.util.List; public class TypeErasureInSubsignature extends MySuper { public static void main(String[] args) { } @Override public void fun(List listString) { System.out.println("This is in SUBclass"); } @Override public void display(List listString) { System.out.println("This is in SUBclass - display UNsynchronized"); } @Override public void f(List listInteger) { System.out.println("This is in SUBclass - display UNsynchronized"); } /* * @Override public void f(List<Integer> listInteger) { * System.out.println("This is in SUPER - f UNsynchronized"); } */ } class MySuper { public void fun(List<String> listString) { System.out.println("This is in SUPER - fun"); } public void display(List listString) { System.out.println("This is in SUPER - display SYNCHRONIZED"); } public void f(List<Integer> listInteger) { System.out.println("This is in SUPER - f UNsynchronized"); } }<file_sep>/src/com/nano/inheritence/PrivateConstructorClassCannotBeSubclassed.java package com.nano.inheritence; /** * @author LXMRX */ public class PrivateConstructorClassCannotBeSubclassed { /* * To suppress default constructor to avoid instantiability */ private PrivateConstructorClassCannotBeSubclassed() { } } <file_sep>/src/com/nano/core/CastInterfaceToObject.java package com.nano.core; public class CastInterfaceToObject implements AnInterface { public static void main(String[] args) { CastInterfaceToObject a = new CastInterfaceToObject(); a.castMeToObject(); } public void castMeToObject() { AnInterface anInterface = new CastInterfaceToObject(); Object a = (Object) anInterface; if (anInterface instanceof Object) System.out.println("TRUE"); else System.out.println("FALSE"); } } interface AnInterface { void castMeToObject(); }<file_sep>/src/com/nano/inter/FindFirstUniqueNumberInUnsortedArray.java package com.nano.inter; import java.util.LinkedHashMap; import java.util.Map; /** * Write a program to find the first unique number in an unsorted array, given * that : 1, numbers can appear more than twice; 2, there may be more than one * unique number; 3, first means first appeared in the given unsorted array; 4, * if first means smallest, can anyone think out a solution other than firstly * sort the array? */ public class FindFirstUniqueNumberInUnsortedArray { public static void main(String[] args) { int[] array = { 1, 3, 4, 2, 33, 11, 12, 3, 4, 54, 90, 0, 7, 1 }; Map<Integer, Integer> timesMap = new LinkedHashMap<Integer, Integer>(); for (int aElement : array) { if (timesMap.containsKey(aElement)) { int count = timesMap.get(aElement).intValue(); timesMap.put(aElement, ++count); } else timesMap.put(aElement, 1); } for (Integer i : timesMap.keySet()) System.out.println(i + " appears " + timesMap.get(i) + " times in the unsorted array..."); for (Integer i : timesMap.keySet()) { if (timesMap.get(i).equals(Integer.valueOf(1))) { System.out.println("\n\nFirst Unique Number is " + i); break; } } /** * When first means smallest */ int smallest = -1; boolean firstTimeInsideIfCondition = true; for (Integer i : timesMap.keySet()) { if (timesMap.get(i).equals(Integer.valueOf(1))) { if (firstTimeInsideIfCondition) { smallest = i.intValue(); firstTimeInsideIfCondition = false; } else { if (smallest > i.intValue()) smallest = i.intValue(); } } } if (firstTimeInsideIfCondition) System.out.println("No unique number exists..."); else System.out.println("\n\nFirst SMALLEST Unique Number is " + smallest); } } <file_sep>/src/net/sapient/metro/bo/SmartCard.java package net.sapient.metro.bo; import java.util.concurrent.ConcurrentHashMap; public class SmartCard { //ConcurrentHashMap<K, V> private String cardNumber = null; private double balance = 0.0d; public SmartCard(String cardNumber, double balance) { this.cardNumber = cardNumber; this.balance = balance; } @Override public boolean equals(Object obj) { if (!(obj instanceof SmartCard)) return false; SmartCard smartCard = (SmartCard) obj; return this.cardNumber.equals(smartCard.cardNumber); } @Override public int hashCode() { return this.cardNumber.hashCode(); } /** * @return the cardNumber */ public String getCardNumber() { return cardNumber; } /** * @param cardNumber * the cardNumber to set */ public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } /** * @return the balance */ public double getBalance() { return balance; } /** * @param balance * the balance to set */ public void setBalance(double balance) { this.balance = balance; } } <file_sep>/src/net/sapient/metro/MetroSystem.java package net.sapient.metro; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import net.sapient.metro.bo.SmartCard; /** * @author AMIT */ public class MetroSystem { static Map<String, SmartCard> smartCardmap = new HashMap<String, SmartCard>(); static Map<String, Integer> stationMap = new HashMap<String, Integer>(); static { stationMap.put("A1", 0); stationMap.put("A2", 0); stationMap.put("A3", 0); stationMap.put("A4", 0); stationMap.put("A5", 0); stationMap.put("A6", 0); smartCardmap.put("smartCard_1", new SmartCard("smartCard_1", 90d)); smartCardmap.put("smartCard_2", new SmartCard("smartCard_2", 2000d)); smartCardmap.put("smartCard_3", new SmartCard("smartCard_3", 30d)); smartCardmap.put("smartCard_4", new SmartCard("smartCard_4", 0d)); smartCardmap.put("smartCard_5", new SmartCard("smartCard_5", 5d)); } /** * @param args */ public static void main(String[] args) throws IOException { boolean wantToTravel = true; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (wantToTravel) { System.out.println("Do you want to travel - Please enter Y or N"); String userWish = reader.readLine(); if (!userWish.equalsIgnoreCase("Y")) { System.out.println("User wishes to opt out...."); break; } boolean hasUserEnteredCorrectCardNum = false; String cardNumber = null; while (!hasUserEnteredCorrectCardNum) { System.out .println("Enter you cardNo - smartCard_1, smartCard_2, smartCard_3, smartCard_4, smartCard_5"); cardNumber = reader.readLine(); if (!smartCardmap.containsKey(cardNumber)) continue; else hasUserEnteredCorrectCardNum = true; } boolean hasUserEnteredCorrectStation = false; String srcStation = null; while (!hasUserEnteredCorrectStation) { System.out.println("Choose Source Station from..."); System.out.println("A1, A2, A3, A4, A5, A6, A7, A8, A9, A10"); srcStation = reader.readLine(); if (!stationMap.containsKey(srcStation)) continue; else { Integer swipeCount = stationMap.get(srcStation); swipeCount++; stationMap.put(srcStation, swipeCount); hasUserEnteredCorrectStation = true; } } hasUserEnteredCorrectStation = false; String destStation = null; while (!hasUserEnteredCorrectStation) { System.out.println("Choose Destination Station from..."); System.out.println("A1, A2, A3, A4, A5, A6, A7, A8, A9, A10"); destStation = reader.readLine(); if (!stationMap.containsKey(srcStation)) continue; else hasUserEnteredCorrectStation = true; } // Calculate fare double fare = calculateFare(srcStation, destStation); if (fare > smartCardmap.get(cardNumber).getBalance()) { System.out.println("You don't have sufficient balance. "); break; } else // Swipe-out the card and decrement price. { doSwipeOut(destStation); deductFare(smartCardmap.get(cardNumber), fare); } printTicket(srcStation, destStation, cardNumber, fare, smartCardmap.get(cardNumber).getBalance()); printStationSwipes(); } } /** * printStationSwipes */ public static void printStationSwipes() { for (String stn : stationMap.keySet()) { System.out.println("swipe for station " + stn + " - " + stationMap.get(stn)); } } /** * @param sm * @param fare */ public static void deductFare(SmartCard sm, double fare) { sm.setBalance(sm.getBalance() - fare); } /** * @param srcStation * @param destStation * @param cardNumber * @param fare * @param balance */ public static void printTicket(String srcStation, String destStation, String cardNumber, double fare, double balance) { System.out.println("Card " + cardNumber + " used to travel from station " + srcStation + " to station " + destStation + " . Fare is Rs " + fare + " and balance on the card is Rs " + balance); } /** * @param srcStation * @param destStation * @return double */ public static double calculateFare(String srcStation, String destStation) { char srcStnindex = srcStation.charAt(1); char destStnIndex = destStation.charAt(1); int distanceBetweenStation = Math.abs(destStnIndex - srcStnindex); Calendar c = Calendar.getInstance(); int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); double fare; if (dayOfWeek == 1 || dayOfWeek == 7) fare = 7 * distanceBetweenStation; else fare = 5.5 * distanceBetweenStation; return fare; } /** * @param destStation */ public static void doSwipeOut(String destStation) { Integer swipeCount = stationMap.get(destStation); swipeCount++; stationMap.put(destStation, swipeCount); } } <file_sep>/src/com/nano/core/ByteTest.java package com.nano.core; import java.io.DataInputStream; import java.io.IOException; public class ByteTest { public static void main(String[] args) { DataInputStream in = new DataInputStream(System.in); try { byte d; while ((d = in.readByte()) != 0) { System.out.println(d); } } catch (IOException e) { e.printStackTrace(); } System.exit(0); } } <file_sep>/src/com/nano/core/Main_Method_Private.java package com.nano.core; public class Main_Method_Private { private static void main() { System.out.println(" Inside Private Main Methods..."); } public static void main(String[] args) { System.out.println(" Inside Main Methods..."); } } <file_sep>/src/com/nano/hacker/contest/SherlockAndWatson_ArrayRotation.java package com.nano.hacker.contest; import java.util.Scanner; public class SherlockAndWatson_ArrayRotation { /** * <NAME> performs an operation called Right Circular Rotation on an * integer array a0,a1 … an-1. Right Circular Rotation transforms the array * from a0,a1 … aN-1 to aN-1,a0,… aN-2. He performs the operation K times * and tests Sherlock’s ability to identify the element at a particular * position in the array. He asks Q queries. Each query consists of one * integer x, for which you have to print the element ax. Input Format The * first line consists of 3 integers N, K and Q separated by a single space. * The next line contains N space separated integers which indicates the * elements of the array A. Each of the next Q lines contain one integer per * line denoting x. Output Format For each query, print the value in the * location in a newline. Constraints 1 ≤ N ≤ 105 1 ≤ A[i] ≤ 105 1 ≤ K ≤ 105 * 1 ≤ Q ≤ 500 0 ≤ x ≤ N-1 Sample input 3 2 3 1 2 3 0 1 2 Sample output 2 3 * 1 Explanation After one rotation array becomes, 3 1 2. After another * rotation array becomes 2 3 1. Final array now is 2,3,1. 0th element of * array is 2. 1st element of array is 3. 2nd element of array is 1. */ public static void main(String[] args) { Scanner in = new Scanner(System.in); String n = in.nextLine(); String[] n_split = n.split(" "); int a_size = Integer.parseInt(n_split[0]); int k = Integer.parseInt(n_split[1]); int q = Integer.parseInt(n_split[2]); int[] _a = new int[a_size]; int _a_item; String next = in.nextLine(); String[] next_split = next.split(" "); for (int _a_i = 0; _a_i < a_size; _a_i++) { _a_item = Integer.parseInt(next_split[_a_i]); _a[_a_i] = _a_item; } int[] queries = new int[q]; for (int j = 0; j < q; j++) queries[j] = Integer.parseInt(in.nextLine()); int[] arrayAfterRotation = rotateArray(_a, k); for (int j = 0; j < q; j++) System.out.println(arrayAfterRotation[queries[j]]); } /** * @param a * @param k * @return int[] */ public static int[] rotateArray(int[] a, int k) { int size = a.length; k = k % size; int[] temp = new int[size]; for (int i = 0; i < size; i++) { if (i + k <= size - 1) temp[i + k] = a[i]; else temp[i + k - size] = a[i]; } return temp; } } <file_sep>/src/com/nano/core/nestedClass/Interface_Inside_Class.java package com.nano.core.nestedClass; public class Interface_Inside_Class { private interface nested_Interface { public static final int constant = 0; } private class nestedClass { } public static void main(String[] args) { // TODO Auto-generated method stub } } <file_sep>/src/com/nano/hacker/algo/dynamicprogramming/MaximumSubArrayProblem.java package com.nano.hacker.algo.dynamicprogramming; import java.util.Scanner; public class MaximumSubArrayProblem { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int totalTestCases = Integer.parseInt(scanner.nextLine()); String[] lenthArray = new String[totalTestCases]; String[] inputLines = new String[totalTestCases]; for (int i = 0; i < totalTestCases; i++) { lenthArray[i] = scanner.nextLine(); inputLines[i] = scanner.nextLine(); } for (int i = 0; i < totalTestCases; i++) System.out.println(calculateMaxSubArraySum(inputLines[i], Integer.parseInt(lenthArray[i]))); scanner.close(); } private static String calculateMaxSubArraySum(String inputLine, int length) { // String maxSum = ""; String[] numStringArray = inputLine.split(" "); long maxSum = 0l; long currentSum = 0l; boolean allNegative = true; long sumAllPositiveNums = 0; int maxAmongNegative = 0; // This will store maximum number in case of // all negative numbers. for (int i = 0; i < length; i++) { int num = Integer.parseInt(numStringArray[i]); currentSum += num; if (maxSum < currentSum) { maxSum = currentSum; } else if (currentSum < 0) currentSum = 0; // Handling for non-contiguous max sum And in case if all -ve // numbers. if (num > 0) { allNegative = false; sumAllPositiveNums += num; } // in case of all -ve nums, track max -ve num i.e that with min // absolute value. else if ((maxAmongNegative == 0 && num < 0) || (maxAmongNegative != 0 && maxAmongNegative < num)) // this big condition is imp { maxAmongNegative = num; } } if (allNegative) return maxAmongNegative + " " + maxAmongNegative; else return maxSum + " " + sumAllPositiveNums; } } <file_sep>/src/com/nano/pramp/MoveZerosToEnd.java import java.io.*; import java.util.*; public class MoveZerosToEnd { static int[] moveZerosToEnd(int[] arr) { // your code goes here int l = arr.length; if(l<2){ return arr; } int count=0; for(int i=0;i<l;i++){ if(arr[i]==0) count++; else if(count!=0){ arr[i-count]=arr[i]; } } for(int i=0;i<count;i++){ arr[l-count+i]=0; } return arr; } public static void main(String[] args) { int[] a = new int[]{1, 10, 0, 2, 8, 3, 0, 0, 6, 4, 0, 5, 7, 0}; System.out.println(Arrays.toString(moveZerosToEnd(a))); } } <file_sep>/api/com/nano/pdf/iText/EncryptionPdf.java package com.nano.pdf.iText; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.commons.io.IOUtils; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfWriter; public class EncryptionPdf { /** User password. */ public static byte[] USER = "Hello".getBytes(); /** Owner password. */ public static byte[] OWNER = "World".getBytes(); /** The resulting PDF file. */ public static final String RESULT1 = "encryption.pdf"; /** The resulting PDF file. */ public static final String RESULT2 = "encryption_decrypted.pdf"; /** The resulting PDF file. */ public static final String RESULT3 = "encryption_encrypted.pdf"; /** * Creates a PDF document. * * @param filename * the path to the new PDF document * @throws DocumentException * @throws IOException */ public void createPdf(String filename) throws IOException, DocumentException { // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); writer.setEncryption(USER, OWNER, PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128); writer.createXmpMetadata(); // step 3 document.open(); // step 4 document.add(new Paragraph("Hello World")); // step 5 document.close(); } /** * Manipulates a PDF file src with the file dest as result * * @param src * the original PDF * @param dest * the resulting PDF * @throws IOException * @throws DocumentException */ public void decryptPdf(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src, OWNER); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.close(); reader.close(); } /** * Manipulates a PDF file src with the file dest as result * * @param src * the original PDF * @param dest * the resulting PDF * @throws IOException * @throws DocumentException */ public void encryptPdf(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.setEncryption(USER, OWNER, PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA); stamper.close(); reader.close(); } public void encryptPrfFromByteArray() { File file = new File("Normal.pdf"); byte[] pdfBytes = null; try { pdfBytes = IOUtils.toByteArray(new FileInputStream(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { PdfReader pdfReader = new PdfReader(pdfBytes); ByteArrayOutputStream lBaos = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(pdfReader, lBaos); stamper.setEncryption(USER, OWNER, PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA); stamper.close(); pdfReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Main method. * * @param args * no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws IOException, DocumentException { int i = 2; double r = Math.sqrt(i); System.out.format("The square root of %d is %f.\n", i, r); System.out.println("sssssss"); System.out.print("dddddddddd"); EncryptionPdf metadata = new EncryptionPdf(); // metadata.createPdf(RESULT1); // metadata.decryptPdf(RESULT1, RESULT2); // metadata.encryptPdf(RESULT2, RESULT3); // metadata.encryptPrfFromByteArray(); } } <file_sep>/src/com/nano/core/math/HighestPowerOfTwo_DiffWays.java package com.nano.core.math; import java.math.BigInteger; public class HighestPowerOfTwo_DiffWays { public static void main(String[] args) { BigInteger bigInteger = new BigInteger("99"); System.out.println("getHighestPowerOf2_Method3 - " + getHighestPowerOf2_Method3(bigInteger)); System.out.println("getHighestPowerOf2_Method2 - " + getHighestPowerOf2_Method2(bigInteger)); } /* * this is wrong byte[] is not right datatype here we need something to * represent bits. private static BigInteger * getHighestPowerOf2_Method1(BigInteger bigInteger) { int bitLength = * bigInteger.bitLength(); byte[] arr = new byte[bitLength]; arr[0] = 1; * return new BigInteger(arr); } */ /** * Best solution so far * * @param bigInteger * @return */ private static BigInteger getHighestPowerOf2_Method2(BigInteger bigInteger) { int bitLength = bigInteger.bitLength(); return BigInteger.ZERO.setBit(bitLength - 1); } /** * My Method - Its expensive because in each iteration it creates new * BigInteger. * * @param bigInteger * @return */ private static BigInteger getHighestPowerOf2_Method3(BigInteger bigInteger) { int bitLength = bigInteger.bitLength(); for (int index = 0; index < (bitLength - 1); index++) bigInteger = bigInteger.clearBit(index); return bigInteger; } } <file_sep>/src/com/nano/core/AbstractStaticMethodTest.java package com.nano.core; public abstract class AbstractStaticMethodTest { // putting static here gives compile-time error as below: // The abstract method fun in type AbstractStaticMethodTest can only set a // visibility modifier, one of public or protected public abstract void fun(); } <file_sep>/src/com/nano/core/inheritanceTest/InherietenceAndException.java package com.nano.core.inheritanceTest; public class InherietenceAndException extends A { public void f() { } public void fun() // Compiletime error: throws Exception { } public void funny() throws RuntimeException { } public void someMorefunny() // Compiletime error: throws Exception { } public static void main(String[] args) { } } class A { public void f() throws Exception { } public void fun() { } public void funny() throws Exception { } public void someMorefunny() throws RuntimeException { } }<file_sep>/src/com/manthano/test/GenericRestictionTEst.java package com.manthano.test; public class GenericRestictionTEst { // https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createStatic public static void main(String[] args) { Object[] a = new String[2]; a[0] = "11ss"; a[1]=1; for(Object o : a) { System.out.println(o); } ArrayStoreException ase; } } <file_sep>/src/com/nano/core/generics/DiamondOperator.java package com.nano.core.generics; /** * @author LXMRX * @param <T> */ public class DiamondOperator<T> { /** * @param t */ public DiamondOperator(T t) { } /** * @return T */ public T get() { return null; } /** * @param s * @return int */ public static int func(String s) { return 1; } /** * @param o * @return int */ public static int func(Object o) { return 2; } /** * @param args */ public static void main(String[] args) { // Note- the method call func() in which object is created. I wasted // some time becoz I missed to see func() call. System.out.println(func(new DiamondOperator<>("").get())); System.out.println(func(new DiamondOperator("").get())); } } <file_sep>/src/com/nano/hacker/IsFibo.java package com.nano.hacker; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Set; import java.util.TreeSet; /** * @author LXMRX You are given an integer N, can you check if the number is an * element of fibonacci series? The first few elements of fibonacci * series are 0,1,1,2,3,5,8,13…. A fibonacci series is one where every * element is a sum of the previous two elements in the series. The * first two elements are 0 and 1. Formally: fib0 = 0 fib1 = 1 fibn = * fibn-1 + fibn-2 ∀ n > 1 Input Format First line contains T, number of * test cases. T lines follows. Each line will contain an integer N. * Output Format Output “IsFibo” (without quotes) if N is a fibonacci * number and “IsNotFibo” (without quotes) if it is not a fibonacci * number, in a new line corresponding to each test case. Constraints 1 * <= T <= 105 1 <= N <= 1010 Sample Input 3 5 7 8 Sample Output IsFibo * IsNotFibo IsFibo Explanation 5 is a Fibonacci number given by fib5 = * 3 + 2 7 is not a Fibonacci number 8 is a Fibonacci number given by * fib6 = 5 + 3 */ public class IsFibo { static Set<BigInteger> fiboSet = new TreeSet<BigInteger>(); static String isFibo = "IsFibo"; static String isNotFibo = "IsNotFibo"; static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static { fillFiboSeries(100); } /** * @param args * @throws NumberFormatException * @throws IOException */ public static void main(String[] args) throws NumberFormatException, IOException { int t = Integer.parseInt(in.readLine()); for (int i = 0; i < t; i++) { System.out.println(solve(in.readLine())); } } /** * @param num * @return String */ public static String solve(String num) { if (num.equals("0")) return isFibo; if (fiboSet.contains(new BigInteger(num))) return isFibo; else return isNotFibo; } /** * @param seriesLength */ public static void fillFiboSeries(int seriesLength) { BigInteger t1 = BigInteger.ZERO; BigInteger t2 = BigInteger.ONE; BigInteger temp; for (int i = 1; i <= seriesLength; i++) { fiboSet.add(new BigInteger(String.valueOf(t2))); temp = t1; t1 = t2; t2 = temp.add(t2); } } } <file_sep>/src/com/nano/thread/PollingVariableThread.java package com.nano.thread; public class PollingVariableThread { static boolean polVariable = false; static int var = 2; /** * @param args */ public static void main(String[] args) { System.out.println("Start........" + System.getenv()); Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println("Inside Run......"); while (!polVariable) { System.out.println("Polling variable is false;"); System.out.println("Value of var = " + var); } } }); t1.start(); var = 43; polVariable = true; } } <file_sep>/src/com/nano/core/datastructure/ReverseLinkedListTest.java package com.nano.core.datastructure; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; public class ReverseLinkedListTest { public static void main(String[] args) { List<String> list = new LinkedList<>(); list.iterator(); list.listIterator(); list.listIterator(0); List<String> arrayList = new ArrayList<>(); arrayList.iterator(); arrayList.listIterator(); arrayList.listIterator(0); MySinglyLinkedList<String> myLinkedList = new MySinglyLinkedList<String>(); Iterator<String> myNodeIteratorForEmptyList = myLinkedList.iterator(); try { while (myNodeIteratorForEmptyList.hasNext()) System.out.println(myNodeIteratorForEmptyList.next()); } catch (NoSuchElementException e) { e.printStackTrace(); } myLinkedList.add("First"); myLinkedList.add("Second"); myLinkedList.add("Third"); myLinkedList.add("Fourth"); myLinkedList.add("Fifth"); Iterator<String> myNodeIterator = myLinkedList.iterator(); while (myNodeIterator.hasNext()) System.out.println(myNodeIterator.next()); // reverse System.out.println("After calling reverse.........."); myLinkedList.reverse(); myNodeIterator = myLinkedList.iterator(); while (myNodeIterator.hasNext()) System.out.println(myNodeIterator.next()); } } class MySinglyLinkedList<E> { private transient Node<E> head = null; // This is needed if Iterator has to be implemented as while traversing private transient int size = 0; private static class Node<E> { E data; Node next; Node(E data, Node next) { this.data = data; this.next = next; } } public boolean add(E e) { linkLast(e); return true; } public E getHead() { final Node<E> h = head; if (head == null) throw new NoSuchElementException(); return h.data; } public void reverse() { Node<E> currentNode = head; // For first node, previousNode will be null Node<E> prevNode = null; Node<E> nextNode = null; while (currentNode != null) { nextNode = currentNode.next; currentNode.next = prevNode; prevNode = currentNode; currentNode = nextNode; } // set head to last Element head = prevNode; } private void linkLast(E e) { Node<E> newNode = new Node(e, null); // if LinkedList is empty, So assign head to new Element and RETURN if (head == null) { head = newNode; return; } Node<E> tempHead = head; Node<E> secondLast = null; while (tempHead != null) { secondLast = tempHead; tempHead = tempHead.next; } secondLast.next = newNode; } public Iterator<E> iterator() { return new ItrNodeImpl<E>(); } private class ItrNodeImpl<E> implements Iterator<E> { /** * This Itr impl is created with 0 cursor value Index of element to be * returned by subsequent call to next. */ // int cursor = 0; private Node<E> headRef = (Node<E>) head; @Override public boolean hasNext() { if (headRef == null) return false; else return true; } @Override public E next() { if (headRef == null) return null; else { E data = headRef.data; headRef = headRef.next; return data; } } @Override public void remove() { // TODO Auto-generated method stub } } }<file_sep>/src/com/nano/hacker/algo/warmup/DiagonalDifference.java package com.nano.hacker.algo.warmup; import java.util.Scanner; public class DiagonalDifference { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t; t = Integer.parseInt(in.nextLine()); int[][] a = new int[t][t]; int mainDiagonalSum = 0; for (int i = 0; i < t; i++) { for (int j = 0; j < t; j++) { a[i][j] = in.nextInt(); if (i == j) mainDiagonalSum += a[i][j]; } } int i = 0, j = t - 1; int oppoDiagonalSum = 0; while (i < t) { oppoDiagonalSum += a[i][j]; i++; j--; } System.out.println(Math.abs(oppoDiagonalSum - mainDiagonalSum)); in.close(); } } <file_sep>/src/com/nano/hacker/ds/linkedList/InsertNodeAtTail.java package com.nano.hacker.ds.linkedList; /** * Problem Statement * * This challenge is part of a tutorial track by MyCodeSchool and is accompanied * by a video lesson. * * You’re given the pointer to the head node of a linked list and an integer to * add to the list. Create a new node with the given integer, insert this node * at the tail of the linked list and return the head node. The head pointer * given may be null meaning that the initial list is empty. * * Input Format You have to complete the Node* Insert(Node* head, int data) * method which takes two arguments - the head of the linked list and the * integer to insert. You should NOT read any input from stdin/console. * * Output Format Insert the new node at the tail and just return the head of the * updated linked list. Do NOT print anything to stdout/console. * * Sample Input * * NULL, data = 2 2 --> NULL, data = 3 * * Sample Output * * 2 -->NULL 2 --> 3 --> NULL * * Explanation 1. We have an empty list and we insert 2. 2. We have 2 in the * tail, when 3 is inserted 3 becomes the tail. * * @author LXMRX * */ public class InsertNodeAtTail { public static void main(String[] args) { Node head = null; insert(head, 1); } /* * Insert Node at the end of a linked list head pointer input could be NULL * as well for empty list Node is defined as */ static class Node { int data; Node next; } static Node insert(Node head, int data) { // This is a "method-only" submission. // You only need to complete this method. Node node = new Node(); node.data = data; node.next = null; Node originalHead = head; Node prevNode = null; // if LinkedList is empty if (head == null) { head = node; return head; } while (head != null) { prevNode = head; head = head.next; } prevNode.next = node; return originalHead; } } <file_sep>/src/com/nano/inter/SapientSearchInThreeFiles.java package com.nano.inter; public class SapientSearchInThreeFiles { public static void main(String[] a) { } } /* * @Override * public List<FlightSearchDTO> searchFlightPrepare(String dirLocation) throws * FlightNotFoundException, * FileNotFoundException * { * File dir = new File(dirLocation); * List<FlightSearchDTO> flightDetailsInAllFiles = new * ArrayList<FlightSearchDTO>(); * if (dir.exists()) * { * File[] files = dir.listFiles(); * for (int i = 0; i < files.length; i++) * { * File file = files[i]; * try * { * BufferedReader readFileBr = new BufferedReader(new FileReader(file)); * String fileData = null; * int firstLine = 0; * while ((fileData = readFileBr.readLine()) != null) * { * FlightSearchDTO flightSearchDTO = new FlightSearchDTO(); * if (firstLine == 0) * { * firstLine = 1; * continue; * } * StringTokenizer st = new StringTokenizer(fileData, "|"); * List<String> list = new LinkedList<String>(); * int myIndex = 0; * while (st.hasMoreElements()) * { * String data = ""; * data = (String) st.nextElement(); * list.add(myIndex, data); * myIndex++; * } * flightSearchDTO.setFlightNumber(list.get(0)); * flightSearchDTO.setDepartureLoccation(list.get(1)); * flightSearchDTO.setArrivalLocation(list.get(2)); * flightSearchDTO.setFlightDate(list.get(3));// valid till * // in csv * // file * flightSearchDTO.setFilghtTime(list.get(4)); * flightSearchDTO.setFlightDuration(list.get(5)); * flightSearchDTO.setFare(list.get(6)); * flightDetailsInAllFiles.add(flightSearchDTO); * } * } * catch (FileNotFoundException exception) * { * new FlightNotFoundException(exception.getMessage()); * } * catch (IOException exception) * { * new FlightNotFoundException(exception.getMessage()); * } * catch (Exception exception) * { * new FlightNotFoundException(exception.getMessage()); * } * } * return flightDetailsInAllFiles; * } * else * { * throw new FileNotFoundException("File is not found on given location"); * } * } * @Override * public List<FlightSearchDTO> searchFlightResult(String depLoc, String arrLoc, * String flightDate, String outPref, * String dirLocation) throws FlightNotFoundException, FileNotFoundException * { * List<FlightSearchDTO> allFlightData = searchFlightPrepare(dirLocation); * List<FlightSearchDTO> matchedFlightData = new ArrayList<FlightSearchDTO>(); * for (Iterator iterator = allFlightData.iterator(); iterator.hasNext();) * { * FlightSearchDTO flightSearchDTO = (FlightSearchDTO) iterator.next(); * if (flightSearchDTO.getDepartureLoccation().equalsIgnoreCase(depLoc) * && flightSearchDTO.getArrivalLocation().equalsIgnoreCase(arrLoc) * && flightSearchDTO.getFlightDate().equalsIgnoreCase(flightDate)) * { * matchedFlightData.add(flightSearchDTO); * } * } * FlightComparator flightComparator = new FlightComparator(); * flightComparator.setOutputPref(outPref); * Collections.sort(matchedFlightData, flightComparator); * return matchedFlightData; * } */ <file_sep>/src/com/nano/hacker/ds/linkedList/GetNodeValueFromTail.java package com.nano.hacker.ds.linkedList; public class GetNodeValueFromTail { static class Node { int data; Node next; } static int getNodeValueFromTail(Node head, int posFromTail) { return 0; } public static void main(String[] args) { Node head = null; System.out.println(getNodeValueFromTail(head, 0)); } } <file_sep>/src/com/nano/hacker/q.java package com.nano.hacker; import java.util.Scanner; public class q { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); // int res; int K = Integer.parseInt(in.nextLine()); String str = in.nextLine(); int strLength = str.length(); int possBlock = strLength / K; char[] cArray = str.toCharArray(); String[] arr = null; int thePass = 0; for (int i = 0; i < possBlock; i++) { int firstIndex = i * K; if (firstIndex == 0) {} else firstIndex--; char temp = cArray[firstIndex]; cArray[firstIndex] = cArray[((firstIndex * K) - 1) < 0 ? K - 1 : (firstIndex * K) - 1]; cArray[((firstIndex * K) - 1) < 0 ? K - 1 : (firstIndex * K) - 1] = temp; thePass++; } String newStr = new String(cArray); System.out.println(newStr); } } <file_sep>/src/com/nano/inter/bankofAmerica/RunMethodAtMostForGivenTime.java package com.nano.inter.bankofAmerica; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class RunMethodAtMostForGivenTime { public static void main(String[] args) { RunMethodAtMostForGivenTime obj = new RunMethodAtMostForGivenTime(); System.out.println(obj.sum()); } private int sum() { int sum = 1; ExecutorService service = Executors.newFixedThreadPool(1); int returnedInt = 0; Future<Integer> calculatedIntFuture = service .submit(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.currentThread().sleep(110); return new Integer(1); } }); try { returnedInt = calculatedIntFuture.get(10, TimeUnit.MILLISECONDS); sum += returnedInt; } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } return sum; } } <file_sep>/src/com/nano/hacker/algo/string/Anagram.java package com.nano.hacker.algo.string; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; /** * @author LXMRX * Sid is obsessed about reading short stories. Being a CS student, he * is doing some interesting frequency analysis with the books. From two * short story books, he choses strings having length a from the first * and strings having length b from the second one. The strings are such * that the difference of length is <= 1 * i.e. * |a-b|<=1, where |x| represents the absolute value function. * He believes that both the strings should be anagrams based on his * experiment. Your challenge is to help him find the minimum number of * characters of the first string he needs to change to make it an * anagram of the second string. Neither can he add a character nor * delete a character from the first string. Only replacement of the * characters with new ones is allowed. * Input Format * First line will contain an integer T representing the number of test * cases. Each test case will contain a string having length (a+b) which * will be concatenation of both the strings described in problem. The * string will only contain small letters and without any spaces. * Output Format * An integer corresponding to each test case is printed in a different * line i.e., the number of changes required for each test case. Print * ‘-1’ if it is not possible. * Constraints * 1<=T<=100 * length of input string i.e. 1<=a+b<=10000 * Sample Input * 5 * aaabbb * ab * abc * mnop * xyyx * Sample Output * 3 * 1 * -1 * 2 * 0 * Explanation * In fifth test case, first string will be “xy” while second string * will be “yx” . so a = 2 and b = 2, where a and b are length of * strings. As we can see that a and b are following relation * |a-b|<=1 * and both strings are anagrams.So number of changes required = 0. * 10 * hhpddlnnsjfoyxpciioigvjqzfbpllssuj * xulkowreuowzxgnhmiqekxhzistdocbnyozmnqthhpievvlj * dnqaurlplofnrtmh * aujteqimwfkjoqodgqaxbrkrwykpmuimqtgulojjwtukjiqrasqejbvfbixnchzsahpnyayutsgecwvcqngzoehrmeeqlgknnb * lbafwuoawkxydlfcbjjtxpzpchzrvbtievqbpedlqbktorypcjkzzkodrpvosqzxmpad * drngbjuuhmwqwxrinxccsqxkpwygwcdbtriwaesjsobrntzaqbe * ubulzt * vxxzsqjqsnibgydzlyynqcrayvwjurfsqfrivayopgrxewwruvemzy * xtnipeqhxvafqaggqoanvwkmthtfirwhmjrbphlmeluvoa * gqdvlchavotcykafyjzbbgmnlajiqlnwctrnvznspiwquxxsiwuldizqkkaawpyyisnftdzklwagv * Expected Output * 10 * 13 * 5 * 26 * 15 * -1 * 3 * 13 * 13 * -1 */ public class Anagram { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws IOException, NumberFormatException { int testCases = Integer.parseInt(reader.readLine()); for (int i = 0; i < testCases; i++) solve(reader.readLine()); } private static void solve(String str) { int length = str.length(); if (length % 2 != 0) { System.out.println("-1"); return; } String firstStr = str.substring(0, length / 2); Map<Character, Integer> firstMap = fillMap(firstStr); String secondStr = str.substring(length / 2); Map<Character, Integer> secMap = fillMap(secondStr); int diffLength = 0; for (Character a : secMap.keySet()) { Integer count1 = firstMap.get(a); Integer count2 = secMap.get(a); if (count1 == null) { diffLength += count2; continue; } if (count2 > count1) diffLength += count2 - count1; } System.out.println(diffLength); } private static Map<Character, Integer> fillMap(String str) { Map<Character, Integer> charMap = new HashMap<Character, Integer>(); char c; for (int i = 0; i < str.length(); i++) { c = str.charAt(i); if (charMap.get(c) == null) charMap.put(c, 1); else { int count = charMap.get(c); count++; charMap.put(c, count); } } return charMap; } } <file_sep>/src/com/nano/core/InitialisationBlocksTest.java package com.nano.core; /** * @author LXMRX */ public class InitialisationBlocksTest { private static int i_static = 11; private int i_instance = 11; /** * */ public InitialisationBlocksTest() { System.out.println("in Constructor ---------%n"); /* * This first print statement is TO CHECK AT WHAT STAGE is Value of * instance and static field equal to 11 as set during declaration OR is * Default value 0. */ System.out.printf("START........ i_static = %d and i_instance = %d%n", i_static, i_instance); i_static = 33; i_instance = 33; System.out.printf("END........ i_static = %d and i_instance = %d%n%n", i_static, i_instance); } static { System.out.println("in Static Block---------%n"); System.out.printf("START........ i_static = %d%n ", i_static); i_static = 22; System.out.printf("END........ i_static = %d %n%n", i_static); } { System.out.println("in object initializer Block--------%n"); System.out.printf("START........ i_static = %d and i_instance = %d%n", i_static, i_instance); i_instance = 44; i_static = 44; System.out.printf("END........ i_static = %d and i_instance = %d%n%n", i_static, i_instance); } /** * @return the i_static */ public static int getI_static() { return i_static; } /** * @param i_static * the i_static to set */ public static void setI_static(int i_static) { InitialisationBlocksTest.i_static = i_static; } /** * @return the i_instance */ public int getI_instance() { return i_instance; } /** * @param i_instance * the i_instance to set */ public void setI_instance(int i_instance) { this.i_instance = i_instance; } /** * @param args */ public static void main(String[] args) { System.out .printf("%n%n *******Let's see if its first to get printed...Or anything CAN RUN BEFORE MAIN METHOD.....%n%n"); InitialisationBlocksTest classWithDiffInitialisationBlocks = new InitialisationBlocksTest(); System.out.printf("MAIN METHOD........ START........ i_static = %d and i_instance = %d%n%n", getI_static(), classWithDiffInitialisationBlocks.getI_instance()); } } <file_sep>/src/com/nano/collection/HashMapKeyHashCodeModification.java package com.nano.collection; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.Map; import java.util.Stack; import java.util.Vector; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingQueue; import com.nano.annotation.ClassPreamble; @ClassPreamble(author = "Amit", createdDate = "22-July-2014", reviewers = { "A", "B" }) public class HashMapKeyHashCodeModification { /** * @param args */ public static void main(String[] args) { Thread aThead = new Thread(); LinkedList<String> linkedList = new LinkedList<String>(); Stack<String> stack = new Stack<String>(); ConcurrentHashMap<String, String> concurrentMap = new ConcurrentHashMap<String, String>(); Object obj = new Object(); Map syncMap = Collections.synchronizedMap(concurrentMap); Hashtable<String, String> hashtable = new Hashtable<String, String>(); Vector<String> vector = new Vector<String>(); CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<String>(); CopyOnWriteArraySet<String> cpoyOnWriteArraySet = new CopyOnWriteArraySet<String>(); BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(9); LinkedBlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<String>(); // Following are additions to Concurrent API in JDK 1.6 ConcurrentSkipListMap<String, String> concurrentSkipListMap = new ConcurrentSkipListMap<String, String>(); ConcurrentSkipListSet<String> concurrentSkipListSet = new ConcurrentSkipListSet<String>(); HashMap<KeyClass, String> map = new HashMap<KeyClass, String>(); KeyClass k1 = new KeyClass("A"); KeyClass k2 = new KeyClass("B"); KeyClass k3 = new KeyClass("C"); KeyClass kZ = new KeyClass("Z"); System.out.println("Before Change, HashCode of K1 = " + k1.hashCode()); map.put(k1, "A-Value"); map.put(k2, "B-Value"); map.put(k3, "C-Value"); map.put(null, "null-Value-1"); map.put(null, "null-Value-2"); map.put(kZ, "Z-Value..."); k1.setStr("Z"); System.out.println("After Change, HashCode of K1 = " + k1.hashCode()); System.out.println(map.containsKey(k1)); System.out.println("Value of NULL-mapped key : " + map.get(null)); System.out.println("Value of Z-mapped key : " + map.get(k1)); /* * KeyClass kA = new KeyClass("A"); * System.out.println("kA.equals(k1) = " + kA.equals(k1)); * System.out.println(map.containsKey(kA)); */ } } class KeyClass { private String str = null; public KeyClass(String str) { this.str = str; } @Override public int hashCode() { int hashCode = 31; hashCode = hashCode + 17 * str.hashCode(); return hashCode; } @Override public boolean equals(Object obj) { if (!(obj instanceof KeyClass)) return false; KeyClass keyClass = (KeyClass) obj; return this.str.equals(keyClass.str); } /** * @return the str */ public String getStr() { return str; } /** * @param str * the str to set */ public void setStr(String str) { this.str = str; } @Override public String toString() { return str; } } <file_sep>/src/com/nano/pramp/DecodeVariations.java package com.nano.pramp; /** * * * https://www.pramp.com/challenge/r1Kw0vwG6OhK9AEGAy6L * Decode Variations A letter can be encoded to a number in the following way: 'A' -> '1', 'B' -> '2', 'C' -> '3', ..., 'Z' -> '26' A message is a string of uppercase letters, and it is encoded first using this scheme. For example, 'AZB' -> '1262' Given a string of digits S from 0-9 representing an encoded message, return the number of ways to decode it. Examples: input: S = '1262' output: 3 explanation: There are 3 messages that encode to '1262': 'AZB', 'ABFB', and 'LFB'. Constraints: [time limit] 5000ms [input] string S 1 ≤ S.length ≤ 12 [output] integer HINT: Try to write the number of ways to write S[i:] in terms of the number of ways to write S[i+1:] and S[i+2:]. For example, if there are 2 ways to write S[1:] = '262' ('ZB' and 'BFB'), and one way to write S[2:] = '62' ('FB'), then we could say there are 3 ways to write S as we either write 'A' then a decoding of S[1:], or write 'L' then a decoding of S[2:]. We can store the answer for S[i:] into an integer array dp. The recursion is given below. You can help the candidate with the specific part of the recursion they are having difficulty with: If S[i] == 0, then dp(i) = 0. If S[i] == 1, then we have dp(i) = dp(i+1) + dp(i+2). If S[i] == 2, then we have dp(i) = dp(i+1) + (S[i+1] <= 6 ? dp(i+2) : 0). If S[i] > 2, then we have dp(i) = dp(i+1). Solution: Dynamic Programming Let dp(i) be the answer for the string S[i:]. We can calculate dp(i) in terms of dp(i+1) and dp(i+2). If S[i] == 0, then dp(i) = 0. There are no ways, since no encoded letter starts with 0. If S[i] == 1, then we have dp(i) = dp(i+1) + dp(i+2), since either we write A plus any way to write S[i+1:], or we write a letter that encodes somewhere between 10 and 19, plus any way to write S[i+2:]. If S[i] == 2, then we have dp(i) = dp(i+1) + (S[i+1] <= 6 ? dp(i+2) : 0). Either we write B plus any way to write S[i+1:], or we write a letter that encodes somewhere between 20 and 26, plus any way to write S[i+2:]. If S[i] > 2, then we have dp(i) = dp(i+1). For example, if S[i] = 5, then we write E plus any way to write S[i+1:]. We can’t write any other letters because the only letter which has encoding that starts with 5 is E. Putting this all together, we have the following code: function decodeVariations(S): N = S.length dp = new Array(N) dp[N] = 1 for i from N-1 to 0: if S[i] == '0': dp[i] = 0 else if S[i] == '1': dp[i] = dp[i+1] + dp[i+2] else if S[i] == '2': dp[i] = dp[i+1] if i+1 < S.length && S[i+1] <= '6': dp[i] += dp[i+2] else: dp[i] = dp[i+1] return dp[0] Of course, since at each step we only reference dp[i+1] and dp[i+2], we could store these as variables first and second. This means we do not need to store the entire array: function decodeVariations(S): pre, cur = 27, 0 first, second = 1, 1 for i from S.length - 1 to 0: d = int(S[i]) if d == 0: cur = 0 else: cur = first # pre represents the previously seen number S[i+1] # If d*10 + pre < 26 (and d != 0), it is valid to # write a letter that uses two digits of encoding length, # so we count 'second = dp[i+2]' in our current answer. if d * 10 + pre < 27: cur += second pre = d first, second = cur, first return cur Time Complexity: O(N) where N is the length of S. Space Complexity: O(N) to store the array dp. In our space saving variation, the complexity is O(1). * @author NanoUser * */ public class DecodeVariations { } <file_sep>/src/com/nano/core/string/ReverseStringRecursively.java package com.nano.core.string; public class ReverseStringRecursively { /** * @param args */ public static void main(String[] args) { String str = "abcdefghi"; System.out.println(recursiveReverse(str)); } static String recursiveReverse(String str) { if (str.length() < 2) return str; return recursiveReverse(str.substring(1)) + str.charAt(0); } } <file_sep>/src/com/nano/inter/goldmansachs/AQuestion.java package com.nano.inter.goldmansachs; public interface AQuestion { public abstract void someMethod() throws Exception; } class ConcreteClass implements AQuestion { // The method need not throw any exception @Override public void someMethod() { // TODO Auto-generated method stub } }<file_sep>/src/com/nano/core/inheritanceTest/InheritenceTest.java package com.nano.core.inheritanceTest; public class InheritenceTest { public static void main(String[] args) { Employee e = new Manager(); System.out.println(e.salary); System.out.println(e.getSalary()); // 2. ERROR- As getBonus() is not in Employee // class.....System.out.println(e.getBonus()); InheritenceTest obj = new InheritenceTest(); obj.getEmployeeData(e); } public void getEmployeeData(Employee e) { System.out.println(e.getSalary()); } public void getEmployeeData(Manager m) { System.out.println(m.getSalary()); } } class Employee { public int salary = 5; public Employee() { } public int getSalary() { return 1; } } class Manager extends Employee { public int salary = 7; // 1. getSalary() cannot be declared protected public int getSalary() { return 2; } public int getBonus() { return 3; } }<file_sep>/src/com/nano/hacker/InsertionSortPart1.java package com.nano.hacker; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author LXMRX */ public class InsertionSortPart1 { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); /** * @param args * @throws NumberFormatException * @throws IOException */ public static void main(String[] args) throws NumberFormatException, IOException { int length = Integer.parseInt(reader.readLine()); int[] arr = new int[length]; String arrayLine = reader.readLine(); String[] splitArray = arrayLine.split(" "); for (int i = 0; i < length; i++) arr[i] = Integer.parseInt(splitArray[i]); int v = arr[length - 1]; for (int i = length - 2; i >= 0; i--) { if (arr[i] > v) { arr[i + 1] = arr[i]; if (i == 0) arr[i] = v; printArray(arr); }// avoiding printing array when arr[i]==v else if (arr[i] < v) { arr[i + 1] = v; printArray(arr); break; } System.out.println(); } } private static void printArray(int[] arr) { for (int j = 0; j < arr.length; j++) { System.out.print(arr[j]); if (j != arr.length - 1) System.out.print(" "); } } } <file_sep>/src/com/nano/core/BitshiftOperators.java package com.nano.core; /** * @author LXMRX */ public class BitshiftOperators { /** * @param args */ public static void main(String[] args) { int i = -16; System.out .println("With Negative number >>> gives DIFFERENT results...........\n"); System.out.println("i = " + i + ", 2 * i = " + multiplyByPowerOfTwo(i, 1)); System.out .println("i = " + i + ", 2 / i = " + divideByPowerOfTwo(i, 1)); System.out.println("unSignedRightShiftOperator -> " + unSignedRightShiftOperator(i)); i = 16; System.out .println("\nWith Positive number .....................................\n"); System.out.println("i = " + i + ", 2 * i = " + multiplyByPowerOfTwo(i, 1)); System.out .println("i = " + i + ", 2 / i = " + divideByPowerOfTwo(i, 1)); System.out.println("unSignedRightShiftOperator -> " + unSignedRightShiftOperator(i)); i = 1; System.out.println("Shift " + i + " right 1 places -> " + (i >> 1)); System.out.println("Shift " + i + " right 4 places -> " + (i >> 4)); } /** * @param num * @return int */ public static int unSignedRightShiftOperator(int num) { return num >>> 1; } /** * @param number * @param powerOfTwo * @return int */ public static int multiplyByPowerOfTwo(int number, int powerOfTwo) { return number << powerOfTwo; } /** * @param number * @param powerOfTwo * @return int */ public static int divideByPowerOfTwo(int number, int powerOfTwo) { return number >> powerOfTwo; } } <file_sep>/src/com/manthano/test/StringSplitSpaceTest.java package com.manthano.test; public class StringSplitSpaceTest { public static void main(String[] args) { String s = " 3paces 2spaces 1space"; String[] a = s.split("\\s+"); System.out.println(a.length); for(String ss : a) { if(ss.startsWith(" ") || ss.isEmpty()) { System.out.println("loud:" + ss); continue; } else System.out.println(ss); } String[] splitWithoutPlus = s.split("\\s"); System.out.println(splitWithoutPlus.length); for(String ss : splitWithoutPlus) { if(ss.startsWith(" ") || ss.isEmpty()) { System.out.println("loudWithoutPlus:" + ss); continue; } else System.out.println(ss); } String ip="..."; String[] ar = ip.split("\\."); System.out.println(ip + ":" + ar.length); ip=".2.."; ar = ip.split("\\."); System.out.println(ip + ":" + ar.length); for(String ss : ar) { if(ss.startsWith(" ") || ss.isEmpty()) { System.out.println("IPWithoutPlus:" + ss); continue; } else System.out.println(ss); } ip=".2.3.4"; ar = ip.split("\\."); System.out.println(ip + ":" + ar.length ); for(String ss : ar) { if(ss.startsWith(" ") || ss.isEmpty()) { System.out.println("IPWithoutPlus:" + ss); continue; } else System.out.println(ss); } } } <file_sep>/src/com/nano/hacker/algo/warmup/ExtraLongFactorials.java package com.nano.hacker.algo.warmup; import java.math.BigInteger; import java.util.Scanner; public class ExtraLongFactorials { public static void main(String[] args) { Scanner in = new Scanner(System.in); int num = in.nextInt(); in.close(); BigInteger bigNum = new BigInteger(String.valueOf(num)); System.out.println(calculateFactorial(bigNum)); } private static BigInteger calculateFactorial(BigInteger bigNum) { if (bigNum.equals(BigInteger.ONE)) return BigInteger.ONE; return bigNum.multiply(calculateFactorial(bigNum .subtract(BigInteger.ONE))); } } <file_sep>/src/com/nano/inheritence/TestInheritence.java package com.nano.inheritence; public class TestInheritence { /** * @param args */ public static void main(String[] args) { SubClass a = new SubClass(); // a.di } } class SuperClass { public void display(String str) { System.out.println("Super Class Display method - String : " + str); } } class SubClass { private void display(String n) { System.out.println("Sub Class Display method - int : " + n); } }<file_sep>/src/com/nano/hacker/java/collections/JavaComparator.java package com.nano.hacker.java.collections; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; /** * Problem Statement * * Comparators are used to compare two objects to sort them. This problem will * test your knowledge on Java Comparators. * * There are N players in a tournament. You will be given the name of each * player and his score. You need to sort the players in decreasing order by * score. If two players have the same score, the one whose name is * lexicographically larger should appear first. * * Note: We have already provided you with the partially completed code in the * editor. Your task is to create the class Checker which uses a comparator desc * to sort the players. * * A string is lexicographically smaller than another string if it appears * earlier in a standard dictionary. For example, "cat" is lexicographically * smaller than "dog", but larger than "cab" or "ca". * * Input Format * * The first line contains an integer N, denoting the number of players. The * next N lines contain the name of a player and his score separated by a space. * Two players can have the same name. A name will consist of lowercase English * characters. The score of a player can range from 0 to 1000. You don't need to * worry about any other constraints. * * Output Format * * Print each player and their space-separated score on a different line * according to the directions in the problem statement. * * Sample Input * * 5 amy 100 david 100 heraldo 50 aakansha 75 aleksa 150 Sample Output * * aleksa 150 david 100 amy 100 aakansha 75 heraldo 50 * * @author LXMRX * */ public class JavaComparator { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine().trim()); String s; StringTokenizer st; Player Player[] = new Player[N]; Checker check = new Checker(); for (int i = 0; i < N; i++) { s = br.readLine().trim(); st = new StringTokenizer(s); Player[i] = new Player(); Player[i].name = st.nextToken(); Player[i].score = Integer.parseInt(st.nextToken()); } Arrays.sort(Player, check.desc); for (int i = 0; i < Player.length; i++) { System.out.printf("%s %s\n", Player[i].name, Player[i].score); } } } class Player { String name; int score; } class Checker { static final Comparator<Player> desc = new Comparator<Player>() { @Override public int compare(Player o1, Player o2) { int diff = o2.score - o1.score; return (diff != 0 ? diff : o2.name .compareTo(o1.name)); } }; } <file_sep>/src/com/nano/core/DecimalToOtherRadixSystemConversion.java package com.nano.core; public class DecimalToOtherRadixSystemConversion { /** * @param args */ public static void main(String[] args) { int number = 9; System.out.println("To Binary - " + Integer.toBinaryString(number)); System.out.println("To Hexa - " + Integer.toHexString(number)); System.out.println("To Binary - " + Integer.toOctalString(number)); } } <file_sep>/src/com/nano/hacker/contest/MakeItAnagram.java package com.nano.hacker.contest; import java.util.Scanner; public class MakeItAnagram { // /Alice recently started learning about cryptography and found that // anagrams are very useful. Two strings are anagrams of each other if they // have same character set. For example strings "bacdc" and "dcbac" are // anagrams, while strings "bacdc" and "dcbad" are not. // // Alice decides on an encryption scheme involving 2 large strings where // encryption is dependent on the minimum number of character deletions // required to make the two strings anagrams. She need your help in finding // out this number. // // Given two strings (they can be of same or different length) help her in // finding out the minimum number of character deletions required to make // two strings anagrams. Any characters can be deleted from any of the // strings. // // Input Format // Two lines each containing a string. // // Constraints // 1 <= Length of A,B <= 10000 // A and B will only consist of lowercase latin letter. // // Output Format // A single integer which is the number of character deletions. // // Sample Input #00: // // cde // abc // Sample Output #00: // // 4 // Explanation #00: // We need to delete 4 characters to make both strings anagram i.e. ‘d’ and // ‘e’ from first string and ‘b’ and ‘a’ from second string. public static void main(String[] args) { Scanner sc = new Scanner(System.in); String firstStr = sc.nextLine(); String secStr = sc.nextLine(); } } <file_sep>/src/com/nano/inter/WellAndDiskProblem.java package com.nano.inter; /** * @author Amit */ public class WellAndDiskProblem { private static boolean wellBlocked = false; private static int ringInnerDiaMin; /** * @param args */ public static void main(String[] args) { // I assuming here the sizes of diameters, it can also be made to read // from files or as user input int[] solidDiskDia = { 2, 1, 4, 5, 6 }; int[] ringInnerDia = { 32, 4, 6, 8, 15, 8, 11, 3 }; ringInnerDiaMin = getMinValue(ringInnerDia); for (int i = 0; i < solidDiskDia.length; i++) System.out.println(solidDiskDia[i] + " --> " + diskGone(solidDiskDia[i])); } /** * @param diskDiameter * @return boolean */ public static boolean diskGone(int diskDiameter) { if (wellBlocked) return false; /** * If diameter is less than inner Diameter, it will go inside the well. * else it will get stuck */ if (diskDiameter < ringInnerDiaMin) return true; else { wellBlocked = true; return false; } } /** * getting the miniumum value * * @param array * @return int */ public static int getMinValue(int[] array) { int minValue = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < minValue) { minValue = array[i]; } } return minValue; } } <file_sep>/src/com/nano/hacker/algo/bitmanipulation/CounterGame_Java7Way.java package com.nano.hacker.algo.bitmanipulation; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Louise and Richard play a game. They have a counter set to N. Louise gets the * first turn and the turns alternate thereafter. In the game, they perform the * following operations. * * If N is not a power of 2, they reduce the counter by the largest power of 2 * less than N. If N is a power of 2, they reduce the counter by half of N. The * resultant value is the new N which is again used for subsequent operations. * The game ends when the counter reduces to 1, i.e., N == 1, and the last * person to make a valid move wins. * * Given N, your task is to find the winner of the game. * * Update If they set counter to 1, Richard wins, because its Louise' turn and * she cannot make a move. * * Input Format The first line contains an integer T, the number of testcases. T * lines follow. Each line contains N, the initial number set in the counter. * * Constraints * * 1 ≤ T ≤ 10 1 ≤ N ≤ 264 - 1 * * Note: Range of N is larger than long long int, consider using unsigned long * long int. * * Output Format * * For each test case, print the winner's name in a new line. So if Louise wins * the game, print "Louise". Otherwise, print "Richard". (Quotes are for * clarity) * * Sample Input * * 1 6 Sample Output * * Richard Explanation * * As 6 is not a power of 2, Louise reduces the largest power of 2 less than 6 * i.e., 4, and hence the counter reduces to 2. As 2 is a power of 2, Richard * reduces the counter by half of 2 i.e., 1. Hence the counter reduces to 1. As * we reach the terminating condition with N == 1, Richard wins the game. * * @author LXMRX * */ public class CounterGame_Java7Way { private static String LOUISE = "Louise"; private static String RICHARD = "Richard"; public static void main(String[] args) { /* * BigInteger n = new BigInteger("9"); * System.out.println(getHighestPowerOf2(n)); */ /* * System.out.println(n); System.out.println(n.bitCount()); * System.out.println(n.bitLength()); System.out.println("Flip Bit " + * n.flipBit(3)); */ Scanner scanner = new Scanner(System.in); int testCases = Integer.parseInt(scanner.nextLine()); List<String> counterStringList = new ArrayList<>(); for (int i = 0; i < testCases; i++) { counterStringList.add(scanner.nextLine()); } for (int i = 0; i < testCases; i++) { process(counterStringList.get(i)); } scanner.close(); } private static void process(String counterString) { BigInteger counterBigInteger = new BigInteger(counterString); int attemptCount = 0; if (counterBigInteger.equals(BigInteger.ONE)) { System.out.println(RICHARD); } while (counterBigInteger.compareTo(BigInteger.ONE) == 1) { if (isPowerOf2(counterBigInteger)) counterBigInteger = counterBigInteger.shiftRight(1); else counterBigInteger = counterBigInteger .subtract(getHighestPowerOf2(counterBigInteger)); attemptCount++; } if (attemptCount % 2 == 0) System.out.println(RICHARD); else System.out.println(LOUISE); } private static BigInteger getHighestPowerOf2(BigInteger bigInteger) { int bitLength = bigInteger.bitLength(); for (int index = 0; index < (bitLength - 1); index++) bigInteger = bigInteger.clearBit(index); return bigInteger; } private static boolean isPowerOf2(BigInteger bigInteger) { int bitLength = bigInteger.bitLength(); for (int index = 0; index < bitLength - 1; index++) { if (bigInteger.testBit(index)) return false; } return true; } } <file_sep>/src/com/nano/hacker/algo/string/TwoStrings.java package com.nano.hacker.algo.string; import java.util.Scanner; /** * Problem Statement * * You are given two strings, A and B. Find if there is a substring that appears * in both A and B. * * Input Format * * Several test cases will be given to you in a single file. The first line of * the input will contain a single integer T, the number of test cases. * * Then there will be T descriptions of the test cases. Each description * contains two lines. The first line contains the string A and the second line * contains the string B. * * Output Format * * For each test case, display YES (in a newline), if there is a common * substring. Otherwise, display NO. * * Constraints * * All the strings contain only lowercase Latin letters. 1<=T<=10 * 1<=|A|,|B|<=105 * * Sample Input * * 2 hello world hi world * * Sample Output * * YES NO * * Explanation * * For the 1st test case, the letter o is common between both strings, hence the * answer YES. For the 2nd test case, hi and world do not have a common * substring, hence the answer NO. * * @author LXMRX * */ public class TwoStrings { private static final String YES = "YES"; private static final String NO = "NO"; public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCases = Integer.parseInt(in.nextLine()); String input1[] = new String[testCases]; String input2[] = new String[testCases]; for (int i = 0; i < testCases; i++) { input1[i] = in.nextLine(); input2[i] = in.nextLine(); // displayResult(input1[i], input2[i]); displayResultOptimized(input1[i], input2[i]); } in.close(); /* * for (int i = 0; i < testCases; i++) { displayResult(input1[i], * input2[i]); } */ } private static void displayResultOptimized(String string1, String string2) { boolean[] containsChar = new boolean[26]; for (char c : string1.toCharArray()) { int value = (int) c - 97; containsChar[value] = true; } boolean containsCommonSubstring = false; for (char c : string2.toCharArray()) { int value = (int) c - 97; if (containsChar[value]) { containsCommonSubstring = true; break; } } if (containsCommonSubstring) System.out.println(YES); else System.out.println(NO); } // Below is the time-wise expensive solution. private static void displayResult(String string1, String string2) { // choosing smaller String for iterating through it. String smallerString = string1.length() <= string2.length() ? string1 : string2; String biggerString = string1 == smallerString ? string2 : string1; boolean constains = false; // Concept - Even if single letter is common, substring exists. // So checking just one string. for (int i = 0; i < smallerString.length(); i++) { if (biggerString.contains(String.valueOf(smallerString.charAt(i)))) { constains = true; break; } } if (constains) System.out.println(YES); else System.out.println(NO); } } <file_sep>/src/com/nano/inter/WihoutDivisionFillArray.java package com.nano.inter; /** * @author Amit */ public class WihoutDivisionFillArray { /** * @param args */ public static void main(String[] args) { int[] input = { 2, 3, 5, 10 }; int[] leftArray = new int[input.length]; int leftmostValue = 1; // Building left array for (int i = 0; i < input.length; i++) { if (i == 0) leftArray[i] = leftmostValue; else { leftmostValue = leftmostValue * input[i - 1]; leftArray[i] = leftmostValue; } } int[] rightArray = new int[input.length]; int rightMostValue = 1; // Building right array for (int i = input.length - 1; i >= 0; i--) { if (i == input.length - 1) rightArray[i] = rightMostValue; else { rightMostValue = rightMostValue * input[i + 1]; rightArray[i] = rightMostValue; } } // Building output array int[] output = new int[input.length]; for (int i = 0; i < input.length; i++) { output[i] = leftArray[i] * rightArray[i]; System.out.println(output[i]); } } } <file_sep>/networking/com/nano/networking/ConnectURL.java package com.nano.networking; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Authenticator; import java.net.MalformedURLException; import java.net.PasswordAuthentication; import java.net.URL; import java.net.URLConnection; import javax.net.ssl.HttpsURLConnection; /** * @author LXMRX */ public class ConnectURL { private static final String Username = "AOL\\45000.sap"; private static final String Password = "<PASSWORD>#"; /** * @param args */ public static void main(String[] args) { String urlLink = "https://profitweb.afasonline.nl"; // String urlLink = "http://www.google.com"; URL url = null; try { url = new URL(urlLink); } catch (MalformedURLException e) { System.out.println("MalformedURLException............"); e.printStackTrace(); return; } catch (Exception ex) { System.out.println("Exception........."); ex.printStackTrace(); return; } NtlmAuthenticator authenticator = new NtlmAuthenticator(Username, Password); Authenticator.setDefault(authenticator); System.out.println("url.getAuthority() - " + url.getAuthority()); System.out.println("url.getPort() - " + url.getPort()); System.out.println("url.getDefaultPort() - " + url.getDefaultPort()); System.out.println("url.getFile() - " + url.getFile()); System.out.println("url.getHost() - " + url.getHost()); System.out.println("url.getPath() - " + url.getPath()); System.out.println("url.getProtocol() - " + url.getProtocol()); System.out.println("url.getQuery() - " + url.getQuery()); System.out.println("url.getRef() - " + url.getRef()); System.out.println("url.getUserInfo() - " + url.getUserInfo()); System.out.println("url.toExternalForm() - " + url.toExternalForm()); try { System.out.println("url.getContent() - " + url.getContent()); } catch (IOException e) { e.printStackTrace(); } catch (Exception ex) { System.out.println("Exception in printing getContent()........."); ex.printStackTrace(); } URLConnection urlConnection = null; try { urlConnection = url.openConnection(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine = null; while ((inputLine = bufferedReader.readLine()) != null) System.out.println(inputLine); HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection; System.out.println(httpsURLConnection.getResponseCode()); } catch (IOException e1) { e1.printStackTrace(); } } } class NtlmAuthenticator extends Authenticator { private final String username; private final char[] password; public NtlmAuthenticator(final String username, final String password) { super(); this.username = new String(username); this.password = <PASSWORD>.<PASSWORD>(); } @Override public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication(username, password)); } } <file_sep>/src/com/manthano/test/MohitTestCode.java package com.manthano.test; public class MohitTestCode { /** * @param args */ public static void main(String[] args) { char ch = '我'; StringBuffer result = new StringBuffer(); if ((ch >= 0x20) && (ch < 0x80)) { result.append(ch); } else { if (ch <= 0x1F) { if ((ch == 0xA) || (ch == 0xD)) result.append("&#" + (int) ch + ";"); else { ch += 0xE000; result.append("&#" + (int) ch + ";"); } } else { result.append(ch); } } System.out.println("1---> " + result); char ch2 = '我'; StringBuffer result2 = new StringBuffer(); if ((ch2 >= 0x20) && (ch2 < 0x80)) { result2.append(ch2); } else if ((ch2 == 0xA) || (ch2 == 0xD)) { // for new line and carriage return character result2.append("&#" + (int) ch2 + ";"); } else { if (ch2 <= 0x1F) ch2 += 0xE000; result2.append("&#" + (int) ch2 + ";"); } System.out.println("2---> " + result2); } } <file_sep>/src/com/nano/leet/DiagonalTraverseII.java package com.nano.leet; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; public class DiagonalTraverseII { public static void main(String[] args) throws IOException { File f = new File("DiagonalTraverseTestcase.txt"); StringBuilder sb = new StringBuilder(); //byte[] b = Files.readAllBytes(f.toPath()); BufferedReader br = new BufferedReader(new FileReader(f)); String line = null; while((line=br.readLine())!=null) sb.append(line); sb= sb.deleteCharAt(0); //delete first '[' sb.deleteCharAt(sb.length()-1); //delete last ']' String[] a = sb.toString().split(","); } public int[] findDiagonalOrder(List<List<Integer>> nums) { List<Integer> result = new ArrayList<>(); int maxCols = 0; //top diagonal --> iterate from top row to last row for(int i=0;i<nums.size();i++) { int row=i; maxCols = Math.max(maxCols,nums.get(row).size()); int j=0; while(row>=0 && j<=i) { if(nums.get(row).size()>j) result.add(nums.get(row).get(j)); j++; row--; } } //bottom diagonal -> iterate over first COLUMN(NOT row) to last COLUMN(NOT row) for(int j=1;j<maxCols;j++) { int col=j; // while() for(int i=nums.size()-1;i>=0 && col<maxCols;i--) { if(nums.get(i).size()>col) result.add(nums.get(i).get(col)); col++; } } int[] a = new int[result.size()]; for(int i=0;i<result.size();i++) a[i]=result.get(i); return a; } } <file_sep>/src/com/nano/core/datastructure/RemoveAllOcuurenceOfElementArrayList.java package com.nano.core.datastructure; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class RemoveAllOcuurenceOfElementArrayList { public static void main(String[] args) { // Set<String> linkedHashSet = new LinkedHashSet<String>(); Map<String, String> linkedHashMap = new LinkedHashMap<String, String>( 16, 0.75f, true); linkedHashMap.put("a", "A"); linkedHashMap.put("b", "B"); linkedHashMap.put("c", "C"); linkedHashMap.put("d", "D"); // linkedHashMap printMap(linkedHashMap); System.out.println("**************************"); System.out.println(linkedHashMap.get("c")); printMap(linkedHashMap); System.out.println(linkedHashMap.get("a")); printMap(linkedHashMap); System.out.println("**************************"); List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("a"); list.add("a"); System.out.println(list.size()); /* * list.remove(0); printList(list); * * System.out.println(list.size()); */ Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { if ("a".equals(iterator.next())) iterator.remove(); } // After removing System.out.println("After removing"); printList(list); } private static void printList(List<String> list) { for (String s : list) System.out.println(s); } private static void printMap(Map<String, String> map) { for (Entry<String, String> entry : map.entrySet()) System.out.println("key - > " + entry.getKey() + " Value - > " + entry.getValue()); } } <file_sep>/src/com/nano/hacker/AngryChildren.java package com.nano.hacker; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; /** * @author LXMRX <NAME> is on one of his philanthropic journeys to a village * in Utopia. He has N packets of candies and would like to distribute * one packet to each of the K children in the village (each packet may * contain different number of candies). To avoid a fight between the * children, he would like to pick K out of N packets such that the * unfairness is minimized. Suppose the K packets have (x1, x2, x3,….xk) * candies in them, where xi denotes the number of candies in the ith * packet, then we define unfairness as max(x1,x2,…xk) - min(x1,x2,…xk) * where max denotes the highest value amongst the elements and min * denotes the least value amongst the elements. Can you figure out the * minimum unfairness and print it? Input Format The first line contains * an integer N. The second line contains an integer K. N lines follow * each integer containing the candy in the ith packet. Output Format A * single integer which will be the minimum unfairness. Constraints * 1<=N<=105 1<=K<=N 0<= number of candies in any packet <=109 Sample * Input #00 7 3 10 100 300 200 1000 20 30 Sample Output #00 20 * Explanation #00 Here K = 3. We can choose packets that contain * 10,20,30 candies. The unfairness is max(10,20,30) - min(10,20,30) = * 30 - 10 = 20 Sample Input #01 10 4 1 2 3 4 10 20 30 40 100 200 Sample * Output #01 3 Explanation #01 Here K = 4. We can choose the packets * that contain 1,2,3,4 candies. The unfairness is max(1,2,3,4) - * min(1,2,3,4) = 4 - 1 = 3 */ public class AngryChildren { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static StringBuilder out = new StringBuilder(); /** * @param args * @throws NumberFormatException * @throws IOException */ public static void main(String[] args) throws NumberFormatException, IOException { int numPackets = Integer.parseInt(in.readLine()); int numKids = Integer.parseInt(in.readLine()); int[] packets = new int[numPackets]; for (int i = 0; i < numPackets; i++) { packets[i] = Integer.parseInt(in.readLine()); } int unfairness = Integer.MAX_VALUE; // Write your code here, to process numPackets N, numKids K, and the // packets of candies // Compute the ideal value for unfairness over here Arrays.sort(packets); for (int i = 0; i < numPackets; i++) { if (i + numKids < numPackets) { int temp = packets[i + numKids - 1] - packets[i]; if (unfairness > temp) unfairness = temp; } } System.out.println(unfairness); } } <file_sep>/src/com/nano/inter/morgan/MohitCheckAnagramCount.java package com.nano.inter.morgan; import java.util.Arrays; public class MohitCheckAnagramCount { public static void main(String[] args) { /* * Given two strings find the Rotation Distance between them. For a pair * of strings which are rotations of each other, rotation distance is * the MINIMUM distance between the respective elements of both the * strings. If the strings are not rotations of each other, then return * -1. Sample Testcases: Testcase 1 Input: str1 = “ABACD” str2 = “CDABA” * Output: 2 Explanation: If we rotate each element of str1 to the RIGHT * by 2, we obtain str2. ABACD --> DABAC --> CDABA Testcase 2 Input: * str1 = “ABACD” str2 = “BACDA” Output: 1 Explanation: If we rotate * each element of str1 to the LEFT by 1, we obtain str2. ABACD --> * BACDA */ // String s1 = "ABACD"; // String s2 = "AABCD";// -1 // String s1 = "ABACD"; // String s2 = "ABACD";// 0 // String s1 = "ABACD"; // String s2 = "BACDA";// 1 String s1 = "ABACD"; String s2 = "CDABA";// 3 boolean flag = false; flag = checkAnagram(s1, s2); if (flag) { // System.out.println("Strings are anagrams of each others"); findCount(s1, s2); } else System.out.println("Strings are not relevant to each others"); } private static void findCount(String s1, String s2) { String s = s1 + s1; if (s.contains(s2)) { int count = s.indexOf(s2); if (count == 0 && !s1.equals(s2)) count++; System.out.print("#Rotations : " + count); } else System.out.print("#Rotations : -1"); } private static boolean checkAnagram(String s1, String s2) { if (s1.length() != s2.length()) return false; String c1 = arrangeLetters(s1); String c2 = arrangeLetters(s2); if (!c1.equalsIgnoreCase(c2)) return false; return true; } private static String arrangeLetters(String s) { String n = ""; char a[] = new char[s.length()]; a = s.toCharArray(); Arrays.sort(a); for (char l : a) { n = n + Character.toString(l); } return n; } } <file_sep>/src/com/manthano/test/MakeListFromArraySortListWillSortArrayAlso.java package com.manthano.test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class MakeListFromArraySortListWillSortArrayAlso { public static void main(String[] args) { // No sorting happens in case of 1-d array int[] arr = {2,3,1,2,88,5,6,4,7,8,5,3}; printArray(arr); List<Integer> l = toList(arr); Collections.sort(l,(a,b)->a-b); System.out.println(); printArray(arr); // now for 2-d array when Arrays.asList(a) is used int[][] arr2 = createArray(); print2DArray(arr2); //List<Integer> l = toList(arr2); Collections.sort(Arrays.asList(arr2),(a,b)->a[0]-b[0]); System.out.println(); print2DArray(arr2); } private static void printArray(int[] a) { for(int i : a) { System.out.print(i + ","); } } private static void print2DArray(int[][] a) { for(int[] ar : a) { for(int i : ar) System.out.print(i + ","); } } private static List<Integer> toList(int[] a) { List<Integer> l = new ArrayList<>(); for(int i : a) { l.add(i); } return l; } private static int[][] createArray(){ int[][] arr2 = new int[5][]; int[] e0 = new int[2]; e0[0]=100; e0[2]=200; arr2[0]=e0; int[] e1 = new int[2]; e1[0]=1; e1[2]=2; arr2[1]=e1; int[] e2 = new int[2]; e2[0]=1; e2[2]=5; arr2[2]=e2; int[] e3 = new int[2]; e3[0]=8; e3[2]=10; arr2[3]=e3; int[] e4 = new int[2]; e4[0]=3; e4[2]=4; arr2[4]=e4; int[] e5 = new int[2]; e5[0]=4; e5[2]=7; arr2[5]=e5; int[] e6 = new int[2]; e6[0]=4; e6[2]=7; arr2[6]=e6; return arr2; } } <file_sep>/src/com/nano/thread/ExecuteThreadSequentially.java package com.nano.thread; /** * @author LXMRX */ public class ExecuteThreadSequentially { /** * @param args */ public static void main(String[] args) { Thread one = new Thread(new SomeRunnable("one...")); one.start(); try { one.join(); } catch (InterruptedException e1) { e1.printStackTrace(); } Thread two = new Thread(new SomeRunnable("Two......")); two.start(); try { two.join(); } catch (InterruptedException e) { e.printStackTrace(); } Thread three = new Thread(new SomeRunnable("Three....")); three.start(); /* * try * { * one.wait(); * } * catch (InterruptedException e) * { * System.out.println("One Exceptionnnnnnnnnnnnn"); * e.printStackTrace(); * } * SomeRunnable two = new SomeRunnable("Two...."); * new Thread(two).start(); * try * { * two.wait(); * } * catch (InterruptedException e) * { * System.out.println("Two Exceptionnnnnnnnnnnnn"); * e.printStackTrace(); * } * SomeRunnable three = new SomeRunnable("Three...."); * new Thread(three).start(); */ } } class TheThread implements Runnable { private String str = "default"; public TheThread(String str) { this.str = str; } public void run() { for (int i = 0; i < 20; i++) System.out.println(i + " " + str); } }<file_sep>/src/com/nano/inter/adobe/BracketMatching.java package com.nano.inter.adobe; import java.util.Scanner; import java.util.Stack; /** * @author NanoUser You are given a function areBracketMatching which takes a * string s (an arithmetic expression) as its parameter. Complete the * function to check if the arithmetic expression contains matching * braces, braces includes square brackets and paranthesis as well. * Return 1 if it exists else 0. */ public class BracketMatching { public static void main(String[] args) { String expr = "[(5+4)*{(5/7)-(5+(8/4))}]"; System.out.println(areBracketsMatched(expr)); } private static int areBracketsMatched(String expr) { Stack<Character> stack = new Stack<Character>(); char c; for (int i = 0; i < expr.length(); i++) { c = expr.charAt(i); if (isStartingBrace(c)) stack.push(c); else if (isEndingBrace(c)) { char topChar = stack.pop(); if (!areBracesMatching(c, topChar)) return 0; } } return 1; } private static boolean areBracesMatching(char c, char topChar) { if ((c == ')' && topChar == '(') || (c == ']' && topChar == '[') || (c == '}' && topChar == '{')) return true; return false; } private static boolean isEndingBrace(char c) { if (c == ')' || c == ']' || c == '}') return true; return false; } private static boolean isStartingBrace(char c) { if (c == '(' || c == '[' || c == '{') return true; return false; } /** * Below impl is copied from * http://www.sanfoundry.com/java-program-implement * -check-balanced-parenthesis-using-stacks/ */ public static void main1(String[] args) { Scanner scan = new Scanner(System.in); /* Creating Stack */ Stack<Integer> stk = new Stack<Integer>(); System.out.println("Parenthesis Matching Test\n"); /* Accepting expression */ System.out.println("Enter expression"); String exp = scan.next(); scan.close(); int len = exp.length(); System.out.println("\nMatches and Mismatches:\n"); for (int i = 0; i < len; i++) { char ch = exp.charAt(i); if (ch == '(') stk.push(i); else if (ch == ')') { try { int p = stk.pop() + 1; System.out.println("')' at index " + (i + 1) + " matched with ')' at index " + p); } catch (Exception e) { System.out.println("')' at index " + (i + 1) + " is unmatched"); } } } while (!stk.isEmpty()) System.out.println("'(' at index " + (stk.pop() + 1) + " is unmatched"); } } <file_sep>/src/com/nano/hacker/java/collections/Java1DArrayEasy.java package com.nano.hacker.java.collections; import java.util.Scanner; /** * Array is a very simple data structure which is used to store a collection of * data, for example roll number of all the students in a class or name of all * the countries in the world. To create an array of integer that can hold 10 * values, you can write code like this: * * int[] myList = new int[10]; This problem will test your knowledge on java * array. You are given an array of n integers. A sub-array is "Negative" if sum * of all the integers in that sub-array is negative. Count the number of * "Negative sub-arrays" in the input array. * * Note: Subarrays are contiguous chunks of the main array. For example if the * array is {1,2,3,5} then some of the subarrays are {1}, {1,2,3}, {2,3,5}, * {1,2,3,5} etc. But {1,2,5} is not an subarray as it is not contiguous. * * Input Format * * The first line consists an integer n. The next line will contain n space * separated integers. Value of n will be at most 100. The numbers in the array * will range between -10000 to 10000. * * Output Format * * Print the answer to the problem. * * Sample Input * * 5 1 -2 4 -5 1 Sample Output * * 9 * * Explanation * * These are the ranges of the 9 negative subarrays in this sample: * * [0:1] [0:3] [0:4] [1:1] [1:3] [1:4] [2:3] [3:3] [3:4] Assume that the index * is 0 based. * * @author LXMRX * */ public class Java1DArrayEasy { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] numArray = new int[n]; int negativeSubArrayCount = 0; boolean allPositive = true; for (int i = 0; i < n; i++) { numArray[i] = in.nextInt(); if (numArray[i] < 0) allPositive = false; } in.close(); if (allPositive) { System.out.println(0); return; } for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { int temp = numArray[j]; if (temp < 0 && i == j) // i==j is very imp { negativeSubArrayCount++; sum += temp; continue; } sum += temp; if (sum < 0) negativeSubArrayCount++; } } System.out.println(negativeSubArrayCount); } } <file_sep>/src/com/nano/exception/SysOutException.java package com.nano.exception; /** * @author LXMRX */ public class SysOutException { /** * @param args */ public static void main(String[] args) { try { wrapperMethod("str"); } catch (NumberFormatException e) { // TODO Auto-generated catch block System.out.println(e); e.printStackTrace(); } } private static void parseInt(String str) { Integer.parseInt("dd"); } private static void wrapperMethod(String str) { parseInt(str); } } <file_sep>/src/com/nano/hacker/MaximizingXOR.java package com.nano.hacker; import java.util.Scanner; /** * @author LXMRX */ public class MaximizingXOR { /** * Problem Statement * Given two integers: L and R, * find the maximal values of A xor B given, L ≤ A ≤ B ≤ R * Input Format * The input contains two lines, L is present in the first line. * R in the second line. * Constraints * 1 ≤ L ≤ R ≤ 103 * Output Format * The maximal value as mentioned in the problem statement. * Sample Input#00 * 1 * 10 * Sample Output#00 * 15 * Sample Input#01 * 10 * 15 * Sample Output#01 * 7 * Explanation * In the second sample let's say L=10, R=15, then all pairs which comply to * above condition are * 10⊕10=0 * 10⊕11=1 * 10⊕12=6 * 10⊕13=7 * 10⊕14=4 * 10⊕15=5 * 11⊕11=0 * 11⊕12=7 * 11⊕13=6 * 11⊕14=5 * 11⊕15=4 * 12⊕12=0 * 12⊕13=1 * 12⊕14=2 * 12⊕15=3 * 13⊕13=0 * 13⊕14=3 * 13⊕15=2 * 14⊕14=0 * 14⊕15=1 * 15⊕15=0 * Here two pairs (10,13) and (11,12) have maximum xor value 7 and this is * the answer. * * @param args */ public static void main(String[] args) { // System.out.println(convertToBase2(12)); // System.out.println(convertToBase10("1110")); Scanner in = new Scanner(System.in); int res; int _l; _l = Integer.parseInt(in.nextLine()); int _r; _r = Integer.parseInt(in.nextLine()); res = maxXor(_l, _r); System.out.println(res); in.close(); } static int maxXor(int l, int r) { int maxXORValue = 0; for (int i = l; i <= r; i++) { int tempXOR = 0; for (int j = i; j <= r; j++) { tempXOR = doXOR(i, j); if (tempXOR > maxXORValue) maxXORValue = tempXOR; } } return maxXORValue; } static int doXOR(int numberOne, int numberTwo) { String string1 = convertToBase2(numberOne); String string2 = convertToBase2(numberTwo); int diff = string2.length() - string1.length(); // As numberTwo will always be passed as greater number, so only first // number is padded and no validation is done w.r.t first number. if (diff > 0) for (int i = diff; i > 0; i--) string1 = "0" + string1; String XORValue = ""; for (int i = 0; i < string2.length(); i++) { if (string1.charAt(i) == string2.charAt(i)) XORValue += "0"; else XORValue += "1"; } return convertToBase10(XORValue); } private static int convertToBase10(String base2Number) { int exponent = 0; int decimalNumber = 0; for (int i = base2Number.length() - 1; i >= 0; i--) { decimalNumber += Integer.parseInt(String.valueOf(base2Number.charAt(i))) * (Math.pow(2, exponent)); exponent++; } return decimalNumber; } static String convertToBase2(int decimalNumber) { String base2Equivalent = ""; if (decimalNumber < 0) return null; while (decimalNumber > 0) { base2Equivalent = String.valueOf((decimalNumber % 2)) + base2Equivalent; decimalNumber /= 2; if (decimalNumber == 0) { // base2Equivalent += "0"; break; } } return base2Equivalent; } } <file_sep>/src/com/nano/core/exception/InterfaceDeclareClassDoesnt.java package com.nano.core.exception; public class InterfaceDeclareClassDoesnt implements DeclaresMethodWithExceptions { public static void main(String[] args) { DeclaresMethodWithExceptions a = new InterfaceDeclareClassDoesnt(); // Accessing Method via Interface type requires Exception to be checked // at compile time // But if accessed via Class Type, No need to declare/catch any // Exception try { a.fun(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // if accessed via Class Type, No need to declare/catch any // Exception InterfaceDeclareClassDoesnt b = new InterfaceDeclareClassDoesnt(); b.fun(); } // no exception declared or caught @Override public void fun() { System.out .println("This method neither specifies nor catches Exception...."); } } interface DeclaresMethodWithExceptions { void fun() throws Exception; }<file_sep>/src/com/nano/inter/adobe/SumOfTwoNumbersInArray.java package com.nano.inter.adobe; import com.manthano.sort.MergeSort; public class SumOfTwoNumbersInArray { public static void main(String[] args) { int[] array = { 11, 18, 21, 28, 31, 38, 40, 55, 60, 62 }; MergeSort.mergeSort(array); // mergeSort.printArray(array); int sum = 66; System.out.println(isSumPossible(array, sum)); } private static int isSumPossible(int[] a, int sum) { int i = 0; int j = a.length - 1; while (i < j) { if (a[i] + a[j] == sum) return 1; else if (a[i] + a[j] < sum) i++; else j--; } return 0; } } <file_sep>/src/com/nano/pramp/BusiestTimeInTheMall.java package com.nano.pramp; public class BusiestTimeInTheMall { public static void main(String[] args) { int[][] data = new int[9][3]; int[] t1 = new int[]{1487799425, 14, 1}; int[] t2 = new int[]{1487799425, 4, 0}; int[] t3 = new int[]{1487799425, 2, 0}; int[] t4 = new int[]{1487800378, 10, 1}; int[] t5 = new int[]{1487801478, 18, 0}; int[] t6 = new int[]{1487801478, 18, 1}; int[] t7 = new int[]{1487901013, 1, 0}; int[] t8 = new int[]{1487901211, 7, 1}; int[] t9 = new int[]{1487901211, 7, 0}; data[0]=t1; data[1]=t2; data[2]=t3; data[3]=t4; data[4]=t5; data[5]=t6; data[6]=t7; data[7]=t8; data[8]=t9; System.out.println(findBusiestPeriod2(data)); } //will static int findBusiestPeriod(int[][] data) { // your code goes here int maxTimestamp = data[0][0];//time where count is max int maxCount = 0; int count=0; int l = data.length; int[] t; int prevTime = 0; for(int i=0;i<l;) { t=data[i]; prevTime = t[0]; int c = t[2]==0? -t[1] : t[1]; //int j=i+1; while(++i<l) { int[] t2 = data[i]; if(t2[0]==prevTime) { if(t2[2]==0) { c -=t2[1];//18 } else { c += t2[1]; } } else break; } count +=c; System.out.println(c + " : " + maxCount + " : " + t[0] ); if(count>maxCount) { maxCount=count;//18 maxTimestamp=prevTime; //t[0]; } } return maxTimestamp; } //Below is wrong as PER the question because it returns timestamp at which number of people is max // but ques is to find time at which MAX people ENTER Not total count but diff static int findBusiestPeriod2(int[][] data) { // your code goes here int maxTimestamp = data[0][0];//time where count is max int maxCount = 0; int count=0; int l = data.length; int[] t; int prevTime = 0; for(int i=0;i<l;i++) { t=data[i]; if(t[2]==0) { count -=t[1];//18 } else { count += t[1]; } System.out.println(count + " : " + maxCount + " : " + t[0] ); if(count>maxCount) { maxCount=count;//18 maxTimestamp=t[0]; System.out.println("Max updated : " + maxCount + " : " + t[0] ); } } return maxTimestamp; } } <file_sep>/src/com/nano/inter/paypay/CashRegister.java package com.nano.inter.paypay; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CashRegister { /** * Iterate through each line of input. */ /* 'PENNY': .01, 'NICKEL': .05, 'DIME': .10, 'QUARTER': .25, 'HALF DOLLAR': .50, 'ONE': 1.00, 'TWO': 2.00, 'FIVE': 5.00, 'TEN': 10.00, 'TWENTY': 20.00, 'FIFTY': 50.00, 'ONE HUNDRED': 100.00 */ private static final String ERROR = "ERROR"; private static final String ZERO = "ZERO"; private static final String PENNY = "PENNY"; private static final String NICKEL = "NICKEL"; private static final String DIME = "DIME"; private static final String QUARTER = "QUARTER"; private static final String HALF_DOLLAR = "HALF DOLLAR"; private static final String ONE = "ONE"; private static final String TWO = "TWO"; private static final String FIVE = "FIVE"; private static final String TEN = "TEN"; private static final String TWENTY = "TWENTY"; private static final String FIFTY = "FIFTY"; private static final String ONE_HUNDRED = "ONE HUNDRED"; //private static final BigDecimal ZERO_BD = new BigDecimal(0); private static final BigDecimal PENNY_BD = new BigDecimal(0); private static final BigDecimal NICKEL_BD = new BigDecimal(0.05); private static final BigDecimal DIME_BD = new BigDecimal(0.10); private static final BigDecimal QUARTER_BD = new BigDecimal(.25); private static final BigDecimal HALF_DOLLAR_BD = new BigDecimal(0.5); private static final BigDecimal ONE_BD = new BigDecimal(1); private static final BigDecimal TWO_BD = new BigDecimal(2); private static final BigDecimal FIVE_BD = new BigDecimal(5); private static final BigDecimal TEN_BD = new BigDecimal(10); private static final BigDecimal TWENTY_BD = new BigDecimal(20); private static final BigDecimal FIFTY_BD = new BigDecimal(50); private static final BigDecimal ONE_HUNDRED_BD = new BigDecimal(100); public static void main(String[] args) throws IOException { InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8); BufferedReader in = new BufferedReader(reader); String line; while ((line = in.readLine()) != null) { String[] a = line.split(";"); System.out.println(change(a[0],a[1])); } } static String change(String s1, String s2){ // /* * double v1 = Double.parseDouble(s1); double v2 = Double.parseDouble(s2); * double diff = v2-v1; */ BigDecimal b1 = new BigDecimal(s1); BigDecimal b2 = new BigDecimal(s2); BigDecimal diff = b2.subtract(b1); if(diff.doubleValue()<0){ return ERROR; } else if(diff.doubleValue()==0){ return ZERO; } List<String> list= change(diff); Collections.sort(list); /* StringBuilder sb = new StringBuilder(); for(String s : list){ sb.append(s) }*/ return String.join(",",list); } static List<String> change(BigDecimal v){ List<String> list = new ArrayList<>(); //System.out.println(v); //int i=0; while(v.doubleValue()>0){ // System.out.println(v + " : " + i++); if(v.compareTo(ONE_HUNDRED_BD)>=1){ list.add(ONE_HUNDRED); v = v.subtract(new BigDecimal(100));//-=100; } //else if(v.doubleValue()>=50){ else if(v.compareTo(FIFTY_BD)>=1){ list.add(FIFTY); v=v.subtract(new BigDecimal(50)); } //else if(v.doubleValue()>=20){ else if(v.compareTo(TWENTY_BD)>=1){ list.add(TWENTY); v=v.subtract(new BigDecimal(20)); } //else if(v.doubleValue()>=10){ else if(v.compareTo(TEN_BD)>=1){ list.add(TEN); v=v.subtract(new BigDecimal(10)); } //else if(v>=5){ else if(v.compareTo(FIVE_BD)>=1) { list.add(FIVE); v=v.subtract(new BigDecimal(5)); } //else if(v>=2){ else if(v.compareTo(TWO_BD)>=1) { list.add(TWO); v=v.subtract(new BigDecimal(2)); } //else if(v>=1){ else if(v.compareTo(ONE_BD)>=1) { list.add(ONE); v=v.subtract(new BigDecimal(1)); } //else if(v>=0.5){ else if(v.compareTo(HALF_DOLLAR_BD)>=1) { list.add(HALF_DOLLAR); v=v.subtract(new BigDecimal(0.5)); } //else if(v>=0.25){ else if(v.compareTo(QUARTER_BD)>=1) { list.add(QUARTER); v=v.subtract(new BigDecimal(0.25)); } //else if(v>=0.1){ else if(v.compareTo(DIME_BD)>=1) { list.add(DIME); v=v.subtract(new BigDecimal(0.1)); } //else if(v>=0.05){ else if(v.compareTo(NICKEL_BD)>=1) { list.add(NICKEL); v=v.subtract(new BigDecimal(0.05)); } //else if(v>=0.01){ else if(v.compareTo(PENNY_BD)>=1) { list.add(PENNY); v=v.subtract(new BigDecimal(0.01)); } } return list; } } <file_sep>/src/com/manthano/test/Test.java package com.manthano.test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.TreeMap; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TransferQueue; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.StampedLock; public class Test { String s; int[] arr = {2,1,3,4,5,1,1,1}; List<String> emptyList = Collections.EMPTY_LIST; // immutable empty List List<String> EmptyList = Collections.emptyList(); List<String> stringEmptyList = Collections.<String>emptyList(); Arrays.binarySearch(arr,2); StringBuilder sb ; // StringBuilder sb = "a"; compile-time error DelayQueue dq; Delayed d; Deque deque; TransferQueue<?> tq; PriorityQueue<?> pq; Integer i; ArrayList<String> al; LinkedList<String> ll; TreeMap tm; StampedLock sl; ReadWriteLock rwl; ReadLock rl; ReentrantLock reel; ReentrantReadWriteLock rrwl; Thread t; ExecutorService es; ThreadPoolExecutor tpe; /*public int eraseOverlapIntervals(int[][] intervals) { int len = intervals.length; int result = 0; if(len==0) return result; Arrays.sort(intervals, new Comparator<int[]>(){ @Override public int compare(int[] arr1, int[] arr2){ return (new Integer(arr1[0]).compareTo(new Integer(arr2[0]))); } }); int end = intervals[0][1]; for(int i=1;i<len;i++){ if(end>intervals[i][0]) { end = Math.min(end, intervals[i][1]); result++; } else { end=intervals[i][1]; } } return result; } }*/ } <file_sep>/src/com/nano/hacker/algo/combinatorics/Handshake.java package com.nano.hacker.algo.combinatorics; import java.util.Scanner; /** * @author LXMRX Problem Statement * * At the annual meeting of Board of Directors of Acme Inc, every one * starts shaking hands with everyone else in the room. Given the fact * that any two persons shake hand exactly once, Can you tell the total * count of handshakes? * * Input Format The first line contains the number of test cases T, T * lines follow. Each line then contains an integer N, the total number * of Board of Directors of Acme. * * Output Format * * Print the number of handshakes for each test-case in a new line. * * Constraints * * 1 <= T <= 1000 0 < N < 106 * * Sample Input * * 2 1 2 Sample Output * * 0 1 Explanation * * Case 1 : The lonely board member shakes no hands, hence 0. Case 2 : * There are 2 board members, 1 handshake takes place. * */ public class Handshake { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int testCases = Integer.parseInt(scanner.nextLine()); StringBuilder output = new StringBuilder(); int n = 0; for (int i = 0; i < testCases; i++) { n = scanner.nextInt(); output.append((n * (n - 1) / 2) + "\n"); } System.out.println(output); scanner.close(); } } <file_sep>/src/com/nano/hacker/algo/string/PalindromeIndex.java package com.nano.hacker.algo.string; import java.util.Scanner; public class PalindromeIndex { /** * Problem Statement * * Russian * * You are given a string of lowercase letters. Your task is to figure out * the index of the character on whose removal will make the string a * palindrome. There will always be a valid solution. * * In case string is already palindrome, then -1 is also a valid answer * along with possible indices. * * Input Format * * The first line contains T i.e. number of test cases. T lines follow, each * line containing a string. * * Output Format * * Print the position ( 0 index ) of the letter by removing which the string * turns into a palindrome. For string, such as * * bcbc we can remove b at index 0 or c at index 3. Both the answers are * accepted. * * Constraints 1 ≤ T ≤ 20 1 ≤ length of string ≤ 100005 All characters are * latin lower case indexed. * * Sample Input * * 3 aaab baa aaa Sample Output * * 3 0 -1 Explanation * * In the given input, T = 3, * * For input aaab, we can see that removing b from the string makes the * string a palindrome, hence the position 3. For input baa, removing b from * the string makes the string palindrome, hence the position 0. As the * string aaa is already a palindrome, you can output 0, 1 or 2 as removal * of any of the characters still maintains the palindrome property. Or you * can print -1 as this is already a palindrome. * * @param args */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int totalTestCases = Integer.parseInt(scanner.nextLine()); String testString = null; StringBuffer outputString = new StringBuffer(); int length = 0; for (int i = 0; i < totalTestCases; i++) { testString = scanner.nextLine(); length = testString.length(); if (isPalindrome(testString) || testString.length() == 1) { outputString.append("-1"); } else { for (int j = 0; j < length / 2; j++) { if (testString.charAt(j) != testString.charAt(length - 1 - j)) { if (testString.charAt(j + 1) == testString .charAt(length - 1 - j) && isPalindrome(testString.substring(0, j) + testString.substring(j + 1))) outputString.append(j); else // if (isPalindrome(testString.substring(0, // testString.charAt(length - 1 - j)) // + testString.substring(length - j))) outputString.append(length - 1 - j); break; } } } outputString.append("\n"); } System.out.println(outputString); scanner.close(); } public static void main_My_Way(String[] args) { Scanner scanner = new Scanner(System.in); int totalTestCases = Integer.parseInt(scanner.nextLine()); String testString = null; StringBuffer outputString = new StringBuffer(); for (int i = 0; i < totalTestCases; i++) { testString = scanner.nextLine(); // boolean is0thElementTrue = false; // One lettered word is always a palindrome so checked that // condition if (isPalindrome(testString) || testString.length() == 1) { outputString.append("-1"); } else { if (isPalindrome(testString.substring(1))) { outputString.append("0 "); continue; // is0thElementTrue = true; } // See here j - index starts from 1 as initial case is // already // handled in above if-condition // Also see the condition checks [j < testString.length() - // 1;] // because (testString.length() - 1) is checked separately // after // this for loop.; // boolean isLoopSuccessAtleastOnce = false; for (int j = 1; j < testString.length() - 1; j++) { if (isPalindrome(testString.substring(0, j) + testString.substring(j + 1, testString.length()))) { /* * isLoopSuccessAtleastOnce = true; if * (is0thElementTrue) { outputString.append(j); * is0thElementTrue = false; } else * outputString.append(" " + j); */ outputString.append(j); } } if (isPalindrome(testString.substring(0, testString.length() - 1))) { /* * if (isLoopSuccessAtleastOnce) outputString.append(" " + * (testString.length() - 1)); else */ outputString.append((testString.length() - 1)); } } outputString.append("\n"); } System.out.println(outputString.toString()); scanner.close(); } private static boolean isPalindrome(String str) { StringBuilder strBuilder = new StringBuilder(str); return str.equals(strBuilder.reverse().toString()); } private static boolean isPalindrome_MyWay_Slow(String str) { int n = str.length(); for (int i = 0; i < (n / 2) + 1; i++) { if (str.charAt(i) != str.charAt(n - i - 1)) { return false; } } return true; /* * boolean isPalindrome = true; int midPoint = ((str.length() % 2) == 0) * ? ((str.length()) / 2) : ((str .length() + 1) / 2); for (int i = 0; i * < midPoint; i++) { if (str.charAt(i) == str.charAt(str.length() - 1 - * i)) continue; else { isPalindrome = false; break; } } return * isPalindrome; */ } } <file_sep>/src/com/nano/core/math/BigDecimal_Precision_Issue.java package com.nano.core.math; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; /** * @author LXMRX */ public class BigDecimal_Precision_Issue { /** * http://araklefeistel.blogspot.sg/2011/06/javamathbigdecimal-difference- * between.html * So calling round with a MathContext of 2 doesn't alway round to a * precision of 2 digits overall. It depends on the number you're trying to * round. Reading the JDK docs you will find * ".... In general the rounding modes and precision setting determine how * operations * return results with a limited number of digits when the exact result has * more digits (perhaps infinitely many in the case of division) than the * number of * digits returned. First, the total number of digits to return is specified * by the MathContext's * precision setting; this determines the result's precision. The digit * count starts from the leftmost nonzero digit of the exact result. * The rounding mode determines how any discarded trailing digits affect the * returned result. ..." * Oops, that is something you have to keep in mind when using round within * BigDecimal. So if you really want to achieve a "real" rounding operation * on a BigDecimal you should use setScale. * * @param args */ public static void main(String[] args) { BigDecimal smallNumber = new BigDecimal("0.01234"); BigDecimal roundedNumber = smallNumber.round(new MathContext(2, RoundingMode.HALF_UP)); System.out.println(roundedNumber); // Result = 0.012 roundedNumber = smallNumber.setScale(2, RoundingMode.HALF_UP); System.out.println(roundedNumber); // Result = 0.01 BigDecimal number = new BigDecimal("1.01234"); roundedNumber = number.round(new MathContext(2, RoundingMode.HALF_UP)); System.out.println(roundedNumber); // Result = 1.0 roundedNumber = number.setScale(2, RoundingMode.HALF_UP); System.out.println(roundedNumber); // Result = 1.01 } } <file_sep>/src/com/nano/core/inheritanceTest/InheritSameNameVarButDiffType.java package com.nano.core.inheritanceTest; /** * The following variation uses the field access expression super.v to refer to * the field named v declared in class SuperTest and uses the qualified name * Frob.v to refer to the field named v declared in interface Frob * * @author LXMRX * */ public class InheritSameNameVarButDiffType extends SuperTest implements Frob { public static void main(String[] args) { new InheritSameNameVarButDiffType().printV(); } void printV() { System.out.println((super.v + Frob.v) / 2); } } interface Frob { float v = 2.0f; } class SuperTest { int v = 3; } <file_sep>/src/com/nano/core/interfaceTest/A.java package com.nano.core.interfaceTest; public interface A { int var = 10; void display(); void print(); interface C { void display(); } } <file_sep>/src/com/nano/design/ObserverPattern_Java_Supported.java package com.nano.design; import java.util.Observable; import java.util.Observer; /** * @author LXMRX */ public class ObserverPattern_Java_Supported { /** * @param args */ public static void main(String[] args) { // Declare Subjects Subject subject = new Subject(); // Declare Observers A_Observer aObserver = new A_Observer(); B_Observer bObserver = new B_Observer(); C_Observer cObserver = new C_Observer(); // register observers subject.addObserver(aObserver); subject.addObserver(bObserver); subject.addObserver(cObserver); subject.notify_The_Observers(); subject.notify_The_Observers(); } } class Subject extends Observable { public void notify_The_Observers() { setChanged(); notifyObservers(); } } class A_Observer implements Observer { @Override public void update(Observable o, Object arg) { System.out.println("A --- got the notification.........."); } } class B_Observer implements Observer { @Override public void update(Observable o, Object arg) { System.out.println("B --- got the notification.........."); } } class C_Observer implements Observer { @Override public void update(Observable o, Object arg) { System.out.println("C --- got the notification.........."); } } <file_sep>/src/com/nano/collection/list/LinkedListImpl.java package com.nano.collection.list; import java.util.LinkedList; import java.util.List; public class LinkedListImpl { /** * @param args */ public static void main(String[] args) { List<String> l = new LinkedList<String>(); // Collections } } <file_sep>/src/com/nano/collection/list/SetConcurrentModification.java package com.nano.collection.list; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class SetConcurrentModification { /** * @param args */ public static void main(String[] args) { // ConcurrentHashMap<K, V> Employee a = new Employee(1, "aaa"); Employee b = new Employee(2, "bbb"); Employee c = new Employee(3, "ccc"); Set<Employee> employeeSet = new HashSet<Employee>(); employeeSet.add(a); employeeSet.add(b); employeeSet.add(c); if (employeeSet.contains(new Employee(1, "aaa"))) System.out.println("Yes its there......."); else System.out.println("See U SHOULD override hasCode() METHOD as well When u override EQUALS..........."); Iterator<Employee> itr = employeeSet.iterator(); Employee aEmp = null; int count = 0; while (itr.hasNext()) { System.out.println(++count); aEmp = itr.next(); if (aEmp.getEmpId() == 2) aEmp.setEmpId(99); } System.out.println("\n\nSecond Iteration.....\n"); itr = employeeSet.iterator(); while (itr.hasNext()) { // System.out.println(++count); aEmp = itr.next(); employeeSet.add(new Employee(7, "should give error")); System.out.println(aEmp.getEmpId()); } System.out.println(b.getEmpId()); } } class Employee { private int empId = 0; private String name = null; public Employee(int empId, String name) { this.empId = empId; this.name = name; } public boolean equals(Object obj) { if (!(obj instanceof Employee)) return false; Employee emp = (Employee) obj; return (this.empId == emp.empId && this.name.equals(emp.name) ? true : false); } public int hashCode() { int result = 31; result += 17 * empId; result += 17 * name.hashCode(); return result; } /** * @return the empId */ public int getEmpId() { return empId; } /** * @param empId * the empId to set */ public void setEmpId(int empId) { this.empId = empId; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } } <file_sep>/src/com/nano/hacker/ChocolateFeastOthers.java package com.nano.hacker; import java.util.Scanner; public class ChocolateFeastOthers { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { System.out.println(f(in.nextInt(), in.nextInt(), in.nextInt())); } } private static long f(int n, int a, int b) { return n / a + g(n / a, b); } private static long g(int a, int b) { if (a < b) return 0; else return a / b + g(a - a / b * b + a / b, b); } } <file_sep>/src/com/nano/inter/goldmansachs/coding/PermuteString.java package com.nano.inter.goldmansachs.coding; import java.util.ArrayList; import java.util.List; /** * http://www.ericleschinski.com/c/java_permutations_recursion/ * http://stackoverflow * .com/questions/4240080/generating-all-permutations-of-a-given-string * * @author LXMRX * */ public class PermuteString { static List<String> list = new ArrayList<String>(); public static void main(String[] args) { permutation("", "ABCD"); for (int i = 0; i < list.size(); i++) System.out.println((i + 1) + " -> " + list.get(i)); } private static void permutation(String prefix, String str) { int n = str.length(); if (n == 0) list.add(prefix);// System.out.println(prefix); else { for (int i = 0; i < n; i++) { System.out.println(i + " **************************prefix " + " -> " + prefix); System.out.println("prefix + str.charAt(i)" + " -> " + prefix + str.charAt(i)); System.out.println("str.substring(0, i) -> " + str.substring(0, i)); System.out.println(" str.substring(i + 1) ->" + str.substring(i + 1)); System.out .println("str.substring(0, i) + str.substring(i + 1) -> " + str.substring(0, i) + str.substring(i + 1)); permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1)); } } } } <file_sep>/src/com/nano/thread/ExecuteThreadSequentially2.java package com.nano.thread; /** * @author AMIT */ public class ExecuteThreadSequentially2 { public static void main(String[] args) { Thread one = new Thread(new SomeRunnable("one...")); one.start(); Object lockObj = new Object(); try { synchronized (lockObj) { one.wait(); } } catch (InterruptedException e) { System.out.println("One Exceptionnnnnnnnnnnnn"); e.printStackTrace(); } SomeRunnable two = new SomeRunnable("Two...."); new Thread(two).start(); try { synchronized (lockObj) { two.wait(); } } catch (InterruptedException e) { System.out.println("Two Exceptionnnnnnnnnnnnn"); e.printStackTrace(); } SomeRunnable three = new SomeRunnable("Three...."); new Thread(three).start(); } } class SomeRunnable implements Runnable { private String str = "default"; public SomeRunnable(String str) { this.str = str; } public void run() { for (int i = 0; i < 20; i++) System.out.println(i + " " + str); } }<file_sep>/src/com/nano/hacker/algo/string/BiggerIsGreater.java package com.nano.hacker.algo.string; import java.util.Scanner; /** * Problem Statement * * Please note that this is a team event, and your submission will be accepted * only as a part of a team, even single member teams are allowed. Please click * here to register as a team, if you have NOT already registered. * * Given a word w, rearrange the letters of w to construct another word s in * such a way that, s is lexicographically greater than w. In case of multiple * possible answers, find the lexicographically smallest one. * * Input Format The first line of input contains t, number of test cases. Each * of the next t lines contains w. * * Constraints 1≤t≤105 1≤|w|≤100 w will contain only lower case english letters * and its' length will not exceed 100. * * Output Format For each testcase, output a string lexicographically bigger * than w in a separate line. In case of multiple possible answers, print the * lexicographically smallest one and if no answer exists, print no answer. * * Sample Input * * 3 ab bb hefg Sample Output * * ba no answer hegf Explanation * * Testcase 1 : There exists only one string greater than ab which can be built * by rearranging ab. That is ba. Testcase 2 : Not possible to re arrange bb and * get a lexicographically greater string. Testcase 3 : hegf is the next string * ( lexicographically greater ) to hefg. * * @author LXMRX * */ public class BiggerIsGreater { static String NOANSWER = "no answer"; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int totalTestCases = Integer.parseInt(scanner.nextLine()); StringBuilder output = new StringBuilder(); for (int i = 0; i < totalTestCases; i++) { output.append(process(scanner.nextLine()) + "\n"); } scanner.close(); System.out.println(output); } private static String process(String word) { String biggerWord = NOANSWER; // byte matches = 0; // char c= 0; // using byte instead of int as max length of word is given as 100 // i>0 has been used as for n things number of comparisons are (n-1) // only for (byte i = (byte) (word.length() - 1); i > 0; i--) { if (word.charAt(i) > word.charAt(i - 1)) { // c= word.charAt(i); if (i != word.length() - 1) biggerWord = word.substring(0, i - 1) + word.charAt(i) + word.charAt(i - 1) + word.substring(i + 1); else biggerWord = word.substring(0, i - 1) + word.charAt(i) + word.charAt(i - 1); break; } // matches var will take of the fact that are all characters in the // word same, if so the no answer is possible. // This is checked here so that we don't have to make a looping // again just to check if all char are same. /* * else if (word.charAt(i) == word.charAt(i - 1)) { matches++; } */ } /* * if (biggerWord == null) { if (matches == (word.length() - 1)) * biggerWord = NOANSWER; */ /* * else { for (byte i = (byte) (word.length() - 1); i > 0; i--) { if * (word.charAt(i) != 'z') { if (i != word.length() - 1) biggerWord = * word.substring(0, i) + String.valueOf(word.charAt(i) + 1) + * word.substring(i + 1); else biggerWord = word.substring(0, i) + * String.valueOf(word.charAt(i) + 1); } } if (biggerWord == null) * biggerWord = NOANSWER; } */ // } return biggerWord; } } <file_sep>/src/com/nano/core/enumTest/GetEnumAsString.java package com.nano.core.enumTest; public class GetEnumAsString { private enum MODE { MODE1, MODE2 }; /** * @param args */ public static void main(String[] args) { for (MODE mode : MODE.values()) System.out.println(mode.name()); // Here mode.toString() works // equally well And toString() // is PREFERRED AS WELL. } } <file_sep>/src/com/nano/hacker/algo/combinatorics/MinimumDraws.java package com.nano.hacker.algo.combinatorics; import java.util.Scanner; /** * Problem Statement * * Jim is off to a party and is searching for a matching pair of socks. His * drawer is filled with socks, each pair of a different color. In its worst * case scenario, how many socks (x) should Jim remove from his drawer after * which he finds a matching pair? * * Input Format The first line contains the number of test cases T. Next T lines * contains an integer N which indicates the total pairs of socks present in the * drawer. * * Output Format Print the number of Draws (x) Jim makes in the worst case * scenario. * * Constraints 1 <= T <= 1000 0 < N < 106 * * Sample Input * * 2 1 2 Sample Output * * 2 3 Explanation Case 1 : A pair of socks are present, hence exactly 2 draws * for the socks to match. Case 2 : 2 pair of socks are present in the drawer. * The first and the second draw might result in 2 socks of different color. The * 3rd socks picked will definitely match one of previously picked socks. Hence, * 3. * * @author LXMRX * */ public class MinimumDraws { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int testCases = Integer.parseInt(scanner.nextLine()); StringBuilder output = new StringBuilder(); for (int i = 0; i < testCases; i++) { output.append((scanner.nextInt() + 1) + "\n"); } System.out.println(output); scanner.close(); } } <file_sep>/src/com/manthano/javababa/CreateObjectsTest.java package com.manthano.javababa; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class CreateObjectsTest implements Cloneable { public static void main(String[] args) { // Using new operator CreateObjectsTest t1 = new CreateObjectsTest(); try { CreateObjectsTest t2 = CreateObjectsTest.class.newInstance(); } catch (InstantiationException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { CreateObjectsTest t3 = (CreateObjectsTest) Class .forName("com.manthano.test.Test").newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { CreateObjectsTest t4 = (CreateObjectsTest) t1.clone(); } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { ObjectInputStream in = new ObjectInputStream( new FileInputStream("data.obj")); CreateObjectsTest t5 = (CreateObjectsTest) in.readObject(); } catch (ClassNotFoundException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/src/com/nano/inter/MaxNummerAusNummers.java package com.nano.inter; public class MaxNummerAusNummers { public static void main(String[] args) { // String[] nos = { "45", "60", "540", "87", "11" };// 87605404511 // String[] nos = { "54", "546", "548", "60" };// 6054854654 // String[] nos = { "7", "776", "7", "7" };// 777776 String[] nos = { "1", "34", "3", "98", "9", "76", "45", "4" }; // 998764543431 String abc = getVisuallyMaxNummer(nos); } private static String getVisuallyMaxNummer(String[] nos) { String nums[] = new String[nos.length]; int i = 0; for (String num : nos) { nums[i] = Character.toString(num.charAt(0)); i++; } sortDec(nums, nos); makeNos(nums, nos); return null; } private static void makeNos(String[] nums, String[] nos) { String finalNos = ""; for (int i = 0; i < nums.length - 1; i++) { if (!nums[i].equals(nums[i + 1])) { finalNos = finalNos + nos[i]; } else { String num1, num2; num1 = nos[i] + nos[i + 1]; num2 = nos[i + 1] + nos[i]; if (Integer.parseInt(num1) > Integer.parseInt(num2)) { finalNos = finalNos + nos[i]; } else { finalNos = finalNos + nos[i + 1]; nos[i + 1] = nos[i]; } } } finalNos = finalNos + nos[nums.length - 1]; System.out.println(finalNos); } private static void sortDec(String[] nums, String[] nos) { for (int i = 0; i < nums.length - 1; i++) { for (int j = 0; j < nums.length - i - 1; j++) { int num1 = Integer.parseInt(nums[j]); int num2 = Integer.parseInt(nums[j + 1]); if (num1 < num2) { String swap1 = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = swap1; String swap2 = nos[j]; nos[j] = nos[j + 1]; nos[j + 1] = swap2; } } } } } <file_sep>/src/com/nano/core/math/PrintChangeAmount.java package com.nano.core.math; import java.math.BigDecimal; /** * @author LXMRX */ public class PrintChangeAmount { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("--- Normal Print-----"); double minuend = 2.0; // double double subtrahend = 1.1; System.out.println("with defined doubles " + (minuend - subtrahend)); System.out.println(minuend); System.out.println(2.00 - 1.1); System.out.println(2.00 - 1.2); System.out.println(2.00 - 1.3); System.out.println(2.00 - 1.4); System.out.println(2.00 - 1.5); System.out.println(2.00 - 1.6); System.out.println(2.00 - 1.7); System.out.println(2.00 - 1.8); System.out.println(2.00 - 1.9); System.out.println(2.00 - 2); System.out.println("--- BigDecimal-----"); System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.1"))); System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.2"))); System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.3"))); System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.4"))); System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.5"))); System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.6"))); System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.7"))); System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.8"))); System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.9"))); System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("2"))); } } <file_sep>/src/com/nano/algo/BinarySearchTree.java package com.nano.algo; import java.util.Arrays; public class BinarySearchTree { public static void main(String[] args) { int[] a = { 1, 3, 2, 5, 4 }; // printArray(a); Arrays.sort(a); // printArray(a); TreeNode root = sortedArrayToBST(a, 0, a.length - 1); printBST(root); } private static void printBST(TreeNode root) { /* * while (root != null) { System.out.println("Left of " + * root.getValue() + " is " + printBST(root.getLeft())); * System.out.println("Right of " + root.getValue() + " is " + * printBST(root.getRight())); } */ if (root.getLeft() != null) { System.out.println("Left of " + root.getValue() + " is " + root.getLeft().getValue()); printBST(root.getLeft()); } if (root.getRight() != null) { System.out.println("Right of " + root.getValue() + " is " + root.getRight().getValue()); printBST(root.getRight()); } /* * while (root.getLeft() != null) { System.out.println("Left of " + * root.getValue() + " is " + root.getLeft().getValue()); root = * root.getLeft(); } * * while (root.getRight() != null) { System.out.println("Right of " + * root.getValue() + " is " + root.getRight().getValue()); root = * root.getRight(); } */ } private static void printArray(int[] a) { for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } private static TreeNode sortedArrayToBST(int[] a, int start, int end) { TreeNode root = null; if (start > end) return null; int midIndex = (start + end) / 2; root = new TreeNode(a[midIndex]); root.setLeft(sortedArrayToBST(a, start, midIndex - 1)); root.setRight(sortedArrayToBST(a, midIndex + 1, end)); return root; } } class TreeNode { int value; private TreeNode left; private TreeNode right; public TreeNode(int value) { this.value = value; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public TreeNode getLeft() { return left; } public void setLeft(TreeNode left) { this.left = left; } public TreeNode getRight() { return right; } public void setRight(TreeNode right) { this.right = right; } }<file_sep>/src/com/nano/hacker/algo/geometry/FindPoint.java package com.nano.hacker.algo.geometry; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * @author LXMRX */ public class FindPoint { /** * Problem statement * Given two points P and Q, output the symmetric point of point P about Q. * Input format: * The first line contains an integer T representing the number of testcases * (T <= 15) * Each test case contains Px Py Qx Qy representing the (x,y) coordinates of * P and Q, all of them being integers. * Constraints * 1 <= T <= 15 * -100 <= x, y <= 100 * Output format * For each test case output x and y coordinates of the symmetric point * Sample input * 1 * 0 0 1 1 * Sample output * 2 2 * * @param args */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int totalTestCases = Integer.parseInt(scanner.nextLine()); String line = null; List<String> inputLines = new ArrayList<>(); for (int i = 0; i < totalTestCases; i++) { line = scanner.nextLine(); inputLines.add(line); } for (int i = 0; i < totalTestCases; i++) { line = inputLines.get(i); String[] points = line.split(" "); if (points.length == 4) { findPoint(Integer.parseInt(points[0]), Integer.parseInt(points[1]), Integer.parseInt(points[2]), Integer.parseInt(points[3])); } } scanner.close(); } static void findPoint(int px, int py, int qx, int qy) { System.out.println(qx + (qx - px) + " " + (qy + (qy - py))); } } <file_sep>/src/com/nano/pramp/SortKMessedArray.java package com.nano.pramp; import java.util.PriorityQueue; /** * * K-Messed Array Sort Given an array of integers arr where each element is at most k places away from its sorted position, code an efficient function sortKMessedArray that sorts arr. For instance, for an input array of size 10 and k = 2, an element belonging to index 6 in the sorted array will be located at either index 4, 5, 6, 7 or 8 in the input array. Analyze the time and space complexities of your solution. Example: input: arr = [1, 4, 5, 2, 3, 7, 8, 6, 10, 9], k = 2 output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Constraints: [time limit] 5000ms [input] array.integer arr 1 ≤ arr.length ≤ 100 [input] integer k 0 ≤ k ≤ 20 [output] array.integer * @author NanoUser * */ public class SortKMessedArray { public static void main(String[] args) { int[] arr = {1, 4, 5, 2, 3, 7, 8, 6, 10, 9}; int k = 2; int[] sortedArray = sortKMessedArray(arr, k); for(int a : sortedArray) { System.out.print(a+","); } System.out.println(); } static int[] sortKMessedArray(int[] arr, int k) { // your code goes here if(k==0) return arr; PriorityQueue<Integer> pq = new PriorityQueue<>(); for(int i=0;i<arr.length;i++) { pq.offer(arr[i]); if(i>=k) { arr[i-k]=pq.poll(); } } while(k>0) { arr[arr.length-k]=pq.poll(); k--; } return arr; } } <file_sep>/src/com/nano/hacker/Pair.java package com.nano.hacker; import java.util.Scanner; public class Pair { static int pairs(int[] a, int k) { int count = 0; for (int index = 0; index < a.length; index++) { for (int innerIndex = 0; innerIndex < a.length; innerIndex++) { if (index == innerIndex) continue; if (a[index] - a[innerIndex] == k) count++; } } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int res; String n = in.nextLine(); String[] n_split = n.split(" "); int _a_size = Integer.parseInt(n_split[0]); int _k = Integer.parseInt(n_split[1]); int[] _a = new int[_a_size]; int _a_item; String next = in.nextLine(); String[] next_split = next.split(" "); for (int _a_i = 0; _a_i < _a_size; _a_i++) { _a_item = Integer.parseInt(next_split[_a_i]); _a[_a_i] = _a_item; } res = pairs(_a, _k); System.out.println(res); } } <file_sep>/src/com/nano/hacker/algo/string/CountPalindromes.java package com.nano.hacker.algo.string; import java.util.Scanner; public class CountPalindromes { /** * Problem Statement * * A string is made of only lowercase latin letters (a,b,c,d,.....,z). Can * you find the length of the lexicographically smallest string such that it * has exactly K sub-strings, each of which are palindromes? * * Input Format The first line of input contains single integer T - the * number of testcases. T lines follow, each containing the integer K. * * Output Format Output exactly T lines. Each line should contain single * integer - the length of the lexicographically smallest string. * * Constraints: 1 <= T <= 100 1 <= K <= 1012 * * Sample input * * 2 10 17 Sample Output * * 4 7 Explanation * * for K = 10, one of the smallest possible strings that satisfies the * property is aaaa. All 10 palindromes are * * a,a,a,a aa, aa, aa aaa, aaa aaaa Note * * Two sub-strings with different indices are both counted. * * @param args */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int totalTestCases = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < totalTestCases; i++) { } scanner.close(); } } <file_sep>/src/com/nano/inter/goldmansachs/OverrideEqualsNotHashcode.java package com.nano.inter.goldmansachs; import java.util.HashSet; import java.util.Set; /** * This contains 2 ques 1. size of array 2. method toArray() compiles * successfully or comiletime error or runtime excep or compiles and runs * without any excep * * @author LXMRX * */ public class OverrideEqualsNotHashcode { private String first, last; public OverrideEqualsNotHashcode(String first, String last) { this.first = first; this.last = last; } @Override public boolean equals(Object o) { OverrideEqualsNotHashcode a = (OverrideEqualsNotHashcode) o; return a.first.equals(first) && a.last.equals(last); } public static void main(String[] args) { Set table = new HashSet<>(); OverrideEqualsNotHashcode a = new OverrideEqualsNotHashcode("XXX", "YYY"); OverrideEqualsNotHashcode b = new OverrideEqualsNotHashcode("XXX", "YYY"); OverrideEqualsNotHashcode c = new OverrideEqualsNotHashcode("XXX", "YYY"); table.add(a); table.add(b); table.add(c); if (table.contains(new OverrideEqualsNotHashcode("XXX", "YYY"))) { table.remove(a); } System.out.println("size = " + table.size()); // / This method CALL results in Runtime Exception toArray(); } // / This method results in Runtime Exception. // But Compiles successfully public static void toArray() { Object[] objects = new Object[10]; String[] strings = (String[]) objects; // String sss = (String)objects; } public static void castObjectToString() { Object a = new Object(); String s = (String) a; String str = "ll"; OverrideEqualsNotHashcode d = (OverrideEqualsNotHashcode) a; // OverrideEqualsNotHashcode over = (OverrideEqualsNotHashcode) str; } } <file_sep>/src/com/nano/hacker/java/collections/JavaDeque.java package com.nano.hacker.java.collections; import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; import java.util.Scanner; /** * @author LXMRX In computer science, a double-ended queue (dequeue, often * abbreviated to deque, pronounced deck) is an abstract data type that * generalizes a queue, for which elements can be added to or removed * from either the front (head) or back (tail). * * Deque interfaces can be implemented using various types of * collections such as LinkedList or ArrayDeque classes. For example, * deque can be declared as: * * Deque deque = new LinkedList<>(); or Deque deque = new * ArrayDeque<>(); You can find more details about Deque here. * * In this problem, you are given N integers. You need to find the * maximum number of unique integers among all the possible contiguous * subarrays of size M. * * Note: Time limit is 3 second for this problem. * * Input Format * * The first line of input contains two integers N and M: representing * the total number of integers and the size of the subarray, * respectively. The next line contains N space separated integers. * * Constraints * * 1≤N≤100000 1≤M≤100000 M≤N The numbers in the array will range between * [0,10000000]. * * Output Format * * Print the maximum number of unique integers among all possible * contiguous subarrays of size M separated by a space. * * Sample Input * * 6 3 5 3 5 2 3 2 Sample Output * * 3 Explanation * * In the sample testcase, there are 5 subarrays of contiguous numbers. * * s1=⟨5,3,5⟩ - Has 2 unique numbers. * * s2=⟨3,5,2⟩ - Has 3 unique numbers. * * s3=⟨5,2,3⟩ - Has 3 unique numbers. * * s4=⟨2,3,2⟩ - Has 2 unique numbers. * * In these subarrays, there are 2,3,3,2 unique numbers, respectively. * The maximum amount of unique numbers among all possible contiguous * subarrays is 3. * */ public class JavaDeque { public static void main(String[] args) { Scanner in = new Scanner(System.in); Deque<Integer> deque = new ArrayDeque<>(); int n = in.nextInt(); int m = in.nextInt(); int maxUnique = 0; for (int i = 0; i < n; i++) { int num = in.nextInt(); deque.addLast(Integer.valueOf(num)); } Iterator<Integer> iterator = deque.iterator(); while (iterator.hasNext()) { } in.close(); } }
6c2e4c8e280d42c6d8535a9eb3c3e1f75a3dbf96
[ "Java" ]
89
Java
devilsuse/contests
baabfbf1eff9ded30ec6364849c75bc4d76c4395
3dbaf27f15bfe3a93a6614d5b100359bc50a6764
refs/heads/master
<repo_name>brandonhostetter/Connect-Four<file_sep>/Helpers.js var Helpers = {}; Helpers.$myTurnLabel = $('#my-turn-label'); Helpers.$waitingForTurnLabel = $('#waiting-for-turn-label'); Helpers.$loadingOverlay = $('#loading-overlay'); Helpers.create2DArray = function(row, col) { var arr = []; for (var i = 0; i < row; i++) { arr.push([]); for (var j = 0; j < col; j++) { arr[i].push({ player: -1 }); } } return arr; }; Helpers.isLocationTaken = function(placementArray, row, column) { if (placementArray[row][column].player !== -1) { return true; } return false; }; Helpers.forcePieceToBottom = function(placementArray, column) { // drop the piece in the column the user clicked, // not necessarily the exact location that was clicked var validMove = null; var row = Page.rows - 1; while (!validMove) { if (Helpers.isLocationTaken(placementArray, row, column)) { row -= 1; if (row < 0) { break; } } else { validMove = [row, column]; } } return validMove; }; Helpers.updatePlacement = function(placementArray, placementOrder, drawPieceAt, playerTurn) { placementArray[drawPieceAt[0]][drawPieceAt[1]].player = playerTurn; placementOrder.push({ row: drawPieceAt[0], col: drawPieceAt[1] }); }; Helpers.updatePlayerTurn = function() { return (Page.playerTurn + 1) % 2; }; Helpers.generateGUID = function() { // http://stackoverflow.com/a/2117523 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }; Helpers.readUrlHash = function() { // get the uuid after the hash in the url var hash = window.location.hash; if (hash == null || hash == '') { return ''; } else { return hash.substring(1); } }; Helpers.copyToClipboard = function(element) { // take 'element' and copy it's text to the clipboard // 'element' should be an input element if (element.tagName !== "INPUT") return; element.focus(); element.setSelectionRange(0, element.value.length); // copy the selection var succeed; try { succeed = document.execCommand('copy'); } catch (e) { succeed = false; } return succeed; }; Helpers.updateTurnLabels = function(turn, playerNumber) { if (turn === playerNumber) { Helpers.$waitingForTurnLabel.hide(); Helpers.$myTurnLabel.show(); } else { Helpers.$myTurnLabel.hide(); Helpers.$waitingForTurnLabel.show(); } }; Helpers.showLoadingOverlay = function() { Helpers.$loadingOverlay.addClass('overlay-visible'); }; Helpers.hideLoadingOverlay = function() { Helpers.$loadingOverlay.removeClass('overlay-visible'); }; <file_sep>/Connect-Four.js var Page = {}; // canvas variables Page.$canvas = null; Page.context = null; Page.$maskCanvas = null; Page.maskContext = null; Page.stopRendering = false; Page.isAnimating = false; Page.canvasWidth = 545; Page.canvasHeight = 470; Page.rows = 6; Page.columns = 7; // dom selectors Page.$initModal = null; Page.$connectPlayersModal = null; Page.$gameOverModal = null; Page.$replayDeclined = null; // player / game related variables Page.playerTurn = null; Page.playerNumber = -1; Page.piececolors = ['gold', 'orangered']; Page.placementArray = null; Page.placementOrder = []; Page.y = 0; Page.dy = 20; Page.piecePlacedAt = []; Page.isGameOver = false; Page.gameUUID = ''; Page.gameStarted = false; Page.isLocalGame = false; Page.initialize = function() { // get dom references Page.$canvas = $('#connect-four-canvas'); Page.context = Page.$canvas[0].getContext('2d'); Page.$maskCanvas = $('#connect-four-mask-canvas'); Page.maskContext = Page.$maskCanvas[0].getContext('2d'); Page.$initModal = $('#init-modal'); Page.$connectPlayersModal = $('#connect-players-modal'); Page.$gameOverModal = $('#game-over-modal'); Page.$replayDeclined = $('#replay-declined-modal'); Page.placementArray = Helpers.create2DArray(Page.rows, Page.columns); Page.drawOpeningMask(); Page.determineOpeningAction(); }; //#region Initialization Page.determineOpeningAction = function() { Page.gameUUID = Helpers.readUrlHash(); if (Page.gameUUID != '') { // Join existing game // this is player 2 Page.playerNumber = 1; Page.joinExistingGame(); Page.isLocalGame = false; } else { // No existing game to join // Instead, ask the user if they would like to play on one computer or two // this is player 1 Page.playerNumber = 0; Page.displayInitModal(); } }; Page.displayInitModal = function() { Page.$initModal.modal('show'); // single player game vs computer Page.$initModal.find('#play-ai').on('click', function() { console.log('Playing single player vs computer'); Page.initSinglePlayer(); Page.$initModal.modal('hide'); }); // two player local game Page.$initModal.find('#play-local-multi').on('click', function() { console.log('Playing two player local game'); Page.initLocalMulti(); Page.$initModal.modal('hide'); }); // two player online game Page.$initModal.find('#play-online-multi').on('click', function() { console.log('Playing two player online game'); Helpers.showLoadingOverlay(); // display an overlay until player 2 joins Page.initOnlineMulti(); Page.createGameData(); Page.getGameData(); Page.$initModal.modal('hide'); }); }; Page.attachListeners = function() { Page.attachCanvasListener(); Page.attachButtonListeners(); }; Page.initSinglePlayer = function() { Page.attachListeners(); Page.playerTurn = 0; Page.isLocalGame = true; }; Page.initLocalMulti = function() { Page.attachListeners(); Page.playerTurn = 0; Page.isLocalGame = true; Page.gameStarted = true; }; Page.initOnlineMulti = function() { // Generate a unique id for the game Page.gameUUID = Helpers.generateGUID(); // Change the url to reflect the unique id window.location = '#' + Page.gameUUID; // Update the modal with the unique game url Page.$connectPlayersModal.find('#my-uuid').val(window.location.href); Page.$connectPlayersModal.modal('show'); Page.$connectPlayersModal.find('#copy-uuid-btn').on('click', function(e) { var target = Page.$connectPlayersModal.find('#my-uuid')[0]; Helpers.copyToClipboard(target); }); }; Page.joinExistingGame = function() { Page.getGameData(); Page.player2Ready(); }; //#region Event Listeners Page.attachCanvasListener = function() { Page.$maskCanvas.on('mouseup', function(e) { if (Page.isAnimating || (!Page.isLocalGame && (Page.playerTurn != Page.playerNumber))) { return; } //else var col = e.offsetX; col -= 50; col /= 75; col = Math.round(col); if (col < 0) col = 0; if (col >= Page.columns) col = Page.columns - 1; Page.piecePlacedAt = Helpers.forcePieceToBottom(Page.placementArray, col); if (Page.piecePlacedAt) { Page.draw(); } }); }; Page.attachButtonListeners = function() { $('#undo-button').on('click', function(e) { if (Page.isGameOver) return; var length = Page.placementOrder.length; if (length > 0) { var last = Page.placementOrder[length - 1]; Page.placementArray[last.row][last.col].player = -1; Helpers.updatePlayerTurn(); Page.drawUndo(); Page.placementOrder.pop(); } }); $('#restart-button').on('click', function(e) { if (!isLocalGame) { // get confirmation from other user that they would like to reset the game } else { Page.resetGame(); } }); }; //#endregion Event Listeners //#endregion Initialization //#region Canvas Drawing Page.draw = function() { Page.intervalId = window.requestAnimationFrame(Page.draw); Page.context.clearRect(0, 0, Page.canvasWidth, Page.canvasHeight); Page.drawPlacedPieces(); Page.drawDropAnimation(); }; Page.drawOpponentMove = function() { Page.intervalId = window.requestAnimationFrame(Page.drawOpponentMove); Page.context.clearRect(0, 0, Page.canvasWidth, Page.canvasHeight); Page.drawPlacedPieces(true); Page.drawOpponentAnimation(); }; Page.drawOpeningMask = function() { // http://stackoverflow.com/a/11770000 // We draw this once at initialization. This is the 'cut-out' of the holes // the pieces will fill; Page.maskContext.fillStyle = 'cornflowerBlue'; Page.maskContext.beginPath(); for (var i = 0; i < Page.rows; i++) { for (var j = 0; j < Page.columns; j++) { Page.maskContext.arc(75 * j + 50, 75 * i + 48, 30, 0, 2 * Math.PI); if (j === 0) { // offset a little more on the left most column so we aren't right on the edge Page.maskContext.rect(75 * j + 90, 96 * i, -80, 96); } else { Page.maskContext.rect(75 * j + 90, 96 * i, -75, 96); } } } Page.maskContext.closePath(); Page.maskContext.fill('evenodd'); }; Page.drawPiece = function(x, y, player) { Page.context.beginPath(); Page.context.arc(x, y, 30, 0, 2 * Math.PI); Page.context.fillStyle = Page.piececolors[player]; Page.context.fill(); Page.context.closePath(); }; Page.drawDropAnimation = function() { if (Page.stopRendering) { cancelAnimationFrame(Page.intervalId); Page.y = 0; Page.stopRendering = false; // update placement array Helpers.updatePlacement(Page.placementArray, Page.placementOrder, Page.piecePlacedAt, Page.playerTurn); // check for winner if (Page.isThereAWinner()) { Page.gameOver(); } // update database if (!Page.isLocalGame) { Page.saveGameData(); } Page.drawPlacedPieces(); Page.isAnimating = false; return; } else if (Page.y >= Page.piecePlacedAt[0] * 96 - 62) { Page.stopRendering = true; return; } Page.isAnimating = true; Page.y += Page.dy; Page.drawPiece(75 * Page.piecePlacedAt[1] + 50, Page.y, Page.playerTurn); }; Page.drawOpponentAnimation = function() { if (Page.stopRendering) { cancelAnimationFrame(Page.intervalId); Page.y = 0; Page.stopRendering = false; Page.drawPlacedPieces(); Page.isAnimating = false; return; } else if (Page.y >= Page.piecePlacedAt[0] * 96 - 62) { Page.stopRendering = true; return; } Page.isAnimating = true; Page.y += Page.dy; // we should be on the current player's turn so we need to change player turn back to the opponent Page.drawPiece(75 * Page.piecePlacedAt[1] + 50, Page.y, ((Page.playerTurn + 1) % 2)); }; Page.drawPlacedPieces = function(ignoreMostRecentlyPlaced) { for (var i = 0; i < Page.placementArray.length; i++) { for (var j = 0; j < Page.placementArray[i].length; j++) { if (Page.placementArray[i][j].player !== -1) { if (ignoreMostRecentlyPlaced && Page.piecePlacedAt[0] === i && Page.piecePlacedAt[1] === j) { continue; } Page.drawPiece(75 * j + 50, 75 * i + 48, Page.placementArray[i][j].player); } } } }; Page.drawUndo = function() { Page.context.clearRect(0, 0, Page.canvasWidth, Page.canvasHeight); Page.drawPlacedPieces(); }; //#endregion Canvas Drawing //#region Update game data Page.createGameData = function() { // create the empty placement array on the database database.ref('connect-four/' + Page.gameUUID).set({ 'placementArray': Page.placementArray, 'player1Ready': true, 'player2Ready': false, 'player1ReplayDenied': false, 'player2ReplayDenied': false, 'player1ReplayAccepted': false, 'player2ReplayAccepted': false }); database.ref('connect-four/' + Page.gameUUID + '/turn').set({ 'playerTurn': 0, 'gameOver': false, 'drawPieceAt': [-1, -1] }); }; Page.player1Ready = function() { database.ref('connect-four/' + Page.gameUUID).update({ 'player1Ready': true }); }; Page.player2Ready = function() { database.ref('connect-four/' + Page.gameUUID).update({ 'player2Ready': true }); }; Page.replayDenied = function() { if (Page.playerNumber === 0) { database.ref('connect-four/' + Page.gameUUID).update({ 'player1ReplayDenied': true, 'player1Ready': false }); } else { database.ref('connect-four/' + Page.gameUUID).update({ 'player2ReplayDenied': true, 'player2Ready': false }); } }; Page.replayAccepted = function() { if (Page.playerNumber === 0) { database.ref('connect-four/' + Page.gameUUID).update({ 'player1ReplayAccepted': true, 'player1Ready': true }); } else { database.ref('connect-four/' + Page.gameUUID).update({ 'player2ReplayAccepted': true, 'player2Ready': true }); } }; Page.saveGameData = function() { var updates = {}; updates['connect-four/' + Page.gameUUID + '/placementArray/' + Page.piecePlacedAt[0] + '/' + Page.piecePlacedAt[1]] = { 'player': Page.playerTurn }; updates['connect-four/' + Page.gameUUID + '/turn'] = { 'playerTurn': Helpers.updatePlayerTurn(), // update the player turn to the next player 'drawPieceAt': Page.piecePlacedAt, 'gameOver': Page.isGameOver }; Page.playerTurn = Helpers.updatePlayerTurn(); return database.ref().update(updates); }; Page.undoMove = function() { }; Page.getGameData = function() { database.ref('connect-four/' + Page.gameUUID).on('value', function(snapshot) { var data = snapshot.val(); if (data) { Page.placementArray = data.placementArray; Page.playerTurn = data.turn.playerTurn; console.log(Page.playerTurn); Helpers.updateTurnLabels(Page.playerTurn, Page.playerNumber); // make sure we're actually updating the value and not looking at our previous entry if (data.turn.drawPieceAt[0] !== -1 && data.turn.drawPieceAt[1] !== -1 && (Page.piecePlacedAt[0] !== data.turn.drawPieceAt[0] || Page.piecePlacedAt[1] !== data.turn.drawPieceAt[1])) { Page.piecePlacedAt = data.turn.drawPieceAt; Page.drawOpponentMove(); } if (data.turn.gameOver && !Page.isGameOver) { Page.gameOver(); } else { Page.isGameOver = false; } if (data.turn.gameOver && Page.isGameOver) { if ((data.player1ReplayDenied && Page.playerNumber == 1) || data.player2ReplayDenied && Page.playerNumber == 0) { Page.$gameOverModal.modal('hide'); Page.$replayDeclined.modal('show'); } else if (data.player1ReplayAccepted && data.player2ReplayAccepted) { console.log('both players want replay'); // only allow player 1 to reset the game (since they created it to begin with // and we don't want both players to create a game at the same time) if (Page.playerNumber === 0) { Page.resetGame(); } } } if (!Page.gameStarted && data.player2Ready) { Page.attachListeners(); Helpers.hideLoadingOverlay(); Page.$connectPlayersModal.modal('hide'); Page.gameStarted = true; } } else { console.warn('error getting data') } }); }; //#endregion Update game data //#region Win Condition Page.isThereAWinner = function() { var matchesHorizontal = 0; var matchVertical = 0; for (var i = 0; i < Page.rows; i++) { matchesHorizontal = 0; for (var j = 0; j < Page.columns; j++) { // check horizontal if (Page.placementArray[i][j].player === Page.playerTurn) { matchesHorizontal++; if (matchesHorizontal == 4) { return true; } } else { matchesHorizontal = 0; } // check vertical if (j - 1 > -1 && Page.placementArray[j - 1][i].player === Page.playerTurn) { matchVertical++; if (matchVertical == 4) { return true; } } else { matchVertical = 0; } } } // check diagonal var diagonalRightMatches = 0; for (var i = 0; i < Page.rows; i++) { for (var j = 0; j < Page.columns; j++) { if (Page.checkWinDiagonal(i, j)) return true; } } return false; }; Page.checkWinDiagonal = function(i, j) { var p = Page.playerTurn; if (Page.placementArray[i][j].player === p && (i + 3 < Page.rows)) { if (j + 3 < Page.columns) { if (Page.placementArray[i + 1][j + 1].player === p && Page.placementArray[i + 2][j + 2].player === p && Page.placementArray[i + 3][j + 3].player === p) { return true; } } if (j - 3 > -1) { if (Page.placementArray[i + 1][j - 1].player === p && Page.placementArray[i + 2][j - 2].player === p && Page.placementArray[i + 3][j - 3].player === p) { return true; } } } return false; }; //#endregion Win Condition //#region Reset / Replay Page.gameOver = function() { Page.$maskCanvas.off('mouseup'); Page.isGameOver = true; Page.$gameOverModal.one('show.bs.modal', function(e) { $(this).find('#confirm-replay-game').one('click', function() { Page.$gameOverModal.modal('hide'); if (Page.isLocalGame) { Page.resetGame(); } else { Page.replayAccepted(); } }); $(this).find('#deny-replay-game').one('click', function() { Page.$gameOverModal.modal('hide'); Page.replayDenied(); }); }); Page.$gameOverModal.modal('show'); }; Page.resetGame = function() { // clear the canvas Page.context.clearRect(0, 0, Page.canvasWidth, Page.canvasHeight); // reset game variables Page.placementArray = Helpers.create2DArray(Page.rows, Page.columns); Page.placementOrder = []; Page.piecePlacedAt = []; if (!Page.isLocalGame) { // clear game data in the database Page.createGameData(); } // reattach click events Page.attachCanvasListener(); }; //#endregion Reset / Replay $(document).on('ready', function() { Page.initialize(); });
c2283781a4ded5089ae5f38dc18b0bd2391c7e0a
[ "JavaScript" ]
2
JavaScript
brandonhostetter/Connect-Four
04969f62e4970b05b597e2062d5da1218e88fa69
133f1348ae87882c2370ae4da36ae607f0e2dccd
refs/heads/master
<file_sep><?php use yii\helpers\Html; use yii\widgets\ActiveForm; use yii\web\View; use backend\models\Province; use backend\models\City; /* @var $this yii\web\View */ /* @var $model app\models\Town */ /* @var $form yii\widgets\ActiveForm */ $js = <<<JS $(function () { changeProvince($("#town-province_id"), $("#town-city_id"), '', ''); }); JS; $this->registerJs($js, View::POS_END); ?> <div class="town-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'province_id')->dropDownList(Province::getProvinceList()) ?> <?= $form->field($model, 'city_id')->dropDownList(City::getCityList($model->province_id)) ?> <?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'status')->dropDownList($model->getStatusArray()) ?> <?= $form->field($model, 'seo_title')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'seo_keyword')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'seo_desc')->textarea(['rows' => 6]) ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div> <file_sep><?php namespace backend\models; use Yii; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; /** * This is the model class for table "tips_class". * * @property integer $id * @property integer $province_id * @property integer $city_id * @property integer $town_id * @property integer $location_id * @property integer $spot_id * @property string $name * @property integer $status * @property integer $created_at * @property string $updated_at */ class TipsClass extends ActiveRecord { const STATUS_ENABLE = 1; const STATUS_DISABLE = 2; /** * @inheritdoc */ public static function tableName() { return 'tips_class'; } /** * @inheritdoc */ public function rules() { return [ [['province_id', 'city_id', 'town_id', 'location_id', 'spot_id', 'status', 'created_at', 'updated_at'], 'integer'], [['name', 'status'], 'required'], [['name'], 'string', 'max' => 100] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'province_id' => 'Province', 'city_id' => 'City', 'town_id' => 'Town', 'location_id' => 'Location', 'spot_id' => 'Spot', 'name' => 'Name', 'status' => 'Status', 'created_at' => 'Created At', 'updated_at' => 'Updated At', ]; } /** * @inheritdoc */ public function behaviors() { return [ TimestampBehavior::className(), ]; } // status array public static function getStatusArray() { return [ self::STATUS_ENABLE => 'Enable', self::STATUS_DISABLE => 'Disable' ]; } } <file_sep><?php use yii\helpers\Html; use yii\grid\GridView; /* @var $this yii\web\View */ /* @var $searchModel app\models\TipsClassSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Tips Classes'; $params = Yii::$app->request->get('TipsClassSearch'); if(!empty($params['province_id'])){ $this->params['breadcrumbs'][] = ['label' => 'Province', 'url' => ['/province']]; } if(!empty($params['city_id'])){ $this->params['breadcrumbs'][] = ['label' => 'city', 'url' => ['/city']]; } if(!empty($params['town_id'])){ $this->params['breadcrumbs'][] = ['label' => 'town', 'url' => ['/town']]; } if(!empty($params['location_id'])){ $this->params['breadcrumbs'][] = ['label' => 'location', 'url' => ['/location']]; } if(!empty($params['spot_id'])){ $this->params['breadcrumbs'][] = ['label' => 'spot', 'url' => ['/spot']]; } $this->params['breadcrumbs'][] = $this->title; ?> <div class="tips-class-index"> <p> <? $params = Yii::$app->request->get('TipsClassSearch'); ?> <? if(!empty($params['province_id'])): ?> <?= Html::a('Create Tips Class', ['create', 'province_id'=>$params['province_id']], ['class' => 'btn btn-success']) ?> <? endif ?> <? if(!empty($params['city_id'])): ?> <?= Html::a('Create Tips Class', ['create', 'city_id'=>$params['city_id']], ['class' => 'btn btn-success']) ?> <? endif ?> <? if(!empty($params['town_id'])): ?> <?= Html::a('Create Tips Class', ['create', 'town_id'=>$params['town_id']], ['class' => 'btn btn-success']) ?> <? endif ?> <? if(!empty($params['location_id'])): ?> <?= Html::a('Create Tips Class', ['create', 'location_id'=>$params['location_id']], ['class' => 'btn btn-success']) ?> <? endif ?> <? if(!empty($params['spot_id'])): ?> <?= Html::a('Create Tips Class', ['create', 'spot_id'=>$params['spot_id']], ['class' => 'btn btn-success']) ?> <? endif ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ 'id', 'name', [ 'attribute' => 'status', 'format' => 'html', 'value'=>function ($data) { if(1 == $data->status){ return Html::tag('span', ' ', ['class' => 'label label-success glyphicon glyphicon-ok']); // return '<span class="glyphicon glyphicon-ok"></span>'; }else if(2 == $data->status){ return Html::tag('span', ' ', ['class' => 'label label-danger glyphicon glyphicon-remove']); } }, 'filter'=> ['1' => 'Enable', '2' => 'Disable'], ], [ 'class' => 'yii\grid\ActionColumn', 'template' => '{city} {tips} {view} {update} {delete}', 'buttons' => [ 'tips' => function ($url, $model) { return Html::a( '<span class="label label-primary">Tips</span>', ['tips', 'id' => $model->id], [ 'title' => Yii::t('yii', 'Tips'), 'data-pjax' => '0', ] ); }, 'view' => function ($url, $model) { return Html::a( '<span class="label label-info">View</span>', ['view', 'id' => $model->id, 'province_id' => $model->province_id], [ 'title' => Yii::t('yii', 'View'), 'data-pjax' => '0', ] ); }, 'update' => function ($url, $model) { return Html::a( '<span class="label label-warning">Update</span>', ['update', 'id' => $model->id, 'province_id' => $model->province_id], [ 'title' => Yii::t('yii', 'Update'), 'data-pjax' => '0', ] ); }, 'delete' => function ($url, $model) { return Html::a('<span class="label label-danger">Delete</span>', $url, [ 'title' => Yii::t('yii', 'Delete'), 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), 'data-method' => 'post', 'data-pjax' => '0', ]); }, ], 'headerOptions' => ['width' => '20%'], ], ], ]); ?> </div> <file_sep><?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model backend\models\TipsClass */ /* @var $form yii\widgets\ActiveForm */ ?> <? $params = Yii::$app->request->get(); ?> <div class="tips-class-form"> <?php $form = ActiveForm::begin(); ?> <? if(!empty($params['province_id'])): ?> <?= Html::activeHiddenInput($model, 'province_id', ['value' => $params['province_id']])?> <? endif ?> <? if(!empty($params['city_id'])): ?> <?= Html::activeHiddenInput($model, 'city_id', ['value' => $params['city_id']])?> <? endif ?> <? if(!empty($params['town_id'])): ?> <?= Html::activeHiddenInput($model, 'town_id', ['value' => $params['town_id']])?> <? endif ?> <? if(!empty($params['location_id'])): ?> <?= Html::activeHiddenInput($model, 'location_id', ['value' => $params['location_id']])?> <? endif ?> <? if(!empty($params['spot_id'])): ?> <?= Html::activeHiddenInput($model, 'spot_id', ['value' => $params['spot_id']])?> <? endif ?> <?= $form->field($model, 'name')->textInput(['maxlength' => 100]) ?> <?= $form->field($model, 'status')->dropDownList($model->getStatusArray()) ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div> <file_sep><?php namespace backend\models; use Yii; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; /** * This is the model class for table "tips". * * @property integer $id * @property integer $tips_class_id * @property string $title * @property string $intro * @property string $content * @property string $keyword * @property integer $status * @property string $created_at * @property string $updated_at */ class Tips extends ActiveRecord { const STATUS_ENABLE = 1; const STATUS_DISABLE = 2; /** * @inheritdoc */ public static function tableName() { return 'tips'; } /** * @inheritdoc */ public function rules() { return [ [['tips_class_id', 'title', 'intro', 'content', 'keyword'], 'required'], [['tips_class_id', 'status', 'created_at', 'updated_at'], 'integer'], [['intro', 'content'], 'string'], [['title', 'keyword'], 'string', 'max' => 255] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'tips_class_id' => 'Tips Class', 'title' => 'Title', 'intro' => 'Intro', 'content' => 'Content', 'keyword' => 'Keyword', 'status' => 'Status', 'created_at' => 'Created At', 'updated_at' => 'Updated At', ]; } /** * @inheritdoc */ public function behaviors() { return [ TimestampBehavior::className(), ]; } // status array public static function getStatusArray() { return [ self::STATUS_ENABLE => 'Enable', self::STATUS_DISABLE => 'Disable' ]; } } <file_sep>-- phpMyAdmin SQL Dump -- version 4.1.6 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: 2014-11-14 17:40:47 -- 服务器版本: 5.5.36 -- PHP Version: 5.4.25 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: `chinatravel` -- -- -------------------------------------------------------- -- -- 表的结构 `city` -- CREATE TABLE IF NOT EXISTS `city` ( `id` int(11) NOT NULL AUTO_INCREMENT, `province_id` int(11) NOT NULL DEFAULT '0', `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1', `seo_title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `seo_keyword` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `seo_desc` text COLLATE utf8_unicode_ci NOT NULL, `created_at` int(10) unsigned NOT NULL, `updated_at` int(10) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ; -- -- 转存表中的数据 `city` -- INSERT INTO `city` (`id`, `province_id`, `name`, `status`, `seo_title`, `seo_keyword`, `seo_desc`, `created_at`, `updated_at`) VALUES (1, 4, 'Chengdu', 1, 'Chengdu', 'Chengdu', 'Chengdu', 1415090188, 1415090188), (2, 4, 'Mianyang', 1, 'Mianyang', 'Mianyang', 'Mianyang', 1415159129, 1415174740); -- -------------------------------------------------------- -- -- 表的结构 `location` -- CREATE TABLE IF NOT EXISTS `location` ( `id` int(11) NOT NULL AUTO_INCREMENT, `province_id` int(11) NOT NULL DEFAULT '0', `city_id` int(11) NOT NULL DEFAULT '0', `town_id` int(11) NOT NULL DEFAULT '0', `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1', `seo_title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `seo_keyword` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `seo_desc` text COLLATE utf8_unicode_ci NOT NULL, `created_at` int(10) unsigned NOT NULL, `updated_at` int(10) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- 表的结构 `migration` -- CREATE TABLE IF NOT EXISTS `migration` ( `version` varchar(180) COLLATE utf8_unicode_ci NOT NULL, `apply_time` int(11) DEFAULT NULL, PRIMARY KEY (`version`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- 转存表中的数据 `migration` -- INSERT INTO `migration` (`version`, `apply_time`) VALUES ('m000000_000000_base', 1415002716), ('m130524_201442_init', 1415002718); -- -------------------------------------------------------- -- -- 表的结构 `province` -- CREATE TABLE IF NOT EXISTS `province` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1', `seo_title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `seo_keyword` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `seo_desc` text COLLATE utf8_unicode_ci NOT NULL, `created_at` int(10) unsigned NOT NULL, `updated_at` int(10) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='省份表' AUTO_INCREMENT=7 ; -- -- 转存表中的数据 `province` -- INSERT INTO `province` (`id`, `name`, `status`, `seo_title`, `seo_keyword`, `seo_desc`, `created_at`, `updated_at`) VALUES (1, 'Beijing', 1, 'title', 'keyword', 'description', 1415005989, 1415007604), (2, 'Tianjin', 2, 'Tianjin', 'Tianjin', 'Tianjin', 1415007914, 1415956646), (3, 'Shanghai', 1, 'Shanghai', 'Shanghai', 'Shanghai', 1415069719, 1415069719), (4, 'Sichuan', 1, 'Sichuan', 'Sichuan', 'Sichuan', 1415089929, 1415089929), (5, 'Hubei', 1, 'Hubei', 'Hubei', 'Hubei', 1415946326, 1415946326), (6, 'Hunan', 1, 'Hunan', 'Hunan', 'Hunan', 1415952380, 1415952380); -- -------------------------------------------------------- -- -- 表的结构 `spot` -- CREATE TABLE IF NOT EXISTS `spot` ( `id` int(11) NOT NULL AUTO_INCREMENT, `province_id` int(11) NOT NULL DEFAULT '0', `city_id` int(11) NOT NULL DEFAULT '0', `town_id` int(11) NOT NULL DEFAULT '0', `location_id` int(11) NOT NULL DEFAULT '0', `status` tinyint(1) NOT NULL DEFAULT '1', `seo_title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `seo_keyword` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `seo_desc` text COLLATE utf8_unicode_ci NOT NULL, `created_at` int(10) unsigned NOT NULL, `updated_at` int(10) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- 表的结构 `town` -- CREATE TABLE IF NOT EXISTS `town` ( `id` int(11) NOT NULL AUTO_INCREMENT, `province_id` int(11) NOT NULL DEFAULT '0', `city_id` int(11) NOT NULL DEFAULT '0', `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1', `seo_title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `seo_keyword` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `seo_desc` text COLLATE utf8_unicode_ci NOT NULL, `created_at` int(10) unsigned NOT NULL, `updated_at` int(10) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ; -- -- 转存表中的数据 `town` -- INSERT INTO `town` (`id`, `province_id`, `city_id`, `name`, `status`, `seo_title`, `seo_keyword`, `seo_desc`, `created_at`, `updated_at`) VALUES (1, 4, 1, 'Santai', 1, 'Santai', 'Santai', 'Santai', 1415159147, 1415180243), (2, 4, 2, 'Yanting', 1, 'Yanting', 'Yanting', 'Yanting', 1415174780, 1415174780); -- -------------------------------------------------------- -- -- 表的结构 `user` -- CREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `auth_key` varchar(32) COLLATE utf8_unicode_ci NOT NULL, `password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `password_reset_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `role` smallint(6) NOT NULL DEFAULT '1', `status` smallint(6) NOT NULL DEFAULT '1', `created_at` int(11) NOT NULL, `updated_at` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ; -- -- 转存表中的数据 `user` -- INSERT INTO `user` (`id`, `username`, `auth_key`, `password_hash`, `password_reset_token`, `email`, `role`, `status`, `created_at`, `updated_at`) VALUES (1, 'admin', '<PASSWORD>', <PASSWORD>', NULL, '<EMAIL>', 1, 1, 1415002799, 1415002799); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php namespace backend\models; use Yii; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; /** * This is the model class for table "town". * * @property integer $id * @property integer $province_id * @property integer $city_id * @property string $name * @property integer $status * @property string $seo_title * @property string $seo_keyword * @property string $seo_desc * @property string $created_at * @property string $updated_at */ class Town extends ActiveRecord { const STATUS_ENABLE = 1; const STATUS_DISABLE = 2; /** * @inheritdoc */ public static function tableName() { return 'town'; } /** * @inheritdoc */ public function rules() { return [ [['province_id', 'city_id', 'status', 'created_at', 'updated_at'], 'integer'], [['name', 'province_id', 'city_id', 'seo_title', 'seo_keyword', 'seo_desc'], 'required'], [['seo_desc'], 'string'], [['name', 'seo_title', 'seo_keyword'], 'string', 'max' => 255] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'province_id' => 'Province', 'city_id' => 'City', 'name' => 'Name', 'status' => 'Status', 'seo_title' => 'Seo Title', 'seo_keyword' => 'Seo Keyword', 'seo_desc' => 'Seo Desc', 'created_at' => 'Created At', 'updated_at' => 'Updated At', ]; } /** * @inheritdoc */ public function behaviors() { return [ TimestampBehavior::className(), ]; } // status array public static function getStatusArray(){ return [ self::STATUS_ENABLE => 'Enable', self::STATUS_DISABLE => 'Disable' ]; } // get town list by city id public static function getTownList($cityId) { $data = self::find()->select(['id', 'name']) ->where(['status' => 1, 'city_id' => $cityId]) ->orderBy(['name' => 'DESC']) ->asArray() ->all(); $array[0] = 'Please Select the Town'; foreach($data as $val){ $array[$val['id']] = $val['name']; } return $array; } } <file_sep><?php use yii\helpers\Html; use yii\widgets\DetailView; use backend\models\Province; /* @var $this yii\web\View */ /* @var $model backend\models\TipsClass */ $this->title = $model->name; $params = Yii::$app->request->get(); if(!empty($params['province_id'])){ $this->params['breadcrumbs'][] = ['label' => 'Province', 'url' => ['/province']]; } if(!empty($params['city_id'])){ $this->params['breadcrumbs'][] = ['label' => 'city', 'url' => ['/city']]; } if(!empty($params['town_id'])){ $this->params['breadcrumbs'][] = ['label' => 'town', 'url' => ['/town']]; } if(!empty($params['location_id'])){ $this->params['breadcrumbs'][] = ['label' => 'location', 'url' => ['/location']]; } if(!empty($params['spot_id'])){ $this->params['breadcrumbs'][] = ['label' => 'spot', 'url' => ['/spot']]; } $this->params['breadcrumbs'][] = [ 'label' => 'Tips Classes', 'url' => [ 'index', 'TipsClassSearch' => [ 'province_id' => isset($params['province_id']) ? $params['province_id'] : '', 'city_id' => isset($params['city_id']) ? $params['city_id'] : '', 'town_id' => isset($params['town_id']) ? $params['town_id'] : '', 'location_id' => isset($params['location_id']) ? $params['location_id'] : '', 'spot_id' => isset($params['spot_id']) ? $params['spot_id'] : '', ] ] ]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="tips-class-view"> <p> <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> <?= Html::a('Delete', ['delete', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', [ 'label' => 'Province', 'value' => Province::getProvinceName($model->province_id), ], 'city_id', 'town_id', 'location_id', 'spot_id', 'name', [ 'label' => 'Status', 'format' => 'raw', 'value' => (1 == $model->status) ? Html::tag('span', ' ', ['class' => 'label label-success glyphicon glyphicon-ok']) : Html::tag('span', ' ', ['class' => 'label label-danger glyphicon glyphicon-remove']), ], [ 'label' => 'Created At', 'value' => date('Y-m-d H:i:s', $model->created_at), ], [ 'label' => 'Updated At', 'value' => date('Y-m-d H:i:s', $model->updated_at), ], ], ]) ?> </div> <file_sep>function changeProvince(province, city, town, location){ if(0 == province.length) return false; province.change(function() { var id = parseInt($(this).val()); // change city if(0 == city.length) return false; city.empty(); city.append('<option value="0">loding......</option>'); $.getJSON("/city/cities", {'id':id}, function(data) { city.empty(); $.each(data, function(key, value) { city.append('<option value="' + key + '">' + value + '</option>'); }); }); changeCity(city, town, location); }); } function changeCity(city, town, location){ if(0 == city.length) return false; city.change(function() { var id = parseInt($(this).val()); // change town if(0 == town.length) return false; town.empty(); $.getJSON("/town/towns", {'id':id}, function(data) { town.empty(); $.each(data, function(key, value) { town.append('<option value="' + key + '">' + value + '</option>'); }); }); changeTown(town, location); }); } function changeTown(town, location){ if(0 == town.length) return false; town.change(function() { var id = parseInt($(this).val()); // change town if(0 == location.length) return false; location.empty(); var locationValue = town.find("option:first").val(); $.getJSON("/location/locations", {'id':id}, function(data) { $.each(data, function(key, value) { location.append('<option value="' + value.id + '">' + value.name + '</option>'); }); }); }); }<file_sep><?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model backend\models\TipsClass */ $this->title = 'Create Tips Class'; $params = Yii::$app->request->get(); $this->params['breadcrumbs'][] = [ 'label' => 'Tips Classes', 'url' => [ 'index', 'TipsClassSearch' => [ 'province_id' => isset($params['province_id']) ? $params['province_id'] : '', 'city_id' => isset($params['city_id']) ? $params['city_id'] : '', 'town_id' => isset($params['town_id']) ? $params['town_id'] : '', 'location_id' => isset($params['location_id']) ? $params['location_id'] : '', 'spot_id' => isset($params['spot_id']) ? $params['spot_id'] : '', ] ] ]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="tips-class-create"> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div> <file_sep><?php namespace backend\models; use Yii; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; /** * This is the model class for table "city". * * @property integer $id * @property integer $province_id * @property string $name * @property integer $status * @property string $seo_title * @property string $seo_keyword * @property string $seo_desc * @property string $created_at * @property string $updated_at */ class City extends ActiveRecord { const STATUS_ENABLE = 1; const STATUS_DISABLE = 2; /** * @inheritdoc */ public static function tableName() { return 'city'; } /** * @inheritdoc */ public function rules() { return [ [['province_id', 'status'], 'integer'], [['name', 'province_id', 'seo_title', 'seo_keyword', 'seo_desc'], 'required'], [['seo_desc'], 'string'], [['name', 'seo_title', 'seo_keyword'], 'string', 'max' => 255], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'province_id' => 'Province', 'name' => 'City', 'status' => 'Status', 'seo_title' => 'Seo Title', 'seo_keyword' => 'Seo Keyword', 'seo_desc' => 'Seo Description', 'created_at' => 'Created At', 'updated_at' => 'Updated At', ]; } /** * @return array relational rules. */ public function relations() { return array( 'province' => array(self::BELONGS_TO, 'Province', 'province_id'), ); } /** * @inheritdoc */ public function behaviors() { return [ TimestampBehavior::className(), ]; } // status array public static function getStatusArray() { return [ self::STATUS_ENABLE => 'Enable', self::STATUS_DISABLE => 'Disable' ]; } // get city list by provinceId public static function getCityList($provinceId) { $data = self::find()->select(['id', 'name']) ->where(['status' => 1, 'province_id' => $provinceId]) ->orderBy(['name' => 'DESC']) ->asArray() ->all(); $array[0] = 'Please Select the City'; foreach($data as $val){ $array[$val['id']] = $val['name']; } return $array; } }
c5ee724b0682d25eb6d5c7b3435b6f0e5bc5e63e
[ "JavaScript", "SQL", "PHP" ]
11
PHP
lemayi/chinatravel
525edd793126cf3ca63a7c609113c7fd5e44779e
0d8a41c5edf9659173fad37ac2dcdd2d55c73197
refs/heads/master
<file_sep>#!/bin/bash ##################################### # setup.sh # # Author: ##################################### ############################################ # Check if this script is running as root. if [[ `whoami` != "root" ]] then echo "This install must be run as root or with sudo." exit fi # Create working directories mkdir -p /var/media/scripts mkdir -p /var/media/logs mkdir -p /var/media/current # Working directory for running slideshow mkdir -p /var/media/slides # Upload location for new slide files mkdir -p /var/media/videos mkdir -p /var/media/data mkdir -p /var/media/data/yimg mkdir -p /var/media/logos chmod -R 777 /var/media # Pull scripts from git repo cp video.sh /var/media/scripts cp slides.sh /var/media/scripts cp refresh.sh /var/media/scripts cp disp.py /var/media/scripts cp media/bg.jpg /var/media/bg.jpg cp media/1.jpg /var/media/slides/ cp media/2.jpg /var/media/slides/ cp media/3.jpg /var/media/slides/ cp logos/* /var/media/logos/ cp -rp data/* /var/media/data/ wget https://app.kronusec.com/pear/get/repo/checkin.sh -O /var/media/scripts/checkin.sh # Make executable chmod a+x /var/media/scripts/*.sh chmod a+x /var/media/scripts/*.py #Setup Crontab cat <<EOF | sudo crontab - */30 * * * * /var/media/scripts/video.sh @reboot /var/media/scripts/slides.sh * * * * * /var/media/scripts/refresh.sh * * * * * /var/media/scripts/checkin.sh 1>/dev/null 2>&1 EOF # Create the service enabled file sudo touch /var/media/enabled apt-get install -y nginx php5 php5-fpm php5-gd mkdir -p /usr/share/nginx/www/ cp -rp www/* /usr/share/nginx/www/ cat <<EOF >/etc/nginx/sites-enabled/default # Default Site server { listen 80; ## listen for ipv4; this line is default and implied root /usr/share/nginx/www; index index.php index.html index.htm; location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } location ~ /\.ht { deny all; } } EOF ln -s /var/media/slides/ /usr/share/nginx/www/share chmod -R 777 /usr/share/nginx/www/share chmod -R 777 /var/media/slides/ /etc/init.d/nginx restart <file_sep><p>Deleting file: <?php //$str = file_get_contents('php://input'); //echo $filename = $_GET["name"] . "-" . md5(time().uniqid()).".jpg"; echo $filename = $_GET["file"]; //file_put_contents("/usr/share/nginx/www/share/".$filename,$str); // In demo version i delete uplaoded file immideately, Please remove it later unlink("/usr/share/nginx/www/share/".$filename); unlink("/usr/share/nginx/www/share/thumbs/".$filename); ?> </p> <p>Return to <a href="/photos/">Photos</a></p> <file_sep>import csv import urllib import PIL from PIL import ImageFont from PIL import Image from PIL import ImageDraw import textwrap import re urllib.urlretrieve("http://genetics.case.edu/VidDISPLAY/INPUT", "INPUT") allinfo=[] with open('INPUT','r') as f: # skip headings # next(f) reader=csv.reader(f,delimiter='\t') for info in reader: allinfo.append(info) talktype_font = ImageFont.truetype("../fonts/TitilliumMaps26L.otf",175) speaker_font = ImageFont.truetype("../fonts/TitilliumMaps26L001.otf",150) title_font = ImageFont.truetype("../fonts/TitilliumMaps26L002.otf",100) description_font = ImageFont.truetype("../fonts/TitilliumTitle12.otf",100) description_font = ImageFont.truetype("../fonts/TitilliumTitle12.otf",100) day_time_font = ImageFont.truetype("../fonts/Titalic750wt.otf",100) loc_font = ImageFont.truetype("../fonts/TitilliumMaps26L003.otf",100) check_event=[] news = [] count = 0 margin = 45 offset= 665 for event in allinfo: Type = event[0] Number = event[1] Background_Img = event[2] img=Image.open(Background_Img) draw = ImageDraw.Draw(img) if Type == "REG": #3-11 Number = event[5] Dayoftheweek = event[6] TalkType = event[7] if '-' in TalkType: Compound_Info = re.split(r'-', TalkType) TalkType = Compound_Info[0].strip() Speaker = Compound_Info[1].strip() else: Speaker = event[8] Title = event[9] Time = event[10] Location = event[11] Day_Time = Dayoftheweek + ', ' + Time draw.text((1000, 200),TalkType,(0,0,0),font=talktype_font) draw = ImageDraw.Draw(img) draw.text((1000, 490),Speaker,(0,0,0),font=speaker_font) draw = ImageDraw.Draw(img) for line in textwrap.wrap(Title, width=45): draw.text((1000, offset), line, (0,0,0), font=title_font) offset += title_font.getsize(line)[1] #draw.text((1000, 550),Title,(0,0,0),font=title_font) draw = ImageDraw.Draw(img) draw.text((1000, 1250),Day_Time,(0,0,0),font=day_time_font) draw = ImageDraw.Draw(img) draw = ImageDraw.Draw(img) draw.text((1000, 1350),Location,(0,0,0),font=loc_font) draw = ImageDraw.Draw(img) image_name = "slide" + str(count) +".png" img.save(image_name) count = count+1 elif Type == "NEWS": #3-6 news = event[6] print news print len(news) elif Type == "SPEC": image_name = "slide" + str(count) +".png" img.save(image_name) count = count+1 else: print "Bad Type: I don't have this type in my logic." <file_sep>#!/bin/bash for int in `cat /proc/net/dev| grep : | cut -f1 -d:| awk '{ print $1 }'` do echo $int curl http://web.wtfoo.net/pear/check.igc?name=`hostname`-${int}\&ip=`/sbin/ifconfig ${int} | grep "inet addr" | cut -f2 -d: | cut -f1 -d" "` >/dev/null 2>&1 done <file_sep>#!/usr/bin/python # # Author <NAME> import pygame, sys, os, math from pygame.locals import * import time from os import listdir from os.path import isfile, join import string import json # Set the display to fb1 - i.e. the TFT os.environ["SDL_FBDEV"] = "/dev/fb0" # Remove mouse os.environ["SDL_NOMOUSE"]="1" SLIDES_DIR = "/var/media/current/" LOGOS_DIR = "/var/media/logos/topright/" DATA_DIR = "/var/media/data/" WEATHER_IMG = "/var/media/data/yimg/" update_slide = 10 update_text1 = 1 update_text2 = 1 update_logo = 60 update_weather = 900 update_stocks = 900 # Set constants FPS=1000 BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) GRAY = (62, 62, 62) BLUE = ( 10, 48, 72) # main game loop def main(): now = time.time() screen = None; "Ininitializes a new pygame screen using the framebuffer" disp_no = os.getenv("DISPLAY") if disp_no: print "I'm running under X display = {0}".format(disp_no) # Check which frame buffer drivers are available # Start with fbcon since directfb hangs with composite output drivers = ['fbcon', 'directfb', 'svgalib'] found = False for driver in drivers: # Make sure that SDL_VIDEODRIVER is set if not os.getenv('SDL_VIDEODRIVER'): os.putenv('SDL_VIDEODRIVER', driver) try: print 'Driver: {0} Success.'.format(driver) pygame.display.init() except pygame.error: print 'Driver: {0} failed.'.format(driver) continue found = True break global FPSCLOCK, DISPLAYSURF, DISPLAY_W, DISPLAY_H global slide_num, last_slide, last_text1, last_text2, last_logo, line1_num, line2_num, logo_num global line1, line2 load_text() #load_stock() load_weather() last_slide = now last_text1 = now last_text2 = now last_logo = now slide_num = 0 line1_num = 0 line2_num = 0 logo_num = 0 FPSCLOCK = pygame.time.Clock() size = (pygame.display.Info().current_w, pygame.display.Info().current_h) #size = (1080, 720) DISPLAY_W = pygame.display.Info().current_w DISPLAY_H = pygame.display.Info().current_h print "Framebuffer size: %d x %d" % (size[0], size[1]) DISPLAYSURF=pygame.display.set_mode(size, pygame.FULLSCREEN, 32) pygame.mouse.set_visible(0) pygame.font.init() print "Showing logo." dispLogo() pygame.display.update() time.sleep(2) print "Running main loop." while True: for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): pygame.quit() sys.exit() mainLoop() pygame.display.update() FPSCLOCK.tick(FPS) time.sleep(2) # a funtion to do something def dispLogo(): DISPLAYSURF.fill(BLACK) logo = pygame.image.load("/var/media/logos/GGS_Case Logo Wide.png").convert() logo2 = pygame.transform.scale(logo, (DISPLAY_W, DISPLAY_H)) DISPLAYSURF.blit(logo2, (0,0)) # fontObj = pygame.font.Font('../fonts/TitilliumMaps26L.otf', 42) # textSurfaceObj = fontObj.render('Department of Genetics and Genome Sciences', True, BLACK) # textRectObj = textSurfaceObj.get_rect() # textRectObj.center = (DISPLAY_W/2,DISPLAY_H/2+20+1) # DISPLAYSURF.blit (textSurfaceObj, textRectObj) # textRectObj.center = (DISPLAY_W/2+1,DISPLAY_H/2+20-1) # DISPLAYSURF.blit (textSurfaceObj, textRectObj) # textRectObj.center = (DISPLAY_W/2+1,DISPLAY_H/2+20) # DISPLAYSURF.blit (textSurfaceObj, textRectObj) # textRectObj.center = (DISPLAY_W/2-1,DISPLAY_H/2+20) # DISPLAYSURF.blit (textSurfaceObj, textRectObj) # textSurfaceObj = fontObj.render('Department of Genetics and Genome Sciences', True, WHITE) # textRectObj = textSurfaceObj.get_rect() # textRectObj.center = (DISPLAY_W/2,DISPLAY_H/2+20) # DISPLAYSURF.blit (textSurfaceObj, textRectObj) def mainLoop(): global slide_num, last_slide, last_text1, last_text2, last_logo, line1_num, line2_num, logo_num global line1, line2, stock, weather now = time.time() DISPLAYSURF.fill(WHITE) #bg = pygame.image.load('/var/media/bg.jpg').convert() #DISPLAYSURF.blit(bg, (0,870)) borderColor = (255, 255, 255) lineColor = (64, 64, 64) s1w = 1440 s1h = 900 so = 5 #pygame.draw.rect(DISPLAYSURF, borderColor, (so,so,s1w,s1h), 1) #pygame.draw.rect(DISPLAYSURF, borderColor, (2*so+s1w,so,364,131), 1) pygame.draw.rect(DISPLAYSURF, BLUE, (2*so+s1w,5,1920-s1w-3*so,1920-s1w-3*so), 0) pygame.draw.rect(DISPLAYSURF, BLUE, (2*so+s1w,480,1920-s1w-3*so,425), 0) #pygame.draw.rect(DISPLAYSURF, borderColor, (2*so+s1w,510,364,364), 1) pygame.draw.rect(DISPLAYSURF, WHITE, (0,0,1920-1,1080-1), 1) pygame.draw.rect(DISPLAYSURF, BLUE, (5,s1h+2*so,1920-2*so,1080-s1h-3*so), 0) # Display Slides slides = [f for f in listdir(SLIDES_DIR) if isfile(join(SLIDES_DIR, f))] if slide_num >= len(slides): slide_num=0; slide = pygame.image.load(SLIDES_DIR+slides[slide_num]).convert() slide2 = pygame.transform.scale(slide, (s1w-2, s1h-2)) DISPLAYSURF.blit(slide2, (6, 6)) if now-last_slide > update_slide: last_slide = now slide_num = slide_num+1 # Draw Text Ticker if line1_num>=len(line1): line1_num=0; font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 100) text_surface = font.render(line1[line1_num], True, (255, 255, 200)) DISPLAYSURF.blit(text_surface, (10, 880)) if now-last_text1 > update_text1: last_text1 = now line1_num = line1_num+1 if line2_num>=len(line2): line2_num=0; font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 70) text_surface = font.render(line2[line2_num], True, (255, 255, 200)) DISPLAYSURF.blit(text_surface, (10, 980)) if now-last_text2 > update_text2: last_text2 = now line2_num = line2_num+1 # Display Logo logos = [f for f in listdir(LOGOS_DIR) if isfile(join(LOGOS_DIR, f))] if logo_num>=len(logos): logo_num=0; logo = pygame.image.load(LOGOS_DIR+logos[logo_num]).convert() logo2 = pygame.transform.scale(logo, (500,500)) DISPLAYSURF.blit(logo2, (2*so+s1w,5)) if now-last_logo > update_logo: last_logo = now logo_num = logo_num+1 # Display Stock Info # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 50) # text_surface = font.render(stock['name'], True, (255, 255, 255), None) # White text # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,515)) # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 30) # text_surface = font.render(stock['share'], True, (200, 255, 200), None) # White text # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,565)) # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 50) # text_surface = font.render("" + stock['change'], True, (255, 100, 100), None) # White text # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,615)) # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 50) # text_surface = font.render("Price: " + stock['price'], True, (200, 200, 200), None) # White text # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,665)) # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 20) # text_surface = font.render("Todays High: " + stock['high'], True, (255, 200, 200), None) # White text # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,735)) # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 20) # text_surface = font.render("Todays Low: " + stock['low'], True, (255, 200, 200), None) # White text # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,765)) move_y_axis = 50 # Display Weather font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 50) text_surface = font.render(weather['location'], True, (255, 255, 255), None) # White text DISPLAYSURF.blit(text_surface, (2*so+s1w+5,480+move_y_axis)) # pygame.draw.rect(DISPLAYSURF, (255,255,255), (2*so+s1w+5,195,350,150), 0) if os.path.isfile(WEATHER_IMG+weather['current_conditions']['icon']+".gif"): icon = pygame.image.load(WEATHER_IMG+weather['current_conditions']['icon']+".gif").convert() DISPLAYSURF.blit(icon, (2*so+s1w+5,530 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 50) text_surface = font.render(weather['current_conditions']['temperature']+"F", True, BLACK) # Black text DISPLAYSURF.blit(text_surface, (2*so+s1w+5+100,530 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 30) text_surface = font.render(weather['current_conditions']['text'], True, GRAY) DISPLAYSURF.blit(text_surface, (2*so+s1w+5,585 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 30) text_surface = font.render("Wind: " + string.lower(weather['current_conditions']['wind']['speed']) + weather['current_conditions']['wind']['text'], True, (100, 100, 100)) DISPLAYSURF.blit(text_surface, (2*so+s1w+5,635 + move_y_axis)) # pygame.draw.rect(DISPLAYSURF, (255,255,255), (2*so+s1w+5,350,55,55), 0) # pygame.draw.rect(DISPLAYSURF, (255,255,255), (2*so+s1w+5+110,350,55,55), 0) # pygame.draw.rect(DISPLAYSURF, (255,255,255), (2*so+s1w+5+220,350,55,55), 0) if os.path.isfile(WEATHER_IMG+weather['current_conditions']['icon']+".gif"): icon = pygame.image.load(WEATHER_IMG+weather['current_conditions']['icon']+".gif").convert() DISPLAYSURF.blit(icon, (2*so+s1w+5,690 + move_y_axis)) if os.path.isfile(WEATHER_IMG+weather['forecasts'][1]['day']['icon']+".gif"): icon = pygame.image.load(WEATHER_IMG+weather['forecasts'][1]['day']['icon']+".gif").convert() DISPLAYSURF.blit(icon, (2*so+s1w+5+110,690 + move_y_axis)) if os.path.isfile(WEATHER_IMG+weather['forecasts'][2]['day']['icon']+".gif"): icon = pygame.image.load(WEATHER_IMG+weather['forecasts'][2]['day']['icon']+".gif").convert() DISPLAYSURF.blit(icon, (2*so+s1w+5+220,690 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15) text_surface = font.render(weather['forecasts'][0]['day_of_week'], True, (255, 255, 255), None) # White text DISPLAYSURF.blit(text_surface, (2*so+s1w+5,740 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15) text_surface = font.render("High: " + weather['forecasts'][0]['high'], True, (255, 100, 100), None) # White text DISPLAYSURF.blit(text_surface, (2*so+s1w+5,770 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15) text_surface = font.render("Low: " + weather['forecasts'][0]['low'], True, (100, 255, 100), None) # White text DISPLAYSURF.blit(text_surface, (2*so+s1w+5,800 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15) text_surface = font.render(weather['forecasts'][1]['day_of_week'], True, (220, 220, 220), None) # White text DISPLAYSURF.blit(text_surface, (2*so+s1w+5+110,740 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15) text_surface = font.render("High: " + weather['forecasts'][1]['high'], True, (255, 100, 100), None) # White text DISPLAYSURF.blit(text_surface, (2*so+s1w+5+110,770 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15) text_surface = font.render("Low: " + weather['forecasts'][1]['low'], True, (100, 255, 100), None) # White text DISPLAYSURF.blit(text_surface, (2*so+s1w+5+110,800 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15) text_surface = font.render(weather['forecasts'][2]['day_of_week'], True, (200, 200, 200), None) # White text DISPLAYSURF.blit(text_surface, (2*so+s1w+5+220,740 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15) text_surface = font.render("High: " + weather['forecasts'][2]['high'], True, (255, 100, 100), None) # White text DISPLAYSURF.blit(text_surface, (2*so+s1w+5+220,770 + move_y_axis)) font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15) text_surface = font.render("Low: " + weather['forecasts'][2]['low'], True, (100, 255, 100), None) # White text DISPLAYSURF.blit(text_surface, (2*so+s1w+5+220,800 + move_y_axis)) print "." def load_text(): global line1, line2 line1 = [line.rstrip('\n') for line in open(DATA_DIR+"line1.txt")] line2 = [line.rstrip('\n') for line in open(DATA_DIR+"line2.txt")] def load_stock(): global stock with open(DATA_DIR+'stock.json', 'r') as f: stock = json.load(f) def load_weather(): global weather with open(DATA_DIR+'weather.json', 'r') as f: weather = json.load(f) # Run Main Function if __name__ == '__main__': main() <file_sep>#!/bin/bash ##################################### # refresh.sh # # Author: ##################################### DATE=`date` # Update slides.txt ls -v /var/media/slides/* | egrep -i "jpg|png|gif|jpeg" > /var/media/logs/slides.new.txt # Change working directory, then md5sum files within dir so output file has relative path, not absolute path cd /var/media/slides md5sum ./* | egrep -i "jpg|png|gif|jpeg" > /var/media/logs/slides.new.md5 cd /var/media/current md5sum ./* | egrep -i "jpg|png|gif|jpeg" > /var/media/logs/slides.current.md5 #md5sum /var/media/slides/* | grep JPG > /var/media/logs/slides.new.md5 #md5sum /var/media/current/* | grep JPG > /var/media/logs/slides.current.md5 # Diff slides files diff /var/media/logs/slides.current.md5 /var/media/logs/slides.new.md5 # If the files are different then replace slides.txt and kill fbi if [[ $? != 0 ]] then echo “$DATE - New slides found. Killing fbi” >> /var/media/logs/refresh.log # Flush current slide deck rm -f /var/media/current/* # Update slide deck cp /var/media/slides/* /var/media/current/ # Set new slide list file mv /var/media/logs/slides.new.txt /var/media/logs/slides.txt # Quit fbi gently so the console doesn't get stuck; slides.sh will relaunch killall -3 fbi fi <file_sep>#!/bin/bash ##################################### # slides.sh # # Author: ##################################### # Generate slides.txt on first run. /var/media/scripts/refresh.sh # Start FBI while true do DATE=`date` # Check if /var/media/enabled file exists. if [[ -f /var/media/enabled ]] then # Collect the PID of fbi _PID=`pidof fbi` # If PID is NOT running restart it. if [[ $? != 0 ]] then echo “$DATE - fbi not running. Restarting.” >> /var/media/logs/slides.log /usr/bin/fbi -T 1 -d /dev/fb0 --noverbose -a -t 4 -l /var/media/logs/slides.txt fi fi # Pause for 5 seconds sleep 5 done <file_sep><?php $str = file_get_contents('php://input'); //echo $filename = $_GET["name"] . "-" . md5(time().uniqid()).".jpg"; echo $filename = $_GET["name"]; file_put_contents("/usr/share/nginx/www/share/".$filename,$str); // In demo version i delete uplaoded file immideately, Please remove it later //unlink("uploads/".$filename); ?> <file_sep>sudo apt-get install nginx php5-fpm php5-gd php5-curl <file_sep>#!/bin/bash ##################################### # setup.sh # # Author: ##################################### # Update apt cache sudo apt-get update # Upgrade OS packages sudo apt-get upgrade -y # Install required packages sudo apt-get install -y fbi screen omxplayer imagemagick python-pygame git # Clone the github directory mkdir -p git-tmp cd $HOME cd git-tmp rm -rf genetics_PIdisplay git clone https://github.com/hgw3lls/genetics_PIdisplay.git cd genetics_PIdisplay chmod a+x install.sh sudo ./install.sh <file_sep># genetics_PIdisplay Scripts/configs for a simple image slideshow on Raspberry Pi To setup a Raspberry Pi from scratch. Download and image Raspbian Lite to an SD card: Base Image Download URL: Raspbian Lite: https://downloads.raspberrypi.org/raspbian_lite_latest Downloaded from: https://www.raspberrypi.org/downloads/raspbian/ (currently) Perform initial boot and configuration of device, expand file system to fill SD card. from ssh session or console: wget https://raw.githubusercontent.com/hgw3lls/genetics_PIdisplay/master/setup.sh chmod a+x setup.sh ./setup.sh (currently) SCP slideshow files to /var/media/slideshow SCP videos files to /var/media/videos Slideshow will cycle through all jpeg files, in ascending file name order. Video will play on the hour and the half-hour. Upload a new set of image files to /var/media/slideshow, and the slideshow will automatically reset to the new content within 60 seconds. <file_sep>#!/bin/bash ##################################### # video.sh # # Author: ##################################### # Capture first video filename to variable VIDEO=`ls /var/media/videos/* | head -n 1` # Play video file, output sound to HDMI /usr/bin/omxplayer -o hdmi $VIDEO
71c158fb132fe95666b0211e4387e3338caa0b39
[ "Markdown", "Python", "PHP", "Shell" ]
12
Shell
hgw3lls/genetics_PIdisplay
22ef0d9d88afe9601d03cfc220c19f99195bcd61
b4f7380295c7dffbd510870a5688ceffc71aecd0
refs/heads/master
<file_sep>var j_textarea = document.getElementById("j-textarea"); j_textarea.setAttribute("style", "-webkit-transform-origin:0px 0px 0px;opacity:1;-webkit-transform:scale(1, 1);direction:ltr;float:left;");<file_sep>package me.zogodo.baidufanyilite; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import java.io.IOException; public class MainActivity extends AppCompatActivity { //region 成员变量 MyWebView webview_baidu; String url_baidu_fy = "https://fanyi.baidu.com/#auto/zh/"; String js_baidu; String css_baidu; long exitTime = 0; //endregion @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); //region 初始化 js css try { js_baidu = ActivityReadFile.readTextFileFromRaw(this, R.raw.js_baidu); css_baidu = ActivityReadFile.readTextFileFromRaw(this, R.raw.css_baidu); } catch (IOException e) { e.printStackTrace(); } //endregion webview_baidu = new MyWebView(this); webview_baidu.VebViewInit(url_baidu_fy, js_baidu, css_baidu); this.setContentView(webview_baidu); } @Override public void onBackPressed() { /* if (webview_baidu.canGoBack()) { webview_baidu.goBack(); return; } */ // 判断是否可后退,是则后退,否则退出程序 if (((System.currentTimeMillis() - exitTime) > 3000)) { Toast.makeText(getApplicationContext(), "再按一次返回 退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { finish(); System.exit(0); } } }
fabce27429813c135d996890ba71b25bf826bffb
[ "JavaScript", "Java" ]
2
JavaScript
zogodo/BaiduFanyiLite
2034dd4ba45f77c2c0e8ed0fb22f3f966640b573
06f23450cb6a503102a67825e680134b55f9e9a4
refs/heads/master
<repo_name>luist1228/SambilServices<file_sep>/pub.py import ssl import sys import json import random import time import paho.mqtt.client as mqtt import paho.mqtt.publish import numpy as np import datetime import psycopg2 as psy import pandas as pd import csv import datetime centrada = psy.connect(host = 'localhost', user= 'postgres', password ='<PASSWORD>', dbname= 'Servicio Camara') ctienda = psy.connect(host = 'localhost', user= 'postgres', password ='<PASSWORD>', dbname= 'Servicio Tienda') cmesa = psy.connect(host = 'localhost', user= 'postgres', password ='<PASSWORD>', dbname= 'Servicio Mesa') knownPeople = [] peopleInside = [] peopleSitting = [] peopleInStore = [] #Aux lists for car's simulation parkingCars = [] queueDrivers = [] knownCars = [] def on_connect(): print("Pub connected!") def main(): client = mqtt.Client("Publisher", False) client.qos = 0 client.connect(host="localhost") #Database variables numAccess = queryNumAccess() storeBeaconID = queryStoreBeaconID() tableBeaconID = queryTableBeaconID() currentTime = datetime.datetime.now().replace(hour=8, minute=0) days = 31 #The main loop! while(days > 0): #This is while the mall is still open while(currentTime.hour < 22): if(int(np.random.uniform(0,3)) == 0): #Get some car in pubCarEntrance(client, currentTime) if(int(np.random.uniform(0,2)) != 0): pubEntrance(client,numAccess,currentTime) currentTime = currentTime + datetime.timedelta(minutes=1) if(int(np.random.uniform(0,3)) == 0): pubStores(client,storeBeaconID,currentTime) print() if(int(np.random.uniform(0,3)) == 0): pubTables(client,tableBeaconID,currentTime) currentTime = currentTime + datetime.timedelta(minutes=1) currentTime = currentTime + datetime.timedelta(minutes=6) #time.sleep(0.2) #At this point, the mall is closing and we start to get people out while((len(peopleInside) + len(peopleInStore) + len(peopleSitting) + len(parkingCars)) > 0): ran = np.random.uniform(0, len(peopleInside)) while(ran > 0): cameraID = int(np.random.uniform(1 , numAccess)) payload = leavingMall(cameraID, currentTime) if(payload["time"] != "null"): client.publish("Sambil/Camaras/Salida", json.dumps(payload), qos=0) print("Saliendo (C.C.) --> ", end='') print(payload) ran -= 1 ran = np.random.uniform(0, len(parkingCars)) while(ran > 0): data = drivingOut(currentTime) payload = data[0] payload2 = data[1] if(payload["time"] != "null"): print("Saliendo (C.C.) --> ", end='') print(payload) client.publish("Sambil/Camaras/Saliendo", json.dumps(payload), qos=0) print("Saliendo (C.C.) --> ", end='') print(payload2) client.publish("Sambil/Estacionamiento/Saliendo", json.dumps(payload2), qos=0) ran -= 1 ran = np.random.uniform(0, len(peopleSitting)) while(ran > 0): tableUser = stadingUp() payload = { "beaconID": str(tableUser[1]), "macAddress": str(tableUser[0][0]), "time": str(currentTime) } client.publish("Sambil/Mesa/Parado", json.dumps(payload), qos=0) print("Parado (Mesa) --> ", end='') print(payload) ran -= 1 ran = np.random.uniform(0, len(peopleInStore)) while(ran > 0): storeUser = leavingStore(client, currentTime) payload = { "beaconID": str(storeUser[1]), "macAddress": str(storeUser[0][0]), "time": str(currentTime) } currentTime += datetime.timedelta(minutes=5) if(storeUser[0] != "null"): #Beacons only detect users with smartphones client.publish("Sambil/Tienda/Saliendo", json.dumps(payload), qos=0) print("Saliendo (Tienda) --> ", end='') print(payload) ran -= 1 #time.sleep(0.1) days -= 1 currentTime = datetime.timedelta(days=1) + currentTime.replace(hour=8, minute=0) getDataFromDB() insertData(knownPeople) #Publisher's Methods def pubEntrance(client, numAccess, currentTime): cameraID = int(np.random.uniform(1 , numAccess)) if((int(np.random.uniform(0,3)) != 1) or (len(peopleInside) == 0)): if(int(np.random.uniform(0,5)) == 1 and len(knownPeople) > 0): #Random to get someone known inside payload = enteringMallAgain(cameraID, currentTime) else: payload = enteringMall(cameraID, currentTime) topic = "Entrada" else: payload = leavingMall(cameraID, currentTime) topic = "Salida" if(payload["time"] != "null"): client.publish("Sambil/Camaras/" + topic, json.dumps(payload), qos=0) print(topic + " (C.C.) --> ", end='') print(payload) def pubCarEntrance(client, currentTime): if((int(np.random.uniform(0,3)) != 1) or (len(parkingCars) == 0)): if((int(np.random.uniform(0,5) == 0) and (len(knownPeople) > 0))): #Probably you know the person data = knownDrivingIn(currentTime) payload = data[0] payload2 = data[1] newCar = data[2] else: newCar = True payload = drivingIn(currentTime) ran = np.random.uniform(1,5) currentTime += datetime.timedelta(minutes=ran) payload2 = enteringMall(4, currentTime) #Validation to see if there is really someone parking if(payload["time"] != "null"): print("Entrando (C.C.) --> ", end='') print(payload) client.publish("Sambil/Estacionamiento/Entrada", json.dumps(payload), qos=0) print("Entrando (C.C.) --> ", end='') print("-----------------------------------------------------------------------------------------------------") print(payload2) print("-----------------------------------------------------------------------------------------------------") client.publish("Sambil/Camaras/Entrada", json.dumps(payload2), qos=0) driver = [payload2["macAddress"], payload2["gender"], int(payload2["age"])] #This is like "parking" the car inside a list parkingCars[len(parkingCars)-1].append(driver) if(driver[0] != "null" and newCar): knownCars.append([payload["numberPlate"], driver[0]]) else: data = drivingOut(currentTime) payload = data[0] payload2 = data[1] if(payload["time"] != "null"): print("Saliendo (C.C.) --> ", end='') print(payload) client.publish("Sambil/Camaras/Saliendo", json.dumps(payload), qos=0) print("Saliendo (C.C.) --> ", end='') print(payload2) client.publish("Sambil/Estacionamiento/Saliendo", json.dumps(payload2), qos=0) def pubStores(client, storeBeaconID, currentTime): if(len(peopleInside) > 0): if(int(np.random.uniform(0,3)) == 1 and len(peopleInStore) > 0): #Get someone out of store storeUser = leavingStore(client, currentTime) topic = "Saliendo" else: #Get someone in storeUser = enteringStore(storeBeaconID) topic = "Entrando" payload = { "beaconID": str(storeUser[1]), "macAddress": str(storeUser[0][0]), "time": str(currentTime) } if(storeUser[0] != "null"): #Beacons only detect users with smartphones client.publish("Sambil/Tienda/" + topic, json.dumps(payload), qos=0) print(topic + " (Tienda) --> ", end='') print(payload) def pubTables(client, tableBeaconID, currentTime): if(len(peopleInside) > 0): if(int(np.random.uniform(0,3)) == 1 and len(peopleSitting) > 0): tableUser = stadingUp() topic = "Parado" else: tableUser = sitting(tableBeaconID) topic = "Sentado" payload = { "beaconID": str(tableUser[1]), "macAddress": str(tableUser[0][0]), "time": str(currentTime) } print(topic + " (Mesa) --> ", end='') print(payload) client.publish("Sambil/Mesa/" + topic, json.dumps(payload), qos=0) def pubSales(client, buyer, currentTime): if(int(np.random.uniform(0,1)) == 0): avgPrice = 150 stdPrice = 100 price = round(np.random.normal(avgPrice, stdPrice),2) while(price <= 0): price = round(np.random.normal(avgPrice, stdPrice),2) payload = buying(buyer, price, currentTime) if(buyer[0] != "null" and len(buyer[0]) == 3): counter = 0 while(counter < len(knownPeople)): if(buyer[0][0] == knownPeople[counter][0]): knownPeople[counter].append(payload["personID"]) knownPeople[counter].append(payload["name"]) knownPeople[counter].append(payload["lastname"]) break counter += 1 print("Compra (Tienda) --> ", end='') print(payload) client.publish("Sambil/Tienda/Compra", json.dumps(payload), qos=0) #People's Actions def enteringMall(cameraID, currentTime): gender = int(np.random.uniform(0, 2)) if(gender == 1): gender = "M" else: gender = "F" minAge = 0 if(cameraID == 4): macAddress = queueDrivers.pop() minAge = 18 elif(int(np.random.uniform(0,4)) != 1): macAddress = str(getMacAddress()) minAge = 9 else: macAddress = "null" age = int(np.random.normal(35,15)) while((age < minAge) or (age > 90)): age = int(np.random.normal(35,15)) correctData = False while(not correctData): personData = random.choice(dataPeople) if(gender == personData["gender"]): correctData = True personID = getPersonID(age) name = personData["first_name"] lastname = personData["last_name"] person = [macAddress,gender,age,personID,name,lastname] payload = { "cameraID": str(cameraID), "gender": str(person[1]), "age": str(person[2]), "macAddress": str(person[0]), "time": str(currentTime) } peopleInside.append(person) if(macAddress != "null"): knownPeople.append(person) return payload def leavingMall(cameraID, currentTime): people = peopleInside[int(np.random.uniform(0, len(peopleInside)))] counter = 0 hasACar = False while(counter < len(parkingCars)): print(parkingCars[counter]) if((people[0] == parkingCars[counter][1][0]) and (people[1] == parkingCars[counter][1][1]) and (people[2] == parkingCars[counter][1][2])): hasACar = True break counter += 1 if(hasACar): print(people) currentTime = "null" else: peopleInside.remove(people) payload = { "cameraID": str(cameraID), "macAddress": str(people[0]), "time": str(currentTime) } return payload def enteringMallAgain(cameraID, currentTime): person = random.choice(knownPeople) counter = 0 gettingKnownPeople = True while(counter < len(peopleInside) or counter < len(peopleInStore) or counter < len(peopleSitting)): if(counter < len(peopleInside)): if(person[0] == peopleInside[counter][0]): gettingKnownPeople = False break if(counter < len(peopleInStore)): if(person[0] == peopleInStore[counter][0][0]): gettingKnownPeople = False break if(counter < len(peopleSitting)): if(person[0] == peopleSitting[counter][0][0]): gettingKnownPeople = False break counter += 1 if(gettingKnownPeople): peopleInside.append(person) else: currentTime = "null" payload = { "cameraID": str(cameraID), "gender": str(person[1]), "age": str(person[2]), "macAddress": str(person[0]), "time": str(currentTime) } return payload def enteringStore(storeBeaconID): beaconID = random.choice(storeBeaconID) ran = int(np.random.uniform(0, len(peopleInside))) storeUser = [peopleInside[ran], beaconID] peopleInside.remove(storeUser[0]) peopleInStore.append(storeUser) return storeUser def leavingStore(client, currentTime): storeUser = random.choice(peopleInStore) #Possible sale before getting out pubSales(client, storeUser, currentTime) peopleInStore.remove(storeUser) peopleInside.append(storeUser[0]) return storeUser def buying(buyer, price, currentTime): if(len(buyer[0])==3): correctData = False while(not correctData): personData = random.choice(dataPeople) if(buyer[0][1] == personData["gender"]): correctData = True age = buyer[0][2] personID = getPersonID(age) name = personData["first_name"] lastname = personData["last_name"] else: personID = buyer[0][3] name = buyer[0][4] lastname = buyer[0][5] #Case for random ID if(int(np.random.uniform(0,1)) == 0): randomPerson = random.choice(knownPeople) counter = 0 inside = False while(counter < len(peopleInside)): if(randomPerson[0] == peopleInside[counter][0]): inside = True counter += 1 if(len(randomPerson) > 3 and (not inside)): personID = randomPerson[3] payload = { "beaconID": str(buyer[1]), "macAddress": str(buyer[0][0]), "name": str(name), "lastname": str(lastname), "personID": str(personID), "time": str(currentTime), "price": str(price) } return payload def sitting(tableBeaconID): beaconID = random.choice(tableBeaconID) ran = int(np.random.uniform(0, len(peopleInside))) tableUser = [peopleInside[ran], beaconID] peopleInside.remove(tableUser[0]) peopleSitting.append(tableUser) return tableUser def stadingUp(): tableUser = random.choice(peopleSitting) peopleSitting.remove(tableUser) peopleInside.append(tableUser[0]) return tableUser def drivingIn(currentTime): if(int(np.random.uniform(0,201)) != 0): numberPlate = getNumberPlate() else: numberPlate = "null" if(int(np.random.uniform(0,4)) != 1): macAddress = str(getMacAddress()) else: macAddress = "null" parkingCars.append([numberPlate]) queueDrivers.append(macAddress) payload = { "numberPlate": str(numberPlate), "macAddress": str(macAddress), "time": str(currentTime) } return payload def knownDrivingIn(currentTime): print("Known people in car is coming") newCar = False if(np.random.uniform(0,4) != 0): #A person who already has come with a car data = random.choice(knownCars) person = [] counter = 0 while(counter < len(knownPeople)): if(data[1][0] == knownPeople[counter][0]): person = knownPeople[counter] break counter += 1 if(np.random.uniform(0,20)): #They could have another car numberPlate = getNumberPlate() newCar = True else: numberPlate = data[0] else: #Probably hasn't come with its car... Yet person = random.choice(knownPeople) numberPlate = getNumberPlate() newCar = True gettingKnownPeople = True while(counter < len(peopleInside) or counter < len(peopleInStore) or counter < len(peopleSitting)): if(counter < len(peopleInside)): if(person[0] == peopleInside[counter][0]): gettingKnownPeople = False break if(counter < len(peopleInStore)): if(person[0] == peopleInStore[counter][0][0]): gettingKnownPeople = False break if(counter < len(peopleSitting)): if(person[0] == peopleSitting[counter][0][0]): gettingKnownPeople = False break counter += 1 payload = { "numberPlate": str(numberPlate), "macAddress": str(person[0]), "time": str(currentTime) } ran = np.random.uniform(1,5) currentTime += datetime.timedelta(minutes=ran) payload2 = { "cameraID": "4", "gender": str(person[1]), "age": str(person[2]), "macAddress": str(person[0]), "time": str(currentTime) } if(not gettingKnownPeople): payload["time"] = "null" personData = [payload, payload2, newCar] return personData def drivingOut(currentTime): counterPeople = 0 person = [] dataInside = [] while(counterPeople < len(parkingCars)): available = False person = random.choice(parkingCars) counter = 0 while(counter < len(peopleInside)): if(person[1][0] == peopleInside[counter][0] and person[1][1] == peopleInside[counter][1] and person[1][2] == peopleInside[counter][2]): dataInside = peopleInside[counter] available = True break counter += 1 if(available): break counterPeople += 1 if(not available): currentTime = "null" else: peopleInside.remove(dataInside) parkingCars.remove(person) payload = { "cameraID": "4", "macAddress": str(person[1][0]), "time": str(currentTime) } if(currentTime != "null"): ran = np.random.uniform(1,5) currentTime += datetime.timedelta(minutes=ran) payload2 = { "numberPlate": str(person[0]), "macAddress": str(person[1][0]), "time": str(currentTime) } data = [payload, payload2] return data #Logical Methods def getMacAddress(): macAddress = "" counter = 0 while(counter < 12): if(counter%2 != 1 and counter > 0): macAddress += ":" macAddress += str(random.choice('0123456789ABCDEF')) counter += 1 return macAddress def getPersonID(age): if(age > 70): personID = int(np.random.uniform(3000000,600000)) elif(age <= 70 and age >= 61): personID = int(np.random.uniform(7000000,3000000)) elif(age <= 60 and age >= 51): personID = int(np.random.uniform(9000000,7000000)) elif(age <= 50 and age >= 41): personID = int(np.random.uniform(12000000,9000000)) elif(age <= 40 and age >= 31): personID = int(np.random.uniform(15000000,12000000)) elif(age <= 30 and age >= 21): personID = int(np.random.uniform(26000000,15000000)) elif(age <= 20 and age >= 16): personID = int(np.random.uniform(30000000,26000000)) elif(age <= 15 and age >= 8): personID = int(np.random.uniform(36000000,30000000)) else: personID = 0 return personID def getNumberPlate(): numberPlate = "" counter = 0 while(counter < 7): if(counter > 1 and counter < 5): numberPlate += str(random.choice('0123456789')) else: numberPlate += str(random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ')) counter += 1 return numberPlate def getJsonData(): with open('database.json') as json_file: data = json.load(json_file) return data['nombres'] dataPeople = getJsonData() #Query Methods def queryNumAccess(): sql='''SELECT * FROM public.camara;''' df = pd.read_sql_query(sql, centrada) camaras = df.count()[0] print("cantidad de camaras "+ str(camaras)) return camaras def queryStoreBeaconID(): sql='''select b."id" from beacon as b inner join tienda as t on t."fkbeacon"=b."id"''' df = pd.read_sql_query(sql, ctienda) Lista = [] for index, row in df.iterrows(): Lista.insert(index, row["id"]) print(Lista) return Lista def queryTableBeaconID(): sql='''select b."id" from beacon as b inner join mesa as mesa on mesa."fkbeacon"=b."id" ''' df = pd.read_sql_query(sql, cmesa) Lista = [] for index, row in df.iterrows(): Lista.insert(index, row["id"]) print(Lista) return Lista def insertData(data): with open('csvFiles/poll.csv','a', newline='') as csvfile: filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) filewriter.writerow(['MacAddress', 'Name', 'Lastname', 'ID', 'Sex', 'Age']) for person in data: filewriter.writerow([person[0], person[4], person[5], person[3], person[1], person[2]]) def getDataFromDB(): sql = '''select count(e."id") Sales , DATE(e."fecha") as Date , e."fktienda" as StoreID, SUM(e.monto) as Amount from compra as e group by Date, StoreID order by Date desc''' df = pd.read_sql_query(sql,ctienda) print(df) with open('csvFiles/sales.csv','a',newline='') as csvfile: filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) filewriter.writerow(['Sales','StoreID','Date','Amount']) dayCounter = 1 target = 1 for index, row in df.iterrows(): filewriter.writerow([row['sales'], row['storeid'], dayCounter, int(row['amount'])]) target += 1 if((index+1)%3 == 0): dayCounter += 1 target = 1 if __name__ == "__main__": main()<file_sep>/sub.py import ssl import sys import psycopg2 import pandas as pd import paho.mqtt.client import json centrada = psycopg2.connect(host = 'localhost', user= 'postgres', password ='<PASSWORD>', dbname= 'Servicio Camara') centrada.autocommit = True ctienda = psycopg2.connect(host = 'localhost', user= 'postgres', password ='<PASSWORD>', dbname= 'Servicio Tienda') ctienda.autocommit = True cmesa = psycopg2.connect(host = 'localhost', user= 'postgres', password ='<PASSWORD>', dbname= 'Servicio Mesa') cmesa.autocommit = True def on_connect(client, userdata, flags, rc): print('Conectado (%s)' % client._client_id) client.subscribe(topic='Sambil/#', qos = 0) def on_message_C(client,userdata,message): c = json.loads(message.payload) print('------------------------------') if ((message.topic=="Sambil/Camaras/Entrada")) : if (c["macAddress"]!="null"): print(c) print('topic: %s' % message.topic) cur = centrada.cursor() sql = '''CALL Personaconmac(%s, %s, %s, %s, %s)''' cur.execute(sql, (c["macAddress"],c["gender"], c["age"],c["time"],c["cameraID"])) centrada.commit() else: print(c) print('topic: %s' % message.topic) cur = centrada.cursor() sql = '''INSERT INTO public.epersona(sexo, edad, fecha, fkcamara) VALUES (%s,%s,%s,%s);''' cur.execute(sql, (c["gender"], c["age"],c["time"],c["cameraID"])) centrada.commit() else: if (c["macAddress"]!="null"): print(c) print('topic: %s' % message.topic) cur = centrada.cursor() sql = '''Call Salidaconmac(%s,%s,%s)''' cur.execute(sql, (c["macAddress"],c["time"],c["cameraID"])) centrada.commit() else: print(c) print('topic: %s' % message.topic) cur = centrada.cursor() sql = '''INSERT INTO public.spersona(fecha, fkcamara) VALUES ( %s, %s);''' cur.execute(sql, (c["time"],c["cameraID"])) centrada.commit() def on_message_A(client,userdata,message): a = json.loads(message.payload) print('------------------------------') def on_message_M(client,userdata,message): m = json.loads(message.payload) print('------------------------------') if (message.topic=="Sambil/Mesa/Parado") : if (m["macAddress"]!="null"): print(m) print('topic: %s' % message.topic) cur = cmesa.cursor() sql = '''INSERT INTO public.iomesa( fecha, io, fkbeacon, mac) VALUES (%s, %s, %s, %s);''' cur.execute(sql, (m["time"], False,m["beaconID"],m["macAddress"] )) cmesa.commit() else: print(m) print('topic: %s' % message.topic) cur = cmesa.cursor() sql = '''INSERT INTO public.iomesa( fecha, io, fkbeacon) VALUES (%s, %s, %s);''' cur.execute(sql, (m["time"], False,m["beaconID"] )) cmesa.commit() else: if (m["macAddress"]!="null"): print(m) print('topic: %s' % message.topic) cur = cmesa.cursor() sql = '''INSERT INTO public.iomesa( fecha, io, fkbeacon, mac) VALUES (%s, %s, %s, %s);''' cur.execute(sql, (m["time"], True ,m["beaconID"],m["macAddress"] )) cmesa.commit() else: print(m) print('topic: %s' % message.topic) cur = cmesa.cursor() sql = '''INSERT INTO public.iomesa( fecha, io, fkbeacon) VALUES (%s, %s, %s);''' cur.execute(sql, (m["time"], True ,m["beaconID"] )) cmesa.commit() def on_message_T(client,userdata,message): t = json.loads(message.payload) print('------------------------------') if (message.topic=="Sambil/Tienda/Entrando") : if (t["macAddress"]!="null"): print(t) print('topic: %s' % message.topic) cur = ctienda.cursor() sql = '''INSERT INTO public.iotienda( fecha, io, fkbeacon, mac) VALUES ( %s, %s, %s, %s);''' cur.execute(sql, (t["time"],True,t["beaconID"],t["macAddress"])) ctienda.commit() else: print(t) print('topic: %s' % message.topic) cur = ctienda.cursor() sql = '''INSERT INTO public.iotienda( fecha, io, fkbeacon) VALUES ( %s, %s, %s);''' cur.execute(sql, (t["time"],True,t["beaconID"])) ctienda.commit() if (message.topic=="Sambil/Tienda/Saliendo") : if (t["macAddress"]!="null"): print(t) print('topic: %s' % message.topic) cur = ctienda.cursor() sql = '''INSERT INTO public.iotienda( fecha, io, fkbeacon, mac) VALUES ( %s, %s, %s, %s);''' cur.execute(sql, (t["time"],False,t["beaconID"],t["macAddress"])) ctienda.commit() else: print(t) print('topic: %s' % message.topic) cur = ctienda.cursor() sql = '''INSERT INTO public.iotienda( fecha, io, fkbeacon) VALUES ( %s, %s, %s);''' cur.execute(sql, (t["time"],False,t["beaconID"])) ctienda.commit() if (message.topic=="Sambil/Tienda/Compra") : if (t["macAddress"]!="null"): print(t) print('topic: %s' % message.topic) cur = ctienda.cursor() sql = '''INSERT INTO public.cliente( nombre, apellido, cedula) VALUES (%s, %s, %s);''' cur.execute(sql, (t["name"],t["lastname"],t["personID"])) ctienda.commit() cur = ctienda.cursor() sql = '''Call Clientenaconmac(%s, %s, %s, %s)''' cur.execute(sql, (t["personID"],t["time"],t["price"],t["beaconID"])) ctienda.commit() else: print(t) print('topic: %s' % message.topic) cur = ctienda.cursor() sql = '''INSERT INTO public.compra( monto, fecha, fktienda) VALUES (%s, %s, %s);''' cur.execute(sql, (t["price"],t["time"],t["beaconID"])) ctienda.commit() def main(): client = paho.mqtt.client.Client(client_id='Actividad Sambil',clean_session=False) client.on_connect = on_connect client.message_callback_add('Sambil/Camaras/#', on_message_C) client.message_callback_add('Sambil/Estacionamiento/#', on_message_A) client.message_callback_add('Sambil/Mesa/#', on_message_M) client.message_callback_add('Sambil/Tienda/#', on_message_T) client.connect(host='localhost') client.loop_forever() if __name__ == '__main__': main() sys.exit(0)<file_sep>/AI/IA.py import numpy as np import matplotlib.pyplot as plt import pandas as pd import io from sklearn.neural_network import MLPRegressor from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn import datasets from sklearn import tree import time def runLinearRegression(day): df = pd.read_csv('csvFiles/sales.csv') x = df['Date'] y = df['Sales'] X = x[:,np.newaxis] X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2) model = MLPRegressor(solver='lbfgs',alpha=1e-5,hidden_layer_sizes=(3,3),random_state=1) counter = 0 print("AI is learning...") for i in range(1000): model.fit(X_train,y_train) if(model.score(X_train,y_train) > 0.80): break counter += 1 x_new = np.array([100]).reshape((-1,1)) y_new = model.predict(x_new) print("Prediction for day " + str(day) + ": ", y_new) print("R^2 = " + str(model.score(X_train,y_train))) x_new= np.array([0,0,day]).reshape((-1,1)) X2 = np.concatenate((X, x_new)) plt.scatter(x, y) plt.plot(X2, model.predict(X2), color='red', linewidth=3) plt.title('Neural Network Regression') plt.xlabel('Days') plt.ylabel('Sales') plt.show() def runSalesTree(storeID,salesNumber): df = pd.read_csv('csvFiles/sales.csv') x = [] for index, row in df.iterrows(): x.append([row['StoreID'], (row['Sales'])]) x = np.array(x) y = df['Amount'] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.5) saman = tree.DecisionTreeClassifier() saman = saman.fit(x_train, y_train) print("And that store, with " + str(salesNumber) + " sales could get $" + str(saman.predict([[storeID, salesNumber]])[0])) def runSalesNeuralNetwork(storeID,day): df = pd.read_csv('csvFiles/sales.csv') x = [] for index, row in df.iterrows(): x.append([row['StoreID'],row['Sales']]) y = df['Date'] x = np.array(x) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.5) patricio = MLPClassifier(max_iter=10000000, hidden_layer_sizes=(20,55)) patricio.fit(x_train, y_train) inputN = [storeID, day] inputArray = np.array(inputN).reshape(1, -1) #Neural Network prediction sales = patricio.predict(inputArray)[0] print("At day " + str(day) + " it's expected for the store ID(" + str(storeID) + ") to have " + str(sales) + " sales.") print("Neural Network precisson: " + str(patricio.score(x_train, y_train))) runSalesTree(storeID, sales) <file_sep>/POSTGRES/BDmesas.sql create table mesa( id serial primary key, sillas int, fkbeacon int REFERENCES beacon(id) ); create table beacon( id serial primary key, modelo varchar(10) ); create table iomesa( id serial primary key, fecha timestamp, io boolean, fkbeacon int references beacon(id), mac varchar(30) ); <file_sep>/POSTGRES/BDtiendas.sql create table beacon( id serial primary key, modelo varchar(20) ); create table tienda ( id serial primary key, nombre varchar(20), fkbeacon int references beacon(id) ); create table cliente ( id serial primary key, nombre varchar(30), apellido varchar(30), cedula bigint unique ); create table compra( id serial primary key, monto float, fecha timestamp, fkcliente int references cliente(id), fktienda int references tienda (id) ); create table iotienda( id serial primary key, fecha timestamp, io boolean, fkbeacon int references beacon(id), mac varchar(30) ); <file_sep>/CSVcontroller.py import csv import datetime import pandas as pd import psycopg2 as psy conn=psy.connect(host = 'localhost', user= 'postgres', password ='<PASSWORD>', dbname= 'Sambil') def insertData(date, data): with open('csvFiles/poll.csv','a', newline='') as csvfile: filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) filewriter.writerow(['MacAddress', 'Name', 'Lastname', 'ID', 'Sex', 'Age']) for person in data: filewriter.writerow([person[0], person[4], person[5], person[3], person[1], person[2]]) def getDataFromDB(): sql = '''SELECT count(c.id) AS sales, substring(CAST(c.fecha AS TEXT) from 1 for 10) AS date, s.fkbeacon_id as storeid, SUM(c.total) AS amount FROM models_compra AS c JOIN models_tienda AS s ON s.fkbeacon_id = c.fktienda_id GROUP BY date, s.fkbeacon_id ORDER BY date DESC''' df = pd.read_sql_query(sql,conn) with open('csvFiles/sales.csv','a',newline='') as csvfile: filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) filewriter.writerow(['Sales','StoreID','Date','Amount']) dayCounter = 1 target = 1 for index, row in df.iterrows(): filewriter.writerow([row['sales'], row['storeid'], dayCounter, int(row['amount'])]) target += 1 if((index+1)%3 == 0): dayCounter += 1 target = 1 <file_sep>/POSTGRES/BDcamaras.sql create table Entrada( id serial primary key, nombre varchar(20) ); create table Camara( id serial primary key, fkEntrada int references Entrada(id), modelo varchar(20) ); create table Persona ( id serial primary key, mac varchar(30) ); create table ePersona ( id serial primary key, sexo varchar(10), edad int, fecha timestamp, fkpersona int references Persona(id), fkCamara int references Camara(id) ); create table sPersona ( id serial primary key, fecha timestamp, fkpersona int references Persona(id), fkCamara int references Camara(id) ); create table Carro( id serial primary key, placa varchar(20), mac varchar(30) ); create table ecarro( id serial primary key, fecha timestamp, fkcamara int references Camara(id), fkcarro int references Carro(id) ); create table scarro( id serial primary key, fecha timestamp, fkcamara int references Camara(id), fkcarro int references Carro(id) );
59140a964605cbda4eb12607d3b407a3a36b9bae
[ "SQL", "Python" ]
7
Python
luist1228/SambilServices
08826cfddebde1d67d1803951b9fa4590bdb52e5
62f5dabfdb9f590118e126ca8951fc8a50b2eb61
refs/heads/master
<file_sep>export class PlanCompleted_POST { item: number value: string time: string } export class PlanCompleted_GET extends PlanCompleted_POST { id: number }<file_sep>import { Component, OnInit } from '@angular/core'; import { ArticleService } from '../../core/services'; import { Subscription } from '../../../../node_modules/rxjs'; import { Article_GET } from '../../core/models'; import { sort_by, reverse_by } from '../../core/fun'; @Component({ selector: 'app-blog-recently', templateUrl: './blog-recently.component.html', styleUrls: ['./blog-recently.component.styl'] }) export class BlogRecentlyComponent implements OnInit { recently_articles: Article_GET[] = [] subscription: Subscription constructor( private articleService: ArticleService ) { } ngOnInit() { this.articleService.get() this.subscription = this.articleService.articles$ .subscribe( articles => this.recently_articles = reverse_by(articles, 'created').slice(0, 3).map(article => { const _article = article _article.link = `blog/${article.id}` return _article }), error => console.log(error) ) } } <file_sep>import { NgModule } from "../../../node_modules/@angular/core"; import { MaterialModule } from '../material/material.module'; import { FilterComponent } from './filter/filter.component'; import { CommonModule } from '../../../node_modules/@angular/common'; import { OrderComponent } from './order/order.component'; import { AddBUttonComponent } from './add-button/add.component'; import { RouterModule } from '../../../node_modules/@angular/router'; import { LMarkdownEditorModule } from '../../../node_modules/ngx-markdown-editor'; import { FormsModule } from '../../../node_modules/@angular/forms'; import { GoBackButtonComponent } from './go-back-button/go-back-button.component'; @NgModule({ declarations: [ FilterComponent, OrderComponent, AddBUttonComponent, GoBackButtonComponent ], imports: [ CommonModule, MaterialModule, RouterModule, LMarkdownEditorModule, FormsModule ], exports: [ FilterComponent, OrderComponent, AddBUttonComponent, GoBackButtonComponent ] }) export class SharedModule {}<file_sep>export class PlanPersonal_POST { name: string value: string start: string end: string } export class PlanPersonal_GET extends PlanPersonal_POST { id: number } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { Article_GET } from '../../core/models'; @Component({ selector: 'app-article-detail', templateUrl: './article-detail.component.html', styleUrls: ['./article-detail.component.styl'] }) export class ArticleDetailComponent implements OnInit { @Input() article: Article_GET @Input() categories category: string constructor() { } ngOnInit() { } ngOnChanges() { this.handleGetCategory() } handleGetCategory() { if (!this.categories) { return } const category = this.categories.find(item => item.id === this.article.category) if (category) { this.category = category.name } } } <file_sep>import { Component, OnInit, Inject } from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '../../../../node_modules/@angular/material/dialog'; import { User } from '../../core/models'; import { UserService } from '../../core/services'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.styl'] }) export class HeaderComponent implements OnInit { public nav: object = [ { link: '', hans: '首页' }, { link: 'blog', hans: '博客' }, { link: 'read', hans: '阅读' }, { link: 'plan', hans: '计划' } ] public user: User = { username: '', password: '' } public cache constructor( public loginDialog: MatDialog, public logoutDialog: MatDialog, private userService: UserService ) { } ngOnInit() { this.cache = window.localStorage } openLoginDialog(): void { const dialogRef = this.loginDialog.open(LoginDialog, { width: '250px', data: { user: this.user } }) dialogRef.afterClosed().subscribe(result => { if (result !== false) { this.user = result.user this.userService.login(this.user) } console.log(result) }) } openLogoutDialog(): void { const dialogRef = this.logoutDialog.open(LogoutDialog, { width: '250px', }) dialogRef.afterClosed().subscribe(result => { if (result) { this.userService.logout() } console.log(result) }) } } @Component({ selector: 'login-dialog', templateUrl: './login-dialog.html' }) export class LoginDialog { isLogin: boolean = false constructor( public dialogRef: MatDialogRef<LoginDialog>, @Inject(MAT_DIALOG_DATA) public data ) {} } @Component({ selector: 'logout-dialog', templateUrl: './logout-dialog.html' }) export class LogoutDialog { }<file_sep>export * from './completed.service' export * from './personal.service' export * from './web.service'<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Option } from '../../core/models/data/options'; @Component({ selector: 'app-order', templateUrl: './order.component.html', styleUrls: ['./order.component.styl'] }) export class OrderComponent implements OnInit { @Input() orders: Option[] @Output() orderSelect = new EventEmitter() selectedOrder: string = 'id' lastOrder: string = 'id' constructor() { } ngOnInit() { } ngDoCheck() { if (this.selectedOrder === this.lastOrder) { return } this.lastOrder = this.selectedOrder this.orderSelect.emit(this.selectedOrder) } } <file_sep>export * from './blog' export * from './book' export * from './plan' export * from './user'<file_sep>export * from './user.service' export * from './token.service'<file_sep>export class Option { value: any hans: string }<file_sep>import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http'; import { environment } from '../../../environments/environment'; @Injectable( // { // providedIn: 'root' // } ) export class HttpTokenInterceptor implements HttpInterceptor { private notTokenUrl: string[] = ['api-token-auth', 'api-token-verify'] constructor( ){} intercept(req: HttpRequest<any>, next: HttpHandler): any { if (req.method === 'GET') { return next.handle(req) } if (this.notTokenUrl.indexOf(req.url.split('/')[3]) > -1){ return next.handle(req) } const headersConfig = { // 'Content-Type': 'application/json', // 'Accept': 'application/json' }; const token = window.localStorage['jwtToken'] if (token) { headersConfig['Authorization'] = `JWT ${token}`; } const request = req.clone({ setHeaders: headersConfig }); return next.handle(request) } } <file_sep>export const environment = { production: true, api_url: 'http://192.168.127.12:82/' }; <file_sep>export class User { username: string password: string } export class User_SAVE extends User { jwtToken: string }<file_sep>import { NgModule } from '@angular/core'; import { HomeRoutingModule } from './home-routing.module'; import { HomeComponent } from './home/home.component'; import { BlogRecentlyComponent } from './blog-recently/blog-recently.component'; import { ReadRecentlyComponent } from './read-recently/read-recently.component'; import { PlanRecentlyComponent } from './plan-recently/plan-recently.component'; import { CommonModule } from '../../../node_modules/@angular/common'; import { SharedModule } from '../shared/shared.module'; import { MarkdownModule } from '../../../node_modules/ngx-markdown'; @NgModule({ imports: [ HomeRoutingModule, CommonModule, MarkdownModule ], declarations: [ HomeComponent, BlogRecentlyComponent, ReadRecentlyComponent, PlanRecentlyComponent ] }) export class HomeModule {} <file_sep>import { Component, OnInit } from '@angular/core'; import { BookService } from '../../core/services'; import { Book_GET } from '../../core/models'; import { Subscription } from '../../../../node_modules/rxjs'; import { reverse_by } from '../../core/fun'; @Component({ selector: 'app-read-recently', templateUrl: './read-recently.component.html', styleUrls: ['./read-recently.component.styl'] }) export class ReadRecentlyComponent implements OnInit { recently_books: Book_GET[] = [] subscription: Subscription constructor( private bookService: BookService ) { } ngOnInit() { this.bookService.get() this.subscription = this.bookService.books$ .subscribe( books => this.recently_books = reverse_by(books, 'last_read_time').slice(0, 3).map(book => { const $book = book $book.link = `read/${$book.id}` return $book }), error => console.log(error) ) } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HeaderComponent, LoginDialog, LogoutDialog } from './header/header/header.component'; import { FooterComponent } from './footer/footer.component'; import { MaterialModule } from './material/material.module' import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { HomeModule } from './home/home.module'; import { BlogModule } from './blog/blog.module'; import { ReadModule } from './read/read.module'; import { PlanModule } from './plan/plan.module'; import { httpInterceptorProviders } from './core/interceptors'; import { ApiService, ArticleService, CategoryService, BookService, InspirationService, CompletedService, PersonalService, WebService, UserService, TokenService } from './core/services'; import { HttpClientModule } from '../../node_modules/@angular/common/http'; import { FormsModule } from '../../node_modules/@angular/forms'; import { MarkdownModule, MarkedOptions } from '../../node_modules/ngx-markdown'; import { LMarkdownEditorModule } from 'ngx-markdown-editor'; import { AdminModule } from './admin/admin.module'; import { SharedModule } from './shared/shared.module'; @NgModule({ declarations: [ AppComponent, HeaderComponent, FooterComponent, LoginDialog, LogoutDialog, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, FormsModule, // SharedModule, HttpClientModule, MaterialModule, HomeModule, BlogModule, ReadModule, PlanModule, SharedModule, // AdminModule, LMarkdownEditorModule, MarkdownModule.forRoot() ], entryComponents: [ LoginDialog, LogoutDialog ], providers: [ httpInterceptorProviders, ApiService, TokenService, UserService, ArticleService, CategoryService, BookService, InspirationService, CompletedService, PersonalService, WebService ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>export * from './book.service' export * from './inspiration.service'<file_sep>import { Component, OnInit } from '@angular/core'; import { Route, ActivatedRoute } from '../../../../node_modules/@angular/router'; import { Article_GET, Category_GET } from '../../core/models'; import { ArticleService, CategoryService } from '../../core/services'; import { Subscription } from '../../../../node_modules/rxjs'; import { filter, combineLatest } from '../../../../node_modules/rxjs/operators'; import { getPluralCategory } from '../../../../node_modules/@angular/common/src/i18n/localization'; @Component({ selector: 'app-article-read', templateUrl: './article-read.component.html', styleUrls: ['./article-read.component.styl'] }) export class ArticleReadComponent implements OnInit { public cache article: Article_GET categories: Category_GET[] = [] category: string subscription: Subscription isWrite: boolean = false constructor( private route: ActivatedRoute, private articleService: ArticleService, private categoryService: CategoryService ) { } ngOnInit() { this.cache = window.localStorage this.articleService.get() this.categoryService.get() this.getArticle() } getArticle() { const id = +this.route.snapshot.paramMap.get('id'); this.subscription = this.articleService.articles$ .subscribe( articles => { this.article = articles.find(article => article.id === id) this.getCategory() }, error => console.log(error) ) this.categoryService.categories$ .subscribe( categories => { this.categories = categories, this.getCategory() }, error => console.log(error) ) } getCategory() { if (this.categories.length > 0 && this.article) { const articleCate = this.article.category this.category = this.categories.find(category => articleCate === category.id).name } } handleEdit() { this.isWrite = true } handleRead() { this.isWrite = false } handlePut() { const { title, abstract, body, reference, category } = this.article const article = { title, abstract, body, reference, category } this.articleService.put(this.article.id, article) } } <file_sep>import { Subject } from '../../../../node_modules/rxjs'; export function sort_by(arr: Object[], sort_name: string): any { return arr.sort((left, right) => { const lc = left[sort_name] const rc = right[sort_name] if (lc < rc) { return -1 } if (lc > rc) { return 1 } return 0 }) }export function reverse_by(arr: Object[], sort_name: string): any { return arr.sort((left, right) => { const lc = left[sort_name] const rc = right[sort_name] if (lc < rc) { return 1 } if (lc > rc) { return -1 } return 0 }) } export function setOneStream(sub: any, obj: any, payload: any, fun: any = false): any { console.log(obj) return sub.subscribe(res => { obj[payload] = res if (fun) { fun() } }, error => console.log(error) ) }<file_sep>export class Book_POST { name: string page_total: number page_read : number start: string anticipated_end: string isCompleted: boolean } export class Book_GET extends Book_POST { id: number last_read_time: string } <file_sep>export class Article_POST { title : string abstract : string body: string reference : string category : number } export class Article_GET extends Article_POST { id: number created: string modified: string } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { ActivatedRoute } from '../../../../node_modules/@angular/router'; @Component({ selector: 'app-add-button', templateUrl: './add.component.html', styleUrls: ['./add.component.styl'] }) export class AddBUttonComponent implements OnInit { @Input() routerPath public cache constructor( private route: ActivatedRoute ) { } ngOnInit() { this.cache = window.localStorage } } <file_sep>import { Component, OnInit } from '@angular/core'; import { PersonalService, WebService, CompletedService } from '../../core/services'; import { PlanPersonal_GET, PlanWeb_GET, PlanCompleted_GET } from '../../core/models'; import { Subscription } from '../../../../node_modules/rxjs'; @Component({ selector: 'app-plan-recently', templateUrl: './plan-recently.component.html', styleUrls: ['./plan-recently.component.styl'] }) export class PlanRecentlyComponent implements OnInit { personalPlan: PlanPersonal_GET[] = [] webPlan: PlanWeb_GET[] = [] completedPlan: PlanCompleted_GET[] = [] personalSubscription: Subscription webSubscription: Subscription completedSubscription: Subscription constructor( private personalService: PersonalService, private webService: WebService, private completedService: CompletedService ) { } ngOnInit() { this.personalService.get() this.webService.get() this.initPlan() } initPlan() { this.personalSubscription = this.personalService.$personals .subscribe( personals => this.personalPlan = personals, error => console.log(error) ) this.webSubscription = this.webService.webs$ .subscribe( webs => this.webPlan = webs, error => console.log(error) ) this.completedSubscription = this.completedService.completeds$ .subscribe( completeds => this.completedPlan = completeds, error => console.log(error) ) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { CategoryService } from '../../core/services'; import { Article_GET, Category_GET } from '../../core/models'; import { Option } from '../../core/models/data/options'; import { PageEvent } from '../../../../node_modules/@angular/material/paginator'; import { ArticleShowService } from './article-show.service'; @Component({ selector: 'app-article', templateUrl: './article.component.html', styleUrls: ['./article.component.styl'], providers: [ ArticleShowService ] }) export class ArticleComponent implements OnInit { routerPath = 'add' articles: Article_GET[] = [] categories: Category_GET[] = [] filters: Option[] = [] filterName = '类型' orders: Option[] = [ { value: 'title', hans: '标题' }, { value: 'category', hans: '类型' }, { value: 'created', hans: '创建时间' }, { value: 'modified', hans: '最后修改时间' } ] pageSizeOptions: number[] = [5, 10, 25, 100] pageEvent: PageEvent constructor( private categoryService: CategoryService, public articleShowService: ArticleShowService ) { } ngOnInit() { this.articleShowService.get() this.categoryService.get() this.articleShowService.setStream() this.articleShowService.articleShowPublic .subscribe(articles => this.articles = articles, error => console.log(error)) this.categoryService.categories$ .subscribe( categories => { this.categories = categories this.filters = categories.map(category => { return { value: category.id, hans: category.name } }) }, error => console.log(error) ) } handlePage(e): void { this.articleShowService.pageSize.next(e.pageSize) this.articleShowService.pageIndex.next(e.pageIndex) } changeFilter(e): void { this.articleShowService.filter.next(e) this.articleShowService.pageIndex.next(0) } changeOrder(e): void { this.articleShowService.order.next(e) this.articleShowService.pageIndex.next(0) } changeOrderMethod(): void { const orderMethod = this.articleShowService.orderMethod orderMethod.next(!orderMethod['_value']) } }<file_sep>import { Component, OnInit } from '@angular/core'; import { Article_GET, Article_POST, Category_GET } from '../../core/models'; import { CategoryService, ArticleService } from '../../core/services'; import { Subscription } from '../../../../node_modules/rxjs'; import { FormBuilder } from '../../../../node_modules/@angular/forms'; import { Validators } from '@angular/forms'; import { Location } from '@angular/common'; @Component({ selector: 'app-article-add', templateUrl: './article-add.component.html', styleUrls: ['./article-add.component.styl'] }) export class ArticleAddComponent implements OnInit { categories: Category_GET[] = [] articleForm = this.fb.group({ title: ['', Validators.required], abstract: [''], body: ['', Validators.required], reference: [''], category: [0] }) constructor( private categoryService: CategoryService, private articleService: ArticleService, private fb: FormBuilder, private loaction: Location ) { } ngOnInit() { this.categoryService.get() this.categoryService.categories$ .subscribe( category => this.categories = category, error => console.log(error) ) } post() { this.articleService.post(this.articleForm.value) } init() { this.articleForm = this.fb.group({ title: ['', Validators.required], abstract: [''], body: ['', Validators.required], reference: [''], category: [0] }) } goBack() { this.loaction.back() } } <file_sep>import { NgModule } from '@angular/core'; import { ArticleComponent } from './article/article.component'; import { BlogRoutingModule } from './blog-routing.module'; import { SharedModule } from '../shared/shared.module'; import { ArticleDetailComponent } from './article-detail/article-detail.component'; import { CommonModule } from '../../../node_modules/@angular/common'; import { MaterialModule } from '../material/material.module'; // import { MarkdownModule } from 'ngx-markdown' import { LMarkdownEditorModule } from '../../../node_modules/ngx-markdown-editor'; import { FormsModule, ReactiveFormsModule } from '../../../node_modules/@angular/forms'; import { ArticleAddComponent } from './article-add/article-add.component'; import { ArticleReadComponent } from './article-read/article-read.component'; import { MarkdownModule } from '../../../node_modules/ngx-markdown'; @NgModule({ imports: [ BlogRoutingModule, SharedModule, CommonModule, MaterialModule, LMarkdownEditorModule, MarkdownModule.forRoot(), FormsModule, ReactiveFormsModule ], declarations: [ ArticleComponent, ArticleDetailComponent, ArticleAddComponent, ArticleReadComponent, ] }) export class BlogModule {}<file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http' import { throwError, Observable } from 'rxjs'; import { tap, catchError } from 'rxjs/operators' import { environment } from '../../../environments/environment'; @Injectable( // { // providedIn: 'root' // } ) export class ApiService { public isLogin: boolean = true constructor( private http: HttpClient ) { } private formatErrors(error: any) { const loginError = ['Signature has expired.', 'Error decoding signature.'] if(loginError.indexOf(error.error.detail) === -1) { this.isLogin = false } console.log(error.error) return throwError(error.error) } get(path: string, params: HttpParams = new HttpParams()): Observable<any> { return this.http.get(`${environment.api_url}${path}`, { params }) .pipe( tap(), catchError(this.formatErrors) ) } post(path: string, body: Object = {}): Observable<any> { return this.http.post(`${environment.api_url}${path}`, body) .pipe( tap(_ => this.isLogin = true), catchError(this.formatErrors) ) } put(path: string, body: object = {}): Observable<any> { return this.http.put(`${environment.api_url}${path}`, body) .pipe( tap(), catchError(this.formatErrors) ) } delete(path: string): Observable<any> { return this.http.delete(`${environment.api_url}${path}`) .pipe( tap(), catchError(this.formatErrors) ) } }<file_sep>import { Injectable } from '@angular/core'; import { ArticleService } from '../../core/services'; import { Article_GET } from '../../core/models'; import { BehaviorSubject } from '../../../../node_modules/rxjs'; import { sort_by, reverse_by } from '../../core/fun'; @Injectable( // { // providedIn: 'root' // } ) export class ArticleShowService { private articles: Article_GET[] = [] public articlesFilter: Article_GET[] = [] public pageSize: BehaviorSubject<number> = new BehaviorSubject(10) public pageIndex: BehaviorSubject<number> = new BehaviorSubject(0) public filter: BehaviorSubject<number> = new BehaviorSubject(0) public order: BehaviorSubject<string> = new BehaviorSubject('id') public articleShowPublic: BehaviorSubject<Article_GET[]> = new BehaviorSubject([]) public orderMethod: BehaviorSubject<boolean> = new BehaviorSubject(true) constructor( private articleSerice: ArticleService ) { } get():void { this.articleSerice.get() } private changeFilter(): Article_GET[] { let articlesFilter = this.articles if (articlesFilter.length === 0) { return [] } const filter = this.filter['_value'] if (filter !== 0) { articlesFilter = articlesFilter.filter(article => article.category === filter) } return articlesFilter } private handleChangeFilter(): void { this.articlesFilter = this.changeFilter() } private ChangeShow(): Article_GET[] { const articles = this.articlesFilter const pageSize = this.pageSize['_value'] const pageIndex = this.pageIndex['_value'] const order = this.order['_value'] const orderMethod = this.orderMethod['_value'] if (articles.length === 0) { return [] } let articlesOrder if (orderMethod) { articlesOrder = sort_by(articles, order) } else { articlesOrder = reverse_by(articles, order) } const start = pageIndex * pageSize const end = start + pageSize return articlesOrder.slice(start, end) } private handleChangeShow(): void { this.articleShowPublic.next(this.ChangeShow()) } private setOneStream(sub: any, fun = function(){}): any { return sub.subscribe(res => { fun.call(this) this.handleChangeShow() }, error => console.log(error) ) } public setStream(): void { this.articleSerice.articles$ .subscribe(articles => { this.articles = articles this.handleChangeFilter() this.handleChangeShow() }, error => console.log(error)) this.setOneStream(this.pageSize) this.setOneStream(this.pageIndex) this.setOneStream(this.filter, this.handleChangeFilter) this.setOneStream(this.orderMethod) this.setOneStream(this.order) } }<file_sep>import { Routes, RouterModule } from "@angular/router" import { BookComponent } from './book/book.component'; import { NgModule } from '@angular/core' import { BookAddComponent } from './book-add/book-add.component'; import { BookReadComponent } from './book-read/book-read.component'; const routes: Routes = [ { path: 'read', component: BookComponent }, { path: 'read/add', component: BookAddComponent }, { path: 'read/:id', component: BookReadComponent } ] @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class ReadRoutingModule {}<file_sep>import { Routes, RouterModule } from "@angular/router"; import { NgModule } from '@angular/core'; import { ArticleComponent } from './article/article.component'; import { ArticleAddComponent } from './article-add/article-add.component'; import { ArticleReadComponent } from './article-read/article-read.component'; const routes: Routes = [ { path: 'blog', component: ArticleComponent, // data: { animation: 'blog' } }, { path: 'blog/add', component: ArticleAddComponent, // data: { animation: '' } }, { path: 'blog/:id', component: ArticleReadComponent, // data: { animation: '' } } ] @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class BlogRoutingModule {}<file_sep>export * from './srot'<file_sep>import { Component, OnInit } from '@angular/core'; import { BookService, InspirationService } from '../../core/services'; import { Book_GET, Inspiration_GET } from '../../core/models'; import { Subscription } from '../../../../node_modules/rxjs'; import { Option } from '../../core/models/data/options'; import { PageEvent } from '../../../../node_modules/@angular/material/paginator'; import { BookShowService } from './book-show.service'; @Component({ selector: 'app-book', templateUrl: './book.component.html', styleUrls: ['./book.component.styl'], providers: [ BookShowService ] }) export class BookComponent implements OnInit { books: Book_GET[] = [] inspiration: Inspiration_GET[] = [] routerPath: string = 'add' filters: Option[] = [ { value: true, hans: '是' }, { value: false, hans: '否' } ] filterName: string = '是否完成' orders: Option[] = [ { value: 'anticipated_end', hans: '预计结束时间' }, { value: 'last_read_time', hans: '最后阅读时间' } ] pageSizeOptions: number[] = [5, 10, 25, 100] pageEvent: PageEvent constructor( private bookService: BookService, private inspirationService: InspirationService, private bookShowService: BookShowService ) { } ngOnInit() { this.bookService.get() this.inspirationService.get() this.bookShowService.setStream() this.bookShowService.booksShow .subscribe( books => this.books = books, error => console.log(error) ) this.inspirationService.inspirations$ .subscribe( inspiration => { this.inspiration = inspiration }, error => console.log(error) ) } handlePage(e): void { this.bookShowService.pageSize.next(e.pageSize) this.bookShowService.pageIndex.next(e.pageIndex) } changeFilter(e): void { this.bookShowService.filter.next(e) this.bookShowService.pageIndex.next(0) } changeOrder(e): void { this.bookShowService.order.next(e) this.bookShowService.pageIndex.next(0) } changeOrderMethod(): void { const orderMethod = this.bookShowService.orderMethod orderMethod.next(!orderMethod['_value']) } } <file_sep>import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { ApiService } from '../api.service'; import { PlanWeb_GET, PlanWeb_POST } from '../../models'; @Injectable( // { // providedIn: 'root' // } ) export class WebService { private webs: BehaviorSubject<PlanWeb_GET[]> = new BehaviorSubject([]) public webs$ = this.webs.asObservable() private base_url = 'api/plan/web/' private isInit: boolean = false constructor( private apiService: ApiService ) { } get(): void { if (!this.isInit) { this.apiService.get(this.base_url) .subscribe(webs => { this.webs.next(webs) this.isInit = true }) } } update(): void { this.apiService.get(this.base_url) .subscribe(webs => this.webs.next(webs)) } post(web: PlanWeb_POST): void { this.apiService.post(this.base_url, web) .subscribe(_ => this.update()) } put(id: number, web: PlanWeb_POST): void { this.apiService.put(`${this.base_url}${id}/`, web) .subscribe(_ => this.update()) } delete(id: number): void { this.apiService.delete(`${this.base_url}${id}/`) .subscribe(_ => this.update()) } }<file_sep>import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { ApiService } from '../api.service'; import { Category_GET, Category_POST } from '../../models'; @Injectable( // { // providedIn: 'root' // } ) export class CategoryService { private categories: BehaviorSubject<Category_GET[]> = new BehaviorSubject([]) public categories$ = this.categories.asObservable() private base_url = 'api/blog/category/' private isInit: boolean = false constructor( private apiService: ApiService ) { } get(): void { if (!this.isInit) { this.apiService.get(this.base_url) .subscribe(categories => { this.categories.next(categories) this.isInit = true }) } } update(): void { this.apiService.get(this.base_url) .subscribe(categories => this.categories.next(categories)) } post(category: Category_POST): void { this.apiService.post(this.base_url, category) .subscribe(_ => this.update()) } put(id: number, category: Category_POST): void { this.apiService.put(`${this.base_url}${id}/`, category) .subscribe(_ => this.update()) } delete(id: number): void { this.apiService.delete(`${this.base_url}${id}/`) .subscribe(_ => this.update()) } }<file_sep>export class Category_POST { name: string } export class Category_GET extends Category_POST { id: number }<file_sep>import { NgModule } from '@angular/core'; import { MatIconModule, } from '@angular/material'; import {MatMenuModule} from '@angular/material/menu'; import {MatButtonModule} from '@angular/material/button'; import {MatDialogModule} from '@angular/material/dialog'; import {MatInputModule} from '@angular/material/input'; import {MatSelectModule} from '@angular/material/select'; import { MatOptionModule, MatNativeDateModule } from '../../../node_modules/@angular/material/core'; import {MatPaginatorModule} from '@angular/material/paginator'; import { CommonModule } from '../../../node_modules/@angular/common'; import {MatDatepickerModule} from '@angular/material/datepicker'; import {MatSlideToggleModule} from '@angular/material/slide-toggle'; import {MatButtonToggleModule} from '@angular/material/button-toggle'; import { FormsModule } from '../../../node_modules/@angular/forms'; @NgModule({ declarations: [], imports: [ CommonModule ], exports: [ MatMenuModule, MatButtonModule, MatDialogModule, MatInputModule, MatSelectModule, MatOptionModule, MatPaginatorModule, MatDatepickerModule, MatNativeDateModule, MatSlideToggleModule, MatButtonToggleModule, MatIconModule, FormsModule ] }) export class MaterialModule { } <file_sep>export * from './web' export * from './personal' export * from './completed' <file_sep>import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { ApiService } from '../api.service'; import { Book_GET, Book_POST } from '../../models'; @Injectable( // { // providedIn: 'root' // } ) export class BookService { private books: BehaviorSubject<Book_GET[]> = new BehaviorSubject([]) public books$ = this.books.asObservable() private base_url = 'api/book/book/' private isInit: boolean = false constructor( private apiService: ApiService ) { } get(): void { if (!this.isInit) { this.apiService.get(this.base_url) .subscribe(books => { this.books.next(books) this.isInit = true }) } } update(): void { this.apiService.get(this.base_url) .subscribe(books => this.books.next(books)) } post(book: Book_POST): void { this.apiService.post(this.base_url, book) .subscribe(_ => this.update()) } put(id: number, book: Book_POST): void { this.apiService.put(`${this.base_url}${id}/`, book) .subscribe(_ => this.update()) } delete(id: number): void { this.apiService.delete(`${this.base_url}${id}/`) .subscribe(_ => this.update()) } }<file_sep>import { NgModule } from "../../../node_modules/@angular/core"; import { PlanRoutingModule } from './plan-routing.module'; import { PlanComponent } from './plan/plan.component'; @NgModule({ declarations: [ PlanComponent ], imports: [ PlanRoutingModule ] }) export class PlanModule {}<file_sep>import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { ApiService } from '../api.service' import { TokenService } from './token.service' import { User, User_SAVE } from '../../models'; @Injectable( // { // providedIn: 'root' // } ) export class UserService { cache = window.localStorage constructor( private apiService: ApiService, private tokenService: TokenService ) { } login(user: User): void { this.apiService.post('api-token-auth/', user) .subscribe( res => { const payload: User_SAVE = { jwtToken: res.token, username: user.username, password: <PASSWORD> } this.tokenService.saveToken(payload) console.log('login') } ) } verifyToken(): void { const body = { token: this.tokenService.getToken() } this.apiService.post('api-token-verify/', body) .subscribe(_ => console.log('login')) } logout(): void { this.tokenService.destoryToken() console.log('logout') } }<file_sep>import { Component, OnInit, Input } from '@angular/core'; import { Inspiration_GET } from '../../core/models'; import { InspirationService, UserService } from '../../core/services'; @Component({ selector: 'app-inspiration-read', templateUrl: './inspiration-read.component.html', styleUrls: ['./inspiration-read.component.styl'] }) export class InspirationReadComponent implements OnInit { @Input() inspiration ins: Inspiration_GET isWrite: boolean = false constructor( private inspirationService: InspirationService, private userService: UserService ) { } ngOnInit() { this.initIns() } ngOnChanges() { this.initIns() } initIns() { this.ins = JSON.parse(JSON.stringify(this.inspiration)) } edit() { this.isWrite = true } put() { const { book, title, body } = this.ins const ins = { book, title, body } this.inspirationService.put(this.ins.id, ins) } cancel() { this.isWrite = false } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { Book_GET, Inspiration_GET } from '../../core/models'; import { sort_by } from '../../core/fun'; @Component({ selector: 'app-book-detail', templateUrl: './book-detail.component.html', styleUrls: ['./book-detail.component.styl'] }) export class BookDetailComponent implements OnInit { @Input() book: Book_GET // @Input() inspiration: Inspiration_GET[] // inspirationFirst: Inspiration_GET constructor( ) { } ngOnInit() { } // ngOnChanges() { // if (this.inspiration && this.inspiration.length > 0) { // this.handleFindInspiration() // } // } // handleFindInspiration() { // const inspirations = sort_by(this.inspiration.filter(ins => ins.book === this.book.id), 'id') // if (inspirations.length > 0) { // this.inspirationFirst = inspirations[inspirations.length-1] // } // } } <file_sep>export class Inspiration_POST { book: number title: string body: string } export class Inspiration_GET extends Inspiration_POST { id : number created: string modified: string }<file_sep>export function getYMD (date: Date): string { const year = date.getFullYear() const month = date.getMonth() let time: string if (month < 10) { time = `${year}-0${month+1}` } else { time = `${year}-${month+1}` } const day = date.getDate() if (day < 10) { time = `${time}-0${day}` } else { time = `${time}-${day}` } return time }<file_sep>import { Injectable } from '@angular/core'; import { BookService, InspirationService } from '../../core/services'; import { BehaviorSubject } from '../../../../node_modules/rxjs'; import { Book_GET } from '../../core/models'; import { sort_by, reverse_by } from '../../core/fun'; @Injectable( // { // providedIn: 'root' // } ) export class BookShowService { books: Book_GET[] = [] booksFilter: Book_GET[] = [] order: BehaviorSubject<string> = new BehaviorSubject('id') filter: BehaviorSubject<boolean | number> = new BehaviorSubject(0) pageSize: BehaviorSubject<number> = new BehaviorSubject(10) pageIndex: BehaviorSubject<number> = new BehaviorSubject(0) public orderMethod: BehaviorSubject<boolean> = new BehaviorSubject(true) booksShow: BehaviorSubject<Book_GET[]> = new BehaviorSubject([]) constructor( private bookService: BookService, private inspirationService: InspirationService ) { } private changeFilter(): Book_GET[] { let booksFilter = this.books if (booksFilter.length === 0) { return [] } const filter = this.filter['_value'] if (filter !== 0) { booksFilter = booksFilter.filter(book => book.isCompleted === filter) } return booksFilter } private handleChangeFilter(): void { this.booksFilter = this.changeFilter() } private changeShow(): Book_GET[] { const booksShow = this.booksFilter const pageSize = this.pageSize['_value'] const pageIndex = this.pageIndex['_value'] const orderMethod = this.orderMethod['_value'] const order = this.order['_value'] if (booksShow.length === 0) { return [] } let booksOrder if (orderMethod) { booksOrder = sort_by(booksShow, order) } else { booksOrder = reverse_by(booksShow, order) } const start = pageIndex * pageSize const end = start + pageSize return booksOrder.slice(start, end) } private handleChangeShow():void { this.booksShow.next(this.changeShow()) } private setOneStream(sub: any, fun = function(){}): any { return sub.subscribe(res => { fun.call(this) this.handleChangeShow() }, error => console.log(error) ) } public setStream(): void { this.bookService.books$ .subscribe(book => { this.books = book this.handleChangeFilter() this.handleChangeShow() }, error => console.log(error)) this.setOneStream(this.pageSize) this.setOneStream(this.pageIndex) this.setOneStream(this.filter, this.handleChangeFilter) this.setOneStream(this.order) this.setOneStream(this.orderMethod) } }<file_sep>import { NgModule } from "@angular/core"; import { BookComponent } from './book/book.component'; import { ReadRoutingModule } from './read-routing.module'; import { SharedModule } from '../shared/shared.module'; import { BookDetailComponent } from './book-detail/book-detail.component'; import { CommonModule } from '../../../node_modules/@angular/common'; import { MaterialModule } from '../material/material.module'; import { BookReadComponent } from './book-read/book-read.component'; import { BookAddComponent } from './book-add/book-add.component'; import { FormsModule, ReactiveFormsModule } from '../../../node_modules/@angular/forms'; import { InspirationReadComponent } from './inspiration-read/inspiration-read.component'; import { MarkdownModule } from '../../../node_modules/ngx-markdown'; import { LMarkdownEditorModule } from '../../../node_modules/ngx-markdown-editor'; @NgModule({ imports: [ ReadRoutingModule, SharedModule, CommonModule, MaterialModule, FormsModule, MarkdownModule, LMarkdownEditorModule, ReactiveFormsModule ], declarations: [ BookComponent, BookDetailComponent, BookReadComponent, BookAddComponent, InspirationReadComponent ] }) export class ReadModule {}<file_sep>import { Component, OnInit } from '@angular/core'; import { Book_GET, Book_POST } from '../../core/models'; import { BookService } from '../../core/services'; import { getYMD } from '../../core/fun/date'; import { FormBuilder } from '../../../../node_modules/@angular/forms'; import { Validators } from '@angular/forms'; @Component({ selector: 'app-book-add', templateUrl: './book-add.component.html', styleUrls: ['./book-add.component.styl'] }) export class BookAddComponent implements OnInit { bookForm = this.fb.group({ name: ['', Validators.required], page_total: [0, Validators.required], page_read: [0, Validators.required], start: ['', Validators.required], anticipated_end: ['', Validators.required], isCompleted: [false, Validators.required] }) constructor( private bookService: BookService, private fb: FormBuilder ) { } ngOnInit() { } change(e) { this.bookForm.value.isCompleted = e } post() { const { name, page_total, page_read, start, anticipated_end, isCompleted } = this.bookForm.value const startTime = getYMD(new Date(start)) const endTime = getYMD(new Date(anticipated_end)) let time = { name, page_total, page_read, isCompleted, start: startTime, anticipated_end: endTime } this.bookService.post(time) } init() { this.bookForm = this.fb.group({ name: ['', Validators.required], page_total: [0, Validators.required], page_read: [0, Validators.required], start: ['', Validators.required], anticipated_end: ['', Validators.required], isCompleted: [false, Validators.required] }) } } <file_sep>import { Injectable } from '@angular/core'; import { User_SAVE } from '../../models'; @Injectable( // { // providedIn: 'root' // } ) export class TokenService { constructor() { } getToken(): string { return window.localStorage['JWTtoken'] } saveToken(payload: User_SAVE): void { window.localStorage['username'] = payload.username window.localStorage['password'] = <PASSWORD> window.localStorage['jwtToken'] = payload.jwtToken } destoryToken(): void { window.localStorage.removeItem('jwtToken') window.localStorage.removeItem('username') window.localStorage.removeItem('password') } }<file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '../../../../node_modules/@angular/router'; import { BookService, InspirationService, UserService } from '../../core/services'; import { Book_GET, Inspiration_GET, Inspiration_POST } from '../../core/models'; import { getYMD } from '../../core/fun/date'; import { FormBuilder } from '../../../../node_modules/@angular/forms'; import { Validators } from '@angular/forms'; @Component({ selector: 'app-book-read', templateUrl: './book-read.component.html', styleUrls: ['./book-read.component.styl'] }) export class BookReadComponent implements OnInit { book: Book_GET initBook: string inspiration = this.fb.group({ title: ['', Validators.required], body: ['', Validators.required] }) inspirations: object[] = [] isWrite: boolean = false isAdd: boolean = false constructor( private route: ActivatedRoute, private bookService: BookService, private inspirationService: InspirationService, public userService: UserService, private fb: FormBuilder ) { } ngOnInit() { this.bookService.get() this.inspirationService.get() this.init() } init() { const id = +this.route.snapshot.paramMap.get('id') this.bookService.books$ .subscribe( books => { this.book = books.find(books => books.id === id) this.initBook = JSON.stringify(this.book) }, error => console.log(error) ) this.inspirationService.inspirations$ .subscribe( inspirations => { if (inspirations.length > 0) { this.inspirations = inspirations.filter(ins => ins.book === id) } }, error => console.log(error) ) } initIns() { this.inspiration = this.fb.group({ title: ['', Validators.required], body: ['', Validators.required] }) } postIns() { const { title, body } = this.inspiration.value const ins = { title, body, book: this.book.id } this.inspirationService.post(ins) } change(e) { this.book.isCompleted = !this.book.isCompleted } cancel() { this.isWrite = false this.book = JSON.parse(this.initBook) } put() { const { name, page_total, page_read, start, anticipated_end, isCompleted } = this.book let startTime, endTime if (typeof start === 'string') { startTime = start } else { startTime = getYMD(new Date(start)) } if (typeof anticipated_end === 'string') { endTime = anticipated_end } else { endTime = getYMD(new Date(anticipated_end)) } let time = { name, page_total, page_read, isCompleted, start: startTime, anticipated_end: endTime } this.bookService.put(this.book.id, time) } } <file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Option } from '../../core/models/data/options'; @Component({ selector: 'app-filter', templateUrl: './filter.component.html', styleUrls: ['./filter.component.styl'] }) export class FilterComponent implements OnInit { @Input() filters: Option[] @Input() name: string @Output() filterSelect = new EventEmitter<any>() selectedFilter: any = 0 lastFilter: any = 0 constructor() { } ngOnInit() { } ngDoCheck() { if (this.selectedFilter === this.lastFilter) { return } this.lastFilter = this.selectedFilter this.filterSelect.emit(this.selectedFilter) } } <file_sep>export class PlanWeb_POST { name: string start: string anticipated_end: string isCompleted: Boolean body: string current_process: string } export class PlanWeb_GET extends PlanWeb_POST { id: number last_modified: string }
c63dc90516faa7e21d2fba53aad6587f26c0ba6a
[ "TypeScript" ]
52
TypeScript
flycsqaq/personal-web-front
395142cdb39cbacaac9a74ba428b846fd3a48f67
887380a6b7ec4350c171db95c35807bfc3f16262
refs/heads/master
<file_sep>package com.ict.sp.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ict.sp.dao.TestDAO; import com.ict.sp.vo.Dept; @Service public class TestService { @Autowired private TestDAO tdao; public List<Dept> getList(){ return tdao.getList(); } }
1147e7725aecd1a0f3986381e9d75af66ffdf387
[ "Java" ]
1
Java
reparkye/ict_spring
63038d3bf637ec46d033702e1b7bd6f82edb0a49
1aa7ebc00cd1e0d4c1ca462e8b8aeb672f55ec50
refs/heads/main
<repo_name>MicoMorenoPH/Api_GetMethod<file_sep>/API_GetMethod.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using masterDatabase; using System.Web.Http.Cors; namespace page2APIdemo.Controllers { [EnableCors(origins: "http://localhost:54720", headers:"*",methods:"*")] public class GetMethodController : ApiController { masterEntities1 spApiBranch = new masterEntities1(); [HttpPost] public List<spApiBranch_Result> GetBranch([FromBody] spApiBranch_Result [] sysParam ) { //NORMAL WAY List<spApiBranch_Result> sysData = spApiBranch.spApiBranch(sysParam[0].function, sysParam[0].branchCode).ToList(); if (sysData.Count == 0) { sysData.Add(new spApiBranch_Result { retValue = false, retStatus = "nothing", retMessage = "Data not found." }); } return sysData; } [HttpPost] public HttpResponseMessage GetBranch1([FromBody] spApiBranch_Result[] sysParam) // STANDARD WAY { List<spApiBranch_Result> sysData = spApiBranch.spApiBranch(sysParam[0].function,sysParam[0].branchCode).ToList(); if (sysData.Count > 0) { return Request.CreateResponse(HttpStatusCode.OK, sysData); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Data not found."); } } public HttpResponseMessage GetBranchByName([FromBody] spApiBranch_Result[] sysParam) // STANDARD WAY { List<spApiBranch_Result> sysData = spApiBranch.spApiBranch(sysParam[0].function, sysParam[0].bran).ToList(); if (sysData.Count > 0) { return Request.CreateResponse(HttpStatusCode.OK, sysData); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Data not found."); } } } }
0dc99ddcb8bdfb9f61d4dcc44fa77ccd8e3da23d
[ "C#" ]
1
C#
MicoMorenoPH/Api_GetMethod
394c55f02aa7d65a933c861c9fe474da8a26649e
3be842f2f837c272c0c2c2a6b744370fd34ad01a
refs/heads/master
<file_sep>#!/bin/bash if [ "${__SCM__:-}" != 'Loaded' ]; then __SCM__='Loaded' # --------------------------------------------------------------------------- # # Load configuration parameters # CONF_GET "SVN_PARENT_PATH" # # Test parameters # if [ -z "${SVN_PARENT_PATH}" ]; then echo "ERROR: configuration parameter not defined: SVN_PARENT_PATH" exit 2 fi # # Auto calculate some parameters # SVN_PERMISSION="$(stat -c %U:%G ${SVN_PARENT_PATH})" # --------------------------------------------------------------------------- # # Function to check environnement # SCM_CHECK() { CHECK svn CHECK svnadmin CHECK svnsync } # # Function to copy an existing repository # SCM_COPY() { svn checkout file://"${SVN_PARENT_PATH}/${name}" "${TEMPDIR}/${name}" mkdir -p "${TEMPDIR}/${name}/tags/"{application,configuration} mkdir -p "${TEMPDIR}/${name}/tags/configuration/"{integration,production} svn add "${TEMPDIR}/${name}"/tags svn commit -m 'Initialize structure' "${TEMPDIR}/${name}/tags/" rm -rf "${TEMPDIR}/${name}" return } # # Function to create a new repository # SCM_CREATE() { local name= name="$1" if [ -n "$(/bin/ls -1 "${SVN_PARENT_PATH}" | grep ${name})" ]; then MESSAGE "Repository already exists" return fi svnadmin create "${SVN_PARENT_PATH}/${name}" if [ !$? ]; then MESSAGE "Unable to create repository" return fi chown -R ${SVN_PERMISSION} "${SVN_PARENT_PATH}/${name}" MESSAGE "Successfull repository created" } # # Function to delete an existing repository # SCM_DELETE() { local name= name="$1" if [ -z "$(/bin/ls -1 "${SVN_PARENT_PATH}" | grep ${name})" ]; then MESSAGE "Repository does not exist" return fi rm -rf "${SVN_PARENT_PATH}/${name}" if [ !$? ]; then MESSAGE "Unable to delete repository" return fi MESSAGE "Successfull repository deleted" } # # Function to print information about an existing repository # SCM_INFO() { local name= name="$1" if [ -z "$(/bin/ls -1 "${SVN_PARENT_PATH}" | grep ${name})" ]; then MESSAGE "Repository does not exist" return fi svn info file://"${SVN_PARENT_PATH}/${name}" } # # Function to initialize an existing repository # SCM_INIT () { local name= name="$1" if [ -z "$(/bin/ls -1 "${SVN_PARENT_PATH}" | grep ${name})" ]; then MESSAGE "Repository does not exist" return fi svn checkout file://"${SVN_PARENT_PATH}/${name}" "${TEMPDIR}/${name}" mkdir -p "${TEMPDIR}/${name}/tags/"{application,configuration} mkdir -p "${TEMPDIR}/${name}/tags/configuration/"{integration,production} svn add "${TEMPDIR}/${name}"/tags svn commit -m 'Initialize structure' "${TEMPDIR}/${name}/tags/" rm -rf "${TEMPDIR}/${name}" } # # Function to list available repositories # SCM_LIST() { /bin/ls -1 "${SVN_PARENT_PATH}" } fi # Loaded <file_sep>#!/bin/bash if [ "${__LOADER__:-}" != 'Loaded' ]; then __LOADER__='Loaded' # --------------------------------------------------------------------------- # # Constants # DIRNAME="$(dirname "$0")" SCRIPTNAME="$(basename "$0")" FILENAME="$(cd ${DIRNAME} 2>/dev/null && /bin/pwd)/${SCRIPTNAME}" HOSTNAME="$(hostname)" CURRDIR="$(/bin/pwd)" ROOTDIR="$(dirname "$(dirname "${FILENAME}")")" TEMPDIR="/tmp/svntool" PROMPT=0 # --------------------------------------------------------------------------- # # Function to check commands # CHECK() { local cmd= cmd="$1"; if [ -z "$(/bin/which ${cmd})" ]; then echo "ERROR: Unable to find command ${cmd}" exit 2 fi return 0; } # # Print headers # CLI_HEADER() { local force= force=$1 if [ "${PROMPT}" == "0" -a "${force}" != "0" ]; then BR return fi BR MSG "Subversion administration tools" MSG "By <NAME> <<EMAIL>>" BR MSG "Use 'help' command to list all avariable commands" BR } # # Main interpreter # CLI_RUN_SVNTOOL() { if [ "$#" != "0" ]; then PROMPT=1 CLI_RUN_COMMAND $* else CLI_HEADER 0 CLI_RUN fi return 0 } # --------------------------------------------------------------------------- # # Load libraries by invoking the helper # . "${ROOTDIR}/lib/helper.lib.sh" # # Create temporary directory # if [ ! -d "${TEMPDIR}" ]; then mkdir "${TEMPDIR}" fi if [ ! -w "${TEMPDIR}" ]; then echo "ERROR: Unable to write to ${TEMPDIR}" exit 2 fi # # Auto set some final parameters # CONF_SET_FILE "${ROOTDIR}/etc/svntool.conf" fi # Loaded <file_sep>#!/bin/bash if [ "${__SCM_WRAPPER__:-}" != 'Loaded' ]; then __SCM_WRAPPER__='Loaded' # --------------------------------------------------------------------------- # # Load repository library # CONF_GET "REPOSITORY_TYPE" if [ -z "$(/bin/ls -1 ${ROOTDIR}/lib/scm/${REPOSITORY_TYPE}.lib.sh)" ]; then echo "ERROR: Unable to find repository ${REPOSITORY_TYPE}" exit 2 fi . "${ROOTDIR}/lib/scm/${REPOSITORY_TYPE}.lib.sh" # # Launch auto checks # SCM_CHECK # --------------------------------------------------------------------------- # # Wrapper function to copy a remote repository # REPOSITORY_COPY() { SCM_COPY $* } # # Wrapper function to create a new repository # REPOSITORY_CREATE() { SCM_CREATE $* } # # Wrapper function to delete an existing directory # REPOSITORY_DELETE() { SCM_DELETE $* } # # Wrapper function to print information of an existing repository # REPOSITORY_INFO() { SCM_INFO $* } # # Wrapper function to initialize an existing repository # REPOSITORY_INIT() { SCM_INIT $* } # # Wrapper function to list available repositories # REPOSITORIES_LIST() { SCM_LIST $* } fi # Loaded <file_sep>svnadmin-tools ==============
42805f3e009c72290a0f3e8ad020b4d60d195d4c
[ "Markdown", "Shell" ]
4
Shell
tchemineau/svnadmin-tools
d638fd77cd217d17262e058755db63fc21927a29
f7f6a928bcc7a9be73692c4b9ad80df73b06b846
refs/heads/master
<repo_name>ilya-kochergin/coursera-statinfer-cproject<file_sep>/exp_means_ctl_demo.Rmd --- title: "Central Limit Theorem demo" subtitle: "Statistical Inference course project" author: "<NAME>" date: "22 nov 2015" output: pdf_document --- ```{r} library(ggplot2) ``` ##Overview [//]: # (Overview: In a few (2-3) sentences explain what is going to be reported on.) Let's demonstrate, that average computed on sample (sample mean) has distribution that tends to be asymptotically normal. Original random variable in this demo is exponentially distributed. ```{r} lambda=0.2 # rate parameter n=40 # sample size nosim=1000 # number of samples ``` ###Density of exponentially distributed random variable. Theoretial $Std. deviation \,(\sigma) =Mean\, (\mu) =1/\lambda$=`r 1/lambda` ```{r,echo=FALSE,fig.height=3} ggplot()+stat_function(aes(x=c(-1,8)),fun=dexp,args = list(rate=lambda)) + # geom_vline(aes(xintersept=5,color="red"))+ labs(x="x",title="Distribution density of original random variables") ``` ##Simulations [//]: # (Simulations: Include English explanations of the simulations you ran, with the accompanying R code. Your explanations should make clear what the R code accomplishes.) We generate `nosim=1000` rows of random numbers (samples). Sample size is `n=40` ```{r} # Random matrix. Each row is a sample (n=40) rnd_exp_samples<- matrix(data=rexp(nosim*n,rate=lambda),ncol = n, byrow = T) ``` ##Sample Mean versus Theoretical Mean [//]: # (Sample Mean versus Theoretical Mean: Include figures with titles. In the figures, highlight the means you are comparing. Include text that explains the figures and what is shown on them, and provides appropriate numbers.) Theoretical mean $\mu=1/\lambda$ Sample mean is a random variable. We have 1000 sample means ```{r} mu=1/lambda # vector of sample means rnd_exp_samples_means <- apply(X = rnd_exp_samples,1 ,FUN = mean) # range of sample means summary(rnd_exp_samples_means) ``` Sample means centered at `r mean(rnd_exp_samples_means)` near theoretial `r mu` ##Sample Variance versus Theoretical Variance [//]: # (Sample Variance versus Theoretical Variance: Include figures (output from R) with titles. Highlight the variances you are comparing. Include text that explains your understanding of the differences of the variances.) Theoretical standard deviation is $\sigma=1/\lambda\,=\,5$ Theoretical variance is $\sigma=25$ Sample variance is a random variable. We have 1000 sample variance ```{r} sigma=1/lambda # vector of sample means rnd_exp_samples_vars <- apply(X = rnd_exp_samples,1 ,FUN = var) # range of sample variances summary(rnd_exp_samples_vars) ``` Sample variance is centered at `r mean(rnd_exp_samples_vars)` near theoretial `r sigma^2` ##Distribution [//]: # (Distribution: Via figures and text, explain how one can tell the distribution is approximately normal.) Histogram of sample means approches to density of Normal distributon with the following parameters: ```{r} gaussian_mu = mu gaussian_sigma = sigma/sqrt(n) ``` ```{r} ggplot(data.frame(x=rnd_exp_samples_means),aes(x)) + stat_function(fun=dnorm,args=list(mean=gaussian_mu,sd=gaussian_sigma),col="red",size=2)+ geom_histogram(aes(y=..density..),fill="green",alpha=0.3,col="green",stat_bin=1/30) ``` <file_sep>/ToothGrows_analyse.Rmd --- title: "The Effect of Vitamin C on Tooth Growth in Guinea Pigs" subtitle: "Statitistic inference course project" author: "<NAME>" date: "22 nov 2015 " output: pdf_document --- ## Dataset description from documetation ### Description The response is the length of odontoblasts (teeth) in each of 10 guinea pigs at each of three dose levels of Vitamin C (0.5, 1, and 2 mg) with each of two delivery methods (orange juice or ascorbic acid). ###Format A data frame with 60 observations on 3 variables. [,1] len numeric Tooth length [,2] supp factor Supplement type (VC or OJ). [,3] dose numeric Dose in milligrams. [//]: # (Load the ToothGrowth data and perform some basic exploratory data analyses ) ```{r} library(datasets) data(ToothGrowth) ``` ```{r} library(ggplot2) ggplot(ToothGrowth, aes(x=factor(dose), y=len, fill=factor(dose)))+geom_boxplot()+facet_grid(.~supp)+labs(title="Toothgrowth depending dose and supplement type") ``` ## A basic summary of the data. ```{r} oj_df=(subset(ToothGrowth,supp=='OJ')[c(1,3)]) # Orange Juice sd(oj_df$len) mean(oj_df$len) vc_df=(subset(ToothGrowth,supp=='VC')[c(1,3)]) # Vitamin C sd(vc_df$len) mean(vc_df$len) ``` Standard deviance too diffrent in 2 groups (OJ and VC) so we should use parameter var.equal=FALSE in t.test() ## Group dataset by dose ```{r} D05 <- subset(ToothGrowth,dose==.5) D1 <- subset(ToothGrowth,dose==1) D2 <- subset(ToothGrowth,dose==2) # number observation in each group: table(ToothGrowth$supp,ToothGrowth$dose) ``` ## T-test of each group ```{r} T05 <- t.test(len~supp,paired=FALSE,var.equal=FALSE,data=D05) T1 <- t.test(len~supp,paired=FALSE,var.equal=FALSE,data=D1) T2 <- t.test(len~supp,paired=FALSE,var.equal=FALSE,data=D2) ``` ```{r} T05$conf.int T1$conf.int T2$conf.int ``` ## Conclusion For dose 2 mg the supplement form doesn't have significance But for doses 0.5 and 1 mg OJ significally better.<file_sep>/hw3.R #Load the data set mtcars in the datasets R package. Calculate a 95% confidence interval to the nearest MPG for the variable mpg. # # What is the lower endpoint of the interval? # What is the upper endpoint of the interval? # # Do library(datasets) and then data(mtcars) to get the data. Consider t.test for calculations. You may have to install the datasets package. t.test(mtcars$mpg) #Suppose that standard deviation of 9 paired differences is 1. What value would #the average difference have to be so that the lower endpoint of a 95% students # t confidence interval touches zero? mn <- qt(.975,8)/3 # Give the number here to two decimal places # Consider the mtcars dataset. Construct a 95% T interval for MPG comparing 4 to # 6 cylinder cars (subtracting in the order of 4 - 6) assume a constant # variance. # # What is the lower endpoint of the interval to 1 decimal place? What is the # upper endpoint of the interval to 1 decimal place? tresult <- t.test(mpg~cyl,data=subset(mtcars,cyl %in% c(4,6)),paired=FALSE,var.equal=TRUE) signif(tresult$conf.int,3) tresult # Suppose that 18 obese subjects were randomized, 9 each, to a new diet pill and # a placebo. Subjects' body mass indices (BMIs) were measured at a baseline and # again after having received the treatment or placebo for four weeks. The # average difference from follow-up to the baseline (followup - baseline) was 3 # kg/m2 for the treated group and 1 kg/m2 for the placebo group. The # corresponding standard deviations of the differences was 1.5 kg/m2 for the # treatment group and 1.8 kg/m2 for the placebo group. The study aims to answer # whether the change in BMI over the four week period appear to differ between # the treated and placebo groups. # What is the pooled variance estimate? (to 2 decimal places) n1 <- n2 <- 9 x1 <- -3 ##treated x2 <- 1 ##placebo s1 <- 1.5 ##treated s2 <- 1.8 ##placebo spsq <- ( (n1 - 1) * s1^2 + (n2 - 1) * s2^2) / (n1 + n2 - 2) S_p_2 <- ((8))<file_sep>/quiz3_calc.R # Question 1 # # In a population of interest, a sample of 9 men yielded a sample average brain # volume of 1,100cc and a standard deviation of 30cc. What is a 95% Student's T # confidence interval for the mean brain volume in this new population? # [1077,1123] [1092, 1108] [1031, 1169] [1080, 1120] bme <- 1100 bsd <- 30 bme+c(-1,1)*qt(.975,8)*bsd/sqrt(9) # Question 2 # # A diet pill is given to 9 subjects over six weeks. The average difference in # weight (follow up - baseline) is -2 pounds. What would the standard deviation # of the difference in weight have to be for the upper endpoint of the 95% T # confidence interval to touch 0? 2.10 1.50 2.60 0.30 sigma <- 2*3/(qt(.975,8)) sigma # Question 7 #Suppose that 18 obese subjects were randomized, 9 each, to a new diet pill and #a placebo. Subjects’ body mass indices (BMIs) were measured at a baseline and #again after having received the treatment or placebo for four weeks. The #average difference from follow-up to the baseline (followup - baseline) was −3 #kg/m2 for the treated group and 1 kg/m2 for the placebo group. The #corresponding standard deviations of the differences was 1.5 kg/m2 for the #treatment group and 1.8 kg/m2 for the placebo group. Does the change in BMI #over the four week period appear to differ between the treated and placebo #groups? Assuming normality of the underlying data and a common population #variance, calculate the relevant *90%* t confidence interval. Subtract in the #order of (Treated - Placebo) with the smaller (more negative) number first. xm <- -3 ; ym <- 1 xsd <- 1.5 ; ysd <- 1.8 Sp <- (1.5+1.8)/2 Sp <- sqrt((1.5^2+1.8^2))/2 xm-ym + c(-1,1)*qt(.95,18-2)*Sp*sqrt(2/9) # Question 6 xm <- 4 ; xsd <- 0.6 ym <- 5 ; yvar <- 0.68 Sp <- sqrt(mean(c(xvar,yvar))) xm-ym +c(-1,1)*qt(.975,10+10-2)*Sp*sqrt(2/10)
701cf7714dba4cbd626060ca0757d70247651461
[ "R", "RMarkdown" ]
4
RMarkdown
ilya-kochergin/coursera-statinfer-cproject
f9cbaeaf4ff7712eeab18d1404429ba3d25cf3d6
bbc525f27651fcc619dae09d354864792d2336fc
refs/heads/master
<file_sep>import java.util.Arrays; import java.util.Random; public class Main { public static void main(String[] args) { int array[] = new int[1000]; Random rand = new Random(); for (int i = 0; i < array.length; i++) { array[i] = rand.nextInt(10000); } long start = System.nanoTime(); Integer[] sortedArray = AVLTree.sort(array); long time = System.nanoTime() - start; System.out.println("Time required to sort this array using AVL Sort Algorithm is : " + (time / 100000 / 1000.0) + " seconds!"); System.out.println(Arrays.toString(sortedArray)); System.out.println("*************************************"); // create an AVL Tree AVLTree tree = new AVLTree(); Node root = new Node(5); tree.root = root; // Insert new nodes in the AVL Tree and maintain the AVL property tree.insert(new Node(7)); tree.insert(new Node(9)); tree.postOrderTraversal(tree.root); } } <file_sep>import java.util.HashMap; /** * @author <NAME> * @context This class illustrate a solution for the document distance problem * * Document distance problem : We're giving 2 documents D1 and D2 and we want to compute the * distance between them, in other words we want to have an idea about * how identical those 2 documents are. * */ public class Main { public static void main(String[] args) { String doc1 = "Appreciation is a wonderful thing: It makes what is excellent in others belong to us as well"; String doc2 = "Parting is such sweet sorrow that i shall say goodnight till it be morrow"; Double distance = getDistanceBetween2Docs(doc1, doc2); distance = Math.floor(distance * 100) / 100; if (distance == 0.0d) { System.out.println("These 2 documents are identical, with a score of : " + distance); } else if (distance == 1.57d) { System.out.println("These 2 documents have no common words, with a score of : " + distance); } else { System.out.println("These 2 documents are different, score is : " + distance); } } /** * * @param document which is a sequence of words * @return array of words in a document without punctuation and whitespace * */ public static String[] getWordsInDocWithoutPun(String document) { String[] words = document.split("[\\p{Punct}\\s]+"); return words; } /** * * @param arrray of words in a document * @return list of all words and how many time each word occurs in the document * */ public static HashMap<String, Integer> computeWordFrequencesInDoc(String[] words) { HashMap<String, Integer> documentVector = new HashMap<String, Integer>(); for (int i = 0; i < words.length; i++) { Integer oldValue = documentVector.get(words[i].toLowerCase()); Integer occurrence = (oldValue == null) ? 1 : oldValue + 1; documentVector.put(words[i].toLowerCase(), occurrence); } return documentVector; } public static Integer computeInnerProduct(HashMap<String, Integer> docVector1, HashMap<String, Integer> docVector2) { Integer sum = 0; HashMap<String, Integer> smallesttDocVector = (docVector1.size() < docVector2.size()) ? docVector1 : docVector2; HashMap<String, Integer> largestDocVector = (docVector1.size() > docVector2.size()) ? docVector1 : docVector2; for (String key : smallesttDocVector.keySet()) { if (largestDocVector.containsKey(key)) { sum += docVector1.get(key) * docVector2.get(key); } } return sum; } /** * * @param doc1 * @param doc2 * @return the distance between the documents doc1 and doc2 * */ public static Double getDistanceBetween2Docs(String doc1, String doc2) { Double angle = 0.0d; HashMap<String, Integer> docVector1 = computeWordFrequencesInDoc(getWordsInDocWithoutPun(doc1)); HashMap<String, Integer> docVector2 = computeWordFrequencesInDoc(getWordsInDocWithoutPun(doc2)); Integer numerator = computeInnerProduct(docVector1, docVector2); Double denominator = Math.sqrt(computeInnerProduct(docVector1, docVector1)) * Math.sqrt(computeInnerProduct(docVector2, docVector2)); angle = Math.acos(numerator / denominator); return angle; } }<file_sep>import java.util.Arrays; import java.util.Random; /** * @author <NAME> * @context This class implements the Counting Sort algorithm which is a sorting algorithm that uses the power * of the RAM to get an array sorted in linear time. * */ public class Main { public static void main(String argv[]) { int array[] = new int[100]; Random rand = new Random(); for (int i = 0; i < array.length; i++) { array[i] = rand.nextInt(100); } long start = System.nanoTime(); int[] sortedArray = sortUsingCountingSort(array); long time = System.nanoTime() - start; System.out.println("Time required to sort this array using Counting Sort Algorithm is : " + (time / 100000 / 1000.0) + " seconds!"); System.out.println(Arrays.toString(sortedArray)); } /** * @context This algorithm implements the counting sort algorithm * @complexity the worst case complexity of this algorithm is order (n + k) where n is the size of the problem * and k is the range where fit all the values. * @param array to be sorted * @return sorted array */ public static int[] sortUsingCountingSort(int[] array) { // Find Max int max = array[0]; for (int i = 0; i < array.length; i++) { max = (array[i] > max) ? array[i] : max; } int[] counts = new int[max + 1]; int[] sortedArray = new int[array.length]; for (int i = 0; i < array.length; i++) { counts[array[i]]++; } for (int i = 1; i < counts.length; i++) { counts[i] += counts[i - 1]; } for (int i = 0; i < array.length; i++) { sortedArray[counts[array[i]] - 1] = array[i]; counts[array[i]]--; } return sortedArray; } } <file_sep>/** * @author <NAME> * * @context This project illustrate an implementation of the Heap data structure, and the Heap Sort algorithm. */ public class Main { public static void main(String[] args) { Node[] array = new Node[7]; array[0] = new Node(2); array[1] = new Node(9); array[2] = new Node(3); array[3] = new Node(5); array[4] = new Node(4); array[5] = new Node(7); array[6] = new Node(2); Heap heap = new Heap(array); // Display the Heap System.out.print("Display Heap"); heap.displayHeap(); System.out.println("*****************"); Heap maxHeap = Heap.buildMaxHeap(array); // Display the Max-Heap System.out.println("Display Max Heap"); maxHeap.displayHeap(); // Sort the array using Heap Sort algorithm Node[] sortedArray = Heap.sort(array); System.out.println("*****************"); System.out.println("Display Sorted Array using Heap Sort Algorithm"); for (int i = 0; i < sortedArray.length; i++) { System.out.print(sortedArray[i].getKey()+ " "); } } } <file_sep>import java.util.Arrays; /** * This class implements the heap data structure and the Heap Sort algorithm */ class Heap { private Node[] heapArray; private int heapSize; public Heap(Node[] array) { heapArray = array; heapSize = array.length; } public boolean isEmpty() { return heapSize == 0; } /** * @param maxHeap, heap which maintains the Max-heap property * @return the maximum element in the Max-heap which corresponds to the node at index 0 */ public static Node returnMaxNode(Heap maxHeap) { return (maxHeap.isEmpty()) ? null : maxHeap.heapArray[0]; } /** * @param heap * @return true if it is a Max-heap otherwise return false */ public static boolean isMaxHeap(Heap heap) { for (int i = 0; i < (heap.heapSize / 2); i++) { if (heap.heapArray[i].getKey() < heap.heapArray[2 * i + 1].getKey() || heap.heapArray[i].getKey() < heap.heapArray[2 * i + 2].getKey()) { return false; } } return true; } /** * @context this method is used to correct a single violation of the max-heap property in a subtree's root indexed by * index * * @param array * @param index, the root of the subtree where the violation of the max-heap property might occur * @return the heap after correcting the violation */ public static Node[] maxHeapify(Node[] array, int index) { if ((array == null || index < 0 || index >= (array.length / 2)) || ((((2 * index + 2) >= array.length) && array[index].getKey() >= array[2 * index + 1].getKey()) || ((2 * index + 2) < array.length && array[index].getKey() >= array[2 * index + 1].getKey() && array[index].getKey() >= array[2 * index + 2].getKey()))) return array; int indexOfLargestkey = 0; if ((2 * index + 2) < array.length) indexOfLargestkey = (array[2 * index + 1].getKey() > array[2 * index + 2].getKey()) ? (2 * index + 1) : (2 * index + 2); else indexOfLargestkey = 2 * index + 1; int temp = array[index].getKey(); array[index].setKey(array[indexOfLargestkey].getKey()); array[indexOfLargestkey].setKey(temp); return maxHeapify(array, indexOfLargestkey); } /** * @context This method produces a Max-heap from an unordered array * @param array * @return the Max-heap associated with the array */ public static Heap buildMaxHeap(Node[] array) { Node[] maxheapAsArray = new Node[array.length]; for (int i = array.length / 2 - 1; i >= 0; i--) { maxheapAsArray = maxHeapify(array, i); } return new Heap(maxheapAsArray); } /** * @context this method implements the Heap Sort algorithm. * @complexity The worst-case complexity of this algorithm is n*log(n) * @param array * @return the sorted array using Heap Sort algorithm */ public static Node[] sort(Node[] array) { Heap maxHeap = buildMaxHeap(array); Node[] sortedArray = new Node[array.length]; for (int i = 0; i < sortedArray.length; i++) { sortedArray[i] = new Node(returnMaxNode(maxHeap).getKey()); int tempval = array[0].getKey(); array[0].setKey(array[array.length - 1].getKey()); array[array.length - 1].setKey(tempval); array = Arrays.copyOf(array, array.length - 1); array = maxHeapify(array, 0); } return sortedArray; } /** * Draw and display a heap in its tree form */ public void displayHeap() { int numberOfLevels = (int) (Math.ceil(Math.log(heapSize + 1) / Math.log(2))); int nodePosition = (int) Math.pow(2, numberOfLevels) + 1; for (int i = 0; i < heapSize; i++) { double temp = Math.log(i + 1) / Math.log(2); if ((int) temp == temp) { nodePosition /= 2; System.out.println(""); System.out.format("%" + (nodePosition) + "s", ""); System.out.print(heapArray[i].getKey()); } else { System.out.format("%" + (nodePosition * 2 - 1) + "s", ""); System.out.print(heapArray[i].getKey()); } } System.out.println(""); } }
23153b53b46cce6ba276d10147ca6d122f61ca08
[ "Java" ]
5
Java
Bennasser-Chafi/Algorithmics
e73a0e8d4a5ab9e3c936aff31c5396732aa717d8
d6c2dc456072316d24253ec99d04a5db08196424
refs/heads/master
<repo_name>krabbyCTL/cys-statics<file_sep>/get.sh #!/bin/sh main() { need_cmd curl need_cmd wget need_cmd uname need_cmd tar need_cmd gzip need_cmd bzip2 need_cmd xz rm -rf ~/.cys mkdir -p ~/.cys pushd ~/.cys info "Downloading Tar files" wget https://github.com/crazystylus/cys-statics/releases/download/v0.1-alpha/cys-zgen.tar.xz unxz cys-zgen.tar.xz wget https://github.com/crazystylus/cys-statics/releases/download/v0.1-alpha/cys.tar.xz unxz cys.tar.xz info "Creating Demo Config file" cat <<EOF >>PackageConfig.toml ThemeFiles = [ "${HOME}/.cys/cys-zgen.tar" ] CompressionFactor = 9 ZipTypes = [ "gzip", "bzip2", "xz" ] EOF info "Getting Binaries" _ostype="$(uname -s)" _cputype="$(uname -m)" _binname="null" case $_cputype in x86_64 | x86-64 | amd64) _cputype="x86_64" ;; *) error "No binaries are available for your CPU architecture ($_cputype)" ;; esac case $_ostype in Linux) _binname="cys-linux.xz" ;; Darwin) _binname="cys-osx.xz" ;; *) error "No binaries are available for your operating system ($_ostype)" ;; esac wget -O "cys.xz" "https://github.com/crazystylus/cys-statics/releases/download/v0.1-alpha/${_binname}" unxz "cys.xz" chmod +x cys popd info "You may copy ~/.cys/cys binary to /usr/bin/cys or /usr/local/bin/cys" info "Examples To create an patched theme run ~/.cys/cys package -pv --theme-name patched To create an un-patched default theme run ~/.cys/cys package -v To SSH to an host with a theme run ~/.cys/cys ssh -c \".tar.xz\" --theme-name patched admin@ubuntu **NOTE** compression format needs to be supported on remote system " } success() { printf "\033[32m%s\033[0m\n" "$1" >&1 } info() { printf "%s\n" "$1" >&1 } warning() { printf "\033[33m%s\033[0m\n" "$1" >&2 } error() { printf "\033[31;1m%s\033[0m\n" "$1" >&2 exit 1 } cmd_chk() { command -v "$1" >/dev/null 2>&1 } ## Ensures that the command executes without error ensure() { if ! "$@"; then error "command failed: $*"; fi } need_cmd() { if ! cmd_chk "$1"; then error "need $1 (command not found)" fi } main "$@" || exit 1 <file_sep>/README.md # cys-statics Contains static files for CarryYourShell ## Installation Only Linux and MacOSX supported currently (amd64/x86_64)<br/> Remotely only supports Linux(amd64/x86_64) <br/> ```shell curl "https://raw.githubusercontent.com/crazystylus/cys-statics/master/get.sh" | sh ``` **NOTE** All files are stores in ~/.cys and /tmp/cys. You may purge them for removing demo completely
6e458ee89f765c460745a3c5749b31e30d085511
[ "Markdown", "Shell" ]
2
Shell
krabbyCTL/cys-statics
33752ad8bc1f7cc53487cea4130deaf09927c0fd
792ba26d72cb078bc64b4ac890639cd4645f9c72
refs/heads/master
<repo_name>hitoyozake/sandbox<file_sep>/python/scrap.py # -* encoding: utf-8 *- import requests import lxml.html response = requests.get('http://gihyo.jp') root = lxml.html.fromstring(response.content) print(root) for a in root.cssselect('#mdHeading01Txt') <file_sep>/README.md # sandbox 言語の各機能を試したり コードをちょっと試したりするリポジトリ This repository is for Testing functions of languages, and short codes.
afa7ccf94157ee3d6c77444760292a642540bca1
[ "Markdown", "Python" ]
2
Python
hitoyozake/sandbox
4bdb376a9cd834b7c06a5a4914771a56fc83b18a
e8d6fe56cbcac581f529dbdf5b1a2b3bfdaa41f5
refs/heads/master
<file_sep>// polyfill React in IE < 11 import 'core-js/es6/map'; import 'core-js/es6/set'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; // rem 适配 (function (window) { var docWidth = 750 // 设计图宽度 var rate = 100 // 1rem = 100px var minWidth = 320 // 允许的文档最小宽度,低于此不再缩小 var maxWidth = 414 // 允许的文档最大宽度,高于此不再放大 var doc = window.document var html = doc.documentElement function calcRem () { var clientWidth = html.getBoundingClientRect().width html.style.fontSize = Math.max(Math.min(clientWidth, maxWidth), minWidth) / (docWidth / rate) + 'px' } window.addEventListener('resize', calcRem, false) doc.addEventListener('DOMContentLoaded', calcRem, false) })(window) ReactDOM.render(<App />, document.getElementById('root')); <file_sep>### 借助 [seamless-scroll](https://github.com/HaoChuan9421/seamless-scroll) 实现“无缝滚动”的 `Demo` 项目 > 基于 [Create React App](https://github.com/facebook/create-react-app) 创建的模板项目开发。 [扫码体验移动端](https://github.com/HaoChuan9421/seamless-scroll/raw/master/assets/qrcode.png)&emsp;[点击预览 PC 端](https://haochuan9421.github.io/seamless-scroll-demo/)&emsp; <img src="https://github.com/HaoChuan9421/seamless-scroll/raw/master/assets/qrcode.png" width="200" /> ## Browser support | <img src="https://github.com/HaoChuan9421/seamless-scroll/raw/master/assets/chrome.png" width="16px" height="16px" /></br>Chrome | <img src="https://github.com/HaoChuan9421/seamless-scroll/raw/master/assets/firefox.png" width="16px" height="16px" /></br>Firefox | <img src="https://github.com/HaoChuan9421/seamless-scroll/raw/master/assets/safari.png" width="16px" height="16px" /></br>Safari | <img src="https://github.com/HaoChuan9421/seamless-scroll/raw/master/assets/ie.png" width="16px" height="16px" /></br>IE | <img src="https://github.com/HaoChuan9421/seamless-scroll/raw/master/assets/ios.png" width="16px" height="16px" /></br>iOS | <img src="https://github.com/HaoChuan9421/seamless-scroll/raw/master/assets/android.png" width="16px" height="16px" /></br>Android | | :------------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------: | | &check; | &check; | 9.1+ | 10+ | 9+ | 5+ | <file_sep>import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'; import Mobile from './pages/Mobile'; import PC from './pages/PC'; class App extends Component { render() { return ( <Router basename={process.env.PUBLIC_URL}> <Switch> <Route path='/' exact render={() => <Redirect to={window.screen.width < 1024 ? '/mobile' : '/pc'} />} /> <Route path='/mobile' exact component={Mobile} /> <Route path='/pc' exact component={PC} /> </Switch> </Router> ); } } export default App;
ddd176b31bd0c2563c871d74d674fa698cf6e96f
[ "JavaScript", "Markdown" ]
3
JavaScript
HaoChuan9421/seamless-scroll-demo
ddd5fd2d722022453eb130ab6c370013000f3938
609c5c0f030d50deb35dc55363e62df3cabfc9f7
refs/heads/master
<file_sep>#include <protocol.h> void protocol_init(void) { } <file_sep>#include "stm32f10x.h" #include "stm32f10x_exti.h" #include <io.h> #include "FreeRTOS.h" #include "timers.h" // Port numbers: 0=A, 1=B, 2=C, 3=D, 4=E, 5=F, 6=G, ... #define LED_PORT_NUMBER (2) #define LED_PIN_NUMBER (13) #define IO_GPIOx(_N) ((GPIO_TypeDef *)(GPIOA_BASE + (GPIOB_BASE-GPIOA_BASE)*(_N))) #define IO_PIN_MASK(_N) (1 << (_N)) #define IO_RCC_MASKx(_N) (RCC_APB2Periph_GPIOA << (_N)) #define BUTTON_PORT_NUMBER (0) #define BUTTON_PIN_NUMBER (4) #define BUTTON_LONG_PRESS_TIMEOUT (3000) typedef struct { io_button_pressed_cb_t button_state_listener; io_module_hit_cb_t module_hit_listener; TimerHandle_t button_timer; } ctx_t; static ctx_t ctx = {0}; static void io_init_led(void) { // Enable GPIO Peripheral clock RCC_APB2PeriphClockCmd(IO_RCC_MASKx(LED_PORT_NUMBER), ENABLE); GPIO_InitTypeDef GPIO_InitStructure; // Configure pin in output push/pull mode GPIO_InitStructure.GPIO_Pin = IO_PIN_MASK(LED_PIN_NUMBER); GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(IO_GPIOx(LED_PORT_NUMBER), &GPIO_InitStructure); // Start with led turned off io_set_led_state(false); } static void button_press(TimerHandle_t xTimer) { if(ctx.button_state_listener) { ctx.button_state_listener(IO_BUTTON_LONG_PRESS); } } static void io_init_button(void) { ctx.button_timer = xTimerCreate("bt740_tim",pdMS_TO_TICKS(BUTTON_LONG_PRESS_TIMEOUT),false,(void *)&ctx ,button_press); // Enable GPIO Peripheral clock RCC_APB2PeriphClockCmd(IO_RCC_MASKx(BUTTON_PORT_NUMBER), ENABLE); GPIO_InitTypeDef GPIO_InitStructure; // Configure pin in output push/pull mode GPIO_InitStructure.GPIO_Pin = IO_PIN_MASK(BUTTON_PIN_NUMBER); GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_Init(IO_GPIOx(LED_PORT_NUMBER), &GPIO_InitStructure); NVIC_EnableIRQ(EXTI4_IRQn); /* Tell system that you will use PA4 for EXTI_Line4 */ GPIO_EXTILineConfig(GPIO_PortSourceGPIOA,GPIO_PinSource4); EXTI_InitTypeDef EXTI_InitStruct; /* PA4 is connected to EXTI_Line4 */ EXTI_InitStruct.EXTI_Line = EXTI_Line4; /* Enable interrupt */ EXTI_InitStruct.EXTI_LineCmd = ENABLE; /* Interrupt mode */ EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt; /* Triggers on rising and falling edge */ EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Rising_Falling; /* Add to EXTI */ EXTI_Init(&EXTI_InitStruct); } void EXTI4_IRQHandler(void) { /* Make sure that interrupt flag is set */ if (EXTI_GetITStatus(EXTI_Line4) != RESET) { /* Do your stuff when PA4 is changed */ if(xTimerIsTimerActive(ctx.button_timer)) { xTimerStop(ctx.button_timer, 0 ); if(ctx.button_state_listener) { ctx.button_state_listener(IO_BUTTON_SHORT_PRESS); } } else { xTimerStart(ctx.button_timer, 0 ); } /* Clear interrupt flag */ EXTI_ClearITPendingBit(EXTI_Line4); } } static void io_init_avalanche_beacon(void) { } static void io_init_module_hit_sensor(void) { } void io_init(void) { /* init LED */ io_init_led(); /* init button */ io_init_button(); /* avalnache beacon */ io_init_avalanche_beacon(); /* module hit detection */ io_init_module_hit_sensor(); } void io_set_led_state(bool state) { if(state) { GPIO_ResetBits(IO_GPIOx(LED_PORT_NUMBER),IO_PIN_MASK(LED_PIN_NUMBER)); } else { GPIO_SetBits(IO_GPIOx(LED_PORT_NUMBER),IO_PIN_MASK(LED_PIN_NUMBER)); } } void io_button_register_listener(io_button_pressed_cb_t cb) { ctx.button_state_listener = cb; } void io_set_avalnache_beacon_state(bool state) { } void io_module_hit_register_listener(io_module_hit_cb_t cb) { ctx.module_hit_listener = cb; } <file_sep>#ifndef STORAGE_H_ #define STORAGE_H_ #include <global.h> typedef enum { DEVICE_TYPE_ROUTER, DEVICE_TYPE_AVALANCHE_BEACON, } device_type_t; void storage_init(void); void storage_set_device_type(device_type_t type); void storage_get_device_type(device_type_t *type); void storage_set_paired_state(bool paired); bool storage_is_paired(void); void storage_set_router_bt_address(uint8_t *bt_address); void storage_get_router_bt_address(uint8_t *bt_address); #endif <file_sep>/* * ToDO: * - add storing bt address of received messages * - pairing * - long press reset * - sending comands to router (I'm online, Module was hitted) * - router commands (hello, enable avalanche beacon) * * Done: * - module storage * - thread safe BT740_sendCmd() + callback * - device type to storage (router, end device) * - led API * - button handling * - get friendly name (command) * - SPP sending messages protocol * - SPP receiving messages */ #include <stdio.h> #include <stdlib.h> /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "stm32f10x.h" #include <bt740.h> #include <eeprom.h> #include <os.h> #include <storage.h> #include <io.h> //#define DEBUG_ON #include <debug.h> // Sample pragmas to cope with warnings. Please note the related line at // the end of this function, used to pop the compiler diagnostics status. #pragma GCC diagnostic push //#pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wmissing-declarations" #pragma GCC diagnostic ignored "-Wreturn-type" void app_task(void *params); int main(int argc, char* argv[]) { DEBUG_INIT(); DEBUG_PRINTF("System clock: %u Hz\r\n", SystemCoreClock); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4); /* IO */ io_init(); /* init flash data storage */ storage_init(); /* init BT740 bluetooth module */ BT740_init(); xTaskCreate(app_task, "app_task", 512, NULL, OS_TASK_PRIORITY, NULL); /* Start the scheduler. */ vTaskStartScheduler(); // Infinite loop for(;;); } void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName ) { for(;;); } #pragma GCC diagnostic pop // ---------------------------------------------------------------------------- <file_sep>/** \file os.h * \brief OS helper definition file */ #ifndef OS_H #define OS_H #include <task.h> #define OS_TASK_NOTIFY_MASK 0xFFFFFFFF #define OS_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define OS_TASK_NOTIFY(task, value) \ ({ \ BaseType_t need_switch, ret; \ ret = xTaskNotifyFromISR(task, value, eSetBits, &need_switch); \ portEND_SWITCHING_ISR(need_switch); \ ret; \ }) #define OS_QUEUE_PUT_FROM_ISR(queue, item) \ ({ \ BaseType_t need_switch, ret; \ ret = xQueueSendToBackFromISR((queue), (item), &need_switch); \ portEND_SWITCHING_ISR(need_switch); \ ret; \ }) #define APP_BT_MODULE_READY_NOTIF (1 << 1) #define APP_BT_MODULE_RESPONSE_NOTIF (1 << 2) #define APP_SHORT_PRESS_NOTIF (1 << 3) #define APP_LONG_PRESS_NOTIF (1 << 4) #define APP_MODULE_HITTED_NOTIF (1 << 5) #define APP_SPP_DATA_RECEIVED_NOTIF (1 << 6) #define BT740_RESPONSE_WAITING_NOTIF (1 << 10) #define BT740_SETUP_DONE_NOTIF (1 << 11) #define BT740_SEND_COMMAND_NOTIF (1 << 12) #define BT740_SPP_CONNECTED_NOTIF (1 << 13) #define BT740_SPP_NO_CARRIER_NOTIF (1 << 14) #define BT740_SPP_ERROR_NOTIF (1 << 15) #define BT740_SPP_DISCONNECT_NOTIF (1 << 16) #define BT740_SPP_SEND_ESCAPE_CHAR_NOTIF (1 << 17) #endif /* OS_H */ <file_sep>/* e * ORANGE GND * BROWN TX A3(RX) * YELLOW RX A2(TX) * BLUE VCC * * FT232 blue gnd * green rxd */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "timers.h" #include "stm32f10x_usart.h" #include "stm32f10x.h" #include <global.h> #include <os.h> #include <bt740.h> #define DEBUG_ON #include <debug.h> #define CMD_LENGTH_MAX (30) #define QUEUE_MAX_ITEMS (5) #define QUEUE_ITEM_SIZE (RESPONSE_DATA_LENGTH) typedef struct { char cmdString[CMD_LENGTH_MAX]; } cmd_info_t; typedef struct { uint8_t buffer[RESPONSE_DATA_LENGTH]; uint8_t length; } response_t; typedef struct { uint8_t bt_address[BT_ADDRESS_STR_LENGTH]; uint8_t *data; uint8_t data_len; TimerHandle_t escape_timer; bool connection_active; data_receive_cb receive_cb; bt_status_t status; } spp_t; struct context { TaskHandle_t task; QueueHandle_t queue; TimerHandle_t bt740_setup_timer; bt_cmd_t cmd; bool processing_cmd; uint8_t cmdString[CMD_LENGTH_MAX]; cmd_response_cb cmd_response_cb; response_queue_t *response_queue; response_queue_t *response_queue_tail; state_cb module_state_cb; spp_t spp; }; static const cmd_info_t commands[] = { {"AT"}, // BT_CMD_STATUS_CHECK {"ATE0"}, // BT_CMD_ECHO_OFF {"AT+BTT?"}, // BT_CMD_GET_DEVICES {"AT&W"}, // BT_CMD_WIRTE_S_REGISTER: write S register to non-volatile memory {"AT+BTF%s"}, // BT_CMD_GET_FRIENDLY_NAME {"ATD%s,1101"}, // BT_CMD_SPP_START {"ATH"} // BT_CMD_SPP_STOP }; static response_t cmdResponse; static struct context ctx = {0}; static void bt740_task(void *params); static void bt_response_ready(void); static void usart_config(void) { USART_InitTypeDef usartConfig; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); USART_Cmd(USART2, ENABLE); usartConfig.USART_BaudRate = 9600; usartConfig.USART_WordLength = USART_WordLength_8b; usartConfig.USART_StopBits = USART_StopBits_1; usartConfig.USART_Parity = USART_Parity_No; usartConfig.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; usartConfig.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_Init(USART2, &usartConfig); GPIO_InitTypeDef gpioConfig; //PA2 = USART2.TX => Alternative Function Output gpioConfig.GPIO_Mode = GPIO_Mode_AF_PP; gpioConfig.GPIO_Pin = GPIO_Pin_2; gpioConfig.GPIO_Speed = GPIO_Speed_2MHz; GPIO_Init(GPIOA, &gpioConfig); //PA3 = USART2.RX => Input gpioConfig.GPIO_Mode = GPIO_Mode_IN_FLOATING; gpioConfig.GPIO_Pin = GPIO_Pin_3; GPIO_Init(GPIOA, &gpioConfig); /* Enable RXNE interrupt */ USART_ITConfig(USART2, USART_IT_RXNE, ENABLE); /* Enable USART2 global interrupt */ NVIC_EnableIRQ(USART2_IRQn); } void BT740_init(void) { /* create task for communication with other devices */ xTaskCreate(bt740_task, "bt740_task", 3072, NULL, OS_TASK_PRIORITY, NULL); } void send_char(char c) { while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET); USART_SendData(USART2, c); DEBUG_PRINTF("%c",c); } void send_buffer(uint8_t *data, uint8_t data_len) { while(data_len) { send_char(*data++); data_len--; } } void send_cmd_string(const char *s) { while (*s) { send_char(*s++); } send_char('\r'); // send \r character DEBUG_PRINTF("\n"); } void BT740_sendCmd(bt_cmd_t *cmd, cmd_response_cb cb) { // save command in the context memcpy(&ctx.cmd, cmd, sizeof(bt_cmd_t)); ctx.cmd_response_cb = cb; OS_TASK_NOTIFY(ctx.task, BT740_SEND_COMMAND_NOTIF); } void BT740_register_for_spp_data(data_receive_cb cb) { ctx.spp.receive_cb = cb; } void BT740_response_free(response_queue_t *resp) { response_queue_t *p; while(resp) { p = resp; resp = resp->next; free(p); } } static void bt_spp_start_respone(bt_status_t status, response_queue_t *resp) { switch(status) { case BT_STATUS_CONNECTED: OS_TASK_NOTIFY(ctx.task, BT740_SPP_CONNECTED_NOTIF); break; case BT_STATUS_ERROR: OS_TASK_NOTIFY(ctx.task, BT740_SPP_ERROR_NOTIF); break; case BT_STATUS_NO_CARRIER: OS_TASK_NOTIFY(ctx.task, BT740_SPP_NO_CARRIER_NOTIF); break; default: break; } BT740_response_free(resp); } static void bt_spp_stop_respone(bt_status_t status, response_queue_t *resp) { ctx.spp.status = status; OS_TASK_NOTIFY(ctx.task, BT740_SPP_DISCONNECT_NOTIF); BT740_response_free(resp); } void BT740_send_spp_data(uint8_t bt_address[], uint8_t *data, uint8_t data_len) { bt_cmd_t cmd; if(ctx.spp.connection_active) { return; } else { ctx.spp.connection_active = true; } ctx.spp.data_len = data_len; ctx.spp.data = data; memcpy(ctx.spp.bt_address,bt_address,BT_ADDRESS_STR_LENGTH); cmd.type = BT_CMD_SPP_START; sprintf(cmd.params.bt_address,"%s",bt_address); BT740_sendCmd(&cmd,bt_spp_start_respone); return; } static void queue_put_response() { uint8_t *item; item = malloc(RESPONSE_DATA_LENGTH); if(!item) { return; } memcpy(item, cmdResponse.buffer, RESPONSE_DATA_LENGTH); OS_QUEUE_PUT_FROM_ISR(ctx.queue, &item); } void USART2_IRQHandler(void) { uint8_t received_data; /* RXNE handler */ if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) { received_data = (uint8_t)USART_ReceiveData(USART2); cmdResponse.buffer[cmdResponse.length] = received_data; cmdResponse.length++; if(cmdResponse.length == RESPONSE_DATA_LENGTH) { cmdResponse.length = 0; } if(received_data == '\r') { if(cmdResponse.length == 1) { cmdResponse.length = 0; cmdResponse.buffer[0] = 0; } else { queue_put_response(); bt_response_ready(); cmdResponse.length = 0; memset(cmdResponse.buffer, 0, RESPONSE_DATA_LENGTH); } } else if((received_data == '\n') && (cmdResponse.length == 1)) { cmdResponse.length = 0; cmdResponse.buffer[0] = 0; } else { /* wait for some more bytes */ } } } static void bt_response_ready(void) { OS_TASK_NOTIFY(ctx.task, BT740_RESPONSE_WAITING_NOTIF); } static void bt740_ready(TimerHandle_t xTimer) { OS_TASK_NOTIFY(ctx.task, BT740_SETUP_DONE_NOTIF); } static bool is_echoed_cmd(uint8_t *response) { return (strncmp(ctx.cmdString, (char*)response, strlen(ctx.cmdString)) == 0); } static void handleCmd(void) { memset(ctx.cmdString,0,CMD_LENGTH_MAX); // send command to BT740 module switch(ctx.cmd.type) { case BT_CMD_GET_FRIENDLY_NAME: case BT_CMD_SPP_START: sprintf(ctx.cmdString,commands[ctx.cmd.type].cmdString,ctx.cmd.params.bt_address); break; default: sprintf(ctx.cmdString,"%s",commands[ctx.cmd.type].cmdString); break; } send_cmd_string(ctx.cmdString); ctx.processing_cmd = true; } void BT740_register_for_state(state_cb cb) { ctx.module_state_cb = cb; } static spp_stop(void) { bt_cmd_t cmd; cmd.type = BT_CMD_SPP_STOP; BT740_sendCmd(&cmd,bt_spp_stop_respone); } static void handleResponse(uint8_t *response) { if(ctx.processing_cmd && is_echoed_cmd(response)) { free(response); return; } DEBUG_PRINTF("Received:%s\r\n",response); if(strncmp("OK", (char*)response, strlen("OK")) == 0) { if(ctx.spp.connection_active) { spp_stop(); } else if(ctx.cmd_response_cb) { ctx.cmd_response_cb(BT_STATUS_OK, ctx.response_queue); ctx.response_queue = NULL; ctx.cmd_response_cb = NULL; } ctx.processing_cmd = false; } else if(strncmp("ERROR", (char*)response, strlen("ERROR")) == 0) { if(ctx.cmd_response_cb) { ctx.cmd_response_cb(BT_STATUS_ERROR, ctx.response_queue); ctx.response_queue = NULL; ctx.cmd_response_cb = NULL; } ctx.processing_cmd = false; } else if(strncmp("CONNECT", (char*)response, strlen("CONNECT")) == 0) { if(ctx.cmd_response_cb) { ctx.cmd_response_cb(BT_STATUS_CONNECTED, NULL); ctx.response_queue = NULL; ctx.cmd_response_cb = NULL; } else if (ctx.spp.connection_active) { if(ctx.spp.receive_cb) { ctx.spp.receive_cb(BT_STATUS_CONNECTED,NULL,0); } } ctx.processing_cmd = false; } else if(strncmp("NO CARRIER", (char*)response, strlen("NO CARRIER")) == 0) { if(ctx.cmd_response_cb) { ctx.cmd_response_cb(BT_STATUS_NO_CARRIER, NULL); ctx.response_queue = NULL; ctx.cmd_response_cb = NULL; } else if (ctx.spp.connection_active) { if(ctx.spp.receive_cb) { ctx.spp.receive_cb(BT_STATUS_NO_CARRIER,NULL,0); } } ctx.processing_cmd = false; } else if(strncmp("RING", (char*)response, strlen("RING")) == 0) { ctx.spp.connection_active = true; if(ctx.spp.receive_cb) { ctx.spp.receive_cb(BT_STATUS_RING,NULL,0); } } else { response_queue_t *item; if(ctx.spp.connection_active) { uint8_t len = strlen(response); ctx.spp.data = malloc(len+1); if(!ctx.spp.data) { return; } sprintf(ctx.spp.data,"%s",response); ctx.spp.data_len = len; ctx.spp.receive_cb(BT_STATUS_DATA,ctx.spp.data,ctx.spp.data_len); } else { item = (response_queue_t*)malloc(sizeof(response_queue_t)); if(!item) { return; } if(BT_STATUS_NO_CARRIER) memcpy(item->data, response, RESPONSE_DATA_LENGTH); item->next = NULL; if(!ctx.response_queue) { ctx.response_queue = item; ctx.response_queue_tail = item; } else { ctx.response_queue_tail->next = item; ctx.response_queue_tail = item; } } } /* response handling here */ free(response); } static volatile uint8_t spp_escape_count; static void send_spp_escape_sequence(void) { spp_escape_count = 3; xTimerStart(ctx.spp.escape_timer, 0 ); } static void spp_escape(TimerHandle_t xTimer) { if(spp_escape_count == 0) { return; } OS_TASK_NOTIFY(ctx.task, BT740_SPP_SEND_ESCAPE_CHAR_NOTIF); spp_escape_count--; xTimerStart(ctx.spp.escape_timer, 0 ); } void handle_spp_connection(uint32_t notification) { if (notification & BT740_SPP_CONNECTED_NOTIF) { /* send data */ send_buffer(ctx.spp.data,ctx.spp.data_len); /* send escape sequence */ send_spp_escape_sequence(); /* ToDo: start response timer */ } if ((notification & BT740_SPP_ERROR_NOTIF) || (notification & BT740_SPP_NO_CARRIER_NOTIF)) { if(ctx.spp.receive_cb) { ctx.spp.receive_cb(false,NULL,0); } ctx.spp.connection_active = false; } if (notification & BT740_SPP_DISCONNECT_NOTIF) { if(ctx.spp.receive_cb) { bool status = false; if(ctx.spp.status == BT_STATUS_OK) { status = true; } ctx.spp.receive_cb(status,NULL,0); } ctx.spp.connection_active = false; } if(notification & BT740_SPP_SEND_ESCAPE_CHAR_NOTIF) { send_buffer("^",1); } } void bt740_task(void *params) { uint8_t *response; DEBUG_PRINTF("BT740 task started!\r\n"); ctx.task = xTaskGetCurrentTaskHandle(); ctx.queue = xQueueCreate(QUEUE_MAX_ITEMS, QUEUE_ITEM_SIZE); ctx.bt740_setup_timer = xTimerCreate("bt740_tim",pdMS_TO_TICKS(1500),false,(void *)&ctx ,bt740_ready); ctx.spp.escape_timer = xTimerCreate("spp_tim",pdMS_TO_TICKS(200),false,(void *)&ctx ,spp_escape); /* configure USART2 */ usart_config(); xTimerStart(ctx.bt740_setup_timer, 0 ); for(;;) { BaseType_t ret; uint32_t notification; // Wait on any of the event group bits, then clear them all ret = xTaskNotifyWait(0, OS_TASK_NOTIFY_MASK, &notification, pdMS_TO_TICKS(50)); if(ret == pdPASS) { if (notification & BT740_RESPONSE_WAITING_NOTIF) { if(!xQueueReceive(ctx.queue, &response, 0)) { continue; } handleResponse(response); } if (notification & BT740_SETUP_DONE_NOTIF) { if(ctx.module_state_cb) { ctx.module_state_cb(BT_MODULE_READY); } } if (notification & BT740_SEND_COMMAND_NOTIF) { handleCmd(); } handle_spp_connection(notification); } if(uxQueueMessagesWaiting(ctx.queue)) { OS_TASK_NOTIFY(ctx.task, BT740_RESPONSE_WAITING_NOTIF); } } } <file_sep>#ifndef BT740_H_ #define BT740_H_ #include <global.h> #define RESPONSE_DATA_LENGTH (30) typedef enum { BT_MODULE_OFFLINE, BT_MODULE_READY, BT_MODULE_SPP_CONNECTION, } bt_state_t; typedef enum { BT_CMD_STATUS_CHECK, BT_CMD_ECHO_OFF, BT_CMD_GET_DEVICES, BT_CMD_WIRTE_S_REGISTER, BT_CMD_GET_FRIENDLY_NAME, BT_CMD_SPP_START, BT_CMD_SPP_STOP, BT_CMD_WRITE_SREG_DISCOVERABLE, BT_CMD_WRITE_SREG_CONNECTABLE, BT_CMD_LAST, } bt_cmd_type_t; typedef union { uint8_t param; uint8_t bt_address[BT_ADDRESS_STR_LENGTH]; } bt_cmd_params_t; typedef struct { bt_cmd_type_t type; bt_cmd_params_t params; } bt_cmd_t; typedef enum { BT_STATUS_OK, BT_STATUS_CONNECTED, BT_STATUS_RING, BT_STATUS_DATA, BT_STATUS_ERROR = 0x10, BT_STATUS_NO_CARRIER, } bt_status_t; typedef struct response_queue { uint8_t data[RESPONSE_DATA_LENGTH]; struct response_queue *next; } response_queue_t; typedef void (*data_receive_cb)(bool status, uint8_t *data, uint8_t data_len); typedef void (*cmd_response_cb)(bt_status_t status, response_queue_t *resp); typedef void (*state_cb)(bt_state_t state); void BT740_init(void); void BT740_sendCmd(bt_cmd_t *cmd, cmd_response_cb cb); void BT740_response_free(response_queue_t *resp); void BT740_register_for_spp_data(data_receive_cb cb); void BT740_send_spp_data(uint8_t bt_address[], uint8_t *data, uint8_t data_len); void BT740_register_for_state(state_cb cb); #endif // BT740_H <file_sep>/** \file app.h * \brief APP definition file */ #ifndef APP_H #define APP_H void app_some_action(void); #endif /* APP_H */ <file_sep>#include <stm32f10x_flash.h> #include <storage.h> #include <eeprom.h> typedef enum { STORAGE_ADDRESS_DEVICE_TYPE, STORAGE_ADDRESS_PAIRED_STATE, STORAGE_ADDRESS_ROUTER_BT_ADDRESS, } storage_address_t; /* Virtual address defined by the user: 0xFFFF value is prohibited */ uint16_t VirtAddVarTab[] = { 0x0000, /* 2 bytes, device type */ 0x0001, /* 2 bytes, paired state */ 0x0002, /* 6 bytes, 1 bt_address */ 0x0003, /* 2 bt_address */ 0x0004, /* 3 bt_address */ 0x0005, /* 4 bt_address */ 0x0006, /* 5 bt_address */ 0x0007, /* 6 bt_address */ }; void storage_init(void) { /* Unlock the Flash Program Erase controller */ FLASH_Unlock(); /* EEPROM Init */ EE_Init(); } void storage_set_device_type(device_type_t type) { EE_WriteVariable(VirtAddVarTab[STORAGE_ADDRESS_DEVICE_TYPE], type); } void storage_get_device_type(device_type_t *type) { EE_ReadVariable(VirtAddVarTab[STORAGE_ADDRESS_DEVICE_TYPE],(uint16_t*)type); } bool storage_is_paired(void) { uint16_t tmp; EE_ReadVariable(VirtAddVarTab[STORAGE_ADDRESS_PAIRED_STATE],&tmp); return tmp; } void storage_set_paired_state(bool paired) { EE_WriteVariable(VirtAddVarTab[STORAGE_ADDRESS_PAIRED_STATE], paired); } void storage_set_router_bt_address(uint8_t *bt_address) { uint16_t *address = (uint16_t*)bt_address; EE_WriteVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS],address[0]); EE_WriteVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS+1],address[1]); EE_WriteVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS+2],address[2]); EE_WriteVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS+3],address[3]); EE_WriteVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS+4],address[4]); EE_WriteVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS+5],address[5]); } void storage_get_router_bt_address(uint8_t *bt_address) { uint16_t *address = (uint16_t*)bt_address; EE_ReadVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS],&address[0]); EE_ReadVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS+1],&address[1]); EE_ReadVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS+2],&address[2]); EE_ReadVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS+3],&address[3]); EE_ReadVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS+4],&address[4]); EE_ReadVariable(VirtAddVarTab[STORAGE_ADDRESS_ROUTER_BT_ADDRESS+5],&address[5]); } <file_sep>#ifndef DEBUG_H #define DEBUG_H #ifdef DEBUG_ON void debug_init(void); int debug(const char* format, ...); #define DEBUG_INIT() debug_init() #define DEBUG_PRINTF(...) debug(__VA_ARGS__) #else #define DEBUG_INIT() #define DEBUG_PRINTF(...) #endif #endif // DEBUG_H <file_sep>#ifndef IO_H_ #define IO_H_ #include <global.h> typedef enum { IO_BUTTON_SHORT_PRESS, IO_BUTTON_LONG_PRESS, } io_button_state_t; typedef void (*io_button_pressed_cb_t)(io_button_state_t state); typedef void (*io_module_hit_cb_t)(void); void io_init(void); void io_set_led_state(bool state); void io_button_register_listener(io_button_pressed_cb_t cb); void io_set_avalnache_beacon_state(bool state); void io_module_hit_register_listener(io_module_hit_cb_t cb); #endif // IO_H <file_sep>#include <global.h> #if defined(DEBUG_ON) #include <stdio.h> #include <stdarg.h> #include "diag/Trace.h" #include "string.h" #include "stm32f10x_usart.h" #include "stm32f10x.h" #define PRINTF_TMP_BUFF_SIZE (128) void debug_init(void) { USART_InitTypeDef usartConfig; RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE); USART_Cmd(USART1, ENABLE); usartConfig.USART_BaudRate = 9600; usartConfig.USART_WordLength = USART_WordLength_8b; usartConfig.USART_StopBits = USART_StopBits_1; usartConfig.USART_Parity = USART_Parity_No; usartConfig.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; usartConfig.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_Init(USART1, &usartConfig); GPIO_InitTypeDef gpioConfig; //PA9 = USART1.TX => Alternative Function Output gpioConfig.GPIO_Mode = GPIO_Mode_AF_PP; gpioConfig.GPIO_Pin = GPIO_Pin_9; gpioConfig.GPIO_Speed = GPIO_Speed_2MHz; GPIO_Init(GPIOA, &gpioConfig); //PA10 = USART1.RX => Input gpioConfig.GPIO_Mode = GPIO_Mode_IN_FLOATING; gpioConfig.GPIO_Pin = GPIO_Pin_10; GPIO_Init(GPIOA, &gpioConfig); } int debug(const char* format, ...) { int ret; va_list ap; va_start (ap, format); static char buf[PRINTF_TMP_BUFF_SIZE]; // Print to the local buffer ret = vsnprintf (buf, sizeof(buf), format, ap); if (ret > 0) { ret = _write(STDOUT_FILENO, buf, (size_t)ret); } va_end (ap); return ret; } #endif // DEBUG <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <FreeRTOS.h> #include <event_groups.h> #include <semphr.h> #include <task.h> #include <timers.h> #include <projdefs.h> #include <os.h> #include <bt740.h> #include <storage.h> #include <io.h> //#define DEBUG_ON #include <debug.h> struct context { TaskHandle_t app_task; response_queue_t *cmd_response; bt_status_t cmd_status; device_type_t device_type; bool send_message_status; }; struct context ctx = { 0 }; static const bt_cmd_type_t init_commands_sequence[] = { BT_CMD_ECHO_OFF, }; void bt_module_state_cb(bt_state_t state) { OS_TASK_NOTIFY(ctx.app_task, APP_BT_MODULE_READY_NOTIF); } static void bt_module_respone(bt_status_t status, response_queue_t *resp) { ctx.cmd_response = resp; ctx.cmd_status = status; OS_TASK_NOTIFY(ctx.app_task, APP_BT_MODULE_RESPONSE_NOTIF); } static void handle_bt_module_response(void) { response_queue_t *tmp_response; DEBUG_PRINTF("APP: Bluetooth module response arrived(%x)\r\n",ctx.cmd_status); while(ctx.cmd_response) { ctx.cmd_response->data[RESPONSE_DATA_LENGTH-1] = 0; DEBUG_PRINTF("APP: Response: %s\r\n", ctx.cmd_response->data); tmp_response = ctx.cmd_response; ctx.cmd_response = ctx.cmd_response->next; free(tmp_response); } } static void button_state_listener(io_button_state_t state) { switch(state) { case IO_BUTTON_SHORT_PRESS: OS_TASK_NOTIFY(ctx.app_task, APP_SHORT_PRESS_NOTIF); break; case IO_BUTTON_LONG_PRESS: OS_TASK_NOTIFY(ctx.app_task, APP_LONG_PRESS_NOTIF); break; default: DEBUG_PRINTF("APP: Unknown button state\r\n"); break; } } static void module_hitted(void) { OS_TASK_NOTIFY(ctx.app_task, APP_MODULE_HITTED_NOTIF); } void spp_data_received(bool status, uint8_t *data, uint8_t data_len) { ctx.send_message_status = status; OS_TASK_NOTIFY(ctx.app_task, APP_SPP_DATA_RECEIVED_NOTIF); } static void handle_module_hitted(void) { DEBUG_PRINTF("APP: Module hitted\r\n"); } void app_task(void *params) { bt_cmd_t cmd; uint8_t bt_router_address[BT_ADDRESS_STR_LENGTH]; DEBUG_PRINTF("Application task started!\r\n"); ctx.app_task = xTaskGetCurrentTaskHandle(); /* register for BT module state */ BT740_register_for_state(bt_module_state_cb); /* get device type from storage */ storage_get_device_type(&ctx.device_type); DEBUG_PRINTF("Device type is %s, state:%s\r\n",((ctx.device_type == DEVICE_TYPE_AVALANCHE_BEACON)? "AVALANCHE_BEACON" : "AVALANCHE_ROUTER"), (storage_is_paired() ? "PAIRED" : "NOT PAIRED")); /* register button state listener */ io_button_register_listener(button_state_listener); /* register module hit listener */ io_module_hit_register_listener(module_hitted); /* get router bluetooth address */ memset(bt_router_address,0,BT_ADDRESS_STR_LENGTH); storage_get_router_bt_address(bt_router_address); for (;;) { BaseType_t ret; uint32_t notification; /* Wait on any of the event group bits, then clear them all */ ret = xTaskNotifyWait(0, OS_TASK_NOTIFY_MASK, &notification, pdMS_TO_TICKS(50)); if(ret != pdPASS) { continue; } if(notification & APP_BT_MODULE_READY_NOTIF) { DEBUG_PRINTF("APP: Bluetooth module is ready\r\n"); /* get ready to receive messages */ BT740_register_for_spp_data(spp_data_received); if(ctx.device_type == DEVICE_TYPE_AVALANCHE_BEACON) { uint8_t *data; data = malloc(4); memcpy(data,"DUPA",4); BT740_send_spp_data(bt_router_address,data,4); } } if(notification & APP_BT_MODULE_RESPONSE_NOTIF) { handle_bt_module_response(); } if(notification & APP_SHORT_PRESS_NOTIF) { DEBUG_PRINTF("APP: Short button press\r\n"); } if(notification & APP_LONG_PRESS_NOTIF) { DEBUG_PRINTF("APP: Long button press\r\n"); /* ToDo: reset device (enable disoverable mode, unpair, reboot */ } if(notification & APP_MODULE_HITTED_NOTIF) { handle_module_hitted(); } if(notification & APP_SPP_DATA_RECEIVED_NOTIF) { //DEBUG_PRINTF("APP: External message received(status=%d)\r\n",ctx.send_message_status); /* ToDo */ } } } <file_sep>/** \file protocol.h * \brief Protocol definition file */ #ifndef PROTOCOL_H #define PROTOCOL_H void protocol_init(void); #endif /* PROTOCOL_H */ <file_sep>/** \file global.h * \brief Global definition file * * This file should be include as first in every c-file */ #ifndef GLOBAL_H #define GLOBAL_H #define DEBUG_ON typedef enum { false = 0, true } bool; #define ON true #define OFF false #define BT_ADDRESS_LENGTH (12) #define BT_ADDRESS_STR_LENGTH (BT_ADDRESS_LENGTH+1) #endif /* GLOBAL_H */
3236bb25b9dbd8b477e13c5ccd28330e5de42376
[ "C" ]
15
C
mkopertowski/stm32_platform
613a1ecc988a9e65203b0cbeffa80a899c8c1dde
ab5fa75e4144993daaf77d1a73750a962882de27
refs/heads/master
<repo_name>shivankkhare/intuigine<file_sep>/src/components/Home.js import React, { Component } from 'react' import Counter from './Counter' import Navbar from './Navbar' import axios from 'axios' class Home extends Component { constructor(props) { super(props); this.state = { error: null, isLoaded: false, items: [], api: 'https://f0ztti2nsk.execute-api.ap-south-1.amazonaws.com/v1/consignment/fetch', data: { "email": "<EMAIL>" }, bearerToken: '<PASSWORD>' }; } componentDidMount() { axios.post(this.state.api, this.state.data, { headers: { "Authorization": `Bearer ${this.state.bearerToken}` } }) .then(res => { this.setState({ items:res.data }) console.log(res) }) .catch(function (error) { // handle error console.log(error); }) } render() { return ( <div> <Navbar /> <main> <section className="container d-flex justify-content-center" > <Counter /> <Counter /> <Counter /> <Counter /> <Counter /> </section> <section className="container d-flex justify-content-center"> <div className="card delivery" > <div className="card-body"> </div> </div> <div className="card info-table" > <div className="card-body"> <table className="table table-responsive"> <thead> <tr> <th scope="col">AWB NUMBER</th> <th scope="col">TRANSPORTER</th> <th scope="col">SOURCE</th> <th scope="col">DESTINATION</th> <th scope="col">BRAND</th> <th scope="col">START DATE</th> <th scope="col">ETD</th> <th scope="col">STATUS</th> </tr> </thead> <tbody> { this.state.items.map((item,i) => <tr key={item._id}> <td>{item.awbno}</td> <td>{item.carrier}</td> <td>{item.from}</td> <td>{item.to}</td> <td>{item.carrier}</td> <td>{item.createdAt}</td> <td>{item.createdAt}</td> <td>{item.current_status}</td> </tr> ) } </tbody> </table> </div> </div> </section> </main> </div> ) } } export default Home
b4d89a4191005edf0aa8f7e210ffa7b7c543875d
[ "JavaScript" ]
1
JavaScript
shivankkhare/intuigine
11107eb1091cef5e18dc578122fcb7c2c364e09c
fd4de4e17c143d755a516a0699cb2f01fd3daabe
refs/heads/main
<file_sep>import firebase from 'firebase'; const firebaseConfig = { apiKey: "<KEY>", authDomain: "india-chat-app-706b0.firebaseapp.com", projectId: "india-chat-app-706b0", storageBucket: "india-chat-app-706b0.appspot.com", messagingSenderId: "614956211301", appId: "1:614956211301:web:c169d9e960eb3ce31d3a8c" }; const app = firebase.initializeApp(firebaseConfig); const database = app.firestore(); export default database;
6027ed8ffa8d060df262de33a4d3530b93672e09
[ "JavaScript" ]
1
JavaScript
altaf53/chatapplication
4db6f1c50aba8b07ee5a3019399915c8c55a5596
53a6f9379fdf3ac942bbb161a3d5ac44ce45c491
refs/heads/master
<repo_name>unography/creative-coding<file_sep>/p5-self-doubt-art/sketch.js // Original by https://www.openprocessing.org/sketch/529835 var particlesQuantity = 900; var positionX = new Array(particlesQuantity); var positionY = new Array(particlesQuantity); var velocityX = new Array(particlesQuantity).fill(0); var velocityY = new Array(particlesQuantity).fill(0); function setup() { createCanvas(windowWidth, windowHeight); stroke(64, 255, 255); for (var particle = 1; particle < particlesQuantity; particle++) { positionX[particle] = random(0, width); positionY[particle] = random(0, height); } positionX[0] = 0; positionY[0] = 0; frameRate(30); } function draw() { background(220, 128); velocityX[0] = velocityX[0] * 0.5 + (mouseX - positionX[0]) * 0.9; velocityY[0] = velocityY[0] * 0.5 + (mouseY - positionY[0]) * 0.9; positionX[0] += velocityX[0]; positionY[0] += velocityY[0]; if (frameCount % 1000 == 0) { reset(); } for (var particle = 1; particle < particlesQuantity; particle++) { var whatever = 1024 / (sq(positionX[0] - positionX[particle]) + sq(positionY[0] - positionY[particle])); whatever = whatever * 2; velocityX[particle] = velocityX[particle] * 0.95 + (velocityX[0] - velocityX[particle]) * whatever; velocityY[particle] = velocityY[particle] * 0.95 + (velocityY[0] - velocityY[particle]) * whatever; positionX[particle] += velocityX[particle]; positionY[particle] += velocityY[particle]; if ((positionX[particle] < 0 && velocityX[particle] < 0) || (positionX[particle] > width && velocityX[particle] > 0)) { velocityX[particle] = -velocityX[particle]; } if ((positionY[particle] < 0 && velocityY[particle] < 0) || (positionY[particle] > height && velocityY[particle] > 0)) { velocityY[particle] = -velocityY[particle]; } stroke(220, 122, 122, 255); strokeWeight(10); // point(positionX[particle], positionY[particle]); text("no", positionX[particle], positionY[particle]) } stroke(122, 220, 122, 255); strokeWeight(10); text("is this art?", width / 2, height / 10); } function reset() { for (var particle = 1; particle < particlesQuantity; particle++) { positionX[particle] = random(0, width); positionY[particle] = random(0, height); } } function mousePressed() { reset(); } <file_sep>/p5-self-doubt-art/README.md # self-doubt-art a p5 sketch with particle simulation https://unography-p5-self-doubt-art.glitch.me/<file_sep>/README.md # creative-coding Experiments with code to make art <file_sep>/p5-generative-portraits/README.md # Generative Portraits Using randomness and perlin noise to generate animated line drawing portraits from images https://dhruvkaran.com/recreating-paintings-with-generative-art/ ![vangoghGenerative](vangoghGenerative.gif)
08fa846ac781aa55489fe90ea2300d1975b55431
[ "JavaScript", "Markdown" ]
4
JavaScript
unography/creative-coding
c8752000e33c718ebd71b14caa6c0f90a0d506fe
d234af6d622915240873bb269e8c09e7d8e78f0e
refs/heads/master
<file_sep>source 'https://rubygems.org' gem 'listen', '3.1.5' <file_sep>#!/usr/bin/env ruby require 'listen' require 'shellwords' def log(msg) puts "#{Time.now} #{msg}" end def main print_usage_and_exit! if ['-h', '--help'].include?(ARGV.first) print_usage_and_exit! unless ARGV.size == 2 # Figure out which file (or directory) we should be monitoring raw_monitor_filename = ARGV[0] monitor_filename = File.expand_path(raw_monitor_filename) unless File.exist?(monitor_filename) puts "#{monitor_filename} does not exist; aborting" abort end # Figure out which executable to run when the monitored file changes raw_on_change_command = ARGV[1] on_change_command = File.expand_path(raw_on_change_command) unless File.exist?(on_change_command) puts "#{on_change_command} does not exist; aborting" abort end unless File.file?(on_change_command) && File.executable?(on_change_command) puts "#{on_change_command} is not executable; aborting" abort end log "Watching #{raw_monitor_filename} for changes" # `Listen.to` can only watch for changes on directories, so if the user specified a file, # we actually have to monitor its parent directory and filter changes as they happen. monitor_directory = File.directory?(monitor_filename) ? monitor_filename : File.dirname(monitor_filename) listener = Listen.to(monitor_directory) do |modified, added, removed| unless File.directory?(monitor_filename) # We have to watch a directory, but we were invoked with a filename, so check to # make sure the correct file changed changed_files = [modified, added, removed].flatten.map do |filename| File.expand_path(filename) end next unless changed_files.include?(monitor_filename) end log "#{raw_monitor_filename} changed; running #{raw_on_change_command}" system Shellwords.escape(on_change_command) end listener.start sleep end def print_usage_and_exit! puts "usage: #{File.basename(__FILE__)} [path to monitor] [script to run when target path changes]" abort end main <file_sep># watchnrun Watch a file (or directory) for changes and run a command in response. ## What `watchnrun` is a simple script that lets you specify a file or directory to watch, and then runs a script in response to changes when they happen. `watchnrun` will keep watching until you terminate it. Example output: ```` $ watchnrun example-file example-script.sh 2019-01-22 18:56:30 -0800 Watching example-file for changes 2019-01-22 18:56:34 -0800 example-file changed; running example-script.sh I am the script and I am running! 2019-01-22 18:56:37 -0800 example-file changed; running example-script.sh I am the script and I am running! ```` ## Why This is part of an elaborate [Rube Goldberg machine](https://en.wikipedia.org/wiki/Rube_Goldberg_machine) that I've wired up to get [my Jekyll blog](https://writing.markchristian.org) to rebuild itself whenever I push a change to its repository, without needing to have my web server process have any elevated permissions (which is particularly important on shared hosting like [DreamHost](https://www.dreamhost.com)). The basic idea is: * A GitHub webhook hits an endpoint on my domain * That endpoint touches a file in a particular location * Meanwhile, an instance of `watchnrun` running inside of a detached `screen` process watches that location for changes * Whenever that file changes, `watchnrun` executes a script that fetches the latest version of my blog's repository from GitHub and runs `jekyll build`. If you'd like to learn more, I've written about [using GitHub webhooks with DreamHost](https://writing.markchristian.org/2019/01/26/watchnrun.html) elsewhere.
59d108f2874d40b247b12f333cfb263365817a46
[ "Markdown", "Ruby" ]
3
Ruby
shinypb/watchnrun
22fe9162c244a1e95d3608fffc335a17912e73d6
d38c88aaf60b4028549c5d02d3454f3761f8bef1
refs/heads/master
<file_sep><?php /** * Linna Framework. * * @author <NAME> <<EMAIL>> * @copyright (c) 2018, <NAME> * @license http://opensource.org/licenses/MIT MIT License */ declare(strict_types=1); namespace Linna\Tests; use Linna\Authentication\Password; use Linna\Authentication\UserMapper; use Linna\Authorization\PermissionMapper; use Linna\Authorization\RoleMapper; use Linna\Authorization\RoleToUserMapper; use Linna\Storage\StorageFactory; use PDO; use PHPUnit\Framework\TestCase; /** * Role Mapper Test. */ class RoleMapperTest extends TestCase { /** * @var RoleMapper */ protected $roleMapper; /** * Setup. */ public function setUp(): void { $options = [ 'dsn' => $GLOBALS['pdo_pgsql_dsn'], 'user' => $GLOBALS['pdo_pgsql_user'], 'password' => $GLOBALS['pdo_pgsql_password'], 'options' => [ PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => false ], ]; $pdo = (new StorageFactory('pdo', $options))->get(); $password = new Password(); $permissionMapper = new PermissionMapper($pdo); $userMapper = new UserMapper($pdo, $password); $role2userMapper = new RoleToUserMapper($pdo, $password); //$roleMapper = new RoleMapper($pdo, $permissionMapper, $userMapper, $role2userMapper); //$enhancedUserMapper = new EnhancedUserMapper($pdo, $password, $permissionMapper, $role2userMapper); $this->roleMapper = new RoleMapper($pdo, $permissionMapper, $userMapper, $role2userMapper); } /** * Test new instance. */ public function testNewInstance() { $this->assertInstanceOf(RoleMapper::class, $this->roleMapper); } } <file_sep><?php /** * Linna Framework. * * @author <NAME> <<EMAIL>> * @copyright (c) 2018, <NAME> * @license http://opensource.org/licenses/MIT MIT License */ declare(strict_types=1); namespace Linna\Tests; use Linna\Authentication\EnhancedAuthenticationMapper; use Linna\Authentication\LoginAttempt; use Linna\DataMapper\NullDomainObject; use Linna\Storage\StorageFactory; use PDO; use PHPUnit\Framework\TestCase; /** * Enhanced Authentication Mapper Test. */ class EnhancedAuthenticationMapperTest extends TestCase { /** * @var EnhancedAuthenticationMapper The enhanced authentication mapper class. */ protected static $enhancedAuthenticationMapper; /** * @var PDO Database connection. */ protected static $pdo; /** * Setup. * * @return void */ public static function setUpBeforeClass(): void { $options = [ 'dsn' => $GLOBALS['pdo_pgsql_dsn'], 'user' => $GLOBALS['pdo_pgsql_user'], 'password' => $GLOBALS['<PASSWORD>'], 'options' => [ PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => false, ], ]; $pdo = (new StorageFactory('pdo', $options))->get(); self::$pdo = $pdo; self::$enhancedAuthenticationMapper = new EnhancedAuthenticationMapper($pdo); self::$pdo->exec('ALTER SEQUENCE public.login_attempt_login_attempt_id_seq RESTART WITH 1 INCREMENT BY 1;'); //populate data base self::createFakeData(); } /** * Insert fake data into persistent storage for tests. * * @return void */ protected static function createFakeData(): void { $loginAttempt = [ ['root', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['root', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['root', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['root', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['root', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['root', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['admin', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['admin', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['admin', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['admin', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['admin', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['admin', 'mbvi2lgdpcj6vp3qemh2estei2', '192.168.1.2'], ['administrator', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['administrator', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['administrator', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['administrator', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['administrator', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['administrator', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['poweruser', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['poweruser', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['poweruser', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['poweruser', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['poweruser', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['poweruser', 'vaqgvpochtif8gh888q6vnlch5', '192.168.1.2'], ['fooroot', '3hto06tko273jjc1se0v1aqvvn', '192.168.1.3'], ['fooroot', '3hto06tko273jjc1se0v1aqvvn', '192.168.1.3'], ['fooroot', '3hto06tko273jjc1se0v1aqvvn', '192.168.1.3'], ['fooroot', '3hto06tko273jjc1se0v1aqvvn', '192.168.1.3'], ]; $timeSliding = 0; foreach ($loginAttempt as $data) { $loginAttempt = self::$enhancedAuthenticationMapper->create(); $loginAttempt->userName = $data[0]; $loginAttempt->sessionId = $data[1]; $loginAttempt->ipAddress = $data[2]; $loginAttempt->when = \date(DATE_ATOM, ((\time() - 28) + $timeSliding++)); self::$enhancedAuthenticationMapper->save($loginAttempt); } } /** * Tear Down. * * @return void */ public static function tearDownAfterClass(): void { self::$pdo->exec('DELETE FROM public.login_attempt'); } /** * Test new instance. */ public function testNewInstance() { $this->assertInstanceOf(EnhancedAuthenticationMapper::class, self::$enhancedAuthenticationMapper); } /** * User id provider * * @return array */ public function loginAttemptIdProvider(): array { return [ [1, 1], [28, 28], [29, 0] ]; } /** * Test fetch by id. * * @dataProvider loginAttemptIdProvider * * @param int $loginAttemptId * @param int $expectedId * * @return void */ public function testFetchById(int $loginAttemptId, int $expectedId): void { $loginAttempt = self::$enhancedAuthenticationMapper->fetchById($loginAttemptId); $this->assertEquals($loginAttempt->getId(), $expectedId); } /** * Test fetch all. * * @return void */ public function testFetchAll(): void { $this->assertCount(28, self::$enhancedAuthenticationMapper->fetchAll()); } /** * Login attempt fetch limit provider. * * @return array */ public function loginAttemptFetchLimitProvider(): array { return [ ['root', 1, 0, 1], ['admin', 7, 6, 1], ['administrator', 13, 12, 1], ['poweruser', 19, 18, 1], ['fooroot', 25, 24, 1] ]; } /** * Test fetch limit. * * @dataProvider loginAttemptFetchLimitProvider * * @param string $userName * @param int $offset * @param int $rowCount * * @return void */ public function testFetchLimit(string $userName, int $rId, int $offset, int $rowCount): void { $loginAttempt = self::$enhancedAuthenticationMapper->fetchLimit($offset, $rowCount); $key = \array_keys($loginAttempt)[0]; $this->assertCount(1, $loginAttempt); $this->assertEquals($loginAttempt[$key]->rId, $rId); $this->assertEquals($loginAttempt[$key]->userName, $userName); } /** * Login attempt with the same user provider. * * @return array */ public function attemptsWithSameUserProvider(): array { return [ ['root', 40, 6], ['admin', 40, 6], ['administrator', 40, 6], ['poweruser', 40, 6], ['fooroot', 40, 4] ]; } /** * Test fetch attempts with the same user. * * @dataProvider attemptsWithSameUserProvider * * @param string $userName * @param int $timeInSeconds * @param int $attempts * * @return void */ public function testFetchAttemptsWithSameUser(string $userName, int $timeInSeconds, int $attempts): void { $this->assertEquals($attempts, self::$enhancedAuthenticationMapper->fetchAttemptsWithSameUser($userName, $timeInSeconds)); } /** * Login attempt with the same session provider. * * @return array */ public function attemptsWithSameSessionProvider(): array { return [ ['mbvi2lgdpcj6vp3qemh2estei2', 40, 12], ['vaqgvpochtif8gh888q6vnlch5', 40, 12], ['3hto06tko273jjc1se0v1aqvvn', 40, 4] ]; } /** * Test fetch attempts with the same session id. * * @dataProvider attemptsWithSameSessionProvider * * @param string $sessionId * @param int $timeInSeconds * @param int $attempts * * @return void */ public function testFetchAttemptsWithSameSession(string $sessionId, int $timeInSeconds, int $attempts): void { $this->assertEquals($attempts, self::$enhancedAuthenticationMapper->fetchAttemptsWithSameSession($sessionId, $timeInSeconds)); } /** * Login attempt with the same ip provider. * * @return array */ public function attemptsWithSameIpProvider(): array { return [ ['192.168.1.2', 40, 24], ['192.168.1.3', 40, 4] ]; } /** * Test fetch attempts with the same ip address. * * @dataProvider attemptsWithSameIpProvider * * @param string $ipAddress * @param int $timeInSeconds * @param int $attempts * * @return void */ public function testFetchAttemptsWithSameIp(string $ipAddress, int $timeInSeconds, int $attempts): void { $this->assertEquals($attempts, self::$enhancedAuthenticationMapper->fetchAttemptsWithSameIp($ipAddress, $timeInSeconds)); } /** * Test delete old login attempts. * * @return void */ public function testDeleteOldLoginAttempts(): void { $this->assertTrue(self::$enhancedAuthenticationMapper->deleteOldLoginAttempts(-86400)); $this->assertEquals(0, \count(self::$enhancedAuthenticationMapper->fetchAll())); } /** * Test concrete create. * * @return void */ public function testConcreteCreate(): void { $this->assertInstanceOf(LoginAttempt::class, self::$enhancedAuthenticationMapper->create()); } /** * Test concrete insert. * * @return void */ public function testConcreteInsert(): void { $loginAttempt = self::$enhancedAuthenticationMapper->create(); $loginAttempt->userName = 'test'; $loginAttempt->sessionId = 'vaqgvpochtzf8gh888q6vnlch5'; $loginAttempt->ipAddress = '127.0.0.1'; $loginAttempt->when = \date(DATE_ATOM); $this->assertEquals(0, $loginAttempt->rId); $this->assertEquals(0, $loginAttempt->getId()); self::$enhancedAuthenticationMapper->save($loginAttempt); $this->assertGreaterThan(0, $loginAttempt->rId); $this->assertGreaterThan(0, $loginAttempt->getId()); $loginAttemptStored = self::$enhancedAuthenticationMapper->fetchById($loginAttempt->rId); $this->assertInstanceOf(LoginAttempt::class, $loginAttemptStored); } /** * Test concrete update. * * @depends testConcreteInsert * * @return void */ public function testConcreteUpdate(): void { $loginAttemptStored = \current(self::$enhancedAuthenticationMapper->fetchAll()); $this->assertEquals('vaqgvpochtzf8gh888q6vnlch5', $loginAttemptStored->sessionId); $this->assertInstanceOf(LoginAttempt::class, $loginAttemptStored); $loginAttemptStored->sessionId = 'qwertyochtzf8gh888q6vnlch5'; self::$enhancedAuthenticationMapper->save($loginAttemptStored); $loginAttemptUpdated = self::$enhancedAuthenticationMapper->fetchById($loginAttemptStored->rId); $this->assertEquals('qwertyochtzf8gh888q6vnlch5', $loginAttemptUpdated->sessionId); $this->assertInstanceOf(LoginAttempt::class, $loginAttemptUpdated); } /** * Test concrete delete. * * @depends testConcreteInsert * * @return void */ public function testConcreteDelete(): void { $loginAttemptStored = \current(self::$enhancedAuthenticationMapper->fetchAll()); $this->assertEquals('qwertyochtzf8gh888q6vnlch5', $loginAttemptStored->sessionId); $this->assertInstanceOf(LoginAttempt::class, $loginAttemptStored); self::$enhancedAuthenticationMapper->delete($loginAttemptStored); $this->assertInstanceOf(NullDomainObject::class, $loginAttemptStored); } } <file_sep> # Linna Auth Mapper Postgresql Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [v0.1.0](https://github.com/linna/auth-mapper-pgsql/compare/v0.1.0...master) - 2019-XX-XX ### Added * `Linna\Authentication\EnhancedAuthenticationMapper` class * `Linna\Authentication\UserMapper` class * `Linna\Authorization\EnhancedUserMapper` class * `Linna\Authorization\PermissionMapper` class * `Linna\Authorization\RoleMapper` class * `Linna\Authorization\RoleToUserMapper` class <file_sep><div align="center"> <a href="#"><img src="logo-linna-96.png" alt="Linna Logo"></a> </div> <br/> <div align="center"> <a href="#"><img src="logo-auth-pgsql.png" alt="Linna Auth Mapper Pgsql Logo"></a> </div> <br/> <div align="center"> [![Build Status](https://travis-ci.org/linna/auth-mapper-pgsql.svg?branch=master)](https://travis-ci.org/linna/auth-mapper-pgsql) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/linna/auth-mapper-pgsql/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/linna/auth-mapper-pgsql/?branch=master) [![Code Coverage](https://scrutinizer-ci.com/g/linna/auth-mapper-pgsql/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/linna/auth-mapper-pgsql/?branch=master) [![StyleCI](https://github.styleci.io/repos/209962835/shield?branch=master&style=flat)](https://github.styleci.io/repos/209962835) [![PDS Skeleton](https://img.shields.io/badge/pds-skeleton-blue.svg?style=flat)](https://github.com/php-pds/skeleton) [![PHP 7.1](https://img.shields.io/badge/PHP-7.1-8892BF.svg)](http://php.net) </div> # About This package provide a concrete implementation for authentication interfaces and for the authorization interfaces of the framework. Mappers use as persistent storage mysql through php pdo. # Requirements * PHP >= 7.1 * PDO extension * Postgresql extension * linna/framework dev-b0.27.0 # Installation With composer: ``` composer require linna/auth-mapper-pgsql ``` # Package Content Implementation of framework interfaces: * `Linna\Authentication\EnhancedAuthenticationMapperInterface` * `Linna\Authentication\UserMapperInterface` * `Linna\Authorization\EnhancedUserMapperInterface` * `Linna\Authorization\PermissionMapperInterface` * `Linna\Authorization\RoleMapperInterface` * `Linna\Authorization\RoleToUserMapperInterface` As: * `Linna\Authentication\EnhancedAuthenticationMapper` * `Linna\Authentication\UserMapper` * `Linna\Authorization\EnhancedUserMapper` * `Linna\Authorization\PermissionMapper` * `Linna\Authorization\RoleMapper` * `Linna\Authorization\RoleToUserMapper`<file_sep><?php /** * Linna Framework. * * @author <NAME> <<EMAIL>> * @copyright (c) 2018, <NAME> * @license http://opensource.org/licenses/MIT MIT License */ declare(strict_types=1); namespace Linna\Tests; use Linna\Authorization\PermissionMapper; use Linna\Storage\StorageFactory; use PDO; use PHPUnit\Framework\TestCase; /** * Permission Mapper Test. */ class PermissionMapperTest extends TestCase { /** * @var PermissionMapper */ protected $permissionMapper; /** * Setup. */ public function setUp(): void { $options = [ 'dsn' => $GLOBALS['pdo_pgsql_dsn'], 'user' => $GLOBALS['pdo_pgsql_user'], 'password' => $GLOBALS['<PASSWORD>'], 'options' => [ PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => false ], ]; $this->permissionMapper = new PermissionMapper((new StorageFactory('pdo', $options))->get()); } /** * Test new instance. */ public function testNewInstance() { $this->assertInstanceOf(PermissionMapper::class, $this->permissionMapper); } }
1a4ea4ee1c27d0c3b17db2c18a2c49618ce3459c
[ "Markdown", "PHP" ]
5
PHP
open-source-contributions/auth-mapper-pgsql
cf324494c9be52cd7c124905bb99b9dbc1bfbde9
83449035b1ce65fc8a38d1ab28358625624bdedf
refs/heads/master
<repo_name>4X0L073/ipk-exercises<file_sep>/Blatt2/Aufgabe2.cpp #include <iostream> void collatz(int x ) { while ( x != 1 && x != 0 && x !=-1 && x!= -5 && x != -17 ){ if( x % 2 == 0){ x = x / 2; } else { x = x * 3 +1; } } std::cout << "Das Ergbnis ist: " << x << std::endl; } int main(){ int a; int b; std::cout << "Gib einen beliebigen Startwert ein: " << std::endl; std::cin >> a; collatz (a); return 0; } <file_sep>/Binomial_coefficient_triangle.cpp #include <iostream> const int gnmax = 10; const int ggroesse = ((gnmax * (gnmax + 1)) / 2); int gfeld[ggroesse]; int pos(int n, int k) { return ((n * (n + 1)) / 2)+k; } void binomialkoeffizient() { for (int n = 0; n <= gnmax; n++) { for (int t=0;t<gnmax-n; t++) std::cout << " "; for (int k = 0; k <= n; k++) { if (n == k || k == 0) { gfeld[pos(n, k)] = 1; std::cout << gfeld[pos(n, k)] << " "; continue; } gfeld[pos(n, k)] = gfeld[pos(n - 1, k - 1)] + gfeld[pos(n - 1, k)]; std::cout << gfeld[pos(n, k)] << " "; } std::cout << '\n' << std::endl; } } int main() { binomialkoeffizient(); return 0; } <file_sep>/Blatt2/Aufgabe3.cpp #include <iostream> int fibonacci (int number) { int erg; if (number == 0){ return 0; } if (number == 1){ return 1; } else { erg = fibonacci(number - 2) + fibonacci(number -1); std::cout << erg << " "; } return erg; } int main() { int a; int b; std::cout << "Gib eine Zahl für die Fibonacci-Folge ein: " << std::endl; std::cin >> a; b = fibonacci (a); std::cout << "Die Fiobonaccizahl dazu ist: " << b << std::endl; return 0; }<file_sep>/Blatt2/Aufgabe1.cpp #include <iostream> #include <cmath> double ergebniss (double a,double b ,double c){ double e1; double D1; D1 = sqrt(b * b - (4 * a * c)); e1 = (-b + D1 )/(2 * a); return e1; } double ergebniss2 (double a, double b, double c){ double e2; double D2; D2 = sqrt(b * b - (4 * a * c)); e2 = (-b - D2 )/(2 * a); return e2; } int main() { double a; double b; double c; std::cout << "Gib die Zahlen für a,b und c ein" << std::endl; std::cout << "a = " ; std::cin >> a; std::cout << "b = "; std::cin >> b; std::cout << "c = "; std::cin >> c; double e1 = ergebniss (a, b, c); double e2 = ergebniss2 (a, b, c); double W = b * b - 4 * a * c; if( W < 0 ) { std::cout << "Die Determinante ist negativ!" << std::endl; } if (W == 0){ std::cout << "Es gibt nur eine Nullstelle bei x1/2: " << e1 << std::endl; } if (W > 0) { std::cout << "Die Nullstellen sind: x1 = " << e1 << " und x2 = " << e2 << std::endl; } return 0; }
6bee665245d15d028d44ac23ed6f4e2616693a4b
[ "C++" ]
4
C++
4X0L073/ipk-exercises
317be7723906cd056f2ca8f14d53e4e214be233e
a961c9c7ab46e8354512818f06725b919f2268e6
refs/heads/master
<file_sep><?php session_start(); require_once 'connection.php'; if(!empty($_GET['id']) && $_SERVER['REQUEST_METHOD']=='GET') { if((int)$_GET['id']) { $id = $_GET['id']; $sql = "SELECT * FROM tbl_login WHERE id=".$id; $result = mysqli_query($conn,$sql); $userdata = mysqli_fetch_assoc($result); } else { $_SESSION['error']='Invalid ID'; header('Location:index.php'); } } else { $_SESSION['error']="Invald access"; header('Location:index.php'); } ?> <!doctype html> <html lang="en"> <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>Document</title> <link rel="stylesheet" href="../../login/Bootstrap/css/bootstrap.css"> </head> <body> <form action="Editaction.php" method="post"> <input type="hidden" name="id" value="<?=$userdata['id']?>"> <h1 style="text-align: center"><i class="glyphicon glyphicon-edit"> </i>Edit Record</h1> <?php if(isset($_SESSION['error'])):?> <div class="alert alert-danger"> <?=$_SESSION['error']?> <?php unset($_SESSION['error'])?> </div> <?php endif;?> <?php if(isset($_SESSION['success'])):?> <div class="alert alert-success"> <?=$_SESSION['success']?> <?php unset($_SESSION['success'])?> </div> <?php endif;?> <hr style="height:1px;border:none;color:#333;background-color:#333;" /> <div class="col-md-6"> <div class="form-group"> <label for="name">Name</label> <input type="text" name="name" value="<?=$userdata["name"]?>" class="form-control" id="name"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" name="email" value="<?=$userdata["email"]?>" class="form-control" id="email"> </div> <div class="form-group"> <label for="gender">Gender</label> <input type="radio" name="gender" <?=$userdata["gender"]=='male' ? 'checked' : ''?> value="male" >Male &emsp; <input type="radio" name="gender" <?=$userdata["gender"]=='female'? 'checked' : ''?> value="female">Female </div> <div class="form-group"> <label for="country">Country</label> <select name="country" id="country" class="form-control"> <option value="Nepal" <?=$userdata["country"]=='Nepal' ? 'selected' : ''?> >Nepal</option> <option value="China" <?=$userdata["country"]=='China' ? 'selected' : ''?>>China</option> <option value="India" <?=$userdata["country"]=='India' ? 'selected' : ''?>>India</option> </select> </div> <div class="form-group"> <button class="btn btn-success">Edit</button> </div> </div> </form> </body> </html> <file_sep># login Simple Login for implementing CRUD <file_sep><?php session_start(); require_once 'connection.php'; if(!empty($_GET['id']) && $_SERVER['REQUEST_METHOD']=='GET') { if((int)$_GET['id']) { $id=$_GET['id']; $sql="DELETE from tbl_login WHERE id=".$id; $result=mysqli_query($conn,$sql); if($result==true) { $_SESSION['success']='User was deleted'; header('Location:index.php'); } else { $_SESSION['error']='Problem in deletion'; header('Location:index.php'); } } else { $_SESSION['error']='Invalid ID'; header('Location:index.php'); } } else { $_SESSION['error']='Invalid acces'; header('Location:index.php'); } <file_sep><?php session_start(); require_once "connection.php"; $sql="SELECT * from tbl_login"; $result=mysqli_query($conn,$sql); ?> <!doctype html> <html lang="en"> <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>Document</title> <link rel="stylesheet" href="../../login/Bootstrap/css/bootstrap.css"> </head> <body> <h1 style="text-align: center"><i class="glyphicon glyphicon-user"> </i> Login Form</h1> <hr style="height:1px;border:none;color:#333;background-color:#333;" > <div class="container"> <div class="row"> <div class="col-md-6"> <form action="loginaction.php" method="post"> <h2>Add record</h2> <hr> <?php if(isset($_SESSION['error'])):?> <div class="alert alert-danger"> <?=$_SESSION['error']?> <?php unset($_SESSION['error'])?> </div> <?php endif;?> <?php if(isset($_SESSION['success'])):?> <div class="alert alert-success"> <?=$_SESSION['success']?> <?php unset($_SESSION['success'])?> </div> <?php endif;?> <hr> <div class="form-group"> <label for="name">Name</label> <input type="text" name="name" class="form-control" id="name"> </div> <div class="form-group"> <label for="password">Password</label> <input type="<PASSWORD>" name="password" class="form-control" id="password"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" name="email" class="form-control" id="email"> </div> <div class="form-group"> <label for="gender">Gender</label> <input type="radio" name="gender" value="male" >Male &emsp; <input type="radio" name="gender" value="female">Female </div> <div class="form-group"> <label for="country">Country</label> <select name="country" id="country" class="form-control"> <option value="Nepal">Nepal</option> <option value="China">China</option> <option value="India">India</option> </select> </div> <div class="form-group"> <button class="btn btn-success">Submit</button> </div> </form> </div> <div class="row"> <div class="col-md-6"> <h2>Display Record</h2> <hr > <table class="table table-striped" > <tr> <th>S.No.</th> <th>Name</th> <th>Email</th> <th>Gender</th> <th>Country</th> <th>Action</th> </tr> <?php $i=1 ; while($test=mysqli_fetch_assoc($result)):?> <tr> <td><?=$i ;?></td> <td><?php echo $test['name'];?></td> <td><?php echo $test['email'];?></td> <td><?php echo $test['gender'];?></td> <td><?php echo $test['country'];?></td> <td><a href="delete.php?id=<?=$test['id'];?>" class="btn btn-danger btn-sm" >Delete</a> <a href="edit.php?id=<?=$test['id'];?>" class="btn btn-success btn-sm">Edit</a> </td> </tr> <?php $i++; endwhile; ?> </table> </div> </div> </div> </div> </body> </html><file_sep><?php session_start(); require_once "connection.php"; if(!empty($_POST ) && $_SERVER["REQUEST_METHOD"]=='POST') { $name=$_POST['name']; $email=$_POST['email']; $password=$_POST['password']; $gender=$_POST['gender']; $country=$_POST['country']; $id=$_POST['id']; $sql="UPDATE tbl_login SET name='$name',email='$email',password='<PASSWORD>',gender='$gender',country='$country' WHERE id=".$id; $result = mysqli_query($conn,$sql); if($result==true) { $_SESSION['success']='Data was updated'; header('Location:index.php'); } else{ $_SESSION['error']='Error'; header('Location:index.php'); } } else{ $_SESSION['error']='Invalid access'; header('Location:index.php'); } <file_sep><?php $conn=mysqli_connect('localhost','root','','loginform'); if($conn==true) { } else { echo "Error"; }<file_sep><?php session_start(); require_once "connection.php"; if(!empty($_POST ) && $_SERVER["REQUEST_METHOD"]=='POST') { $name=$_POST['name']; $email=$_POST['email']; $password=$_POST['<PASSWORD>']; $cgender=$_POST['gender']; $country=$_POST['country']; $sql="INSERT INTO tbl_login (name,email,password,gender,country) VALUES ('$name','$email','$password','$gender','$country') "; $result=mysqli_query($conn,$sql); var_dump($result); if($result==true) { $_SESSION['success']='User was inserted'; header('Location:index.php'); } } else { $_SESSION['error']='Invalid acces'; header('Location:index.php'); }
1ea4c4a15e391c5c1a1cce44f194138b4aa5da16
[ "Markdown", "PHP" ]
7
PHP
Karkisushant/login
dd07061a47785e508c0cd6e705e6580a27a22c2b
a05ec87f920ead2265d99a211c8a5ab8929d06c7
refs/heads/master
<file_sep>import java.util.*; /* Master class of both decryption classes. */ class code { WordDictionary dic; String m_ValueToDecrypt; public code(WordDictionary dict) { this.m_ValueToDecrypt = ""; dic = dict; } public code(String input, WordDictionary dict) { this(dict); this.m_ValueToDecrypt = input; } void setCode(String input) { this.m_ValueToDecrypt = input; } /* Used for converting code back into the "accepted" format */ String convertForOutputToUser(String input) { StringBuffer buff = new StringBuffer(input); for(int x = 5; x < buff.length(); x = x + 6) { buff = buff.insert(x, " "); } return (buff.toString().toUpperCase()); } /* This function is used to verify a sentence It scans through the text for words in the dictionary list If it is a real word the relative position of it is taken up This is summed up and then divided to return an over-all percentage */ int findAsManyWordsAsPossible(String input) { int num = 0; for(int x = 2; x < this.dic.sizeOfLargestWord(); x++) { for(int y = 0; y <= input.length() - x; y++) { if(dic.exists(input.substring(y, y + x))) { num++; } } } return num; } } <file_sep>import java.util.*; import java.io.*; /* An abstraction of the HashMap class used to store a Dictionary of words. */ class WordDictionary { private HashSet<String> m_WordCache = new HashSet<String>(); private int m_SizeOfLargestWord = -1; public WordDictionary() { } public WordDictionary(String input) throws FileNotFoundException { this.addWordsFromTextfile(input); } public Boolean exists(String input) { return this.m_WordCache.contains(input); } public int sizeOfLargestWord() { return this.m_SizeOfLargestWord; } public void addWord(String wordToInsert) { if (wordToInsert.length() > this.m_SizeOfLargestWord) { this.m_SizeOfLargestWord = wordToInsert.length(); } this.m_WordCache.add(wordToInsert); } public void addWordsFromTextfile(String input) throws FileNotFoundException { File _textFileToRead = new File(input); Scanner scanner = new Scanner(_textFileToRead); while(scanner.hasNextLine()) { this.addWord(scanner.nextLine()); } } } <file_sep>import java.util.*; /* The Ceasar decryption code The main function (decode) is mostly the driver It only picks the "top 6" solutions due to the way the loop works However if it finds a "100% letter match" from verify it breaks out of the loop */ class Ceasar extends code { static private final int CHARACTERS_IN_ALPHABET = 26 Ceasar(WordDictionary dict) { super(dict); } Ceasar(String valueToDecode, WordDictionary dict) { super(input, dict); } String decode() { String _StringToDecrypt = this.m_ValueToDecrypt.replace(" ", ""); String _BestDecodedString = ""; int _KeyUsedForBestDecodedString = 0; int _HighestNumberOfWords = -1; //Calculate the top 6 possible answers, and then take the most likely one. for(int x = 1; x < 6; x++) { int _KeyUsedToDecode = this.keyFind(_StringToDecrypt, x); String _DecodedString = this.decodeString(_StringToDecrypt, _KeyUsedToDecode); int _NumberOfWordsTemp = this.findAsManyWordsAsPossible(_DecodedString); if(_NumberOfWordsTemp > _HighestNumberOfWords) { _KeyUsedForBestDecodedString = _KeyUsedToDecode; _BestDecodedString = _DecodedString; _HighestNumberOfWords = _NumberOfWordsTemp; } } return ("Stream Cipher\n" + convertForOutputToUser(_BestDecodedString) + "\nKey: " + _KeyUsedForBestDecodedString); } /* Adjust the string according to the key. */ String decodeString(String stringToDecrypt, int decodeKey) { String _DecodedString = ""; for(int x = 0; x < stringToDecrypt.length(); x++) { if(stringToDecrypt.charAt(x) != ' ') { int _CharacterAscii = ((stringToDecrypt.charAt(x) - (int)('a') - decodeKey)) % Ceasar.CHARACTERS_IN_ALPHABET; if(_CharacterAscii < 0) _CharacterAscii = (Ceasar.CHARACTERS_IN_ALPHABET + _CharacterAscii); _DecodedString += (char)(_CharacterAscii + (int)('a')); } else { _DecodedString += ' '; } } return _DecodedString; } /* Uses letter frequency to find the most likely key Bases everything off the letter "e" Depending on the run through it uses the variable "mostLikelyKeyToUse" To find the nth most likely position */ int keyFind(String input, int mostLikelyKeyToUse) { int[] _LetterFrequency = new int[Ceasar.CHARACTERS_IN_ALPHABET], highNum = new int[mostLikelyKeyToUse]; int returnValue; for(int x = 0; x < mostLikelyKeyToUse; x++) highNum[x] = -1; for(int x = 0; x < input.length(); x++) { if(input.charAt(x) != ' ') { _LetterFrequency[input.charAt(x) - (int)('a')]++; } } for(int y = 0; y < mostLikelyKeyToUse; y++) { int num = 0; for(int x = 0; x < Ceasar.CHARACTERS_IN_ALPHABET; x++) { if(_LetterFrequency[x] > num) { Boolean test = true; for(int z = 0; z < y; z++) { if(x == highNum[z]) { //I don't particularly like this bit but it works so it will stay test = false; break; } } if(test) { num = _LetterFrequency[x]; highNum[y] = x; } } } } return (highNum[likelyPos - 1] - 4); } } <file_sep>/* Decoder.java Made by <NAME> Completed on 21/10/2013 Usage: javac decoder.java AND java decoder OR java decoder <ciphertext.txt> */ import java.util.*; import java.io.*; import java.lang.StringBuffer; class decoder { static WordDictionary dic; public static void main(String args[]) { String _TextFileToDecode = "testfile.txt"; String _DictionaryFileLocation = "dict_en.txt"; Scanner reader = new Scanner(System.in); try { decoder.dic = new WordDictionary(_DictionaryFileLocation); } catch(FileNotFoundException e) { System.out.println("Default Dictionary " + _DictionaryFileLocation + " does not exist. This can create problems."); } while(true) { System.out.println("\n\nWelcome to the Block/Ceasar decrypter by <NAME>"); System.out.println("Current Textfile to decrypt is: " + _TextFileToDecode); System.out.println("Current Dictionary location is: " + _DictionaryFileLocation); System.out.println("\nSelect an option:"); System.out.println("1. Decrypt selected textfile"); System.out.println("2. Decrypt manually entered line"); System.out.println("3. Change the textfile to decrypt"); System.out.println("4. Change the dictionary location"); System.out.println("5. Exit"); System.out.println("Input: "); int input = reader.nextInt(); switch(input) { case 1: textFileDecrypt(_TextFileToDecode); System.console().readLine("Press any key to continue"); break; case 2: System.out.println("Code must only use lowercase alphabetical characters and grouped in lots of 5"); String _TextToDecode = System.console().readLine("Input: "); System.out.println(singleDecrypt(_TextToDecode)); System.console().readLine("Press any key to continue"); break; case 3: System.out.println("Enter the full name/location of the target textfile to decrypt"); System.out.println("Input: "); _TextFileToDecode = reader.next(); break; case 4: System.out.println("Enter the full name/location of the new dictionary"); System.out.println("Input: "); String _NewWordDictionaryLocation = reader.nextLine(); try { WordDictionary _NewDictionary = new WordDictionary(_NewWordDictionaryLocation); dic = _NewDictionary; _DictionaryFileLocation = _NewWordDictionaryLocation; } catch (FileNotFoundException e) { System.out.println("File not found for dictionary\n"); } break; case 5: return; } } } static String textFileDecrypt(String input) { File file = new File(input); String code = ""; try { int x = 1; Scanner scanner = new Scanner(file); while(scanner.hasNextLine()) { code = scanner.nextLine(); System.out.println("Line " + x++ + ": "); System.out.println(singleDecrypt(code)); } }catch(FileNotFoundException e) { return("Encryption File not found"); } return ("Decryption completed"); } static String singleDecrypt(String input) { double output = pickEncrypt(input); Ceasar ceasar = new Ceasar(dic); Block block = new Block(dic); switch(validCode(input)) { case 0: if(output > 0.30) { block.setCode(input); return(block.decode() + "\n"); } else { ceasar.setCode(input); return(ceasar.decode() + "\n"); } case 1: return("Error: Invalid spacing (5 lowercase alphabetical characters then a space"); case 2: return("Error: Invalid characters (lowercase alphabetical characters only"); case 3: return("Error: Both invalid spacing and characters (5 lowercase alphabetical characters then a space)"); } return ("An error has occured"); } static double pickEncrypt(String input) { //Count the characters: ETAONRI - It should make up at least 30% of the letters in a non-ceasar sentence double percentage, count = 0; String value; for (int x = 0; x < input.length(); x++) { if (input.charAt(x) == 'e' || input.charAt(x) == 't' || input.charAt(x) == 'a' || input.charAt(x) == 'o' || input.charAt(x) == 'n' || input.charAt(x) == 'r' || input.charAt(x) == 'i') { count++; } } percentage = (count / input.length()); return percentage; } /* Uses bitwise operations to double check the errors a person can encounter It has to double check if there is a space on every 6th character otherwise just alphenumeric characters */ static int validCode(String input) { int valid = 0; for(int x = 0; x < input.length() && valid != 3; x++) { if((x + 1) % 6 == 0 && x != 0 && input.charAt(x) != ' ') { valid = valid | 1; } else if(!(input.charAt(x) >= 'a' && input.charAt(x) <= 'z')&& (x + 1) % 6 != 0 && x == 0) { valid = valid | 2; } } return valid; } } <file_sep>The Ceasar Box Decoder was an old Uni Assignment designed to programatically choose to decode something with Ceasar, or Box Cipher, and then decode it accordingly. Input format: Uniform blocks of characters, with an Output: Decoded message in blocks of 5 characters, the type of Cipher (T for Box/Transposition, and S for Ceasar/Subsitution), and the size of the character blocks from the output. readme.txt - this readme file dict_en.txt - an English dictionary file which contains one word on each line testfile.txt - a test file provided to test your program, which contains a cipher text message on each separate line <file_sep>import java.util.*; /* The Block decryption code The main function (decode) does the vast majority of the work It cycles through all possible solutions from 1 row to each character having it's own row However if it finds a "100% letter match" from verify it breaks out of the loop */ class Block extends code { Block(WordDictionary dict) { super(dict); } Block(String input, WordDictionary dict) { super(input, dict); } String decode() { String _BestDecodedString = ""; int _KeyUsedForBestDecodedString = 0; String _ValueToDecrypt = this.m_ValueToDecrypt.replace(" ", ""); ArrayList<String> rows = new ArrayList<String>(0); ArrayList<Integer> pool = new ArrayList<Integer>(0); int _NumberOfWordsInString = -1; //X decides how many rows there are going to be in the system for(int x = 1; x < _ValueToDecrypt.length(); x++) { String _DecryptedString = ""; rows.clear(); pool.clear(); //Creates new storage values for the two array lists for(int y = 0; y <= x; y++) { rows.add(new String("")); pool.add(0); } //Sets the "pool" to decide how many characters should go in each row. A solution I don't like but just shrugged my shoulders for(int y = 0; y < _ValueToDecrypt.length(); y++) { pool.set(y % (x + 1), pool.get(y % (x + 1)) + 1); } //Adds characters according to the pool. Decriments the poolcount after a character has been assigned for(int y = 0, poolNum = 0; y < _ValueToDecrypt.length(); y++) { if(pool.get(poolNum) == 0) poolNum += 1; rows.set(poolNum, rows.get(poolNum).concat(Character.toString(_ValueToDecrypt.charAt(y)))); pool.set(poolNum, (pool.get(poolNum) - 1)); } //This function adds each character to the system. It double checks to see if it is within the bounds of the possibly smaller rows for(int y = 0; y < rows.get(0).length(); y++) { _DecryptedString += rows.get(0).charAt(y); for(int z = 1; z <= x; z++) if(rows.get(z).length() > y) _DecryptedString += rows.get(z).charAt(y); } int _NumberOfWordsInDecryptedString = this.findAsManyWordsAsPossible(_DecryptedString); if(_NumberOfWordsInDecryptedString > _NumberOfWordsInString) { _KeyUsedForBestDecodedString = x + 1; _BestDecodedString = _DecryptedString; _NumberOfWordsInString = _NumberOfWordsInDecryptedString; } } return ("Transposition Cipher\n" + convertForOutputToUser(_BestDecodedString) + "\nKey: " + _KeyUsedForBestDecodedString); } }
cf9f5189af793c2f541c8c3f8f3705b8aa5a015a
[ "Java", "Text" ]
6
Java
Gorexxar/CeasarBoxDecoder
82451b9b350ad486eae11dbbda6f860445eaebdd
fe204cb79c118471a4b644edaf0f0b2cd2a81775
refs/heads/master
<repo_name>nagadeepsharma/backend<file_sep>/api/migrations/0005_auto_20210619_1137.py # Generated by Django 3.2.2 on 2021-06-19 06:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0004_blogs'), ] operations = [ migrations.AddField( model_name='blogs', name='active', field=models.BooleanField(blank=True, default=True, null=True), ), migrations.AddField( model_name='blogs', name='created', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AddField( model_name='blogs', name='description', field=models.CharField(blank=True, max_length=500, null=True), ), migrations.AddField( model_name='blogs', name='title', field=models.CharField(blank=True, max_length=200, null=True), ), ] <file_sep>/api/migrations/0001_initial.py # Generated by Django 3.2.2 on 2021-06-18 06:17 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Projects', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('thumbnail', models.ImageField(blank=True, null=True, upload_to='images/')), ('title', models.CharField(blank=True, max_length=150, null=True)), ('description', models.CharField(blank=True, max_length=200, null=True)), ('link', models.URLField(blank=True, null=True)), ('created', models.DateTimeField(auto_now_add=True)), ('isactive', models.BooleanField(blank=True, default=True, null=True)), ('isfeatured', models.BooleanField(blank=True, default=False, null=True)), ], ), ] <file_sep>/api/models.py from django.db import models from ckeditor.fields import RichTextField # Create your models here. class Tag(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Projects(models.Model): thumbnail=models.ImageField(blank=True,null=True,upload_to="images/") title=models.CharField(max_length=150,blank=True,null=True) description=models.CharField(max_length=200,blank=True,null=True) link=models.URLField(max_length=200,blank=True,null=True) tags = models.ManyToManyField(Tag, null=True, blank=True) created=models.DateTimeField(auto_now_add=False,blank=True,null=True) isactive=models.BooleanField(default=True,blank=True,null=True) isfeatured=models.BooleanField(default=False,blank=True,null=True) class Meta: ordering=('-created',) def __str__(self): return self.title class Blogs(models.Model): title=models.CharField(max_length=200,blank=True,null=True) description=models.CharField(max_length=500,blank=True,null=True) content=RichTextField() created=models.DateTimeField(auto_now_add=True,blank=True,null=True) active=models.BooleanField(default=True,blank=True,null=True) def __str__(self): return self.title <file_sep>/api/urls.py from django.urls import path from. import views urlpatterns = [ path('',views.index,name='index'), path('projects',views.projects,name='projects'), path('blogs',views.blogs,name='blogs'), path('blogs/<str:pk>',views.blog,name='blog') ]<file_sep>/requirements.txt asgiref==3.3.4 click==8.0.1 colorama==0.4.4 Django==3.2.2 django-ckeditor==6.1.0 django-cors-headers==3.7.0 django-js-asset==1.2.2 djangorestframework==3.12.4 joblib==1.0.1 nltk==3.6.2 Pillow==8.2.0 psycopg2==2.8.6 pytz==2021.1 regex==2021.4.4 sqlparse==0.4.1 tqdm==4.61.0 <file_sep>/api/views.py from api.serializers import Blogsserializer, Projectsserializer from api.models import Blogs, Projects from rest_framework.response import Response from rest_framework.decorators import api_view # Create your views here. @api_view(['GET']) def index(request): content={ "Projects":"/projects", "Blogs":"/blogs" } return Response(content) @api_view(['GET']) def projects(request): projects=Projects.objects.filter(isfeatured=False) featuredproject=Projects.objects.filter(isfeatured=True) fps=Projectsserializer(featuredproject,many=True) projectserializer=Projectsserializer(projects,many=True) return Response({"active":projectserializer.data,"featured":fps.data}) @api_view(['GET']) def blogs(request): blogs=Blogs.objects.filter(active=True) bs=Blogsserializer(blogs,many=True) return Response(bs.data) @api_view(['GET']) def blog(request,pk): blogs=Blogs.objects.get(pk=pk,active=True) bs=Blogsserializer(blogs,) return Response(bs.data) <file_sep>/api/admin.py from api.views import projects from django.contrib import admin from .models import Blogs, Projects,Tag # Register your models here. admin.site.register(Projects) admin.site.register(Tag) admin.site.register(Blogs) <file_sep>/api/serializers.py from django.db.models import fields from rest_framework import serializers from .models import Blogs, Projects, Tag class Projectsserializer(serializers.ModelSerializer): tags=serializers.SlugRelatedField(many=True,slug_field='name',queryset=Tag.objects.all()) class Meta: model=Projects fields=('id','thumbnail','title','description','link','tags',) class Blogsserializer(serializers.ModelSerializer): class Meta: model=Blogs fields=('id','title','description','content','created')<file_sep>/api/migrations/0003_alter_projects_created.py # Generated by Django 3.2.2 on 2021-06-18 10:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20210618_1537'), ] operations = [ migrations.AlterField( model_name='projects', name='created', field=models.DateTimeField(blank=True, null=True), ), ]
972fb98910918a05a6c436de26844abc5b4794d8
[ "Python", "Text" ]
9
Python
nagadeepsharma/backend
f713f2cf0365bf7fe583fce79a742a5d0a549593
9336f2b41ca291b5aad31bd5268c3eead21a0978
refs/heads/master
<file_sep>##[Simple Chat Client](http://simplechatclient.github.io "Simple Chat Client Offical Site") Simple Chat Client is a lightweight and simple program which allows talking in the czat.onet.pl without using a browser or java. The program of the assumptions is small, lightweight and stable client. <file_sep>/* * Simple Chat Client * * Copyright (C) <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.simplechatclient.android; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.core.Network; import com.models.Channels; import com.models.ChannelsManager; import com.models.Notifications; public class MainActivity extends ActionBarActivity implements NavigationDrawerLeftFragment.NavigationDrawerLeftCallbacks, NavigationDrawerRightFragment.NavigationDrawerRightCallbacks { /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ private NavigationDrawerRightFragment mNavigationDrawerRightFragment; private NavigationDrawerLeftFragment mNavigationDrawerLeftFragment; /** * Used to store the last screen title. For use in {@link #restoreActionBar()}. */ private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // TODO fix drawers http://stackoverflow.com/a/19834384 // TODO Adapting to Latency https://youtu.be/uzboHWX3Kvc?list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE mNavigationDrawerRightFragment = (NavigationDrawerRightFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer_right); mNavigationDrawerLeftFragment = (NavigationDrawerLeftFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer_left); // Set up the drawer. mNavigationDrawerRightFragment.setUp( R.id.navigation_drawer_right, (DrawerLayout) findViewById(R.id.drawer_layout)); mNavigationDrawerLeftFragment.setUp( R.id.navigation_drawer_left, (DrawerLayout) findViewById(R.id.drawer_layout)); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_drawer); // add channel switchChannel(1, Channels.STATUS); // connect Network.getInstance().connect(); } private void switchChannel(int index, String channel) { // add channel ChannelFragment f = new ChannelFragment(); f.setArguments(index, channel, mNavigationDrawerLeftFragment); mTitle = channel; setTitle(mTitle); // update the main content by replacing fragments FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, f) .commit(); ChannelsManager.getInstance().setCurrentFragment(f); } @Override public void onBackPressed() { //super.onBackPressed(); moveTaskToBack(true); } @Override public void onNavigationDrawerLeftItemSelected(int position) { Log.i("MainActivity", "onNavigationDrawerLeftItemSelected - position: " + position); if (position == 0) { if (Network.getInstance().isConnected()) { Network.getInstance().disconnect(); } else { Network.getInstance().connect(); } } else if (position == 1) { // TODO profiles list /* Intent profileListIntent = new Intent(this, ProfileActivity.class); profileListIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); profileListIntent.putExtra("tab", "0"); // main startActivity(profileListIntent); */ } else if (position == 2) { // TODO close application if (Network.getInstance().isConnected()) { Network.getInstance().disconnect(); } finish(); Notifications.getInstance().destroy(); } else { position -= 3; // first 3 items are options String channel = Channels.getInstance().getNameFromIndex(position); Log.w("MainActivity", "switch to channel "+channel); if (!channel.isEmpty()) { switchChannel(position, channel); } } } @Override public void onNavigationDrawerRightItemSelected(int position) { Log.i("MainActivity", "onNavigationDrawerRightItemSelected"); } public void onSectionAttached(int number) { Log.i("MainActivity", "onSectionAttached: "+number); String channel = Channels.getInstance().getNameFromIndex(number); if (!channel.isEmpty()) { mTitle = channel; } } public void restoreActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { Log.i("MainActivity", "onCreateOptionsMenu"); /* if ((!mNavigationDrawerLeftFragment.isDrawerOpen()) && (!mNavigationDrawerRightFragment.isDrawerOpen())) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. getMenuInflater().inflate(R.menu.main, menu); restoreActionBar(); return true; } */ return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } <file_sep>/* * Simple Chat Client * * Copyright (C) <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.simplechatclient.android; import java.util.List; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.core.Config; import com.core.Settings; import com.database.DatabaseProfile; import com.database.DatabaseSetting; public class ProfileEditActivity extends ActionBarActivity { private DatabaseProfile profile; private Config current_config; private String nick; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.profile_edit_activity); context = getApplicationContext(); final ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayShowTitleEnabled(true); setHasOptionsMenu(true); nick = getIntent().getStringExtra("nick"); current_config = new Config(this); profile = current_config.getProfile(nick); EditText editTextNick = (EditText)findViewById(R.id.editTextEditNick); EditText editTextPassword = (EditText)findViewById(R.id.editTextEditPassword); editTextNick.setText(profile.getNick()); editTextPassword.setText(profile.getPassword()); if (!nick.contains("~")) { editTextPassword.setVisibility(View.VISIBLE); } else { editTextPassword.setVisibility(View.INVISIBLE); } } private void setHasOptionsMenu(boolean b) { // TODO Auto-generated method stub } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.profile_edit, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.edit_profile_button_remove: button_remove(); return true; case R.id.edit_profile_button_save: button_save(); return true; default: return super.onOptionsItemSelected(item); } } private void button_remove() { current_config.deleteProfile(nick); if (current_config.getProfilesCount() == 0) { current_config.createRandomUser(); } if (Integer.parseInt(Settings.getInstance().get("current_profile")) == profile.getId()) { List<DatabaseProfile> profiles = current_config.getProfiles(); DatabaseProfile current_profile = profiles.get(0); DatabaseSetting current_setting = current_config.getSetting(); current_setting.setCurrent_profile(current_profile.getId()); Settings.getInstance().set("current_profile", String.valueOf(current_profile.getId())); Settings.getInstance().set("nick", current_profile.getNick()); Settings.getInstance().set("password", <PASSWORD>()); Settings.getInstance().set("font", current_profile.getFont()); Settings.getInstance().set("bold", current_profile.getBold()); Settings.getInstance().set("italic", current_profile.getItalic()); Settings.getInstance().set("color", current_profile.getColor()); } Toast toast = Toast.makeText(getApplicationContext(), getResources().getString(R.string.successfully_removed), Toast.LENGTH_SHORT); toast.show(); Intent profileListIntent = new Intent(context, ProfileActivity.class); profileListIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); profileListIntent.putExtra("tab", "1"); // profile list startActivity(profileListIntent); } private void button_save() { EditText editTextNick = (EditText)findViewById(R.id.editTextEditNick); EditText editTextPassword = (EditText)findViewById(R.id.editTextEditPassword); if (editTextPassword.getVisibility() == View.VISIBLE) { String save_nick = editTextNick.getText().toString(); String save_password = editTextPassword.getText().toString(); if (save_nick.length() > 32) save_nick = save_nick.substring(0, 32); profile.setNick(save_nick); profile.setPassword(<PASSWORD>); } else { String save_nick = editTextNick.getText().toString(); save_nick = save_nick.replace("~",""); if (save_nick.length() > 31) save_nick = save_nick.substring(0, 31); save_nick = "~"+save_nick; profile.setNick(save_nick); } current_config.updateProfile(profile); if (Integer.parseInt(Settings.getInstance().get("current_profile")) == profile.getId()) { Settings.getInstance().set("nick", profile.getNick()); Settings.getInstance().set("password", profile.getPassword()); } Toast toast = Toast.makeText(context, getResources().getString(R.string.successfully_saved), Toast.LENGTH_SHORT); toast.show(); Intent profileListIntent = new Intent(context, ProfileActivity.class); profileListIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); profileListIntent.putExtra("tab", "1"); // profile list startActivity(profileListIntent); } } <file_sep>/* * Simple Chat Client * * Copyright (C) <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.simplechatclient.android; public class NavigationDrawerItem { private String title; private String icon; public NavigationDrawerItem(){} public NavigationDrawerItem(String title, String icon){ this.title = title; this.icon = icon; } public String getTitle(){ return this.title; } public String getIcon(){ return this.icon; } public void setTitle(String title){ this.title = title; } public void setIcon(String icon){ this.icon = icon; } } <file_sep>/* * Simple Chat Client * * Copyright (C) <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.onet; import android.annotation.SuppressLint; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import com.core.Messages; import com.core.Network; import com.core.Settings; import com.models.Channels; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.IOException; import java.io.StringReader; import java.net.CookieManager; import java.net.CookiePolicy; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; public class OnetAuth { private static final String AJAX_API = "http://czat.onet.pl/include/ajaxapi.xml.php3"; private static final String TAG = "OnetAuth"; private boolean registeredNick; private boolean override = false; private String nick; private String password; private String version; private OkHttpClient httpclient; private static OnetAuth instance = new OnetAuth(); public static synchronized OnetAuth getInstance() { return instance; } private AuthHandler authHandler; private String current_category; private String current_result; public OnetAuth() { authHandler = new AuthHandler(); } public void authorize() { if (Settings.getInstance().get("authorizing").equalsIgnoreCase("true")) { Log.w(TAG, "Already authorizing"); return; } nick = Settings.getInstance().get("nick"); password = Settings.getInstance().get("password"); registeredNick = !nick.startsWith("~"); Log.i("Auth", "Authorizing nick: "+nick+" password: "+password+" registered: "+registeredNick); override = true; Settings.getInstance().set("authorizing", "true"); current_category = null; current_result = null; httpclient = new OkHttpClient(); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); httpclient.setCookieHandler(cookieManager); downloadChat(); } private class AuthHandler extends Handler { @Override public void handleMessage(Message msg) { //Bundle bundle = msg.getData(); //String current_category = msg.getData().getString("current_category"); //String current_result = msg.getData().getString("current_result"); authkernel(); } public void authkernel() { if (current_category == null) downloadChat(); else { if (current_category.equals("chat")) downloadDeploy(); else if (current_category.equals("deploy")) { parseDeploy(current_result); downloadKropka1(); } else if (current_category.equals("kropka_1")) downloadKropka1Full(); else if (current_category.equals("kropka_1_full")) downloadKropka5Full(); else if (current_category.equals("kropka_5_full")) downloadSk(); else if (current_category.equals("sk")) { if (registeredNick) downloadSecureLogin(); else { // showCaptchaDialog(); // TODO startActivityForResult // TODO http://developer.android.com/reference/android/app/Activity.html // TODO http://developer.android.com/training/basics/intents/result.html String code = "empty"; downloadCheckCode(code); } } else if (current_category.equals("secure_login")) { if (override) downloadOverride(); else downloadUo(); } else if (current_category.equals("override")) downloadUo(); else if (current_category.equals("check_code")) downloadUo(); else if (current_category.equals("uo")) { parseUo(current_result); Settings.getInstance().set("authorizing", "false"); } else { Log.e(TAG, "Undefined category: "+current_category); Settings.getInstance().set("authorizing", "false"); } } } } private void downloadChat() { String url = "http://czat.onet.pl/chat.html"; String content = "ch=&n=&p=&category=0"; String category = "chat"; new HttpDownload(url, content, category).start(); } private void downloadDeploy() { String url = "http://czat.onet.pl/_s/deployOnetCzat.js"; String category = "deploy"; new HttpDownload(url, null, category).start(); } private void parseDeploy(String data) { version = parseVersion(data); version = String.format("1.1(%s - R)", version); } private void downloadKropka1() { String url = "http://kropka.onet.pl/_s/kropka/1?DV=czat/applet"; String category = "kropka_1"; new HttpDownload(url, null, category).start(); } private void downloadKropka1Full() { String url = "http://kropka.onet.pl/_s/kropka/1?DV=czat/applet/FULL"; String category = "kropka_1_full"; new HttpDownload(url, null, category).start(); } private void downloadKropka5Full() { String url = "http://kropka.onet.pl/_s/kropka/5?DV=czat/applet/FULL"; String category = "kropka_5_full"; new HttpDownload(url, null, category).start(); } private void downloadSk() { String url = "http://czat.onet.pl/sk.gif"; String category = "sk"; new HttpDownload(url, null, category).start(); } @SuppressLint("DefaultLocale") private void downloadCheckCode(String code) { String url = AJAX_API; String content = String.format("api_function=checkCode&params=a:1:{s:4:\"code\";s:%d:\"%s\";}", code.length(), code); String category = "check_code"; new HttpDownload(url, content, category).start(); } private void downloadSecureLogin() { String url = "https://secure.onet.pl/mlogin.html"; String content = String.format("r=&url=&login=%s&haslo=%s&app_id=20&ssl=1&ok=1", nick, password); String category = "secure_login"; new HttpDownload(url, content, category).start(); } @SuppressLint("DefaultLocale") private void downloadOverride() { String url = AJAX_API; String content = String.format("api_function=userOverride&params=a:1:{s:4:\"nick\";s:%d:\"%s\";}", nick.length(), nick); String category = "override"; new HttpDownload(url, content, category).start(); } @SuppressLint("DefaultLocale") private void downloadUo() { int isRegistered = (registeredNick ? 0 : 1); String url = AJAX_API; String content = String.format("api_function=getUoKey&params=a:3:{s:4:\"nick\";s:%d:\"%s\";s:8:\"tempNick\";i:%d;s:7:\"version\";s:%d:\"%s\";}", nick.length(), nick, isRegistered, version.length(), version); String category = "uo"; new HttpDownload(url, content, category).start(); } private String parseVersion(String data) { if (data != null) { if (data.contains("OnetCzatLoader")) { String strFind1 = "signed-OnetCzatLoader-"; String strFind2 = ".jar"; int pos1 = data.indexOf(strFind1) + strFind1.length(); int pos2 = data.indexOf(strFind2, pos1); String ver = data.substring(pos1, pos2); if ((ver.length() > 0) && (ver.length() < 20)) return ver; } } return "20150114-1332"; } // <?xml version="1.0" encoding="ISO-8859-2"?><root><uoKey><KEY></uoKey><zuoUsername>~Succubi_test</zuoUsername><error err_code="TRUE" err_text="wartość prawdziwa" ></error></root> // <?xml version="1.0" encoding="ISO-8859-2"?><root><error err_code="-2" err_text="U.ytkownik nie zalogowany" ></error></root> private void parseUo(String data) { try { Log.i(TAG, "pareUO: "+data); if (data == null) { Messages.getInstance().showMessage(Channels.STATUS, "Błąd autoryzacji [Brak odpowiedzi od serwera]", Messages.MessageType.ERROR); return; } DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(data))); document.getDocumentElement().normalize(); Node error = document.getElementsByTagName("error").item(0); String err_code = error.getAttributes().getNamedItem("err_code").getNodeValue(); String err_text = error.getAttributes().getNamedItem("err_text").getNodeValue(); if (err_code.equalsIgnoreCase("true")) { String UOKey = document.getElementsByTagName("uoKey").item(0).getTextContent(); String UONick = document.getElementsByTagName("zuoUsername").item(0).getTextContent(); if (Network.getInstance().isConnected()) { Settings.getInstance().set("uo_nick", UONick); Settings.getInstance().set("uo_key", UOKey); Network.getInstance().send("AUTHKEY"); } } else { Log.e(TAG, String.format("Authentication error [%s]", err_text)); Messages.getInstance().showMessage(Channels.STATUS, String.format("Błąd autoryzacji [%s]", err_text), Messages.MessageType.ERROR); } } catch (ParserConfigurationException e) { Log.e(TAG, "Parse XML configuration exception:"+ e.getMessage()); e.printStackTrace(); } catch (SAXException e) { Log.e(TAG, "Wrong XML file structure:"+ e.getMessage()); e.printStackTrace(); } catch (IOException e) { Log.e(TAG, "Cannot parse XML:"+ e.getMessage()); e.printStackTrace(); } } public class HttpDownload extends Thread { private String url; private String content; private String category; public HttpDownload(String _url, String _content, String _category) { url = _url; content = _content; category = _category; } public void run() { Log.i(TAG, "HttpDownload url: "+url); Log.i(TAG, "HttpDownload content: "+content); current_category = category; current_result = null; try { if ((content == null) || (content.isEmpty())) { Request request = new Request.Builder().url(url).build(); Response response = httpclient.newCall(request).execute(); if (response.isSuccessful()) { current_result = response.body().string(); } } else { RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), content); Request request = new Request.Builder().url(url).post(body).build(); Response response = httpclient.newCall(request).execute(); if (response.isSuccessful()) { current_result = response.body().string(); } } } catch (IOException e) { Log.e(TAG, "Unable to retrieve web page (IOException:"+e.getMessage()+"): " + url); } finally { Message msg = new Message(); Bundle bundle = new Bundle(); bundle.putString("current_category", current_category); bundle.putString("current_result", current_result); msg.setData(bundle); authHandler.sendMessage(msg); } } } } <file_sep>/* * Simple Chat Client * * Copyright (C) <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.core; import java.util.HashMap; import java.util.Map; public class Replace { public static String replaceEmots(String message) { Map<String, String> emoticons = new HashMap<>(); emoticons.put(":*", "%Icmok%"); emoticons.put(";)", "%Ioczko%"); emoticons.put(":P", "%Ijezor%"); emoticons.put(";P", "%Ixjezyk%"); emoticons.put(":)", "%Ihaha%"); emoticons.put(":(", "%Izal%"); emoticons.put(":x", "%Inie_powiem%"); emoticons.put(":?", "%Inie_rozumiem%"); emoticons.put(":((", "%Ibardzo_smutny%"); emoticons.put(":|", "%Ixdepresja%"); emoticons.put(":]", "%Iusmieszek%"); emoticons.put(":>", "%Ixluzak%"); emoticons.put(";>", "%Iwazniak%"); emoticons.put(":<", "%Iumm%"); emoticons.put(":$", "%Iskwaszony%"); emoticons.put(";$", "%Ixkwas%"); emoticons.put(";/", "%Ixsceptyk%"); //emoticons.put(":/", "%Isceptyczny%"); emoticons.put(";D", "%Ixhehe%"); emoticons.put(":D", "%Ihehe%"); //emoticons.put("o_O", "%Iswir%"); emoticons.put("!!", "%Iwykrzyknik%"); emoticons.put("??", "%Ipytanie%"); //emoticons.put("xD", "%Ilol%"); //emoticons.put("-_-", "%Iwrr%"); emoticons.put(";(", "%Iszloch%"); // scc emoticons.put(":))", "%Ihaha%"); emoticons.put(";))", "%Ioczko%"); emoticons.put(";((", "%Iszloch%"); emoticons.put(";(", "%Iszloch%"); emoticons.put(":p", "%Ijezyk%"); emoticons.put(";p", "%Ijezor%"); emoticons.put(":d", "%Ihehe%"); emoticons.put(";d", "%Ihehe%"); emoticons.put(";x", "%Inie_powiem%"); emoticons.put(":o", "%Ipanda%"); emoticons.put(";o", "%Ipanda%"); emoticons.put(";<", "%Ibuu%"); emoticons.put(";]", "%Ioczko%"); emoticons.put(":[", "%Izal%"); emoticons.put(";[", "%Iszloch%"); emoticons.put(";|", "%Ixdepresja%"); emoticons.put(";*", "%Icmok2%"); emoticons.put(":s", "%Iskwaszony%"); emoticons.put(";s", "%Iskwaszony%"); emoticons.put("]:->", "%Ixdiabel%"); emoticons.put("];->", "%Ixdiabel%"); emoticons.put(";?", "%Ixco%"); for(Map.Entry<String, String> entry : emoticons.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); message = message.replace(key, value); } // exception // :/ if ((!message.contains("http://")) && (!message.contains("https://"))) message = message.replace(":/", "%Isceptyczny%"); return message; } } <file_sep>/* * Simple Chat Client * * Copyright (C) <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.simplechatclient.android; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.text.Spanned; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import com.core.Convert; import com.core.Messages; import com.core.Network; import com.core.Replace; import com.core.Settings; import com.models.Channels; import com.models.ChannelsManager; import com.models.Commands; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * A placeholder fragment containing a simple view. */ public class ChannelFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private int sectionNumber = 0; private String channelName = ""; private View rootView; private ArrayAdapter<Spanned> adapter; private ListView listView; private EditText editText; private ArrayList<Spanned> listItems = new ArrayList<>(); private NavigationDrawerLeftFragment mNavigationDrawerLeftFragment; public ChannelFragment() {} public void setArguments(int section_number, String channel_name, NavigationDrawerLeftFragment _mNavigationDrawerLeftFragment) { sectionNumber = section_number; channelName = channel_name; mNavigationDrawerLeftFragment = _mNavigationDrawerLeftFragment; Channels.getInstance().add(channel_name); ChannelsManager.getInstance().setCurrentName(channel_name); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_main, container, false); adapter = new ArrayAdapter<>(container.getContext(), R.layout.fragment_item, R.id.textViewFragmentItem, listItems); listView = (ListView) rootView.findViewById(R.id.listViewChannel); listView.setAdapter(adapter); editText = (EditText)rootView.findViewById(R.id.editTextChannel); editText.setOnEditorActionListener(mWriteListener); ImageButton sendButton = (ImageButton)rootView.findViewById(R.id.imageButtonSendMessage); sendButton.setOnClickListener(sendButtonClickListener); return rootView; } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); Log.w("ChannelFragment", "onPrepareOptionsMenu"); } @Override public void onStart() { super.onStart(); // clear before init listItems.clear(); String channel = channelName; List<String> messages = ChannelsManager.getInstance().getMessages(channel); if (messages.size() > 0) { if (rootView != null) { for (String message : messages) { listItems.add(Html.fromHtml(message, new ImageGetter(), null)); } adapter.notifyDataSetChanged(); scrollToBottom(); } } } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainActivity) activity).onSectionAttached(sectionNumber); } public String getChannelName() { return channelName; } public void showMessage(String message) { Log.i("ChannelFragment", channelName + " show message: " + message); if (rootView != null) { if (listItems.size() > 100) { listItems.remove(0); } listItems.add(Html.fromHtml(message, new ImageGetter(), null)); adapter.notifyDataSetChanged(); scrollToBottom(); } } private void scrollToBottom() { listView.post(new Runnable() { @Override public void run() { // Select the last row so it will scroll into view... listView.setSelection(adapter.getCount() - 1); } }); } private boolean sendMultiLineMessage(String message, boolean moderation) { String[] list = message.split("(\\n|\\r)"); int len = 396; boolean clearLine = true; for (String line : list) { if (line.length() > len) { // find last space and cut int pos = line.lastIndexOf(' ', len); if (pos != -1) { pos++; // remove space } else { pos = len; // no cut } String shortLine = line; shortLine = shortLine.substring(0, pos); clearLine = sendMessage(shortLine, moderation); line = line.substring(pos); } if ((line.length() < len) && (line.length() != 0)) { clearLine = sendMessage(line, moderation); } } return clearLine; } private boolean sendMessage(String message, boolean moderation) { String myNick = Settings.getInstance().get("nick"); String channel = ChannelsManager.getInstance().getCurrentName(); String message_original = ""; String command = ""; if ((message.startsWith("/")) && (!message.startsWith("//"))) { message = message.substring(1); message_original = message; String[] message_splited = message.split(" "); if (message_splited.length != 0) command = message_splited[0]; if (!command.isEmpty()) { command = command.toLowerCase(); Commands commands = new Commands(channel, message); message = commands.execute(); } if (message.isEmpty()) return true; } Log.i("ChannelFragment", "sending: "+message); if ((command.equalsIgnoreCase("amsg")) || (command.equalsIgnoreCase("all"))) { message = Convert.simpleReverseConvert(message); message = Replace.replaceEmots(message); message = Convert.createText(message); List<String> opened_channels = Channels.getInstance().get(); for (String opened_channel : opened_channels) { Network.getInstance().send(String.format("PRIVMSG %s :%s", opened_channel, message)); Messages.getInstance().showMessage(channel, message, Messages.MessageType.DEFAULT, myNick); } return true; } else if (command.equalsIgnoreCase("me")) { if (!channel.equals(Channels.STATUS)) { Network.getInstance().send(message); if (message_original.length() > 3) message_original = message_original.substring(3); message_original = Convert.simpleReverseConvert(message_original); message_original = Replace.replaceEmots(message_original); message_original = Convert.createText(message_original); byte zero_one = 0x01; String display = String.format("%sACTION %s%s", Byte.toString(zero_one), message_original, Byte.toString(zero_one)); Messages.getInstance().showMessage(channel, display, Messages.MessageType.ME, myNick); } return true; } else if (command.equalsIgnoreCase("raw")) { Network.getInstance().send(message); return true; } else if (!command.isEmpty()) { Network.getInstance().send(message); return true; } if (channel.equalsIgnoreCase(Channels.STATUS)) return true; message = Convert.simpleReverseConvert(message); message = Replace.replaceEmots(message); message = Convert.createText(message); // moder notice if (moderation) { Network.getInstance().send(String.format("MODERNOTICE %s :%s", channel, message)); Messages.getInstance().showMessage(channel, message, Messages.MessageType.MODER_NOTICE, myNick); } // standard text else { boolean offline = Channels.getInstance().getOffline(channel); String nick = Channels.getInstance().getAlternativeName(channel); if ((offline) && (!nick.isEmpty())) { Network.getInstance().send(String.format("NS OFFLINE MSG %s %s", nick, message)); } else { Network.getInstance().send(String.format("PRIVMSG %s :%s", channel, message)); } Messages.getInstance().showMessage(channel, message, Messages.MessageType.DEFAULT, myNick); } return true; } private ImageButton.OnClickListener sendButtonClickListener = new ImageButton.OnClickListener() { @Override public void onClick(View v) { if (v.getId() == R.id.imageButtonSendMessage) { boolean moderation = false; boolean clearLine = sendMultiLineMessage(editText.getText().toString(), moderation); if (clearLine) { editText.setText(""); } } } }; private TextView.OnEditorActionListener mWriteListener = new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if ((actionId == EditorInfo.IME_ACTION_DONE) || ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN))) { handled = true; boolean moderation = false; boolean clearLine = sendMultiLineMessage(editText.getText().toString(), moderation); if (clearLine) { editText.setText(""); } } return handled; } }; private class ImageGetter implements Html.ImageGetter { public Drawable getDrawable(String image) { String[] emoticons = Convert.emoticons; if (Arrays.asList(emoticons).contains(image)) { try { InputStream ims = getContext().getAssets().open("emoticons/" + image + ".png"); Drawable d = Drawable.createFromStream(ims, null); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } catch (IOException e) { return null; } } else { return null; } } }; } <file_sep>/* * Simple Chat Client * * Copyright (C) <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.models; public class OnetChannel { String avatar; String name; boolean displayedOptions; boolean offline; public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public boolean isDisplayedOptions() { return displayedOptions; } public void setDisplayedOptions(boolean displayedOptions) { this.displayedOptions = displayedOptions; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isOffline() { return offline; } public void setOffline(boolean offline) { this.offline = offline; } } <file_sep>/* * Simple Chat Client * * Copyright (C) <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.core; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.database.DatabaseHelper; import com.database.DatabaseProfile; import com.database.DatabaseSetting; public class Config { private static final String TAG = "Config"; private DatabaseHelper myDatabaseHelper; public Config(Context context) { myDatabaseHelper = new DatabaseHelper(context); } public DatabaseSetting getSetting() { DatabaseSetting setting = new DatabaseSetting(); SQLiteDatabase db = myDatabaseHelper.getWritableDatabase(); Cursor cursor = null; try { String[] columns = {DatabaseHelper.TABLE_SETTINGS_CURRENT_PROFILE, DatabaseHelper.TABLE_SETTINGS_UNIQUE_ID}; cursor = db.query(DatabaseHelper.TABLE_SETTINGS, // table columns, // column names DatabaseHelper.TABLE_SETTINGS_ID +" = ?", // selections new String[] { String.valueOf(DatabaseHelper.TABLE_SETTINGS_ID_CURRENT) }, // selections args null, // group by null, // having null, // order by null); // limit if (cursor != null) cursor.moveToFirst(); int current_profile = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_SETTINGS_CURRENT_PROFILE)); String unique_id = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_SETTINGS_UNIQUE_ID)); setting.setCurrent_profile(current_profile); setting.setUnique_id(unique_id); } catch (Exception e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } finally { if (cursor != null) cursor.close(); if (db != null) db.close(); } return setting; } public DatabaseProfile getProfile(int nick_id) { DatabaseProfile profile = new DatabaseProfile(); SQLiteDatabase db = myDatabaseHelper.getWritableDatabase(); Cursor cursor = null; try { String[] columns = {DatabaseHelper.TABLE_PROFILES_ID, DatabaseHelper.TABLE_PROFILES_NICK, DatabaseHelper.TABLE_PROFILES_PASSWORD, DatabaseHelper.TABLE_PROFILES_FONT, DatabaseHelper.TABLE_PROFILES_BOLD, DatabaseHelper.TABLE_PROFILES_ITALIC, DatabaseHelper.TABLE_PROFILES_COLOR}; cursor = db.query(DatabaseHelper.TABLE_PROFILES, // table columns, // column names DatabaseHelper.TABLE_PROFILES_ID+" = ?", // selections new String[] { String.valueOf(nick_id) }, // selections args null, // group by null, // having null, // order by null); // limit if (cursor != null) cursor.moveToFirst(); int id = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_ID)); String nick = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_NICK)); String password = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_PASSWORD)); String font = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_FONT)); String bold = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_BOLD)); String italic = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_ITALIC)); String color = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_COLOR)); profile.setId(id); profile.setNick(nick); profile.setPassword(<PASSWORD>); profile.setFont(font); profile.setBold(bold); profile.setItalic(italic); profile.setColor(color); } catch (Exception e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } finally { if (cursor != null) cursor.close(); if (db != null) db.close(); } return profile; } public DatabaseProfile getProfile(String profile_nick) { DatabaseProfile profile = new DatabaseProfile(); SQLiteDatabase db = myDatabaseHelper.getWritableDatabase(); Cursor cursor = null; try { String[] columns = {DatabaseHelper.TABLE_PROFILES_ID, DatabaseHelper.TABLE_PROFILES_NICK, DatabaseHelper.TABLE_PROFILES_PASSWORD, DatabaseHelper.TABLE_PROFILES_FONT, DatabaseHelper.TABLE_PROFILES_BOLD, DatabaseHelper.TABLE_PROFILES_ITALIC, DatabaseHelper.TABLE_PROFILES_COLOR}; cursor = db.query(DatabaseHelper.TABLE_PROFILES, // table columns, // column names DatabaseHelper.TABLE_PROFILES_NICK+" = ?", // selections new String[] { String.valueOf(profile_nick) }, // selections args null, // group by null, // having null, // order by null); // limit if (cursor != null) cursor.moveToFirst(); int id = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_ID)); String nick = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_NICK)); String password = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_PASSWORD)); String font = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_FONT)); String bold = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_BOLD)); String italic = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_ITALIC)); String color = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_COLOR)); profile.setId(id); profile.setNick(nick); profile.setPassword(<PASSWORD>); profile.setFont(font); profile.setBold(bold); profile.setItalic(italic); profile.setColor(color); } catch (Exception e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } finally { if (cursor != null) cursor.close(); if (db != null) db.close(); } return profile; } public long getProfilesCount() { long count = 0; SQLiteDatabase db = myDatabaseHelper.getWritableDatabase(); Cursor cursor = null; try { String selectQuery = "SELECT COUNT(*) AS c FROM " + DatabaseHelper.TABLE_PROFILES; cursor = db.rawQuery(selectQuery, null); if (cursor != null) cursor.moveToFirst(); count = cursor.getInt(cursor.getColumnIndexOrThrow("c")); } catch (Exception e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } finally { if (db != null) db.close(); } return count; } public boolean profileExists(String nick) { SQLiteDatabase db = myDatabaseHelper.getWritableDatabase(); Cursor cursor = null; try { String selectQuery = "SELECT COUNT(*) AS c FROM " + DatabaseHelper.TABLE_PROFILES + " WHERE nick = \""+ nick +"\""; cursor = db.rawQuery(selectQuery, null); if (cursor != null) cursor.moveToFirst(); long count = cursor.getInt(cursor.getColumnIndexOrThrow("c")); if (count > 0) return true; else return false; } catch (Exception e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } finally { if (db != null) db.close(); } return false; } public List<DatabaseProfile> getProfiles() { List<DatabaseProfile> profiles = new ArrayList<>(); SQLiteDatabase db = myDatabaseHelper.getWritableDatabase(); Cursor cursor = null; try { String selectQuery = "SELECT * FROM " + DatabaseHelper.TABLE_PROFILES; cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { int id = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_ID)); String nick = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_NICK)); String password = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_PASSWORD)); String font = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_FONT)); String bold = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_BOLD)); String italic = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_ITALIC)); String color = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TABLE_PROFILES_COLOR)); DatabaseProfile profile = new DatabaseProfile(); profile.setId(id); profile.setNick(nick); profile.setPassword(<PASSWORD>); profile.setFont(font); profile.setBold(bold); profile.setItalic(italic); profile.setColor(color); profiles.add(profile); } while (cursor.moveToNext()); } } catch (Exception e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } finally { if (cursor != null) cursor.close(); if (db != null) db.close(); } return profiles; } public void createRandomUser() { SQLiteDatabase db = myDatabaseHelper.getWritableDatabase(); try { myDatabaseHelper.createRandomUser(db); } catch (Exception e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } finally { if (db != null) db.close(); } } public void updateSettings(DatabaseSetting setting) { SQLiteDatabase db = myDatabaseHelper.getWritableDatabase(); try { ContentValues update_setting = new ContentValues(); update_setting.put(DatabaseHelper.TABLE_SETTINGS_CURRENT_PROFILE, setting.getCurrent_profile()); update_setting.put(DatabaseHelper.TABLE_SETTINGS_UNIQUE_ID, setting.getUnique_id()); db.update(DatabaseHelper.TABLE_SETTINGS, update_setting, DatabaseHelper.TABLE_SETTINGS_ID+" = ?", new String[] { String.valueOf(DatabaseHelper.TABLE_SETTINGS_ID_CURRENT) }); } catch (Exception e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } finally { if (db != null) db.close(); } } public long addProfile(String nick, String password) { SQLiteDatabase db = myDatabaseHelper.getWritableDatabase(); ContentValues new_profile = new ContentValues(); new_profile.put(DatabaseHelper.TABLE_PROFILES_NICK, nick); new_profile.put(DatabaseHelper.TABLE_PROFILES_PASSWORD, password); //new_profile.put(DatabaseHelper.TABLE_PROFILES_FONT, font); //new_profile.put(DatabaseHelper.TABLE_PROFILES_BOLD, bold); //new_profile.put(DatabaseHelper.TABLE_PROFILES_ITALIC, italic); //new_profile.put(DatabaseHelper.TABLE_PROFILES_COLOR, color); long id = db.insert(DatabaseHelper.TABLE_PROFILES, null, new_profile); db.close(); return id; } public void updateProfile(DatabaseProfile profile) { SQLiteDatabase db = myDatabaseHelper.getWritableDatabase(); try { ContentValues update_profile = new ContentValues(); update_profile.put(DatabaseHelper.TABLE_PROFILES_NICK, profile.getNick()); update_profile.put(DatabaseHelper.TABLE_PROFILES_PASSWORD, profile.getPassword()); update_profile.put(DatabaseHelper.TABLE_PROFILES_FONT, profile.getFont()); update_profile.put(DatabaseHelper.TABLE_PROFILES_BOLD, profile.getBold()); update_profile.put(DatabaseHelper.TABLE_PROFILES_ITALIC, profile.getItalic()); update_profile.put(DatabaseHelper.TABLE_PROFILES_COLOR, profile.getColor()); db.update(DatabaseHelper.TABLE_PROFILES, update_profile, DatabaseHelper.TABLE_PROFILES_ID+" = ?", new String[] { String.valueOf(profile.getId()) }); } catch (Exception e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } finally { if (db != null) db.close(); } } public void deleteProfile(String nick) { SQLiteDatabase db = myDatabaseHelper.getWritableDatabase(); try { db.delete(DatabaseHelper.TABLE_PROFILES, DatabaseHelper.TABLE_PROFILES_NICK + " = ?", new String[] { String.valueOf(nick) }); } catch (Exception e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } finally { if (db != null) db.close(); } } } <file_sep>/* * Simple Chat Client * * Copyright (C) <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.simplechatclient.android; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Toast; import com.core.Config; public class ProfileAddFragment extends Fragment implements View.OnClickListener { private Context context; private View view; public static ProfileAddFragment newInstance() { ProfileAddFragment fragment = new ProfileAddFragment(); return fragment; } public ProfileAddFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.profile_add_fragment, container, false); context = container.getContext(); myStart(); return view; } public void myStart() { CompoundButton compoundButtonRegistered = (CompoundButton)view.findViewById(R.id.add_profile_switch_registered); compoundButtonRegistered.setOnClickListener(this); add_profile_switch_registered(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.profile_add, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.profile_add_button_add: add_new_profile(); break; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.add_profile_switch_registered: add_profile_switch_registered(); break; } } private void add_profile_switch_registered() { CompoundButton compoundButtonRegistered = (CompoundButton)view.findViewById(R.id.add_profile_switch_registered); EditText editTextNewPassword = (EditText)view.findViewById(R.id.editTextNewPassword); if (compoundButtonRegistered.isChecked()) { editTextNewPassword.setVisibility(View.VISIBLE); } else { editTextNewPassword.setVisibility(View.GONE); } } private void add_new_profile() { EditText editTextNewNick = (EditText)view.findViewById(R.id.editTextNewNick); EditText editTextNewPassword = (EditText)view.findViewById(R.id.editTextNewPassword); String add_nick = null; String add_password = null; if (editTextNewPassword.getVisibility() == View.VISIBLE) { add_nick = editTextNewNick.getText().toString(); add_password = editTextNewPassword.getText().toString(); if (add_nick.length() > 32) add_nick = add_nick.substring(0, 32); } else { add_nick = editTextNewNick.getText().toString(); add_nick = add_nick.replace("~",""); if (add_nick.length() > 31) add_nick = add_nick.substring(0, 31); add_nick = "~"+add_nick; } if (add_nick.length() <= 1) { Toast toast = Toast.makeText(context, getResources().getString(R.string.profile_length_too_small), Toast.LENGTH_SHORT); toast.show(); return; } Config current_config = new Config(context); if (!current_config.profileExists(add_nick)) { current_config.addProfile(add_nick, add_password); Toast toast = Toast.makeText(context, getResources().getString(R.string.successfully_added), Toast.LENGTH_SHORT); toast.show(); Intent profileListIntent = new Intent(context, ProfileActivity.class); profileListIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); profileListIntent.putExtra("tab", "1"); // profile list startActivity(profileListIntent); } else { Toast toast = Toast.makeText(context, getResources().getString(R.string.profile_already_exists), Toast.LENGTH_SHORT); toast.show(); } } } <file_sep>/* * Simple Chat Client * * Copyright (C) <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.models; import java.util.List; import java.util.Map; public class OnetNick { String avatar; List<String> channels; Map<String, String> channel_modes; Map<String, Integer> channel_max_modes; Character sex; public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public List<String> getChannels() { return channels; } public void setChannels(List<String> channels) { this.channels = channels; } public Map<String, String> getChannel_modes() { return channel_modes; } public void setChannel_modes(Map<String, String> channel_modes) { this.channel_modes = channel_modes; } public Map<String, Integer> getChannel_max_modes() { return channel_max_modes; } public void setChannel_max_modes(Map<String, Integer> channel_max_modes) { this.channel_max_modes = channel_max_modes; } public Character getSex() { return sex; } public void setSex(Character sex) { this.sex = sex; } } <file_sep>/* * Simple Chat Client * * Copyright (C) <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.onet; import android.util.Log; import com.core.Messages; import com.core.Network; import com.core.Settings; import com.models.Channels; import com.models.ChannelsFavourites; import com.models.ChannelsManager; import com.models.Nick; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class OnetKernel { private static final String TAG = "OnetKernel"; private String[] data; private static OnetKernel instance = new OnetKernel(); public static synchronized OnetKernel getInstance() { return instance; } public void parse(String message) { data = message.split(" "); if (data.length < 2) return; String data0 = data[0]; String data1 = data[1]; if (data0.equalsIgnoreCase("ping")) { raw_ping(); return; } else if (data0.equalsIgnoreCase("error")) { raw_error(); return; } else if (data1.equalsIgnoreCase("pong")) { raw_pong(); return; } else if (data1.equalsIgnoreCase("privmsg")) { raw_privmsg(); return; } else if (data1.equalsIgnoreCase("join")) { raw_join(); return; } else if (data1.equalsIgnoreCase("part")) { raw_part(); return; } else if (data1.equalsIgnoreCase("quit")) { raw_quit(); return; } else if (data1.equalsIgnoreCase("kick")) { raw_kick(); return; } else if (data1.equalsIgnoreCase("invite")) { raw_invite(); return; } else if (data1.equalsIgnoreCase("mode")) { raw_mode(); return; } if (data1.equalsIgnoreCase("001")) { raw_001(); return; } else if (data1.equalsIgnoreCase("341")) { raw_341(); return; } else if (data1.equalsIgnoreCase("353")) { raw_353(); return; } else if (data1.equalsIgnoreCase("433")) { raw_433(); return; } else if (data1.equalsIgnoreCase("801")) { raw_801(); return; } else if (data1.equalsIgnoreCase("817")) { raw_817(); return; } if (data.length >= 4) { String data3 = data[3]; if ((data1.equalsIgnoreCase("notice")) && (!data3.isEmpty())) { if ((data3.length() != 4) || (data3.equalsIgnoreCase(":***"))) { raw_notice(); } else { data3 = data3.substring(1); if (data3.length() == 3) { int int3 = Integer.parseInt(data3); if (int3 == 111) { raw_111n(); } else if (int3 == 141) { raw_141n(); } else if (int3 == 142) { raw_142n(); } else if (int3 == 256) { raw_256n(); } } } } } //Log.i(TAG, "Unknown RAW: "+message); } // PING :cf1f1.onet private void raw_ping() { String server = data[1]; Network.getInstance().send(String.format("PONG %s", server)); } // ERROR :Closing link ([email protected]) [Registration timeout] private void raw_error() { String message = ""; for (int i = 0; i < data.length; ++i) { if (i != 0) message += " "; message += data[i]; } if (message.startsWith(":")) message = message.substring(1); Messages.getInstance().showMessageAll(message, Messages.MessageType.INFO); //Network.getInstance().disconnect(); } // :cf1f4.onet PONG cf1f4.onet :1340185644095 private void raw_pong() { // TODO } // :[email protected] JOIN #Quiz :rx,0 private void raw_join() { String nick = data[0]; if (nick.startsWith(":")) nick = nick.substring(1); nick = nick.substring(0, nick.indexOf("!")); String channel = data[2]; String modes = ""; if (!data[3].isEmpty()) { String suffix = data[3]; if (suffix.startsWith(":")) suffix = suffix.substring(1); modes = suffix.substring(0, suffix.indexOf(",")); } if (nick.equalsIgnoreCase(Settings.getInstance().get("nick"))) { // add ChannelsManager.getInstance().add(channel); // info if (!channel.startsWith("^")) { Network.getInstance().send(String.format("CS INFO %s i", channel)); } } // show message String display = String.format("* %s wchodzi do pokoju %s", nick, channel); Messages.getInstance().showMessage(channel, display, Messages.MessageType.JOIN); // nick add Nick.getInstance().add(nick, channel, modes); } // :[email protected] PART #scc private void raw_part() { String nick = data[0]; if (nick.startsWith(":")) nick = nick.substring(1); nick = nick.substring(0, nick.indexOf("!")); String channel = data[2]; String reason = ""; for (int i = 3; i < data.length; ++i) { if (i != 3) reason += " "; reason += data[i]; } if (reason.startsWith(":")) reason = reason.substring(1); String display; if (reason.isEmpty()) display = String.format("* %s wychodzi z pokoju %s", nick, channel); else display = String.format("* %s wychodzi z pokoju %s [%s]", nick, channel, reason); Messages.getInstance().showMessage(channel, display, Messages.MessageType.PART); Nick.getInstance().remove(nick, channel); if (nick.equalsIgnoreCase(Settings.getInstance().get("nick"))) { ChannelsManager.getInstance().remove(channel); } } // :[email protected] QUIT :Client exited private void raw_quit() { String nick = data[0]; if (nick.startsWith(":")) nick = nick.substring(1); nick = nick.substring(0, nick.indexOf("!")); String reason = ""; for (int i = 2; i < data.length; ++i) { if (i != 2) reason += " "; reason += data[i]; } if (reason.startsWith(":")) reason = reason.substring(1); String display; if (reason.isEmpty()) display = String.format("* %s wychodzi z czata", nick); else display = String.format("* %s wychodzi z czata [%s]", nick, reason); Nick.getInstance().quit(nick, display); } // :[email protected] KICK #scc Moment_w_atmosferze :sio private void raw_kick() { String who = data[0]; if (who.startsWith(":")) who = who.substring(1); who = who.substring(0, who.indexOf("!")); String channel = data[2]; String nick = data[3]; String reason = ""; for (int i = 4; i < data.length; ++i) { if (i != 4) reason += " "; reason += data[i]; } if (reason.startsWith(":")) reason = reason.substring(1); Nick.getInstance().remove(nick, channel); String display; if (!nick.equalsIgnoreCase(Settings.getInstance().get("nick"))) { if (reason.isEmpty()) display = String.format("* %s zostaje wyrzucony z %s przez %s", nick, channel, who); else display = String.format("* %s zostaje wyrzucony z %s przez %s. Powód: %s", nick, channel, who, reason); Messages.getInstance().showMessage(channel, display, Messages.MessageType.KICK); } else { if (reason.isEmpty()) display = String.format("* Zostajesz wyrzucony z %s przez %s", channel, who); else display = String.format("* Zostajesz wyrzucony z %s przez %s. Powód: %s", channel, who, reason); Messages.getInstance().showMessage(channel, display, Messages.MessageType.KICK); Messages.getInstance().showMessage(Channels.STATUS, display, Messages.MessageType.KICK); ChannelsManager.getInstance().remove(channel); } } // :[email protected] PRIVMSG @#scc :hello // :[email protected] PRIVMSG %#scc :hello // :[email protected] PRIVMSG +#scc :hello // :[email protected] PRIVMSG #scc :hello // :[email protected] PRIVMSG ^scc_test :hello private void raw_privmsg() { String nick = data[0]; if (nick.startsWith(":")) nick = nick.substring(1); if (nick.contains("!")) nick = nick.substring(0, nick.indexOf("!")); String nickOrChannel = data[2]; String message = ""; for (int i = 3; i < data.length; ++i) { if (i != 3) message += " "; message += data[i]; } if (message.startsWith(":")) message = message.substring(1); String display = String.format("%s: %s", nick, message); // channel if (nickOrChannel.contains("#")) { String fullChannel = nickOrChannel; @SuppressWarnings("unused") String group = fullChannel.substring(fullChannel.indexOf("#")); String channel = fullChannel.substring(fullChannel.indexOf("#")); Messages.getInstance().showMessage(channel, display, Messages.MessageType.DEFAULT); } // priv else if (nickOrChannel.contains("^")) { String channel = nickOrChannel; Messages.getInstance().showMessage(channel, display, Messages.MessageType.DEFAULT); } // notice else { Messages.getInstance().showMessageActive(display, Messages.MessageType.NOTICE); } } // :Llanero!<EMAIL> NOTICE #channel :test // :cf1f2.onet NOTICE scc_test :Your message has been filtered and opers notified: spam #2480 // :Llanero!<EMAIL> NOTICE $* :458852 * * :%Fb%%C008100%Weź udział w Konkursie Mikołajkowym - skompletuj zaprzęg Świetego Mikołaja! Więcej info w Wieściach z Czata ! http://czat.onet.pl/1632594,wiesci.html // :Panie_kierowniku!<EMAIL> NOTICE Darom :458852 * * :bum // :Panie_kierowniku!<EMAIL> NOTICE Darom :458853 * * :bum // :Panie_kierowniku!<EMAIL> NOTICE Darom :458854 * * :bum // :<EMAIL>kierowniku!<EMAIL> NOTICE Darom :458855 * * :bum private void raw_notice() { String who = data[0]; if (who.startsWith(":")) who = who.substring(1); if (who.contains("!")) who = who.substring(0, who.indexOf("!")); String nickOrChannel = data[2]; String category = data[3]; if (category.startsWith(":")) category = category.substring(1); int iCategory = 0; try { iCategory = Integer.parseInt(category); } catch (NumberFormatException e) {} String message = ""; String categoryString = ""; switch (iCategory) { case Messages.NOTICE_INFO: //if (categoryString.isEmpty()) categoryString = getResources().getString(R.string.notice_information)+": "; case Messages.NOTICE_WARNING: //if (categoryString.isEmpty()) categoryString = tr("Warning")+": "; case Messages.NOTICE_ERROR: //if (categoryString.isEmpty()) categoryString = tr("Error")+": "; case Messages.NOTICE_QUESTION: //if (categoryString.isEmpty()) categoryString = tr("Question")+": "; for (int i = 6; i < data.length; ++i) { if (i != 6) message += " "; message += data[i]; } if (message.startsWith(":")) message = message.substring(1); break; default: for (int i = 3; i < data.length; ++i) { if (i != 3) message += " "; message += data[i]; } if (message.startsWith(":")) message = message.substring(1); break; } String display = String.format("-%s- %s%s", who, categoryString, message); Log.i(TAG, "notice display: "+display); // channel if (nickOrChannel.contains("#")) { String fullChannel = nickOrChannel; @SuppressWarnings("unused") String group = fullChannel.substring(fullChannel.indexOf("#")); String channel = fullChannel.substring(fullChannel.indexOf("#")); Messages.getInstance().showMessage(channel, display, Messages.MessageType.NOTICE); } // priv else if (nickOrChannel.contains("^")) { String channel = nickOrChannel; Messages.getInstance().showMessage(channel, display, Messages.MessageType.NOTICE); } // notice else { Messages.getInstance().showMessageActive(display, Messages.MessageType.NOTICE); } } // :[email protected] INVITE scc_test :^cf1f41437962 // :Merovingian!<EMAIL> INVITE scc_test :#Komputery private void raw_invite() { String nick = data[0]; if (nick.startsWith(":")) nick = nick.substring(1); if (nick.contains("!")) nick = nick.substring(0, nick.indexOf("!")); String channel = data[3]; if (channel.startsWith(":")) channel = channel.substring(1); if (channel.startsWith("^")) { Channels.getInstance().setAlternativeName(channel, nick); } // invite flash/message (?) } // :Merovingian!<EMAIL> MODE Merovingian :+b // :[email protected] MODE Merovingian :+b // :[email protected] MODE ankaszo -W // :ChanServ!<EMAIL> MODE #glupia_nazwa +k bum // :ChanServ!<EMAIL> MODE #bzzzz -l // :NickServ!<EMAIL> MODE scc_test +r // :ChanServ!<EMAIL> MODE #scc +ips // :ChanServ!<EMAIL> MODE #scc +o scc_test // :ChanServ!<EMAIL> MODE #scc +eo *!51976824@* scc_test // :ChanServ!<EMAIL> MODE #abc123 +il-e 1 *!51976824@* private void raw_mode() { String who = data[0]; if (who.startsWith(":")) who = who.substring(1); if (who.contains("!")) who = who.substring(0, who.indexOf("!")); String nickOrChannel = data[2]; if ((nickOrChannel.startsWith("#")) || (nickOrChannel.startsWith("^"))) { String channel = nickOrChannel; String flags = data[3]; Map<String, String> flag_value = new HashMap<>(); String mode3 = "GQLDMRVimnprstu"; String plusminus = ""; int index = 4; for (int i = 0; i < flags.length(); i++) { String f = Character.toString(flags.charAt(i)); if ((f.equalsIgnoreCase("+")) || (f.equalsIgnoreCase("-"))) { if (f.equalsIgnoreCase("+")) plusminus = f; else if (f.equalsIgnoreCase("-")) plusminus = f; } else { String flag = plusminus+f; if (mode3.contains("f")) { flag_value.put(flag, ""); } else { if (index < data.length) { flag_value.put(flag, data[index]); index++; } else flag_value.put(flag, ""); } } } for (Map.Entry<String, String> entry : flag_value.entrySet()) { String flag = entry.getKey(); String value = entry.getValue(); String display = ""; boolean nick_flag = false; if (flag.equals("+q")) { display = String.format("* %s jest teraz właścicielem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("-q")) { display = String.format("* %s nie jest już właścicielem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("+o")) { display = String.format("* %s jest teraz super operatorem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("-o")) { display = String.format("* %s nie jest już super operatorem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("+h")) { display = String.format("* %s jest teraz operatorem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("-h")) { display = String.format("* %s nie jest już operatorem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("+v")) { display = String.format("* %s jest teraz gościem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("-v")) { display = String.format("* %s nie jest już gościem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("+X")) { display = String.format("* %s jest teraz moderatorem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("-X")) { display = String.format("* %s nie jest już moderatorem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("+Y")) { display = String.format("* %s jest teraz screenerem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("-Y")) { display = String.format("* %s nie jest już screenerem pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("+b")) { display = String.format("* %s jest teraz na liście wyproszonych w %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("-b")) { display = String.format("* %s nie jest już na liście wyproszonych w %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("+I")) { display = String.format("* %s jest teraz na liście zaproszonych w %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("-I")) { display = String.format("* %s nie jest już na liście zaproszonych w %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("+e")) { display = String.format("* %s posiada teraz wyjątek od bana w pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("-e")) { display = String.format("* %s nie posiada już wyjątku od bana w pokoju %s (Ustawił %s)", value, channel, who); nick_flag = true; } else if (flag.equals("+k")) display = String.format("* Pokój %s ma teraz ustawiony klucz %s (Ustawił %s)", channel, value, who); else if (flag.equals("-k")) display = String.format("* Pokój %s nie ma już ustawionego klucza (Ustawił %s)", channel, who); else if (flag.equals("+n")) display = String.format("* Pokój %s nie będzie teraz otrzymywać zewnętrznych wiadomości wysyłanych do pokoju (Ustawił %s)", channel, who); else if (flag.equals("-n")) display = String.format("* Pokój %s będzie mógł teraz otrzymywać zewnętrzne wiadomości wysyłane do pokoju (Ustawił %s)", channel, who); else if (flag.equals("+t")) display = String.format("* Tylko operatorzy będą mogli teraz zmieniać temat w pokoju %s (Ustawił %s)", channel, who); else if (flag.equals("-t")) display = String.format("* Każdy będzie mógł teraz zmienić temat w pokoju %s (Ustawił %s)", channel, who); else if (flag.equals("+i")) display = String.format("* Pokój %s jest teraz pokojem ukrytym (Ustawił %s)", channel, who); else if (flag.equals("-i")) display = String.format("* Pokój %s nie jest już pokojem ukrytym (Ustawił %s)", channel, who); else if (flag.equals("+p")) display = String.format("* Pokój %s jest teraz pokojem prywatnym (Ustawił %s)", channel, who); else if (flag.equals("-p")) display = String.format("* Pokój %s nie jest już pokojem prywatnym (Ustawił %s)", channel, who); else if (flag.equals("+s")) display = String.format("* Pokój %s jest teraz pokojem sekretnym (Ustawił %s)", channel, who); else if (flag.equals("-s")) display = String.format("* Pokój %s nie jest już pokojem sekretnym (Ustawił %s)", channel, who); else if (flag.equals("+m")) display = String.format("* Pokój %s jest teraz pokojem moderowanym (Ustawił %s)", channel, who); else if (flag.equals("-m")) display = String.format("* Pokój %s nie jest już pokojem moderowanym (Ustawił %s)", channel, who); else if (flag.equals("+u")) display = String.format("* Pokój %s jest teraz pokojem audytywnym (Ustawił %s)", channel, who); else if (flag.equals("-u")) display = String.format("* Pokój %s nie jest już pokojem audytywnym (Ustawił %s)", channel, who); else if (flag.equals("+l")) display = String.format("* Pokój %s ma teraz ustawiony limit użytkowników na %s (Ustawił %s)", channel, value, who); else if (flag.equals("-l")) display = String.format("* Pokój %s nie ma już ustawionego limitu użytkowników (Ustawił %s)", channel, who); else if (flag.equals("+G")) display = String.format("* Pokój %s ma teraz włączoną cenzure słów (Ustawił %s)", channel, who); else if (flag.equals("-G")) display = String.format("* Pokój %s nie ma już włączonej cenzury słów (Ustawił %s)", channel, who); else if (flag.equals("+Q")) display = String.format("* Pokój %s ma teraz włączoną blokade wyrzucania użytkowników (Ustawił %s)", channel, who); else if (flag.equals("-Q")) display = String.format("* Pokój %s nie ma już włączonej blokady wyrzucania użytkowników (Ustawił %s)", channel, who); else if (flag.equals("+V")) display = String.format("* Pokój %s posiada teraz blokade wysyłania zaproszeń przez 1 godzinę (Ustawił %s)", channel, who); else if (flag.equals("-V")) display = String.format("* Pokój %s nie posiada już blokady wysyłania zaproszeń (Ustawił %s)", channel, who); else if (flag.equals("+L")) display = String.format("* Pokój %s ma teraz ustawione przekierowanie do innego pokoju gdy zostanie przekroczona ilość użytkowników w %s (Ustawił %s)", channel, value, who); else if (flag.equals("-L")) display = String.format("* Pokój %s nie ma już ustawionego przekierowania do innego pokoju gdy zostanie przekroczona ilość użytkowników (Ustawił %s)", channel, who); else if (flag.equals("+J")) display = String.format("* Pokój %s posiada teraz blokade uniemożliwiającą użytkownikom automatyczny powrót do pokoju kiedy zostaną wyrzuceni. Limit wynosi %s sec. (Ustawił %s)", channel, value, who); else if (flag.equals("-J")) display = String.format("* Pokój %s nie posiada już blokady uniemożliwiającej użytkownikom na automatyczny powrót do pokoju kiedy zostaną wyrzuceni (Ustawił %s)", channel, who); else if (flag.equals("+D")) display = String.format("* Pokój %s jest teraz pokojem chronionym (Ustawił %s)", channel, who); else if (flag.equals("-D")) display = String.format("* Pokój %s nie jest już pokojem chronionym (Ustawił %s)", channel, who); else if (flag.charAt(1) == 'F') { String status; if (Integer.parseInt(value) == 0) status = "Dziki"; else if (Integer.parseInt(value) == 1) status = "Oswojony"; else if (Integer.parseInt(value) == 2) status = "Z klasą"; else if (Integer.parseInt(value) == 3) status = "Kultowy"; else status = "nieznany"; if (flag.charAt(0) == '+') display = String.format("* Pokój %s ma teraz status %s (Ustawił %s)", channel, status, who); else if (flag.charAt(0) == '-') display = String.format("* %s zmienił/a status pokoju %s", who, channel); } else if (flag.charAt(1) == 'c') { String category; if (Integer.parseInt(value) == 1) category = "Teen"; else if (Integer.parseInt(value) == 2) category = "Towarzyskie"; else if (Integer.parseInt(value) == 3) category = "Erotyczne"; else if (Integer.parseInt(value) == 4) category = "Tematyczne"; else if (Integer.parseInt(value) == 5) category = "Regionalne"; else category = "nieznany"; if (flag.charAt(0) == '+') display = String.format("* Pokój %s należy teraz do kategorii %s (Ustawił %s)", channel, category, who); else if (flag.charAt(0) == '-') display = String.format("* %s zmienił/a kategorie pokoju %s", who, channel); } else { if (value.isEmpty()) display = String.format("* Pokój %s ma teraz flage %s (Ustawił %s)", channel, flag, who); else { display = String.format("* %s ma teraz flage %s (Ustawił %s)", value, flag, who); nick_flag = true; } } if (!display.isEmpty()) Messages.getInstance().showMessage(channel, display, Messages.MessageType.MODE); if ((nick_flag) && (!flag.isEmpty())) Nick.getInstance().changeFlag(value, channel, flag); } flag_value.clear(); } else { String nick = nickOrChannel; String flag = data[3]; if (flag.startsWith(":")) flag = flag.substring(1); // get +- String plusminus = Character.toString(flag.charAt(0)); // fix flag flag = flag.substring(1); String[] flags = flag.split(""); for (String f : flags) { flag = plusminus+f; String display; switch (flag) { case "+O": display = String.format("* %s jest oznaczony jako administrator czata", nick); break; case "-O": display = String.format("* %s nie jest już oznaczony jako administrator czata", nick); break; case "+b": display = String.format("* %s jest oznaczony jako zajęty", nick); break; case "-b": display = String.format("* %s nie jest już oznaczony jako zajęty", nick); break; case "+W": display = String.format("* %s ma teraz włączoną kamerke publiczną", nick); break; case "-W": display = String.format("* %s ma teraz wyłączoną kamerke publiczną", nick); break; case "+V": display = String.format("* %s ma teraz włączoną kamerke prywatną", nick); break; case "-V": display = String.format("* %s ma teraz wyłączoną kamerke prywatną", nick); break; case "+x": display = String.format("* %s ma teraz szyfrowane IP", nick); break; case "-x": display = String.format("* %s nie ma już szyfrowanego IP", nick); break; case "+r": display = String.format("* %s jest oznaczony jako zarejestrowany", nick); break; case "-r": display = String.format("* %s nie jest już oznaczony jako zarejestrowany", nick); break; default: display = String.format("* %s ma teraz flage %s", nick, flag); break; } if ((flag.contains("r")) || (flag.contains("x"))) Messages.getInstance().showMessage(Channels.STATUS, display, Messages.MessageType.MODE); if (!flag.isEmpty()) Nick.getInstance().changeFlag(nick, flag); // registered nick if ((nick.equalsIgnoreCase(Settings.getInstance().get("nick"))) && (flag.equalsIgnoreCase("+r"))) { // channel homes Network.getInstance().send("CS HOMES"); // get my stats Network.getInstance().send(String.format("RS INFO %s", nick)); } } } } // :cf1f4.onet 001 scc_test :Welcome to the OnetCzat IRC Network [email protected] private void raw_001() { Settings.getInstance().set("ignore_favourites", "false"); ChannelsFavourites.getInstance().clear(); Nick.getInstance().clear(); // protocol Network.getInstance().send("PROTOCTL ONETNAMESX"); // channels list Network.getInstance().send("SLIST R- 0 0 100 null"); } // NS INFO aleksa7 // :NickServ!<EMAIL> NOTICE Merovingian :111 aleksa7 type :2 private void raw_111n() { String nick = data[4]; String key = data[5]; String value = ""; for (int i = 6; i < data.length; ++i) { if (i != 6) value += " "; value += data[i]; } if (value.startsWith(":")) value = value.substring(1); if (key.equals("avatar")) { Nick.getInstance().setAvatar(nick, value); } } // NS FAVOURITES // :NickServ!<EMAIL> NOTICE scc_test :141 :#Scrabble #Quiz #scc private void raw_141n() { for (int i = 4; i < data.length; ++i) { String channel = data[i]; if (channel.startsWith(":")) channel = channel.substring(1); Log.i(TAG, "favourites adding: "+channel); ChannelsFavourites.getInstance().add(channel); } } // NS FAVOURITES // :NickServ!<EMAIL> NOTICE scc_test :142 :end of favourites list private void raw_142n() { if (Settings.getInstance().get("ignore_favourites").equalsIgnoreCase("false")) { Settings.getInstance().set("ignore_favourites", "true"); List<String> channels = ChannelsFavourites.getInstance().get(); java.util.Collections.sort(channels, String.CASE_INSENSITIVE_ORDER); String massJoin = ""; for (String channel : channels) { if (massJoin.isEmpty()) massJoin += channel; else massJoin += ","+channel; } Log.i(TAG, "mass join: "+massJoin); if (!massJoin.isEmpty()) Network.getInstance().send(String.format("JOIN %s", massJoin)); } } // CS HOMES // :ChanServ!<EMAIL> NOTICE scc_test :151 :h#scc // NS OFFLINE // :NickServ!<EMAIL> NOTICE Merovingian :151 :jubee_blue private void raw_151n() { String nick = data[0]; if (nick.startsWith(":")) nick = nick.substring(1); if (nick.contains("!")) nick = nick.substring(0, nick.indexOf("!")); if (nick.equalsIgnoreCase("chanserv")) { // TODO } else if (nick.equalsIgnoreCase("nickserv")) { // TODO } } // CS HOMES // :ChanServ!<EMAIL> NOTICE scc_test :152 :end of homes list // NS OFFLINE // :NickServ!<EMAIL> NOTICE Merovingian :152 :end of offline senders list private void raw_152n() { // TODO } // :ChanServ!<EMAIL> NOTICE #scc :256 Merovingian +o scc_test :channel privilege changed private void raw_256n() { String channel = data[2]; String who = data[4]; String flag = data[5]; String nick = data[6]; String display = ""; if (flag.equals("+q")) display = String.format("* %s jest teraz właścicielem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("-q")) display = String.format("* %s nie jest już właścicielem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("+o")) display = String.format("* %s jest teraz super operatorem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("-o")) display = String.format("* %s nie jest już super operatorem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("+h")) display = String.format("* %s jest teraz operatorem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("-h")) display = String.format("* %s nie jest już operatorem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("+v")) display = String.format("* %s jest teraz gościem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("-v")) display = String.format("* %s nie jest już gościem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("+X")) display = String.format("* %s jest teraz moderatorem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("-X")) display = String.format("* %s nie jest już moderatorem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("+Y")) display = String.format("* %s jest teraz screenerem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("-Y")) display = String.format("* %s nie jest już screenerem pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("+b")) display = String.format("* %s jest teraz na liście wyproszonych w %s (Ustawił %s)", nick, channel, who); else if (flag.equals("-b")) display = String.format("* %s nie jest już na liście wyproszonych w %s (Ustawił %s)", nick, channel, who); else if (flag.equals("+I")) display = String.format("* %s jest teraz na liście zaproszonych w %s (Ustawił %s)", nick, channel, who); else if (flag.equals("-I")) display = String.format("* %s nie jest już na liście zaproszonych w %s (Ustawił %s)", nick, channel, who); else if (flag.equals("+e")) display = String.format("* %s posiada teraz wyjątek od bana w pokoju %s (Ustawił %s)", nick, channel, who); else if (flag.equals("-e")) display = String.format("* %s nie posiada już wyjątku od bana w pokoju %s (Ustawił %s)", nick, channel, who); else display = String.format("* %s ma teraz flage %s (Ustawił %s)", nick, flag, who); // display Messages.getInstance().showMessage(channel, display, Messages.MessageType.MODE); } // :cf1f4.onet 341 Merovingian ~test34534 #Scrabble // :cf1f1.onet 341 scc_test Merovingian ^cf1f1162848 private void raw_341() { String nick = data[3]; String channel = data[4]; if (channel.startsWith("^")) { Channels.getInstance().setAlternativeName(channel, nick); // TODO rename channel } } // NAMES // :cf1f1.onet 353 scc_test = #scc :scc_test|rx,0 `@Merovingian|brx,1 @chanky|rx,1 // :cf1f3.onet 353 Merovingian = #hack :%Hacker %weed %cvf @Majkel SzperaCZ_11 Merovingian `ChanServ %but private void raw_353() { String channel = data[4]; for (int i = 5; i < data.length; ++i) { String nick = data[i]; if (nick.startsWith(":")) nick = nick.substring(1); nick = nick.substring(0, nick.indexOf("|")); String suffix = data[i]; if (suffix.contains("|")) { suffix = suffix.substring(suffix.indexOf("|")+1, suffix.length()-2); } else suffix = ""; String clean_nick = nick; String prefix = ""; if (clean_nick.contains(Nick.FLAG_OWNER)) { clean_nick = clean_nick.replace(Nick.FLAG_OWNER, ""); prefix += Nick.FLAG_OWNER; } if (clean_nick.contains(Nick.FLAG_OP)) { clean_nick = clean_nick.replace(Nick.FLAG_OP, ""); prefix += Nick.FLAG_OP; } if (clean_nick.contains(Nick.FLAG_HALFOP)) { clean_nick = clean_nick.replace(Nick.FLAG_HALFOP, ""); prefix += Nick.FLAG_HALFOP; } if (clean_nick.contains(Nick.FLAG_MOD)) { clean_nick = clean_nick.replace(Nick.FLAG_MOD, ""); prefix += Nick.FLAG_MOD; } if (clean_nick.contains(Nick.FLAG_SCREENER)) { clean_nick = clean_nick.replace(Nick.FLAG_SCREENER, ""); prefix += Nick.FLAG_SCREENER; } if (clean_nick.contains(Nick.FLAG_VOICE)) { clean_nick = clean_nick.replace(Nick.FLAG_VOICE, ""); prefix += Nick.FLAG_VOICE; } String modes = prefix+suffix; Nick.getInstance().add(clean_nick, channel, modes); if ((!clean_nick.startsWith("~")) && (!suffix.contains(Nick.FLAG_BOT)) && (Nick.getInstance().get(clean_nick).getAvatar().isEmpty())) { Network.getInstance().send(String.format("NS INFO %s s", clean_nick)); } } } // :cf1f1.onet 433 * scc_test :Nickname is already in use. private void raw_433() { String nick = data[3]; Network.getInstance().disconnect(); String display = String.format("* Nickname %s is already in use.", nick); Messages.getInstance().showMessageAll(display, Messages.MessageType.ERROR); Network.getInstance().connect(); } // :cf1f3.onet 801 scc_test :q5VMy1wl6hKL5ZUt // :cf1f2.onet 801 384-unknown :mIGlbZP0R056xedZ private void raw_801() { String key = data[3]; if (key.startsWith(":")) key = key.substring(1); String auth = OnetUtils.transform(key); String nick = Settings.getInstance().get("uo_nick"); String UOKey = Settings.getInstance().get("uo_key"); if (Network.getInstance().isConnected()) { Network.getInstance().send(String.format("NICK %s", nick)); Network.getInstance().send(String.format("AUTHKEY %s", auth)); Network.getInstance().send(String.format("USER * %s czat-app.onet.pl :%s", UOKey, nick)); } } // :cf1f2.onet 817 scc_test #scc 1253216797 mikefear - :%Fb:arial%%Ce40f0f%re private void raw_817() { String channel = data[3]; long time = Long.parseLong(data[4]); Date date = new Date(time*1000L); // *1000 is to convert seconds to milliseconds SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); String formattedDate = sdf.format(date); String nick = data[5]; String message = ""; for (int i = 7; i < data.length; ++i) { if (i != 7) message += " "; message += data[i]; } if (message.startsWith(":")) message = message.substring(1); String display = String.format("%s: %s", nick, message); Messages.getInstance().showMessage(channel, display, Messages.MessageType.DEFAULT); } } <file_sep>include ':SimpleChatClient'
0a2d18aa3a464543712c9be4c73ad1aa0962bf7f
[ "Markdown", "Java", "Gradle" ]
13
Markdown
simplechatclient/simplechatclient-android
0eb530dc1cfbd8294f9caf3cae1a61a14094c064
6e1166d68a5267ebbe0d31266ca91c23e8ba2c4b
refs/heads/master
<file_sep>import { withRouter } from 'next/router'; import Layout from "../components/Layout"; const Post = ({ router }) => ( <Layout title={router.query.title}> <p style={{ width: "80vw"}}> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Itaque quae, dicta ipsum natus explicabo nemo quos eligendi culpa consequuntur aperiam blanditiis a, molestiae necessitatibus harum, optio doloribus id nostrum quidem. </p> </Layout> ); export default withRouter(Post);
cbc76dce11762d4ad0e375f0ab55a4aa8a950bf1
[ "JavaScript" ]
1
JavaScript
landon-sturgeon/next-js
dd0837651cbc8717cc4ffd04987d1291265b1219
bc55ade791b97eda0955bd5a9d25c5d227bcb9e5
refs/heads/master
<file_sep>/* feedreader.js * * This is the spec file that Jasmine will read and contains * all of the tests that will be run against your application. */ /* We're placing all of our tests within the $() function, * since some of these tests may require DOM elements. We want * to ensure they don't run until the DOM is ready. */ $(function() { /* This is our first test suite - a test suite just contains * a related set of tests. This suite is all about the RSS * feeds definitions, the allFeeds variable in our application. */ describe('RSS Feeds', function() { /* This is our first test - it tests to make sure that the * allFeeds variable has been defined and that it is not * empty. Experiment with this before you get started on * the rest of this project. What happens when you change * allFeeds in app.js to be an empty array and refresh the * page? */ it('are defined', function() { expect(allFeeds).toBeDefined(); expect(allFeeds.length).not.toBe(0); }); // This test is looping through each feed and making sure it has a valid URL and value it('has a URL for every Feed', function(){ allFeeds.forEach(function (e){ expect(e.url).toBeDefined(); expect(e.url.length).toBeGreaterThan(0); }) }); // This test loops through each feed and makes sure it has a valid NAME and value it('has a Name for every Feed', function(){ allFeeds.forEach(function (e){ expect(e.name).toBeDefined(); expect(e.name.length).toBeGreaterThan(0); }) }); }); // This test suite tests the menu icon describe('The Menu',function(){ var thisBody= document.querySelector('body'); // This test checks for the precense of the menu element and that it is hidden it('should be hidden by default', function(){ expect(thisBody).toHaveClass('menu-hidden'); }); // This test checks that the functionality of the menu allows it to work properly. it('should toggle visibility when clicked on', function(){ var menuIcon = $('.menu-icon-link'); menuIcon.click(); expect(thisBody).not.toHaveClass('menu-hidden'); menuIcon.click(); expect(thisBody).toHaveClass('menu-hidden'); }); }); // This suite tests the initial feed entries describe('Initial Entries', function(){ // beforeEach running loadFeed beforeEach(function(done){ loadFeed(0,function(){ done(); }); }); // verifies that there's an entry after loadFeed is run. it('should populate an element entry',function(){ var myFeed = document.querySelector('.feed .entry'); expect(myFeed).toBeTruthy(); }); }); // This suite tests the selection of a new feed. describe('New Feed Selection', function(){ var firstFeed; var secondFeed; // before Each running loadFeed twice, each time grabbing the href attribute from the first item in the feed. beforeEach(function(done){ loadFeed(0,function(){ firstFeed = document.querySelector('.feed').getAttribute('href'); loadFeed(1,function(){ secondFeed = document.querySelector('.feed').getAttribute('href'); done() }); }); }); // tests whether firstFeed and secondFeed have different content. it('should populate feeds one after another',function(){ expect(firstFeed === secondFeed).toBeFalsy(); }); }) }());
bc6bef0e46b7d19b3ae16bda65dff4246ecd4326
[ "JavaScript" ]
1
JavaScript
Tuxhedoh/frontend-nanodegree-feedreader
dbebdf0dac302f283c42d21f2aca4177338947f8
a85df4ed36aa138ec98f388bb613afc8dc730ff8
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; import { Http, Headers, Response, RequestOptions } from '@angular/http'; @Injectable() export class AccountService { account: {}; constructor(private http: Http) { } getAccount(){ let headers = new Headers(); headers.append('X-XFERS-USER-API-KEY', '<KEY>'); let opts = new RequestOptions(); opts.headers = headers; let apiUrl: string = 'https://sandbox-id.xfers.com/api/v3/user'; return this.http .get(apiUrl, opts) .subscribe(data => { this.account = data.json(); console.log('inside service', this.account); }); } } <file_sep>import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; import { Http, Headers, Response, RequestOptions } from '@angular/http'; @Component({ selector: 'app-transfer', templateUrl: './transfer.component.html', styleUrls: ['./transfer.component.css'], encapsulation: ViewEncapsulation.None }) export class TransferComponent implements OnInit { transfer: any; transferLists: any; getTransfer(){ let headers = new Headers(); headers.append('X-XFERS-USER-API-KEY', '<KEY>'); let opts = new RequestOptions(); opts.headers = headers; let apiUrl: string = 'https://sandbox-id.xfers.com/api/v3/user/transfer_info?disable_va=false'; return this.request .get(apiUrl, opts) .subscribe(data => { this.transfer= data.json(); this.transferLists = this.transfer.transfer_info_array }); } constructor(private http: HttpClient, private request: Http) {} ngOnInit() { this.getTransfer(); } } <file_sep>import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; import { Http, Headers, Response, RequestOptions } from '@angular/http'; // import { AccountService } from '../account.service'; @Component({ selector: 'app-account', templateUrl: './account.component.html', styleUrls: ['./account.component.css'], encapsulation: ViewEncapsulation.None }) export class AccountComponent implements OnInit { account: any; constructor(private http: HttpClient, private request: Http) {} getAccount(){ let headers = new Headers(); headers.append('X-XFERS-USER-API-KEY', '<KEY>'); let opts = new RequestOptions(); opts.headers = headers; let apiUrl: string = 'https://sandbox-id.xfers.com/api/v3/user'; return this.request .get(apiUrl, opts) .subscribe(data => { this.account = data.json(); }); } ngOnInit() { this.getAccount(); } }
38d3723b028df47bad3056dc23220116c658b114
[ "TypeScript" ]
3
TypeScript
prasaria/xfers-api-webapp
e9cd09867f42d81f95decfed211899f51c327352
a67120f69a68808a9898c556fc43e03c25648074
refs/heads/master
<repo_name>victor-whong/fa<file_sep>/fa-base/src/main/java/com/yidu/bond/paging/BondTradePaging.java package com.yidu.bond.paging; /** * 类的描述:债券交易数据搜索分页字段 * * @author wh * @since 2020/9/6 13:02 */ public class BondTradePaging { /** * 债券交易编号 */ private String bondTradeNo; /** * 基金名称 */ private String fundName; /** * 债券名称 */ private String bondName; /** * 基金经理 */ private String managerName; /** * 券商名 */ private String brokerName; /** * 交易状态 已结算1 未结算 2 */ private String tradeStatus; /** * 页码 */ private int page; /** * 每页条数 */ private int limit; public String getBondTradeNo() { return bondTradeNo; } public void setBondTradeNo(String bondTradeNo) { this.bondTradeNo = bondTradeNo; } public String getFundName() { return fundName; } public void setFundName(String fundName) { this.fundName = fundName; } public String getBondName() { return bondName; } public void setBondName(String bondName) { this.bondName = bondName; } public String getManagerName() { return managerName; } public void setManagerName(String managerName) { this.managerName = managerName; } public String getBrokerName() { return brokerName; } public void setBrokerName(String brokerName) { this.brokerName = brokerName; } public String getTradeStatus() { return tradeStatus; } public void setTradeStatus(String tradeStatus) { this.tradeStatus = tradeStatus; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } } <file_sep>/fa-base/src/main/java/com/yidu/fund/domain/FundTrade.java package com.yidu.fund.domain; import com.yidu.utils.DateUtils; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; /** * 类的描述:基金交易POJO * @author 李昊林 * @date 2020-09-08 */ public class FundTrade implements Serializable{ private static final long serialVersionUID = 1690506313736029235L; /** * 基金交易Id */ private String fundTradeId; /** * 基金交易编号,交易编号:ZJJY-yyyy-MM-dd-xxxxx */ private String fundTradeNo; /** * 基金Id,参考基金表 */ private String fundId; /** * 基金代码 */ private String fundNo; /** * 基金名 */ private String fundName; /** * 基金交易类型,1:申购、2:认购、3:赎回 */ private String fundTradeType; /** * 账户ID,参考账户表,基金对应的托管账户 */ private String accountId; /** * 账号 */ private String accountNo; /** * 账户名 */ private String accountName; /** * 交易标识,1.流入(申购、认购资金流入到基金账户)、2.流出(赎回时资金从基金账户流出) */ private BigInteger tradeFlag; /** * 交易价格 */ private BigDecimal tradePrice; /** * 交易时间 */ @DateTimeFormat(pattern = "yyyy-MM-dd") private Date tradeDate; /** * 格式化交易时间 */ private String tradeDateStr; /** * 交易数量,单位:份 */ private BigInteger share; /** * 交易额(总),交易额 = 交易价*交易数量(份额) */ private BigDecimal turnover; /** * 费用,申购|赎回|认购费 */ private BigDecimal fee; /** * 总金额,交易额+各种税费 */ private BigDecimal total; /** * 交易状态,交易状态 已结算1 未结算 0 */ private BigInteger tradeStatus; public FundTrade() { } public String getFundTradeId() { return fundTradeId; } public void setFundTradeId(String fundTradeId) { this.fundTradeId = fundTradeId; } public String getFundTradeNo() { return fundTradeNo; } public void setFundTradeNo(String fundTradeNo) { this.fundTradeNo = fundTradeNo; } public String getFundId() { return fundId; } public void setFundId(String fundId) { this.fundId = fundId; } public String getFundNo() { return fundNo; } public void setFundNo(String fundNo) { this.fundNo = fundNo; } public String getFundName() { return fundName; } public void setFundName(String fundName) { this.fundName = fundName; } public String getFundTradeType() { return fundTradeType; } public void setFundTradeType(String fundTradeType) { this.fundTradeType = fundTradeType; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public BigInteger getTradeFlag() { return tradeFlag; } public void setTradeFlag(BigInteger tradeFlag) { this.tradeFlag = tradeFlag; } public BigDecimal getTradePrice() { return tradePrice; } public void setTradePrice(BigDecimal tradePrice) { this.tradePrice = tradePrice; } public Date getTradeDate() { return tradeDate; } public void setTradeDate(Date tradeDate) { this.tradeDate = tradeDate; this.tradeDateStr = DateUtils.dataToString(tradeDate,"yyyy-MM-dd"); } public BigInteger getShare() { return share; } public void setShare(BigInteger share) { this.share = share; } public BigDecimal getTurnover() { return turnover; } public void setTurnover(BigDecimal turnover) { this.turnover = turnover; } public BigDecimal getFee() { return fee; } public void setFee(BigDecimal fee) { this.fee = fee; } public BigDecimal getTotal() { return total; } public void setTotal(BigDecimal total) { this.total = total; } public BigInteger getTradeStatus() { return tradeStatus; } public void setTradeStatus(BigInteger tradeStatus) { this.tradeStatus = tradeStatus; } public String getTradeDateStr() { return tradeDateStr; } @Override public String toString() { return "FundTrade{" + "fundTradeId='" + fundTradeId + '\'' + ",fundTradeNo='" + fundTradeNo + '\'' + ",fundId='" + fundId + '\'' + ",fundNo='" + fundNo + '\'' + ",fundName='" + fundName + '\'' + ",fundTradeType='" + fundTradeType + '\'' + ",accountId='" + accountId + '\'' + ",accountNo='" + accountNo + '\'' + ",accountName='" + accountName + '\'' + ",tradeFlag='" + tradeFlag + '\'' + ",tradePrice='" + tradePrice + '\'' + ",tradeDate='" + tradeDate + '\'' + ",share='" + share + '\'' + ",turnover='" + turnover + '\'' + ",fee='" + fee + '\'' + ",total='" + total + '\'' + ",tradeStatus='" + tradeStatus + '\'' + '}'; } } <file_sep>/fa-web/src/main/webapp/static/fund/js/cashInterest.js $(function(){ /* * layui引入样式的两种方式:模块化用和全模块用法 * layui的初始化模块可以理解为,引入这个模块的js文件 * 值得注意的是:layui的模块之间存在依赖关系,例如引入了table模块,它会layui/lay/moudules/table.js * 这个文件引入进来,并且它还会将这个模块所依赖的其他模块自动加入进来, * 实际引入的模块有:table、form、jquery、layer、laypage、laytpl、util,7个js文件 * 所以我仅仅初始化了table模块,却能获得form、jquery、layer的模块对象 */ //layui初始化表格模组 layui.use(['table', 'laydate', 'upload','element'], function() { // 获得模块对象 var table = layui.table; var form = layui.form; var $ = layui.jquery; var layer = layui.layer; var laydate = layui.laydate; var upload = layui.upload; var element = layui.element; //----1.基金交易数据表格渲染------------------------------------------------------------------ table.render({ elem: '#cashInterestTable', url: '../calcRevenue/cashInventoryList', //后期改回获取用户列表的后端程序的url method: 'post', height: 'full-50', where: {}, // 你额外要携带数据,以键值对的方式存入 toolbar: '#cashInterestToolbar', // 开启头部工具栏,并为其绑定左侧模板 page: true, // 开启分页 limit: 10, // 每页显示的条数 limits: [5,10, 20, 50, 100], // 每页条数的选择项 loading: true, // 是否显示加载条(切换分页的时候显示) title: '现金计息表', // 定义 table 的大标题(在文件导出等地方会用到) id: 'cashInterestTable', // 设定容器唯一 id defaultToolbar: [{ title: '搜索' ,layEvent: 'LAYTABLE_SEARCH' ,icon: 'layui-icon-search' },'filter', 'exports', 'print' ], // 隔行变色 even: false, cols: [ [{ title:'序列', type: 'numbers' }, // 序号 { type: 'checkbox' }, //复选框 { field:'cashInventoryId', title:'现金库存Id', hide: true, //一般情况下不显示ID align:'center', width: 200 }, { field: 'cashInventoryNo', title: '现金库存编号', // fixed:'left', //钉在左侧 align: "center", width: 260 }, { field: 'fundId', title: '基金Id', hide: true, align: "center", width: 100 }, { field: 'fundNo', title: '基金代码', sort: true, align: "center", width: 160 }, { field: 'fundName', title: '基金名称', sort: true, align: "center", width: 200 }, { field: 'accountId', title: '账户Id', sort: true, hide: true, align: "center", width: 130 }, { field: 'accountNo', title: '账号', sort: true, align: "center", width: 180 }, { field: 'accountName', title: '账户名', align: "center", width: 190 }, { field: 'cashBalance', title: '现金余额', align: "center", sort: true, width: 130 }, { field: 'statisticalDateStr', title: '统计日期', align: "center", sort:true, width: 130 }, { field: 'description', title: '描述', align: "center", hide: true, width: 150 } ] ] }); //----1.基金交易数据表格渲染------------------------------------------------------------------ //----2.头部搜索栏基金交易日期时间选择器-------------------------------------------------------------------- //----3.处理表行修改------------------------------------------------------------------ // table.on("tool(fundTableEvent)",function (obj) { // var data = obj.data; // console.log(data); // if (obj.event == "update"){ // initUpdatefundModal(data); // } // }); var ltips=layer.tips("为你定制的搜索^_^","[title='搜索']",{tips:[2,'#1211115e'],time:3000,shadeClose:true}); // 现金计息表头部工具栏计息|搜索按钮的事件句柄绑定 table.on('toolbar(cashInterestEvent)', function(obj) { // 获取当前表格选中状态和选中的数据 var checkStatus = table.checkStatus(obj.config.id); // 区分点击的按钮 switch(obj.event) { case 'LAYTABLE_SEARCH': laytablesearch(); layer.close(ltips); break; case 'interest': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要计息的数据!!", { icon: 4 //图标,可输入范围0~6 }); return; } // 定义一个要现金计息的所有现金库存id的字符串 var cashInventoryIdStr = ""; // 遍历传递过来的要计息的数据 for(var i = 0; i < data.length; i++) { // 拿出基金库存id进行拼接 cashInventoryIdStr += data[i].cashInventoryId + ","; } // 截取掉因为拼接产生的多余的一个逗号 cashInventoryIdStr = cashInventoryIdStr.substring(0, cashInventoryIdStr.length - 1); // 调用向后台发起现金计息的请求方法 cashInterest(cashInventoryIdStr); break; }; }); // 定义向后台发起现金计息的请求方法 var cashInterest = function(cashInventoryIds) { $.ajax({ url:"../calcRevenue/cashInterest", type:'post', data:{ cashInventoryIds:cashInventoryIds, }, success:function (data) { if(data == 1) { layer.msg("计息成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg("计息失败!", { icon: 1 // 图标,可输入范围0~6 }); } table.reload('cashInterestTable',{ url:"../calcRevenue/cashInventoryList" }); } }) }; }); }); <file_sep>/fa-web/src/main/java/com/yidu/stock/controller/StockQuotationController.java package com.yidu.stock.controller; import com.alibaba.excel.EasyExcel; import com.yidu.format.LayuiFormat; import com.yidu.stock.Listener.DataStockQuotationListener; import com.yidu.stock.domain.StockQuotation; import com.yidu.stock.paging.StockQuotationPaging; import com.yidu.stock.service.StockQuotationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; /** * 类的描述:股票详细业务的逻辑处理,控制器层 * * @author 江北 * @since 2020/9/11 13:03 */ @RestController @RequestMapping("/stockQuotation") public class StockQuotationController { @Autowired private StockQuotationService stockQuotationService; /** * 搜索查询所有股票行情数据并分页 * @param stockQuotationPaging 搜索分页参数 * @return 股票交易集合的layui格式数据 */ @ResponseBody @RequestMapping("/list") public LayuiFormat findStockQuotation(StockQuotationPaging stockQuotationPaging){ return stockQuotationService.findStockQuotation(stockQuotationPaging); } /** * Excel数据导入,保存至数据库 * @param file * @return 1:导入成功,0导入出错 */ @RequestMapping("/poi") public String addStockQuotation(@RequestParam MultipartFile file) { System.out.println("正在进行导入..."); try { InputStream InputStream = file.getInputStream(); EasyExcel.read(InputStream, StockQuotation.class,new DataStockQuotationListener(stockQuotationService)).sheet().doRead(); } catch (Exception e) { e.printStackTrace(); return "0"; } //1:导入成功,0导入出错 return "1"; } } <file_sep>/fa-web/src/main/webapp/static/deposit/js/depositInterestAccrual.js /* * layui引入样式的两种方式:模块化用和全模块用法 * layui的初始化模块可以理解为,引入这个模块的js文件 * 值得注意的是:layui的模块之间存在依赖关系,例如引入了table模块,它会layui/lay/moudules/table.js * 这个文件引入进来,并且它还会将这个模块所依赖的其他模块自动加入进来, * 实际引入的模块有:table、form、jquery、layer、laypage、laytpl、util,7个js文件 * 所以我仅仅初始化了table模块,却能获得form、jquery、layer的模块对象 */ //layui初始化表格模组 layui.use(['table', 'laydate', 'upload','element'], function() { // 获得模块对象 var table = layui.table; var form = layui.form; var $ = layui.jquery; var layer = layui.layer; var laydate = layui.laydate; var upload = layui.upload; //定义下拉搜索框方法 function xia() { var hideBtn = $("#hideBtn"); var flag = false; var search_header = $("#search-header"); search_header.css("top",-search_header.height()); hideBtn.click(function () { let height = search_header.height(); if(flag){ search_header.animate({ "top":-height },"fast","linear"); flag = false; }else { search_header.animate({ "top":0 },"fast","linear"); flag = true; } }); } //调用下拉框方法 xia(); //定义数据表格渲染方法 function f(a,b) { var tableIns=table.render({ elem: '#'+ a, url: '/fa/depositInterestAccrualController/findSecuritiesInventoryByCondition?tradeStatus=' + b, //后期改回获取用户列表的后端程序的url method: 'get', where: {}, // 你额外要携带数据,以键值对的方式存入 toolbar: '#depositInterestAccrual', // 开启头部工具栏,并为其绑定左侧模板 cellMinWidth: 80, // 全局定义所有常规单元格的最小宽度(默认:60) height: 'full-10', cols: [ [{ type: 'numbers' }, // 序号 { type: 'checkbox' }, //复选框 { field: 'securitiesInventoryId', title: '证劵库存Id', unresize: true, hide:true, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'sechuritiesInventoryNo', title: '证劵库存编号', unresize: true, width:150, align: "center" }, { field: 'securitiesId', title: '证券Id', unresize: true, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'securitiesNo', title: '证券编号', unresize: true, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'securitiesName', title: '证券名', unresize: true, align: "center" }, { field: 'fundId', title: '基金Id', unresize: true, hide:true, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'fundNo', title: '基金代码', unresize: true, align: "center", }, { field: 'fundName', title: '基金名', width:160, unresize: true, align: "center", }, { field: 'accountId', title: '账户ID', unresize: true, width:130, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'accountNo', title: '账户账号', unresize: true, hide:true, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'accountName', title: '账户名', unresize: true, hide: true, align: "center", }, { field: 'price', title: '单位成本', unresize: true, align: "center", }, { field: 'share', title: '持有份额', unresize: true, align: "center", }, { field: 'turnover', title: '总金额', width:105, unresize: true, align: "center" }, { field: 'securitiesType', title: '证劵类型', unresize: true, align: "center", templet: "#tradeStatusTpl4" }, { field: 'statisticalDate', title: '统计日期', unresize: true, align: "center" }, { field: 'description', title: '描述', unresize: true, align: "center" }, { field: 'tradeStatus', title: '状态', unresize: true, align: "center", //fixed:'right', templet: '#tradeStatusTpl' } ] ], page: true, // 开启分页 limit: 10, // 每页显示的条数 limits: [10, 20, 50, 100], // 每页条数的选择项 loading: true, // 是否显示加载条(切换分页的时候显示) title: '存款计息', // 定义 table 的大标题(在文件导出等地方会用到) text:{none:'被抽干了!没东西可以给你了,555!!(ㄒoㄒ)~~'}, // 隔行变色 even: false })}; //调用渲染表格方法 f("depositInterestAccrualTable1",0); f("depositInterestAccrualTable2",1); // 基金交易未结算数据表头部工具栏结算|导入按钮的事件句柄绑定 table.on('toolbar(depositInterestAccrualTableEvent)', function(obj) { // 获取当前表格选中状态和选中的数据 var checkStatus = table.checkStatus(obj.config.id); // 区分点击的按钮 switch(obj.event) { case 'settlement': // 当前选中行的数据 var data = checkStatus.data; //判断是否有全选中 if(!checkStatus.isAll) { layer.msg("请全选你要结算的数据!!", { icon: 4 //图标,可输入范围0~6 }); return; } // 定义一个要计息的所有存款数据ID的字符串 var depositInterestAccrualIdStr = ""; // 遍历传递过来的要计息的数据 for(var i = 0; i < data.length; i++) { if(data[i].tradeStatus == '1') { layer.msg("所选数据中有已计息数据!", { icon: 1 // 图标,可输入范围0~6 }); return; } // 拿出存款数据Id进行拼接 depositInterestAccrualIdStr += data[i].securitiesInventoryId + ","; } // 截取掉因为拼接产生的多余的一个逗号 depositInterestAccrualIdStr = depositInterestAccrualIdStr.substring(0, depositInterestAccrualIdStr.length - 1); // 调用修改基金状态请求方法 updateTradeStatus(depositInterestAccrualIdStr, '1'); break; }; }); // 定义修改交易状态请求方法 var updateTradeStatus = function(securitiesInventoryIds,tradeStatus) { $.ajax({ url:"/fa/depositInterestAccrualController/depositInterestAccrual", type:'post', data:{ securitiesInventoryIds:securitiesInventoryIds, tradeStatus:tradeStatus }, success:function (data) { console.log(data); if(data) { layer.msg("结算成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg("结算失败!", { icon: 1 // 图标,可输入范围0~6 }); } f("depositInterestAccrualTable1",0); f("depositInterestAccrualTable2",1) } }) }; }); <file_sep>/fa-base/src/main/java/com/yidu/stock/service/impl/StockLogicalServiceImpl.java package com.yidu.stock.service.impl; import com.yidu.capital.domain.CapitalTransfer; import com.yidu.deposit.domain.CashInventory; import com.yidu.format.LayuiFormat; import com.yidu.index.domain.SecuritiesInventory; import com.yidu.stock.dao.StockLogicalDao; import com.yidu.stock.domain.StockTrade; import com.yidu.stock.paging.StockTradePaging; import com.yidu.stock.service.StockLogicalService; import com.yidu.utils.DateUtils; import com.yidu.utils.IDUtil; import com.yidu.utils.NoUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.math.BigDecimal; import java.util.Date; import java.util.List; @Service("StockLogicalService") public class StockLogicalServiceImpl implements StockLogicalService { @Autowired private StockLogicalDao stockLogicalDao; @Autowired private LayuiFormat layuiFormat; @Override public LayuiFormat findStockTrade(StockTradePaging stockTradePaging) { int limit = stockTradePaging.getLimit(); int page = (stockTradePaging.getPage()-1)*limit; stockTradePaging.setPage(page); stockTradePaging.setLimit(limit); List<StockTrade> stockTrades = stockLogicalDao.findStockTrade(stockTradePaging); if(CollectionUtils.isEmpty(stockTrades)){ layuiFormat.setCode(1); //状态码0为查询到数据 layuiFormat.setCount(0L); layuiFormat.setMsg("未查询到指定数据哦!"); }else{ layuiFormat.setCode(0); //状态码0为查询到数据 layuiFormat.setCount(stockLogicalDao.findStockTradeCount(stockTradePaging)); layuiFormat.setMsg("成功找到数据"); layuiFormat.setData(stockTrades); } return layuiFormat; } @Override public void addStockTrade(StockTrade stockTrade) { stockTrade.setStockId(IDUtil.getUuid()); stockLogicalDao.addStockTrade(stockTrade); } @Override public int settlementsT(String stockTradeId, String tradeStatus) { int flag = 0; //修改股票交易数据的状态 flag=stockLogicalDao.updateTradeStatus(stockTradeId,tradeStatus); //往资金调拨单中添加记录 买 流出 卖 流入 flag=addCTRecording(stockTradeId); //证券库存表中添加|修改 每天有多条记录(一个股票一条) 买 份额增加 卖 份额减少 flag = addSIRecording(stockTradeId); //现金库存表中添加(或修改)记录 每天一条记录 买 余额减少 卖 余额增加 flag = addCIRecording(stockTradeId); return flag; } private int addCIRecording(String stockTradeId) { int flag = 0; //4.1 通过stockTradeId查询交易记录 StockTrade stockTrade = stockLogicalDao.findStockTradeById(stockTradeId); //4.2 按债券交易中的fundId和bondId,联表查询出现金对应的现金库存数据对象 CashInventory cashInventory = stockLogicalDao.findCashInventory(stockTrade.getFundId(),stockTrade.getStockId()); if(stockTrade.getTradeFlag()==1){ //流入,现金库存+ cashInventory.setCashBalance(cashInventory.getCashBalance().add(stockTrade.getTurnover())); }else if(stockTrade.getTradeFlag() == 2){ //流出 现金库存- cashInventory.setCashBalance(cashInventory.getCashBalance().subtract(stockTrade.getTurnover())); } //4.3 判断此数据是否是今天的数据 //是今天的数据,修改此对象现金库存数据 if(cashInventory.getStatisticalDate().getTime()>= DateUtils.ZeroDate(new Date())){ //修改更改账户统计日期 cashInventory.setStatisticalDate(new Date()); //4.3 将对应的现金账户更新 flag = stockLogicalDao.updateCashInventory(cashInventory); }else{//不是今天的数据,添加今天新的现金库存数据 //设置现金库存id cashInventory.setCashInventoryId(IDUtil.getUuid()); //设置现金库存编号 cashInventory.setCashInventoryNo(NoUtils.getNo("XJKC")); //修改更改账户统计日期 cashInventory.setStatisticalDate(new Date()); //4.3 添加今天新的现金库存数据 flag = stockLogicalDao.addCashInventory(cashInventory); } return flag; } private int addSIRecording(String stockTradeId) { int flag=0; //3.1 通过stockTradeId查询交易记录 StockTrade stockTrade = stockLogicalDao.findStockTradeById(stockTradeId); System.out.println(stockTrade.getFundId()+","+stockTrade.getStockId()); //3.2 查询证券库存中是否有同一支基金的同一支债券(有:修改,没有:添加) SecuritiesInventory securitiesInventory = stockLogicalDao.findStockInventory(stockTrade.getFundId(),stockTrade.getStockId()); /*System.out.println("securitiesInventory"+securitiesInventory); System.out.println("StatisticalDate"+securitiesInventory.getStatisticalDate().getTime()); System.out.println("ZeroDate"+DateUtils.ZeroDate(new Date()));*/ //如果securitiesInventory不为空,且交易数据的时间小于今天零点(今天没有数据),则添加 if(null == securitiesInventory || securitiesInventory.getStatisticalDate().getTime()< DateUtils.ZeroDate(new Date())){ //3.3/查询到账户信息,及单位成本,赋值到证券库存对象中 securitiesInventory = stockLogicalDao.findSIByFundId(stockTrade.getFundId(),stockTrade.getStockTradeId()); //设置相关初始信息,及相关数据到证券库存对象 securitiesInventory.setSecuritiesInventoryId(IDUtil.getUuid()); securitiesInventory.setSechuritiesInventoryNo(NoUtils.getNo("GPJS")); securitiesInventory.setSecuritiesType(1);//1:股票,2:债券,3:银行存款 securitiesInventory.setStatisticalDate(new Date()); securitiesInventory.setDescription("股票交易数据清算"); securitiesInventory.setSecuritiesId(stockTrade.getStockId()); securitiesInventory.setSecuritiesNo(stockTrade.getStockCode()); securitiesInventory.setSecuritiesName(stockTrade.getStockName()); securitiesInventory.setFundId(stockTrade.getFundId()); securitiesInventory.setFundNo(stockTrade.getFundNo()); securitiesInventory.setFundName(stockTrade.getFundName()); securitiesInventory.setShare(stockTrade.getShare()); securitiesInventory.setTurnover(securitiesInventory.getPrice().multiply(new BigDecimal(stockTrade.getShare()))); //注意计算的精度问题 System.out.println(securitiesInventory); //3.4添加证券库存数据 flag = stockLogicalDao.addSecuritiesInventory(securitiesInventory); }else{//交易数据的时间大于今天零点(今天有数据),则修改 //3.3存在则 修改数据 //修改 更新数据时的日期 securitiesInventory.setStatisticalDate(new Date()); //判断是证券(债券)是 买入 or 卖出 if(stockTrade.getTradeType() == 1){ //买入 //持有份额+ securitiesInventory.setShare(securitiesInventory.getShare()+(stockTrade.getShare())); //总金额+ securitiesInventory.setTurnover(securitiesInventory.getTurnover().add(stockTrade.getTurnover()));//注意计算的精度问题 }else{ //流出 //持有份额- securitiesInventory.setShare(securitiesInventory.getShare()-(stockTrade.getShare())); //总金额+ securitiesInventory.setTurnover(securitiesInventory.getTurnover().subtract(stockTrade.getTurnover()));//注意计算的精度问题 } // 3.4 修改证券(债券)库存数据 flag = stockLogicalDao.updateSecuritiesInventory(securitiesInventory); } return flag; } /** * 往资金调拨单表中添加记录 * @param stockTradeId 股票交易id * @return */ private int addCTRecording(String stockTradeId) { //2.1 根据stockTradeId查询出股票数据所需字段 并封装到‘资金调度’对象 CapitalTransfer capitalTransfer = stockLogicalDao.findCapitalTransferByStockTradeId(stockTradeId); //2.2 设置capitalTransferId(uuid) capitalTransfer.setCapitalTransferId(IDUtil.getUuid()); //2.3 设置调拨编号 capitalTransfer.setCapitalTransferNo(NoUtils.getNo("ZJDB")); //2.4设置调拨日期 capitalTransfer.setTransferDate(new Date()); //2.5设置调拨类型(4.清算调拨) capitalTransfer.setTransferType("4"); //2.6将查出的调拨单存入数据库表中 int flag = stockLogicalDao.addCapitalTransfer(capitalTransfer); return flag; } /** * 往资金调拨单表中添加记录 * @param stockTradeId 股票交易id * @return */ private int addSecuritiesInventory(String stockTradeId) { //2.1 根据stockTradeId查询出股票数据所需字段 并封装到‘资金调度’对象 CapitalTransfer capitalTransfer = stockLogicalDao.findCapitalTransferByStockTradeId(stockTradeId); System.out.println(capitalTransfer); //2.2 设置capitalTransferId(uuid) capitalTransfer.setCapitalTransferId(IDUtil.getUuid()); //2.3 设置调拨编号 capitalTransfer.setCapitalTransferNo(NoUtils.getNo("ZJDB")); //2.4设置调拨日期 capitalTransfer.setTransferDate(new Date()); //2.5设置调拨类型(4.清算调拨) capitalTransfer.setTransferType("4"); //2.6将查出的调拨单存入数据库表中 int flag = stockLogicalDao.addCapitalTransfer(capitalTransfer); return flag; } } <file_sep>/fa-base/src/main/java/com/yidu/stock/domain/StockTrade.java package com.yidu.stock.domain; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; /** * 类的描述:股票交易数据表 * @author 江北 * @version 1.0 * since 2020/09/09 */ public class StockTrade { /** * 股票交易Id */ private String stockTradeId; /** * 股票交易编号 */ private String stockTradeNo; /** * 基金Id */ private String fundId; /** * 基金代码 */ private String fundNo; /** * 基金名 */ private String fundName; /** * 股票Id */ private String stockId; /** * 股票代码 */ private String stockCode; /** * 股票名 */ private String stockName; /** * 基金经理Id */ private String managerId; /** * 基金经理 */ private String managerName; /** * 券商Id */ private String brokerId; /** * 券商名 */ private String brokerName; /** * 交易方式 */ private int tradeType; /** * 交易标识 */ private int tradeFlag; /** * 交易价格(单价) */ private BigDecimal tradePrice; /** * 交易日期 */ private Date tradeDate; /** * 交易数量(份额) */ private Integer share; /** * 交易额(总) */ private BigDecimal turnover; /** * 印花税(国家) */ private BigDecimal stampTax; /** * 征管费(国家) */ private BigDecimal managementFees; /** * 过户费(交易所) */ private BigDecimal transferFee; /** * 佣金费用(券商) */ private BigDecimal commission; /** * 经手费(交易所) */ private BigDecimal brokerage; /** * 总金额 */ private BigDecimal total; /** * 交易状态 */ private String tradeStatus; /** * 备注 */ private String description; public String getStockTradeId() { return stockTradeId; } public void setStockTradeId(String stockTradeId) { this.stockTradeId = stockTradeId; } public String getStockTradeNo() { return stockTradeNo; } public void setStockTradeNo(String stockTradeNo) { this.stockTradeNo = stockTradeNo; } public String getFundId() { return fundId; } public void setFundId(String fundId) { this.fundId = fundId; } public String getFundNo() { return fundNo; } public void setFundNo(String fundNo) { this.fundNo = fundNo; } public String getFundName() { return fundName; } public void setFundName(String fundName) { this.fundName = fundName; } public String getStockId() { return stockId; } public void setStockId(String stockId) { this.stockId = stockId; } public String getStockCode() { return stockCode; } public void setStockCode(String stockCode) { this.stockCode = stockCode; } public String getStockName() { return stockName; } public void setStockName(String stockName) { this.stockName = stockName; } public String getManagerId() { return managerId; } public void setManagerId(String managerId) { this.managerId = managerId; } public String getManagerName() { return managerName; } public void setManagerName(String managerName) { this.managerName = managerName; } public String getBrokerId() { return brokerId; } public void setBrokerId(String brokerId) { this.brokerId = brokerId; } public String getBrokerName() { return brokerName; } public void setBrokerName(String brokerName) { this.brokerName = brokerName; } public int getTradeType() { return tradeType; } public void setTradeType(int tradeType) { this.tradeType = tradeType; } public int getTradeFlag() { return tradeFlag; } public void setTradeFlag(int tradeFlag) { this.tradeFlag = tradeFlag; } public BigDecimal getTradePrice() { return tradePrice; } public void setTradePrice(BigDecimal tradePrice) { this.tradePrice = tradePrice; } public Date getTradeDate() { return tradeDate; } public void setTradeDate(Date tradeDate) { this.tradeDate = tradeDate; } public Integer getShare() { return share; } public void setShare(Integer share) { this.share = share; } public BigDecimal getTurnover() { return turnover; } public void setTurnover(BigDecimal turnover) { this.turnover = turnover; } public BigDecimal getStampTax() { return stampTax; } public void setStampTax(BigDecimal stampTax) { this.stampTax = stampTax; } public BigDecimal getManagementFees() { return managementFees; } public void setManagementFees(BigDecimal managementFees) { this.managementFees = managementFees; } public BigDecimal getTransferFee() { return transferFee; } public void setTransferFee(BigDecimal transferFee) { this.transferFee = transferFee; } public BigDecimal getCommission() { return commission; } public void setCommission(BigDecimal commission) { this.commission = commission; } public BigDecimal getBrokerage() { return brokerage; } public void setBrokerage(BigDecimal brokerage) { this.brokerage = brokerage; } public BigDecimal getTotal() { return total; } public void setTotal(BigDecimal total) { this.total = total; } public String getTradeStatus() { return tradeStatus; } public void setTradeStatus(String tradeStatus) { this.tradeStatus = tradeStatus; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "StockTrade{" + "stockTradeId='" + stockTradeId + '\'' + ", stockTradeNo='" + stockTradeNo + '\'' + ", fundId='" + fundId + '\'' + ", fundNo='" + fundNo + '\'' + ", fundName='" + fundName + '\'' + ", stockId='" + stockId + '\'' + ", stockCode='" + stockCode + '\'' + ", stockName='" + stockName + '\'' + ", managerId='" + managerId + '\'' + ", managerName='" + managerName + '\'' + ", brokerId='" + brokerId + '\'' + ", brokerName='" + brokerName + '\'' + ", tradeType='" + tradeType + '\'' + ", tradeFlag='" + tradeFlag + '\'' + ", tradePrice=" + tradePrice + ", tradeDate=" + tradeDate + ", share=" + share + ", turnover=" + turnover + ", stampTax=" + stampTax + ", managementFees=" + managementFees + ", transferFee=" + transferFee + ", commission=" + commission + ", brokerage=" + brokerage + ", total=" + total + ", tradeStatus='" + tradeStatus + '\'' + ", description='" + description + '\'' + '}'; } } <file_sep>/fa-web/src/main/webapp/static/account/js/account.js /* * layui引入样式的两种方式:模块化用和全模块用法 * layui的初始化模块可以理解为,引入这个模块的js文件 * 值得注意的是:layui的模块之间存在依赖关系,例如引入了table模块,它会layui/lay/moudules/table.js * 这个文件引入进来,并且它还会将这个模块所依赖的其他模块自动加入进来, * 实际引入的模块有:table、form、jquery、layer、laypage、laytpl、util,7个js文件 * 所以我仅仅初始化了table模块,却能获得form、jquery、layer的模块对象 */ //layui初始化表格模组 layui.use(['table', 'laydate', 'util', 'upload'], function() { // 获得模块对象 var table = layui.table; var form = layui.form; var $ = layui.jquery; var layer = layui.layer; var laydate = layui.laydate; var util = layui.util; var upload = layui.upload; //下拉搜索框设置 var hideBtn = $("#hideBtn"); var flag = false; var search_header = $("#search-header"); search_header.css("top",-search_header.height()); hideBtn.click(function () { let height = search_header.height(); if(flag){ search_header.animate({ "top":-height },"fast","linear"); flag = false; }else { search_header.animate({ "top":0 },"fast","linear"); flag = true; } }); //----1.用户数据表格渲染------------------------------------------------------------------ table.render({ elem: '#accountTable', url: '/fa/accountController/findAllAccount', //后期改回获取用户列表的后端程序的url method: 'get', where: {}, // 你额外要携带数据,以键值对的方式存入 toolbar: '#accountToolbar', // 开启头部工具栏,并为其绑定左侧模板 height: 'full-10', cellMinWidth: 80, // 全局定义所有常规单元格的最小宽度(默认:60) cols: [ [{ type: 'numbers' }, // 序号 { type: 'checkbox' }, //复选框 /*{ title:'头像', field:'userPic', unresize:true, // width:150, align:'center', templet: function(data) { if(data.userPic !='' && data.userPic != undefined){ return '<img src="'+ data.userPic+'" width="50px" height="50px"/>'; }else{ return '<img src="sys/img/7.png" width="50px" height="50px"/>'; } } },*/ { field: 'accountId', title: '账户Id', unresize: true, hide: true, //一般情况下不显示用户ID align: "center" }, { field: 'accountNO', title: '账号', unresize: true, hide: true, //一般情况下不显示用户ID align: "center" }, { field: 'accountName', title: '账户名', unresize: true, align: "center" }, { field: 'depositType', title: '存款类型', unresize: true, // width:130, align: "center" }, { field: 'depositRate', title: '存款利率', unresize: true, // hide: true, align: "center" }, /*{ field: 'genderStr', title: '用户性别', unresize: true, align: "center", templet: function(d) { if(d.genderStr == '男') { return '<span style="color: #00F;">' + d.genderStr + '</span>'; } else { return '<span style="color: #fd04bc;">' + d.genderStr + '</span>'; } } },*/ { field: 'bankName', title: '开户银行', unresize: true, // templet: '#checkboxTpl', align: "center" }, { field: 'openDateStr', title: '开户时间', unresize: true, // templet: '#checkboxTpl', align: "center", width: 200 }, { field: 'fundId', title: '所属基金Id', unresize: true, hide: true,//一般不显示 align: "center" }, { field: 'fundNo', title: '所属基金代码', unresize: true, align: "center" }, { field: 'fundName', title: '所属基金名', unresize: true, align: "center" }, { field: 'description', title: '描述', unresize: true, hide: true, Width:'auto', align: "center" }, { field: 'usable', title: '现金账户状态', unresize: true, templet: '#checkboxTpl', align: "center" },/*, { field: 'createTimeStr', title: '创建时间', unresize: true, align: "center", width: 160 }*/ ] ], page: true, // 开启分页 limit: 10, // 每页显示的条数 limits: [10, 20, 50, 100], // 每页条数的选择项 loading: true, // 是否显示加载条(切换分页的时候显示) title: '现金账户表', // 定义 table 的大标题(在文件导出等地方会用到) id: 'accountTable', // 设定容器唯一 id // 隔行变色 even: false }); //----1.用户数据表格渲染------------------------------------------------------------------ //----2.添加用户入职时间选择器-------------------------------------------------------------------- laydate.render({ elem: '#addOpenDate', type:'datetime' }); //修改用户入职时间选择器 laydate.render({ elem: '#updateOpenDate', type:'datetime' }); //重置按钮 $(".my-bg-green3").click(function () { // 刷新数据表格 table.reload('accountTable', { url: '/fa/accountController/findAllAccount' //后期改为查询用户的后台程序的url }); }) //----3.处理头部条件组合搜素------------------------------------------------------------------ form.on('submit(accountSearchBtn)', function(data) { //将搜索下列框收回 let height = search_header.height(); if(flag){ search_header.animate({ "top":-height },"fast","linear"); flag = false; }else { search_header.animate({ "top":0 },"fast","linear"); flag = true; } // 执行后台代码 table.reload('accountTable', { url: '/fa/accountController/findAccountByCondition', where: { // 设定异步数据接口的额外参数,任意设 accountName: $("#queryAccountName").val(), depositType: $("#queryDepositType").val(), bankName: $("#queryBankName").val(), }, page: { curr: 1 //从第一页开始 }, limit: 10 }); return false; // 阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); //----3.处理表行修改------------------------------------------------------------------ table.on("tool(accountTableEvent)",function (obj) { var data = obj.data; console.log(data); if (obj.event == "update"){ initUpdateAccountModal(data); } }); // 用户列表头部工具栏添加|修改|删除(逻辑删除)|恢复按钮的事件句柄绑定 table.on('toolbar(accountTableEvent)', function(obj) { // 获取当前表格选中状态和选中的数据 var checkStatus = table.checkStatus(obj.config.id); // 区分点击的按钮 switch(obj.event) { case 'addAccount': // 弹出新增模态框 initAddAccountModal(); break; case 'updateAccount': // 选择的数据数量 if(checkStatus.data.length > 1) { layer.msg("最多只能修改一行数据哦!!", { icon: 0 //图标,可输入范围0~6 }); } else if(checkStatus.data.length < 1) { layer.msg("请选择要修改的数据哦!!", { icon: 3 //图标,可输入范围0~6 }); } else if(checkStatus.data[0].usable == 'N') { layer.msg("该用户被禁用了哦!!", { icon: 4 //图标,可输入范围0~6 }); } else { // 弹出修改模态框,传递当前选中的一行数据过去 initUpdateAccountModal(checkStatus.data[0]); } break; case 'frozenRecord': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要冻结的用户!!", { icon: 4 //图标,可输入范围0~6 }); } // 定义一个要删除的所有资源ID的字符串 var accountIdStr = ""; // 遍历传递过来的要删除的数据 for(var i = 0; i < data.length; i++) { if(data[i].usable == 'N') { layer.msg("所选用户中有被冻结的用户!", { icon: 1 // 图标,可输入范围0~6 }); return; } // 拿出用户ID进行拼接 accountIdStr += data[i].accountId + ","; } // 截取掉因为拼接产生的多余的一个逗号 accountIdStr = accountIdStr.substring(0, accountIdStr.length - 1); frozenORrecoverArchives(accountIdStr, 'N'); break; case 'restoreRecord': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要还原的用户!!", { icon: 4 //图标,可输入范围0~6 }); } // 定义一个要删除的所有资源ID的字符串 var accountIds = ""; // 遍历传递过来的要删除的数据 for(var i = 0; i < data.length; i++) { if(data[i].usable == 'Y') { layer.msg("所选用户中有可用的用户!", { icon: 1 // 图标,可输入范围0~6 }); return; } // 拿出资源ID进行拼接 accountIds += data[i].accountId + ","; } // 截取掉因为拼接产生的多余的一个逗号 accountIds = accountIds.substring(0, accountIds.length - 1); frozenORrecoverArchives(accountIds, 'Y'); break; }; }); //----4.处理新增用户表单提交-------------------------------------------------------------- form.on('submit(addAccountBtn)', function(data) { // 执行后台代码 $.ajax({ type: 'POST', //适用RESTful风格的添加: 查询GET、添加POST、更新PUT、删除DELETE async: false, url: '/fa/accountController/addAccount', //后期改为添加用户的后台程序的url data: data.field, success: function(data) { // 关闭页面上所有类型的所有弹框 layer.closeAll(); if(data == 1) { layer.msg("添加成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg("添加失败!", { icon: 1 // 图标,可输入范围0~6 }); } } }); // 刷新数据表格 table.reload('accountTable', { url: '/fa/accountController/findAllAccount' //后期改为查询用户的后台程序的url }); return false; // 阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); //----5.处理修改现金账户表单提交-------------------------------------------------------------- form.on('submit(updateAccountBtn)', function(data) { //执行后台代码 $.ajax({ type: 'POST', //适用RESTful风格的添加: 查询GET、添加POST、更新PUT、删除DELETE async: false, url: '/fa/accountController/updateAccount', //后期改为修改用户的后台程序url data: data.field,//data.field success: function(data) { console.log(data.result) //关闭页面上所有类型的所有弹框 layer.closeAll(); if(data == 1) { layer.msg("修改成功!", { icon: 1 //图标,可输入范围0~6 }); } else { layer.msg("修改失败!", { icon: 1 //图标,可输入范围0~6 }); } } }); //刷新数据表格 table.reload('accountTable', { url: '/fa/accountController/findAllAccount' // }); return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); // 监听锁定操作 form.on('switch(usable)', function(obj) { frozenORrecoverArchives(obj.value, this.checked == true ? 'Y' : 'N'); }); // 定义冻结或还原的方法 var frozenORrecoverArchives = function(accountIdStr, status) { // 现金账户ID var userId = accountIdStr; // 定义提示信息, 状态 var msg, usable; if(status == 'Y') { msg = "还原", usable = 'Y'; } else { msg = "禁用", usable = 'N'; } // 发送异步请求冻结或还原资源 $.ajax({ async: false, // 默认为true,false表示同步,如果当前请求没有返回则不执行后续代码 type: "DELETE", url:'/fa/accountController/updateAccountStatus/' + accountIdStr + "/" + usable,// /updateUser '/updateUserStatus/' + userIds + "/" + usable data: { // userId:userId, // usable:usable, // _method: 'DELETE' }, datatype: 'json', success: function(data) { if(data.result == "1") { layer.msg(msg + "成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg(msg + "失败!", { icon: 2 }); } // 刷新数据表格 table.reload('accountTable', { url: '/fa/accountController/findAllAccount' }); } }); }; // var hiddeDisable = function(){ // // } // 初始化新增模态框 var initAddAccountModal = function() { // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '添加现金账户', // 标题 skin: "layui-layer-molv", anim: 2, // 弹出动画 area: ["100%","100%"], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#addAccountModal"), // 文本、html都行 resize: false, // 是否允许拉伸 end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) // 清空表单 $("#addAccountForm")[0].reset(); $("#demo1").attr("src", ""); $("#demoText").text(""); } }); } // 初始化修改模态框 var initUpdateAccountModal = function(data) { // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '修改现金账户', // 标题 skin: "layui-layer-molv", anim: 2, // 弹出动画 area: ["100%","100%"], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#updateAccountModal"), // 文本、html都行 resize: false, // 是否允许拉伸 end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) // 清空表单 $("#addAccountForm")[0].reset(); $("#demo1").attr("src", ""); $("#demoText").text(""); } }); // 表单赋值 form.val('updateAccountForm', { "accountId": data.accountId, "accountNo": data.accountNo, //layui.util.toDateString(data.commonStart, 'HH:mm:ss'), "accountName": data.accountName, "depositType": data.depositType, "depositRate": data.depositRate, "bankName": data.bankName, "openDate": data.openDateStr, "fundId": data.fundId, "fundNo":data.fundNo, "fundName": data.fundName, "usable": data.usable, "description": data.description, }); }; // $.ajax({ // url: '/findUserByConditionuuuu',//system/org', // dataType: 'json', // type: 'post', // success: function(data) { // $.each(data, function(index) { // var orgName = data[index].orgName; // var orgId = data[index].orgId; // /* var sdSdd = data[index].sdSdd; */ // // 头部的搜索 // $("#queryOrgName").append( // "<option value='" + orgName + "'>" + orgName + // "</option>"); // // 添加 // $("#addOrgName").append( // "<option value='" + orgId + "'>" + orgName + // "</option>"); // // 修改 // $("#updateOrgName").append( // "<option value='" + orgId + "'>" + orgName + // "</option>"); // // form.render()渲染将option添加进去 // form.render(); // }); // } // }); // 自定义表单校验 form.verify({ pass: [ /^[\S]{6,12}$/, '密码必须6到12位,且不能出现空格'], mobile: function(value) { var msg; $.ajax({ type: "POST", url: '/fa/verifyTelephone',//system/toVerifyUserPhone async: false, // 使用同步的方法 data: { 'telephone': value }, dataType: 'json', success: function(result) { if(result.flag) { msg = result.msg; } } }); return msg; } }); }); <file_sep>/fa-base/src/main/java/com/yidu/deposit/dao/DepositInterestAccrualDao.java package com.yidu.deposit.dao; import com.yidu.deposit.domain.DepositTrade; import com.yidu.index.domain.SecuritiesArap; import com.yidu.index.domain.SecuritiesInventory; import com.yidu.index.domain.SecuritiesarapInventory; import com.yidu.index.paging.SecuritiesInventoryPaging; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * 类的描述:存款计息持久层接口 * * @author 蔡任骋 * @version 1.0 * @since 2020/09/21 */ public interface DepositInterestAccrualDao { /** * 1.1.查询满足条件的证券库存数 * @param securitiesInventoryPaging 包含条件的POJO类 * @return 成功返回数量,赋值返回0 */ long countDepositInterestAccrualByCondition(SecuritiesInventoryPaging securitiesInventoryPaging); /** * 1.2.查询满足条件的证券库存 * @param securitiesInventoryPaging 包含条件的POJO类 * @return 成功返回一个包含数据的集合,否则返回null */ List<SecuritiesInventory> findSecuritiesInventoryByCondition(SecuritiesInventoryPaging securitiesInventoryPaging); /** * 2.1.1修改证券库存中银行存款的计息状态 * @param paramMap 包含条件的map * @return 成功返回true,否则返回false */ boolean updateDepositInterestAccrualStatus(Map<String,Object> paramMap); /** * 2.1.2根据证券库存Id查询数据 * @param securitiesInventoryId 证券库存id * @return 成功返回对应数据,否则返回null */ SecuritiesInventory findSecuritiesInventoryById (String securitiesInventoryId); /** * 2.2.1.根据银行交易数据ID查询交易数据 * @param depositId 银行交易数据id * @return 银行交易数据 */ DepositTrade findDepositTradeById(String depositId); /** * 2.2.2.添加证券应收应付表数据 * @param securitiesArap 证券应收应付表数据 * @return 成功返回true,否则返回false */ boolean addDepositInterestAccrual(SecuritiesArap securitiesArap); /** * 2.3.1根据条件查询证券应收应付库存表中数据 * @param paramMap 包含条件的map * @return 成功返回证券应收应付库存对象,否则返回null */ SecuritiesarapInventory findSecuritiesarapInventoryByCondition(Map<String,Object> paramMap); /** * 2.3.2添加证券应收应付库存数据 * @param securitiesarapInventory 证券应收应付库存数据 * @return 成功返回true,否则返回false */ boolean addSecuritiesarapInventory(SecuritiesarapInventory securitiesarapInventory); /** * 2.3.3修改证券应收应付库存数据 * @param paramMap 包含条件的map * @return 成功返回true,否则返回false */ boolean updateSecuritiesarapInventory(Map<String,Object> paramMap); /** * 2.3.4查询证券应收应付最近的一条数据 * @param securitiesId 证券id * @param fundId 基金id * @param accountId 账户id * @return 证券应收应付库存数据 */ SecuritiesarapInventory findSecuritiesarapInventoryById(@Param("securitiesId") String securitiesId, @Param("fundId") String fundId, @Param("accountId") String accountId); } <file_sep>/fa-web/src/main/java/com/yidu/deposit/controller/DepositInterestAccrualController.java package com.yidu.deposit.controller; import com.yidu.deposit.service.DepositInterestAccrualBiz; import com.yidu.format.LayuiFormat; import com.yidu.index.domain.SecuritiesInventory; import com.yidu.index.paging.SecuritiesInventoryPaging; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /** * 类的描述:存款计息控制器 * * @author 蔡任骋 * @version 1.0 * @since 2020/09/21 */ @Controller @RequestMapping("/depositInterestAccrualController") public class DepositInterestAccrualController { @Autowired private DepositInterestAccrualBiz depositInterestAccrualBiz; @Autowired private LayuiFormat layuiFormat; /** * 1.根据条件查询证券库存表中的银行交易数据 * @param securitiesInventoryPaging 包含条件的POJO类 * @return 成功返回一个JSON格式的数据 */ @ResponseBody @RequestMapping("/findSecuritiesInventoryByCondition") public LayuiFormat findSecuritiesInventoryByCondition(SecuritiesInventoryPaging securitiesInventoryPaging){ //调用持久层方法查询满足条件的证券库存数 long count = depositInterestAccrualBiz.countDepositInterestAccrualByCondition(securitiesInventoryPaging); List<SecuritiesInventory> securitiesInventoryList = depositInterestAccrualBiz.findSecuritiesInventoryByCondition(securitiesInventoryPaging); if(CollectionUtils.isEmpty(securitiesInventoryList)){ layuiFormat.setCode(0); layuiFormat.setCount(0L); layuiFormat.setMsg("失败"); layuiFormat.setData(null); } layuiFormat.setCode(0); layuiFormat.setCount(count); layuiFormat.setMsg("成功"); layuiFormat.setData(securitiesInventoryList); return layuiFormat; }; /** * 2.存款计息 * @param securitiesInventoryIds 证券库存中银行存款数据Id * @param tradeStatus 计息状态 * @return 成功返回true,否则返回false */ @ResponseBody @RequestMapping("/depositInterestAccrual") public boolean depositInterestAccrual(String securitiesInventoryIds,String tradeStatus){ //调用存款计息业务逻辑层的存款计息方法 boolean result = depositInterestAccrualBiz.depositInterestAccrualByCondition(securitiesInventoryIds,tradeStatus); return result; }; } <file_sep>/fa-base/src/main/java/com/yidu/stock/service/impl/StockServiceImpl.java package com.yidu.stock.service.impl; import com.yidu.stock.service.StockService; import com.yidu.stock.dao.StockDao; import com.yidu.stock.domain.Stock; import com.yidu.utils.IDUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; @Service("StockService") public class StockServiceImpl implements StockService { @Autowired private StockDao stockDao; @Override public List<Stock> queryAllStock() { return stockDao.findAllStock(); } @Override public Long countStockByCondition(Map<String, Object> paramMap) { return stockDao.countStockByCondition(paramMap); } @Override public List<Stock> findStockByCondition(Map<String, Object> paramMap) { return stockDao.findStockByCondition(paramMap); } @Override public boolean addStock(Stock stock) { //添加id stock.setStockId(IDUtil.getUuid()); stock.setUsable("Y"); System.out.println(stock); return stockDao.addStock(stock); } @Override public boolean updateStock(Stock stock) { System.out.println(stock); return stockDao.updateStock(stock); } @Override public boolean updateStockStatus(String stockCodes, String usable) { //分割用户Id String[] ids = stockCodes.split(","); System.out.println(ids); //定义修改状态的参数Map集合 Map<String,Object> paramMap = new HashMap<String, Object>(); //定义修改结果 boolean result = false; paramMap.put("usable",usable); for (String stockCode : ids) { paramMap.put("stockCode",stockCode); System.out.println(paramMap); result = stockDao.updateStockStatus(paramMap); // if (!result) throw new RuntimeException(""); } return result; } } <file_sep>/fa-sys/src/main/java/com/yidu/security/demo.java package com.yidu.security; /** * 类的描述: * * @author wh * @since 2020/9/2 17:08 */ public class demo { } <file_sep>/fa-web/src/main/java/com/yidu/stock/Listener/DataListener.java package com.yidu.stock.Listener; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.yidu.stock.domain.StockTrade; import com.yidu.stock.service.StockLogicalService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; // 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去 public class DataListener extends AnalysisEventListener<StockTrade> { private StockLogicalService stockLogicalService; private static final Logger LOGGER = LoggerFactory.getLogger(DataListener.class); /** * 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收 */ private static final int BATCH_COUNT = 5; List<StockTrade> list = new ArrayList<StockTrade>(); /** * 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。 */ /*public DataListener() { // 这里是demo,所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数 demoDAO = new DemoDAO(); }*/ /** * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来 * * @param stockLogicalService */ public DataListener(StockLogicalService stockLogicalService) { this.stockLogicalService = stockLogicalService; } /** * 这个每一条数据解析都会来调用 * * @param stockTrade * one row value. Is is same as {@link AnalysisContext#readRowHolder()} * @param context */ @Override public void invoke(StockTrade stockTrade, AnalysisContext context) { list.add(stockTrade); // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM if (list.size() >= BATCH_COUNT) { saveData(list); // 存储完成清理 list list.clear(); } } /** * 所有数据解析完成了 都会来调用 * * @param context */ @Override public void doAfterAllAnalysed(AnalysisContext context) { // 这里也要保存数据,确保最后遗留的数据也存储到数据库 saveData(list); LOGGER.info("所有数据解析完成!"); } /** * 加上存储数据库 */ private void saveData(List<StockTrade> stockTrades) { for(StockTrade stockTrade:stockTrades){ System.out.println(stockTrade); stockLogicalService.addStockTrade(stockTrade); } System.out.println("存储数据"); } }<file_sep>/fa-web/src/main/java/com/yidu/fund/controller/FundController.java package com.yidu.fund.controller; import com.yidu.format.LayuiFormat; import com.yidu.fund.domain.Fund; import com.yidu.fund.paging.FundPaging; import com.yidu.fund.service.FundService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * 类的描述: * * @Author 李昊林 * @Date 2020/9/3 8:32 */ @Controller public class FundController { @Autowired private FundService fundService; @ResponseBody @RequestMapping("/findAllFund") public LayuiFormat findAllFund(FundPaging fundPaging){ return fundService.findAllFundWithPage(fundPaging); } @ResponseBody @RequestMapping("/findFundByCondition") public LayuiFormat findFundByCondition(FundPaging fundPaging){ return fundService.findFundByCondition(fundPaging); } @ResponseBody @RequestMapping("/updateFundStatus/{fundId}/{usable}") public Map<String,String> updateFundStatus(@PathVariable("fundId") String fundId, @PathVariable("usable") String usable){ boolean result = fundService.updateFundStatus(fundId,usable); Map<String,String> resultMap = new HashMap<>(); if(result){ resultMap.put("result","1"); }else{ resultMap.put("result","0"); } return resultMap; } @ResponseBody @RequestMapping("/findUserAndFundCompany") public Map<String,Object> findUserAndFundCompany(){ return fundService.findUserAndFundCompany(); } @ResponseBody @RequestMapping("/saveFund") public Map<String,Object> saveFund(Fund fund){ return fundService.addFund(fund); } @ResponseBody @RequestMapping("/updateFund") public int updateFund(Fund fund){ return fundService.updateFund(fund); } } <file_sep>/fa-base/src/main/java/com/yidu/deposit/dao/CashInventoryDao.java package com.yidu.deposit.dao; import com.yidu.deposit.paging.CashInventoryPaging; import com.yidu.deposit.domain.CashInventory; import java.util.List; /** * 类的描述:现金库存持久层接口 * * @author wh * @since 2020/9/11 14:38 */ public interface CashInventoryDao { /** * 模糊加分页查询所有现金库存 * @param cashInventoryPaging 现金库存对象 * @return 金库存数据集合 */ List<CashInventory> findAll(CashInventoryPaging cashInventoryPaging); /** * 模糊加分页查询所有现金库存数量 * @param cashInventoryPaging 现金库存对象 * @return 现金库存数据条数 */ Long findCashInventoryCount(CashInventoryPaging cashInventoryPaging); /** * 根据id查询现金库存 * @param cashInventoryId 现金库存id * @return 现金库存对象 */ CashInventory fundCashInventoryById(String cashInventoryId); } <file_sep>/fa-base/src/main/java/com/yidu/bond/dao/BondDao.java package com.yidu.bond.dao; import com.yidu.bond.domain.Bond; import com.yidu.bond.domain.BondTrade; import com.yidu.bond.paging.BondPaging; import com.yidu.bond.paging.BondTradePaging; import com.yidu.format.LayuiFormat; import org.apache.ibatis.annotations.Param; import java.math.BigInteger; import java.util.List; /** * 类的描述:债券 数据操作类 * * @author wh * @since 2020/9/3 10:10 */ public interface BondDao { /** * 查询所有债券对象 * @return 债券对象集合 */ List<Bond> findAll(BondPaging bondPaging); /** * 条件查询的数据条数 * @return 数据条数 */ Long findCount(BondPaging bondPaging); /** * 添加债券 * @param bond 债券对象 * @return 是否添加成功 1:添加成功,0:添加失败 */ int addBond(Bond bond); /** * 修改债券 * @param bond 修改对象 * @return 1:修改成功,0:修改失败 */ int updateBond(Bond bond); /** * 修改债券是否可用 * @param usable 是否可用参数 * @param bondId 修改的id * @return 是否都修改成功 */ int updateUsable(@Param("usable") String usable, @Param("bondId") String bondId); } <file_sep>/fa-base/src/main/java/com/yidu/fund/dao/FundDao.java package com.yidu.fund.dao; import com.yidu.deposit.domain.CashInventory; import com.yidu.deposit.domain.FundInventory; import com.yidu.fund.domain.Fund; import com.yidu.fund.paging.FundPaging; import com.yidu.manage.domain.Account; import com.yidu.manage.domain.FundCompany; import javax.security.auth.login.AccountException; import java.util.List; import java.util.Map; /** * 类的描述: * * @Author 李昊林 * @Date 2020/9/3 8:34 */ public interface FundDao { /** * 查询所有基金信息并分页 * @return 基金对象集合 */ List<Fund> findAllFundWithPage(FundPaging fundPaging); /** * 根据基金id查询基金信息 * @param fundId 基金id * @return 基金对象 */ Fund findFundById(String fundId); /** * 根据条件查询基金信息 * @param fundPaging 查询条件 * @return 基金对象集合 */ List<Fund> findFundByCondition(FundPaging fundPaging); /** * 根据条件统计基金信息条数 * @param fundPaging 查询条件 * @return 基金对象 */ Long countFundByCondition(FundPaging fundPaging); /** * 添加基金信息 * @param fund 基金对象 * @return 成功添加返回true,否则返回false */ boolean addFund(Fund fund); /** * 修改基金信息 * @param fund 基金对象 * @return 成功修改返回true,否则返回false */ boolean updateFund(Fund fund); /** * 修改基金可用状态 * @param paramMap 修改基金Id和状态信息 * @return 成功修改返回true,否则返回false */ boolean updateFundStatus(Map<String,Object> paramMap); /** * 添加基金库存信息 * @param fundInventory 基金库存信息对象 * @return 添加成功返回true,否则返回false */ boolean addFundInventory(FundInventory fundInventory); /** * 根据基金Id查询对应的账户信息 * @param fundNo 基金编号 * @return 账户对象 */ Account findAccountByFundId(String fundNo); /** * 查询所有基金公司 * @return 基金公司对象 */ List<FundCompany> findAllFundCompany(); /** * 添加现金库存信息 * @param cashInventory 现金库存对象 * @return 添加成功返回true,否则返回false */ boolean addCashInventory(CashInventory cashInventory); } <file_sep>/fa-web/src/main/java/com/yidu/account/controller/AccountController.java package com.yidu.account.controller; import com.yidu.account.domain.Account; import com.yidu.account.paging.AccountPaging; import com.yidu.account.service.AccountBiz; import com.yidu.format.LayuiFormat; import com.yidu.utils.IDUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 类的描述:... * * @author 蔡任骋 * @version 1.0 * @since 2020/09/03 */ @Controller @RequestMapping("/accountController") public class AccountController { @Autowired private AccountBiz accountBiz; @Autowired private LayuiFormat layuiFormat; /** * 查询所有现金账户,并分页 * @param page 页数 * @param limit 页面数据行数 * @return 成功返回一个JSON格式的数据 */ @ResponseBody @RequestMapping("/findAllAccount") public LayuiFormat findAllAccount(int page,int limit){ //处理请求数据 Map<String,Object> map = new HashMap(); map.put("page",(page-1)*limit); map.put("limit",limit); System.out.println(map.get("page") + "||||||||" + map.get("limit")); //调用Biz层countAccountByCondition方法查询所有现金账户的数量 Long count = accountBiz.countAccountByCondition(map); //调用Biz层findAccountByConditionWithPaging方法查询所有现金账户 List<Account> accountByConditionWithPaging = accountBiz.findAccountByConditionWithPaging(map); //将数据处理成前端需要的JSON格式 layuiFormat.setCode(0); layuiFormat.setCount(count); layuiFormat.setMsg("成功"); layuiFormat.setData(accountByConditionWithPaging); return layuiFormat; } /** * 2.多条件组合查询 * @param accountPaging 包含条件的实体类 * @return 成功返回一个JSON格式的数据 */ @RequestMapping("/findAccountByCondition") @ResponseBody public LayuiFormat findAccountByCondition(AccountPaging accountPaging){ //处理请求数据 Map<String,Object> map = new HashMap<>(); map.put("page",(accountPaging.getPage()-1)*accountPaging.getLimit()); map.put("limit",accountPaging.getLimit()); map.put("accountName",accountPaging.getAccountName()); map.put("depositType",accountPaging.getDepositType()); map.put("bankName",accountPaging.getBankName()); //调用Biz层countAccountByCondition方法查询满足条件的现金账户的数量 Long count = accountBiz.countAccountByCondition(map); //调用Biz层findAccountByConditionWithPaging方法查询满足条件现金账户 List<Account> accountByConditionWithPaging = accountBiz.findAccountByConditionWithPaging(map); //将数据处理成前端需要的JSON格式 layuiFormat.setCode(0); layuiFormat.setCount(count); layuiFormat.setMsg("成功"); layuiFormat.setData(accountByConditionWithPaging); return layuiFormat; } /** * 3.添加现金账户 * @param account 要添加的现金账户 * @return 成功返回1.否则返回0 */ @RequestMapping("/addAccount") @ResponseBody public int addAccount(Account account){ account.setAccountId(IDUtil.getUuid()); return accountBiz.addAccount(account); } /** * 4.修改现金账户 * @param account 要修改的现金账户 * @return 成功返回1,否则返回0 */ @ResponseBody @RequestMapping("/updateAccount") public int updateAccount(Account account){ return accountBiz.updateAccount(account); } @RequestMapping(value = "/updateAccountStatus/{accountIds}/{usable}",method = RequestMethod.DELETE) @ResponseBody public Map<String,Object> updateAccountStatus(@PathVariable("accountIds") String accountIds,@PathVariable("usable") String usable){ System.out.println(accountIds + " ......"+usable); Map<String, Object> returnMap = new HashMap<String, Object>(); if (accountBiz.updateAccountStatus(accountIds,usable)) { returnMap.put("result", 1); } else { returnMap.put("result", 0); } return returnMap; } } <file_sep>/fa-web/src/main/webapp/static/index/js/login.js //layui初始化表格模组 layui.use(['laydate', 'util'],function () { var $ = layui.jquery; $("#imgRefresh").click(function () { $(this).attr("src","../../loginCodeServlet?"+ new Date().getTime()); }); $("#submit").submit(function () { var userName = $("#userName").val(); var password = $("#password").val(); var vercode = $("#vercode").val(); $.get("../../userController",{biz:"login",userName:userName,password:password,vercode:vercode},function (data) { if(data.flag){//登录成功 $("#msg").html(""); window.location.href="../admin.html"; }else { //登录失败 $("#msg").html(data.msg); $("#imgRefresh").attr("src","../../loginCodeServlet?"+ new Date().getTime()); } }); return false; }); $("#userName").blur(function () { if(!checkuser()){ $("#usermsg").html("用户名格式错误(8—20字符,非空格)"); }else { $("#usermsg").html(""); } }); $("#password").blur(function () { if(!password()){ $("#pwdmsg").html("密码格式错误(8—20字符,非空格)"); }else { $("#pwdmsg").html(""); } }); //验证用户名 function checkuser() { //获取表单用户名 var username = $("#userName").val(); //定义正则 var reg_username = /^\w{8,20}$/; //3.判断,给出提示信息 var flag = reg_username.test(username); return flag; } //验证密码 function password(){ //获取表单用户名 var password = $("#password").val(); //定义正则 var reg_password = /^\w{8,20}$/; //3.判断,给出提示信息 var flag = reg_password.test(password); return flag; } });<file_sep>/fa-base/src/main/java/com/yidu/fund/service/impl/CalculateRevenueServiceImpl.java package com.yidu.fund.service.impl; import com.yidu.deposit.dao.CashInventoryDao; import com.yidu.deposit.dao.FundInventoryDao; import com.yidu.deposit.domain.CashArap; import com.yidu.deposit.domain.CashInventory; import com.yidu.deposit.domain.CasharapInventory; import com.yidu.deposit.domain.FundInventory; import com.yidu.deposit.paging.CashInventoryPaging; import com.yidu.deposit.paging.FundInventoryPaging; import com.yidu.deposit.service.CashInventoryService; import com.yidu.fund.dao.CalculateRevenueDao; import com.yidu.fund.dao.FundDao; import com.yidu.fund.domain.Fund; import com.yidu.fund.paging.CalculateRevenuePaging; import com.yidu.fund.service.CalculateRevenueService; import com.yidu.manage.domain.Account; import com.yidu.utils.IDUtil; import com.yidu.utils.NoUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.*; /** * 类的描述:收益计提业务层 * @Author 李昊林 * @Date 2020/9/17 11:16 */ @Service public class CalculateRevenueServiceImpl implements CalculateRevenueService { @Autowired private CalculateRevenueDao calculateRevenueDao; @Autowired private FundInventoryDao fundInventoryDao; @Autowired private CashInventoryDao cashInventoryDao; @Autowired private FundDao fundDao; @Override public List<FundInventory> findFundInventoryByCondition(FundInventoryPaging fundInventoryPaging) { return calculateRevenueDao.findAllFIByConditionForNotAccrual(fundInventoryPaging); } @Override public Long findCountFundInventoryByCondition(FundInventoryPaging fundInventoryPaging) { return calculateRevenueDao.findCountByConditionForNotAccrual(fundInventoryPaging); } @Override public boolean doFeeCalculate(String fundInventoryIds){ //分割基金库存id字符串 String[] ids = fundInventoryIds.split(","); //声明计提结果变量 boolean accrualResult = false; //遍历基金库存id查询基金库存对象封装到集合中 for (String fundInventoryId : ids) { //获取基金库存对象 FundInventory fundInventory = fundInventoryDao.findFundInventoryById(fundInventoryId); //获取基金对象 Fund fund = fundDao.findFundById(fundInventory.getFundId()); //调用计提方法 accrualResult = doAccrual(fundInventory,fund); } return accrualResult; } /** * 计提业务操作 * @param fundInventory 基金库存对象 * @param fund 基金对象 * @return 计提成功返回true,否则返回false */ private boolean doAccrual(FundInventory fundInventory,Fund fund){ //获取账户信息 Account account = calculateRevenueDao.findAccountByFundId(fund.getFundId()); //获取基金库存余额 BigDecimal balance = fundInventory.getBalance(); //获取基金表中的计费有效天数 int billingDays = fund.getBillingDays(); //获取基金表中的托管费率 BigDecimal trusteeFee = fund.getTrusteeFee(); //获取基金表的中管理费率 BigDecimal managementFee = fund.getManagementFee(); //计算托管费用 BigDecimal calcTrusteeFee = balance.multiply(trusteeFee).divide(new BigDecimal("1000"),BigDecimal.ROUND_UNNECESSARY).divide(new BigDecimal(billingDays),4,BigDecimal.ROUND_HALF_UP); //计算管理费用 BigDecimal calcManagementFee = balance.multiply(managementFee).divide(new BigDecimal("1000"),BigDecimal.ROUND_UNNECESSARY).divide(new BigDecimal(billingDays),4,BigDecimal.ROUND_HALF_UP); //设置现金应收应付对象 CashArap cashArap = new CashArap(); cashArap.setCashArapId(IDUtil.getUuid()); cashArap.setCashArapNo(NoUtils.getNo("XJYSYF")); cashArap.setFundId(fund.getFundId()); cashArap.setFundNo(fund.getFundNo()); cashArap.setFundName(fund.getFundName()); cashArap.setAccountId(account.getAccountId()); cashArap.setAccountNo(account.getAccountNo()); cashArap.setAccountName(account.getAccountName()); cashArap.setArapDate(new Date()); //设置托管费 cashArap.setArapAmount(calcTrusteeFee); //设置应收应付标识:2应付 cashArap.setArapFlag(2); //设置应收应付类型为托管费3 cashArap.setArapType(3); //往现金应收应付表中插入托管费 boolean addTrusteeFeeResult = calculateRevenueDao.addCashArap(cashArap); //调用处理现金应收应付库存业务方法操作托管费 boolean PCIBTFResult = processingCasharapInventoryBusiness(cashArap); cashArap.setCashArapId(IDUtil.getUuid()); cashArap.setCashArapNo(NoUtils.getNo("XJYSYF")); //设置管理费 cashArap.setArapAmount(calcManagementFee); //设置应收应付类型为管理费4 cashArap.setArapType(4); //往现金应收应付表中插入管理费 boolean addManagementFeeResult = calculateRevenueDao.addCashArap(cashArap); //调用处理现金应收应付库存业务方法操作管理费 boolean PCIBMFResult = processingCasharapInventoryBusiness(cashArap); //修改基金库存计提状态 boolean updateAccrualStatusResult = calculateRevenueDao.updateAccrualStatus(fundInventory.getFundInventoryId()); return addTrusteeFeeResult && PCIBTFResult && addManagementFeeResult && PCIBMFResult && updateAccrualStatusResult; } /** * 处理现金应收应付库存数据业务 * @param cashArap 现金应收应付对象 * @return 处理成功返回true,否则返回false */ private boolean processingCasharapInventoryBusiness(CashArap cashArap){ //定义查询参数map Map<String,Object> paramMap = new HashMap<>(); //准备查询参数 paramMap.put("fundId",cashArap.getFundId()); paramMap.put("businessType",cashArap.getArapType()); paramMap.put("businessDate",cashArap.getArapDate()); //声明操作结果变量 boolean result = false; //查询现金应收应付库存中是否有指定基金指定业务类型当天的应收应付库存数据 CasharapInventory casharapInventory = calculateRevenueDao.findCARAPIByFundIdAndBusinessType(paramMap); if (casharapInventory != null) { //累加指定业务类型的数据 casharapInventory.setBalance(casharapInventory.getBalance().add(cashArap.getArapAmount())); casharapInventory.setBusinessDate(cashArap.getArapDate()); result = calculateRevenueDao.updateCasharapInventory(casharapInventory); }else{ //查询最近日期的指定基金指定业务的现金应收应付库存数据 CasharapInventory addCasharapInventory = calculateRevenueDao.findCARAPIByLatestDateWithFundIdAndBusinessType(paramMap); if (null == addCasharapInventory) { addCasharapInventory = new CasharapInventory(); addCasharapInventory.setFundId(cashArap.getFundId()); addCasharapInventory.setFundNo(cashArap.getFundNo()); addCasharapInventory.setFundName(cashArap.getFundName()); addCasharapInventory.setAccountId(cashArap.getAccountId()); addCasharapInventory.setAccountNo(cashArap.getAccountNo()); addCasharapInventory.setAccountName(cashArap.getAccountName()); //设置初始值,避免累加出现空指针 addCasharapInventory.setBalance(new BigDecimal("0")); addCasharapInventory.setBusinessType(cashArap.getArapType()); addCasharapInventory.setFlag(cashArap.getArapFlag()); } //根据现金应收应付数据对应设置新添加现金应收应付库存数据 addCasharapInventory.setCachArapInventoryId(IDUtil.getUuid()); addCasharapInventory.setCachArapInventoryNo(NoUtils.getNo("XJYSYFKC")); //累加最近日期的余额 addCasharapInventory.setBalance(addCasharapInventory.getBalance().add(cashArap.getArapAmount())); addCasharapInventory.setBusinessDate(new Date()); //往数据库中新增现金应收应付库存数据 result= calculateRevenueDao.addCasharapInventory(addCasharapInventory); } return result; } @Override public List<CashInventory> findCashInventoryByCondition(CashInventoryPaging cashInventoryPaging) { cashInventoryPaging.setPage((cashInventoryPaging.getPage()-1)*cashInventoryPaging.getLimit()); return calculateRevenueDao.findAllCIByConditionForNotInterest(cashInventoryPaging); } @Override public Long findCountCashInventoryByCondition(CashInventoryPaging cashInventoryPaging) { return calculateRevenueDao.findCountByConditionForNotInterest(cashInventoryPaging); } @Override public boolean doCashInterest(String cashInventoryIds) { //分割现金库存id字符串 String[] ids = cashInventoryIds.split(","); //声明添加利息结果变量 boolean addInterestResult = false; //声明添加现金应收应付库存结果变量 boolean PCIBTFResult = false; //声明修改现金计息状态结果变量 boolean updateInterestStatusResult = false; //遍历现金库存id查询现金库存 for (String cashInventoryId : ids) { CashInventory cashInventory = cashInventoryDao.fundCashInventoryById(cashInventoryId); //获取基金对象 Fund fund = fundDao.findFundById(cashInventory.getFundId()); //获取基金表中的计费有效天数 int billingDays = fund.getBillingDays(); //计息 现金库存余额*利率0.35÷计费有效天数 BigDecimal interest = cashInventory.getCashBalance().multiply(new BigDecimal("0.35")).divide(new BigDecimal(billingDays),4,BigDecimal.ROUND_HALF_UP); //设置现金应收应付对象 CashArap cashArap = new CashArap(); cashArap.setCashArapId(IDUtil.getUuid()); cashArap.setCashArapNo(NoUtils.getNo("XJYSYF")); cashArap.setFundId(cashInventory.getFundId()); cashArap.setFundNo(cashInventory.getFundNo()); cashArap.setFundName(cashInventory.getFundName()); cashArap.setAccountId(cashInventory.getAccountId()); cashArap.setAccountNo(cashInventory.getAccountNo()); cashArap.setAccountName(cashInventory.getAccountName()); cashArap.setArapDate(new Date()); //往现金应收应付余额中设置存款利息 cashArap.setArapAmount(interest); //设置应收应付标识:1应收 cashArap.setArapFlag(1); //设置应收应付类型为存款利息2 cashArap.setArapType(2); //往现金应收应付表中插入存款利息 addInterestResult = calculateRevenueDao.addCashArap(cashArap); //调用处理现金应收应付库存业务方法操作托管费 PCIBTFResult = processingCasharapInventoryBusiness(cashArap); //修改现金库存计息状态 updateInterestStatusResult = calculateRevenueDao.updateInterestStatus(cashInventory.getCashInventoryId()); } return addInterestResult && PCIBTFResult && updateInterestStatusResult; } } <file_sep>/fa-web/src/main/webapp/static/bond/js/bonds.js /* * layui引入样式的两种方式:模块化用和全模块用法 * layui的初始化模块可以理解为,引入这个模块的js文件 * 值得注意的是:layui的模块之间存在依赖关系,例如引入了table模块,它会layui/lay/moudules/table.js * 这个文件引入进来,并且它还会将这个模块所依赖的其他模块自动加入进来, * 实际引入的模块有:table、form、jquery、layer、laypage、laytpl、util,7个js文件 * 所以我仅仅初始化了table模块,却能获得form、jquery、layer的模块对象 */ //layui初始化表格模组 layui.use(['table', 'laydate', 'util', 'upload'], function() { // 获得模块对象 var table = layui.table; var form = layui.form; var $ = layui.jquery; var layer = layui.layer; var laydate = layui.laydate; var util = layui.util; var upload = layui.upload; //判断点击的”添加“操作还是“修改”操作 var addAndEdit = ""; // 全局的对象,存放选中行的dom元素 var checkElem; //下拉搜索框设置 var hideBtn = $("#hideBtn"); var flag = false; var search_header = $("#search-header"); search_header.css("top",-search_header.height()); hideBtn.click(function () { let height = search_header.height(); if(flag){ search_header.animate({ "top":-height },"fast","linear"); flag = false; }else { search_header.animate({ "top":0 },"fast","linear"); flag = true; } /*if(flag){ } search_header.css("top",-height);*/ }); //----1.用户数据表格渲染------------------------------------------------------------------ table.render({ elem: '#bondTable', url: '../bond/list', //后期改回获取用户列表的后端程序的url method: 'post', height: 'full-10', where: {}, // 你额外要携带数据,以键值对的方式存入 toolbar: '#userToolbar', // 开启头部工具栏,并为其绑定左侧模板 // cellMinWidth: 80, // 全局定义所有常规单元格的最小宽度(默认:60) cellMaxWidth: 200, page: true, // 开启分页 limit: 10, // 每页显示的条数 limits: [5,10, 20, 50, 100], // 每页条数的选择项 loading: true, // 是否显示加载条(切换分页的时候显示) title: '用户表', // 定义 table 的大标题(在文件导出等地方会用到) id: 'bondTable', // 设定容器唯一 id // 隔行变色 even: false, cols: [ [{ title:'序列', type: 'numbers', fixed:'left', //钉在左侧 }, // 序号 { type: 'checkbox', fixed:'left', //钉在左侧 }, //复选框 { field:'bondId', title:'债券Id', fixed:'left', //钉在左侧 hide: true, //一般情况下不显示用户ID align:'center', width: 100 }, { field: 'bondCode', title: '债券代码', fixed:'left', //钉在左侧 align: "center", width: 100 }, { field: 'bondShortName', title: '债券简称', fixed:'left', align: "center", width: 100 }, { field: 'actualIssuance', title: '发行量(亿元)', sort: true, align: "center", width: 160 }, { field: 'issuePrice', title: '发行价格', sort: true, align: "center", width: 130 }, { field: 'par', title: '票面价值', sort: true, align: "center", width: 130 }, { field: 'term', title: '期限(年)', sort: true, align: "center", width: 130 }, { field: 'paymentFrequency', title: '付息方式', align: "center", width: 140 }, { field: 'valueDateStr', title: '起息日期', align: "center", width: 130 }, { field: 'expireDateStr', title: '到期日期', align: "center", width: 130 }, { field: 'couponRate', title: '票面利率', sort: true, align: "center", width: 150 }, { field: 'bondFullName', title: '债券全称', align: "center", width: 150 }, { field: 'description', title: '备注', align: "center", width: 150 }, { field: 'usable', title: '是否可用', fixed:'right', align: "center", width: 95, templet: function (data) { if(data.usable == "1"){ return '<span class="useable font-color my-bg-green">可用</span>'; }else { return '<span class="useable font-color my-bg-red1">弃用</span>'; } } } ] ] }); //----1.用户数据表格渲染------------------------------------------------------------------ //----2.添加用户入职时间选择器-------------------------------------------------------------------- laydate.render({ elem: '#addExpireDate' }); //修改用户入职时间选择器 laydate.render({ elem: '#addValueDate' }); //----3.处理头部条件组合搜素------------------------------------------------------------------ form.on('submit(SearchBtn)', function(data) { //将搜索下列框收回 let height = search_header.height(); if(flag){ search_header.animate({ "top":-height },"fast","linear"); flag = false; }else { search_header.animate({ "top":0 },"fast","linear"); flag = true; } // 搜索并刷新数据表格 table.reload('bondTable', { url: '../bond/list', // where: data.field, page: { curr: 1 //从第一页开始 }, limit: 10 }); return false; // 阻止表单跳转。 }); //债券添加或修改按钮时间 form.on('submit(addBtn)', function(data) { //通知进行的操作是添加“操作” if(addAndEdit == "add"){ $.ajax({ url:'../bond/add',// type: 'post', data: data.field, success:function (obj) { layer.closeAll(); if(obj == 1){ addOpen.close(); layer.msg("添加成功!", { icon: 1 // 图标,可输入范围0~6 }); }else{ layer.msg("添加出错!", { icon: 2 // 图标,可输入范围0~6 }); } } }); // 刷新数据表格 table.reload('bondTable', { url: '../bond/list' // }); } if(addAndEdit == "edit"){ $.ajax({ type: 'POST', //适用RESTful风格的添加: 查询GET、添加POST、更新PUT、删除DELETE async: false, url: '../bond/update', //后期改为添加用户的后台程序的url data: data.field, success: function(obj) { // 关闭页面上所有类型的所有弹框 layer.closeAll(); if(obj == 1) { layer.msg("修改成功!", { icon: 1 // 图标,可输入范围0~6 }); // 修改行数据 let a = checkElem.children("[data-field='bondCode']").children().html(); alert(a); } else { layer.msg("修改失败!", { icon: 2 // 图标,可输入范围0~6 }); } } }); } return false; // 阻止表单跳转 }); //----3.处理表行修改------------------------------------------------------------------ table.on("tool(bondTableEvent)",function (obj) { var data = obj.data; console.log(data); if (obj.event == "update"){ initUpdateUserModal(data); } }); // 用户列表头部工具栏添加|修改|删除(逻辑删除)|恢复按钮的事件句柄绑定 table.on('toolbar(bondTableEvent)', function(obj) { //获取当前表格选中状态和选中的一行dom元素 // checkElem = table.checkStatus(obj.tr); // 获取当前表格选中状态和选中的数据 var checkStatus = table.checkStatus(obj.config.id); // console.log(obj); // console.log(checkStatus); // console.log(checkStatus.data[0].bondId); // 区分点击的按钮 /*obj.update({ bondCode: "sd" });*/ // 定义一个要删除的所有资源ID的字符串 let idStr = ""; switch(obj.event) { case 'addUser': // 弹出新增模态框 initAddModal(); break; case 'updateUser': // 选择的数据数量 if(checkStatus.data.length > 1) { layer.msg("最多只能修改一行数据哦!!", { icon: 4 //图标,可输入范围0~6 }); } else if(checkStatus.data.length < 1) { layer.msg("请选择要修改的数据哦!!", { icon: 4 //图标,可输入范围0~6 }); } else if(checkStatus.data[0].usable == '0') { layer.msg("该用户被弃用了哦!!", { icon: 4 //图标,可输入范围0~6 }); } else { // 弹出修改模态框,传递当前选中的一行数据过去 initUpdateUserModal(checkStatus.data[0]); } break; case 'frozenRecord': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要弃用的债券!!", { icon: 4 //图标,可输入范围0~6 }); return; } // 遍历传递过来的要删除的数据 for(var i = 0; i < data.length; i++) { if(data[i].usable == '0') { layer.msg("所选的债券已经被弃用!", { icon: 4 // 图标,可输入范围0~6 }); return; } // 拿出用户ID进行拼接 idStr += data[i].bondId + ","; } // 截取掉因为拼接产生的多余的一个逗号 idStr = idStr.substring(0, idStr.length - 1); frozenORrecoverArchives(idStr, '0'); break; case 'restoreRecord': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要还原的债券!!", { icon: 4 //图标,可输入范围0~6 }); return; } // 遍历传递过来的要删除的数据 for(var i = 0; i < data.length; i++) { if(data[i].usable == '1') { layer.msg("所选债券是可用的,无需修改!", { icon: 4 // 图标,可输入范围0~6 }); return; } // 拿出资源ID进行拼接 idStr += data[i].bondId + ","; } // 截取掉因为拼接产生的多余的一个逗号 idStr = idStr.substring(0, idStr.length - 1); frozenORrecoverArchives(idStr, '1'); break; }; }); // 监听锁定操作 form.on('switch(usable)', function(obj) { frozenORrecoverArchives(obj.value, this.checked == true ? 'Y' : 'N'); }); // 定义弃用或还原的方法 var frozenORrecoverArchives = function(bondIds, usable) { // 定义提示信息, 状态 var msg; if(usable == '1') { msg = "还原"; } else { msg = "弃用"; } // 发送异步请求冻结或还原资源 $.ajax({ async: false, // 默认为true,false表示同步,如果当前请求没有返回则不执行后续代码 type: "post", url:'../bond/updateUsable' ,// /updateUser '/updateUserStatus/' + userIds + "/" + usable data: { bondIds:bondIds, usable:usable }, success: function(data) { if(data == "1") { layer.msg(msg + "成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg(msg + "失败!", { icon: 2 }); } // 刷新数据表格 table.reload('bondTable', { url: '../bond/list' }); } }); }; // var hiddeDisable = function(){ // // } // 初始化新增模态框 var initAddModal = function() { // 弹出一个页面层 addAndEdit = "add"; layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '添加债券', // 标题 skin: "layui-layer-molv", anim: 2, // 弹出动画 area: ["100%","100%"], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#addModal"), // 文本、html都行 resize: false, // 是否允许拉伸 end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) // 清空表单 $("#addForm")[0].reset(); } }); } // 初始化修改模态框 var initUpdateUserModal = function(data) { //通知进行的操作是修改“操作” addAndEdit = "edit"; // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '修改用户', // 标题 skin: "layui-layer-molv", anim: 2, // 弹出动画 area: ["100%","100%"], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#addModal"), // 文本、html都行 resize: false, // 是否允许拉伸 end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) // 清空表单 $("#addForm")[0].reset(); } }); // 表单赋值 form.val('addForm', { bondId:data.bondId, bondCode:data.bondCode, bondShortName:data.bondShortName, actualIssuance:data.actualIssuance, issuePrice:data.issuePrice, par:data.par, term:data.term, paymentFrequency:data.paymentFrequency, valueDate:data.valueDateStr, expireDate:data.expireDateStr, couponRate:data.couponRate, bondFullName:data.bondFullName, description:data.description }); }; // $.ajax({ // url: '/findUserByConditionuuuu',//system/org', // dataType: 'json', // type: 'post', // success: function(data) { // $.each(data, function(index) { // var orgName = data[index].orgName; // var orgId = data[index].orgId; // /* var sdSdd = data[index].sdSdd; */ // // 头部的搜索 // $("#queryOrgName").append( // "<option value='" + orgName + "'>" + orgName + // "</option>"); // // 添加 // $("#addOrgName").append( // "<option value='" + orgId + "'>" + orgName + // "</option>"); // // 修改 // $("#updateOrgName").append( // "<option value='" + orgId + "'>" + orgName + // "</option>"); // // form.render()渲染将option添加进去 // form.render(); // }); // } // }); // 自定义表单校验 form.verify({ pass: [ /^[\S]{6,12}$/, '密码必须6到12位,且不能出现空格'], mobile: function(value) { var msg; $.ajax({ type: "POST", url: '/verifyTelephone',//system/toVerifyUserPhone async: false, // 使用同步的方法 data: { 'telephone': value }, dataType: 'json', success: function(result) { if(result.flag) { msg = result.msg; } } }); return msg; } }); }); <file_sep>/fa-web/src/main/webapp/static/stock/js/stock_trade.js /* * layui引入样式的两种方式:模块化用和全模块用法 * layui的初始化模块可以理解为,引入这个模块的js文件 * 值得注意的是:layui的模块之间存在依赖关系,例如引入了table模块,它会layui/lay/moudules/table.js * 这个文件引入进来,并且它还会将这个模块所依赖的其他模块自动加入进来, * 实际引入的模块有:table、form、jquery、layer、laypage、laytpl、util,7个js文件 * 所以我仅仅初始化了table模块,却能获得form、jquery、layer的模块对象 */ //layui初始化表格模组 layui.use(['table', 'laydate', 'util', 'upload'], function() { // 获得模块对象 var table = layui.table; var form = layui.form; var $ = layui.jquery; var layer = layui.layer; var laydate = layui.laydate; var util = layui.util; var upload = layui.upload; //下拉搜索框设置 var hideBtn = $("#hideBtn"); var flag = false; var search_header = $("#search-header"); search_header.css("top",-search_header.height()); hideBtn.click(function () { let height = search_header.height(); if(flag){ search_header.animate({ "top":-height },"fast","linear"); flag = false; }else { search_header.animate({ "top":0 },"fast","linear"); flag = true; } /*if(flag){ } search_header.css("top",-height);*/ }); //----1.数据表格渲染------------------------------------------------------------------ table.render({ elem: '#stockTable', url: '../stockTrade/list', //后期改回获取用户列表的后端程序的url method: 'post', height: 'full-10', where: {}, // 你额外要携带数据,以键值对的方式存入 toolbar: '#stockToolbar', // 开启头部工具栏,并为其绑定左侧模板 // cellMinWidth: 80, // 全局定义所有常规单元格的最小宽度(默认:60) cellMaxWidth: 200, page: true, // 开启分页 limit: 10, // 每页显示的条数 limits: [5,10, 20, 50, 100], // 每页条数的选择项 loading: true, // 是否显示加载条(切换分页的时候显示) title: '股票交易表', // 定义 table 的大标题(在文件导出等地方会用到) id: 'stockTable', // 设定容器唯一 id // 隔行变色 even: false, cols: [ [{ title:'序列', type: 'numbers', // fixed:'left', //钉在左侧 }, // 序号 { type: 'checkbox', }, //复选框 { field:'stockTradeId', title:'股票交易Id', hide: true, //一般情况下不显示ID align:'center', width: 200 }, { field: 'stockTradeNo', title: '股票交易编号', align: "center", width: 200 }, { field: 'fundId', title: '基金Id', hide: true, align: "center", width: 100 }, { field: 'fundNo', title: '基金代码', sort: true, align: "center", width: 160 }, { field: 'fundName', title: '基金名称', sort: true, align: "center", width: 200 }, { field: 'stockId', title: '股票Id', sort: true, hide: true, align: "center", width: 130 }, { field: 'stockCode', title: '股票代码', sort: true, align: "center", width: 130 }, { field: 'stockName', title: '股票名', align: "center", width: 140 }, { field: 'managerId', title: '基金经理Id', align: "center", hide: true, width: 130 }, { field: 'managerName', title: '基金经理', align: "center", width: 130 }, { field: 'brokerId', title: '券商Id', sort: true, hide: true, align: "center", width: 150 }, { field: 'brokerName', title: '券商名', align: "center", width: 200 }, { field: 'tradeType', title: '交易方式', align: "center", width: 150 }, { field: 'tradeFlag', title: '交易标识', align: "center", width: 150 }, { field: 'tradePrice', title: '交易价格(单价)', align: "center", width: 150 }, { field: 'tradeDate', title: '交易日期', align: "center", templet: function(data) { return formatChinaDate(data); }, width: 200 }, { field: 'share', title: '交易数量(份额)', align: "center", width: 150 }, { field: 'turnover', title: '交易额(总)', align: "center", width: 120 }, { field: 'stampTax', title: '印花费(国家)', align: "center", width: 150 }, { field: 'managementFees', title: '征管费(国家)', align: "center", width: 150 }, { field: 'transferFee', title: '过户费(交易所)', align: "center", width: 150 }, { field: 'commission', title: '佣金费用(券商)', align: "center", width: 150 }, { field: 'brokerage', title: '经手费(交易所)', align: "center", width: 150 }, { field: 'total', title: '总金额', align: "center", width: 120 }, { field: 'description', title: '备注', align: "center", width: 120 }, { field: 'tradeStatus', title: '交易状态', align: "center", width: 100, templet:function (data) { if(data.tradeStatus =='1'){ return '<span style="color: #3acc37">已结算</span>' }else if(data.tradeStatus =='0'){ return '<span style="color: #ff9960">未结算</span>' }else { return '<span style="color: #ff0800">数据有误</span>' } } } ] ] }); //拖拽上传 upload.render({ elem: '#addStockTrader' ,url: '../stockTrade/poi' //改成您自己的上传接口https://httpbin.org/post ,accept: 'file' //普通文件 ,done: function(data){ if(data == 1){ layer.closeAll(); //导入数据成功关闭弹出层 layer.msg('导入数据成功!'); // 刷新数据表格 table.reload('stockTable', { url: '../stockTrade/list' }); }else{ layer.msg("导入数据出错(检查文件格式是否正确)!!"); } } }); //----2.时间选择器-------------------------------------------------------------------- laydate.render({ elem: '#addExpireDate' }); //时间选择器 laydate.render({ elem: '#addValueDate' }); // 初始化新增模态框 var addStockTrader = function() { // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: 'Excel导入数据', // 标题 skin: 'layui-layer-molv', anim: 2, // 弹出动画 area: ["100%","100%"], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $('#addStockTrader'), // 文本、html都行 resize: false, // 是否允许拉伸 end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) //发送请求查询所有数据 } }); }; //修改日期格式(年,月,日) function formatChinaDate(data) { console.log(data); var oIssueDate = data.tradeDate; var oDate = new Date(oIssueDate); var sIssueDate = oDate.getFullYear() + "年" + (oDate.getMonth() + 1) + "月" + oDate.getDate() + "日"; return sIssueDate; } //----3.处理头部条件组合搜素------------------------------------------------------------------ form.on('submit(SearchBtn)', function(data) { //将搜索下列框收回 let height = search_header.height(); if(flag){ search_header.animate({ "top":-height },"fast","linear"); flag = false; }else { search_header.animate({ "top":0 },"fast","linear"); flag = true; } // 搜索并刷新数据表格 table.reload('stockTable', { url: '../stockTrade/list', // where: data.field, page: { curr: 1 //从第一页开始 }, limit: 10 }); return false; // 阻止表单跳转。 }); //----3.处理表行修改------------------------------------------------------------------ table.on("tool(bondTableEvent)",function (obj) { var data = obj.data; console.log(data); if (obj.event == "update"){ initUpdateUserModal(data); } }); // 用户列表头部工具栏添加|修改|删除(逻辑删除)|恢复按钮的事件句柄绑定 table.on('toolbar(stockTableEvent)', function(obj) { //获取当前表格选中状态和选中的一行dom元素 // checkElem = table.checkStatus(obj.tr); // 获取当前表格选中状态和选中的数据 var checkStatus = table.checkStatus(obj.config.id); // console.log(obj); // console.log(checkStatus); // console.log(checkStatus.data[0].bondId); // 区分点击的按钮 /*obj.update({ bondCode: "sd" });*/ // 定义一个要删除的所有资源ID的字符串 let idStr = ""; switch(obj.event) { case 'sd': // 弹出新增模态框 alert("sd"); // addBondTrader(); break; case 'updateUser': // 选择的数据数量 if(checkStatus.data.length > 1) { layer.msg("最多只能修改一行数据哦!!", { icon: 4 //图标,可输入范围0~6 }); } else if(checkStatus.data.length < 1) { layer.msg("请选择要修改的数据哦!!", { icon: 4 //图标,可输入范围0~6 }); } else if(checkStatus.data[0].usable == '0') { layer.msg("该用户被弃用了哦!!", { icon: 4 //图标,可输入范围0~6 }); } else { // 弹出修改模态框,传递当前选中的一行数据过去 initUpdateUserModal(checkStatus.data[0]); } break; case 'settlements': //结算 // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要结算的数据行!!", { icon: 4 //图标,可输入范围0~6 }); return; } for(let i = 0; i < data.length; i++) { if (new Date(data[i].tradeDateStr).getTime() >= (new Date().getTime()-1000*60*60*24)) { layer.msg("操作被限制(T+1日才能结算!!)", { icon: 4 //图标,可输入范围0~6 }); return; } } // 遍历传递过来的要结算的数据 for(let i = 0; i < data.length; i++) { if(data[i].tradeStatus == '1') { layer.msg("所选的数据有已结算的!", { icon: 4 // 图标,可输入范围0~6 }); return; } // 拿出用户ID进行拼接 idStr += data[i].stockTradeId + ","; } // 截取掉因为拼接产生的多余的一个逗号 idStr = idStr.substring(0, idStr.length - 1); settlements(idStr, '1'); break; case 'addStockTrader': addStockTrader(); }; }); // 监听锁定操作 form.on('switch(usable)', function(obj) { settlements(obj.value, this.checked == true ? 'Y' : 'N'); }); // 定义弃用或还原的方法 var settlements = function(stockTradeIds, tradeStatus) { // 定义提示信息, 状态 var msg; if(tradeStatus == '1') { msg = "结算"; } else { msg = "弃用"; } layer.msg("发送结算请求"); // 发送异步请求冻结或还原资源 $.ajax({ async: false, // 默认为true,false表示同步,如果当前请求没有返回则不执行后续代码 type: "post", url:'../stockTrade/settlements' ,// / data: { stockTradeIds:stockTradeIds, tradeStatus:tradeStatus }, success: function(data) { if(data == "1") { layer.msg(msg + "成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg(msg + "失败!", { icon: 2 }); } // 刷新数据表格 table.reload('stockTable', { url: '../stockTrade/list' }); } }); }; // 自定义表单校验 form.verify({ pass: [ /^[\S]{6,12}$/, '密码必须6到12位,且不能出现空格'], mobile: function(value) { var msg; $.ajax({ type: "POST", url: '/verifyTelephone',//system/toVerifyUserPhone async: false, // 使用同步的方法 data: { 'telephone': value }, dataType: 'json', success: function(result) { if(result.flag) { msg = result.msg; } } }); return msg; } }); }); <file_sep>/fa-web/src/main/webapp/static/fund/js/fund.js /* * layui引入样式的两种方式:模块化用和全模块用法 * layui的初始化模块可以理解为,引入这个模块的js文件 * 值得注意的是:layui的模块之间存在依赖关系,例如引入了table模块,它会layui/lay/moudules/table.js * 这个文件引入进来,并且它还会将这个模块所依赖的其他模块自动加入进来, * 实际引入的模块有:table、form、jquery、layer、laypage、laytpl、util,7个js文件 * 所以我仅仅初始化了table模块,却能获得form、jquery、layer的模块对象 */ //layui初始化表格模组 layui.use(['table', 'laydate', 'util', 'upload'], function() { // 获得模块对象 var table = layui.table; var form = layui.form; var $ = layui.jquery; var layer = layui.layer; var laydate = layui.laydate; var util = layui.util; var upload = layui.upload; var element = layui.element; //----1.用户数据表格渲染------------------------------------------------------------------ table.render({ elem: '#fundTable', url: '../findAllFund', //后期改回获取用户列表的后端程序的url method: 'get', where: {}, // 你额外要携带数据,以键值对的方式存入 toolbar: '#fundToolbar', // 开启头部工具栏,并为其绑定左侧模板 cellMinWidth: 80, // 全局定义所有常规单元格的最小宽度(默认:60) height:'full', cols: [ [{ title:'序号', type: 'numbers' }, // 序号 { type: 'checkbox' }, //复选框 { field: 'fundId', title: '基金Id', unresize: true, hide: true, //一般情况下不显示用户ID align: "center" }, { field: 'fundNo', title: '基金代码', unresize: true, align: "center", sort:true }, { field: 'fundName', title: '基金名', unresize: true, width:130, align: "center" }, { field: 'fundCompanyId', title: '基金所属公司Id', unresize: true, align: "center" }, { field: 'comShortName', title: '所属基金管理公司', unresize: true, hide:true, align: "center" }, { field: 'trusteeBank', title: '托管银行', unresize: true, align: "center", }, { field: 'fundScale', title: '基金规模', unresize: true, hide:true, align: "center", }, { field: 'nav', title: '初始净值', unresize: true, hide:true, align: "center", }, { field: 'trusteeFee', title: '托管费', unresize: true, align: "center", templet:'<span>{{d.trusteeFee + "‰"}}</span>' }, { field: 'billingDays', title: '计费有效天数', unresize: true, align: "center" }, { field: 'managementFee', title: '管理费率', unresize: true, Width:'auto', align: "center", templet:'<span>{{d.managementFee + "‰"}}</span>' }, { field: 'managerId', title: '基金经理Id', unresize: true, align: "center", }, { field: 'managerName', title: '基金经理名', unresize: true, hide:true, align: "center", }, { field: 'usable', title: '是否可用', unresize: true, templet: '#checkboxTpl', align: "center", }, { field: 'estDateStr', title: '成立时间', unresize: true, hide:true, align: "center", }, { field: 'description', title: '备注', unresize: true, hide:true, align: "center", } ] ], defaultToolbar: [{ title: '搜索' ,layEvent: 'LAYTABLE_SEARCH' ,icon: 'layui-icon-search' },'filter', 'exports', 'print' ], page: true, // 开启分页 limit: 10, // 每页显示的条数 limits: [10, 20, 50, 100], // 每页条数的选择项 loading: true, // 是否显示加载条(切换分页的时候显示) title: '基金表', // 定义 table 的大标题(在文件导出等地方会用到) id: 'fundTable', // 设定容器唯一 id // 隔行变色 even: false }); //----1.用户数据表格渲染------------------------------------------------------------------ //----2.添加基金成立时间选择器-------------------------------------------------------------------- laydate.render({ elem: '#estDate' ,trigger: 'click' }); //修改用户入职时间选择器 laydate.render({ elem: '#updatefundHiredate' }); var ltips=layer.tips("为你定制的搜索^_^","[title='搜索']",{tips:[2,'#1211115e'],time:5000,shadeClose:true}); //----3.处理头部条件组合搜素------------------------------------------------------------------ form.on('submit(fundSearchBtn)', function(data) { // 执行后台代码 table.reload('fundTable', { url: '../findFundByCondition', where: { // 设定异步数据接口的额外参数,任意设 fundNo: $("#queryFundNo").val(), trusteeBank: $("#queryTrusteeBank").val(), managementFeeMin: $("#queryManagementFeeMin").val(), managementFeeMax: $("#queryManagementFeeMax").val(), managerId: $("#queryManagerId").val(), usable: $("#queryUsable").val(), }, page: { curr: 1 //从第一页开始 }, limit: 10 }); return false; // 阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); //----3.处理表行修改------------------------------------------------------------------ table.on("tool(fundTableEvent)",function (obj) { var data = obj.data; console.log(data); if (obj.event == "update"){ initUpdatefundModal(data); } }); // 用户列表头部工具栏添加|修改|删除(逻辑删除)|恢复按钮的事件句柄绑定 table.on('toolbar(fundTableEvent)', function(obj) { // 获取当前表格选中状态和选中的数据 var checkStatus = table.checkStatus(obj.config.id); // 区分点击的按钮 switch(obj.event) { case 'addfund': // 弹出新增模态框 initAddFundModal(); break; case 'LAYTABLE_SEARCH': laytablesearch(); layer.close(ltips); break; case 'updatefund': // 选择的数据数量 if(checkStatus.data.length > 1) { layer.msg("最多只能修改一行数据哦!!", { icon: 0 //图标,可输入范围0~6 }); } else if(checkStatus.data.length < 1) { layer.msg("请选择要修改的数据哦!!", { icon: 3 //图标,可输入范围0~6 }); } else if(checkStatus.data[0].usable == 'N') { layer.msg("该基金被禁用了哦!!", { icon: 4 //图标,可输入范围0~6 }); } else { // 弹出修改模态框,传递当前选中的一行数据过去 initUpdatefundModal(checkStatus.data[0]); } break; case 'frozenRecord': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要冻结的用户!!", { icon: 4 //图标,可输入范围0~6 }); } // 定义一个要删除的所有资源ID的字符串 var fundIdStr = ""; // 遍历传递过来的要删除的数据 for(var i = 0; i < data.length; i++) { if(data[i].usable == 'N') { layer.msg("所选用户中有被冻结的用户!", { icon: 1 // 图标,可输入范围0~6 }); return; } // 拿出用户ID进行拼接 fundIdStr += data[i].fundId + ","; } // 截取掉因为拼接产生的多余的一个逗号 fundIdStr = fundIdStr.substring(0, fundIdStr.length - 1); frozenORrecoverArchives(fundIdStr, 'N'); break; case 'restoreRecord': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要还原的用户!!", { icon: 4 //图标,可输入范围0~6 }); } // 定义一个要删除的所有资源ID的字符串 var fundIdStr = ""; // 遍历传递过来的要删除的数据 for(var i = 0; i < data.length; i++) { if(data[i].usable == 'Y') { layer.msg("所选用户中有可用的用户!", { icon: 1 // 图标,可输入范围0~6 }); return; } // 拿出资源ID进行拼接 fundIdStr += data[i].fundId + ","; } // 截取掉因为拼接产生的多余的一个逗号 fundIdStr = fundIdStr.substring(0, fundIdStr.length - 1); frozenORrecoverArchives(fundIdStr,'Y'); break; }; }); // 初始化修改模态框 var initUpdatefundModal = function(data) { // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '修改基金', // 标题 skin: "layui-layer-molv", anim: 2, // 弹出动画 area: ["100%",'100%'], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#updatefundModal"), // 文本、html都行 resize: false, // 是否允许拉伸 end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) // 清空表单 $("#addfundForm")[0].reset(); $("#demo1").attr("src", ""); $("#demoText").text(""); } }); // 表单赋值 form.val('updateFundForm', { "fundId": data.fundId, "fundNo": data.fundNo, "fundName": data.fundName, //layui.util.toDateString(data.commonStart, 'HH:mm:ss'), "estDate": data.estDateStr, "managerName": data.managerName, "trusteeBank": data.trusteeBank, "fundScale": data.fundScale, "nav": data.nav, "managementFee":data.managementFee, "trusteeFee": data.trusteeFee, "billingDays": data.billingDays, "fundCompanyId": data.fundCompanyId, "comShortName": data.comShortName, "description": data.description, }); }; //获取选中下拉列表的值 var managerIdVal; form.on('select', function(data){ let obj = data.elem; if($(data.elem).attr("id") == "updateManagerName") managerIdVal = $(obj).children("[value='"+data.value+"']").attr("managerId"); if($(data.elem).attr("id") == "addManagerName") managerIdVal = $(obj).children("[value='"+data.value+"']").attr("managerId"); console.log(managerIdVal); //联动显示基金公司id //根据父元素ID判断是否是添加模态框里的选择事件 if($(data.elem).attr("id") == "addComShortName") $("#addFundCompanyId").val($(data.elem).children("[value='"+ data.value+"']").attr("fundCompanyId")); //根据父元素ID判断是否是修改模态框里的选择事件 if($(data.elem).attr("id") == "updateComShortName") $("#updateFundCompanyId").val($(data.elem).children("[value='"+ data.value+"']").attr("fundCompanyId")); console.log($(data.elem).children("[value='"+ data.value+"']").attr("fundCompanyId")) }); //----4.处理新增用户表单提交-------------------------------------------------------------- form.on('submit(addFundBtn)',function(data) { let addFundForm = form.val("addFundForm"); // $("#fundCompanyId").val(data.value); console.log(addFundForm.fundName); // 执行后台代码 $.ajax({ type:'POST', //适用RESTful风格的添加: 查询GET、添加POST、更新PUT、删除DELETE async:false, url:'../saveFund', //后期改为添加用户的后台程序的url data:{ fundNo:addFundForm.fundNo, fundName:addFundForm.fundName, fundCompanyId:addFundForm.fundCompanyId, trusteeBank:addFundForm.trusteeBank, fundScale:addFundForm.fundScale, nav:addFundForm.nav, trusteeFee:addFundForm.trusteeFee, managementFee:addFundForm.managementFee, billingDays:addFundForm.billingDays, managerId:managerIdVal, managerName:addFundForm.managerName, estDate:addFundForm.estDate, comShortName:addFundForm.comShortName, description:addFundForm.description, }, // data:data.field, success: function(data) { console.log(data.result) // 关闭页面上所有类型的所有弹框 layer.closeAll(); if(data.result == 1) { layer.msg("添加成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg("添加失败!", { icon: 1 // 图标,可输入范围0~6 }); } } }); // 刷新数据表格 table.reload('fundTable', { url: '../findFundByCondition' //后期改为查询用户的后台程序的url }); return false; // 阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); //----5.处理修改基金表单提交-------------------------------------------------------------- form.on('submit(updatefundBtn)', function(data) { let updateFundForm = form.val("updateFundForm"); //执行后台代码 $.ajax({ type: 'POST', //适用RESTful风格的添加: 查询GET、添加POST、更新PUT、删除DELETE async: false, url: '../updateFund', //后期改为修改用户的后台程序url data: { fundId:updateFundForm.fundId, fundCompanyId:updateFundForm.fundCompanyId, trusteeFee:updateFundForm.trusteeFee, managementFee:updateFundForm.managementFee, billingDays:updateFundForm.billingDays, managerId:managerIdVal, managerName:updateFundForm.managerName, comShortName:updateFundForm.comShortName, description:updateFundForm.description, },//data.field success: function(data) { //关闭页面上所有类型的所有弹框 layer.closeAll(); if(data == 1) { layer.msg("修改成功!", { icon: 1 //图标,可输入范围0~6 }); } else { layer.msg("修改失败!", { icon: 1 //图标,可输入范围0~6 }); } } }); //刷新数据表格 table.reload('fundTable', { url: '../findFundByCondition' // }); return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); // 监听锁定操作 form.on('switch(usable)', function(obj) { frozenORrecoverArchives(obj.value, this.checked == true ? 'Y' : 'N'); }); // 定义冻结或还原的方法 var frozenORrecoverArchives = function(fundIdStr, status) { // 用户ID var fundId = fundIdStr; // 定义提示信息, 状态 var msg, usable; if(status == 'Y') { msg = "还原", usable = 'Y'; } else { msg = "禁用", usable = 'N'; } // 发送异步请求冻结或还原资源 $.ajax({ async: false, // 默认为true,false表示同步,如果当前请求没有返回则不执行后续代码 type: "DELETE", url:'../updateFundStatus/' + fundId + "/" + usable,// /updatefund '/updatefundStatus/' + fundIds + "/" + usable data: { // fundId:fundId, // usable:usable, // _method: 'DELETE' }, datatype: 'json', success: function(data) { if(data.result == "1") { layer.msg(msg + "成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg(msg + "失败!", { icon: 2 }); } // 刷新数据表格 table.reload('fundTable', { url: '../findFundByCondition' }); } }); }; // 初始化新增模态框 var initAddFundModal = function() { // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '添加基金', // 标题 skin: "layui-layer-molv", anim: 2, // 弹出动画 area: ["100%",'100%'], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#addFundModal"), // 文本、html都行 offset:'l', resize: false, // 是否允许拉伸 end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) // 清空表单 $("#addFundForm")[0].reset(); $("#demo1").attr("src", ""); $("#demoText").text(""); } }); } $.ajax({ url: '../findUserAndFundCompany',//system/org', dataType: 'json', type: 'get', success: function(data) { $.each(data.users, function(index) { var managerId = data.users[index].userId; var managerName = data.users[index].userName; /* var sdSdd = data[index].sdSdd; */ // 添加模态框基金经理名动态添加下拉列表 $("#addManagerName").append( "<option managerId='" + managerId + "' value='" + managerName + "'>" + managerName + "</option>"); // 修改模态框基金经理名动态添加下拉列表 $("#updateManagerName").append( "<option managerId='" + managerId + "' value='" + managerName + "'>" + managerName + "</option>"); }); $.each(data.fundCompanies, function(index) { var fundCompanyId = data.fundCompanies[index].fundCompanyId; var comFullName = data.fundCompanies[index].comFullName; // 添加模态框所属基金管理公司名下拉列表 $("#addComShortName").append( "<option fundCompanyId='" + fundCompanyId + "' value='" + comFullName + "'>" + comFullName + "</option>"); // 修改模态框所属基金管理公司名下拉列表 $("#updateComShortName").append( "<option fundCompanyId='" + fundCompanyId + "' value='" + comFullName + "'>" + comFullName + "</option>"); }); form.render();//渲染将option添加进去 } }); // 自定义表单校验 form.verify({ pass: [ /^[\S]{6,12}$/, '密码必须6到12位,且不能出现空格'], mobile: function(value) { var msg; $.ajax({ type: "POST", url: '../verifyTelephone',//system/toVerifyfundPhone async: false, // 使用同步的方法 data: { 'telephone': value }, dataType: 'json', success: function(result) { if(result.flag) { msg = result.msg; } } }); return msg; } }); }); <file_sep>/fa-web/src/main/webapp/static/stock/js/stock.js /* * layui引入样式的两种方式:模块化用和全模块用法 * layui的初始化模块可以理解为,引入这个模块的js文件 * 值得注意的是:layui的模块之间存在依赖关系,例如引入了table模块,它会layui/lay/moudules/table.js * 这个文件引入进来,并且它还会将这个模块所依赖的其他模块自动加入进来, * 实际引入的模块有:table、form、jquery、layer、laypage、laytpl、util,7个js文件 * 所以我仅仅初始化了table模块,却能获得form、jquery、layer的模块对象 */ //layui初始化表格模组 layui.use(['table', 'laydate', 'util', 'upload'], function() { // 获得模块对象 var table = layui.table; var form = layui.form; var $ = layui.jquery; var layer = layui.layer; var laydate = layui.laydate; var util = layui.util; var upload = layui.upload; //----1.用户数据表格渲染------------------------------------------------------------------ table.render({ elem: '#stockTable', url: '../stock/findAllStock', //后期改回获取用户列表的后端程序的url method: 'get', where: {}, // 你额外要携带数据,以键值对的方式存入 toolbar: '#stockToolbar', cellMinWidth: 80, // 全局定义所有常规单元格的最小宽度(默认:60) cols: [ [{ type: 'numbers' }, // 序号 { type: 'checkbox' }, //复选框 { field: 'stockId', title: '股票Id', unresize: true, hide: true, //一般情况下不显示股票ID align: "center" }, { field: 'stockCode', title: '股票代码', unresize: true, align: "center" }, { field: 'stockShortName', title: '股票简称', unresize: true, align: "center" }, { field: 'issueDate', title: '上市日期', align: "center", templet: function(data) { return formatChinaDate(data); } }, { field: 'issuer', title: '发行人', unresize: true, align: "center" }, { field: 'plate', title: '所属板块', unresize: true, align: "center", }, { field: 'industry', title: '所属行业', unresize: true, align: "center", }, { field: 'exchange', title: '交易所', unresize: true, align: "center", }, { field: 'usable', title: '股票状态', unresize: true, templet: '#checkboxTpl', align: "center" }, { field: 'description', title: '备注', unresize: true, hide:true, align: "center", } ] ], page: true, // 开启分页 limit: 10, // 每页显示的条数 limits: [10, 20, 50, 100], // 每页条数的选择项 loading: true, // 是否显示加载条(切换分页的时候显示) title: '股票表', // 定义 table 的大标题(在文件导出等地方会用到) id: 'stockTable', // 设定容器唯一 id // 隔行变色 even: false }); //----1.用户数据表格渲染------------------------------------------------------------------ //----2.添加股票上市日期选择器-------------------------------------------------------------------- laydate.render({ elem: '#addStockHiredate' ,type: 'date' ,format: 'yyyy-MM-dd' }); //----2.修改股票上市日期选择器-------------------------------------------------------------------- laydate.render({ elem: '#updateStockHiredate' ,type: 'date' ,format: 'yyyy-MM-dd' }); //修改用户入职时间选择器 laydate.render({ elem: '#updatefundHiredate' }); //----3.处理头部条件组合搜素------------------------------------------------------------------ form.on('submit(stockSearchBtn)', function(data) { // 执行后台代码 table.reload('stockTable', { url: '/findStockByCondition', where: { // 设定异步数据接口的额外参数,任意设 stockCode: $("#queryStockCode").val(), stockShortName: $("#queryStockShortName").val(), plate: $("#queryPlate").val(), industry: $("#queryIndustry").val(), exchange: $("#queryExchange").val(), queryusable: $("#usable").val(), }, page: { curr: 1 //从第一页开始 }, limit: 10 }); return false; // 阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); //----3.处理表行修改------------------------------------------------------------------ table.on("tool(stockTableEvent)",function (obj) { var data = obj.data; if (obj.event == "update"){ initUpdateStockModal(data); } }); //修改日期格式(年,月,日) function formatChinaDate(data) { var oIssueDate = data.issueDate; var oDate = new Date(oIssueDate); var sIssueDate = oDate.getFullYear() + "年" + (oDate.getMonth() + 1) + "月" + oDate.getDate() + "日"; return sIssueDate; } //修改日期格式(yyyy-MM-dd) function formatDate(date) { var d = new Date(date), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; return [year, month, day].join('-'); } // 用户列表头部工具栏添加|修改|删除(逻辑删除)|恢复按钮的事件句柄绑定 table.on('toolbar(stockTableEvent)', function(obj) { // 获取当前表格选中状态和选中的数据 var checkStatus = table.checkStatus(obj.config.id); // 区分点击的按钮 switch(obj.event) { case 'addStock': // 弹出新增模态框 initAddStockModal(); break; case 'updateStock': // 选择的数据数量 if(checkStatus.data.length > 1) { layer.msg("最多只能修改一行数据哦!!", { icon: 0 //图标,可输入范围0~6 }); } else if(checkStatus.data.length < 1) { layer.msg("请选择要修改的数据哦!!", { icon: 3 //图标,可输入范围0~6 }); } else if(checkStatus.data[0].usable == 'N') { layer.msg("该用户被禁用了哦!!", { icon: 4 //图标,可输入范围0~6 }); } else { // 弹出修改模态框,传递当前选中的一行数据过去 initUpdateStockModal(checkStatus.data[0]); } break; case 'frozenRecord': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要冻结的股票!!", { icon: 4 //图标,可输入范围0~6 }); } // 定义一个要删除的所有资源ID的字符串 var stockIdStr = ""; // 遍历传递过来的要删除的数据 for(var i = 0; i < data.length; i++) { if(data[i].usable == 'N') { layer.msg("所选用户中有被冻结的用户!", { icon: 1 // 图标,可输入范围0~6jues }); return; } // 拿出用户ID进行拼接 stockIdStr += data[i].stockCode + ","; } // 截取掉因为拼接产生的多余的一个逗号 stockIdStr = stockIdStr.substring(0, stockIdStr.length - 1); frozenORrecoverArchives(stockIdStr, 'N'); break; case 'restoreRecord': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要还原的用户!!", { icon: 4 //图标,可输入范围0~6 }); } // 定义一个要删除的所有资源ID的字符串 var stockIdStr = ""; // 遍历传递过来的要删除的数据 for(var i = 0; i < data.length; i++) { if(data[i].usable == 'Y') { layer.msg("所选用户中有可用的用户!", { icon: 1 // 图标,可输入范围0~6 }); return; } // 拿出资源ID进行拼接 stockIdStr += data[i].stockCode + ","; } // 截取掉因为拼接产生的多余的一个逗号 stockIdStr = stockIdStr.substring(0, stockIdStr.length - 1); frozenORrecoverArchives(stockIdStr, 'Y'); break; }; }); //----4.处理新增用户表单提交-------------------------------------------------------------- form.on('submit(addStockBtn)', function(data) { // 执行后台代码 $.ajax({ type: 'POST', //适用RESTful风格的添加: 查询GET、添加POST、更新PUT、删除DELETE async: false, url: '/addStock', //后期改为添加用户的后台程序的url data: data.field, success: function(data) { console.log(data); // 关闭页面上所有类型的所有弹框 layer.closeAll(); if(data == 1) { layer.msg("添加成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg("添加失败!", { icon: 1 // 图标,可输入范围0~6 }); } //关闭添加模态框 } }); // 刷新数据表格 table.reload('stockTable', { url: '/findStockByCondition' //后期改为查询用户的后台程序的url }); return false; // 阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); //----5.处理修改用户表单提交-------------------------------------------------------------- form.on('submit(updateStockBtn)', function(data) { //执行后台代码 $.ajax({ type: 'POST', //适用RESTful风格的添加: 查询GET、添加POST、更新PUT、删除DELETE async: false, url: '/updateStock', //后期改为修改用户的后台程序url data: data.field,//data.field success: function(data) { console.log(data) //关闭页面上所有类型的所有弹框 layer.closeAll(); if(data.result == 1) { layer.msg("修改成功!", { icon: 1 //图标,可输入范围0~6 }); } else { layer.msg("修改失败!", { icon: 1 //图标,可输入范围0~6 }); } } }); //刷新数据表格 table.reload('stockTable', { url: '/findStockByCondition' // }); return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); // 监听锁定操作 form.on('switch(usable)', function(obj) { frozenORrecoverArchives(obj.value, this.checked == true ? 'Y' : 'N'); }); // 定义冻结或还原的方法 var frozenORrecoverArchives = function(stockIdStr, status) { // 用户ID var stockId = stockIdStr; // 定义提示信息, 状态 var msg, usable; if(status == 'Y') { msg = "还原", usable = 'Y'; } else { msg = "禁用", usable = 'N'; } // 发送异步请求冻结或还原资源 $.ajax({ async: false, // 默认为true,false表示同步,如果当前请求没有返回则不执行后续代码 type: "DELETE", url:'/updateStockStatus/' + stockId + "/" + usable,// /updatefund '/updatefundStatus/' + fundIds + "/" + usable data: { // fundId:fundId, // usable:usable, // _method: 'DELETE' }, datatype: 'json', success: function(data) { if(data.result == "1") { layer.msg(msg + "成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg(msg + "失败!", { icon: 2 }); } // 刷新数据表格 table.reload('stockTable', { url: '/findStockByCondition' }); } }); }; // var hiddeDisable = function(){ // // } // 初始化新增模态框 var initAddStockModal = function() { // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '添加股票', // 标题 skin: "layui-layer-molv", anim: 2, // 弹出动画 area: ["680px"], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#addStockModal"), // 文本、html都行 resize: false, // 是否允许拉伸 end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) // 清空表单 /*$("#addfundForm")[0].reset(); $("#demo1").attr("src", ""); $("#demoText").text("");*/ } }); } // 初始化修改模态框 var initUpdateStockModal = function(data) { // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '修改股票', // 标题 skin: "layui-layer-molv", anim: 2, // 弹出动画 area: ['680px'], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#updateStockModal"), // 文本、html都行 resize: false, // 是否允许拉伸 end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) // 清空表单 $("#addStockForm").reset(); /*$("#demo1").attr("src", ""); $("#demoText").text("");*/ } }); // 表单赋值 form.val('updateStockForm', { "stockCode": data.stockCode, "stockShortName": data.stockShortName, //layui.util.toDateString(data.commonStart, 'HH:mm:ss'), "issueDate": formatDate(data.issueDate), "issuer": data.issuer, // "orgId": data.orgId, // "orgName": data.orgName, "plate": data.plate, // "fundBirthdate": data.fundBirthdate, // "fundHiredate": data.fundHiredate, "industry": data.industry, "exchange": data.exchange, // "headImage": data.file, }); }; // $.ajax({ // url: '/findfundByConditionuuuu',//system/org', // dataType: 'json', // type: 'post', // success: function(data) { // $.each(data, function(index) { // var orgName = data[index].orgName; // var orgId = data[index].orgId; // /* var sdSdd = data[index].sdSdd; */ // // 头部的搜索 // $("#queryOrgName").append( // "<option value='" + orgName + "'>" + orgName + // "</option>"); // // 添加 // $("#addOrgName").append( // "<option value='" + orgId + "'>" + orgName + // "</option>"); // // 修改 // $("#updateOrgName").append( // "<option value='" + orgId + "'>" + orgName + // "</option>"); // // form.render()渲染将option添加进去 // form.render(); // }); // } // }); // 自定义表单校验 form.verify({ stockCode: [ /^[\S]{6}$/, '股票代码必须是6位,且不能出现空格'], stockShortName: [ /^[\S]{1,}$/, '股票简称不能为空!'], issueDate: [ /^[\S]/, '上市日期不能为空!'], issuer: [ /^[\S]{1,}$/, '发行人不能为空!'], plate: [ /\S/, '所属板块不能为空!'], industry: [/\S/, '所属行业不能为空!'], mobile: function(value) { var msg; $.ajax({ type: "POST", url: '/verifyTelephone',//system/toVerifyfundPhone async: false, // 使用同步的方法 data: { 'telephone': value }, dataType: 'json', success: function(result) { if(result.flag) { msg = result.msg; } } }); return msg; } }); }); <file_sep>/fa-base/src/main/java/com/yidu/fund/service/impl/FundTradeServiceImpl.java package com.yidu.fund.service.impl; import com.yidu.capital.domain.CapitalTransfer; import com.yidu.deposit.domain.CashInventory; import com.yidu.deposit.domain.FundInventory; import com.yidu.format.LayuiFormat; import com.yidu.fund.dao.FundDao; import com.yidu.fund.dao.FundTradeDao; import com.yidu.fund.domain.Fund; import com.yidu.fund.domain.FundTrade; import com.yidu.fund.paging.FundTradePaging; import com.yidu.fund.service.FundTradeService; import com.yidu.utils.IDUtil; import com.yidu.utils.NoUtils; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.ResponseBody; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; /** * 类的描述: * * @Author 李昊林 * @Date 2020/9/7 15:38 */ @Service public class FundTradeServiceImpl implements FundTradeService { @Autowired private FundTradeDao fundTradeDao; // @Autowired // private LayuiFormat layuiFormat; @Override public List<FundTrade> findFundTradeByCondition(FundTradePaging fundTradePaging) { //计算分页 fundTradePaging.setPage((fundTradePaging.getPage()-1)*fundTradePaging.getLimit()); return fundTradeDao.findFundTradeByCondition(fundTradePaging); } @Override public Long findCountFundTradeByCondition(FundTradePaging fundTradePaging) { return fundTradeDao.findCountFundTradeByCondition(fundTradePaging); } @Override public boolean addFundTrade(List<FundTrade> fundTradeList) { boolean result = false; for (FundTrade trade : fundTradeList) { trade.setFundTradeId(IDUtil.getUuid()); // trade.setFundTradeNo(NoUtils.getNo("JJJY")); result = fundTradeDao.addFundTrade(trade); if (!result) throw new RuntimeException("添加失败,请检查数据!"); } return result; } @Override public boolean fundSettlement(String ids,String tradeStatus) { //分割基金交易Id字符串 String[] fundTradeIds = ids.split(","); //先查询要结算的基金交易对象集合 List<FundTrade> fundTradeList = new ArrayList<>(); for (String fundTradeId : fundTradeIds) { fundTradeList.add(fundTradeDao.findFundTradeById(fundTradeId)); } //调用修改交易状态方法 boolean UTSResult = updateTradeStatus(fundTradeIds,tradeStatus); //调用添加调拨记录方法 boolean ACTResult = addCapitalTransfer(fundTradeList); //调用结算至基金库存方法 boolean STTIResult = settlementToFundInventory(fundTradeList); //调用结算至现金库存方法 boolean STCIResult = settlementToCashInventory(fundTradeList); return UTSResult && ACTResult && STTIResult && STCIResult; } /** * 修改基金交易状态 * @param fundTradeIds 基金交易Id字符数组 * @param tradeStatus 交易状态 * @return 修改成功返回true */ private boolean updateTradeStatus(String[] fundTradeIds,String tradeStatus) { //声明布尔类型结果变量 boolean result = false; //创建参数map集合对象 Map<String,Object> paramMap = new HashMap<>(); //封装前端交易状态到参数map集合 paramMap.put("tradeStatus",tradeStatus); //遍历前端基金交易Id字符数组 for (String fundTradeId : fundTradeIds) { //封装前端交易id到参数map集合 paramMap.put("fundTradeId",fundTradeId); //修改基金交易状态 result = fundTradeDao.updateTradeStatus(paramMap); if (!result) throw new RuntimeException("修改基金交易状态失败,请检查相关数据"); } return result; } /** * 添加调拨记录 * @param fundTradeList 基金交易对象集合 * @return 成功添加返回true,否则返回false */ private boolean addCapitalTransfer(List<FundTrade> fundTradeList) { //定义资金调拨对象 CapitalTransfer capitalTransfer = new CapitalTransfer(); //声明添加资金调拨结果变量 boolean result = false; for (FundTrade fundTrade : fundTradeList) { //设置资金调拨id capitalTransfer.setCapitalTransferId(IDUtil.getUuid()); //设置资金调拨编号 capitalTransfer.setCapitalTransferNo(NoUtils.getNo("ZJDB")); capitalTransfer.setFundId(fundTrade.getFundId()); capitalTransfer.setFundNo(fundTrade.getFundNo()); capitalTransfer.setFundName(fundTrade.getFundName()); capitalTransfer.setAccountId(fundTrade.getAccountId()); capitalTransfer.setAccountNo(fundTrade.getAccountNo()); capitalTransfer.setAccountName(fundTrade.getAccountName()); capitalTransfer.setTransferAmount(fundTrade.getTurnover()); //设置资金调拨日期 capitalTransfer.setTransferDate(new Date()); //设置资金调拨标识 capitalTransfer.setTransferFlag(fundTrade.getTradeFlag()); //设置资金调拨类型 capitalTransfer.setTransferType("4"); //添加资金调拨到数据库 result = fundTradeDao.addCapitalTransfer(capitalTransfer); if (!result) throw new RuntimeException("资金调拨添加失败,请检查数据"); } return result; } /** * 结算至基金库存 * @param fundTradeList 基金交易对象集合 * @return 成功添加返回true,否则返回false */ private boolean settlementToFundInventory(List<FundTrade> fundTradeList){ //声明执行结果变量 boolean result = false; //定义查询参数map集合 Map<String,String> paramMap = new HashMap<>(); //定义日期格式化对象 DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //格式化当前时间 String currentDate = df.format(new Date()); //准备模糊查询统计日期条件数据 拼接百分号 paramMap.put("statisticalDate",currentDate + "%"); for (FundTrade fundTrade : fundTradeList) { //准备查询条件数据 基金id paramMap.put("fundId",fundTrade.getFundId()); //查询现金库存中指定基金的当天基金库存数据 FundInventory fundInventory = fundTradeDao.findFundInventoryByIdAndStatisticalDate(paramMap); System.out.println("fundInventory = " + fundInventory); //判断基金库存是否存在指定基金当天的库存数据 if (fundInventory != null) { //调用计算基金库存余额和份额的方法 calcBalanceAndShare(fundTrade,fundInventory); //如果有指定基金的当天基金库存数据,则调用数据访问对象方法修改该基金的当天基金库存数据 result = fundTradeDao.updateFundInventory(fundInventory); }else{ //调用数据访问方法查询该基金最近一次库存信息 FundInventory lastFundInventory = fundTradeDao.findLastFIByFundId(fundTrade.getFundId()); if ( null==lastFundInventory) { throw new RuntimeException("找不到最近一次基金库存信息,请检查基金库中是否有对应的基金id"); } System.out.println("lastFundInventory = " + lastFundInventory); //调用计算基金库存余额和份额的方法 calcBalanceAndShare(fundTrade,lastFundInventory); //设置基金库存id lastFundInventory.setFundInventoryId(IDUtil.getUuid()); //设置基金库存编号 lastFundInventory.setFundInventoryNo(NoUtils.getNo("JJKC")); //如果没有指定基金的当天基金库存数据,则调用数据访问对象新增一条基金库存数据 result = fundTradeDao.addFundInventory(lastFundInventory); } } return result; } /** * 计算基金库存余额和份额 * @param fundTrade 基金交易对象 * @param fundInventory 基金库存对象 */ private void calcBalanceAndShare(FundTrade fundTrade,FundInventory fundInventory){ //获取交易类型 String type = fundTrade.getFundTradeType(); //获取交易金额 BigDecimal turnover = fundTrade.getTurnover(); //获取交易数量 BigInteger share = fundTrade.getShare(); //判断交易类型 if ("3".equals(type)) { //赎回减少库存份额及余额 fundInventory.setShare(fundInventory.getShare().subtract(share)); fundInventory.setBalance(fundInventory.getBalance().subtract(turnover)); }else{ //申购或认购增加库存份额及余额 fundInventory.setShare(fundInventory.getShare().add(share)); fundInventory.setBalance(fundInventory.getBalance().add(turnover)); } //设置统计日期 fundInventory.setStatisticalDate(new Date()); } /** * 结算至现金库存 * @param fundTradeList 基金交易对象集合 * @return 成功添加返回true,否则返回false */ private boolean settlementToCashInventory(List<FundTrade> fundTradeList){ //声明执行结果变量 boolean result = false; //定义查询参数map集合 Map<String,String> paramMap = new HashMap<>(); //定义日期格式化对象 DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //格式化当前时间 String currentDate = df.format(new Date()); //准备模糊查询统计日期条件数据 拼接百分号 paramMap.put("statisticalDate",currentDate + "%"); for (FundTrade fundTrade : fundTradeList) { //准备查询条件数据 基金id paramMap.put("fundId",fundTrade.getFundId()); //查询现金库存中指定基金的当天现金库存数据 CashInventory cashInventory = fundTradeDao.findCashInventoryByIdAndStatisticalDate(paramMap); System.out.println("cashInventory = " + cashInventory); //判断现金库存是否存在指定基金当天的库存数据 if (cashInventory != null) { //调用计算现金余额的方法 calcCashBalance(fundTrade,cashInventory); //如果有指定基金的当天现金库存数据,则调用数据访问对象方法修改该基金当天的现金库存数据 result = fundTradeDao.updateCashInventory(cashInventory); }else{ //调用数据访问方法查询指定基金最近一次现金库存信息 CashInventory lastCashInventory = fundTradeDao.findLastCIByFundId(fundTrade.getFundId()); if ( null==lastCashInventory) { throw new RuntimeException("找不到最近一次现金库存信息,请检查现金库中是否有对应的基金id"); } System.out.println("lastCashInventory = " + lastCashInventory); //调用计算现金余额的方法 calcCashBalance(fundTrade,lastCashInventory); //设置现金库存id lastCashInventory.setCashInventoryId(IDUtil.getUuid()); //设置现金库存编号 lastCashInventory.setCashInventoryNo(NoUtils.getNo("XJKC")); //如果没有指定基金的当天现金库存数据,则调用数据访问对象新增一条现金库存数据 result = fundTradeDao.addCashInventory(lastCashInventory); } } return result; } /** * 计算现金库存的现金余额 * @param fundTrade 基金交易对象 * @param cashInventory 现金库存对象 */ private void calcCashBalance(FundTrade fundTrade,CashInventory cashInventory){ //获取交易类型 String type = fundTrade.getFundTradeType(); //获取交易金额 BigDecimal turnover = fundTrade.getTurnover(); //判断交易类型 if ("3".equals(type)) { //赎回减少现金余额 cashInventory.setCashBalance(cashInventory.getCashBalance().subtract(turnover)); }else{ //申购或认购增加现金余额 cashInventory.setCashBalance(cashInventory.getCashBalance().add(turnover)); } //设置统计日期 cashInventory.setStatisticalDate(new Date()); } } <file_sep>/fa-base/src/main/java/com/yidu/deposit/service/DepositInterestAccrualBiz.java package com.yidu.deposit.service; import com.yidu.index.domain.SecuritiesInventory; import com.yidu.index.paging.SecuritiesInventoryPaging; import java.util.List; /** * 类的描述:存款计息业务逻辑接口 * * @author 蔡任骋 * @version 1.0 * @since 2020/09/21 */ public interface DepositInterestAccrualBiz { /** * 1.1.根据条件查询证券库存表中的银行交易数据数量 * @param securitiesInventoryPaging 包含条件的POJO类 * @return 功返回一个数量,否则返回0 */ Long countDepositInterestAccrualByCondition(SecuritiesInventoryPaging securitiesInventoryPaging); /** * 1.2.根据条件查询证券库存表中的银行交易数据 * @param securitiesInventoryPaging 包含条件的POJO类 * @return 成功返回一个包含数据的集合,否则返回null */ List<SecuritiesInventory> findSecuritiesInventoryByCondition(SecuritiesInventoryPaging securitiesInventoryPaging); /** * 2.存款计息 * @param securitiesInventoryIds 证券库存中银行存款数据Id * @param tradeStatus 计息状态 * @return 成功返回true,否则返回false */ boolean depositInterestAccrualByCondition(String securitiesInventoryIds,String tradeStatus); } <file_sep>/fa-base/src/main/java/com/yidu/deposit/service/DepositTradeBiz.java package com.yidu.deposit.service; import com.yidu.deposit.domain.DepositTrade; import com.yidu.deposit.paging.DepositTradePaging; import java.util.List; /** * 类的描述:... * * @author 蔡任骋 * @version 1.0 * @since 2020/09/10 */ public interface DepositTradeBiz { /** * 1.添加银行存款交易数据 * @param depositTrade 银行存款交易数据 * @return 成功返回1,否则返回0 */ int addDeposit(DepositTrade depositTrade); /** * 2.1.查询满足条件的银行交易数据数量 * @param depositTradePaging 包含条件的实体类 * @return 成功返回数量,否则返回0 */ long countDepositTradeByCondition(DepositTradePaging depositTradePaging); /** * 2.2.查询满足条件的银行交易数据 * @param depositTradePaging 包含条件的实体类 * @return 成功返回数据的集合,否则返回null */ List<DepositTrade> findDepositByCondition(DepositTradePaging depositTradePaging); /** * 3.结算 * @param depositIds * @param tradeStatus * @return */ boolean depositTradeSettlement(String depositIds,String tradeStatus); /** * 3.1.修改银行交易数据状态 * @param depositIds 银行交易数据ID字符串 * @param tradeStatus 银行交易数据状态 * @return 成功返回true,否则返回false *//* boolean updateTransactionStatus(String depositIds,String tradeStatus); *//** * 3.2往资金调拨表中添加数据 * @param depositTradeList 银行交易数据对象集合 * @return 成功返回true,否则返回false *//* boolean addBankTreasurer(List<DepositTrade> depositTradeList); *//** * 3.3修改或添加证券库存表 * @param depositTradeList 银行交易数据对象集合 * @return 成功返回true,否则返回false *//* boolean addOrUpdateStockInventory(List<DepositTrade> depositTradeList);*/ } <file_sep>/fa-web/src/main/webapp/static/fund/js/fundTrade.js $(function(){ /* * layui引入样式的两种方式:模块化用和全模块用法 * layui的初始化模块可以理解为,引入这个模块的js文件 * 值得注意的是:layui的模块之间存在依赖关系,例如引入了table模块,它会layui/lay/moudules/table.js * 这个文件引入进来,并且它还会将这个模块所依赖的其他模块自动加入进来, * 实际引入的模块有:table、form、jquery、layer、laypage、laytpl、util,7个js文件 * 所以我仅仅初始化了table模块,却能获得form、jquery、layer的模块对象 */ //layui初始化表格模组 layui.use(['table', 'laydate', 'upload','element'], function() { // 获得模块对象 var tId = 'fundTradeTable'; var table = layui.table; var form = layui.form; var $ = layui.jquery; var layer = layui.layer; var laydate = layui.laydate; var upload = layui.upload; var element = layui.element; //----1.基金交易数据表格渲染------------------------------------------------------------------ function f(a,b) { var tablIns=table.render({ elem: '#'+a, url: '../findAllFundTrade?b='+b, //后期改回获取用户列表的后端程序的url method: 'get', where: {}, // 你额外要携带数据,以键值对的方式存入 toolbar: '#fundToolbar', // 开启头部工具栏,并为其绑定左侧模板 cellMinWidth: 80, // 全局定义所有常规单元格的最小宽度(默认:60) height:'full-50', cols: [ [{ title:'序号', type: 'numbers', fixed:'left' }, // 序号 { type: 'checkbox', fixed:'left' }, //复选框 { field: 'fundTradeId', title: '基金交易Id', // unresize: true, hide:true, width:'20%', align: "center" }, { field: 'fundTradeNo', title: '基金交易编号', // unresize: true, width:'23%', align: "center" }, { field: 'fundId', title: '基金Id', // unresize: true, hide:true, width:'30%', align: "center" }, { field: 'fundNo', title: '基金代码', // unresize: true, width:'20%', align: "center", hide: true //一般情况下不显示用户ID }, { field: 'fundName', title: '基金名', width:'20%', // unresize: true, align: "center" }, { field: 'fundTradeType', title: '基金交易类型', // unresize: true, width:'12%', align: "center", templet: "#fundTradeTypeTpl" }, { field: 'accountId', title: '账户Id', // unresize: true, hide:true, width:'15%', align: "center" }, { field: 'accountNo', title: '账号', // unresize: true, hide: true, width:'30%', align: "center" }, { field: 'accountName', title: '账户名', width:'20%', // unresize: true, align: "center" }, { field: 'tradeFlag', title: '交易标识', width:'7%', // unresize: true, align: "center", templet: "<span>{{d.tradeFlag == '1' ? '流入' : d.tradeFlag == '2' ? '流出' : d.tradeFlag}}</span>" }, { field: 'tradePrice', title: '交易价格', width:'7%', // unresize: true, align: "center" }, { field: 'tradeDateStr', title: '交易日期', width:'11%', sort:true, // unresize: true, align: "center" }, { field: 'share', title: '交易数量(份额)', width:'10%', // unresize: true, Width:'auto', align: "center" }, { field: 'turnover', title: '交易额(总)', width:'8%', // unresize: true, align: "center" }, { field: 'fee', title: '费用', // unresize: true, width:'8%', align: "center" }, { field: 'total', title: '总金额', // unresize: true, width:'8%', align: "center" }, { field: 'tradeStatus', title: '交易状态', // unresize: true, width:'10%', align: "center", sort:true, fixed:'right', templet: '#tradeStatusTpl' } ] ], defaultToolbar: [{ title: '搜索' ,layEvent: 'LAYTABLE_SEARCH' ,icon: 'layui-icon-search' },'filter', 'exports', 'print' ], page: true, // 开启分页 limit: 10, // 每页显示的条数 limits: [10, 20, 50, 100], // 每页条数的选择项 loading: true, // 是否显示加载条(切换分页的时候显示) title: '基金表', // 定义 table 的大标题(在文件导出等地方会用到) text:{none:'被抽干了!没什么东西可以给你了,555!!(ㄒoㄒ)~~'}, // 隔行变色 even: false, done:function () { resize(); } }); } //----1.基金交易数据表格渲染------------------------------------------------------------------ f('fundTradeTable',0); f('fundTradeTable2',1); //----2.头部搜索栏基金交易日期时间选择器-------------------------------------------------------------------- laydate.render({ elem: '#queryTradeDateStart' ,trigger: 'click' }); //头部搜索栏基金交易日期时间选择器 laydate.render({ elem: '#queryTradeDateEnd' ,trigger: 'click' }); //----3.处理头部条件组合搜素------------------------------------------------------------------ form.on('submit(fundSearchBtn)', function(data) { let b; tId == "fundTradeTable" ? b = 0: b = 1; // 执行后台代码 table.reload(tId, { url: '../findAllFundTrade?b='+b, where: data.field, // 设定异步数据接口的额外参数,任意设 page: { curr: 1 //从第一页开始 }, limit: 10 }); return false; // 阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); //----3.处理表行修改------------------------------------------------------------------ // table.on("tool(fundTableEvent)",function (obj) { // var data = obj.data; // console.log(data); // if (obj.event == "update"){ // initUpdatefundModal(data); // } // }); window.onresize=function(){ resize(); } var ltips=layer.tips("为你定制的搜索^_^","[title='搜索']",{tips:[2,'#1211115e'],time:3000,shadeClose:true}); // 基金交易未结算数据表头部工具栏结算|导入按钮的事件句柄绑定 table.on('toolbar(fundTableEvent)', function(obj) { // 获取当前表格选中状态和选中的数据 var checkStatus = table.checkStatus(obj.config.id); // 区分点击的按钮 switch(obj.event) { case 'LAYTABLE_SEARCH': laytablesearch(); layer.close(ltips); break; case 'upload': // 弹出上传模态框 initUploadModal(); break; case 'settlement': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要结算的数据!!", { icon: 4 //图标,可输入范围0~6 }); return; } // 定义一个要结算的所有交易数据ID的字符串 var fundTradeIdStr = ""; // 遍历传递过来的要结算的数据 for(var i = 0; i < data.length; i++) { if(data[i].tradeStatus == '1') { layer.msg("所选数据中有已结算数据!", { icon: 1 // 图标,可输入范围0~6 }); return; } // 拿出基金交易数据Id进行拼接 fundTradeIdStr += data[i].fundTradeId + ","; } // 截取掉因为拼接产生的多余的一个逗号 fundTradeIdStr = fundTradeIdStr.substring(0, fundTradeIdStr.length - 1); // 调用修改基金状态请求方法 updateTradeStatus(fundTradeIdStr, '1'); break; }; }); // 定义修改交易状态请求方法 var updateTradeStatus = function(fundTradeIds,tradeStatus) { $.ajax({ url:"../fundSettlement", type:'post', data:{ fundTradeIds:fundTradeIds, tradeStatus:tradeStatus }, success:function (data) { if(data == 1) { layer.msg("结算成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg("结算失败!", { icon: 1 // 图标,可输入范围0~6 }); } table.reload('fundTradeTable',{ url:"../findAllFundTrade?b=0" }); table.reload('fundTradeTable2',{ url:"../findAllFundTrade?b=1" }) } }) }; function resize(){ // $("#dataTable .layui-table-fixed thead tr").css("height",$("#dataTable thead tr").height() + "px"); // $(".layui-table-body:last table").css("height", $(".layui-table-main")[0].clientHeight+"px") $("#dataTable .layui-table-fixed thead tr").css("height",$("#dataTable thead tr").height() + "px"); $("#dataTable2 .layui-table-fixed thead tr").css("height",$("#dataTable2 thead tr").height() + "px"); $.each($("#dataTable .layui-table-fixed-l .layui-table-body table tr"),function (index,data) { let right = $("#dataTable .layui-table-fixed-r .layui-table-body table tr").get(index); $(right).css("height",$(".layui-table-main:first tr").get(index).clientHeight+"px") $(data).css("height",$(".layui-table-main:first tr").get(index).clientHeight+"px") }) $.each($("#dataTable2 .layui-table-fixed-l .layui-table-body table tr"),function (index,data) { let right = $("#dataTable2 .layui-table-fixed-r .layui-table-body table tr").get(index); $(right).css("height",$(".layui-table-main:last tr").get(index).clientHeight+"px") $(data).css("height",$(".layui-table-main:last tr").get(index).clientHeight+"px") }) } // function resize(){ // // $("#dataTable .layui-table-fixed thead tr").css("height",$("#dataTable thead tr").height() + "px"); // // $(".layui-table-body:last table").css("height", $(".layui-table-main")[0].clientHeight+"px") // $("#dataTable .layui-table-fixed thead tr").css("height",$("#dataTable thead tr").height() + "px"); // $("#dataTable2 .layui-table-fixed thead tr").css("height",$("#dataTable2 thead tr").height() + "px"); // $.each($(".layui-table-body:eq(1) table tr"),function (index,data) { // $(data).css("height",$(".layui-table-main:first tr").get(index).clientHeight+"px") // }) // $.each($(".layui-table-body:last table tr"),function (index,data) { // $(data).css("height",$(".layui-table-main:last tr").get(index).clientHeight+"px") // }) // } // 初始化上传模态框 var initUploadModal = function(data) { // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '', // 标题 skin: "", anim: 2, // 弹出动画 area: ["100%",'100%'], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#upload"), // 文本、html都行 resize: false, // 是否允许拉伸 }); }; element.on('tab',function (data) { tId = data.elem.find(".layui-show table").attr("id") table.resize(tId); resize(); }); //渲染上传模态框 upload.render({ elem:'#upload', accept: 'file', url:"../upload", done: function(res){ //上传完毕回调 layer.closeAll(); layer.msg(res.success); // 刷新数据表格 table.reload('fundTradeTable', { url: '../findAllFundTrade?b=0' }); table.reload('fundTradeTable2', { url: '../findAllFundTrade?b=1' }); resize() } ,error: function(){ //请求异常回调 layer.msg("上传失败,请检查数据格式是否正确"); }, acceptMime:Lay_xls_xlsx, exts: 'xls|excel|xlsx', }); // 自定义表单校验 // form.verify({ // pass: [ /^[\S]{6,12}$/, '密码必须6到12位,且不能出现空格'], // mobile: function(value) { // var msg; // $.ajax({ // type: "POST", // url: '../verifyTelephone',//system/toVerifyfundPhone // async: false, // 使用同步的方法 // data: { // 'telephone': value // }, // dataType: 'json', // success: function(result) { // if(result.flag) { // msg = result.msg; // } // } // }); // return msg; // } // }); // function laytablesearch(){search.stop().slideToggle(1500);} }); }); <file_sep>/fa-base/src/main/java/com/yidu/bond/service/BondService.java package com.yidu.bond.service; import com.yidu.bond.domain.Bond; import com.yidu.bond.paging.BondPaging; import com.yidu.bond.paging.BondTradePaging; import com.yidu.format.LayuiFormat; import java.math.BigInteger; /** * 类的描述: * * @author wh * @since 2020/9/3 10:12 */ public interface BondService { /** * 查询所有债券对象 * @return 债券对象集合 */ LayuiFormat findAll(BondPaging bondPaging); /** * 添加债券 * @param bond 债券对象 * @return 1:添加成功,0:添加失败 */ int addBond(Bond bond); /** * 修改债券 * @param bond 修改对象 * @return 1:修改成功,0:修改失败 */ int updateBond(Bond bond); /** * 修改债券是否可用 * @param usable 是否可用参数 * @param bondIds 多个id,“,”分割 * @return 是否都修改成功 */ int updateUsable(String usable, String bondIds); } <file_sep>/fa-base/src/main/java/com/yidu/stock/service/StockService.java package com.yidu.stock.service; import com.yidu.stock.domain.Stock; import java.util.List; import java.util.Map; /** * 类的描述:股票业务的逻辑处理 * * @author 江北 * @since 2020/9/22 */ public interface StockService { List<Stock> queryAllStock(); Long countStockByCondition(Map<String, Object> paramMap); List<Stock> findStockByCondition(Map<String,Object> paramMap); boolean addStock(Stock stock); boolean updateStock(Stock stock); boolean updateStockStatus(String stockIds, String usable); } <file_sep>/fa-base/src/main/java/com/yidu/deposit/service/FundInventoryService.java package com.yidu.deposit.service; import com.yidu.deposit.domain.FundInventory; import com.yidu.deposit.paging.FundInventoryPaging; import java.util.List; /** * 类的描述:基金库存业务层 * @Author 李昊林 * @Date 2020/9/15 18:26 */ public interface FundInventoryService { /** *根据条件查询基金库存 * @param fundInventoryPaging 基金库存分页对象 * @return 基金库存对象集合 */ List<FundInventory> findFundInventoryByCondition(FundInventoryPaging fundInventoryPaging); /** * 根据条件统计基金库存数据数量 * @param fundInventoryPaging 基金库存分页对象 * @return 基金库存数量 */ Long findCountByCondition(FundInventoryPaging fundInventoryPaging); } <file_sep>/fa-base/src/main/java/com/yidu/bond/dao/BondLogicalDao.java package com.yidu.bond.dao; import com.yidu.bond.domain.BondTrade; import com.yidu.bond.paging.BondTradePaging; import com.yidu.capital.domain.CapitalTransfer; import com.yidu.deposit.domain.CashInventory; import com.yidu.index.domain.SecuritiesInventory; import com.yidu.index.paging.SecuritiesInventoryPaging; import org.apache.ibatis.annotations.Param; import java.math.BigInteger; import java.util.List; /** * 类的描述:债券详细业务的逻辑处理,数据操作层接口 * * @author wh * @since 2020/9/8 13:08 */ public interface BondLogicalDao { /** * 搜索查询所有债券交易数据并分页 * @param bondTradePaging 搜索分页参数 * @return 债券交易集合的layui格式数据 */ List<BondTrade> findBondTrade(BondTradePaging bondTradePaging); /** * 搜索查询所有债券交易数据条数 * @param bondTradePaging 搜索分页参数 * @return 数据条数 */ Long findBondTradeCount(BondTradePaging bondTradePaging); /** * 修改债券交易状态 * @param bondTradeId 债券交易数据id * @param tradeStatus 交易状态 * @return 1:修改成功,0:修改失败 */ int updateTradeStatus(@Param("bondTradeId") String bondTradeId, @Param("tradeStatus") String tradeStatus); /** * 添加债券交易数据 * @param bondTrade 债券交易数据对象 */ void addBondTrade(BondTrade bondTrade); /** * 按bondTradeId 联表t_capital_transfer,t_account,t_bond_trade 查询 ,返回资金调度对象 * @param bondTradeId 债券交易id * @return 资金调度表对象 */ CapitalTransfer findCapitalTransferByBondTradeId(String bondTradeId); /** * 向资金调拨表中插入数据 * @param capitalTransfer 资金调拨对象 * @return 是否插入成功 1:成功,0:失败 */ int addCapitalTransfer(CapitalTransfer capitalTransfer); /** * 通过bondTradeId查询交易记录 * @param bondTradeId 债券交易id * @return 债券交易对象 */ BondTrade findBondTradeById(String bondTradeId); /** * 根据基金id 和 债券id 查询证券库存数据 (用于判断是否有同一支基金的同一支债券) * @param fundId 基金id * @param bondId 债券id * @return 券库存对象 */ SecuritiesInventory findBondInventory(@Param("fundId") String fundId, @Param("bondId") String bondId); /** * 查询到账户信息,及单位成本,赋值到证券库存对象中 * @param fundId 基金id * @return 券库存对象 */ SecuritiesInventory findSIByFundId(@Param("fundId") String fundId, @Param("bondTradeId") String bondTradeId); /** * 添加证券库存数据 * @param securitiesInventory 债券库存对象 * @return 是否插入成功, 1:成功,0:失败 */ int addSecuritiesInventory(SecuritiesInventory securitiesInventory); /** * 修改证券(债券)库存数据 * @param securitiesInventory 债券库存对象 * @return 是否修改成功, 1:成功,0:失败 */ int updateSecuritiesInventory(SecuritiesInventory securitiesInventory); /** * 按债券交易中的fundId和bondId,联表查询出现金对应的现金库存数据对象 * @param fundId 基金id * @param bondId 债券id * @return 现金库存对象 */ CashInventory findCashInventory(@Param("fundId") String fundId,@Param("securitiesId") String bondId); /** * 将对应的现金账户更新 * @param cashInventory 现金库存对象 * @return 是否更新成功 1:成功,0:失败 */ int updateCashInventory(CashInventory cashInventory); /** * 添加今天新的现金库存数据 * @param cashInventory 现金库存对象 * @return 是否添加成功 1:成功,0:失败 */ int addCashInventory(CashInventory cashInventory); /** * 查询需要计息的债券库存 * @param securitiesInventoryPaging 搜索词条 * @return layui格式的集合数据 */ List<SecuritiesInventory> findInterestAccrual(SecuritiesInventoryPaging securitiesInventoryPaging); /** * 查询需要计息的债券库存数量 * @param securitiesInventoryPaging 搜索词条 * @return layui格式的集合数据 */ Long findInterestAccrualCount(SecuritiesInventoryPaging securitiesInventoryPaging); } <file_sep>/fa-web/src/main/java/com/yidu/bond/Listener/DataListener.java package com.yidu.bond.Listener; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.yidu.bond.domain.BondTrade; import com.yidu.bond.service.BondLogicalService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; // 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去 public class DataListener extends AnalysisEventListener<BondTrade> { private BondLogicalService bondLogicalService; private static final Logger LOGGER = LoggerFactory.getLogger(DataListener.class); /** * 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收 */ private static final int BATCH_COUNT = 5; List<BondTrade> list = new ArrayList<BondTrade>(); /** * 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。 */ /*public DataListener() { // 这里是demo,所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数 demoDAO = new DemoDAO(); }*/ /** * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来 * * @param bondLogicalService */ public DataListener(BondLogicalService bondLogicalService) { this.bondLogicalService = bondLogicalService; } /** * 这个每一条数据解析都会来调用 * * @param bondTrade * one row value. Is is same as {@link AnalysisContext#readRowHolder()} * @param context */ @Override public void invoke(BondTrade bondTrade, AnalysisContext context) { list.add(bondTrade); // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM if (list.size() >= BATCH_COUNT) { saveData(list); // 存储完成清理 list list.clear(); } } /** * 所有数据解析完成了 都会来调用 * * @param context */ @Override public void doAfterAllAnalysed(AnalysisContext context) { // 这里也要保存数据,确保最后遗留的数据也存储到数据库 saveData(list); LOGGER.info("所有数据解析完成!"); } /** * 加上存储数据库 */ private void saveData(List<BondTrade> bondTrades) { for(BondTrade bondTrade:bondTrades){ bondLogicalService.addBondTrade(bondTrade); } System.out.println("存储数据"); } }<file_sep>/fa-web/src/main/java/com/yidu/stock/controller/StockLogicalController.java package com.yidu.stock.controller; import com.alibaba.excel.EasyExcel; import com.yidu.format.LayuiFormat; import com.yidu.stock.Listener.DataListener; import com.yidu.stock.domain.StockTrade; import com.yidu.stock.paging.StockTradePaging; import com.yidu.stock.service.StockLogicalService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; /** * 类的描述:股票详细业务的逻辑处理,控制器层 * * @author 江北 * @since 2020/9/11 13:03 */ @RestController @RequestMapping("/stockTrade") public class StockLogicalController { @Autowired private StockLogicalService stockLogicalService; /** * 搜索查询所有股票交易数据并分页 * @param stockTradePaging 搜索分页参数 * @return 债券交易集合的layui格式数据 */ @ResponseBody @RequestMapping("/list") public LayuiFormat findStockTrade(StockTradePaging stockTradePaging){ return stockLogicalService.findStockTrade(stockTradePaging); } /** * * @param stockTradeIds 股票交易数据ids * @param tradeStatus 交易状态 * @return 1:修改成功,0:修改失败 */ @ResponseBody @RequestMapping("/settlements") public String settlements(String stockTradeIds , String tradeStatus){ //将传来的多个id转换为String数组 String[] ids = stockTradeIds.split(","); //循环ids数组,进行业务处理 int flag = 0; for(String stockTradeId : ids){ flag = stockLogicalService.settlementsT(stockTradeId,tradeStatus); } return flag==1 ? "1": "0"; } /** * Excel数据导入,保存至数据库 * @param file * @return 1:导入成功,0导入出错 */ @RequestMapping("/poi") public String addStockTrade(@RequestParam MultipartFile file) { try { System.out.println(file); InputStream InputStream = file.getInputStream(); System.out.println(InputStream); EasyExcel.read(InputStream, StockTrade.class,new DataListener(stockLogicalService)).sheet().doRead(); } catch (Exception e) { e.printStackTrace(); return "0"; } //1:导入成功,0导入出错 return "1"; } } <file_sep>/fa-web/src/main/java/com/yidu/bond/controller/BondController.java package com.yidu.bond.controller; import com.yidu.bond.domain.Bond; import com.yidu.bond.paging.BondPaging; import com.yidu.bond.service.BondService; import com.yidu.format.LayuiFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * 类的描述: 债券基础操作 * * @author wh * @since 2020/9/3 13:16 */ @RestController @RequestMapping("/bond") public class BondController { @Autowired private BondService bondService; /** * 搜索查询债券+分页 * @param bondPaging 分页搜索查询 * @return 债券数据及相关数据 */ @RequestMapping("/list") public LayuiFormat findAll(BondPaging bondPaging){ return bondService.findAll(bondPaging); } /** * 添加债券 * @param bond 债券对象 * @return 1:添加成功,0:添加失败 */ @RequestMapping("/add") public String addBond(Bond bond){ int flag = bondService.addBond(bond); //返回修改成功与否1:成功,0:失败 return flag == 1 ? "1" : "0"; } /** * 修改债券状态 * @param usable 1:可用,0:禁用 * @param bondIds 修改的债券ids * @return 是否修改成功1:成功,0失败 */ @RequestMapping("/updateUsable") public String updateUsable(@RequestParam("usable") String usable,@RequestParam("bondIds") String bondIds){ int flag = bondService.updateUsable(usable,bondIds); //返回修改成功与否1:成功,0:失败 return flag == 1 ? "1" : "0"; } /** * 修改债券 * @param bond 修改对象 * @return 1:修改成功,0:修改失败 */ @RequestMapping("/update") public String updateBond(Bond bond){ int flag = bondService.updateBond(bond); return flag == 1 ? "1" : "0"; } } <file_sep>/fa-base/src/main/java/com/yidu/fund/service/impl/FundServiceImpl.java package com.yidu.fund.service.impl; import com.yidu.deposit.domain.CashInventory; import com.yidu.deposit.domain.FundInventory; import com.yidu.format.LayuiFormat; import com.yidu.fund.dao.FundDao; import com.yidu.fund.domain.Fund; import com.yidu.fund.paging.FundPaging; import com.yidu.fund.service.FundService; import com.yidu.manage.domain.Account; import com.yidu.manage.domain.FundCompany; import com.yidu.user.dao.UserDao; import com.yidu.user.domain.User; import com.yidu.utils.IDUtil; import com.yidu.utils.NoUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 类的描述: * * @Author 李昊林 * @Date 2020/9/3 15:05 */ @Service public class FundServiceImpl implements FundService { @Autowired private FundDao fundDao; @Autowired private LayuiFormat layuiFormat; @Autowired private UserDao userDao; @Override public LayuiFormat findAllFundWithPage(FundPaging fundPaging) { fundPaging.setPage((fundPaging.getPage()-1)*fundPaging.getLimit()); List<Fund> fundList = fundDao.findAllFundWithPage(fundPaging); layuiFormat.setCode(0); layuiFormat.setMsg("OK"); layuiFormat.setData(fundList); fundPaging.setLimit(null); fundPaging.setPage(null); Long count = fundDao.countFundByCondition(fundPaging); layuiFormat.setCount(count); return layuiFormat; } @Override public LayuiFormat findFundByCondition(FundPaging fundPaging) { //计算分页起始行 fundPaging.setPage((fundPaging.getPage()-1)*fundPaging.getLimit()); List<Fund> fundList = fundDao.findFundByCondition(fundPaging); if(fundList.isEmpty()){ layuiFormat.setCode(0); layuiFormat.setMsg("fail"); layuiFormat.setCount(0L); layuiFormat.setData(null); }else { layuiFormat.setCode(0); layuiFormat.setMsg("OK"); layuiFormat.setData(fundList); fundPaging.setLimit(null); fundPaging.setPage(null); Long count = fundDao.countFundByCondition(fundPaging); layuiFormat.setCount(count); } return layuiFormat; } @Override public Long countFundByCondition(FundPaging fundPaging) { return fundDao.countFundByCondition(fundPaging); } @Override public int updateFund(Fund fund) { if(fundDao.updateFund(fund)){ System.out.println("业务层:" + fund.getFundCompanyId() +" " +fund.getManagerId()); return 1; } return 0; } @Override public boolean updateFundStatus(String fundId,String usable) { String[] ids = fundId.split(","); Map<String,Object> paramMap = new HashMap<>(); paramMap.put("usable",usable); boolean result = false; for (String id : ids) { paramMap.put("fundId",id); result = fundDao.updateFundStatus(paramMap); if(!result) throw new RuntimeException("修改失败,请检查数据"); } return result; } @Override public Map<String,Object> findUserAndFundCompany(){ List<User> userList = userDao.findAllUser(); List<FundCompany> fundCompanies = fundDao.findAllFundCompany(); Map<String,Object> resultMap = new HashMap<>(); resultMap.put("users",userList); resultMap.put("fundCompanies",fundCompanies); return resultMap; } @Override public Map<String,Object> addFund(Fund fund) { //调用Id工具类生成并设置基金Id fund.setFundId(IDUtil.getUuid()); //设置可用状态为禁用 fund.setUsable("N"); //添加基金到数据库 boolean fundFlag = fundDao.addFund(fund); //调用添加基金库存到数据库的方法 boolean fundInventoryFlag = addFundInventory(fund); Map<String,Object> resultMap = new HashMap<>(); if (fundFlag && fundInventoryFlag) { resultMap.put("result",1); }else{ resultMap.put("result",0); throw new RuntimeException("保存失败,请检测数据"); } return resultMap; } @Override public boolean addFundInventory(Fund fund) { //创建基金库存对象 FundInventory fundInventory = new FundInventory(); //根据基金对象设置库存信息 fundInventory.setFundInventoryId(IDUtil.getUuid()); fundInventory.setFundInventoryNo(NoUtils.getNo("JJKC")); fundInventory.setFundId(fund.getFundId()); fundInventory.setFundNo(fund.getFundNo()); fundInventory.setFundName(fund.getFundName()); fundInventory.setShare(fund.getFundScale().divide(fund.getNav()).toBigInteger()); fundInventory.setBalance(fund.getFundScale().multiply(fund.getNav())); fundInventory.setStatisticalDate(new Date()); fundInventory.setDescription(fund.getDescription()); //调用添加现金库存到数据库的方法 boolean cashInventoryFlag = addCachInventory(fundInventory); //添加基金库存到数据库 boolean fundInventoryFlag = fundDao.addFundInventory(fundInventory); return cashInventoryFlag && fundInventoryFlag; } @Override public boolean addCachInventory(FundInventory fundInventory) { //创建现金库存对象 CashInventory cashInventory = new CashInventory(); //根据基金库存设置现金库存信息 cashInventory.setCashInventoryId(IDUtil.getUuid()); cashInventory.setCashInventoryNo(NoUtils.getNo("XJKC")); cashInventory.setFundId(fundInventory.getFundId()); cashInventory.setFundNo(fundInventory.getFundNo()); cashInventory.setFundName(fundInventory.getFundName()); cashInventory.setCashBalance(fundInventory.getBalance()); cashInventory.setStatisticalDate(fundInventory.getStatisticalDate()); cashInventory.setDescription(fundInventory.getDescription()); //根据账户信息设置现金库存中的账户信息 Account account = fundDao.findAccountByFundId(fundInventory.getFundNo()); if (account != null) { cashInventory.setAccountId(account.getAccountId()); cashInventory.setAccountNo(account.getAccountNo()); cashInventory.setAccountName(account.getAccountName()); }else{ throw new RuntimeException("没有对应的账户信息,请先开户!"); } //将现金库存信息添加到数据库 return fundDao.addCashInventory(cashInventory); } } <file_sep>/fa-base/src/main/java/com/yidu/deposit/service/CashInventoryService.java package com.yidu.deposit.service; import com.yidu.deposit.paging.CashInventoryPaging; import com.yidu.deposit.domain.CashInventory; import java.util.List; /** * 类的描述: 现金库存业务逻辑接口层 * @author wh * @since 2020/9/11 14:40 */ public interface CashInventoryService { /** * 模糊加分页查询所有现金库存 * @param cashInventoryPaging 现金库存对象 * @return 金库存数据集合 */ List<CashInventory> findAll(CashInventoryPaging cashInventoryPaging); /** * 模糊加分页查询所有现金库存数量 * @param cashInventoryPaging 现金库存对象 * @return 金库存数据条数 */ Long findCashInventoryCount(CashInventoryPaging cashInventoryPaging); } <file_sep>/fa-base/src/main/java/com/yidu/deposit/dao/DepositTradeDao.java package com.yidu.deposit.dao; import com.yidu.capital.domain.CapitalTransfer; import com.yidu.deposit.domain.CashInventory; import com.yidu.deposit.domain.DepositTrade; import com.yidu.deposit.paging.DepositTradePaging; import com.yidu.index.domain.SecuritiesInventory; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * 类的描述:... * * @author 蔡任骋 * @version 1.0 * @since 2020/09/10 */ public interface DepositTradeDao { /** * 1.添加存款交易数据 * @param depositTrade 存款交易数据 * @return 成功返回1,否则返回0 */ int addDeposit(DepositTrade depositTrade); /** * 2.1.查询满足条件的银行交易数据的数量 * @param depositTradePaging 包含条件的实体类 * @return 成功返回数量,否则返回0 */ long countDepositTradeByCondition(DepositTradePaging depositTradePaging); /** * 2.2.查询满足条件的银行交易数据 * @param depositTradePaging 包含条件的实体类 * @return 成功返回数据的集合,否则返回null */ List<DepositTrade> findDepositByCondition(DepositTradePaging depositTradePaging); /** * 3.1.修改银行交易数据状态 * @param paramMap 包含状态的map集合 * @return 成功返回true,否则返回false */ boolean updateTransactionStatus(Map<String,Object> paramMap); /** * 3.2.1.添加资金调拨数据 * @param capitalTransfer 要添加的资金调拨数据 * @return 成功返回true,否则返回false */ boolean addBankTreasurer(CapitalTransfer capitalTransfer); /** * 3.2.2.根据ID查询银行交易数据 * @param depositId 银行交易数据ID * @return 银行交易数据对象集合 */ DepositTrade findDepositById(String depositId); /** * 3.3.1.根据条件查询满足的证券库存数据 * @param paramMap 包含条件的map * @return 成功返回对象,否则返回null */ SecuritiesInventory findSecuritiesInventoryByCondition(Map<String,Object> paramMap); /** * 3.3.2.添加证券库存数据 * @param securitiesInventory 添加对象 * @return 成功返回true,否则返回false */ boolean addSecuritiesInventory(SecuritiesInventory securitiesInventory); /** * 3.3.3.修改对应的证券库存数据 * @param paramMap 包含修改条件的map * @return 成功返回true,否则返回false */ boolean updateSecuritiesInventory(Map<String,Object> paramMap); /** * 3.4.1.查询今天的现金库存数据 * @param paramMap 包含条件的map * @return 成功返回对象,否则返回null */ CashInventory findCashInventoryByCondition(Map<String,Object> paramMap); /** * 3.4.2.查询最近一条现金库存数据 * @param fundId 基金ID * @return 成功返回现金库存数据,否则返回null */ CashInventory findCashInventoryByFundId(@Param("fundId") String fundId,@Param("accountId") String accountId); /** * 3.4.3.添加现金库存数据 * @param cashInventory 现金库存数据 * @return 成功返回true,否则返回false */ boolean addCashInventory(CashInventory cashInventory); /** * 3.4.4.修改今天的现金库存数据 * @param paramMap2 包含条件的map * @return 成功返回对象,否则返回null */ boolean updateCashInventory(Map<String,Object> paramMap2); } <file_sep>/fa-base/src/main/java/com/yidu/index/service/SecuritiesInventoryService.java package com.yidu.index.service; import com.yidu.index.domain.SecuritiesInventory; import com.yidu.index.paging.SecuritiesInventoryPaging; import java.util.List; /** * 类的描述:证券库存业务逻辑层接口类 * * @author wh * @since 2020/9/14 9:10 */ public interface SecuritiesInventoryService { /** * 通过搜索词 查询所有 * @param securitiesInventoryPaging 搜索词对象 * @return 证券库存集合 */ List<SecuritiesInventory> findAll(SecuritiesInventoryPaging securitiesInventoryPaging); /** * 通过搜索词 查询所有的条数 * @param securitiesInventoryPaging 搜索词对象 * @return 条数 */ Long findCount(SecuritiesInventoryPaging securitiesInventoryPaging); } <file_sep>/fa-base/src/main/java/com/yidu/index/paging/SecuritiesInventoryPaging.java package com.yidu.index.paging; import java.math.BigInteger; import java.util.Date; /** * 类的描述:证券库存搜索字段实体对象 * * @author wh * @since 2020/9/14 21:49 */ public class SecuritiesInventoryPaging { /** * 证券编号 */ private String securitiesNo; /** * 证券名 */ private String securitiesName; /** * 基金代码 */ private String fundNo; /** * 基金名 */ private String fundName; /** * 证劵类型,1股票 2债券 3 银行存款 */ private int securitiesType; /** * 统计日期,搜索起始日期 */ private Date startStatisticalDate; /** * 统计日期,搜索终止日期 */ private Date endStatisticalDate; private int page; private int limit; public String getSecuritiesNo() { return securitiesNo; } public void setSecuritiesNo(String securitiesNo) { this.securitiesNo = securitiesNo; } public String getSecuritiesName() { return securitiesName; } public void setSecuritiesName(String securitiesName) { this.securitiesName = securitiesName; } public String getFundNo() { return fundNo; } public void setFundNo(String fundNo) { this.fundNo = fundNo; } public String getFundName() { return fundName; } public void setFundName(String fundName) { this.fundName = fundName; } public int getSecuritiesType() { return securitiesType; } public void setSecuritiesType(int securitiesType) { this.securitiesType = securitiesType; } public Date getStartStatisticalDate() { return startStatisticalDate; } public void setStartStatisticalDate(Date startStatisticalDate) { this.startStatisticalDate = startStatisticalDate; } public Date getEndStatisticalDate() { return endStatisticalDate; } public void setEndStatisticalDate(Date endStatisticalDate) { this.endStatisticalDate = endStatisticalDate; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } } <file_sep>/fa-base/src/main/java/com/yidu/deposit/domain/CasharapInventory.java package com.yidu.deposit.domain; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * 类的描述:现金应收应付库存POJO * @author 李昊林 * @date 2020-09-18 */ public class CasharapInventory implements Serializable{ private static final long serialVersionUID = 8583412743049350036L; /** * 现金应收应付库存Id */ private String cachArapInventoryId; /** * 现金应收应付库存编号 */ private String cachArapInventoryNo; /** * 基金Id */ private String fundId; /** * 基金代码 */ private String fundNo; /** * 基金名 */ private String fundName; /** * 账户Id */ private String accountId; /** * 账号 */ private String accountNo; /** * 账户名 */ private String accountName; /** * 余额 */ private BigDecimal balance; /** * 业务日期 */ private Date businessDate; /** * 业务类型 */ private int businessType; /** * 应收应付标识 */ private int flag; /** * 描述 */ private String description; public CasharapInventory() { } public String getCachArapInventoryId() { return cachArapInventoryId; } public void setCachArapInventoryId(String cachArapInventoryId) { this.cachArapInventoryId = cachArapInventoryId; } public String getCachArapInventoryNo() { return cachArapInventoryNo; } public void setCachArapInventoryNo(String cachArapInventoryNo) { this.cachArapInventoryNo = cachArapInventoryNo; } public String getFundId() { return fundId; } public void setFundId(String fundId) { this.fundId = fundId; } public String getFundNo() { return fundNo; } public void setFundNo(String fundNo) { this.fundNo = fundNo; } public String getFundName() { return fundName; } public void setFundName(String fundName) { this.fundName = fundName; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } public Date getBusinessDate() { return businessDate; } public void setBusinessDate(Date businessDate) { this.businessDate = businessDate; } public int getBusinessType() { return businessType; } public void setBusinessType(int businessType) { this.businessType = businessType; } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "CasharapInventory{" + "cachArapInventoryId='" + cachArapInventoryId + '\'' + ",cachArapInventoryNo='" + cachArapInventoryNo + '\'' + ",fundId='" + fundId + '\'' + ",fundNo='" + fundNo + '\'' + ",fundName='" + fundName + '\'' + ",accountId='" + accountId + '\'' + ",accountNo='" + accountNo + '\'' + ",accountName='" + accountName + '\'' + ",balance='" + balance + '\'' + ",businessDate='" + businessDate + '\'' + ",businessType='" + businessType + '\'' + ",flag='" + flag + '\'' + ",description='" + description + '\'' + '}'; } } <file_sep>/fa-web/src/main/java/com/yidu/index/controller/SecuritiesInventoryController.java package com.yidu.index.controller; import com.yidu.format.LayuiFormat; import com.yidu.index.domain.SecuritiesInventory; import com.yidu.index.paging.SecuritiesInventoryPaging; import com.yidu.index.service.SecuritiesInventoryService; import com.yidu.utils.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.text.ParseException; import java.util.Date; import java.util.List; /** * 类的描述: * * @author wh * @since 2020/9/14 9:15 */ @RestController @RequestMapping("/securities") public class SecuritiesInventoryController { @Autowired private SecuritiesInventoryService securitiesInventoryService; @Autowired private LayuiFormat layuiFormat; @RequestMapping("/list") public LayuiFormat findAll(SecuritiesInventoryPaging securitiesInventoryPaging){ //计算分页 int limit = securitiesInventoryPaging.getLimit(); int page = (securitiesInventoryPaging.getPage()-1)*limit; securitiesInventoryPaging.setPage(page); securitiesInventoryPaging.setLimit(limit); if(null != securitiesInventoryPaging.getEndStatisticalDate() && null != securitiesInventoryPaging.getStartStatisticalDate() ){ if(securitiesInventoryPaging.getStartStatisticalDate().getTime()>securitiesInventoryPaging.getEndStatisticalDate().getTime()){ //起始值大于终止值,则交换 Date param = securitiesInventoryPaging.getStartStatisticalDate(); securitiesInventoryPaging.setStartStatisticalDate(securitiesInventoryPaging.getEndStatisticalDate()); securitiesInventoryPaging.setEndStatisticalDate(param); } }else{ securitiesInventoryPaging.setEndStatisticalDate(new Date()); try { securitiesInventoryPaging.setStartStatisticalDate(DateUtils.stringToDate("1900-01-01","yyyy-MM-dd")); } catch (ParseException e) { layuiFormat.setCode(1); //状态码0为查询到数据 layuiFormat.setCount(0L); layuiFormat.setMsg("未查询到指定数据哦!"); layuiFormat.setData(null); return layuiFormat; } } List<SecuritiesInventory> securitiesInventorys = securitiesInventoryService.findAll(securitiesInventoryPaging); if (CollectionUtils.isEmpty(securitiesInventorys)){ //集合为空 layuiFormat.setCode(1); //状态码0为查询到数据 layuiFormat.setCount(0L); layuiFormat.setMsg("未查询到指定数据哦!"); layuiFormat.setData(null); }else{ layuiFormat.setCode(0); //状态码0为查询到数据 layuiFormat.setCount(securitiesInventoryService.findCount(securitiesInventoryPaging)); layuiFormat.setMsg("成功找到数据"); layuiFormat.setData(securitiesInventorys); } return layuiFormat; } } <file_sep>/fa-web/src/main/webapp/static/deposit/js/deposit.js /* * layui引入样式的两种方式:模块化用和全模块用法 * layui的初始化模块可以理解为,引入这个模块的js文件 * 值得注意的是:layui的模块之间存在依赖关系,例如引入了table模块,它会layui/lay/moudules/table.js * 这个文件引入进来,并且它还会将这个模块所依赖的其他模块自动加入进来, * 实际引入的模块有:table、form、jquery、layer、laypage、laytpl、util,7个js文件 * 所以我仅仅初始化了table模块,却能获得form、jquery、layer的模块对象 */ //layui初始化表格模组 layui.use(['table', 'laydate', 'upload','element'], function() { // 获得模块对象 var tId = 'depositTradeTable'; var table = layui.table; var form = layui.form; var $ = layui.jquery; var layer = layui.layer; var laydate = layui.laydate; var upload = layui.upload; //下拉搜索框设置 var hideBtn = $("#hideBtn"); var flag = false; var search_header = $("#search-header"); search_header.css("top",-search_header.height()); hideBtn.click(function () { let height = search_header.height(); if(flag){ search_header.animate({ "top":-height },"fast","linear"); flag = false; }else { search_header.animate({ "top":0 },"fast","linear"); flag = true; } }); //----1.数据表格渲染------------------------------------------------------------------ function f(a,b) { var tableIns=table.render({ elem: '#'+ a, url: '/fa/depositController/findDepositByCondition?tradeStatus=' + b, //后期改回获取用户列表的后端程序的url method: 'get', where: {}, // 你额外要携带数据,以键值对的方式存入 toolbar: '#depositToolbar', // 开启头部工具栏,并为其绑定左侧模板 cellMinWidth: 80, // 全局定义所有常规单元格的最小宽度(默认:60) height: 'full-10', cols: [ [{ type: 'numbers' }, // 序号 { type: 'checkbox' }, //复选框 { field: 'depositId', title: '存款Id', unresize: true, hide:true, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'depositNo', title: '存款流水号', unresize: true, width:150, align: "center" }, { field: 'fundId', title: '基金Id', unresize: true, hide:true, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'fundNo', title: '基金代码', unresize: true, align: "center", }, { field: 'fundName', title: '基金名', width:160, unresize: true, align: "center", }, { field: 'outAccountId', title: '流出账户ID', unresize: true, width:130, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'outAccountNo', title: '流出账户账号', unresize: true, hide:true, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'outAccountName', title: '流出账户名', unresize: true, hide: true, align: "center", }, { field: 'inAccountId', title: '流入账户Id', unresize: true, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'inAccountNo', title: '流入账户账号', unresize: true, align: "center", hide: true //一般情况下不显示用户ID }, { field: 'inAccountName', title: '流入账户名', unresize: true, align: "center" }, { field: 'tradeType', title: '交易方式', unresize: true, align: "center", templet: "#tradeStatusTpl2" }, { field: 'tradeFlag', title: '交易标识', unresize: true, align: "center", templet: "#tradeStatusTpl3" }, { field: 'businessDateStr', title: '存款时间', width:105, unresize: true, align: "center" }, { field: 'businessType', title: '存款类型', unresize: true, align: "center", templet: "#tradeStatusTpl4" }, { field: 'money', title: '存款金额', unresize: true, align: "center" }, { field: 'interestRate', title: '存款利率', unresize: true, align: "center" }, { field: 'endDateStr', title: '到期时间', unresize: true, align: "center" }, { field: 'description', title: '描述', unresize: true, align: "center" }, { field: 'tradeStatus', title: '存款状态', unresize: true, align: "center", //fixed:'right', templet: '#tradeStatusTpl' } ] ], page: true, // 开启分页 limit: 10, // 每页显示的条数 limits: [10, 20, 50, 100], // 每页条数的选择项 loading: true, // 是否显示加载条(切换分页的时候显示) title: '基金表', // 定义 table 的大标题(在文件导出等地方会用到) text:{none:'被抽干了!没东西可以给你了,555!!(ㄒoㄒ)~~'}, // 隔行变色 even: false })}; //----1.数据表格渲染------------------------------------------------------------------ f('depositTradeTable',-1); f('depositTradeTable2',1); //----2.头部搜索栏基金交易日期时间选择器-------------------------------------------------------------------- laydate.render({ elem: '#queryTradeDateStart' ,trigger: 'click' }); //头部搜索栏基金交易日期时间选择器 laydate.render({ elem: '#queryTradeDateEnd' ,trigger: 'click' }); //----3.处理头部条件组合搜素------------------------------------------------------------------ form.on('submit(fundSearchBtn)', function(data) { //将搜索下列框收回 let height = search_header.height(); if(flag){ search_header.animate({ "top":-height },"fast","linear"); flag = false; }else { search_header.animate({ "top":0 },"fast","linear"); flag = true; } console.log(data.field); //定义局部变量 let b; tId == "depositTradeTable" ? b = -1 : b = 1; // 执行后台代码depositTradeTable alert(tId); table.reload(tId, { url: '/fa/depositController/findDepositByCondition?tradeStatus='+ b, where: data.field, // 设定异步数据接口的额外参数,任意设 page: { curr: 1 //从第一页开始 }, limit: 10 }); return false; // 阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); //----3.处理表行修改------------------------------------------------------------------ // table.on("tool(fundTableEvent)",function (obj) { // var data = obj.data; // console.log(data); // if (obj.event == "update"){ // initUpdatefundModal(data); // } // }); // 基金交易未结算数据表头部工具栏结算|导入按钮的事件句柄绑定 table.on('toolbar(depositTableEvent)', function(obj) { // 获取当前表格选中状态和选中的数据 var checkStatus = table.checkStatus(obj.config.id); // 区分点击的按钮 switch(obj.event) { case 'upload': // 弹出上传模态框 initUploadModal(); break; case 'settlement': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(!checkStatus.isAll) { layer.msg("请全选你要结算的数据!!", { icon: 4 //图标,可输入范围0~6 }); return; } // 定义一个要结算的所有交易数据ID的字符串 var depositTradeIdStr = ""; // 遍历传递过来的要结算的数据 for(var i = 0; i < data.length; i++) { if(data[i].tradeStatus == '1') { layer.msg("所选数据中有已结算数据!", { icon: 1 // 图标,可输入范围0~6 }); return; } // 拿出基金交易数据Id进行拼接 depositTradeIdStr += data[i].depositId + ","; } // 截取掉因为拼接产生的多余的一个逗号 depositTradeIdStr = depositTradeIdStr.substring(0, depositTradeIdStr.length - 1); // 调用修改基金状态请求方法 updateTradeStatus(depositTradeIdStr, '1'); break; /*case 'restoreRecord': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要还原的用户!!", { icon: 4 //图标,可输入范围0~6 }); } // 定义一个要删除的所有资源ID的字符串 var fundIdStr = ""; // 遍历传递过来的要删除的数据 for(var i = 0; i < data.length; i++) { if(data[i].usable == 'Y') { layer.msg("所选用户中有可用的用户!", { icon: 1 // 图标,可输入范围0~6 }); return; } // 拿出资源ID进行拼接 fundIdStr += data[i].fundId + ","; } // 截取掉因为拼接产生的多余的一个逗号 fundIdStr = fundIdStr.substring(0, fundIdStr.length - 1); frozenORrecoverArchives(fundIdStr,'Y'); break;*/ }; }); // 定义修改交易状态请求方法 var updateTradeStatus = function(depositIds,tradeStatus) { $.ajax({ url:"/fa/depositController/depositTradeSettlement", type:'post', data:{ depositIds:depositIds, tradeStatus:tradeStatus }, success:function (data) { console.log(data); if(data) { layer.msg("结算成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg("结算失败!", { icon: 1 // 图标,可输入范围0~6 }); } f('depositTradeTable',-1); f('depositTradeTable2',1); } }) }; // 初始化上传模态框 var initUploadModal = function(data) { // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '', // 标题 skin: "", anim: 2, // 弹出动画 area: ["100%",'100%'], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#upload"), // 文本、html都行 resize: false, // 是否允许拉伸 // end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) // // 清空表单 // $("#addfundForm")[0].reset(); // $("#demo1").attr("src", ""); // $("#demoText").text(""); // } }); // 表单赋值 // form.val('updateFundForm', { // "fundId": data.fundId, // "fundNo": data.fundNo, // "fundName": data.fundName, //layui.util.toDateString(data.commonStart, 'HH:mm:ss'), // "estDate": data.estDateStr, // "managerName": data.managerName, // "trusteeBank": data.trusteeBank, // "fundScale": data.fundScale, // "nav": data.nav, // "managementFee":data.managementFee, // "trusteeFee": data.trusteeFee, // "billingDays": data.billingDays, // "fundCompanyId": data.fundCompanyId, // "comShortName": data.comShortName, // "description": data.description, // }); }; //获取选中下拉列表的值 var managerIdVal; form.on('select', function(data){ let obj = data.elem; if($(data.elem).attr("id") == "updateManagerName") managerIdVal = $(obj).children("[value='"+data.value+"']").attr("managerId"); if($(data.elem).attr("id") == "addManagerName") managerIdVal = $(obj).children("[value='"+data.value+"']").attr("managerId"); console.log(managerIdVal); //联动显示基金公司id //根据父元素ID判断是否是添加模态框里的选择事件 if($(data.elem).attr("id") == "addComShortName") $("#addFundCompanyId").val($(data.elem).children("[value='"+ data.value+"']").attr("fundCompanyId")); //根据父元素ID判断是否是修改模态框里的选择事件 if($(data.elem).attr("id") == "updateComShortName") $("#updateFundCompanyId").val($(data.elem).children("[value='"+ data.value+"']").attr("fundCompanyId")); console.log($(data.elem).children("[value='"+ data.value+"']").attr("fundCompanyId")) }); //----4.处理新增用户表单提交-------------------------------------------------------------- form.on('submit(addFundBtn)',function(data) { let addFundForm = form.val("addFundForm"); // $("#fundCompanyId").val(data.value); // 执行后台代码 $.ajax({ type:'POST', //适用RESTful风格的添加: 查询GET、添加POST、更新PUT、删除DELETE async:false, url:'../saveFund', //后期改为添加用户的后台程序的url data:{ fundNo:addFundForm.fundNo, fundName:addFundForm.fundName, fundCompanyId:addFundForm.fundCompanyId, trusteeBank:addFundForm.trusteeBank, fundScale:addFundForm.fundScale, nav:addFundForm.nav, trusteeFee:addFundForm.trusteeFee, managementFee:addFundForm.managementFee, billingDays:addFundForm.billingDays, managerId:managerIdVal, managerName:addFundForm.managerName, estDate:addFundForm.estDate, comShortName:addFundForm.comShortName, description:addFundForm.description, }, // data:data.field, success: function(data) { console.log(data.result) // 关闭页面上所有类型的所有弹框 layer.closeAll(); if(data.result == 1) { layer.msg("添加成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg("添加失败!", { icon: 1 // 图标,可输入范围0~6 }); } } }); // 刷新数据表格 table.reload('fundTable', { url: '../findFundByCondition' //后期改为查询用户的后台程序的url }); return false; // 阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); //----5.处理修改基金表单提交-------------------------------------------------------------- form.on('submit(updatefundBtn)', function(data) { let updateFundForm = form.val("updateFundForm"); //执行后台代码 $.ajax({ type: 'POST', //适用RESTful风格的添加: 查询GET、添加POST、更新PUT、删除DELETE async: false, url: '../updateFund', //后期改为修改用户的后台程序url data: { fundId:updateFundForm.fundId, fundCompanyId:updateFundForm.fundCompanyId, trusteeFee:updateFundForm.trusteeFee, managementFee:updateFundForm.managementFee, billingDays:updateFundForm.billingDays, managerId:managerIdVal, managerName:updateFundForm.managerName, comShortName:updateFundForm.comShortName, description:updateFundForm.description, },//data.field success: function(data) { //关闭页面上所有类型的所有弹框 layer.closeAll(); if(data == 1) { layer.msg("修改成功!", { icon: 1 //图标,可输入范围0~6 }); } else { layer.msg("修改失败!", { icon: 1 //图标,可输入范围0~6 }); } } }); //刷新数据表格 table.reload('fundTable', { url: '../findFundByCondition' // }); return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); // 监听锁定操作 form.on('switch(usable)', function(obj) { frozenORrecoverArchives(obj.value, this.checked == true ? 'Y' : 'N'); }); // 定义冻结或还原的方法 var frozenORrecoverArchives = function(fundIdStr, status) { // 用户ID var fundId = fundIdStr; // 定义提示信息, 状态 var msg, usable; if(status == 'Y') { msg = "还原", usable = 'Y'; } else { msg = "禁用", usable = 'N'; } // 发送异步请求冻结或还原资源 $.ajax({ async: false, // 默认为true,false表示同步,如果当前请求没有返回则不执行后续代码 type: "DELETE", url:'../updateFundStatus/' + fundId + "/" + usable,// /updatefund '/updatefundStatus/' + fundIds + "/" + usable data: { // fundId:fundId, // usable:usable, // _method: 'DELETE' }, datatype: 'json', success: function(data) { if(data.result == "1") { layer.msg(msg + "成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg(msg + "失败!", { icon: 2 }); } // 刷新数据表格 table.reload('fundTable', { url: '../findFundByCondition' }); } }); }; // $.ajax({ // url: '../findUserAndFundCompany',//system/org', // dataType: 'json', // type: 'get', // success: function(data) { // $.each(data.result, function(index) { // var managerId = data.result[index].userId; // var managerName = data.result[index].userName; // /* var sdSdd = data[index].sdSdd; */ // // 添加模态框基金经理名动态添加下拉列表 // $("#addManagerName").append( // "<option managerId='" + managerId + "' value='" + managerName + "'>" + managerName + // "</option>"); // // 修改模态框基金经理名动态添加下拉列表 // $("#updateManagerName").append( // "<option managerId='" + managerId + "' value='" + managerName + "'>" + managerName + // "</option>"); // // 添加 // $("#addComShortName").append( // "<option fundCompanyId='" + managerId + "' value='" + managerName + "'>" + managerName + // "</option>"); // // 修改 // $("#updateComShortName").append( // "<option fundCompanyId='" + managerId + "' value='" + managerName + "'>" + managerName + // "</option>"); // form.render();//渲染将option添加进去 // }); // } // }); upload.render({ elem:'#upload', accept: 'file', url:"/fa/depositController/upload", done: function(res){ //上传完毕回调 layer.closeAll(); alert(res.success); layer.msg(res.success); // 刷新数据表格 table.reload('depositTradeTable', { url: '/fa/depositController/findDepositByCondition?b=0' }); table.reload('depositTradeTable', { url: '/fa/depositController/findDepositByCondition?b=1' }); } ,error: function(){ //请求异常回调 layer.msg("上传失败,请检查数据格式是否正确"); }, }); // 自定义表单校验 /*form.verify({ pass: [ /^[\S]{6,12}$/, '密码必须6到12位,且不能出现空格'], mobile: function(value) { var msg; $.ajax({ type: "POST", url: '../verifyTelephone',//system/toVerifyfundPhone async: false, // 使用同步的方法 data: { 'telephone': value }, dataType: 'json', success: function(result) { if(result.flag) { msg = result.msg; } } }); return msg; } });*/ }); <file_sep>/fa-base/src/main/java/com/yidu/stock/dao/StockDao.java package com.yidu.stock.dao; import com.yidu.stock.domain.Stock; import java.util.List; import java.util.Map; /** * 类的描述:股票数据层 * @author 江北 * @version 1.0 * since 2020/09/09 */ public interface StockDao { List<Stock> findAllStockWithPaging(Map<String,Integer> paramMap); long countStockByCondition(Map<String,Object> paramMap); List<Stock> findAllStock(); List<Stock> findStockByCondition(Map<String,Object> paramMap); boolean addStock(Stock stock); boolean updateStock(Stock stock); boolean updateStockStatus(Map<String, Object> paramMap); // void addStock(Stock ); } <file_sep>/fa-base/src/main/java/com/yidu/fund/service/CalculateRevenueService.java package com.yidu.fund.service; import com.yidu.deposit.domain.CashInventory; import com.yidu.deposit.domain.FundInventory; import com.yidu.deposit.paging.CashInventoryPaging; import com.yidu.deposit.paging.FundInventoryPaging; import com.yidu.format.LayuiFormat; import com.yidu.fund.paging.CalculateRevenuePaging; import java.util.List; /** * 类的描述:基金收益计提业务层 * @Author 李昊林 * @Date 2020/9/15 16:31 */ public interface CalculateRevenueService { /** * 根据条件查询基金库存 * @param fundInventoryPaging 基金库存分页字段 * @return 基金库存对象集合 */ List<FundInventory> findFundInventoryByCondition(FundInventoryPaging fundInventoryPaging); /** * 根据条件统计基金库存数量 * @param fundInventoryPaging 基金库存分页字段 * @return 基金库存数量 */ Long findCountFundInventoryByCondition(FundInventoryPaging fundInventoryPaging); /** * 根据基金库存id处理两费计提 * @param fundInventoryIds 基金库存id * @return 计提成功返回true,否则返回false */ boolean doFeeCalculate(String fundInventoryIds); /** * 根据条件查询现金库存 * @param cashInventoryPaging 现金库存分页字段 * @return 现金库存对象集合 */ List<CashInventory> findCashInventoryByCondition(CashInventoryPaging cashInventoryPaging); /** * 根据条件统计现金库存数量 * @param cashInventoryPaging 现金库存分页字段 * @return 现金库存数量 */ Long findCountCashInventoryByCondition(CashInventoryPaging cashInventoryPaging); /** * 根据现金库存id处理现金计息 * @param cashInventoryIds 现金库存id * @return 计息成功返回true,否则返回false */ boolean doCashInterest(String cashInventoryIds); } <file_sep>/fa-utils/src/main/java/com/yidu/utils/DateUtils.java package com.yidu.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * 类的描述: * * @author wh * @since 2020/7/22 17:40 */ public class DateUtils { //日期转换成字符串 public static String dataToString(Date date,String patt){ SimpleDateFormat sdf=new SimpleDateFormat(patt); String format = sdf.format(date); return format; } /** * //字符串转换传成日期 * @param str 格式还的日期 * @param patt 以这种方式进行解析 * @return 日期对象 * @throws ParseException 抛出异常 */ public static Date stringToDate(String str,String patt) throws ParseException { SimpleDateFormat sdf=new SimpleDateFormat(patt); Date parse = sdf.parse(str); return parse; } /** * 今天零点零分零秒的毫秒数 * @param date 日期对象 * @return 这个日期对象的零点零分零秒的毫秒数 */ public static Long ZeroDate(Date date){ return date.getTime()/(1000*3600*24)*(1000*3600*24)- TimeZone.getDefault().getRawOffset(); } public static void main(String[] args){ System.out.println(DateUtils.ZeroDate(new Date())); } } <file_sep>/fa-base/src/main/java/com/yidu/index/service/impl/SecuritiesInventoryServiceImpl.java package com.yidu.index.service.impl; import com.yidu.index.dao.SecuritiesInventoryDao; import com.yidu.index.domain.SecuritiesInventory; import com.yidu.index.paging.SecuritiesInventoryPaging; import com.yidu.index.service.SecuritiesInventoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 类的描述:证券库存业务逻辑层实现类 * * @author wh * @since 2020/9/14 9:10 */ @Service public class SecuritiesInventoryServiceImpl implements SecuritiesInventoryService { @Autowired private SecuritiesInventoryDao securitiesInventoryDao; @Override public List<SecuritiesInventory> findAll(SecuritiesInventoryPaging securitiesInventoryPaging) { return securitiesInventoryDao.findAll(securitiesInventoryPaging); } @Override public Long findCount(SecuritiesInventoryPaging securitiesInventoryPaging) { return securitiesInventoryDao.findCount(securitiesInventoryPaging); } } <file_sep>/fa-base/src/main/java/com/yidu/index/domain/SecuritiesInventory.java package com.yidu.index.domain; import com.yidu.utils.DateUtils; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; /** * 证劵库存表 * POJO_Description: SecuritiesInventory * @author wh * @since 2020-09-09 */ public class SecuritiesInventory implements Serializable{ private static final long serialVersionUID = 2066767366243467631L; /** * 证劵库存Id securitiesInventoryId */ private String securitiesInventoryId; /** * 证劵库存编号ZQKC-yyyy-MM-dd-xxxxx */ private String sechuritiesInventoryNo; /** * 证券Id参考的是 股票|债券|银行存款表的主键 */ private String securitiesId; /** * 证券编号 */ private String securitiesNo; /** * 证券名 */ private String securitiesName; /** * 基金Id */ private String fundId; /** * 基金代码 */ private String fundNo; /** * 基金名 */ private String fundName; /** * 账户Id */ private String accountId; /** * 账号 */ private String accountNo; /** * 账户名 */ private String accountName; /** * 单位成本,股票|债券|银行理财产品的单份价值 */ private BigDecimal price; /** * 持有份额 */ private BigInteger share; /** * 总金额 = 单位净值 * 份额 */ private BigDecimal turnover; /** * 证劵类型,1股票 2债券 3 银行存款 */ private int securitiesType; /** * 证劵类型字符串格式 */ private String securitiesTypeStr; /** * 统计日期 */ private Date statisticalDate; /** * 统计日期字符串格式 */ private String statisticalDateStr; /** * 描述 */ private String description; /** * 备用字段 */ private String remark1; /** * 备用字段 */ private String remark2; /** * 备用字段 */ private String remark3; /** * 计息状态 0未计息 1已计息 */ private Integer tradeStatus; public Integer getTradeStatus() { return tradeStatus; } public void setTradeStatus(Integer tradeStatus) { this.tradeStatus = tradeStatus; } public SecuritiesInventory() { } public String getSecuritiesInventoryId() { return securitiesInventoryId; } public void setSecuritiesInventoryId(String securitiesInventoryId) { this.securitiesInventoryId = securitiesInventoryId; } public String getSechuritiesInventoryNo() { return sechuritiesInventoryNo; } public void setSechuritiesInventoryNo(String sechuritiesInventoryNo) { this.sechuritiesInventoryNo = sechuritiesInventoryNo; } public String getSecuritiesId() { return securitiesId; } public void setSecuritiesId(String securitiesId) { this.securitiesId = securitiesId; } public String getSecuritiesNo() { return securitiesNo; } public void setSecuritiesNo(String securitiesNo) { this.securitiesNo = securitiesNo; } public String getSecuritiesName() { return securitiesName; } public void setSecuritiesName(String securitiesName) { this.securitiesName = securitiesName; } public String getFundId() { return fundId; } public void setFundId(String fundId) { this.fundId = fundId; } public String getFundNo() { return fundNo; } public void setFundNo(String fundNo) { this.fundNo = fundNo; } public String getFundName() { return fundName; } public void setFundName(String fundName) { this.fundName = fundName; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigInteger getShare() { return share; } public void setShare(BigInteger share) { this.share = share; } public BigDecimal getTurnover() { return turnover; } public void setTurnover(BigDecimal turnover) { this.turnover = turnover; } public int getSecuritiesType() { return securitiesType; } public void setSecuritiesType(int securitiesType) { this.securitiesType = securitiesType; if(securitiesType == 1){ this.securitiesTypeStr = "股票"; }else if(securitiesType == 2){ this.securitiesTypeStr = "债券"; }else if(securitiesType == 3){ this.securitiesTypeStr = "银行存款"; } } public Date getStatisticalDate() { return statisticalDate; } public void setStatisticalDate(Date statisticalDate) { this.statisticalDate = statisticalDate; if(null != statisticalDate){ this.statisticalDateStr = DateUtils.dataToString(statisticalDate,"yyyy-MM-dd HH:mm:ss"); } } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getStatisticalDateStr() { return statisticalDateStr; } public String getSecuritiesTypeStr() { return securitiesTypeStr; } public String getRemark1() { return remark1; } public void setRemark1(String remark1) { this.remark1 = remark1; } public String getRemark2() { return remark2; } public void setRemark2(String remark2) { this.remark2 = remark2; } public String getRemark3() { return remark3; } public void setRemark3(String remark3) { this.remark3 = remark3; } @Override public String toString() { return " SecuritiesInventory{" + "securitiesInventoryId='" + securitiesInventoryId + '\'' + "sechuritiesInventoryNo='" + sechuritiesInventoryNo + '\'' + "securitiesId='" + securitiesId + '\'' + "securitiesNo='" + securitiesNo + '\'' + "securitiesName='" + securitiesName + '\'' + "fundId='" + fundId + '\'' + "fundNo='" + fundNo + '\'' + "fundName='" + fundName + '\'' + "accountId='" + accountId + '\'' + "accountNo='" + accountNo + '\'' + "accountName='" + accountName + '\'' + "price='" + price + '\'' + "share='" + share + '\'' + "turnover='" + turnover + '\'' + "securitiesType='" + securitiesType + '\'' + "statisticalDate='" + statisticalDate + '\'' + "description='" + description + '\'' + "remark1='" + remark1 + '\'' + "remark2='" + remark2 + '\'' + "remark3='" + remark3 + '\'' + '}'; } } <file_sep>/fa-base/src/main/java/com/yidu/account/service/impl/AccountBizImpl.java package com.yidu.account.service.impl; import com.yidu.account.dao.AccountDao; import com.yidu.account.domain.Account; import com.yidu.account.service.AccountBiz; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 类的描述:... * * @author 蔡任骋 * @version 1.0 * @since 2020/09/03 */ @Service public class AccountBizImpl implements AccountBiz { @Autowired private AccountDao accountDao; @Override public Long countAccountByCondition(Map<String, Object> paramMap) { return accountDao.countAccountByCondition(paramMap); } @Override public List<Account> findAccountByConditionWithPaging(Map<String, Object> paramMap) { return accountDao.findAccountByConditionWithPaging(paramMap); } @Override public int addAccount(Account account) { return accountDao.addAccount(account); } @Override public int updateAccount(Account account) { return accountDao.updateAccount(account); } @Override public boolean updateAccountStatus(String accountIds, String usable) { String[] ids = accountIds.split(","); //定义修改状态的参数Map集合 Map<String,Object> paramMap = new HashMap<>(); //定义修改结果 boolean result = false; paramMap.put("usable",usable); for (String accountId : ids) { paramMap.put("accountId",accountId); result = accountDao.updateAccountStatus(paramMap); if (!result) throw new RuntimeException(""); } return result; } } <file_sep>/fa-web/src/main/java/com/yidu/stock/Listener/DataStockQuotationListener.java package com.yidu.stock.Listener; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.yidu.stock.domain.StockQuotation; import com.yidu.stock.service.StockQuotationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; // 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去 public class DataStockQuotationListener extends AnalysisEventListener<StockQuotation> { private StockQuotationService stockQuotationService; private static final Logger LOGGER = LoggerFactory.getLogger(DataStockQuotationListener.class); /** * 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收 */ private static final int BATCH_COUNT = 5; List<StockQuotation> list = new ArrayList<StockQuotation>(); /** * 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。 */ /*public DataListener() { // 这里是demo,所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数 demoDAO = new DemoDAO(); }*/ /** * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来 * * @param stockQuotationService */ public DataStockQuotationListener(StockQuotationService stockQuotationService) { this.stockQuotationService = stockQuotationService; } /** * 这个每一条数据解析都会来调用 * * @param stockQuotation * one row value. Is is same as {@link AnalysisContext#readRowHolder()} * @param context */ @Override public void invoke(StockQuotation stockQuotation, AnalysisContext context) { list.add(stockQuotation); // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM if (list.size() >= BATCH_COUNT) { saveStockTradeData(list); // 存储完成清理 list list.clear(); } } /** * 所有数据解析完成了 都会来调用 * * @param context */ @Override public void doAfterAllAnalysed(AnalysisContext context) { // 这里也要保存数据,确保最后遗留的数据也存储到数据库 saveStockTradeData(list); LOGGER.info("所有数据解析完成!"); } /** * 加上存储数据库 */ private void saveStockTradeData(List<StockQuotation> stockQuotations) { for(StockQuotation stockQuotation:stockQuotations){ System.out.println(stockQuotation); stockQuotationService.addStockQuotation(stockQuotation); } System.out.println("存储数据"); } }<file_sep>/fa-utils/src/main/java/com/yidu/utils/NoUtils.java package com.yidu.utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; /** * 类的描述:编号生成,工具类 * * @author wh * @since 2020/9/7 16:31 */ public class NoUtils { /** * 编号生成方法 * @param prefix 编号前缀 * @return 加工后的编号 如:JJKC-yyyy-MM-dd-HHmmss */ public static String getNo(String prefix){ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); StringBuilder stringBuilder = new StringBuilder(prefix); stringBuilder.append(sdf.format(new Date())); stringBuilder.append(UUID.randomUUID().toString().replace("-","").substring(0,6)); return stringBuilder.toString(); } public static void main(String[] args) { String str = getNo("JJKC"); } } <file_sep>/fa-base/src/main/java/com/yidu/fund/domain/Fund.java package com.yidu.fund.domain; import com.yidu.utils.DateUtils; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * 类的描述:基金实体类 * @author 李昊林 * @date 2020-09-03 */ public class Fund implements Serializable{ private static final long serialVersionUID = 2403125439650571085L; /** * 基金Id */ private String fundId; /** * 基金代码 */ private String fundNo; /** * 基金名 */ private String fundName; /** * 所属基金管理公司Id,参考基金管理人表 */ private String fundCompanyId; /** * 所属基金管理公司 */ private String comShortName; /** * 托管银行 */ private String trusteeBank; /** * 基金规模,初始融资额 */ private BigDecimal fundScale; /** * 初始净值,初始单位净值一般为1.00 */ private BigDecimal nav; /** * 托管费,0.001 代表千分之一 交给托管银行的费用 */ private BigDecimal trusteeFee; /** * 管理费,0.001 代表千分之一 交给基金管理公司的费用 */ private BigDecimal managementFee; /** * 计费有效天数 */ private int billingDays; /** * 基金经理ID,参考用户表主键 */ private String managerId; /** * 基金经理名 */ private String managerName; /** * 成立时间 */ @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private Date estDate; /** * 格式化成立时间 */ private String estDateStr; /** * 是否可用 */ private String usable; /** * 备注 */ private String description; public Fund() { } public Fund(String fundId,String fundNo,String fundName,String fundCompanyId,String comShortName,String trusteeBank,BigDecimal fundScale,BigDecimal nav,BigDecimal trusteeFee,BigDecimal managementFee,int billingDays,String managerId,String managerName,Date estDate,String usable,String description){ this.fundId = fundId; this.fundNo = fundNo; this.fundName = fundName; this.fundCompanyId = fundCompanyId; this.comShortName = comShortName; this.trusteeBank = trusteeBank; this.fundScale = fundScale; this.nav = nav; this.trusteeFee = trusteeFee; this.managementFee = managementFee; this.billingDays = billingDays; this.managerId = managerId; this.managerName = managerName; this.estDate = estDate; this.usable = usable; this.description = description; } public String getFundId() { return fundId; } public void setFundId(String fundId) { this.fundId = fundId; } public String getFundNo() { return fundNo; } public void setFundNo(String fundNo) { this.fundNo = fundNo; } public String getFundName() { return fundName; } public void setFundName(String fundName) { this.fundName = fundName; } public String getFundCompanyId() { return fundCompanyId; } public void setFundCompanyId(String fundCompanyId) { this.fundCompanyId = fundCompanyId; } public String getComShortName() { return comShortName; } public void setComShortName(String comShortName) { this.comShortName = comShortName; } public String getTrusteeBank() { return trusteeBank; } public void setTrusteeBank(String trusteeBank) { this.trusteeBank = trusteeBank; } public BigDecimal getFundScale() { return fundScale; } public void setFundScale(BigDecimal fundScale) { this.fundScale = fundScale; } public BigDecimal getNav() { return nav; } public void setNav(BigDecimal nav) { this.nav = nav; } public BigDecimal getTrusteeFee() { return trusteeFee; } public void setTrusteeFee(BigDecimal trusteeFee) { this.trusteeFee = trusteeFee; } public BigDecimal getManagementFee() { return managementFee; } public void setManagementFee(BigDecimal managementFee) { this.managementFee = managementFee; } public int getBillingDays() { return billingDays; } public void setBillingDays(int billingDays) { this.billingDays = billingDays; } public String getManagerId() { return managerId; } public void setManagerId(String managerId) { this.managerId = managerId; } public String getManagerName() { return managerName; } public void setManagerName(String managerName) { this.managerName = managerName; } public Date getEstDate() { return estDate; } public void setEstDate(Date estDate) { this.estDate = estDate; if(null != estDate){ this.estDateStr = DateUtils.dataToString(estDate,"yyyy-MM-dd"); } } public String getUsable() { return usable; } public void setUsable(String usable) { this.usable = usable; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getEstDateStr() { return estDateStr; } @Override public String toString() { return "Fund{" + "fundId='" + fundId + '\'' + ",fundNo='" + fundNo + '\'' + ",fundName='" + fundName + '\'' + ",fundCompanyId='" + fundCompanyId + '\'' + ",comShortName='" + comShortName + '\'' + ",trusteeBank='" + trusteeBank + '\'' + ",fundScale='" + fundScale + '\'' + ",nav='" + nav + '\'' + ",trusteeFee='" + trusteeFee + '\'' + ",managementFee='" + managementFee + '\'' + ",billingDays='" + billingDays + '\'' + ",managerId='" + managerId + '\'' + ",managerName='" + managerName + '\'' + ",estDate='" + estDate + '\'' + ",usable='" + usable + '\'' + ",description='" + description + '\'' + '}'; } } <file_sep>/fa-sys/src/main/java/com/yidu/user/service/UserBiz.java package com.yidu.user.service; import com.yidu.user.domain.User; import java.util.List; import java.util.Map; /** * 类的描述: * * @Author 李昊林 * @Date 2020/8/26 16:15 */ public interface UserBiz { /** * 查询所有用户 * @return 用户对象集合 */ List<User> findAllUser(); /** * 根据条件查询 * @param paramMap 查询条件map集合 * @return 用户对象集合 */ List<User> findUserByCondition(Map<String, Object> paramMap); /** * 添加用户 * @param user 用户对象 * @return 成功添加返回true,否则返回false */ boolean addUser(User user); /** * 删除用户 * @param userId 用户Id * @return 成功删除返回true,否则返回false */ boolean deleteUser(String userId); /** * 修改用户 * @param user 用户对象 * @return 成功修改返回true,否则返回false */ boolean updateUser(User user); /** * 修改用户可用状态 * @param userIds 用户Id * @param useable 修改状态 * @return 成功修改返回true,否则返回false */ boolean updateUserStatus(String userIds, String useable); /** * 根据条件统统用户数量 * @param paramMap 查询条件map集合 * @return 返回用户数量 */ Long countUserByCondition(Map<String, Object> paramMap); } <file_sep>/fa-base/src/main/java/com/yidu/deposit/paging/CashInventoryPaging.java package com.yidu.deposit.paging; /** * 类的描述:现金库存搜索及分页所需参数分页 * * @author wh * @since 2020/9/11 14:35 */ public class CashInventoryPaging { /** * 现金库存编号 */ private String cashInventoryNo; /** * 基金编号 */ private String fundNo; /** * 基金名称 */ private String fundName; /** * 账户编号 */ private String accountNo; private int page; private int limit; public String getCashInventoryNo() { return cashInventoryNo; } public void setCashInventoryNo(String cashInventoryNo) { this.cashInventoryNo = cashInventoryNo; } public String getFundNo() { return fundNo; } public void setFundNo(String fundNo) { this.fundNo = fundNo; } public String getFundName() { return fundName; } public void setFundName(String fundName) { this.fundName = fundName; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } } <file_sep>/fa-web/src/main/webapp/static/sys/js/user.js /* * layui引入样式的两种方式:模块化用和全模块用法 * layui的初始化模块可以理解为,引入这个模块的js文件 * 值得注意的是:layui的模块之间存在依赖关系,例如引入了table模块,它会layui/lay/moudules/table.js * 这个文件引入进来,并且它还会将这个模块所依赖的其他模块自动加入进来, * 实际引入的模块有:table、form、jquery、layer、laypage、laytpl、util,7个js文件 * 所以我仅仅初始化了table模块,却能获得form、jquery、layer的模块对象 */ $(function () { //layui初始化表格模组 layui.use(['table', 'laydate', 'util', 'upload'], function() { // 获得模块对象 var table = layui.table; var form = layui.form; var $ = layui.jquery; var layer = layui.layer; var laydate = layui.laydate; var util = layui.util; var upload = layui.upload; //----1.用户数据表格渲染------------------------------------------------------------------ var tableIns=table.render({ elem: '#userTable', url: '../findAllUser', //后期改回获取用户列表的后端程序的url method: 'get', where: {}, // 你额外要携带数据,以键值对的方式存入 toolbar: '#userToolbar', // 开启头部工具栏,并为其绑定左侧模板 cellMinWidth: 80, // 全局定义所有常规单元格的最小宽度(默认:60) cols: [ [{ type: 'numbers' }, // 序号 { type: 'checkbox' }, //复选框 { title:'头像', field:'userPic', unresize:true, // width:150, align:'center', templet: function(data) { if(data.userPic !='' && data.userPic != undefined){ return '<img src="'+ data.userPic+'" width="50px" height="50px"/>'; }else{ return '<img src="sys/img/7.png" width="50px" height="50px"/>'; } } }, { field: 'userId', title: '用户ID', unresize: true, hide: true, //一般情况下不显示用户ID align: "center" }, { field: 'userName', title: '用户名', unresize: true, align: "center" }, { field: 'telephone', title: '用户电话', unresize: true, width:150, align: "center" }, { field: 'password', title: '用户密码', unresize: true, hide: true, align: "center" }, { field: 'genderStr', title: '用户性别', unresize: true, align: "center", templet: function(d) { if(d.genderStr == '男') { return '<span style="color: #00F;">' + d.genderStr + '</span>'; } else { return '<span style="color: #fd04bc;">' + d.genderStr + '</span>'; } } }, { field: 'description', title: '用户描述', unresize: true, hide: true, Width:'auto', align: "center" }, { field: 'createTimeStr', title: '创建时间', unresize: true, align: "center", width: 200 }, { field: 'usable', title: '用户状态', unresize: true, align: "center", templet: '#checkboxTpl' } ] ], defaultToolbar: [{ title: '搜索' ,layEvent: 'LAYTABLE_SEARCH' ,icon: 'layui-icon-search' },'filter', 'exports', 'print' ], page: true, // 开启分页 limit: 10, // 每页显示的条数 limits: [10, 20, 50, 100], // 每页条数的选择项 loading: true, // 是否显示加载条(切换分页的时候显示) title: '用户表', // 定义 table 的大标题(在文件导出等地方会用到) id: 'userTable', // 设定容器唯一 id // 隔行变色 even: false }); //----1.用户数据表格渲染------------------------------------------------------------------ //----2.添加用户入职时间选择器-------------------------------------------------------------------- laydate.render({ elem: '#addUserHiredate' }); //修改用户入职时间选择器 laydate.render({ elem: '#updateUserHiredate' }); //----3.处理头部条件组合搜素------------------------------------------------------------------ form.on('submit(userSearchBtn)', function(data) { // 执行后台代码 table.reload('userTable', { url: '../findUserByCondition', where: { // 设定异步数据接口的额外参数,任意设 userName: $("#queryUserName").val(), gender: $("#queryUserSex").val(), usable: $("#queryusable").val(), }, page: { curr: 1 //从第一页开始 }, limit: 10 }); return false; // 阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); $("#reset").click(function () { tableIns.reload({ url: '../findUserByCondition', where:{ userName:null, gender: null, usable: null, } }) }) //----3.处理表行修改------------------------------------------------------------------ table.on("tool(userTableEvent)",function (obj) { var data = obj.data; console.log(data); if (obj.event == "update"){ initUpdateUserModal(data); } }); // 用户列表头部工具栏添加|修改|删除(逻辑删除)|恢复按钮的事件句柄绑定 table.on('toolbar(userTableEvent)', function(obj) { // 获取当前表格选中状态和选中的数据 var checkStatus = table.checkStatus(obj.config.id); // 区分点击的按钮 switch(obj.event) { case 'addUser': // 弹出新增模态框 initAddUserModal(); break; case 'LAYTABLE_SEARCH': laytablesearch(); layer.close(ltips); break; case 'updateUser': // 选择的数据数量 if(checkStatus.data.length > 1) { layer.msg("最多只能修改一行数据哦!!", { icon: 0 //图标,可输入范围0~6 }); } else if(checkStatus.data.length < 1) { layer.msg("请选择要修改的数据哦!!", { icon: 3 //图标,可输入范围0~6 }); } else if(checkStatus.data[0].usable == 'N') { layer.msg("该用户被禁用了哦!!", { icon: 4 //图标,可输入范围0~6 }); } else { // 弹出修改模态框,传递当前选中的一行数据过去 initUpdateUserModal(checkStatus.data[0]); } break; case 'frozenRecord': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要冻结的用户!!", { icon: 4 //图标,可输入范围0~6 }); } // 定义一个要删除的所有资源ID的字符串 var userIdStr = ""; // 遍历传递过来的要删除的数据 for(var i = 0; i < data.length; i++) { if(data[i].usable == 'N') { layer.msg("所选用户中有被冻结的用户!", { icon: 1 // 图标,可输入范围0~6 }); return; } // 拿出用户ID进行拼接 userIdStr += data[i].userId + ","; } // 截取掉因为拼接产生的多余的一个逗号 userIdStr = userIdStr.substring(0, userIdStr.length - 1); frozenORrecoverArchives(userIdStr, 'N'); break; case 'restoreRecord': // 当前选中行的数据 var data = checkStatus.data; //判断是否有选中 if(checkStatus.data.length < 1) { layer.msg("请选择你要还原的用户!!", { icon: 4 //图标,可输入范围0~6 }); } // 定义一个要删除的所有资源ID的字符串 var userIdStr = ""; // 遍历传递过来的要删除的数据 for(var i = 0; i < data.length; i++) { if(data[i].usable == 'Y') { layer.msg("所选用户中有可用的用户!", { icon: 1 // 图标,可输入范围0~6 }); return; } // 拿出资源ID进行拼接 userIdStr += data[i].userId + ","; } // 截取掉因为拼接产生的多余的一个逗号 userIdStr = userIdStr.substring(0, userIdStr.length - 1); frozenORrecoverArchives(userIdStr, 'Y'); break; }; }); //----4.处理新增用户表单提交-------------------------------------------------------------- form.on('submit(addUserBtn)', function(data) { // 执行后台代码 $.ajax({ type: 'POST', //适用RESTful风格的添加: 查询GET、添加POST、更新PUT、删除DELETE async: false, url: '../saveUser', //后期改为添加用户的后台程序的url data: data.field, success: function(data) { // 关闭页面上所有类型的所有弹框 layer.closeAll(); if(data == 1) { layer.msg("添加成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg("添加失败!", { icon: 1 // 图标,可输入范围0~6 }); } } }); // 刷新数据表格 table.reload('userTable', { url: '../findUserByCondition' //后期改为查询用户的后台程序的url }); return false; // 阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); //----5.处理修改用户表单提交-------------------------------------------------------------- form.on('submit(updateUserBtn)', function(data) { //执行后台代码 $.ajax({ type: 'POST', //适用RESTful风格的添加: 查询GET、添加POST、更新PUT、删除DELETE async: false, url: '../updateUser', //后期改为修改用户的后台程序url data: data.field,//data.field success: function(data) { console.log(data.result) //关闭页面上所有类型的所有弹框 layer.closeAll(); if(data.result == 1) { layer.msg("修改成功!", { icon: 1 //图标,可输入范围0~6 }); } else { layer.msg("修改失败!", { icon: 1 //图标,可输入范围0~6 }); } } }); //刷新数据表格 table.reload('userTable', { url: '../findUserByCondition' // }); return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); var ltips=layer.tips("为你定制的搜索^_^",".layui-table-tool-self",{tips:[2,'#1211115e'],time:5000,shadeClose:true}); // 监听锁定操作 form.on('switch(usable)', function(obj) { frozenORrecoverArchives(obj.value, this.checked == true ? 'Y' : 'N'); }); // 定义冻结或还原的方法 var frozenORrecoverArchives = function(userIdStr, status) { // 用户ID var userId = userIdStr; // 定义提示信息, 状态 var msg, usable; if(status == 'Y') { msg = "还原", usable = 'Y'; } else { msg = "禁用", usable = 'N'; } // 发送异步请求冻结或还原资源 $.ajax({ async: false, // 默认为true,false表示同步,如果当前请求没有返回则不执行后续代码 type: "DELETE", url:'../updateUserStatus/' + userId + "/" + usable,// /updateUser '/updateUserStatus/' + userIds + "/" + usable data: { // userId:userId, // usable:usable, // _method: 'DELETE' }, datatype: 'json', success: function(data) { if(data.result == "1") { layer.msg(msg + "成功!", { icon: 1 // 图标,可输入范围0~6 }); } else { layer.msg(msg + "失败!", { icon: 2 }); } // 刷新数据表格 table.reload('userTable', { url: '../findUserByCondition' }); } }); }; // var hiddeDisable = function(){ // // } // 初始化新增模态框 var initAddUserModal = function() { // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '添加用户', // 标题 skin: "layui-layer-molv", anim: 2, // 弹出动画 area: ["500px"], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#addUserModal"), // 文本、html都行 resize: false, // 是否允许拉伸 end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) // 清空表单 $("#addUserForm")[0].reset(); $("#demo1").attr("src", ""); $("#demoText").text(""); } }); } // 初始化修改模态框 var initUpdateUserModal = function(data) { // 弹出一个页面层 layer.open({ type: 1, // 基本层类型0~4,1为页面层 title: '修改用户', // 标题 skin: "layui-layer-molv", anim: 2, // 弹出动画 area: ["500px"], //自适应宽高 只写一个参数就是表示宽度,高度会自适应 // 宽高 只写一个参数就是表示宽度,高度会自适应 content: $("#updateUserModal"), // 文本、html都行 resize: false, // 是否允许拉伸 end: function() { // 弹出层销毁时的回调函数(不论何种方式,只要关闭了就执行) // 清空表单 $("#addUserForm")[0].reset(); $("#demo1").attr("src", ""); $("#demoText").text(""); } }); // 表单赋值 form.val('updateUserForm', { "userId": data.userId, "userName": data.userName, //layui.util.toDateString(data.commonStart, 'HH:mm:ss'), "password": <PASSWORD>, "telephone": data.telephone, // "orgId": data.orgId, // "orgName": data.orgName, "gender": data.gender, // "userBirthdate": data.userBirthdate, // "userHiredate": data.userHiredate, "usable": data.usable, "description": data.description, // "headImage": data.file, }); }; // $.ajax({ // url: '/findUserByConditionuuuu',//system/org', // dataType: 'json', // type: 'post', // success: function(data) { // $.each(data, function(index) { // var orgName = data[index].orgName; // var orgId = data[index].orgId; // /* var sdSdd = data[index].sdSdd; */ // // 头部的搜索 // $("#queryOrgName").append( // "<option value='" + orgName + "'>" + orgName + // "</option>"); // // 添加 // $("#addOrgName").append( // "<option value='" + orgId + "'>" + orgName + // "</option>"); // // 修改 // $("#updateOrgName").append( // "<option value='" + orgId + "'>" + orgName + // "</option>"); // // form.render()渲染将option添加进去 // form.render(); // }); // } // }); // 自定义表单校验 form.verify({ pass: [ /^[\S]{6,12}$/, '密码必须6到12位,且不能出现空格'], mobile: function(value) { var msg; $.ajax({ type: "POST", url: '../verifyTelephone',//system/toVerifyUserPhone async: false, // 使用同步的方法 data: { 'telephone': value }, dataType: 'json', success: function(result) { if(result.flag) { msg = result.msg; } } }); return msg; } }); }); })<file_sep>/fa-base/src/main/java/com/yidu/fund/service/FundTradeService.java package com.yidu.fund.service; import com.yidu.format.LayuiFormat; import com.yidu.fund.domain.FundTrade; import com.yidu.fund.paging.FundTradePaging; import java.util.List; import java.util.Map; /** * 类的描述: * * @Author 李昊林 * @Date 2020/9/7 15:37 */ public interface FundTradeService { /** * 根据条件查找基金交易数据 * @param fundTradePaging 查询条件 * @return 基金交易数据集合 */ List<FundTrade> findFundTradeByCondition (FundTradePaging fundTradePaging); /** * 根据条件查找统计基金交易数据数量 * @param fundTradePaging 查询条件 * @return 数量 */ Long findCountFundTradeByCondition(FundTradePaging fundTradePaging); /** * 添加基金交易数据 * @param fundTrade 基金交易数据对象 * @return 成功添加返回true,否则返回false */ boolean addFundTrade(List<FundTrade> fundTrade); /** * 基金结算 * @param fundTradeIds 基金交易Id字符串数 * @param tradeStatus 交易状态 * @return 结算成功返回true */ boolean fundSettlement(String fundTradeIds,String tradeStatus); }
16273e58b22c605fe6638e0abb71eced0caf098b
[ "JavaScript", "Java" ]
56
Java
victor-whong/fa
8083103940d9ea7bab23d7306c61af25115bf28b
4e7a850243e34a59e45db714cf69efd7c6b904b9
refs/heads/master
<file_sep>import argparse import random import sys import time import uuid import rl_client class my_error_callback(rl_client.error_callback): def on_error(self, error_code, error_message): print("Background error:") print(error_message) def load_config_from_json(file_name): with open(file_name, 'r') as config_file: return rl_client.create_config_from_json(config_file.read()) class person: def __init__(self, id, major, hobby, fav_char, p): self._id = id self._major = major self._hobby = hobby self._favorite_character = fav_char self._topic_click_probability = p def get_features(self): return '"User":{{"id":"{}","major":"{}","hobby":"{}","favorite_character":"{}"}}'.format(self._id, self._major, self._hobby, self._favorite_character) def get_outcome(self, chosen_action): draw_uniform = random.uniform(0, 10000) norm_draw_val = draw_uniform / 10000.0 click_prob = self._topic_click_probability[chosen_action] if (norm_draw_val <= click_prob): return 1.0 else: return 0.0 class rl_sim: def __init__(self, args): self._options = args self.config = load_config_from_json(self._options.json_config) self._rl = rl_client.live_model(self.config, my_error_callback()) self._rl.init() tp1 = {'HerbGarden': 0.6, "MachineLearning": 0.4 } tp2 = {'HerbGarden': 0.2, "MachineLearning": 0.8 } self._actions = ['HerbGarden', 'MachineLearning'] self._people = [ person('rnc', 'engineering', 'hiking', 'spock', tp1), person('mk', 'psychology', 'kids', '7of9', tp2)] def loop(self): round = 0 while (True): try: p = self.pick_a_random_person() context_features = p.get_features() action_features = '"_multi": [ {"topic":"HerbGarden"}, {"topic":"MachineLearning"} ]' context_json = self.create_context_json(context_features, action_features) req_id = str(uuid.uuid4()) model_id, chosen_action_id, action_probabilities = self._rl.choose_rank(req_id, context_json) outcome = p.get_outcome(self._actions[chosen_action_id]) self._rl.report_outcome(req_id, outcome) print('Round: {}, Person: {}, Action: {}, Outcome: {}' .format(round, p._id, chosen_action_id, outcome)) round = round + 1 time.sleep(0.1) except Exception as e: print(e) time.sleep(2) continue def pick_a_random_person(self): return self._people[random.randint(0, len(self._people) - 1)] def create_context_json(self, context, action): return '{{ {}, {} }}'.format(context, action) def process_cmd_line(args): parser = argparse.ArgumentParser() parser.add_argument('--json_config', help='client json config', required=True) return parser.parse_args(args) def main(args): vm = process_cmd_line(args) sim = rl_sim(vm) sim.loop() if __name__ == "__main__": main(sys.argv[1:])
ec5d8b89512a4357970e2f139a506dace6419df6
[ "Python" ]
1
Python
anupamandroid/vowpal_wabbit
5becde24fd1464e8fc7bbcc02312fbdb8f12891d
c99b65e9853d500fc54021c1d40d3a245c4daa2c
refs/heads/master
<repo_name>ning5280/node_spider<file_sep>/qingchun.js var http = require('http'); var fs = require('fs'); var cheerio = require('cheerio'); var request = require('request'); var i = 0; var baseUrl = "http://www.mm131.com/qingchun/"; var url = baseUrl+ "2435_43.html"; var iconv = require('iconv-lite'); var maxnum = 8888; //抓取总条数 //初始url function fetchPage(x) { //封装了一层函数 startRequest(x); } function startRequest(x) { //采用http模块向服务器发起一次get请求 http.get(x, function (res) { //用来存储请求网页的整个html内容 var html = []; var len = 0; // res.setEncoding('utf-8'); //防止中文乱码 //监听data事件,每次取一块数据 res.on('data', function(chrunk) { html.push(chrunk); len += chrunk.length; }); //监听end事件,如果整个网页内容的html都获取完毕,就执行回调函数 res.on('end', function () { var data = Buffer.concat(html, len); data = iconv.decode(data, 'gb2312'); var $ = cheerio.load(data); //采用cheerio模块解析html // 获取标题 var title = $('.content h5').text().trim(); //文章发布时间 var time = $('.content .content-msg').text().trim(); // 获取下一个url var nextUrlObj = $('.content-page .page-ch').last(); // 如果有href 说明有下一页 if(nextUrlObj.attr('href')){ var nextUrl = baseUrl+nextUrlObj.attr('href'); }else{ // 如果没有下一页 获取下一组 var nextUrl = $('.updown .updown_l').attr('href'); } var list = { title: title, Time: time, url: x, nextUrl:nextUrl, //i是用来判断获取了多少篇文章 i: i = i + 1, }; console.log(list); //打印信息 console.log(nextUrl); // savedContent($,news_title); //存储每篇文章的内容及文章标题 savedImg($,list); //存储每篇文章的图片及图片标题 //通过控制I,可以控制爬取多少篇文章. if (i <= maxnum) { fetchPage(nextUrl); } }); }).on('error', function (err) { console.log(err); }); } //该函数的作用:在本地存储所爬取的内容资源 function savedContent($, news_title) { $('.article-content p').each(function (index, item) { var x = $(this).text(); var y = x.substring(0, 2).trim(); if (y == '') { x = x + '\n'; //将文本内容一段一段添加到/data文件夹下,并用标题来命名文件 fs.appendFile('./data/' + news_title + '.txt', x, 'utf-8', function (err) { if (err) { console.log(err); } }); } }) } //该函数的作用:在本地存储所爬取到的图片资源 function savedImg($,news_title) { $('.content-pic img').each(function (index, item) { var img_title = $(this).attr('alt').trim(); //获取图片的标题 if(img_title.length>55||img_title==""){ img_title="Null";} var img_filename = img_title + '.jpg'; var img_src = $(this).attr('src'); //获取图片的url console.log(img_src); //采用request模块,向服务器发起一次请求,获取图片资源 request.head(img_src,function(err,res,body){ if(err){ console.log(err); } }); request(img_src).pipe(fs.createWriteStream('./image/qingchun/'+img_title + '---' + img_filename)); //通过流的方式,把图片写到本地/image目录下,并用新闻的标题和图片的标题作为图片的名称。 }) } fetchPage(url);
5005e23acff7fd9cea087ad262b25c6ebdf7ec26
[ "JavaScript" ]
1
JavaScript
ning5280/node_spider
0934c93503dddee5d8a50f4eec8323ec8287431b
b67d4390b424dcb51ab13d78893cd72de0600b87
refs/heads/master
<repo_name>ZhangFengze/CrazyTang<file_sep>/client_ue4/CrazyTang/Config/DefaultGame.ini [/Script/EngineSettings.GeneralProjectSettings] ProjectID=A6A872A34055230CDE5B038326D617E9 <file_sep>/common/Voxel.cpp #include "Voxel.h" #include "FastNoiseLite.h" namespace ct { namespace voxel { bool _InRange(int value, int begin, int end) { return value >= begin && value < end; } void GenerateVoxels(Container& container) { FastNoiseLite noise; noise.SetNoiseType(FastNoiseLite::NoiseType_OpenSimplex2); noise.SetFrequency(0.02f); container.ForEach([&noise](int x, int y, int z, voxel::Voxel* voxel) { auto v = noise.GetNoise((float)x, (float)z); v = (v + 1) * 0.5f * voxel::Container::y; voxel->type = y < v ? voxel::Type::Block : voxel::Type::Empty; }); } void Process(Container& container, float step) { } std::tuple<int, int, int> DecodeIndex(const Position& pos) { int x = pos.data.x() / sideLength; int y = pos.data.y() / sideLength; int z = pos.data.z() / sideLength; return { x,y,z }; } } }<file_sep>/server/Server.h #pragma once #include "ConnectionInfo.h" #include "../common/Entity.h" #include "../common/Net.h" #include "../common/Voxel.h" #include "../common/fps.h" #include <asio.hpp> #include <cstdint> #include <memory> #include <unordered_map> namespace ct { class Server { public: void Run(); private: asio::awaitable<void> Listen(); asio::awaitable<void> OnConnection(asio::ip::tcp::socket); void OnLoginSuccess(std::shared_ptr<NetAgent> agent, uint64_t connectionID); asio::awaitable<void> LogFps(); private: asio::io_context io_; uint64_t connectionID_ = 0; std::unordered_map<uint64_t, Connection> connections_; EntityContainer entities_; voxel::Container voxels_; FPS fps_; }; } <file_sep>/client_core/CMakeLists.txt cmake_minimum_required(VERSION 3.14) project(client_core) aux_source_directory(. source) aux_source_directory(../common source) add_library(${PROJECT_NAME} STATIC ${source}) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD_REQUIRED ON) target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/asio/asio/include") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/eigen") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/ZSerializer")<file_sep>/client_ue4/CrazyTang/Source/CrazyTang/CrazyTangGameModeBase.h // Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include <memory> #include <map> #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" #include "VoxelWorld.h" #include "CrazyTangPawnBase.h" #if PLATFORM_WINDOWS #include "Windows/PreWindowsApi.h" #endif #include "asio.hpp" #include "common/Pipe.h" #include "common/Entity.h" #include "common/UUID.h" #include "common/Voxel.h" #if PLATFORM_WINDOWS #include "Windows/PostWindowsApi.h" #endif #include "CrazyTangGameModeBase.generated.h" /** * */ UCLASS() class CRAZYTANG_API ACrazyTangGameModeBase : public AGameModeBase { GENERATED_BODY() public: ACrazyTangGameModeBase(); void InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage) override; void Tick(float DeltaSeconds) override; public: void OnConnected(asio::io_context& io, std::shared_ptr<ct::Pipe<>> pipe); void OnLoginSuccess(asio::io_context& io, uint64_t id, std::shared_ptr<ct::Pipe<>> pipe); ct::EntityHandle GetEntity(uint64_t); void TickVoxels(float dt); AVoxelWorld* GetVoxelWorld(); private: asio::io_context m_HighPriorityIO; asio::io_context m_LowPriorityIO; UPROPERTY(EditDefaultsOnly) TSubclassOf<ACrazyTangPawnBase> MyPawn; ct::EntityContainer m_Entities; ct::voxel::Container m_Voxels; }; <file_sep>/README.md # CrazyTang Build =============== ```shell git clone https://github.com/ZhangFengze/CrazyTang.git cd CrazyTang git submodule update --init --recursive python tools/server.py # for server python tools/client_gui.py # for client ``` Build Requirements =============== * a **C++20** compatible compiler * cmake 3.19+ * python 3 Note that we intentionally take advantages of the latest features of C++ standard and other tools. It is recommended to keep toolchains up-to-date. ### **Windows** Just install the latest `Visual Studio` `CMake` and `Python`. ### **Linux** Usually we have to build from source. `https://hub.docker.com/r/rikorose/gcc-cmake` is here to help you ```shell cd CrazyTang docker run -it --rm -v `pwd`:/usr/src/myapp -w /usr/src/myapp rikorose/gcc-cmake # now you have gcc cmake and python ``` <file_sep>/client_gui/client_gui.h #pragma once #include <memory> #include <asio.hpp> #include <PxConfig.h> #include <PxPhysicsAPI.h> #include <Magnum/GL/Buffer.h> #include <Magnum/GL/Mesh.h> #include <Magnum/Math/Matrix4.h> #include <Magnum/Shaders/PhongGL.h> #include <Magnum/Platform/GlfwApplication.h> #include "../common/Net.h" #include "../common/Entity.h" #include "../common/Voxel.h" #include "../common/fps.h" #include "VoxelView.h" using namespace Magnum; namespace ct { class App { public: App(const Vector2i& windowSize, GLFWwindow* window); void Tick(); void OnMouseMove(float dx, float dy); private: void DrawVoxels(); void DrawPlayers(); void TickImGui(); void TickInput(); void TickVoxelsView(); private: asio::awaitable<void> Login(asio::io_context& io, const asio::ip::tcp::endpoint&); asio::awaitable<void> Sync(); private: struct Server { std::string name; asio::ip::tcp::endpoint endpoint; }; std::vector<Server> servers_; asio::awaitable<void> RefreshServerList(asio::io_context& io); private: GL::Mesh voxelMesh_; Shaders::PhongGL voxelShader_; GL::Buffer voxelBuffer_; GL::Mesh playerMesh_; Shaders::PhongGL playerShader_; GL::Buffer playerBuffer_; Matrix4 projection_; std::unordered_map<voxel::Type, Color3> palette_; Vector2 windowSize_; GLFWwindow* window_; Vector3 cameraPos_{ 0,0,30 }; float cameraYaw_ = 0.f; float cameraPitch_ = 0.f; private: asio::io_context io_; std::shared_ptr<ct::NetAgent> curAgent_; uint64_t curID_ = 0; EntityContainer curEntities_; voxel::Container curVoxels_; voxel_view::Container curVoxelsView_; FPS fps_; int drawVoxels_ = 0; }; }<file_sep>/common/Net.h #pragma once #include "Packet.h" #include <ZSerializer.hpp> #include <asio.hpp> #include <array> #include <list> #include <vector> #include <functional> #include <system_error> #include <utility> #include <memory> #include <string> #include <cassert> namespace ct { inline asio::awaitable<void> AsyncWritePacket(asio::ip::tcp::socket& socket, Packet&& packet) { uint32_t lengthBuffer[1]{ packet.Size() }; std::array<asio::const_buffer, 2> buffers { asio::buffer(lengthBuffer), asio::buffer((const void*)packet.Data(),packet.Size()) }; if (4 + packet.Size() != co_await asio::async_write(socket, buffers, asio::use_awaitable)) throw asio::error::make_error_code(asio::error::broken_pipe); } inline asio::awaitable<Packet> AsyncReadPacket(asio::ip::tcp::socket& socket) { uint32_t lengthBuffer[1]; if (4 != co_await asio::async_read(socket, asio::buffer(lengthBuffer), asio::use_awaitable)) throw asio::error::make_error_code(asio::error::eof); uint32_t length = lengthBuffer[0]; std::array<char, 1024 * 1024> buffer; if (length > buffer.size()) throw asio::error::make_error_code(asio::error::no_buffer_space); if (length != co_await asio::async_read(socket, asio::buffer(buffer, length), asio::use_awaitable)) throw asio::error::make_error_code(asio::error::eof); co_return Packet{ buffer.data(), length }; } struct CallOnDestroy { CallOnDestroy(std::function<void()> f) :func(f) {} ~CallOnDestroy() { func(); } std::function<void()> func; }; class NetAgent { public: NetAgent(asio::ip::tcp::socket socket) :socket_(std::move(socket)) {} void Listen(const std::string& tag, std::function<void(std::string&&)> handler) { assert(listeners_.find(tag) == listeners_.end()); listeners_[tag] = handler; } void OnError(std::function<void()> handler) { errorHandler_ = handler; } void Send(const std::string& tag, const std::string& content) { zs::StringWriter out; zs::Write(out, tag); zs::Write(out, content); out_.emplace_back(Packet{ out.String() }); } void NotifyError() { if (errorHandler_) errorHandler_(); } asio::awaitable<void> ReadRoutine() { auto _ = CallOnDestroy([this] {NotifyError();}); while (socket_.is_open()) { auto packet = co_await AsyncReadPacket(socket_); zs::StringReader ar(std::string{ packet.Data(),packet.Size() }); auto tag = zs::Read<std::string>(ar); if (std::holds_alternative<zs::Error>(tag)) co_return; auto iter = listeners_.find(std::get<0>(tag)); if (iter == listeners_.end()) continue; auto content = zs::Read<std::string>(ar); if (std::holds_alternative<zs::Error>(content)) co_return; iter->second(std::move(std::get<0>(content))); } } asio::awaitable<void> WriteRoutine() { auto _ = CallOnDestroy([this] {NotifyError();}); while (socket_.is_open()) { // TODO optimize if (out_.empty()) { asio::steady_timer t{ co_await asio::this_coro::executor }; t.expires_after(std::chrono::milliseconds{ 0 }); co_await t.async_wait(asio::use_awaitable); continue; } auto packet = out_.front(); out_.pop_front(); co_await AsyncWritePacket(socket_, std::move(packet)); } } private: asio::ip::tcp::socket socket_; std::unordered_map<std::string, std::function<void(std::string&&)>> listeners_; std::function<void()> errorHandler_; std::list<Packet> out_; }; }<file_sep>/server/Server.cpp #include "Server.h" #include "Login.h" #include "ConnectionInfo.h" #include "VoxelWatcher.h" #include "../common/Net.h" #include "../common/MoveSystem.h" #include "../common/Position.h" #include "../common/Velocity.h" #include "../common/Name.h" #include "../common/Voxel.h" #include "../common/Math.h" #include "../common/UUID.h" #include <Eigen/Eigen> #include <ZSerializer.hpp> #ifdef _WIN32 #include <format> #endif #include <thread> #include <chrono> #include <iostream> using namespace std::placeholders; using namespace ct; namespace zs { template<> struct Trait<ct::EntityHandle> { template<typename Out> static void Write(Out& out, const ct::EntityHandle& e) { assert(e.Has<UUID>()); zs::Write(out, *e.Get<UUID>()); zs::StringWriter components; if (auto connection = e.Get<ConnectionInfo>()) { zs::Write(components, "connection"); zs::Write(components, connection->connectionID); } if (auto position = e.Get<Position>()) { zs::Write(components, "position"); zs::Write(components, *position); } if (auto velocity = e.Get<Velocity>()) { zs::Write(components, "velocity"); zs::Write(components, *velocity); } if (auto name = e.Get<xy::Name>()) { zs::Write(components, "name"); zs::Write(components, *name); } zs::Write(out, components.String()); } }; } namespace ct { asio::awaitable<void> Server::Listen() { auto endpoint = asio::ip::tcp::endpoint{ asio::ip::tcp::v4(),33773 }; asio::ip::tcp::acceptor acceptor{ io_, endpoint }; for (;;) { auto socket = co_await acceptor.async_accept(asio::use_awaitable); co_spawn(io_, OnConnection(std::move(socket)), asio::detached); } } asio::awaitable<void> Server::OnConnection(asio::ip::tcp::socket socket) { auto id = ++connectionID_; if (!co_await ServerLogin(socket, id, std::chrono::seconds{ 3 })) co_return; auto agent = std::make_shared<NetAgent>(std::move(socket)); OnLoginSuccess(agent, id); co_spawn(socket.get_executor(), [agent]() -> asio::awaitable<void> { co_await agent->ReadRoutine(); }, asio::detached); co_spawn(socket.get_executor(), [agent]() -> asio::awaitable<void> { co_await agent->WriteRoutine(); }, asio::detached); } asio::awaitable<void> Server::LogFps() { asio::system_timer timer(co_await asio::this_coro::executor); while (true) { timer.expires_after(std::chrono::seconds{ 1 }); co_await timer.async_wait(asio::use_awaitable); #ifdef _WIN32 std::cout << std::format("{} fps: {}\n", std::chrono::system_clock::now(), fps_.get()); #endif } } void Server::Run() { asio::co_spawn(io_, Listen(), asio::detached); asio::co_spawn(io_, LogFps(), asio::detached); voxel::GenerateVoxels(voxels_); auto interval = std::chrono::milliseconds{ 33 }; auto shouldTick = std::chrono::steady_clock::now(); while (true) { io_.poll(); move_system::Process(entities_, interval.count() / 1000.f); // voxel::Process(voxels_, interval.count() / 1000.f); zs::StringWriter worldOut; entities_.ForEach([&](EntityHandle e) {zs::Write(worldOut, e);}); auto world = worldOut.String(); for (auto& [_, connection] : connections_) { connection.agent->Send("entities", world); } // voxel_watcher::Process(entities_, voxels_, interval.count() / 1000.f); fps_.fire(); shouldTick += interval; io_.run_until(shouldTick); } } void Server::OnLoginSuccess(std::shared_ptr<NetAgent> agent, uint64_t connectionID) { Connection connection; connection.connectionID = connectionID; connection.agent = agent; connections_[connectionID] = connection; auto e = entities_.Create(); auto uuid = e.Add<UUID>(); uuid->id = GenerateUUID(); auto position = e.Add<Position>(); position->data.x() = 0; position->data.y() = 0; position->data.z() = 0; auto velocity = e.Add<Velocity>(); velocity->data.x() = 0; velocity->data.y() = 0; velocity->data.z() = 0; auto name = e.Add<xy::Name>(); name->data = "zjx"; auto info = e.Add<ConnectionInfo>(); info->connectionID = connectionID; info->agent = agent; agent->Listen("set position", [this, e](std::string&& data) mutable { zs::StringReader in{ std::move(data) }; auto pos = zs::Read<Eigen::Vector3f>(in); if (std::holds_alternative<zs::Error>(pos)) return; e.Get<Position>()->data = std::get<0>(pos); }); agent->Listen("set velocity", [this, e](std::string&& data) mutable { zs::StringReader in{ std::move(data) }; auto vel = zs::Read<Eigen::Vector3f>(in); if (std::holds_alternative<zs::Error>(vel)) return; e.Get<Velocity>()->data = std::get<0>(vel); }); agent->Listen("set name", [this, e](std::string&& data) mutable { zs::StringReader in{ std::move(data) }; auto name = zs::Read<std::string>(in); if (std::holds_alternative<zs::Error>(name)) return; e.Get<xy::Name>()->data = std::get<0>(name); }); agent->OnError([e, connectionID, this]() mutable { if (e.Valid()) e.Destroy(); connections_.erase(connectionID); }); voxel_watcher::Sync(e, voxels_); } } // namespace ct<file_sep>/common/Math.cpp #include "Math.h" #include <random> namespace { std::random_device rd; std::mt19937 gen(rd()); } namespace ct { float Rand(float min, float max) { std::uniform_real_distribution<float> dis(min, max); return dis(gen); } }<file_sep>/client_ue4/CrazyTang/Source/CrazyTang/CrazyTangPawnBase.cpp // Fill out your copyright notice in the Description page of Project Settings. #include "CrazyTangPawnBase.h" THIRD_PARTY_INCLUDES_START #include "ZSerializer.hpp" #include "common/Math.h" #include "common/Position.h" THIRD_PARTY_INCLUDES_END #include "CrazyTangGameModeBase.h" #include "Components/InputComponent.h" #include "Kismet/GameplayStatics.h" #include "Engine/World.h" // Sets default values ACrazyTangPawnBase::ACrazyTangPawnBase() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; // Set this pawn to be controlled by the lowest-numbered player //AutoPossessPlayer = EAutoReceiveInput::Player0; } // Called when the game starts or when spawned void ACrazyTangPawnBase::BeginPlay() { Super::BeginPlay(); } // Called every frame void ACrazyTangPawnBase::Tick(float DeltaTime) { Super::Tick(DeltaTime); auto gm = GetWorld()->GetAuthGameMode<ACrazyTangGameModeBase>(); auto entity = gm->GetEntity(m_UUID); assert(entity.Valid()); if (auto pos = entity.Get<ct::Position>()) SetActorLocation(FVector{ pos->data.x(), pos->data.y(), pos->data.z() }); SendInput(); } // Called to bind functionality to input void ACrazyTangPawnBase::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAxis("MoveX", this, &ACrazyTangPawnBase::MoveX); PlayerInputComponent->BindAxis("MoveY", this, &ACrazyTangPawnBase::MoveY); } void ACrazyTangPawnBase::SetupNetAgent(ct::NetAgent<>* agent) { m_NetAgent = agent; auto controller = UGameplayStatics::GetPlayerController(GetWorld(), 0); controller->Possess(this); } void ACrazyTangPawnBase::SetUUID(uint64_t id) { m_UUID = id; } void ACrazyTangPawnBase::MoveX(float axis) { m_Input.x() = axis * 100; } void ACrazyTangPawnBase::MoveY(float axis) { m_Input.y() = axis * 100; } void ACrazyTangPawnBase::SendInput() { if (m_NetAgent) { zs::StringWriter out; zs::Write(out, m_Input); m_NetAgent->Send("set velocity", out.String()); } } <file_sep>/common/Packet.h #pragma once #include <vector> #include <string> #include <string_view> namespace ct { struct Packet { Packet() = default; Packet(const Packet&) = default; Packet(Packet&&) = default; Packet(size_t); Packet(const char*, size_t); Packet(const std::string_view&); Packet(const std::string&); Packet& operator=(const Packet&) = default; Packet& operator=(Packet&&) = default; const char* Data() const; size_t Size() const; std::vector<char> buffer_; }; bool operator==(const Packet& left, const Packet& right); bool operator!=(const Packet& left, const Packet& right); } <file_sep>/tools/client_core.py import argparse from ct_common import execute, get_root_path, rmdir, cmake, build parser = argparse.ArgumentParser() parser.add_argument("--clean", help="clean before build", action="store_true") parser.add_argument("--config", help="configuration", default="debug") parser.add_argument("--ninja", help="build using ninja", action="store_true") args = parser.parse_args() source_dir = get_root_path().joinpath("client_core") build_dir = get_root_path().joinpath("build/client_core") if args.clean: rmdir(build_dir) exit() cmake(source_dir, build_dir, args.ninja) build(build_dir, args.config) <file_sep>/common/Position.h #pragma once #include <Eigen/Eigen> #include <ZSerializer.hpp> namespace ct { struct Position { Eigen::Vector3f data=Eigen::Vector3f::Zero(); }; } namespace zs { template<> struct Trait<ct::Position> : public WriteBitwise<ct::Position>, public ReadBitwise<ct::Position> {}; }<file_sep>/common/Math.h #pragma once #include <Eigen/Eigen> #include <ZSerializer.hpp> namespace ct { float Rand(float min, float max); template<typename T> std::tuple<T, T, T> ToTuple(const Eigen::Matrix<T, 3, 1>& vec3) { return { vec3.x(), vec3.y(), vec3.z() }; } } namespace zs { template<> struct Trait<Eigen::Vector3f> : public WriteBitwise<Eigen::Vector3f>, public ReadBitwise<Eigen::Vector3f> {}; }<file_sep>/common/Velocity.h #pragma once #include <Eigen/Eigen> namespace ct { struct Velocity { Eigen::Vector3f data=Eigen::Vector3f::Zero(); }; } namespace zs { template<> struct Trait<ct::Velocity> : public WriteBitwise<ct::Velocity>, public ReadBitwise<ct::Velocity> {}; }<file_sep>/client_cli/CMakeLists.txt cmake_minimum_required(VERSION 3.19) project(client_cli) aux_source_directory(. source) aux_source_directory(../common source) add_executable(${PROJECT_NAME} ${source}) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STACK_SIZE 100000000) target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/asio/asio/include") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/eigen") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/ZSerializer") install(TARGETS ${PROJECT_NAME})<file_sep>/common/Packet.cpp #include "Packet.h" #include <cstring> namespace ct { Packet::Packet(size_t size) :buffer_(size) { } Packet::Packet(const char* data, size_t size) :buffer_(data, data + size) { } Packet::Packet(const std::string_view& view) : buffer_(view.data(), view.data() + view.size()) { } Packet::Packet(const std::string& str) : buffer_(str.data(), str.data() + str.size()) { } const char* Packet::Data() const { return buffer_.data(); } size_t Packet::Size() const { return buffer_.size(); } bool operator==(const Packet& left, const Packet& right) { if (left.Size() != right.Size()) return false; return 0 == memcmp(left.Data(), right.Data(), left.Size()); } bool operator!=(const Packet& left, const Packet& right) { return !(left == right); } } <file_sep>/common/Entity.cpp #include "Entity.h" namespace ct { void EntityHandle::Destroy() { return container_->Remove(id_); } bool EntityHandle::Valid() const { if (!container_) return false; return container_->Has(id_); } bool operator<(EntityHandle lhs, EntityHandle rhs) { if (lhs.container_ < rhs.container_) return true; if (lhs.container_ > rhs.container_) return false; return lhs.id_ < rhs.id_; } bool operator==(EntityHandle lhs, EntityHandle rhs) { return lhs.container_ == rhs.container_ && lhs.id_ == rhs.id_; } bool operator!=(EntityHandle lhs, EntityHandle rhs) { return !(lhs == rhs); } EntityHandle EntityContainer::Create() { auto e = EntityHandle(); e.id_ = ++assignedID_; e.container_ = this; entities_[e.id_] = {}; return e; } void EntityContainer::ForEach(std::function<void(EntityHandle)> func) { for (const auto& [id, components] : entities_) { auto e = EntityHandle{}; e.id_ = id; e.container_ = this; func(e); } } void EntityContainer::Remove(uint64_t id) { assert(Has(id)); entities_.erase(id); } bool EntityContainer::Has(uint64_t id) const { return entities_.find(id) != entities_.end(); } } <file_sep>/test/MoveSystem_Test.cpp #define CATCH_CONFIG_MAIN #include <catch.hpp> #include "../common/Entity.h" #include "../common/MoveSystem.h" #include "../common/Position.h" #include "../common/Velocity.h" TEST_CASE("dummy") { ct::EntityContainer entities; auto e = entities.Create(); auto position = e.Add<ct::Position>(); position->data = { 1.f,2.f,3.f }; auto velocity = e.Add<ct::Velocity>(); velocity->data = { 3.f,4.f,5.f }; ct::move_system::Process(entities, 0.1f); } TEST_CASE("can handle entities without required components") { ct::EntityContainer entities; auto e = entities.Create(); ct::move_system::Process(entities, 0.1f); }<file_sep>/test/CMakeLists.txt cmake_minimum_required(VERSION 3.19) project(test) aux_source_directory(. source) aux_source_directory(../common common) aux_source_directory(../server server) list(REMOVE_ITEM server "../server/main.cpp") find_package(Threads REQUIRED) foreach(test ${source}) string(SUBSTRING ${test} 2 -1 test) set(test_name "${test}") add_executable(${test_name} ${test} ${common} ${server}) set_property(TARGET ${test_name} PROPERTY CXX_STANDARD 20) set_property(TARGET ${test_name} PROPERTY CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STACK_SIZE 100000000) target_include_directories(${test_name} PUBLIC "../submodules/asio/asio/include") target_include_directories(${test_name} PUBLIC "../submodules/Catch2/single_include/catch2") target_include_directories(${test_name} PUBLIC "../submodules/eigen") target_include_directories(${test_name} PUBLIC "../submodules/ZSerializer") target_link_libraries(${test_name} ${CMAKE_THREAD_LIBS_INIT}) install(TARGETS ${test_name}) endforeach()<file_sep>/common/UUID.h #pragma once #include <cstdint> #include <atomic> namespace ct { struct UUID { uint64_t id; }; // TODO inline uint64_t GenerateUUID() { static std::atomic_uint64_t id; return ++id; } }<file_sep>/client_ue4/CrazyTang/Source/CrazyTang/CrazyTangPawnBase.h // Fill out your copyright notice in the Description page of Project Settings. #pragma once #include <cstdint> #include "CoreMinimal.h" #include "GameFramework/Pawn.h" #if PLATFORM_WINDOWS #include "Windows/PreWindowsApi.h" #endif #include "Eigen/Eigen" #include "common/NetAgent.h" #if PLATFORM_WINDOWS #include "Windows/PostWindowsApi.h" #endif #include "CrazyTangPawnBase.generated.h" UCLASS() class CRAZYTANG_API ACrazyTangPawnBase : public APawn { GENERATED_BODY() public: // Sets default values for this pawn's properties ACrazyTangPawnBase(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; public: void SetupNetAgent(ct::NetAgent<>*); void SetUUID(uint64_t); void MoveX(float axis); void MoveY(float axis); void SendInput(); private: uint64_t m_UUID = 0; ct::NetAgent<>* m_NetAgent = nullptr; Eigen::Vector3f m_Input; }; <file_sep>/common/MoveSystem.h #pragma once #include "Entity.h" namespace ct { namespace move_system { void Process(EntityContainer&, float step); } }<file_sep>/client_ue4/CrazyTang/Source/CrazyTang/CrazyTang.Build.cs // Copyright Epic Games, Inc. All Rights Reserved. using System.IO; using System; using System.Linq; using System.Diagnostics; using System.Text; using UnrealBuildTool; public class CrazyTang : ModuleRules { string RepositoryRoot { get { return Path.Combine(ModuleDirectory, "../../../../"); } } string Core { get { return Path.Combine(RepositoryRoot, "build/client_core/Release/client_core.lib"); } } string Asio { get { return Path.Combine(RepositoryRoot, "submodules/asio/asio/include"); } } string Eigen { get { return Path.Combine(RepositoryRoot, "submodules/eigen"); } } string ZSerializer { get { return Path.Combine(RepositoryRoot, "submodules/ZSerializer"); } } bool BuildCore() { return ExecuteCommandSync("python tools/client_core.py --config release") == 0; } public CrazyTang(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.NoSharedPCHs; PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "Voxel" }); PrivateDependencyModuleNames.AddRange(new string[] { }); BuildCore(); PublicAdditionalLibraries.Add(Core); PublicIncludePaths.Add(RepositoryRoot); PublicIncludePaths.Add(Asio); PublicIncludePaths.Add(Eigen); PublicIncludePaths.Add(ZSerializer); bUseRTTI = true; bEnableExceptions = true; CppStandard = CppStandardVersion.Latest; // Uncomment if you are using Slate UI // PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" }); // Uncomment if you are using online features // PrivateDependencyModuleNames.Add("OnlineSubsystem"); // To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true } int ExecuteCommandSync(string command) { var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command) { CreateNoWindow = true, UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, WorkingDirectory = RepositoryRoot, StandardOutputEncoding = Encoding.Default }; Process p = Process.Start(processInfo); p.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data); p.BeginOutputReadLine(); p.WaitForExit(); return p.ExitCode; } } <file_sep>/common/Entity.h #pragma once #include <any> #include <cassert> #include <cstdint> #include <typeinfo> #include <typeindex> #include <unordered_map> #include <functional> namespace ct { class EntityContainer; class EntityHandle { public: template<typename Component> Component* Add(); template<typename Component> void Remove(); template<typename Component> bool Has() const; template<typename Component> Component* Get(); template<typename Component> const Component* Get() const; public: void Destroy(); bool Valid() const; public: uint64_t id_ = 0; EntityContainer* container_ = nullptr; }; bool operator<(EntityHandle, EntityHandle); bool operator==(EntityHandle, EntityHandle); bool operator!=(EntityHandle, EntityHandle); class EntityContainer { public: EntityHandle Create(); void ForEach(std::function<void(EntityHandle)>); private: bool Has(uint64_t) const; void Remove(uint64_t); private: template<typename Component> Component* Add(uint64_t id); template<typename Component> void Remove(uint64_t id); template<typename Component> bool Has(uint64_t id); template<typename Component> Component* Get(uint64_t id); private: friend class EntityHandle; uint64_t assignedID_ = 0; using EntityComponents = std::unordered_map<std::type_index, std::any>; std::unordered_map<uint64_t, EntityComponents> entities_; }; template<typename Component> Component* EntityHandle::Add() { return container_->Add<Component>(id_); } template<typename Component> void EntityHandle::Remove() { return container_->Remove<Component>(id_); } template<typename Component> bool EntityHandle::Has() const { return container_->Has<Component>(id_); } template<typename Component> Component* EntityHandle::Get() { return container_->Get<Component>(id_); } template<typename Component> const Component* EntityHandle::Get() const { return container_->Get<Component>(id_); } template<typename Component> Component* EntityContainer::Add(uint64_t id) { assert(Has(id)); auto& components = entities_[id]; assert(components.find(typeid(Component)) == components.end()); auto type = std::type_index(typeid(Component)); auto [where, _] = components.emplace(std::make_pair(type, Component{})); auto value = &(where->second); return std::any_cast<Component>(value); } template<typename Component> void EntityContainer::Remove(uint64_t id) { assert(Has(id)); auto& components = entities_[id]; assert(components.find(typeid(Component)) != components.end()); auto type = std::type_index(typeid(Component)); components.erase(type); } template<typename Component> bool EntityContainer::Has(uint64_t id) { assert(Has(id)); auto& components = entities_[id]; auto type = std::type_index(typeid(Component)); return components.find(type) != components.end(); } template<typename Component> Component* EntityContainer::Get(uint64_t id) { assert(Has(id)); if (!Has<Component>(id)) return nullptr; auto type = std::type_index(typeid(Component)); auto& components = entities_[id]; auto value = &(components[type]); return std::any_cast<Component>(value); } } namespace std { template<> struct hash<ct::EntityHandle> { std::size_t operator()(ct::EntityHandle e) const noexcept { std::size_t h1 = std::hash<decltype(e.container_)>{}(e.container_); std::size_t h2 = std::hash<decltype(e.id_)>{}(e.id_); return h1 ^ (h2 << 1); } }; }<file_sep>/tools/ct_common.py import os import pathlib import subprocess import shutil def execute(cmd): print_colored(f"executing: {cmd}") assert(0 == subprocess.call(cmd, shell=True)) def get_root_path(): cur = pathlib.Path(__file__) return cur.absolute().parent.parent def print_colored(str): os.system("color") green = '\033[92m' end = '\033[0m' print(f"{green}{str}{end}") def rmdir(dir): print_colored(f"executing: rmdir {dir}") shutil.rmtree(dir, ignore_errors=True) def prefix(install_dir): return f"-DCMAKE_INSTALL_PREFIX={install_dir}" if install_dir else "" def cmake(source_dir, build_dir, ninja, install_dir=None): execute( f"cmake {prefix(install_dir)} -S {source_dir} -B {build_dir} {' -G Ninja' if ninja else ''}") def build(build_dir, config): execute(f"cmake --build {build_dir} --config {config} -j {os.cpu_count()}") def install(build_dir, config): execute( f"cmake --install {build_dir} --config {config}") <file_sep>/server/CMakeLists.txt cmake_minimum_required(VERSION 3.19) project(server) aux_source_directory(. source) aux_source_directory(../common source) add_executable(${PROJECT_NAME} ${source}) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD_REQUIRED ON) set(CMAKE_EXE_LINKER_FLAGS " -static") set(CMAKE_CXX_STACK_SIZE 100000000) target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/asio/asio/include") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/eigen") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/ZSerializer") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/FastNoiseLite/Cpp") find_package(Threads REQUIRED) target_link_libraries(${PROJECT_NAME} ${CMAKE_THREAD_LIBS_INIT}) install(TARGETS ${PROJECT_NAME})<file_sep>/client_ue4/CrazyTang/Source/CrazyTang/CrazyTangGameModeBase.cpp // Copyright Epic Games, Inc. All Rights Reserved. #include "CrazyTangGameModeBase.h" #include "Engine.h" #include "VoxelValue.h" #include "VoxelData/VoxelDataIncludes.h" #include "VoxelTools/VoxelToolHelpers.h" THIRD_PARTY_INCLUDES_START #include "Eigen/Eigen" #include "ZSerializer.hpp" #include "common/AsyncConnect.h" #include "common/NetAgent.h" #include "common/Entity.h" #include "common/Position.h" #include "common/Velocity.h" #include "common/Voxel.h" #include "common/Math.h" #include "client_core/Login.h" THIRD_PARTY_INCLUDES_END using namespace asio::ip; using namespace ct; namespace { tcp::endpoint StringToEndpoint(const std::string& str) { auto pos = str.find(':'); if (pos == std::string::npos) return {}; auto ip = str.substr(0, pos); int port = std::stoi(str.substr(pos + 1)); return { asio::ip::make_address_v4(ip), (unsigned short)port }; } tcp::endpoint ServerEndpoint() { return StringToEndpoint("127.0.0.1:33773"); } struct ConnectionID { uint64_t id; }; template<typename In> bool ReadEntity(In& in, ct::EntityHandle e) { auto uuid = zs::Read<UUID>(in); if (std::holds_alternative<zs::Error>(uuid)) return false; *e.Add<UUID>() = std::get<0>(uuid); zs::StringReader components(std::get<0>(zs::Read<std::string>(in))); while (true) { auto _tag = zs::Read<std::string>(components); if (std::holds_alternative<zs::Error>(_tag)) break; auto tag = std::get<0>(_tag); if (tag == "connection") { if (!e.Has<ConnectionID>()) e.Add<ConnectionID>(); *e.Get<ConnectionID>() = std::get<0>(zs::Read<ConnectionID>(components)); } else if (tag == "position") { if (!e.Has<Position>()) e.Add<Position>(); *e.Get<Position>() = std::get<0>(zs::Read<Position>(components)); } else if (tag == "velocity") { if (!e.Has<Velocity>()) e.Add<Velocity>(); *e.Get<Velocity>() = std::get<0>(zs::Read<Velocity>(components)); } else { assert(false); } } return true; } struct ActorInfo { ACrazyTangPawnBase* pawn = nullptr; }; } ACrazyTangGameModeBase::ACrazyTangGameModeBase() { PrimaryActorTick.bCanEverTick = true; } void ACrazyTangGameModeBase::InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage) { Super::InitGame(MapName, Options, ErrorMessage); if (GEngine) GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, TEXT("InitGame")); ct::AsyncConnect(m_HighPriorityIO, ServerEndpoint(), [&](const std::error_code& ec, std::shared_ptr<ct::Socket> socket) { if (ec) { GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, TEXT("Connection Failed")); return; } GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, TEXT("Connection Succeed")); auto pipe = std::make_shared<ct::Pipe<>>(std::move(*socket)); OnConnected(m_HighPriorityIO, pipe); }); auto world = GetVoxelWorld(); if (world) { world->VoxelSize = 10.f; world->SetWorldSize(std::max((int)m_Voxels.x, (int)m_Voxels.y)); world->CreateWorld(); } } void ACrazyTangGameModeBase::Tick(float DeltaSeconds) { m_HighPriorityIO.poll(); m_LowPriorityIO.run_for(std::chrono::milliseconds{ 1 }); TickVoxels(DeltaSeconds); return Super::Tick(DeltaSeconds); } void ACrazyTangGameModeBase::OnConnected(asio::io_context& io, std::shared_ptr<ct::Pipe<>> pipe) { auto login = std::make_shared<ct::Login<>>(pipe, io, std::chrono::seconds{ 3 }); login->OnSuccess( [login, &io, pipe, this](uint64_t id) { GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, TEXT("Login Succeed")); OnLoginSuccess(io, id, pipe); }); login->OnError( [login]() { GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, TEXT("Login Failed")); }); } void ACrazyTangGameModeBase::OnLoginSuccess(asio::io_context& io, uint64_t clientID, std::shared_ptr<Pipe<>> pipe) { auto agent = std::make_shared<ct::NetAgent<>>(pipe); agent->OnError( [agent]() { GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, TEXT("NetAgent OnError")); }); { zs::StringWriter out; zs::Write(out, Eigen::Vector3f{ 1.f,0,0 }); agent->Send("set position", out.String()); } { zs::StringWriter out; zs::Write(out, Eigen::Vector3f{ 0,50.f,0 }); agent->Send("set velocity", out.String()); } agent->Listen("entities", [this, clientID, agent](std::string&& rawWorld) { zs::StringReader worldArchive{ std::move(rawWorld) }; ct::EntityContainer newEntities; std::unordered_map<uint64_t, ct::EntityHandle> newIDToEntities; while (true) { auto e = newEntities.Create(); if (!ReadEntity(worldArchive, e)) { e.Destroy(); break; } newIDToEntities[e.Get<UUID>()->id] = e; } std::unordered_map<uint64_t, ct::EntityHandle> oldIDToEntities; m_Entities.ForEach([&oldIDToEntities](ct::EntityHandle e) { oldIDToEntities[e.Get<UUID>()->id] = e; }); for (auto [uuid, entity] : oldIDToEntities) { if (newIDToEntities.find(uuid) == newIDToEntities.end()) { // remove entity.Get<ActorInfo>()->pawn->Destroy(); entity.Destroy(); } } for (auto [uuid, entity] : newIDToEntities) { auto old = oldIDToEntities.find(uuid); if (old == oldIDToEntities.end()) { // add auto actor = GetWorld()->SpawnActor<ACrazyTangPawnBase>(MyPawn); if (entity.Has<ConnectionID>() && entity.Get<ConnectionID>()->id == clientID) actor->SetupNetAgent(agent.get()); actor->SetUUID(uuid); auto info = entity.Add<ActorInfo>(); info->pawn = actor; } else { // refresh auto info = entity.Add<ActorInfo>(); *info = *(old->second.Get<ActorInfo>()); } } m_Entities = newEntities; }); agent->Listen("voxels", [this, agent](std::string&& rawVoxels) { zs::StringReader in(std::move(rawVoxels)); while (true) { auto rawX = zs::Read<int>(in); if (std::holds_alternative<zs::Error>(rawX)) break; auto x = std::get<0>(rawX); auto y = std::get<0>(zs::Read<int>(in)); auto z = std::get<0>(zs::Read<int>(in)); auto newVoxel = std::get<0>(zs::Read<ct::voxel::Voxel>(in)); auto nowVoxel = m_Voxels.Get(x, y, z); *nowVoxel = newVoxel; } }); } ct::EntityHandle ACrazyTangGameModeBase::GetEntity(uint64_t id) { ct::EntityHandle entity; m_Entities.ForEach([&entity, id](ct::EntityHandle e) { if (entity.Valid()) return; if(e.Get<UUID>()->id == id) entity = e; }); return entity; } void ACrazyTangGameModeBase::TickVoxels(float dt) { auto world = GetVoxelWorld(); int index = 0; for (size_t x = 0;x < m_Voxels.x;++x) { for (size_t y = 0;y < m_Voxels.y;++y) { for (size_t z = 0;z < m_Voxels.z;++z) { auto type = m_Voxels.Get(x, y, z)->type; if (type == ct::voxel::Type::Block) { if (world) world->GetData().SetValue(x, y, z, FVoxelValue(-1.f)); } else if (type == ct::voxel::Type::Empty) { if (world) world->GetData().SetValue(x, y, z, FVoxelValue(1.f)); } else { if (world) world->GetData().SetValue(x, y, z, FVoxelValue(1.f)); } index++; } } } if (world) { FVoxelToolHelpers::UpdateWorld(world, FVoxelIntBox{ FIntVector{-100,-100,-100},FIntVector{100,100,100} }); } } AVoxelWorld* ACrazyTangGameModeBase::GetVoxelWorld() { TArray<AActor*> worlds; UGameplayStatics::GetAllActorsOfClass(GetWorld(), AVoxelWorld::StaticClass(), worlds); return worlds.Num() > 0 ? Cast<AVoxelWorld>(worlds[0]) : nullptr; } <file_sep>/server/ConnectionInfo.h #pragma once #include <cstdint> #include <memory> #include "../common/Net.h" namespace ct { struct ConnectionInfo { uint64_t connectionID; std::weak_ptr<ct::NetAgent> agent; }; struct Connection { uint64_t connectionID; std::shared_ptr<ct::NetAgent> agent; }; } // namespace<file_sep>/server/VoxelWatcher.h #pragma once #include "../common/Voxel.h" #include "../common/Entity.h" namespace ct { namespace voxel_watcher { void Process(EntityContainer&, voxel::Container&, float step); void Sync(EntityHandle&, voxel::Container&); } }<file_sep>/common/MoveSystem.cpp #include "MoveSystem.h" #include "Move.h" #include "Position.h" #include "Velocity.h" namespace ct { namespace move_system { void Process(EntityContainer& entities, float step) { entities.ForEach([step](EntityHandle e) { if (!e.Has<Position>() || !e.Has<Velocity>()) return; move::State s; s.position = e.Get<Position>()->data; s.velocity = e.Get<Velocity>()->data; s = move::Process(s, step); e.Get<Position>()->data = s.position; e.Get<Velocity>()->data = s.velocity; }); } } }<file_sep>/client_core/Login.h #pragma once #include <cstdint> #include <memory> #include <optional> #include <asio.hpp> #include "../common/Packet.h" #include "../common/Net.h" namespace ct { inline std::optional<uint64_t> _ToNumber(const std::string& str) { try { return std::stoull(str); } catch (...) { return std::nullopt; } } inline asio::awaitable<std::optional<uint64_t>> ClientLogin(asio::ip::tcp::socket& socket, std::chrono::seconds timeout) { std::stop_source timeoutHandle; co_spawn(co_await asio::this_coro::executor, [&socket, timeout, stop = timeoutHandle.get_token()]()->asio::awaitable<void> { asio::steady_timer timer{ co_await asio::this_coro::executor }; timer.expires_after(timeout); co_await timer.async_wait(asio::use_awaitable); if (!stop.stop_requested()) socket.close(); }, asio::detached); co_await AsyncWritePacket(socket, Packet{ std::string("hello from client") }); auto read = co_await AsyncReadPacket(socket); timeoutHandle.request_stop(); const std::string_view expected = "hello client, your id is "; auto reply = std::string(read.Data(), read.Size()); if (reply.substr(0, expected.size()) != expected) co_return std::nullopt; co_return _ToNumber(reply.substr(expected.size())); } } <file_sep>/common/Move.h #pragma once #include <Eigen/Eigen> namespace ct { namespace move { struct State { Eigen::Vector3f velocity; Eigen::Vector3f position; }; State Process(const State&, float dt); } }<file_sep>/common/Voxel.h #pragma once #include "../common/Position.h" #include <ZSerializer.hpp> #include <Eigen/Eigen> #include <tuple> #include <functional> namespace ct { namespace voxel { bool _InRange(int value, int begin, int end); constexpr float sideLength = 10.f; enum class Type { Unknown, Empty, Block }; struct Voxel { Type type; }; template<typename Voxel> struct ContainerT { static constexpr size_t x = 128; static constexpr size_t y = 16; static constexpr size_t z = 128; static constexpr size_t size = x * y * z; static inline const auto indices = [] { std::array<Eigen::Vector3i, size> indices; size_t index = 0; for (int _x = 0;_x < x;++_x) for (int _y = 0;_y < y;++_y) for (int _z = 0;_z < z;++_z) indices[index++] = { _x,_y,_z }; return indices; }(); std::vector<Voxel> voxels{ x * y * z }; Voxel* Get(int _x, int _y, int _z) { if (!ct::voxel::_InRange(_x, 0, x)) return nullptr; if (!ct::voxel::_InRange(_y, 0, y)) return nullptr; if (!ct::voxel::_InRange(_z, 0, z)) return nullptr; return GetNoCheck(_x, _y, _z); } Voxel* GetNoCheck(int _x, int _y, int _z) { size_t index = _x + _y * x + _z * x * y; return &voxels[index]; } template<typename Func> void ForEach(Func func) { for (size_t _z = 0;_z < z;++_z) for (size_t _y = 0;_y < y;++_y) for (size_t _x = 0;_x < x;++_x) func(_x, _y, _z, GetNoCheck(_x, _y, _z)); } }; using Container = ContainerT<Voxel>; void GenerateVoxels(Container&); void Process(Container&, float step); std::tuple<int, int, int> DecodeIndex(const Position&); } } namespace zs { template<> struct Trait<ct::voxel::Container> :public WriteMembers<ct::voxel::Container>, public ReadMembers<ct::voxel::Container> { static constexpr auto members = std::make_tuple ( &ct::voxel::Container::voxels ); }; }<file_sep>/test/Entity_Test.cpp #define CATCH_CONFIG_MAIN #include <catch.hpp> #include "../common/Entity.h" namespace { struct Data {}; } TEST_CASE("entity default constructor") { ct::EntityHandle e; REQUIRE(!e.Valid()); } TEST_CASE("entity component") { ct::EntityContainer entities; ct::EntityHandle e = entities.Create(); REQUIRE(e.Has<Data>() == false); REQUIRE(e.Get<Data>() == nullptr); auto data = e.Add<Data>(); REQUIRE(e.Has<Data>() == true); REQUIRE(e.Get<Data>() == data); e.Remove<Data>(); REQUIRE(e.Has<Data>() == false); REQUIRE(e.Get<Data>() == nullptr); } TEST_CASE("entity equality") { ct::EntityContainer entities; ct::EntityHandle e0 = entities.Create(); ct::EntityHandle e1 = entities.Create(); REQUIRE(e0 == e0); REQUIRE(e0 != e1); auto e0Copy = e0; REQUIRE(e0Copy == e0); REQUIRE(e0Copy != e1); ct::EntityHandle defaultConstructed; REQUIRE(defaultConstructed != e0); REQUIRE(defaultConstructed != e1); } TEST_CASE("entity comparison") { ct::EntityContainer entities; ct::EntityHandle e0 = entities.Create(); ct::EntityHandle e1 = entities.Create(); REQUIRE((e0 < e1) != (e1 < e0)); } TEST_CASE("entity hash") { ct::EntityContainer entities; ct::EntityHandle e = entities.Create(); REQUIRE(std::hash<ct::EntityHandle>{}(e) == std::hash<ct::EntityHandle>{}(e)); } TEST_CASE("entity destroy") { ct::EntityContainer entities; ct::EntityHandle e = entities.Create(); REQUIRE(e.Valid()); e.Destroy(); REQUIRE(e.Valid() == false); } TEST_CASE("for each") { ct::EntityContainer container; std::set<ct::EntityHandle> entities; for (int i = 0;i < 10;++i) entities.emplace(container.Create()); container.ForEach([&entities](ct::EntityHandle e) { REQUIRE(!entities.empty()); entities.erase(e); } ); REQUIRE(entities.empty()); }<file_sep>/common/Name.h #pragma once #include <Eigen/Eigen> namespace xy { struct Name { std::string data = ""; }; } namespace zs { template<> struct Trait<xy::Name> : public WriteMembers<xy::Name>, public ReadMembers<xy::Name> { static constexpr auto members = std::make_tuple ( &xy::Name::data ); }; }<file_sep>/client_ue4/CrazyTang/Source/CrazyTang/CrazyTang.cpp // Copyright Epic Games, Inc. All Rights Reserved. #include "CrazyTang.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, CrazyTang, "CrazyTang" ); <file_sep>/common/Move.cpp #include "Move.h" namespace ct { namespace move { State Process(const State& origin, float dt) { auto copy = origin; copy.position += copy.velocity * dt; return copy; } } }<file_sep>/client_gui/client_gui.cpp #include "client_gui.h" #include <algorithm> #include <execution> #include <array> #include <atomic> #include "imgui.h" #include "cpr/cpr.h" #include "nlohmann/json.hpp" #include <Magnum/Math/Color.h> #include <Magnum/Math/Quaternion.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/Primitives/Icosphere.h> #include <Magnum/MeshTools/Compile.h> #include <Magnum/Trade/MeshData.h> #include "ZSerializer.hpp" #include "../client_core/Login.h" #include "../common/Position.h" #include "../common/Velocity.h" #include "../common/Name.h" #include "../common/Math.h" #include "../common/UUID.h" using namespace ct; using namespace Math::Literals; using asio::ip::tcp; using json = nlohmann::json; #define PX_RELEASE(x) if(x) { x->release(); x = NULL; } namespace { using namespace physx; PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; PxPhysics* gPhysics = NULL; PxDefaultCpuDispatcher* gDispatcher = NULL; PxScene* gScene = NULL; PxMaterial* gMaterial = NULL; PxRigidStatic* CreateBoxStatic(const PxTransform& t, const PxVec3& halfExtents) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtents), *gMaterial); auto body = gPhysics->createRigidStatic(t); body->attachShape(*shape); gScene->addActor(*body); shape->release(); return body; } void initPhysics() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); } void stepPhysics() { gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PX_RELEASE(gFoundation); } } namespace { std::vector<std::string> logs; void Log(const std::string& str) { logs.push_back(str); } struct ConnectionID { uint64_t id; }; tcp::endpoint StringToEndpoint(const std::string& str) { auto pos = str.find(':'); if (pos == std::string::npos) return {}; auto ip = str.substr(0, pos); int port = std::stoi(str.substr(pos + 1)); return { asio::ip::make_address_v4(ip), (unsigned short)port }; } template<typename In> bool ReadEntity(In& in, EntityHandle e) { auto uuid = zs::Read<UUID>(in); if (std::holds_alternative<zs::Error>(uuid)) return false; *e.Add<UUID>() = std::get<0>(uuid); zs::StringReader components(std::get<0>(zs::Read<std::string>(in))); while (true) { auto _tag = zs::Read<std::string>(components); if (std::holds_alternative<zs::Error>(_tag)) break; auto tag = std::get<0>(_tag); if (tag == "connection") { if (!e.Has<ConnectionID>()) e.Add<ConnectionID>(); *e.Get<ConnectionID>() = std::get<0>(zs::Read<ConnectionID>(components)); } else if (tag == "position") { if (!e.Has<Position>()) e.Add<Position>(); *e.Get<Position>() = std::get<0>(zs::Read<Position>(components)); } else if (tag == "velocity") { if (!e.Has<Velocity>()) e.Add<Velocity>(); *e.Get<Velocity>() = std::get<0>(zs::Read<Velocity>(components)); } else if (tag == "name") { if (!e.Has<xy::Name>()) e.Add<xy::Name>(); *e.Get<xy::Name>() = std::get<0>(zs::Read<xy::Name>(components)); } else { assert(false); } } return true; } } namespace ct { asio::awaitable<void> App::Login(asio::io_context& io, const tcp::endpoint& endpoint) { asio::ip::tcp::socket s{ io }; co_await s.async_connect(endpoint, asio::use_awaitable); auto id = co_await ClientLogin(s, std::chrono::seconds{ 3 }); if (!id) co_return; Log("login success " + std::to_string(*id)); auto agent = std::make_shared<NetAgent>(std::move(s)); agent->OnError( [agent]() { Log("net agent on error"); }); agent->Listen("entities", [agent, this](std::string&& rawWorld) { zs::StringReader worldArchive{ std::move(rawWorld) }; curEntities_ = EntityContainer{}; while (true) { auto e = curEntities_.Create(); if (!ReadEntity(worldArchive, e)) { e.Destroy(); break; } } }); agent->Listen("voxels", [agent, this](std::string&& rawVoxels) { zs::StringReader in(std::move(rawVoxels)); while (true) { auto rawX = zs::Read<int>(in); if (std::holds_alternative<zs::Error>(rawX)) break; auto x = std::get<0>(rawX); auto y = std::get<0>(zs::Read<int>(in)); auto z = std::get<0>(zs::Read<int>(in)); auto newVoxel = std::get<0>(zs::Read<voxel::Voxel>(in)); auto nowVoxel = curVoxels_.Get(x, y, z); *nowVoxel = newVoxel; } }); { zs::StringWriter out; zs::Write(out, std::string("a")); agent->Send("set name", out.String()); } co_spawn(co_await asio::this_coro::executor, [agent]() -> asio::awaitable<void> { co_await agent->ReadRoutine(); }, asio::detached); co_spawn(co_await asio::this_coro::executor, [agent]() -> asio::awaitable<void> { co_await agent->WriteRoutine(); }, asio::detached); curAgent_ = agent; curID_ = *id; co_spawn(co_await asio::this_coro::executor, Sync(), asio::detached); } asio::awaitable<void> App::Sync() { asio::system_timer t{ io_ }; while (curAgent_) { t.expires_after(std::chrono::milliseconds{ 33 }); co_await t.async_wait(asio::use_awaitable); zs::StringWriter out; zs::Write(out, Eigen::Vector3f(cameraPos_.data())); curAgent_->Send("set position", out.String()); } } asio::awaitable<void> App::RefreshServerList(asio::io_context& io) { cpr::Response r = cpr::Get(cpr::Url{ "http://ct-1302800279.cos.ap-hongkong.myqcloud.com/server.json" }); if (r.status_code != 200) co_return; servers_.clear(); for (auto server : json::parse(r.text)) servers_.push_back({ server["name"], StringToEndpoint(server["endpoint"]) }); } App::App(const Vector2i& windowSize, GLFWwindow* window) :windowSize_(windowSize), window_(window), voxelShader_(Shaders::PhongGL::Flag::InstancedTransformation | Shaders::PhongGL::Flag::VertexColor) { voxelMesh_ = MeshTools::compile(Primitives::cubeSolid()); voxelMesh_.addVertexBufferInstanced(voxelBuffer_, 1, 0, Shaders::PhongGL::TransformationMatrix{}, Shaders::PhongGL::NormalMatrix{}, Shaders::PhongGL::Color4{}); palette_[voxel::Type::Block] = 0xffffff_rgbf; playerMesh_ = MeshTools::compile(Primitives::icosphereSolid(2)); co_spawn(io_, RefreshServerList(io_), asio::detached); initPhysics(); } void App::Tick() { io_.run_for(std::chrono::milliseconds{ 1 }); TickInput(); TickVoxelsView(); stepPhysics(); DrawVoxels(); DrawPlayers(); TickImGui(); fps_.fire(); } void App::OnMouseMove(float dx, float dy) { cameraYaw_ -= dx * 0.002f; cameraPitch_ -= dy * 0.002f; } void App::DrawVoxels() { struct Instance { Matrix4 transformation; Matrix3x3 normal; Color4 color; }; std::array<Instance, voxel::Container::size> instances; std::atomic_size_t index = 0; std::for_each(std::execution::par_unseq, std::cbegin(voxel::Container::indices), std::cend(voxel::Container::indices), [&](auto voxelIndex) { auto [x, y, z] = ToTuple(voxelIndex); auto voxel = curVoxels_.Get(x, y, z); if (!voxel) return; if (voxel->type != voxel::Type::Block) return; Vector3 pos = { float(x),float(y),float(z) }; auto transform = Matrix4::translation(pos) * Matrix4::scaling(Vector3{ 0.5f,0.5f,0.5f }); auto color = palette_[voxel->type]; instances[index++] = { transform, transform.normalMatrix(), color }; }); voxelBuffer_.setData( Containers::ArrayView{ instances.data(), index }, GL::BufferUsage::DynamicDraw); voxelMesh_.setInstanceCount(index); voxelShader_.setLightPositions({ {1.4f, 1.0f, 0.75f, 0.0f} }) .setDiffuseColor(0xffffff_rgbf) .setAmbientColor(Color3::fromHsv(Deg(0.f), 0.f, 0.3f)) .setProjectionMatrix(projection_); voxelShader_.draw(voxelMesh_); drawVoxels_ = index; } void App::DrawPlayers() { curEntities_.ForEach([&](auto e) { if (!e.Has<Position>()) return; auto pos = e.Get<Position>()->data; auto transform = Matrix4::translation(Vector3{ pos.x(), pos.y(), pos.z() }) * Matrix4::scaling(Vector3{ 0.5f,0.5f,0.5f }); playerShader_.setLightPositions({ {1.4f, 1.0f, 0.75f, 0.0f} }) .setDiffuseColor(0x0000ff_rgbf) .setAmbientColor(Color3::fromHsv(Deg(0.f), 0.f, 0.3f)) .setProjectionMatrix(projection_) .setTransformationMatrix(transform) .setNormalMatrix(transform.normalMatrix()); playerShader_.draw(playerMesh_); }); } void App::TickImGui() { ImGui::Begin("CrazyTang"); ImGui::Text("fps: %f", fps_.get()); ImGui::Text("voxel: %d/%llu", drawVoxels_, curVoxels_.x * curVoxels_.y * curVoxels_.z); if (curAgent_) { ImGui::Text("id: %llu", curID_); } else { ImGui::Separator(); ImGui::Text("servers:"); ImGui::SameLine(); if (ImGui::Button("refresh")) co_spawn(io_, RefreshServerList(io_), asio::detached); for (const auto& server : servers_) if (ImGui::Button(server.name.c_str())) co_spawn(io_, Login(io_, server.endpoint), asio::detached); ImGui::Separator(); } ImGui::DragFloat("camera yaw", &cameraYaw_, 0.01f); ImGui::DragFloat("camera pitch", &cameraPitch_, 0.01f); ImGui::DragFloat3("camera", cameraPos_.data(), 0.01f); { auto camera = Matrix4::translation(cameraPos_) * Matrix4::rotation(Rad{ cameraYaw_ }, Vector3::yAxis()) * Matrix4::rotation(Rad{ cameraPitch_ }, Vector3::xAxis()); camera = camera.inverted(); projection_ = Matrix4::perspectiveProjection(35.0_degf, windowSize_.aspectRatio(), 0.01f, 1000.0f) * camera; } curEntities_.ForEach([](auto e) { auto id = e.Get<ConnectionID>()->id; auto name = "entity " + std::to_string(id); if (ImGui::TreeNode(name.c_str())) { if (e.Has<Position>()) { auto pos = e.Get<Position>()->data; ImGui::Text("pos:%06f %06f %06f", pos.x(), pos.y(), pos.z()); } if (e.Has<Velocity>()) { auto vel = e.Get<Velocity>()->data; ImGui::Text("vel:%06f %06f %06f", vel.x(), vel.y(), vel.z()); } if (e.Has<xy::Name>()) { auto name = e.Get<xy::Name>()->data; ImGui::Text("name:%s", name.c_str()); } ImGui::TreePop(); } }); ImGui::End(); ImGui::Begin("log"); for (auto beg = logs.rbegin();beg != logs.rend();++beg) ImGui::Text(beg->c_str()); ImGui::End(); } void App::TickInput() { float speed = 0.1f; float forward = 0.f; float left = 0.f; float up = 0.f; if (glfwGetKey(window_, GLFW_KEY_W) == GLFW_PRESS) forward += 1.f; if (glfwGetKey(window_, GLFW_KEY_S) == GLFW_PRESS) forward -= 1.f; if (glfwGetKey(window_, GLFW_KEY_A) == GLFW_PRESS) left += 1.f; if (glfwGetKey(window_, GLFW_KEY_D) == GLFW_PRESS) left -= 1.f; if (glfwGetKey(window_, GLFW_KEY_Q) == GLFW_PRESS) up -= 1.f; if (glfwGetKey(window_, GLFW_KEY_E) == GLFW_PRESS) up += 1.f; auto q = Quaternion::rotation(Rad(cameraYaw_), Vector3::yAxis()) * Quaternion::rotation(Rad(cameraPitch_), Vector3::xAxis()); cameraPos_ += speed * forward * q.transformVector(-Vector3::zAxis()); cameraPos_ += speed * left * q.transformVector(-Vector3::xAxis()); cameraPos_ += speed * up * q.transformVector(Vector3::yAxis()); } void App::TickVoxelsView() { for (auto index : voxel::Container::indices) { auto data = curVoxels_.GetNoCheck(index.x(), index.y(), index.z()); auto view = curVoxelsView_.GetNoCheck(index.x(), index.y(), index.z()); if (data->type == voxel::Type::Block) { if (!view->rigid) { view->rigid = CreateBoxStatic(PxTransform{ PxVec3(index.x(),index.y(),index.z()) }, PxVec3{ 0.5f,0.5f,0.5f }); } } else { if (view->rigid) { view->rigid->release(); view->rigid = nullptr; } } } } }<file_sep>/test/Move_Test.cpp #define CATCH_CONFIG_MAIN #include <catch.hpp> #include "../common/Move.h" TEST_CASE("Move") { ct::move::State origin; origin.velocity = { 0.f,0.f,1.f }; origin.position = { 2.f,3.f,4.f }; float dt = 1.f; auto newState = ct::move::Process(origin, 1.f); REQUIRE(newState.velocity == Eigen::Vector3f(0.f, 0.f, 1.f)); REQUIRE(newState.position == Eigen::Vector3f(2.f, 3.f, 5.f)); }<file_sep>/server/VoxelWatcher.cpp #include "VoxelWatcher.h" #include "ConnectionInfo.h" #include "../common/Position.h" #include "ZSerializer.hpp" using namespace ct; namespace { template<typename Func> void TraverseVoxels(voxel::Container& voxels, const Position& pos, int side, Func&& func) { auto [x, y, z] = voxel::DecodeIndex(pos); for (int nowX = x - side;nowX < x + side;++nowX) { for (int nowY = y - side;nowY < y + side;++nowY) { for (int nowZ = z - side;nowZ < z + side;++nowZ) { auto voxel = voxels.Get(nowX, nowY, nowZ); if (!voxel) continue; func(nowX, nowY, nowZ, *voxel); } } } } std::vector<std::string> ArchiveVoxels(voxel::Container& voxels, const Position& pos, int side, int voxelPerMessage) { std::vector<std::string> messages; zs::StringWriter out; int count = 0; TraverseVoxels(voxels, pos, side, [&](int x, int y, int z, const voxel::Voxel& voxel) { if (count >= voxelPerMessage) { messages.emplace_back(out.String()); out = zs::StringWriter{}; count = 0; } zs::Write(out, x); zs::Write(out, y); zs::Write(out, z); zs::Write(out, voxel); ++count; }); if (count != 0) messages.emplace_back(out.String()); return messages; } } namespace ct { namespace voxel_watcher { void Process(EntityContainer& entities, voxel::Container& voxels, float step) { entities.ForEach([&](EntityHandle e) { auto connection = e.Get<ConnectionInfo>(); if (!connection) return; auto pos = e.Get<Position>(); if (!pos) return; auto agent = connection->agent.lock(); assert(agent); auto messages = ArchiveVoxels(voxels, *pos, 10, 100); for (const auto& message : messages) agent->Send("voxels", message); }); } void Sync(EntityHandle& e, voxel::Container& voxels) { auto connection = e.Get<ConnectionInfo>(); if (!connection) return; auto agent = connection->agent.lock(); assert(agent); zs::StringWriter out; int count = 0; int voxelPerMessage = 100; voxels.ForEach([&](int x, int y, int z, voxel::Voxel* voxel) { if (!voxel) return; if (count >= voxelPerMessage) { agent->Send("voxels", out.String()); out = zs::StringWriter{}; count = 0; } zs::Write(out, x); zs::Write(out, y); zs::Write(out, z); zs::Write(out, *voxel); ++count; }); if (count != 0) agent->Send("voxels", out.String()); } } }<file_sep>/doc/serialization_framework.md ## 纯数据存储 ... ## 序列化 ### 接口 * 快照(可选) * delta更新(可选) * 快照的使用 * delta更新的使用 ### 实现 * 普通struct * bitwise快照 * bitwise delta更新 * 带反射复杂结构 * 自动生成快照 * 自动生成delta更新 * 纯自定义手工代码 ## 框架 ### 全局一致 正常使用数据模块 如果有某数据,序列化时使用全局的预定义的序列化方式 ### 多模板 正常使用数据模块 预先指定好自身模板 使用模板预定义的序列化方式 ### 个体自定义 正常使用数据模块 自身运行时注册自身的序列化方式 ### 思考 纯数据存储模块 网络模块遍历存储的数据,查是否有 网络相关需求 网络设置可以全局一致,可以有多份模板,可以按个体不同? delta更新不好做的话,换一个思路 其实可以不用两个快照之间算diff 可以每一个操作都算一个delta 例如set,例如add 到时候正着施加操作,就得到下一个 回退操作,就得到之前的 纯数据截面自然好,不过类似 受击了显示从哪被攻击的,就不好做,因为没有攻击概念了,只剩下底层数据 可以从服务器被攻击时增加一个 单帧事件数据 从哪被攻击了,客户端看见了消费下 纯数据的话可以把entity和entity下属component都弄成同一个东西,可嵌套组合,类比json了 方便数据处理,可以直接以同一种方式遍历,diff,snapshot 但是这样就不好做那种 非纯数据的component 如果让纯数据就直接是个json这种的呢? 如何和运行时的需求结合在一起,比如weak ptr? 另外,之前想的 不同的使用方式写不同的archive,实现上可以让使用方式作为一个标记 可选是用默认的,还是区分,这样大部分默认,避免太麻烦 服务器维持兴趣列表,每次刷新时,记录客户端可见物,是一个数据结构 每次算出来不一样,可以做diff,把delta发给客户端 (不方便的地方在于,运行时数据,和同步的数据,要两套,diff也比较麻烦 可以区分普通的直接覆盖数据和特殊需要处理的数据? diff包含: 添加删除entity(可划归到 添加删除项?) entity内部添加删除项 每项内部数据变动(这个不太好想。。。)) 每个component都包含多个切面(服务器运行时数据、服务器数据快照、客户端对数据快照的处理?) 好像也不对,还是直接两个entities比较,能处理对最好 这样最灵活,丢包、重连 等都方便处理 服务器把东西打包后,变成了一个DOM数据结构 可以对DOM做diff 得到 更新列表(增实体 删实体) 更新列标项(增字段、删字段) 再细化,应该能递归 客户端如何处理呢? 客户端得到DOM后,再反推回去客户端的entities view? DOM的增删实体,对应entity增删 DOM的更新,施加到entity的数据上? 服务器model -> 客户端model -> 客户端view model 大概这三层 服务器model专注服务器逻辑。挑选之后,筛出客户端model,同步给客户端 客户端model的各种修改,告知客户端view model 客户端view model做客户端逻辑<file_sep>/client_cli/main.cpp #include <memory> #include "ZSerializer.hpp" #include "../client_core/Login.h" #include "../common/Net.h" #include "../common/Entity.h" #include "../common/Position.h" #include "../common/Velocity.h" #include "../common/Voxel.h" #include "../common/Math.h" #include "../common/UUID.h" using namespace ct; using asio::ip::tcp; namespace { struct ConnectionID { uint64_t id; }; tcp::endpoint StringToEndpoint(const std::string& str) { auto pos = str.find(':'); if (pos == std::string::npos) return {}; auto ip = str.substr(0, pos); int port = std::stoi(str.substr(pos + 1)); return { asio::ip::make_address_v4(ip), (unsigned short)port }; } tcp::endpoint ServerEndpoint() { return StringToEndpoint("127.0.0.1:33773"); } } // namespace asio::awaitable<void> client(asio::io_context& io) { asio::ip::tcp::socket s{ io }; co_await s.async_connect(ServerEndpoint(), asio::use_awaitable); auto id = co_await ClientLogin(s, std::chrono::seconds{ 3 }); if (!id) co_return; printf("login success %llu\n", *id); auto agent = std::make_shared<NetAgent>(std::move(s)); agent->OnError( [agent]() { printf("net agent on error\n"); }); { zs::StringWriter out; zs::Write(out, Eigen::Vector3f{ 1.f,0,0 }); agent->Send("set position", out.String()); } { zs::StringWriter out; zs::Write(out, Eigen::Vector3f{ 0,1.f,0 }); agent->Send("set velocity", out.String()); } { zs::StringWriter out; zs::Write(out,std::string("a")); agent->Send("set name", out.String()); } co_spawn(co_await asio::this_coro::executor, [agent]() -> asio::awaitable<void> { co_await agent->ReadRoutine(); }, asio::detached); co_spawn(co_await asio::this_coro::executor, [agent]() -> asio::awaitable<void> { co_await agent->WriteRoutine(); }, asio::detached); } int main() { asio::io_context io; co_spawn(io, client(io), asio::detached); io.run(); return 0; }<file_sep>/tools/test.py import os import argparse from ct_common import execute, get_root_path, rmdir, cmake, build, install parser = argparse.ArgumentParser() parser.add_argument("--clean", help="clean before build", action="store_true") parser.add_argument("--config", help="configuration", default="debug") parser.add_argument("--ninja", help="build using ninja", action="store_true") args = parser.parse_args() source_dir = get_root_path().joinpath("test") build_dir = get_root_path().joinpath("build/build_test") install_dir = get_root_path().joinpath(f"build/test/{args.config}") if args.clean: rmdir(build_dir) exit() cmake(source_dir, build_dir, args.ninja, install_dir) build(build_dir, args.config) install(build_dir, args.config) with os.scandir(install_dir.joinpath("bin")) as it: for entry in it: if entry.name.endswith('.exe') and entry.is_file(): execute(entry.path) <file_sep>/server/Login.h #pragma once #include <cstdint> #include <memory> #include <chrono> #include <stop_token> #include <asio.hpp> #include "../common/Packet.h" #include "../common/Net.h" namespace ct { inline asio::awaitable<bool> ServerLogin(asio::ip::tcp::socket& socket, uint64_t id, std::chrono::seconds timeout) { std::stop_source timeoutHandle; co_spawn(co_await asio::this_coro::executor, [&socket, timeout, stop = timeoutHandle.get_token()]()->asio::awaitable<void> { asio::steady_timer timer{ co_await asio::this_coro::executor }; timer.expires_after(timeout); co_await timer.async_wait(asio::use_awaitable); if (!stop.stop_requested()) socket.close(); }, asio::detached); auto read = co_await AsyncReadPacket(socket); timeoutHandle.request_stop(); if (read != std::string("hello from client")) co_return false; auto reply = "hello client, your id is " + std::to_string(id); co_await AsyncWritePacket(socket, Packet{ reply }); co_return true; } } <file_sep>/test/Packet_Test.cpp #define CATCH_CONFIG_MAIN #include <catch.hpp> #include "../common/Packet.h" namespace { const std::string testData = "hohoho hahaha"; } TEST_CASE("default packet") { ct::Packet p; REQUIRE(p.Size() == 0); } TEST_CASE("packet with size") { ct::Packet p{ 1024 }; REQUIRE(p.Size() == 1024); } TEST_CASE("packet with data") { ct::Packet p{ testData.data(),testData.size() }; REQUIRE(p.Size() == testData.size()); REQUIRE(0 == memcmp(p.Data(), testData.data(), p.Size())); } TEST_CASE("packet should copy origin data") { auto origin = testData; ct::Packet p{ origin.data(),origin.size() }; origin[2] = 'a'; REQUIRE(p.Size() == testData.size()); REQUIRE(0 == memcmp(p.Data(), testData.data(), p.Size())); } TEST_CASE("packet comparison") { ct::Packet p0{ testData.data(),testData.size() }; ct::Packet p1{ testData.data(),testData.size() }; REQUIRE(p0 == p1); char* raw = const_cast<char*>(p0.Data()); raw[2] = 'a'; REQUIRE(p0 != p1); } TEST_CASE("packet should deep copy") { ct::Packet p0{ testData.data(),testData.size() }; ct::Packet p1{ p0 }; char* raw = const_cast<char*>(p0.Data()); raw[2] = 'a'; REQUIRE(p0 != p1); REQUIRE(p1.Size() == testData.size()); REQUIRE(0 == memcmp(p1.Data(), testData.data(), p1.Size())); } TEST_CASE("packet should move rvalue") { ct::Packet p0{ testData.data(),testData.size() }; ct::Packet p1{ std::move(p0) }; REQUIRE(p0.Size() == 0); REQUIRE(p1.Size() == testData.size()); ct::Packet p2; p2 = std::move(p1); REQUIRE(p1.Size() == 0); REQUIRE(p2.Size() == testData.size()); }<file_sep>/tools/server.py import argparse from ct_common import execute, get_root_path, rmdir, cmake, build, install parser = argparse.ArgumentParser() parser.add_argument("--clean", help="clean before build", action="store_true") parser.add_argument("--config", help="configuration", default="debug") parser.add_argument("--ninja", help="build using ninja", action="store_true") parser.add_argument("--no-run", help="build only, not run", action="store_true") args = parser.parse_args() source_dir = get_root_path().joinpath("server") build_dir = get_root_path().joinpath("build/build_server") install_dir = get_root_path().joinpath(f"build/server/{args.config}") if args.clean: rmdir(build_dir) exit() cmake(source_dir, build_dir, args.ninja, install_dir) build(build_dir, args.config) install(build_dir, args.config) if args.no_run: exit() execute(str(install_dir.joinpath("bin/server"))) <file_sep>/common/fps.h #pragma once #include <chrono> namespace ct { class FPS { public: void fire() { count_++; auto now = std::chrono::high_resolution_clock::now(); auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_); if (dur > std::chrono::seconds{ 1 }) { fps_ = count_ * 1000.f / dur.count(); count_ = 0; last_ = std::chrono::high_resolution_clock::now(); } } float get() const { return fps_; } private: int fps_ = 0; int count_ = 0; std::chrono::high_resolution_clock::time_point last_; }; }<file_sep>/client_gui/CMakeLists.txt cmake_minimum_required(VERSION 3.19) project(client_gui) set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/../submodules/magnum/modules" ${CMAKE_MODULE_PATH}) set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/../submodules/magnum-integration/modules" ${CMAKE_MODULE_PATH}) SET(BUILD_STATIC ON CACHE BOOL "") set(IMGUI_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../submodules/imgui) SET(WITH_IMGUI ON CACHE BOOL "" FORCE) add_subdirectory(../submodules/corrade EXCLUDE_FROM_ALL corrade) add_subdirectory(../submodules/GLFW EXCLUDE_FROM_ALL glfw) SET(WITH_GLFWAPPLICATION ON CACHE BOOL "") add_subdirectory(../submodules/magnum EXCLUDE_FROM_ALL magnum) add_subdirectory(../submodules/magnum-integration EXCLUDE_FROM_ALL magnum-integration) find_package(GLFW REQUIRED) find_package(Corrade REQUIRED Main) find_package(Magnum REQUIRED GL Shaders MeshTools Primitives Shaders GlfwApplication ) find_package(MagnumIntegration REQUIRED ImGui) aux_source_directory(. source) aux_source_directory(../common source) add_executable(${PROJECT_NAME} ${source}) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STACK_SIZE 100000000) target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/asio/asio/include") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/eigen") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/ZSerializer") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/json/single_include") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/FastNoiseLite/Cpp") target_include_directories(${PROJECT_NAME} PUBLIC "../submodules/PhysX/physx/include") target_link_libraries(${PROJECT_NAME} PRIVATE GLFW::GLFW Corrade::Main Magnum::Application Magnum::GL Magnum::Magnum Magnum::MeshTools Magnum::Primitives Magnum::Shaders MagnumIntegration::ImGui) SET(CMAKE_USE_OPENSSL OFF CACHE BOOL "") include(FetchContent) FetchContent_Declare(cpr GIT_REPOSITORY https://github.com/whoshuu/cpr.git GIT_TAG c8d33915dbd88ad6c92b258869b03aba06587ff9) # the commit hash for 1.5.0 FetchContent_MakeAvailable(cpr) target_link_libraries(${PROJECT_NAME} PRIVATE cpr::cpr) #### Build PhysX library #### # PHYSX_PATH - path to the `{cloned repository}/physx` repo directory git://github.com/NVIDIAGameWorks/PhysX.git set( PHYSX_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../submodules/PhysX/physx ) set( PHYSX_ROOT_DIR ${PHYSX_PATH} ) #This is needed for $ENV{PHYSX_PATH}/compiler/public/CMakeLists.txt set( PHYSX_INCLUDE_DIRS ${PHYSX_PATH}/include/ ${PHYSX_PATH}/../pxshared/include/ ) set( PHYSX_LIBRARIES PhysXExtensions PhysX PhysXPvdSDK PhysXVehicle PhysXCharacterKinematic PhysXCooking PhysXCommon PhysXFoundation # SnippetUtils ) set(TARGET_BUILD_PLATFORM "windows") # has to match the TARGET_BUILD_PLATFORM in $ENV{PHYSX_PATH}/physix/buildtools/cmake_generate_projects.py set(PX_BUILDSNIPPETS OFF CACHE BOOL "Generate the snippets") set(PX_BUILDPUBLICSAMPLES OFF CACHE BOOL "Generate the samples projects") set(PX_GENERATE_STATIC_LIBRARIES ON CACHE BOOL "Generate static libraries") set(PX_FLOAT_POINT_PRECISE_MATH OFF CACHE BOOL "Float point precise math") set(NV_USE_STATIC_WINCRT ON CACHE BOOL "Use the statically linked windows CRT") set(NV_USE_DEBUG_WINCRT ON CACHE BOOL "Use the debug version of the CRT") set(PXSHARED_PATH ${PHYSX_PATH}/../pxshared) set(PXSHARED_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX}) set(CMAKEMODULES_VERSION "1.27") set(CMAKEMODULES_PATH ${PHYSX_PATH}/../externals/cmakemodules) set(PX_OUTPUT_LIB_DIR ${CMAKE_CURRENT_BINARY_DIR}/externals/physx) set(PX_OUTPUT_BIN_DIR ${CMAKE_CURRENT_BINARY_DIR}/externals/physx) # Call into PhysX's CMake scripts add_subdirectory(${PHYSX_PATH}/compiler/public externals/physx) # Add physx libraries to target target_link_libraries(${PROJECT_NAME} PUBLIC ${PHYSX_LIBRARIES}) install(TARGETS ${PROJECT_NAME})
4cce7dfa34e15ebbf640240d327dd4590c07e579
[ "CMake", "Markdown", "INI", "C#", "Python", "C++" ]
50
INI
ZhangFengze/CrazyTang
d96daf53c69ab71b53e4428764550553a527928a
ac8f12f83e7b5175604eb48ac035731e984054af
refs/heads/master
<repo_name>vscopise/caretas-2021<file_sep>/packages/caretas-2021-theme/src/components/index.js import React, { useEffect } from 'react'; import { connect, css, Global, Head, styled } from 'frontity'; import Switch from "@frontity/components/switch"; import Title from './title'; import Header from './header'; import Footer from './footer'; import Home from './home'; import Post from './post'; import List from './list'; import ImageModal from './image-modal' import oswaldMediumTTF from '../assets/fonts/Oswald-Medium.ttf'; import ptSerifBoldTTF from '../assets/fonts/PTSerif-Bold.ttf'; import ptSerifBoldItalicTTF from '../assets/fonts/PTSerif-BoldItalic.ttf'; import ptSerifItalicTTF from '../assets/fonts/PTSerif-Italic.ttf'; import ptSerifRegularTTF from '../assets/fonts/PTSerif-Regular.ttf'; import { mainCategories } from './utility/config'; const Theme = ({ state, actions }) => { useEffect(() => { const attachExtraDataToState = async () => { await Promise.all( Object.values(mainCategories).map( category => actions.source.fetch( `/category/${category}` ) ) ) }; attachExtraDataToState(); }); const data = state.source.get(state.router.link); return ( <> <Title /> <Head> <meta name="description" content={state.theme.description} /> <html lang="es" /> </Head> <Global styles={globalStyles} /> <Main> <Header /> {state.theme.isModalOpen && <ImageModal />} <Switch> <Home when={data.isHome} /> <Post when={data.isPostType} /> <List when={data.isArchive} /> </Switch> </Main> <Switch> <Footer when={!data.isPostType} /> </Switch> </> ); }; export default connect(Theme); const globalStyles = css` @font-face { font-family: "Oswald"; src: url(${oswaldMediumTTF}) format("truetype"); font-weight: 500; font-display: swap; } @font-face { font-family: "PT Serif"; src: url(${ptSerifBoldTTF}) format("truetype"); font-weight: 700; font-style: normal; font-display: swap; } @font-face { font-family: "PT Serif"; src: url(${ptSerifBoldItalicTTF}) format("truetype"); font-weight: 700; font-style: italic; font-display: swap; } @font-face { font-family: "PT Serif"; src: url(${ptSerifItalicTTF}) format("truetype"); font-weight: 400; font-style: italic; font-display: swap; } @font-face { font-family: "PT Serif"; src: url(${ptSerifRegularTTF}) format("truetype"); font-weight: 400; font-style: normal; font-display: swap; } *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body { margin: 0; padding: 0; font-size: 1.0rem; line-height: 1.6; background: #efefef; font-family: "PT Serif", sans-serif; } html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } h1, h2, h3, h4, h5, h6 { font-family: "Oswald", Helvetica, Arial, sans-serif; font-weight: 400; } img { max-width: 100%; height: auto; vertical-align: bottom; } a { text-decoration: none; color: inherit; & :hover { color: #d00000; } } `; const Main = styled.div` width: 90%; max-width: 1220px; min-height: 100vh; margin: 0 auto; padding: 0 20px 20px; overflow: hidden; background: #fff; `;<file_sep>/packages/caretas-2021-theme/src/components/utility/config.js /* export const mainCategories = { 7: 'politica', 43: 'sociedad', 67701: 'sindicales', 11: 'internacionales', 14: 'deportes', 44: 'economia-2', 50: 'cultura-y-espectaculos', 26: 'empresariales', 3238: 'caras-y-caretas-tv', } */ /* export const mainCategories = { 2: 'politica', 3: 'sociedad', 9: 'sindicales', 10: 'internacionales', 4: 'deportes', 11: 'economia-2', 12: 'cultura-y-espectaculos', 13: 'empresariales', 14: 'caras-y-caretas-tv', } */ export const mainCategories = { 11: 'politica', 12: 'sociedad', 13: 'sindicales', 14: 'internacionales', 15: 'deportes', 16: 'economia-2', 17: 'cultura-y-espectaculos', 18: 'empresariales', 19: 'caras-y-caretas-tv', }<file_sep>/packages/caretas-2021-theme/src/components/header/menu-header.js import React from 'react'; import { connect, styled } from 'frontity'; import Link from '../link'; import MegaMenu from './mega-menu'; import {HamburgerIcon, CloseIcon} from '../menu-icon'; import MenuModal from '../menu-modal'; const MenuHeader = ({ state, actions }) => { const hideMobileMenu = state.theme.isMobileMenuOpen ? null : 'hide-mobile-menu'; return ( <Container> <NavContainer hideMobileMenu> { state.theme.menu.map(item => { const isCat = item.link.split('/')[1] === 'categoria'; const catName = isCat ? item.link.split('/')[2] : ''; const showMegaMenu = state.theme.showMegaMenu && catName === state.theme.megaMenuCatName; return ( <NavItem key={item.name} onMouseEnter={isCat ? () => actions.theme.showMegaMenu(`${catName}`) : null} onMouseLeave={isCat ? actions.theme.hideMegaMenu : null} showMegaMenu={showMegaMenu} > <Link link={item.link}> {item.name} </Link> {showMegaMenu && <MegaMenu />} </NavItem> ) }) } </NavContainer> <ToggleMenu onClick={actions.theme.toggleMobileMenu}> {!state.theme.isMobileMenuOpen && <HamburgerIcon size={32} />} {state.theme.isMobileMenuOpen && <CloseIcon size={32} />} </ToggleMenu> </Container> ); } export default connect(MenuHeader); const Container = styled.div` background: #dd0008; text-transform: uppercase; font-family: "Oswald", Helvetica, sans-serif; position: relative; height: 44px; `; const NavContainer = styled.div` position: absolute; display: ${props => props.hideMobileMenu ? 'none': 'block'}; left: 0; top: 44px; width: 100%; z-index: 99; background: #dd0008; @media only screen and (min-width: 980px) { top: 0; display: block; } `; const NavItem = styled.span` float: none; & > a { color: #fff; display: block; position: relative; padding: 0.625rem 0.5rem; } & > a:hover { color: #ccc; } & a:after { content: ""; position: absolute; left: 50%; bottom: 0; margin-left: -12px; border-width: 0 12px 12px; border-style: solid; border-color: transparent transparent #222; display: ${props => props.showMegaMenu ? 'block' : 'none'}; width: 0; z-index: 999; } @media only screen and (min-width: 980px) { float: left; & > a { display: inline-block; } } `; const ToggleMenu = styled.div` position: absolute; right: 0; float: right; width: 10%; font-size: 1.5em; margin: 0 10px; color: #fff; & svg { height: 44px; } @media only screen and (min-width: 980px) { display: none; } `;<file_sep>/packages/caretas-2021-theme/src/components/utility/second-column.js import React from 'react'; import { styled } from 'frontity'; const SecondColumn = ({ children }) => { return ( <Container> {children} </Container> ); }; export default SecondColumn; const Container = styled.div` width: 100%; display: block; overflow: hidden; float: left; @media only screen and (min-width: 980px) { width: 31.66%; } `;<file_sep>/packages/caretas-2021-theme/src/components/sidebar.js import React from 'react'; import { styled } from 'frontity'; const Sidebar = () => { return ( <div>Sidebar</div> ); } export default Sidebar;<file_sep>/packages/caretas-2021-theme/src/assets/icons/loading.js import React from 'react'; import { styled, keyframes } from 'frontity'; const circleBounceDelay = keyframes` 0%, 80%, 100% {transform: scale(0)} 40% {transform: scale(1)} `; const Loading = ({size}) => ( <Container size={size}> <Child /> <Child item='2' /> <Child item='3' /> <Child item='4' /> <Child item='5' /> <Child item='6' /> <Child item='7' /> <Child item='8' /> <Child item='9' /> <Child item='10' /> <Child item='11' /> <Child item='12' /> </Container> ); export default Loading; const Container = styled.div` margin: ${props => props.size/2 - 20}px auto; width: 40px; height: 40px; position: relative; `; const Child = styled.div` width: 100%; height: 100%; position: absolute; left: 0; top: 0; -webkit-transform: ${props => props.item ? `rotate(${30 * (1 - props.item)}deg)` : 'unset'}; -ms-transform: ${props => props.item ? `rotate(${30 * (1 - props.item)}deg)` : 'unset'}; transform: ${props => props.item ? `rotate(${30 * (1 - props.item)}deg)` : 'unset'}; & :before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #333; border-radius: 100%; -webkit-animation: ${circleBounceDelay} 1.2s infinite ease-in-out both; animation: ${circleBounceDelay} 1.2s infinite ease-in-out both; -webkit-animation-delay: ${props => props.item ? `${0.1 * props.item - 1.3}s` : 'unset'}; animation-delay: ${props => props.item ? `${0.1 * props.item - 1.3}s` : 'unset'}; } `;<file_sep>/packages/caretas-2021-theme/src/components/list/list.js import React from 'react'; import { connect } from 'frontity'; const List = ({ state }) => { return ( <>List</> ); }; export default connect(List);<file_sep>/packages/caretas-2021-theme/src/components/utility/wrapper-inner.js import {styled} from 'frontity'; const WrapperInner = ({children}) => ( <Container> {children} </Container> ); export default WrapperInner; const Container = styled.div` width: 90%; max-width: 1180px; margin: 0 auto; `;<file_sep>/packages/caretas-2021-theme/src/assets/icons/loading-image.js import React from 'react'; import {styled, keyframes} from 'frontity'; const preloadAnimation = keyframes` from { background-position: -468px 0 } to { background-position: 468px 0 } `; const LoadingImage = ({size}) => ( <Container size={size} /> ); export default LoadingImage; const Container = styled.div` animation-duration: 2s; animation-fill-mode: forwards; animation-iteration-count: infinite; animation-name: ${preloadAnimation}; animation-timing-function: linear; background: #f6f7f8; background: linear-gradient(to right, #eeeeee 8%, #dddddd 18%, #eeeeee 33%); background-size: 1000px 104px; height: ${props => props.size}px; position: relative; overflow: hidden; `;<file_sep>/packages/caretas-2021-theme/src/components/header/sub-header.js import { styled } from 'frontity'; import NewsTicker from './news-ticker'; import SocialButtons from './social-buttons'; export const SubHeader = () => ( <Container> <NewsTicker /> <SocialButtons /> </Container> ); const Container = styled.div` padding: 10px; text-transform: uppercase; overflow: hidden; background: #efefef; font-family: 'Oswald',Helvetica,Arial,sans-serif; `;<file_sep>/packages/caretas-2021-theme/src/components/header/news-ticker.js import React, { useState, useEffect } from 'react'; import { connect, styled } from 'frontity'; import Link from '../link'; const NewsTicker = ({ state }) => { const [tickerItems] = useState( Object.keys(state.source.post).slice(0, 5) ); const [count, setcount] = useState(0); useEffect(() => { setInterval(() => { setcount(count => (5 > count + 1 ? count + 1 : 0)); }, 4000); }, []); const tickerItem = state.source.post[tickerItems[count]]; return ( <Container> <Title>Ultimas Noticias</Title> <TickerContent> <Link link={tickerItem.link}> {tickerItem.title.rendered} </Link> </TickerContent> </Container> ) } export default connect(NewsTicker); const Container = styled.div` display: none; @media only screen and (min-width: 980px) { float: left; height: 33px; font-size: 12px; line-height: 33px; width: 60%; display: block; } `; const Title = styled.span` background: #dd0000; color: #fff; padding: 5px 10px; margin-right: 10px; `; const TickerContent = styled.div` display: inline-grid; & a { color: #222; } `;<file_sep>/frontity.settings.js const settings = { "name": "caretas-2021", "state": { "frontity": { "url": "https://test.frontity.org", title: 'Caras & Caretas', "description": "WordPress installation for Frontity development" } }, "packages": [ { //"name": "@frontity/mars-theme", "name": "caretas-2021-theme", "state": { "theme": { "featured": { "showOnList": false, "showOnPost": false } } } }, { "name": "@frontity/wp-source", "state": { "source": { // categoryBase: 'categoria', //"url": "https://www.carasycaretas.com.uy" //"url": "https://creatable-vacuums.000webhostapp.com", url: 'http://wp.pixie.com.uy' //"api": "https://creatable-vacuums.000webhostapp.com" //"url": "https://test.frontity.org" } } }, "@frontity/tiny-router", "@frontity/html2react", "@frontity/wp-comments", { name: '@frontity/google-ad-manager', state: { fills: { googleAdManager: { beforeHeaderAd: { slot: 'top-header', library: 'googleAdManager.GooglePublisherTag', priority: 5, props: { id: 'top-header-ad', unit: '/90767959/banner_top_home', size: [728, 90] } } } } } } ] }; export default settings; <file_sep>/packages/caretas-2021-theme/src/components/post-block.js import React, { useEffect } from 'react'; import { connect, styled } from 'frontity'; import Link from './link'; import FeaturedMedia from './featured-media'; import WidgetTitle from './widget-title'; import { VideoIcon } from '../assets/icons/video-icon'; import Loading from '../assets/icons/loading'; const PostBlock = ({ postId, state, actions, title, size, padding, background, excerpt }) => { useEffect(() => { actions.source.fetch(`/post/${postId}`); }, []); const post = state.source.post[postId]; if (post) { const isVideo = post.format === 'video' && post.video !== ''; return ( <Container padding={padding} background={background}> <Link link={post.link}> {title && <WidgetTitle title={title} />} <ImageContainer > <Image size={size}> <FeaturedMedia id={post.featured_media} size={size} /> </Image> {isVideo && <Icon><VideoIcon size='28px' color='white' /></Icon>} </ImageContainer> <Title size={size} dangerouslySetInnerHTML={{ __html: post.title.rendered }} /> {excerpt && <Excerpt dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} />} </Link> </Container> ) } else { return (<Loading size={size}/>); } } export default connect(PostBlock); const Container = styled.div` padding: ${props => props.padding ? props.padding : 0}px; background: ${props => props.background ? props.background : '#ffffff'}; margin-bottom: 20px; `; const ImageContainer = styled.div` margin-bottom: 5px; position: relative; `; const Image = styled.div` & > div { height: 200px; } @media only screen and (min-width: 980px) { & > div { height: ${props => props.size}px; } } `; const Title = styled.h2` font-size: ${props => 10 + 0.05 * props.size}px; line-height: 1.3; `; const Excerpt = styled.div` padding-top: 10px; `; const Icon = styled.div` position: absolute; top: 10px; right: 10px; width: 24px; height: 24px; -webkit-transition: 0.43s cubic-bezier(0.47, 0.13, 0.16, 0.72) 0s; -moz-transition: 0.43s cubic-bezier(0.47, 0.13, 0.16, 0.72) 0s; -o-transition: 0.43s cubic-bezier(0.47, 0.13, 0.16, 0.72) 0s; transition: 0.43s cubic-bezier(0.47, 0.13, 0.16, 0.72) 0s; ${Container}:hover & { top: 50%; right: 50%; margin-top: -12px; margin-right: -12px; -webkit-transform: scale(1.5); -moz-transform: scale(1.5); transform: scale(1.5); -webkit-transition: 0.43s cubic-bezier(0.47, 0.13, 0.16, 0.72) 0s; -moz-transition: 0.43s cubic-bezier(0.47, 0.13, 0.16, 0.72) 0s; -o-transition: 0.43s cubic-bezier(0.47, 0.13, 0.16, 0.72) 0s; transition: 0.43s cubic-bezier(0.47, 0.13, 0.16, 0.72) 0s; } `;<file_sep>/packages/caretas-2021-theme/src/components/home/boton-edicion-impresa.js import React from 'react'; import { connect } from 'frontity'; const BotonEdicionImpresa = ({ state }) => { return ( <>Boton Edicion Impresa</> ); }; export default connect(BotonEdicionImpresa);<file_sep>/packages/caretas-2021-theme/src/components/home/index.js import React from 'react'; import HomeHeader from './home-header'; import BotonEdicionImpresa from './boton-edicion-impresa'; import ColumnasDeOpinion from './columnas-de-opinion'; import ImportantesEditorial from './importantes-editorial'; import MainContent from './main-content'; const Home = () => ( <> <HomeHeader /> <BotonEdicionImpresa /> <ColumnasDeOpinion /> <ImportantesEditorial /> <MainContent /> </> ); export default Home;<file_sep>/packages/caretas-2021-theme/src/components/title.js import React from 'react'; import { Head, connect } from 'frontity'; const Title = ({ state }) => { // Obtener datos sobre la URL actual. const data = state.source.get(state.router.link); // Establecer el título predeterminado. let title = state.theme.title; if (data.isTaxonomy) { // Agrego títulos a las taxonomías, como "Categoría: Naturaleza - Nombre del blog" o "Etiqueta: Japón - Nombre del blog". // 1. Obtengo la taxonomía del estado para obtener su término y nombre. const { taxonomy, name } = state.source[data.taxonomy][data.id]; // 2. Primera letra mayúscula del término de taxonomía (de "categoría" a "Categoría"). const taxonomyCapitalized = taxonomy.charAt(0).toUpperCase() + taxonomy.slice(1); // 3. Renderizo el título correctamente compuesto. title = `${taxonomyCapitalized}: ${name} - ${state.frontity.title}`; } else if (data.isAuthor) { // Agrego títulos a los autores, como "Autor: <NAME> - Nombre del blog". // 1. Obtengo el autor del estado para obtener su nombre. const { name } = state.source.author[data.id]; // 2. Renderizo el título correctamente compuesto. title = `Author: ${name} - ${state.frontity.title}`; } else if (data.isPostType) { // Agrego títulos a publicaciones y páginas, utilizando el título y terminando con el nombre del blog. // 1. Obtengo la publicación del estado y obtengo su título. const postTitle = state.source[data.type][data.id].title.rendered; // 2. Elimino las etiquetas HTML del título. const cleanTitle = postTitle.replace(/<\/?[^>]+(>|$)/g, ""); // 3. Renderizo el título correcto. title = `${cleanTitle} - ${state.frontity.title}`; } else if (data.is404) { // Añado títulos a 404's. title = `404 No Encontrado - ${state.frontity.title}`; } return ( <Head> <title>{title}</title> </Head> ); }; export default connect(Title);<file_sep>/packages/caretas-2021-theme/src/components/header/mega-menu.js import React from 'react'; import { connect, styled } from 'frontity'; import Link from "../link"; import { getPostsGroupedByCategory } from '../utility/'; import { animated, useSpring } from 'react-spring'; import FeaturedMedia from '../featured-media'; const MegaMenu = ({ state }) => { const postsPerCategory = getPostsGroupedByCategory(state); const categoryPosts = postsPerCategory.filter(item => item.category.slug === state.theme.megaMenuCatName)[0]; const settings = { position: 'absolute', left: '0', color: '#fff', background: '#222', width: '100%', padding: '20px 0', zIndex: '99', } const animateStyle = useSpring({ opacity: '1', from: { ...settings, opacity: '0' } }); return ( <animated.div style={animateStyle}> <Row> { categoryPosts.posts.splice(0,4).map(post => ( <BoxCategory key={post.id}> <Link link={post.link}> <ImageContainer> <FeaturedMedia id={post.featured_media} /> </ImageContainer> <PostTitle dangerouslySetInnerHTML={{ __html: post.title.rendered }} /> </Link> </BoxCategory> )) } </Row> </animated.div> ); }; export default connect(MegaMenu); const Row = styled.div` padding: 0 10px; `; const PostTitle = styled.h3` text-transform: none; `; const BoxCategory = styled.div` display: inline-grid; width: 23.125%; margin-left: 2.5%; & :first-of-type { margin-left: 0; } & a { color: #fff; } `; const ImageContainer = styled.div` & > div { height: 150px; } `;<file_sep>/packages/caretas-2021-theme/src/components/post/comments.js import React, { useEffect } from 'react'; import { styled, connect } from 'frontity'; import post from '.'; const Comments = ({ state, actions, postId }) => { useEffect(() => { actions.source.fetch(`@comments/${postId}`); }, []); const data = state.source.get(`@comments/${postId}`); return ( data.isReady && <> <div>CommentForm</div> <div>Comments</div> </> ); } export default connect(Comments);<file_sep>/packages/caretas-2021-theme/src/assets/icons/video-icon.js import React from 'react'; export const VideoIcon = ({ size, color }) => ( <svg height={size} width={size} viewBox="0 0 24 24" color={color} xmlns="http://www.w3.org/2000/svg" > <title>Video</title> <g fill='currentColor'> <path d="M12,0.3C5.5,0.3,0.3,5.5,0.3,12S5.5,23.8,12,23.8S23.8,18.5,23.8,12S18.5,0.3,12,0.3z M17.3,12.9L10,17.8 C9.3,18.3,8.6,18,8.6,17V7C8.6,6,9.3,5.7,10,6.2l7.3,4.9C18.1,11.6,18.1,12.4,17.3,12.9z"/> </g> </svg> ); <file_sep>/packages/caretas-2021-theme/src/components/home/destacadas-media.js import React from 'react'; import { connect, styled } from 'frontity'; import Clearfix from '../utility/clearfix'; import PostBlock from '../post-block'; import { getPostsFromCategory } from '../utility/'; import HomeImageGallery from './home-image-gallery'; const DestacadasMedia = ({ state }) => { const data = state.source.get(state.router.link); const videoPost = getPostsFromCategory( state.source, data.homeData.cat_videos ).sort((a, b) => a.date < b.date ? 1 : -1)[0]; return ( <Container> <Clearfix> <Column first> <PostBlock postId={data.homeData.zones[3][0]} title='Noticia destacada' size='200' /> <PostBlock postId={videoPost.id} title='Videos' size='200' /> </Column> <Column> <PostBlock postId={data.homeData.zones[4][0]} title='Noticia destacada' size='200' /> <HomeImageGallery items={data.homeData.img_gallery_items} title={data.homeData.img_gallery_title} size='200' /> </Column> </Clearfix> </Container> ); } export default connect(DestacadasMedia); const Container = styled.div` margin-bottom: 20px; @media only screen and (min-width: 980px) { margin-bottom: 48px; } `; const Column = styled.div` @media only screen and (min-width: 980px) { float: left; width: 49%; margin-left: ${props => props.first ? '0' : '2'}%; } `;<file_sep>/packages/caretas-2021-theme/src/components/utility/wrapper.js import {styled} from 'frontity'; import Clearfix from './clearfix'; const Wrapper = ({children, padding}) => ( <Container p={padding}> <Clearfix> {children} </Clearfix> </Container> ); export default Wrapper; const Container = styled.div` padding: ${props => props.p}; &:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; margin: 0; padding: 0; } margin-bottom: 20px; @media only screen and (min-width: 980px) { margin-bottom: 48px; } `;<file_sep>/packages/caretas-2021-theme/src/components/home/grid-category.js import React from 'react'; import { connect, styled } from 'frontity'; import WidgetTitle from '../widget-title'; import PostBlock from '../post-block'; import { getPostsGroupedByCategory } from '../utility/'; const GridCategory = ({ state, category, excerpt, right }) => { const postsPerCategory = getPostsGroupedByCategory(state, 5); const categoryPosts = postsPerCategory.filter(item => item.category.slug === category)[0]; const categoryName = state.source.category[ Object.keys(state.source.category).find( item => state.source.category[item].slug === category ) ].name; return ( <Container> <WidgetTitle title={categoryName} /> <Column first> <PostBlock postId={categoryPosts.posts.slice(0, 1)[0].id} size='200' excerpt /> </Column> <Column> {categoryPosts.posts.slice(1, 5).map((post, index) => { return ( <Item key={index} index={index}> <PostBlock postId={post.id} size='100' /> </Item> ); })} </Column> </Container> ); }; export default connect(GridCategory); const Container = styled.div` @media only screen and (min-width: 980px) { float: left; margin-bottom: 48px; } ` const Column = styled.div` @media only screen and (min-width: 980px) { float: ${props => props.right ? 'right' : 'left'}; width: 49%; margin-left: ${props => props.first ? '0' : '2'}%; } `; const Item = styled.div` @media only screen and (min-width: 980px) { width: 50%; display: inline-grid; padding-right: ${props => props.index % 2 === 0 ? '10' : '0'}px; } `;<file_sep>/packages/caretas-2021-theme/src/components/post/index.js import React from 'react'; import { styled, connect } from 'frontity'; import { SocialIcon } from 'react-social-icons'; import FeaturedMedia from '../featured-media'; import Comments from './comments'; import Sidebar from '../sidebar'; const Post = ({ state, actions, libraries }) => { const data = state.source.get(state.router.link); const post = state.source[data.type][data.id]; const options = { year: 'numeric', month: 'long', day: 'numeric' }; const date = new Date(post.date).toLocaleDateString('es-ES', options); const author = state.source.author[post.author]; const Html2React = libraries.html2react.Component; return data.isReady ? ( <> <Main> <Title dangerouslySetInnerHTML={{ __html: post.title.rendered }} /> <Excerpt dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} /> <Featured> <FeaturedMedia id={post.featured_media} size={437} /> </Featured> <EntryMeta> Por: {author.name} - {date} { state.theme.socialShare.map( network => <Icon url={network.url + state.frontity.url + state.router.link} network={network.id} key={network.id} style={{ height: 20, width: 20 }} /> ) } </EntryMeta> <Content> <Html2React html={post.content.rendered} /> </Content> <Comments postId={post.id} /> </Main> <Side /> </> ) : null; }; export default connect(Post); const Title = styled.h1` @media only screen and (min-width: 980px) { font-size: 35px; margin-bottom: 20px; } `; const Featured = styled.div` margin-bottom: 20px; `; const Excerpt = styled.div` border-top: 1px solid #888; border-bottom: 1px solid #888; padding: 8px 0 10px; margin: 15px 0; & p { font-size: 20px; } `; const Icon = styled(SocialIcon)` margin-left: 5px; `; const EntryMeta = styled.div` text-transform: uppercase; border-bottom: 1px solid #888; margin-bottom: 15px; padding-bottom: 15px; font-size: 0.75rem; `; const Main = styled.div` float: left; width: 100%; @media only screen and (min-width: 980px) { width: 65.83%; margin-right: 2.5%; } `; const Side = styled(Sidebar)` float: left; width: 100%; @media only screen and (min-width: 980px) { width: 31.66%; } `; const Content = styled.div` p { font-size: 19px; margin-bottom: 20px; } `;<file_sep>/packages/caretas-2021-theme/src/components/home/home-image-gallery.js import React, { useState, useEffect } from 'react'; import { styled, connect } from 'frontity'; import { useTransition, animated, config } from 'react-spring'; import WidgetTitle from '../widget-title'; const Slides = ({ state, actions, items }) => { const [count, setcount] = useState(0); const transitions = useTransition(items[count], item => item, { from: { opacity: 0 }, enter: { opacity: 1 }, leave: { opacity: 0 }, config: config.molasses, }) useEffect(() => void setInterval(() => setcount(count => (count + 1) % 4), 4000), []); return transitions.map(({ item, props, key }) => ( <animated.div onClick={() => actions.theme.toggleModal(item)} key={key} style={{ ...props, backgroundImage: `url(${state.source.attachment[item].source_url})` }} /> )) } const HomeImageGallery = ({ state, actions, items, title, size }) => { return ( <Container> <WidgetTitle title='Galería de fotos' /> <SlidesContainer> <Slides state={state} actions={actions} items={items} /> </SlidesContainer> <Title size={size} dangerouslySetInnerHTML={{ __html: title }} /> </Container> ) } export default connect(HomeImageGallery); const Container = styled.div` margin-bottom: 20px; `; const Title = styled.h2` font-size: ${props => 10 + 0.05 * props.size}px; line-height: 1.3; `; const SlidesContainer = styled.div` position: relative; height: 200px; margin-bottom: 5px; & > div { position: absolute; top: 0; left: 0; width: 100%; height: 200px; background-size: cover; background-position: center; will-change: opacity; display: flex; justify-content: center; align-items: center; } `; const Modal = styled.div` position: absolute; top: 0; left: 0; right: 0; bottom: 0; display: flex; align-items: center; justify-content: center; z-index: 2000; `;<file_sep>/build/bundling/entry-points/server.ts import server from "@frontity/core/src/server"; import caretas_2021_theme_default from "caretas-2021-theme/src/index"; import frontity__wp_source_default from "@frontity/wp-source/src/index"; import frontity__tiny_router_default from "@frontity/tiny-router/src/index"; import frontity__html2react_default from "@frontity/html2react/src/index"; import frontity__wp_comments_default from "@frontity/wp-comments/src/index"; import frontity__google_ad_manager_default from "@frontity/google-ad-manager/src/index"; const packages = { caretas_2021_theme_default, frontity__wp_source_default, frontity__tiny_router_default, frontity__html2react_default, frontity__wp_comments_default, frontity__google_ad_manager_default, }; export default server({ packages }); <file_sep>/packages/caretas-2021-theme/src/components/widget-title.js import React from 'react'; import {styled} from 'frontity'; const WidgetTitle = ({title}) => ( <Container> <ContainerInner>{title}</ContainerInner> </Container> ) export default WidgetTitle; const Container = styled.h4` padding: 0; margin-bottom: 20px; margin: 0 0 15px; font-size: 14px; line-height: 14px; position: relative; text-transform: uppercase; & :after { top: inherit; bottom: 0; height: 2px; margin-top: 0; background-color: #dd0000; content: ''; display: inline-block; position: absolute; left: 0; width: 100%; } `; const ContainerInner = styled.span` padding: 0 10px; background: #dd0000; line-height: 24px; color: #fff; border-radius: 5px 5px 0 0; `;<file_sep>/packages/caretas-2021-theme/src/components/header/main-logo.js import React from 'react'; import { styled } from 'frontity'; import Image from "@frontity/components/image"; import Link from '../link'; import Logo from '../../assets/images/logo_caras.png'; const MainLogo = () => { const options = { year: 'numeric', month: 'long', day: 'numeric' }; const date = new Date().toLocaleDateString('es-ES', options); const localDate = `Montevideo, ${date}`; return ( <> <Link link='/'> <StyledLogo src={Logo} /> </Link> <StyledDate>{localDate}</StyledDate> </> ); } export default MainLogo; const StyledLogo = styled(Image)` margin: 10px auto; `; const StyledDate = styled.h6` text-align: center; color: #a6a6a6; font-size: 0.9em; padding-top: 15px; `;<file_sep>/packages/caretas-2021-theme/src/components/utility/clearfix.js import {styled} from 'frontity'; const Clearfix = ({children, padding}) => ( <Container p={padding}> {children} </Container> ); export default Clearfix; const Container = styled.div` padding: ${props => props.p}; &:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; margin: 0; padding: 0; } `;<file_sep>/packages/caretas-2021-theme/src/components/header/index.js import React from 'react'; import { connect, styled } from 'frontity'; import Clearfix from '../utility/clearfix'; import MainLogo from './main-logo'; import AdSlot from '../ad-slot'; import MenuHeader from './menu-header'; import { SubHeader } from './sub-header'; const Header = () => ( <Container> <Clearfix padding={'20px 0'}> <HeaderLogo> <MainLogo /> </HeaderLogo> <HeaderAd> <AdSlot name='top-header' /> </HeaderAd> </Clearfix> <Clearfix> <MenuHeader /> </Clearfix> <Clearfix> <SubHeader /> </Clearfix> </Container> ); export default connect(Header); const Container = styled.div` margin-bottom: 30px; `; const HeaderLogo = styled.div` display: inline-block; vertical-align: middle; width: 27%; @media (max-width: 980px) { text-align: center; width: 100%; } `; const HeaderAd = styled.div` display: inline-block; vertical-align: middle; width: 71.83%; margin-left: 0.5%; float: right; @media (max-width: 980px) { text-align: center; width: 100%; } `;
0f63d4a607c32b6d52ca1f4a3ace21cbe4652d68
[ "JavaScript", "TypeScript" ]
29
JavaScript
vscopise/caretas-2021
6e6ee28e094b42d61efd1d754b0cbb51091d76be
ba4f5ec36c7efc7b3e01a3a1632c0f9b624c1488
refs/heads/master
<file_sep>from gdb import * #USAGE: reload(vault_solver).VaultSolver(x()).solve() START = 2623 FINISH = 2578 FINISH_VALUE = 30 def is_op(symbol): return symbol in ['-', '+', '*'] def apply_op(a, op, b): if op == '-': return a - b if op == '+': return a + b if op == '*': return a * b assert False, op class State: def __init__(self, location, path, value, op=None): self.path = path self.location = location self.value = value self.op = op class VaultSolver: def __init__(self, gdb): locations = gdb.get_vault_info() self.map = {} for l in locations: self.map[ l.pos ] = l def print_solution(self, solution): now = self.map[START] output = [22] for move in solution: print now.pos, output next_pos = now.exits[move] now = self.map[next_pos] output += [now.symbol] print now.pos, output def solve(self): start_location = self.map[START] now = [ State(start_location, [], start_location.symbol) ] depth = 15 for i in xrange(depth): next = [] print 'depth = {}, len = {}'.format( i, len(now) ) for state in now: location = state.location # print '(depth = {}): pos = {}, value = {}'.format( # i, # location.pos, # state.value, # ) if location.pos == FINISH: if state.value == FINISH_VALUE: print state.path continue else: continue # print location for move, next_pos in location.exits.items(): if next_pos == START: continue next_location = self.map.get(next_pos, None) if next_location is None: continue if state.op is None: assert is_op(next_location.symbol), next_location.symbol next.append( State( next_location, state.path + [move], state.value, next_location.symbol)) else: assert is_op(state.op), state.op assert not is_op(next_location.symbol), next_location.symbol next_value = apply_op(state.value, state.op, next_location.symbol) next.append( State( next_location, state.path + [move], next_value)) now = next <file_sep>from util import * from ops import * import re from itertools import permutations def unhash(code, seed): # r1: seed # 2125| ;;; # 2129| and r2 r0 r1 # 2133| not r2 r2 # 2136| or r0 r0 r1 # 2140| and r0 r0 r2 r2 = code & seed r2 = inverse(r2) code = code | seed code = code & r2 return code # movement solutions def take_lantern_and_go_to_ladder(): s = ['doorway', 'north', 'north', 'bridge', 'continue', 'down', 'east', 'take empty lantern', 'west', 'west', 'passage', 'ladder'] return s def go_to_door_from_ladder(): # assume starts in ladder s = ['ladder'] # go back s += ['darkness', 'continue', 'west', 'west', 'west', 'west', 'north', 'north'] return s def take_can_in_maze(): # assume starts in ladder s = ['west', 'south', 'north', 'take can', 'west'] return s def light_lantern(): s = ['use can', 'use lantern'] return s def gather_coins(): # assume start at door s = ['south', 'take red coin', 'north', 'east', 'take concave coin', 'down', 'take corroded coin', 'up', 'west', 'west', 'take blue coin', 'up', 'take shiny coin', 'down', 'east'] return s def solve_door(): # 9 + 2 * 5^2 + 7^3 - 3 = 399 s = ['use blue coin', 'use red coin', 'use shiny coin', 'use concave coin', 'use corroded coin'] return s def take_and_use_teleport(): # assumes start at door s = ['north', 'take teleporter', 'use teleporter'] return s def go_to_antechamber(): # assume starts at island s = ['west', 'north', 'east', 'north', 'north', 'north', 'north', 'north', 'north', 'north', 'north'] return s def solution_to_vault(): s = ['north', 'east', 'east', 'north', 'west', 'south', 'east', 'east', 'west', 'north', 'north', 'east'] return s def solve_vault(): return ['take orb'] + solution_to_vault() def enter_vault_and_get_mirror(): return ['vault', 'take mirror', 'use mirror'] class FindResult: def __init__(self, pos, context): self.pos = pos self.context = context self.info = ' (??)' class LocationInfo: def __init__(self, pos, name, desc, exits): self.pos = pos self.name = name self.desc = desc self.exits = {} for move, next_pos in exits: self.exits[move] = next_pos self.symbol = None # print 'Creating info for ', repr(self) ss = self.symbol_impl() if ss in ['+', '-', '*']: self.symbol = ss else: self.symbol = int(ss) def __repr__(self): return 'LocationInfo({}):\nname = {}\ndesc = {}\nsymbol = {}\nexits = {}'.format( self.pos, self.name, self.desc, self.symbol, self.exits ) def symbol_impl(self): re1 = "the number '(.*?)'" re2 = "depicting a '(.*)' symbol" m1 = re.search(re1, self.desc) m2 = re.search(re2, self.desc) if m1 is not None: return m1.group(1) elif m2 is not None: return m2.group(1) else: return None # limit on textual output of memory fields LOC_LIMIT = 300 ITEM_LIMIT = 100 PRINT_LIMIT = 300 class GDB: def __init__(self, vm): self.vm = vm self.annotations = [''] * MEMSIZE self.funcs = [None] * MEMSIZE def go(self): self.vm.return_on_input = False self.vm.run() def find_begin(self, pos): F_LIMIT = 1000 start = max(0, pos - F_LIMIT) begin = pos for i in xrange(start, pos): # 'ret' if self.vm.memory[i] == 18: begin = i return begin def analyze(self): good, bad = self.filter_by_pattern_1458() for find_result in good: start = self.find_begin(find_result.pos) self.annotations[find_result.pos] = find_result.info for i in xrange(start, find_result.pos + 1): # print 'Added ', find_result.info, 'at ', i self.funcs[i] = find_result.info # CODE_END = 6067 # now = 0 # while now < CODE_END: # op = self.vm.read_op(now) # if op.name == 'call': # addr = self.vm[now + 1] # if addr < CODE_END and self.funcs[addr] != '': def read_raw_string(self, r0, limit=None): m = self.vm.memory output = '' length = m[r0] if limit is not None: length = min(limit, length) for i in xrange(length): code = m[r0 + 1 + i] if code <= 128: output += chr(code) else: output += '?' return output def read_string(self, r0, r1, r2): hashing = False if r1 == 1531: hashing = True m = self.vm.memory output = '' length = m[r0] for i in xrange(length): code = m[r0 + 1 + i] if hashing: output += chr(unhash(code, r2)) else: output += chr(code) return output def try_read_string(self, offset, limit=1000): output = '' m = self.vm.memory for i in xrange(limit): if offset + i >= len(m): break code = m[offset + i] if 32 <= code <= 128: output += chr(code) elif code == 10: output += '\\n' else: output += 'chr({}) '.format(code) return output def find_calls(self, addr): result = [] m = self.vm.memory ln = len(m) for i in xrange(ln): if i + 1 < ln: a, b = m[i: i + 2] # call addr if (a, b) == (17, addr): result.append(i) return result def try_match_pattern(self, pos, pattern, values): vm = self.vm m = vm.memory ok = True start = pos - len(pattern) for i in xrange(len(pattern)): if pattern[i].startswith('>'): if m[start + i] >= MAX_VALUE: ok = False break values[ pattern[i][1:] ] = m[start + i] elif m[start + i] != to_opcode(pattern[i]): ok = False break return ok def next(self): self.vm.execute_one_op(ignore_break=True) def up(self): self.depth = 0 self.vm.stop_on_return = True self.vm.run() self.vm.stop_on_return = False def try_match_1518(self, pos): pattern = [ 'set', 'r0', '>A', ] values = {} ok = self.try_match_pattern(pos, pattern, values) if ok: context = {} context['r0'] = values['A'] find_result = FindResult(pos, context) c = context s = self.read_raw_string(c['r0']) find_result.info = ' // print "{}"'.format( s[:PRINT_LIMIT].replace('\n', '\\n') ) return find_result return None def try_match_1458_r1_1531(self, pos): pattern = [ 'set', 'r0', '>A', 'set', 'r1', '>B', 'add', 'r2', '>C', '>D', ] values = {} ok = self.try_match_pattern(pos, pattern, values) if ok: context = {} context['r0'] = values['A'] context['r1'] = values['B'] context['r2'] = values['C'] + values['D'] find_result = FindResult(pos, context) c = context s = self.read_string(c['r0'], c['r1'], c['r2']) find_result.info = ' // print "{}"'.format( s[:100].replace('\n', '\\n') ) return find_result return None def filter_by_pattern_1458(self): pts = self.find_calls(1458) results = [] not_matched = [] for pos in pts: values = {} find_result = self.try_match_1458_r1_1531(pos) if find_result is not None: results.append(find_result) else: not_matched.append(pos) return results, not_matched def run_seq(self, s, show_output=False): self.vm.buffer += '\n'.join(s) + '\n' if show_output: self.vm.run() else: self.vm.disable_output = True self.vm.run() self.vm.disable_output = False def solution(self): def do(f, show_output=False): print 'Executing', f.__name__ s = f() self.run_seq(s, show_output) do( take_lantern_and_go_to_ladder ) do( take_can_in_maze ) do( light_lantern ) do( go_to_door_from_ladder ) do( gather_coins ) do( solve_door ) do( take_and_use_teleport ) # set right amount of energy and teleport again self.vm.r[7] = 25734 do( lambda : ['use teleporter'] ) do( go_to_antechamber ) do( solve_vault, show_output=True) do( enter_vault_and_get_mirror, show_output=True) def get_all_items(self): pos = 2668 while pos <= 2728: self.vm.memory[pos + 2] = 0 pos += 4 def read_location_desc(self, offset): code = self.vm.memory[offset] max_length = self.vm.memory[code] length = min(max_length, LOC_LIMIT) s = self.try_read_string(code + 1, limit=length) return s def get_vault_info(self): locations = [] for pos in xrange(2563, 2643, 5): locations.append( self.get_location_info(pos) ) return locations def get_location_info(self, pos): name = self.read_location_desc(pos) desc = self.read_location_desc(pos + 1) exits = [] exits_str_code = self.vm.memory[pos + 2] # 26900 <-- code exits_pos_code = self.vm.memory[pos + 3] num_exits = self.vm.memory[exits_str_code] for i in xrange(num_exits): exit_str_addr = self.vm.memory[exits_str_code + 1 + i] exit_str = self.read_raw_string(exit_str_addr, limit=20) exit_pos = self.vm.memory[exits_pos_code + 1 + i] exits.append( (exit_str, exit_pos) ) return LocationInfo(pos, name, desc, exits) def mark_location(self, offset, counter): addr = self.vm.memory[offset] s = str(counter) if len(s) < 2: s = '0' + s self.vm.memory[addr + 1] = ord(s[0]) self.vm.memory[addr + 2] = ord(s[1]) self.vm.memory[addr + 3] = ord('_') def mark_locations(self): counter = 0 ranges = \ range(2317, 2460, 5) + \ range(2463, 2658, 5) for i in ranges: self.mark_location(i, counter) counter += 1 def try_read_items(self, offset, code): # description of locations if 2317 <= offset < 2668: if offset < 2463: delta = (offset - 2317) % 5 else: delta = (offset - 2468) % 5 if delta in [0, 1]: s = self.read_location_desc(offset) max_length = self.vm.memory[code] if len(s) >= LOC_LIMIT: dots = '... {}'.format(max_length - LOC_LIMIT) else: dots = '' s = s.replace('\n', '\\n') if delta == 1: dd = '[raw_string]' if delta == 0: dd = '__________' return ' // {} "{}{}"'.format(dd, s, dots) if delta in [2, 3]: code = self.vm.memory[offset] # 26900 <-- code num_exits = self.vm.memory[code] if delta == 2: # 26900| push 6336 # 26902| unknown (6344) exits = [] for i in xrange( min(num_exits, 5) ): exit_str_addr = self.vm.memory[code + 1 + i] s = self.read_raw_string(exit_str_addr, limit=20) exits.append(s) return ' // num exits {}: {}'.format( num_exits, ', '.join(exits)) if delta == 3: exits = [] for i in xrange( min(num_exits, 5) ): loc_offset = self.vm.memory[code + 1 + i] s = self.read_location_desc(loc_offset) exits.append('"' + s + '"') return ' // locations {}: {}'.format( num_exits, ', '.join(exits)) # description of items if 2668 <= offset < 2732: delta = (offset - 2668) % 4 # 0, 1: description if (delta in [0, 1]): s = self.read_raw_string(code) if len(s) >= ITEM_LIMIT: dots = '... {}'.format(len(s) - ITEM_LIMIT) else: dots = '' s = s[:ITEM_LIMIT].replace('\n', '\\n') return ' // desc: "{}{}"'.format( s, dots) # 3: location of item # 0 means inventory # X means room X if delta == 2: if code == 0: return '// loc: inventory' if code == 32767: return '// loc: ???' loc_offset = code s = self.read_location_desc(loc_offset) return ' // loc: "{}"'.format( s ) return '' def interpret_op(self, op, offset): data = op.name m = self.vm.memory if op.name == 'unknown': code = m[offset] data += ' ({})'.format( code, ) if 32 < code < 128: data += ' | ' + chr(code) data += self.try_read_items(offset, code) return data for i in xrange(op.arity): value = m[offset + 1 + i] mem_value = read_memory(value) if op.name == 'out': if value < 256: data += ' {} ({})'.format( chr(value), value, ) else: data += ' ({})'.format( mem_value ) continue data += ' ' + mem_value if op.name == 'call': addr = m[offset + 1] if addr < MEMSIZE: info = self.funcs[addr] if info is not None: data += info # if self.funcs[offset] is not None: # data += ' | ann: {} |'.format( # len(self.funcs[offset]) # ) if op.name == 'call': addr = m[offset + 1] if addr == 2125: data += ' // unhash(r0, r1)' if addr == 1518: find_result = self.try_match_1518(offset) if find_result is not None: data += find_result.info else: data += ' // print_string( m[r0] )' if addr == 5814: data += ' // print_stirng("- m[r0] \\n") ' if addr == 1458: find_result = self.try_match_1458_r1_1531(offset) if find_result is not None: c = find_result.context data += find_result.info else: data += ' // for loop ' if op.name == 'set': addr = m[offset + 2] # address in memory where list of items start if addr == 27381: data += ' // addr: list<items> (16) ' return data def disasm_to_file(self, file_name): f = open(file_name, 'wt') output = self.disasm(0, None) f.write(output) f.close() def try_coins(self): coins = [ 'red coin', 'corroded coin', 'shiny coin', 'concave coin', 'blue coin', ] counter = 0 self.vm.return_on_input = True for cc in permutations(coins): self.get_all_items() seq = '' for c in cc: seq += 'use ' + c + '\n' counter += 1 print counter, seq.replace('\n', '\\n') if counter == 100: # self.vm.disable_output = True self.vm.set_input(seq) self.vm.run() # self.vm.disable_output = False self.vm.set_input('look\n') self.vm.run() def disasm(self, offset, limit=14): output = '' n = 0 start_offset = offset offset = max(0, offset - 6) while offset < len(self.vm.memory): n += 1 if limit is not None and n > limit: break jump, data = self.vm.try_read_out(offset) if not jump: op = self.vm.read_op(offset) jump = op.size() mem = self.vm.memory[offset : offset + op.size()] data = self.interpret_op(op, offset) # f.write("{:6}|{:>40} | {}\n".format( # offset, # ", ".join(map(str, mem)), # data, # )) cursor = ' ' if offset == start_offset: cursor = '>' output += "{}{:6}| {}\n".format( cursor, offset, # ", ".join(map(str, mem)), data, ) offset += jump return output <file_sep>from util import * def f2125(r0, r2): x = r0 & r2 x = inverse(x) r0 = r0 | r2 r0 = r0 & x return x <file_sep># 6027: f(A, B, C) # r0 = A # r1 = B # r7 = C --> parameter of algo # 1) A == 0: # f(0, B) = B + 1 # 2) A > 0 # 1) B == 0: # f(A, 0) = f(A - 1, C) # 2) B > 0: # f(A, B) = f(A - 1, f(A, B - 1)) # # Observation: # f(a, b, c) = X + 1, X # So we need to compute only first # # # a = 0: # f(0, b) = 1 + b # # a = 1: # b == 0 # f(1, 0) = f(0, c) = c + 1 # b > 0 # f(1, b - 1) = b + c # f(0, b + c) = b + c + 1 # >> f(1, b) = c + 1 + b # # a = 2: # b == 0 # f(2, 0) = f(1, c) = c + (1) + c = 2c + 1 = 2c + 1 # b == 1 # f(2, 1) = f(1, f(2, 0)) = f(1, 2c + 1) = c + (1) + (2c + 1) = 3c + 2 # f(2, 2) = f(1, f(2, 1)) = f(1, 3c + 2) = c + (1) + (3c + 2) = 4c + 3 # >> f(2, b) = 2c + 1 + (c + 1) * b # # a = 3: # b == 0 # f(3, 0) = f(2, c) = 2c + 1 + (c + 1) * c = [1, 3, 1] # b == 1 # f(3, 1) = f(2, f(3, 0)) = f(2, [1, 3, 1] = b ) = 2c + 1 + (c + 1) * [1, 3, 1] = # = [0, 2, 1] + [1, 3, 1, 0] + [1, 3, 1] = [1, 4, 6, 2] # f(3, 2) = f(2, f(3, 1)) = f(2, [2, 6, 5] ) = ... # Polynomial approach # Essentially we need to represent f(A, B) = polynomial from B, C and relaclulate # from previous values # r7 = C --> parameter of algo # 1) A == 0: # f(0, B) = B + 1 # 2) A > 0 # 1) B == 0: # f(A, 0) = f(A - 1, C) # 2) B > 0: # f(A, B) = f(A - 1, f(A, B - 1)) MOD = 32768 MAX_VALUE = 32768 CACHE = {} def mod(a): return ((a % MOD + MOD) % MOD) F_CACHE = {} def compute(start, end, dp, c): for i in xrange(start, end): dp[i] = mod( dp[i - 1] * (c + 1) + 1 + 2 * c ) # return computed hash for this value of register def compute_c(c): dp = [None] * MAX_VALUE dp[0] = f_wrapper(2, c, c) compute(1, c + 1, dp, c) value = dp[c] if value <= c: return dp[ value ] # print 'dp[ {} ] = {}'.format(c, value) compute(c + 1, value + 1, dp, c) return dp[ value ] def find_good(): for c in xrange(1, MAX_VALUE): res = compute_c(c) print 'Trying ', c, ' --> ', res if res == 6: print 'Found good: ', c return def prefill(c): if c in F_CACHE: return # here assumes a = 3 print 'Prefilling cache for', c dp = [0] * MAX_VALUE dp[0] = f_wrapper(2, c, c) for i in xrange(1, MAX_VALUE): dp[i] = mod( dp[i - 1] * (c + 1) + 1 + 2 * c ) F_CACHE[c] = dp def f4_1(c): prefill(c) dp = F_CACHE[c] return dp[ dp[c] ] def f_wrapper(a, b, c): return f_fast(a, b, c)[0] def f_fast(a, b, c): if a == 0: return mod(b + 1), True if a == 1: return mod(b + c + 1), True if a == 2: return mod(2 * c + 1 + (c + 1) * b), False if a == 3: prefill(c) return F_CACHE[c][b], False assert False, (a, b, c) def f_6027(a, b, c): key = (a, b, c) if key in CACHE: return CACHE[ key ] v0, ok = f_fast(a, b, c) if ok and v0 is not None: return v0 f = f_6027 assert 0 <= a < MOD assert 0 <= b < MOD assert 0 <= c < MOD if a == 0: value = mod(b + 1) elif b == 0: value = f( mod(a - 1), c, c) else: a1 = f(a, mod(b - 1), c) value = f( mod(a - 1), a1, c) CACHE[ key ] = value print '{} -- > ({} vs {})'.format( key, value, v0 ) if v0 is not None: assert value == v0 return value if __name__ == "__main__": find_good() <file_sep> # 9 + 2 * 5^2 + 7^3 - 3 = 399 5275| wmem 2462 0 5278| set r0 27095 5281| set r1 5341 5284| call 1458 5341: > 5341| push r2 5343| add r2 2457 1 # r2 = 2457 + 1 5347| rmem r2 r2 # r2 = * r2 # r2 = 10109 5350| add r2 r2 r0 # r2 = r2 + r0 # r2 = 10109 + char 5354| wmem r2 95 # *r2 = 95 5357| pop r2 5359| ret 5846: > 5846| push r3 5848| push r4 5850| rmem r3 2732 5853| add r4 r0 2 5857| rmem r4 r4 5860| eq r3 r3 r4 5864| jf r3 5871 5867| add r2 r2 1 5871| pop r4 5873| pop r3 5875| ret 1619| push r3 1621| add r3 r2 1 1625| add r3 r3 r1 1629| rmem r3 r3 1632| eq r3 r0 r3 1636| jt r3 1645 1639| set r2 r1 1642| set r1 32767 1645| pop r3 1647| ret ===================================== 25974| mod 117 115 101 was changed to 25974| mult 117 115 101 -- function calls: 2830| set r0 25974 2833| set r1 32 2836| call 1571 r0: 25974 r1: 32 r2: 4 r3: 6 r4: 101 r5: 0 r6: 0 r7: 0 1571| push r1 1573| push r2 1575| set r2 r1 1578| set r1 1605 1581| call 1543 1583| pop r2 1585| pop r1 1587| ret -- ===================================== > 1458| push r0 1460| push r3 1462| push r4 1464| push r5 1466| push r6 1468| set r6 r0 1471| set r5 r1 1474| rmem r4 r0 1477| set r1 0 > 1480| add r3 1 r1 r0: 72 r1: 2 r2: 32767 r3: 6131 r4: 12 r5: 1528 r6: 6129 r7: 0 // starting from 1480: loop to print string 1484| gt r0 r3 r4 r1 - current index symbol to output r4 - number of symbols in string r0 - will be '0' if last symbol 1488| jt r0 1507 1491| add r3 r3 r6 1495| rmem r0 r3 r0 <-- memory[ r6 + r1 + 1] > 1498| call r5 1500| add r1 r1 1 r1 += 1 > 1504| jt r1 1480 r5: 1531 // encoded r5: 1528:// no encoding r6: offset from which to read in memory > 1528| out (r0) 1530| ret > 1531| push r1 1533| set r1 r2 1536| call 2125 1538| out (r0) 1540| pop r1 1542| ret r0: 18143 r1: 18175 r2: 18175 > 2125| push r1 2127| push r2 2129| and r2 r0 r1 2133| not r2 r2 2136| or r0 r0 r1 2140| and r0 r0 r2 2144| pop r2 2146| pop r1 2148| ret r1: X r2: X stack = [r1, r2] r2 = r1 & r0 r2 = ! r2 r0 = r0 | r1 r0 = r0 & r2 After string was printed: > 1507| pop r6 1509| pop r5 1511| pop r4 1513| pop r3 1515| pop r0 r0: 1 r1: 12 r2: 32767 r3: 13 r4: 12 r5: 1528 r6: 6129 r7: 0 stack: [6129, 1, 12, 1, 118] ================================= <file_sep>from vm2 import VM2, load_bytecode import gdb ops = load_bytecode() vm = VM2(ops) vm.index = 0 # useful shortcuts def d(offset=None, limit=15): if offset is None: offset = vm.index print reload(gdb).GDB(vm).disasm(offset, limit) def p(): vm.show_state() # def s(limit=1): # vm.step(limit) def r(): vm.run() d() def bt(): vm.show_trace() def n(): vm.execute_one_op(ignore_break=True) d() def x(): return reload(gdb).GDB(vm) def i(s): vm.return_on_input = True vm.buffer += s + '\n' vm.run() def up(): x().up() d() def skip(): op = vm.read_op(vm.index) next = vm.index + op.size() vm.break_points.add(next) vm.run() vm.break_points.remove(next) d() def l(n): print x().get_location_info(n) # g.disasm_to_file('asm/0.asm') # vm.buffer += "take tablet\nuse tablet\n" # vm.break_points.add(1841) def preare_teleport(): # vm.break_points.add(6027) vm.r[7] = 25734 i('use teleporter') def current_solution(): vm.return_on_input = True vm.run() x().mark_locations() x().solution() x().disasm_to_file('asm/8.asm') # i('look') def on_start(): vm.return_on_input = True vm.run() # x().mark_locations() x().disasm_to_file('asm/start-2.asm') # i('look') def go_to_maze(): vm.return_on_input = True vm.run() x().mark_locations() x().run_seq( gdb.take_lantern_and_go_to_ladder() ) i('look') # go_to_maze() # patch the memory to show all items # 5902| eq r3 r2 r3 # 5906| jf r3 5918 --> noop noop noop # 5909| add r0 r0 0 # # vm.memory[5906] = 21 # vm.memory[5907] = 21 # vm.memory[5908] = 21 # # on_start() current_solution() # take teleport # x().get_all_items() # x().solution() # x().try_coins() # x().disasm_to_file('asm/5.asm') # # # vm.block_on_output = True # vm.buffer += "\n" # vm.return_on_input = True # vm.run() # # # g().analyze() # # g().disasm_to_file('asm/4.asm') # vm.return_on_input = False # commands = [ # 'doorway', # 'north', # 'north', # 'bridge', # 'continue', # 'down', # 'east', # 'take empty lantern', # 'west', # 'west', # 'passage', # ] # for cmd in commands: # vm.buffer += (cmd + '\n') # vm.run() <file_sep>def inverse(a): return a ^ (2**15 - 1) def mod(v): return v % MOD MEMSIZE = 32768 MAX_VALUE = 32768 MOD = 32768 TRACE = True def read_memory(v): if v < MAX_VALUE: return str(v) return 'r{}'.format(v - MAX_VALUE) def is_register(a): return MAX_VALUE <= a <= MAX_VALUE + 7 def translate_program(s): ops = [] for i in xrange(0, len(s), 2): b1 = ord(s[i]) b2 = ord(s[i + 1]) byte = b1 + b2 * 256 assert byte <= 32775, byte ops.append(byte) return ops def load_bytecode(): f = open('data/challenge.bin', 'rb') s = f.read() return translate_program(s) <file_sep> import sys from ops import * from util import * from copy import copy from teleport import f4_1 class FrameInfo: def __init__(self): self.jump = 0 self.ret = 0 self.name = '' self.r = [] def __str__(self): return '({}), ret = {}'.format( self.name, self.ret ) class Break(Exception): def __init__(self, value): self.value = value class VM2: def __init__(self, ops): self.ops = ops # setup memory self.memory = [0] * MEMSIZE for i in xrange(len(self.ops)): self.memory[i] = self.ops[i] self.r = [0] * 8 self.stack = [] self.meta_stack = [] self.index = 0 self.stop = False self.buffer = "" self.bi = 0 self.log = open('log.txt', 'wt') self.return_on_input = False self.block_on_output = False self.disable_output = False self.stop_on_return = False self.use_fast_6027 = True self.depth = 0 self.cpu = 0 self.output = [] self.call_stack = [] self.break_points = set() def read_op(self, offset): op_code = self.memory[offset] if op_code in CODES: return CODES[op_code] else: return OpSpec.unknown() def show_program(self, offset, limit=10): for i in xrange(limit): op = self.read_op(offset) print "{} | {} {}".format( offset, op.name, op.args, ) offset += op.size() def try_read_out(self, offset): jump = 0 stop = False s = '' while not stop: op = self.read_op(offset) stop = True if op.name == 'out': value = self.memory[offset + 1] if value < 256: if value == 10: s += '\\n' else: s += chr(value) stop = False offset += 2 jump += 2 data = 'out "{}"'.format(s) return jump, data def get_value(self, v): if v < MAX_VALUE: return v return self.r[ v - MAX_VALUE ] def write_r(self, a, value): self.r[ a - MAX_VALUE ] = value def read(self, num): res = self.memory[self.index : self.index + num] self.index += num if num == 1: return res[0] return res def set_input(self, buffer): self.buffer = buffer self.bi = 0 def get_char(self): if self.bi >= len(self.buffer): if self.return_on_input: # restore 2 read symbols self.index -= 2 raise Break('>: returned while reading from stdin') input = raw_input('>:') if input == '?': # restore 2 read symbols self.index -= 2 raise Break('>: returned back to shell') self.buffer += input + '\n' # print "Read line {} (len = {}) from console".format( # self.buffer, # len(self.buffer), # ) # self.bi = 0 char = self.buffer[self.bi] self.bi += 1 # print "Read {} from console".format( # ord(char) # ) return char def show_state(self): index = self.index print print "index = {}, cpu step = {}".format( index, self.cpu) for i in xrange(len(self.r)): print "r{}: {}".format(i, self.r[i]) # print 'stack ({}): {}'.format(len(self.stack), self.stack) data = 'stack ({}): '.format(len(self.stack)) vals = [] for i in xrange(len(self.stack)): vals.append('{}({})'.format( self.stack[i], self.meta_stack[i], )) data += '[' + ', '.join(vals) + ']' print data self.show_output() def show_output(self, limit=20): print 'output: "{}"'.format( ''.join(self.output[-limit:]) ) def dump_state(self): i = self.index if TRACE: print >> self.log print >> self.log, "index = ", i print >> self.log, "Registers: ", self.r print >> self.log, "Memory: ", self.memory[i: i + 5] def execute_one_op(self, ignore_break=False): i = self.index m = self.memory[i] if not ignore_break: if i in self.break_points: raise Break('Stop on {}'.format(i)) if self.use_fast_6027 and i == 6027: r0 = self.r[0] r1 = self.r[1] r7 = self.r[7] ok = (r0 == 4 and r1 == 1) if not ok: raise Break( 'Unexpected args to 6027: (r0 = {}, r1 = {})'.format( r0, r1 )) a = f4_1(r7) print 'Got {} for {}'.format(a, (r0, r1, r7) ) # code around: #>6027| jt r0 6035 # if A == 0 # 6030| add r0 r1 1 # r0 = r1 + 1 # 6034| ret # so we go to next instructions self.r[1] = mod(a - 1) self.index = 6030 return op = self.read(1) r = self.r if op == 0: # halt: 0 # stop execution and terminate the program name = 'halt' self.stop = True elif op == 1: # set: 1 a b # set register <a> to the value of <b> name = 'set' a, b = self.read(2) self.write_r(a, self.get_value(b)) elif op == 2: # push: 2 a # push <a> onto the stack name = 'push' a = self.read(1) self.stack.append( self.get_value(a) ) self.meta_stack.append( read_memory(a) ) elif op == 3: # pop: 3 a # remove the top element from the stack and write it into <a>; empty stack = error name = 'pop' a = self.read(1) self.write_r(a, self.stack.pop() ) self.meta_stack.pop() elif op == 4: # eq: 4 a b c # set <a> to 1 if <b> is equal to <c>; set it to 0 otherwise name = 'eq' a, b, c = self.read(3) vb = self.get_value(b) vc = self.get_value(c) if vb == vc: self.write_r(a, 1) else: self.write_r(a, 0) elif op == 5: # gt: 5 a b c # set <a> to 1 if <b> is greater than <c>; set it to 0 otherwise name = 'gt' a, b, c, = self.read(3) vb = self.get_value(b) vc = self.get_value(c) if vb > vc: self.write_r(a, 1) else: self.write_r(a, 0) elif op == 6: # jmp: 6 a # jump to <a> name = 'jmp' a = self.read(1) self.index = self.get_value(a) elif op == 7: # jt: 7 a b # if <a> is nonzero, jump to <b> name = 'jt' a, b = self.read(2) if self.get_value(a) != 0: self.index = self.get_value(b) elif op == 8: # jf: 8 a b # if <a> is zero, jump to <b> name = 'jf' a, b = self.read(2) if self.get_value(a) == 0: self.index = self.get_value(b) elif op == 9: # add: 9 a b c # assign into <a> the sum of <b> and <c> (modulo 32768) name = 'add' a, b, c = self.read(3) vb = self.get_value(b) vc = self.get_value(c) self.write_r(a, mod(vb + vc) ) elif op == 10: # mult: 10 a b c # store into <a> the product of <b> and <c> (modulo 32768) name = 'mult' a, b, c = self.read(3) vb = self.get_value(b) vc = self.get_value(c) self.write_r(a, mod(vb * vc) ) elif op == 11: # mod: 11 a b c # store into <a> the remainder of <b> divided by <c> name = 'mod' a, b, c = self.read(3) vb = self.get_value(b) vc = self.get_value(c) self.write_r(a, vb % vc) elif op == 12: # and: 12 a b c # stores into <a> the bitwise and of <b> and <c> name = 'and' a, b, c = self.read(3) vb = self.get_value(b) vc = self.get_value(c) self.write_r(a, vb & vc) elif op == 13: # or: 13 a b c # stores into <a> the bitwise or of <b> and <c> name = 'or' a, b, c = self.read(3) vb = self.get_value(b) vc = self.get_value(c) self.write_r(a, vb | vc) elif op == 14: # not: 14 a b # stores 15-bit bitwise inverse of <b> in <a> name = 'not' a, b = self.read(2) vb = inverse( self.get_value(b) ) self.write_r(a, vb) elif op == 15: # rmem: 15 a b # read memory at address <b> and write it to <a> name = 'rmem' a, b = self.read(2) self.write_r(a, self.memory[ self.get_value(b) ]) elif op == 16: # wmem: 16 a b # write the value from <b> into memory at address <a> name = 'wmem' a, b = self.read(2) self.memory[ self.get_value(a) ] = self.get_value(b) elif op == 17: # call: 17 a # write the address of the next instruction to the stack and jump to <a> name = 'call' a = self.read(1) self.stack.append(self.index) meta = 'call {}'.format(self.get_value(a)) self.meta_stack.append( meta ) addr = self.get_value(a) self.trace_call(addr, meta) self.depth += 1 self.index = addr elif op == 18: if self.stop_on_return and self.depth == 0: self.index -= 1 raise Break('Returning from function') self.depth -= 1 # ret: 18 # remove the top element from the stack and jump to it; empty stack = halt name = 'ret' if not self.stack: print 'empty stack = halt, while executing "ret"' self.stop = True else: self.index = self.stack.pop() self.meta_stack.pop() self.trace_return() elif op == 19: # out: 19 a # write the character represented by ascii code <a> to the terminal name = 'out' a = self.read(1) char = chr(self.get_value(a)) if not self.disable_output: sys.stdout.write( char ) self.output.append( char ) if self.block_on_output: raise Break('Interruption while outputting') elif op == 20: # in: 20 a # read a character from the terminal and write its ascii code to <a>; # it can be assumed that once input starts, it will continue until # a newline is encountered; this means that you can safely read # whole lines from the keyboard and trust that they will be fully read name = 'in' # print "Found input: exiting" # self.stop = True # return a = self.read(1) char = self.get_char() self.write_r(a, ord(char) ) elif op == 21: # noop: 21 # no operation name = 'noop' self.cpu += 1 # if TRACE: # print >> self.log, 'Executing {} ({}) at {}'.format( # m, # name, # i, # ) def trace_call(self, addr, meta): frame = FrameInfo() frame.name = meta frame.jump = addr frame.ret = self.index frame.r = copy(self.r) self.call_stack.append(frame) def trace_return(self): self.call_stack.pop() def show_trace(self): num = 0 for i in reversed(xrange(len(self.call_stack))): print '#{}: {}'.format( num, str(self.call_stack[i]), ) num += 1 def run(self): try: while True: if self.stop: print 'Program halted' break # self.dump_state() self.execute_one_op() except Break as e: print 'Caught exception: ', e.value def step(self, limit): try: for i in xrange(limit): if self.stop: print 'Program halted' break self.execute_one_op() except Break as e: print 'Caught exception: ', e.value <file_sep>from util import * SPEC = [ ('halt', '0'), ('set', '1 a b'), ('push', '2 a'), ('pop', '3 a'), ('eq', '4 a b c'), ('gt', '5 a b c'), ('jmp', '6 a'), ('jt', '7 a b'), ('jf', '8 a b'), ('add', '9 a b c'), ('mult', '10 a b c'), ('mod', '11 a b c'), ('and', '12 a b c'), ('or', '13 a b c'), ('not', '14 a b'), ('rmem', '15 a b'), ('wmem', '16 a b'), ('call', '17 a'), ('ret', '18'), ('out', '19 a'), ('in', '20 a'), ('noop', '21'), ] class OpSpec: def __init__(self, name=None, spec=None): if name is not None: self.name = name ss = spec.split(' ') self.opcode = int(ss[0]) self.arity = len(ss) - 1 self.args = ", ".join(ss[1:]) def size(self): return self.arity + 1 @staticmethod def unknown(): op = OpSpec() op.name = 'unknown' op.arity = 0 op.args = '' return op CODES = {} for name, s in SPEC: op = OpSpec(name, s) CODES[op.opcode] = op OPNAME_TO_CODE = {} for op in CODES.values(): OPNAME_TO_CODE[op.name] = op.opcode def to_opcode(s): if s in OPNAME_TO_CODE: return OPNAME_TO_CODE[s] if s.startswith('r'): return int(s[1:]) + MAX_VALUE return int(s) <file_sep>#include <stdio.h> #include <iostream> #include <vector> #include <string> #include <math.h> #include <algorithm> #include <bitset> #include <set> #include <sstream> #include <stdlib.h> #include <map> #include <queue> #include <assert.h> #include <deque> #include <string.h> using namespace std; #define sz(x) ((int)x.size()) #define all(x) (x).begin(), (x).end() #define pb(x) push_back(x) #define mp(x, y) make_pair(x, y) typedef long long int64; typedef vector <int64> vi; typedef vector <vi> vvi; // if a == 2: // return mod(2 * c + 1 + (c + 1) * b), False // for i in xrange(start, end): // dp[i] = mod( dp[i - 1] * (c + 1) + 1 + 2 * c ) const int64 MX = 32768; const int64 MOD = 32768; int64 mod(int64 v) { return ((v % MOD) + MOD) % MOD; } int64 f2(int64 c) { return mod(2 * c + 1 + (c + 1) * c); } void solution() { for (int c = 1; c < MX; ++c) { vi dp(MX, 0); dp[0] = f2(c); for (int i = 1; i < MX; ++i) { dp[i] = mod( dp[i - 1] * (c + 1) + 1 + 2 * c ); } int64 value = dp[ dp[c] ]; cout << "dp[ " << c << " ] = " << value << endl; if (value == 6) { cout << "Found ans: " << value << endl; return; } } } int main () { //freopen("", "rt", stdin); //freopen("", "wt", stdout); //std::ios::sync_with_stdio(false); solution(); return 0; } <file_sep> import unittest from vm import VM class TestVM(unittest.TestCase): def test_input(self): ops =[9, 32768, 32769, 4, 19, 32768] # - Store into register 0 the sum of 4 and the value contained in register 1. # - Output to the terminal the character with the ascii code contained in register 0. vm = VM(ops) vm.r[1] = 65 vm.run() self.assertEqual(vm.r[0], vm.r[1] + 4) if __name__ == '__main__': unittest.main()
9c3ad7e180c91db12b376c2bcc59372c84bc74d1
[ "Python", "Text", "C++" ]
11
Python
pankdm/synacor-challenge
6289c3cc0ee0e4d10f40473e10ee87ac03f66317
fd15f17450d8d21eb142ad70d5675d1a6859bbd1
refs/heads/master
<file_sep>CREATE TABLE IF NOT EXISTS `dummy` ( `id` bigint(20) unsigned NOT NULL, `name` varchar(255) NOT NULL DEFAULT '', `comment` varchar(255) NOT NULL DEFAULT '', `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `updated` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; <file_sep><?php include __DIR__ . '/common.php'; function getData($pdo, $limit = false) { $sql = 'SELECT * FROM dummy'; if (is_numeric($limit)) { $sql .= sprintf(' LIMIT %d', $limit); } $stmt = $pdo->prepare($sql); $stmt->execute(); $csv = []; while ($row = $stmt->fetch()) { $csv[] = sprintf( '%d,%s,%s,%s,%s,%s MB', $row['id'], $row['name'], $row['comment'], $row['created'], $row['updated'], memory_get_peak_usage(true) / 1024 / 1024 ); } return $csv; } $limit = $_GET['limit'] ?? false; $csv = getData($pdo, $limit); header('Content-Disposition: attachment; filename="csv-normal.csv"'); foreach ($csv as $line) { echo $line, PHP_EOL; } <file_sep><?php for ($i = 1; $i <= 5000000; $i++): ?> <?= $i ?>,<?= sprintf('Tanaka Taro%05d', $i) ?>,This is test data!!Wow!!!!!!!!!!!!!####!!<?= $i.PHP_EOL ?> <?php endfor ?> <file_sep><?php // show all errors. error_reporting(-1); $pdo = new PDO('mysql:dbname=pdo_test', 'root', 'secret'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); header('Content-type: text/csv; charset=utf-8'); <file_sep># 目的 CSV ダウンロード機能を実装する上で、ファイルサイズが大きくなればなるほど 通常メモリの消費が大きくなってくる どれだけファイルサイズが大きくなっても、メモリの問題を回避して実装する方法を検証するためのスクリプトを作ってみた # 前提 vagrant, virtualbox がインストールされている環境であること # vagrant 起動方法 ``` git clone https://github.com/oz-urabe/qiita-for-csv-download.git cd qiita-for-csv-download vagrant up --provision ``` # 動作確認方法 ブラウザで http://10.0.0.10 にアクセス - 取り急ぎ実装したバージョン - 該当ソースコード: src/csv-download.php - メモリリミットが起きないように回避したバージョン - 該当ソースコード: src/csv-download-tuned.php # License These codes are licensed under CC0. [![CC0](http://i.creativecommons.org/p/zero/1.0/88x31.png "CC0")](http://creativecommons.org/publicdomain/zero/1.0/deed.ja) <file_sep>#!/bin/bash # mysql prepare sudo cp /vagrant/script/add.cnf /etc/mysql/conf.d/add.cnf echo "restarting mysql..." sudo systemctl restart mysql echo "done." # prepare echo "prepare insert csv file..." gzip -dc /vagrant/script/insert.csv.gz > /tmp/insert.csv echo "done." echo "create database..." mysqladmin -uroot create pdo_test > /dev/null 2>&1 || : echo "done." echo "create table..." mysql -uroot pdo_test < /vagrant/script/create_dummy.sql echo "done." echo "truncate table..." mysql -uroot pdo_test -e 'TRUNCATE dummy;' echo "done." echo "insert data..." mysql -uroot pdo_test -e 'LOAD DATA LOCAL INFILE "/tmp/insert.csv" INTO TABLE dummy FIELDS TERMINATED BY "," LINES TERMINATED BY "\n" IGNORE 1 LINES (@id, @name, @comment) SET id = @id, name = @name, comment = @comment, created = NOW(), updated = NOW();' echo "done." rm -rf /tmp/insert.csv echo "set symbolic link to index.php..." sudo ln -sf /vagrant/src/*.php /var/www/html/ sudo rm -rf /var/www/html/index.html > /dev/null 2>&1 || : echo "done."
bdd5336e1edfe28a6b0dc673d16c3affd72c8401
[ "Markdown", "SQL", "PHP", "Shell" ]
6
SQL
oz-urabe/qiita-for-csv-download
da5d2db11639f9a5c19b243bd1cc55ff649f105d
ecac7282423020d4d668e1d61b28ebd6f21b489d
refs/heads/master
<repo_name>osejob/hw4<file_sep>/index.js // I struggled to put this together, and couldn't get the APIs to work unfortunately. I definitely underestimated // this assignment and didn't leave myself with enough time. I was able to do the 3-column newspaper layout and // was also able to get the ads to work. I feel like some of the javascript code below was on the right track but // clear not where it needed to be. // Would really appreciate some feedback and hopefully a passing grade :) let updateWidget = function(data) { console.log("Got weather data: ", data) // YOUR CODE GOES HERE let temp = $("#headline1 h1") temp.html("It is " + Math.round(data.main.temp) + " degrees outside in" + city.html(data.name)) } let getWeather = function(info) { let latitude = '48.8566'; // let longitude = '2.3522'; let apiKey = 'fad13ca22af87754cadeaf2ec94e01e9'; // REPLACE THIS VALUE with your own key. let weatherServiceURL = 'https://api.openweathermap.org/data/2.5/weather?' weatherServiceURL += 'lat=' + latitude weatherServiceURL += '&lon=' + longitude weatherServiceURL +='&appid=' + apiKey + '&units=imperial' fetch(weatherServiceURL).then(convertToJSON).then(updateWidget).catch(displayError); } let handlePosition = function(event) { event.preventDefault(); navigator.geolocation.getCurrentPosition(getWeather); } let link = jQuery("#get_forecast") link.on("click", handlePosition); let convertToJSON = function(rawData) { return rawData.json(); } let displayError = function(error) { console.debug(error); } $(function() { let apiKey = "<KEY>"; let url = "https://api.nytimes.com/json?api-key=" + apiKey; $.get(url, function(data) { console.log(data); $("#headline2").empty(); for (let i=0; data.results.length;) { let news = data.results[i]; let html = '<div class="col-4">'; $(".row").append(html); } $(".row").fadeIn(2000); }); });
5e5d246ab2a2c364bad2fc5359834daa145d364d
[ "JavaScript" ]
1
JavaScript
osejob/hw4
2dbbd6c4669ac0e103e9d5951df40a5a88182a91
c335edf6870584635efc15dee80d5e0e8a78314f
refs/heads/master
<file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- from lxml import etree import string html = ''' <book> <author>Tom <em>John</em> cat</author> <author>Jerry <em>Bush</em> mouse</author> <pricing> <price>20</price> <discount>0.8</discount> </pricing> </book> ''' selector = etree.HTML(html) data = selector.xpath('//book/author/text()') # print(data) str1 = " ".join(data) # print(str1) data2 = selector.xpath('string(//book//author)') # print(data2) # intab = "aeiou" # outtab = "12345" trantab = str.maketrans(" ", "\n") str = "this is string example......wow, yeah!" print(str.translate(trantab).strip()) <file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- from scrapy import cmdline # cmdline.execute("scrapy crawl spider1".split()) cmdline.execute("scrapy crawl spider1 -o FinanceSinaItems.csv -t csv --nolog".split()) # cmdline.execute("scrapy crawl spider2 --nolog".split()) # cmdline.execute("scrapy crawl spider2 -o EastMoneyItems.csv -t csv --nolog".split()) <file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- import scrapy import string import re from WebSpider.items import FinanceSinaItem class Spider1(scrapy.Spider): name = 'spider1' allowed_domains = ['sina.com.cn'] start_urls = ['http://finance.sina.com.cn/'] def parse(self, response): label_list = response.xpath('//a[@target="_blank" and \ re:test(@href, "http://finance.sina.com.cn/.*?/\d{4}-\d{2}-\d{2}/.*?\d+\\.shtml$") and \ not(img) and \ not(@href=preceding::a/@href)]') #防止重复取网址 print(len(label_list)) for each in label_list: print(each.extract()) url = each.xpath('@href').extract_first() # print(url) yield scrapy.Request(url, callback=self.parse_dir_contents) pass def parse_dir_contents(self, response): item = FinanceSinaItem() item['url_link'] = response.url # print(response.url) title = response.xpath('//*[@id="artibodyTitle"]/text()').extract_first().strip() item['title'] = title # print(title) time = response.xpath('//*[@id="wrapOuter"]/div/div[4]/span/text() | \ //*[@id="pub_date"]/text() | \ //h2[@class="u-content-time"]/text()').re_first('(\d.*\d)') item['time'] = time # print(time) author = response.xpath('//*[@id="wrapOuter"]/div/div[4]/span//text() |\ //*[@id="media_name"]//text() |\ //*[@id="author_ename"]/a/text() |\ //h2[@class="u-content-time"]/text()').re_first('FX168|[\u4e00-\u9fa5][\u4e00-\u9fa5]+') # 这里的re匹配考虑到'FX168'不属于中文,因此单列 # [\u4e00-\u9fa5]中文字符编码区间 item['author'] = author # print(author) content = response.xpath('//*[@id="artibody"]//p//text()').extract() data1 = "".join(content) data2 = data1.translate(str.maketrans('', '', string.whitespace)).strip() final_data = re.sub("\\u3000+", "\n\n", data2) item['description'] = final_data # print(final_data) # print('\n') yield item pass <file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- import scrapy import string import re from WebSpider.items import EastMoneyItem class Spider2(scrapy.Spider): name = 'spider2' allowed_domains = ['eastmoney.com'] start_urls = ['http://www.eastmoney.com/'] def parse(self, response): label_list = response.xpath('//a[re:test(@href, "http://.*?(?<!ideo|life)\\.eastmoney.com/news/\d+,\d+\\.html") and \ not (img)]') #去除财经生活、视频类报道 print(len(label_list)) for each in label_list: print(each.extract()) # url_old = each.xpath('@href').extract_first() url = each.xpath('@href').re_first('(.*)\\.html') + "_0.html" #这里照顾到翻页无法取全文的问题,故用_0.html取全文网页 # print(url_old) # print(url) # print('\n') yield scrapy.Request(url, callback=self.parse_dir_contents) pass def parse_dir_contents(self, response): item = EastMoneyItem() item['url_link'] = response.url title = response.xpath('//h1/text()').extract_first().strip() item['title'] = title time = response.xpath('//div[@class="time"]/text()').extract_first() item['time'] = time author = response.xpath('//div[@class="source"]/img/@alt |\ //div[@class="source"]/a/text()').extract_first() item['author'] = author content = response.xpath('//div[@id="ContentBody"]/p/text() |\ //div[@id="ContentBody"]//a[@class]/text() |\ //div[@id="ContentBody"]/p/strong/text() |\ //div[@id="ContentBody"]/text()').extract() data1 = "".join(content) data2 = data1.translate(str.maketrans('', '', string.whitespace)).strip() #string.whitespace = ' \t\n\r\v\f' final_data = re.sub("\\u3000+", "\n\n", data2) # print(title) # print(response.url) # print(final_data) # print('\n') item['description'] = final_data yield item pass <file_sep># Simple-Scrapy A simple example for the scrapy framwork. This is the project in HanBo laboratory. <file_sep># -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymysql from WebSpider import settings from WebSpider.items import FinanceSinaItem from WebSpider.items import EastMoneyItem class WebcrawlerScrapyPipeline(object): '''保存到数据库中对应的class 1、在settings.py文件中配置 2、在自己实现的爬虫类中yield item,会自动执行''' def __init__(self): self.connect = pymysql.connect( host=settings.MYSQL_HOST, db=settings.MYSQL_DBNAME, user=settings.MYSQL_USER, passwd=settings.MYSQL_PASSWD, charset='utf8', use_unicode=True) self.cursor = self.connect.cursor() self.cursor.execute("""CREATE TABLE IF NOT EXISTS finance_sina(author VARCHAR(50), title VARCHAR(255), pub_time VARCHAR(50), description text, url_link text)""") self.cursor.execute("""CREATE TABLE IF NOT EXISTS east_money(author VARCHAR(50), title VARCHAR(255), pub_time VARCHAR(50), description text, url_link text)""") # pipeline默认调用 def process_item(self, item, spider): if item.__class__ == FinanceSinaItem: try: self.cursor.execute("""select * from finance_sina where url_link = %s""", item["url_link"]) ret = self.cursor.fetchone() #决定是更新还是首次插入 if ret: self.cursor.execute( """update finance_sina set author = %s,title = %s,pub_time = %s, description = %s,url_link = %s""", (item['author'], item['title'], item['time'], item['description'], item['url_link'])) else: self.cursor.execute( """insert into finance_sina(author,title,pub_time,description,url_link) value (%s,%s,%s,%s,%s)""", (item['author'], item['title'], item['time'], item['description'], item['url_link'])) self.connect.commit() except Exception as error: print(error) return item elif item.__class__ == EastMoneyItem: try: self.cursor.execute("""select * from east_money where url_link = %s""", item["url_link"]) ret = self.cursor.fetchone() if ret: self.cursor.execute( """update east_money set author = %s,title = %s,pub_time = %s, description = %s,url_link = %s""", (item['author'], item['title'], item['time'], item['description'], item['url_link'])) else: self.cursor.execute( """insert into east_money(author,title,pub_time,description,url_link) value (%s,%s,%s,%s,%s)""", (item['author'], item['title'], item['time'], item['description'], item['url_link'])) self.connect.commit() except Exception as error: print(error) return item else: pass
e9cc030a769f467565ffd24291e00f59e785e12d
[ "Markdown", "Python" ]
6
Python
zhaoshihan/Simple-Scrapy
88a9a39234ab628ff74b6b2148d50f6574f8403e
18f3ae6a0f1184dab7db0b973efa60a999736e64
refs/heads/master
<repo_name>kiranjadhavcreditsystems/FullStackApplication<file_sep>/CSIHRMCRUD/src/main/java/com/csi/controller/EmployeeController.java package com.csi.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.csi.model.Employee; import com.csi.service.EmployeeServiceImpl; @CrossOrigin(origins="*") @RestController @RequestMapping("/api/employees") public class EmployeeController { @Autowired EmployeeServiceImpl employeeServiceImpl; @GetMapping("/") public List<Employee> getAllData() { return employeeServiceImpl.getAllData(); } @GetMapping("/{empId}") public Optional<Employee> getDataById(@PathVariable long empId) { return employeeServiceImpl.getDataById(empId); } @PostMapping("/") public Employee saveData(@RequestBody Employee employee) { return employeeServiceImpl.saveData(employee); } @PutMapping("/{empId}") public Employee updateData(@PathVariable long empId, @RequestBody Employee employee) { return employeeServiceImpl.updateData(empId, employee); } @DeleteMapping("/{empId}") public String deleteData(@PathVariable long empId) { employeeServiceImpl.deleteData(empId); return "Data deleted Successfully"; } }
0a5607787c972b510d0a83724b4fb097bc196d46
[ "Java" ]
1
Java
kiranjadhavcreditsystems/FullStackApplication
4327408c916bc2e1ede5cff5a3e275e9ecdcd1f0
6d54caeedb75e5ba743279e6a3abb21533a4b893
refs/heads/main
<repo_name>brentoooo/hw5<file_sep>/6.37/source/hw.c #include<stdio.h> #include<stdlib.h> int main(void) { int integer[20]; int max = 0; int i = 0; int j = 0; char y; printf("Enter a integer: "); do { scanf_s("%d", &integer[20]); i++; for (j = 0; j< integer[20]; j++) { if (integer[20] > max) { max = integer[20]; } } } while (y = getchar() != '\n'); printf("the maximum is: %d",max ); printf("\n"); system("pause"); return 0; }
8944cc9564c238db7f91b8ff59a3c9aedd54f52c
[ "C" ]
1
C
brentoooo/hw5
0018844b8c665d0374181b605dfeb6878c26fce2
f78beebd3c3dff37c928ec974c29310579d0ee3b
refs/heads/master
<repo_name>freethinker/adsenseclient<file_sep>/project/jni/process_reports.c #include "adsensejni.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <regex.h> #define LINESIZE 1000 #define DELIM "\t" void create_report(FILE *fp, FILE *fpout, char *timeRange) { char *buf; int timeRangeWritten = 0; buf = (char *) malloc(LINESIZE*sizeof(char)); while (fgets(buf, LINESIZE, fp) != NULL) { char *token; int written; int isDate = (strstr(buf, "Date") == NULL) && (strstr(buf, "Totals") == NULL) && (strstr(buf, "Averages") == NULL); if ( timeRangeWritten == 0 && isDate == 1) { char *timetoken; timetoken=(char *)malloc((strlen(timeRange)+10)*sizeof(char)); sprintf(timetoken,"%s,",timeRange); written=fwrite(timetoken, sizeof(char), strlen(timetoken), fpout); free(timetoken); timeRangeWritten = 1; } if (strstr(buf, "Totals") != NULL) { strtok(buf,"\t"); while((token = strtok( (char *) NULL, DELIM) ) != NULL ) { char *tokenupdate; tokenupdate=(char *)malloc((strlen(token)+10)*sizeof(char)); if(strstr(token,"\n")) { written=fwrite(token, sizeof(char), strlen(token)-1, fpout); } else { sprintf(tokenupdate,"%s,",token); written=fwrite(tokenupdate, sizeof(char), strlen(tokenupdate), fpout); } free(tokenupdate); } fwrite(",",sizeof(char),1,fpout); } if (strstr(buf, "Averages") != NULL) { int i = 0; strtok(buf,"\t"); while((token = strtok( (char *) NULL, DELIM) ) != NULL ) { i++; if ( i != 3 && i != 4 && i != 5 ) { continue; } char *tokenupdate; tokenupdate=(char *)malloc((strlen(token)+10)*sizeof(char)); if( i == 3) { sprintf(tokenupdate,"%s,",token); written=fwrite(tokenupdate, sizeof(char), strlen(tokenupdate), fpout); } else if( i == 5) { written=fwrite(token, sizeof(char), strlen(token)-1, fpout); } else { sprintf(tokenupdate,"%s,",token); written=fwrite(tokenupdate, sizeof(char), strlen(tokenupdate), fpout); } free(tokenupdate); } fwrite("\n",sizeof(char),1,fpout); } } free(buf); } void process_adsense_reports(void) { char afcfiles[6][1000]={AFC_TODAYCSV,AFC_YESTERDAYCSV,AFC_LAST7DAYSCSV,AFC_THISMONTHCSV,AFC_LASTMONTHCSV,AFC_ALLTIMECSV}; char afctime[6][50]={"Today","Yesterday","Last 7 Days","This Month","Last Month","All Time"}; int i; FILE *fp, *fpout; fpout = fopen(AFC_CSV,"w"); for (i = 0; i < 6; i++) { D("Processing %s\n",afcfiles[i]); fp = fopen(afcfiles[i],"r"); create_report(fp, fpout, afctime[i]); fclose(fp); } fclose(fpout); } <file_sep>/project/src/in/humbug/adsenseclient/AccountSetupCheckSettings.java package in.humbug.adsenseclient; import java.io.File; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.util.Log; import android.view.KeyEvent; import android.widget.ProgressBar; import android.widget.TextView; public class AccountSetupCheckSettings extends Activity { private static final boolean D = true; String TAG = "AdsenseValidateAccount"; private ProgressBar mProgressBar; private TextView mTextView; private Handler mHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "+++ OnCreate +++"); super.onCreate(savedInstanceState); int verified = getSp().getInt("verified", 0); int refresh = getSp().getInt("refresh", 0); if ( verified == 1 && refresh == 0) { startActivity(new Intent(this, AccountSetupBasics.class)); return; } setContentView(R.layout.account_setup_check_settings); if (refresh == 1) { mTextView = (TextView)findViewById(R.id.message); mTextView.setText("Reloading Adsense Data"); } mProgressBar = (ProgressBar)findViewById(R.id.progress); mProgressBar.setIndeterminate(true); if(isInternetOn()) { new Thread() { int status; public void run() { try{ System.loadLibrary("adsensejni"); String email = getSp().getString("email", null); String password = getSp().getString("password", null); int refresh = getSp().getInt("refresh", 0); if ( refresh == 0) { delAccountDir("/sdcard/humbug_adsense_client/"); File adsenseDataDir = new File("/sdcard/humbug_adsense_client/"); adsenseDataDir.mkdirs(); } if ( email != null && password != null ) { status = genAdsenseReports(email, password); if (status == 0) { startActivity(new Intent(AccountSetupCheckSettings.this, AdsenseClient.class)); Editor e = getSp().edit(); e.putInt("verified", 1); e.putInt("refresh", 0); e.commit(); } else if (status == 1) { } else if (status == 2) { showErrorDialogInvalidPassword(); } else if (status == 3) { showErrorDialogReportsError(); } else { Log.d(TAG, "Internet Issue"); showErrorDialogInternetError(); } } else { Log.d(TAG, "+++ NULL EMAIL PASSWORD +++"); startActivity(new Intent(AccountSetupCheckSettings.this, AccountSetupBasics.class)); } } catch (Exception e) { Log.d(TAG, "+++ Exception that was not caught +++" + status); if (status == 1) { } else if (status == 2) { showErrorDialogInvalidPassword(); } else if (status == 3) { showErrorDialogReportsError(); } else { Log.d(TAG, "Internet Issue"); showErrorDialogInternetError(); } } } }.start(); } else { showErrorDialogInternetError(); } } @Override public synchronized void onResume() { super.onResume(); if(D) Log.e(TAG, "+ ON RESUME +"); int verified = getSp().getInt("verified", 0); int refresh = getSp().getInt("refresh", 0); if ( verified == 1 && refresh == 0) { //startActivity(new Intent(this, AccountSetupBasics.class)); finish(); return; } } public native int genAdsenseReports(String username, String password); public native int delAccountDir(String path); private void showErrorDialogInvalidPassword() { mHandler.post(new Runnable() { public void run() { mProgressBar.setIndeterminate(false); new AlertDialog.Builder(AccountSetupCheckSettings.this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(getString(R.string.account_setup_failed_dlg_title)) .setMessage("Invalid Password") .setCancelable(true) .setPositiveButton( getString(R.string.account_setup_failed_dlg_edit_details_action), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(AccountSetupCheckSettings.this, AccountSetupBasics.class)); } }) .show(); } }); } private void showErrorDialogReportsError() { mHandler.post(new Runnable() { public void run() { mProgressBar.setIndeterminate(false); new AlertDialog.Builder(AccountSetupCheckSettings.this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(getString(R.string.account_setup_failed_dlg_title)) .setMessage("Error in fetching reports") .setCancelable(true) .setPositiveButton( getString(R.string.account_setup_failed_retry), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { reload(); } }) .show(); } }); } private void showErrorDialogInternetError() { mHandler.post(new Runnable() { public void run() { mProgressBar.setIndeterminate(false); new AlertDialog.Builder(AccountSetupCheckSettings.this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(getString(R.string.account_setup_failed_dlg_title)) .setMessage("Internet seems to be down?") .setCancelable(true) .setPositiveButton( getString(R.string.account_setup_failed_retry), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { reload(); } }) .show(); } }); } public final boolean isInternetOn() { ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); // ARE WE CONNECTED TO THE NET if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED || connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) { return true; } else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED ) { return false; } return false; } public void reload() { onStop(); onCreate(getIntent().getExtras()); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR && keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // Take care of calling this method on earlier versions of // the platform where it doesn't exist. onBackPressed(); } return super.onKeyDown(keyCode, event); } @Override public void onBackPressed() { Log.d(TAG, "Resetting refresh"); SharedPreferences settings = getSp(); Editor e = settings.edit(); e.putInt("refresh", 0); e.commit(); finish(); return; } private SharedPreferences getSp() { return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); } } <file_sep>/project/jni/adsensejni.c #include <string.h> #include <jni.h> #include <stdio.h> #include <stdlib.h> #include "urlcode.h" #include "adsensejni.h" jint Java_in_humbug_adsenseclient_AdsenseDataService_genAdsenseReports( JNIEnv* env, jobject thiz, jstring username, jstring password ) { CURLcode res; const char *nativeUserName = (*env)->GetStringUTFChars(env, username, 0); const char *nativePassWord = (*env)->GetStringUTFChars(env, password, 0); if(curl_local_init() != 0) { curl_easy_cleanup(curl); return 1; } if((res = adsense_login(nativeUserName, nativePassWord)) != 0) { curl_easy_cleanup(curl); if ( res != 1000) return 1000; return 2; } if((res = get_adsense_reports()) != 0) { curl_easy_cleanup(curl); if ( res != 1000) return 1000; return 3; } process_adsense_reports(); curl_easy_cleanup(curl); return 0; } jint Java_in_humbug_adsenseclient_AccountSetupCheckSettings_genAdsenseReports( JNIEnv* env, jobject thiz, jstring username, jstring password ) { CURLcode res; const char *nativeUserName = (*env)->GetStringUTFChars(env, username, 0); const char *nativePassWord = (*env)->GetStringUTFChars(env, password, 0); if(curl_local_init() != 0) { curl_easy_cleanup(curl); return 1; } if((res = adsense_login(nativeUserName, nativePassWord)) != 0) { curl_easy_cleanup(curl); if ( res != 1000) return 1000; return 2; } if((res = get_adsense_reports()) != 0) { curl_easy_cleanup(curl); if ( res != 1000) return 1000; return 3; } process_adsense_reports(); curl_easy_cleanup(curl); return 0; } jint Java_in_humbug_adsenseclient_AccountSetupCheckSettings_delAccountDir( JNIEnv* env, jobject thiz, jstring path) { int status; char *command; const char *nativePath = (*env)->GetStringUTFChars(env, path, 0); command = (char *)malloc((strlen(nativePath)+10)*sizeof(char)); sprintf(command,"rm -r %s",nativePath); D("Deleting Directory - command %s", command); system(command); free(command); return 0; } <file_sep>/project/src/in/humbug/adsenseclient/AdsenseClientState.java package in.humbug.adsenseclient; import android.app.Application; public class AdsenseClientState extends Application { private boolean AdsenseDataServiceState = false; private boolean AdsenseDataServiceStatePrev = false; private int ListItemClickPosition = 1; @Override public void onCreate(){ super.onCreate(); } public boolean getServiceState(){ return AdsenseDataServiceState; } public boolean getPrevServiceState(){ return AdsenseDataServiceStatePrev; } public void setServiceState(boolean state){ AdsenseDataServiceStatePrev = AdsenseDataServiceState; AdsenseDataServiceState = state; } public void setItemClickPosition(int position) { ListItemClickPosition = position; } public int getItemClickPosition() { return ListItemClickPosition; } } <file_sep>/project/src/in/humbug/adsenseclient/CleanThemeListItem.java package in.humbug.adsenseclient; import android.app.Activity; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; public class CleanThemeListItem extends Activity { private static final boolean D = true; String TAG = "AdsenseClient"; private ListView mTimeFrameDataView; private TextView mTimeFrameView; public static String AUTHORITY = "in.humbug.adsenseclient.adsensecontentprovider"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_clean); AdsenseClientState appState = ((AdsenseClientState)getApplicationContext()); int position = appState.getItemClickPosition(); String ExtraUri = "today"; String TimeFrame = "Today"; switch(position) { case 0: ExtraUri = "today"; TimeFrame="Today"; break; case 1: ExtraUri = "yesterday"; TimeFrame="Yesterday"; break; case 2: ExtraUri = "last7days"; TimeFrame="Last 7 Days"; break; case 3: ExtraUri = "thismonth"; TimeFrame="This Month"; break; case 4: ExtraUri = "lastmonth"; TimeFrame="Last Month"; break; case 5: ExtraUri = "alltime"; TimeFrame="All Time"; break; } mTimeFrameView = (TextView) findViewById(R.id.timeframe); mTimeFrameView.setText(TimeFrame); Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/adsense/afc/" + ExtraUri); mTimeFrameDataView = (ListView) findViewById(R.id.list); Cursor managedCursor = null; managedCursor = managedQuery(CONTENT_URI, null, null, null, null); if (managedCursor != null) { ListAdapter mTimeFrameCursorAdapter = new SimpleCursorAdapter(this, R.layout.item_clean, managedCursor, new String[] { "Colname", "Data" }, new int[] { R.id.colname, R.id.data }); mTimeFrameDataView.setAdapter(mTimeFrameCursorAdapter); } } } <file_sep>/Application.mk #Application.mk APP_PROJECT_PATH := $(call my-dir)/project APP_MODULES := libmxml libcurl adsensejni <file_sep>/project/jni/Android.mk LOCAL_PATH:= $(call my-dir) OPENSSL_INCLUDE_DIR := /home/pratik/work/android/droid/external/openssl/include common_CFLAGS := -Wpointer-arith -Wwrite-strings -Wunused -Winline -Wnested-externs -Wmissing-declarations -Wmissing-prototypes -Wno-long-long -Wfloat-equal -Wno-multichar -Wsign-compare -Wno-format-nonliteral -Wendif-labels -Wstrict-prototypes -Wdeclaration-after-statement -Wno-system-headers -DHAVE_CONFIG_H ######################### # Build the mxml library include $(CLEAR_VARS) MXML_HEADERS := \ config.h \ mxml.h \ mxml-private.h MXML_SOURCES := \ mxml-attr.c \ mxmldoc.c \ mxml-entity.c \ mxml-file.c \ mxml-index.c \ mxml-node.c \ mxml-private.c \ mxml-search.c \ mxml-set.c \ mxml-string.c \ testmxml.c LOCAL_SRC_FILES := $(addprefix mxml/,$(MXML_SOURCES)) LOCAL_MODULE:= libmxml include $(BUILD_STATIC_LIBRARY) ######################### # Build the libcurl library include $(CLEAR_VARS) include $(LOCAL_PATH)/lib/Makefile.inc CURL_HEADERS := \ curlbuild.h \ curl.h \ curlrules.h \ curlver.h \ easy.h \ mprintf.h \ multi.h \ stdcheaders.h \ typecheck-gcc.h \ types.h LOCAL_SRC_FILES := $(addprefix lib/,$(CSOURCES)) LOCAL_C_INCLUDES += $(LOCAL_PATH)/include/ $(OPENSSL_INCLUDE_DIR) LOCAL_CFLAGS += $(common_CFLAGS) LOCAL_COPY_HEADERS_TO := libcurl/curl LOCAL_COPY_HEADERS := $(addprefix include/curl/,$(CURL_HEADERS)) LOCAL_MODULE:= libcurl # Copy the licence to a place where Android will find it. # Actually, this doesn't quite work because the build system searches # for NOTICE files before it gets to this point, so it will only be seen # on subsequent builds. ALL_PREBUILT += $(LOCAL_PATH)/NOTICE $(LOCAL_PATH)/NOTICE: $(LOCAL_PATH)/COPYING | $(ACP) $(copy-file-to-target) include $(BUILD_STATIC_LIBRARY) #adsensejni ########### include $(CLEAR_VARS) LOCAL_MODULE := adsensejni LOCAL_SRC_FILES := adsensejni.c curl.c urlcode.c ConvertUTF.c process_reports.c LOCAL_STATIC_LIBRARIES := libcurl #LOCAL_C_INCLUDES += adsensejni.h urlcode.h $(LOCAL_PATH)/curl/include $(OPENSSL_INCLUDE_DIR) LOCAL_C_INCLUDES += $(LOCAL_PATH)/curl/include $(OPENSSL_INCLUDE_DIR) LOCAL_LDLIBS := -lz -lcrypto -lssl -llog #LOCAL_LDLIBS := -lz include $(BUILD_SHARED_LIBRARY) <file_sep>/project/jni/curl.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include "adsensejni.h" #include "urlcode.h" #include "ConvertUTF.h" #define BSIZ 32768 int convert_to_utf8(FILE *stream1, FILE *stream2) { FILE *fp, *fp1; unsigned int bytes; UTF16 *source_start, *source_end, *source_backup; UTF8 *target_start, *target_end, *target_backup; char *sourceout; size_t num, i, bad; fp = stream1; fp1 = stream2; source_start = (UTF16 *) malloc(BSIZ*sizeof(UTF16)); source_backup = source_start; while (0 < (num = fread(source_start,sizeof(UTF16),BSIZ,fp))) { ConversionResult ret; source_end = source_start + num + 1; ret = ConvertUTF16toUTF8((const UTF16 **)&source_start, source_end, NULL, NULL, strictConversion, &bytes); if (ret != conversionOK) { D("first call to ConvertUTF16toUTF8 failed (%d)", ret); if (ret == sourceExhausted) { D("Partial character in input"); } else if (ret == targetExhausted) { D("target buffer exhausted"); } else if (ret == sourceIllegal) { D("malformed/illegal source sequence"); } else { D("unknown ConvertUTF16toUTF8 error"); } return 1; } target_start = (UTF8 *) malloc((bytes + 1)*sizeof(UTF8)); target_backup = target_start; target_end = target_start + bytes; source_start = source_backup; source_end = source_start + num; ret = ConvertUTF16toUTF8((const UTF16 **)&source_start, source_end, &target_start, target_end, strictConversion, &bytes); if (ret != conversionOK) { D("second call to ConvertUTF16toUTF8 failed (%d)", ret); if (ret == sourceExhausted) { D("Partial character in input"); } else if (ret == targetExhausted) { D("target buffer exhausted"); } else if (ret == sourceIllegal) { D("malformed/illegal source sequence"); } else { D("unknown ConvertUTF16toUTF8 error"); } return 1; } target_start = target_backup; source_start = source_backup; bad=fwrite(target_start, sizeof(UTF8),bytes,fp1); free(target_backup); } D("Bytes Written %d", bad); free(source_backup); return 0; } static void *myrealloc(void *ptr, size_t size) { if (ptr) return realloc(ptr, size); else return calloc(1, size); } static size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) { size_t written; written = fwrite(ptr, size, nmemb, stream); return written; } static size_t write_response(void *ptr, size_t size, size_t nmemb, void *stream) { struct write_result *mem = (struct write_result*)stream; size_t realsize = nmemb * size; mem->memory = myrealloc(mem->memory, mem->size + realsize + 1); if (mem->memory) { memcpy(&(mem->memory[mem->size]), ptr, realsize); mem->size += realsize; mem->memory[mem->size] = 0; } return realsize; } int curl_local_init(void) { curl = curl_easy_init(); D("Curl Init"); if (! curl) return 1; D("Curl Init Done"); curl_easy_setopt(curl, CURLOPT_COOKIEJAR, COOKIEFILE); curl_easy_setopt(curl, CURLOPT_COOKIEFILE, COOKIEFILE); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); return 0; } int adsense_login(const char *username, const char*password) { //const char *username = "<EMAIL>"; //const char *password = "<PASSWORD>"; char *token, *GALX; CURLcode status; int ret; char *src; static struct write_result response; char *params, *encoded_params; D("Stage 1 Login"); /* STAGE 1 Adsense Login */ response.memory = NULL; response.size = 0; curl_easy_setopt(curl, CURLOPT_URL, ADSENSE_LOGIN_URL); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); status = curl_easy_perform(curl); if(status != 0) { D("curl error: unable to send data to ADSENSE_LOGIN_URL\n"); D("%s\n", curl_easy_strerror(status)); ret = status; goto cleanup; } GALX = NULL; src = response.memory; strtok(src,"\""); while((token=strtok(NULL,"\"")) != NULL) { if ((strstr(token, "GALX")) != NULL) { D("Matches GALX %s", token); strtok(NULL,"\""); GALX = strtok(NULL,"\""); break; } else GALX = NULL; } if (GALX == NULL) { D("Didnot Match, Can't find GALX"); /* May be we are already logged in*/ if (strcasestr(response.memory, ADSENSE_VERIFY_LOGIN_STRING) == NULL) { D("May be we are already logged in\n"); response.memory = NULL; response.size = 0; curl_easy_setopt(curl, CURLOPT_URL, ADSENSE_LOGIN_URL_STAGE4); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); status = curl_easy_perform(curl); if(status != 0) { D("curl error: unable to send data to ADSENSE_LOGIN_URL_STAGE4\n"); D("%s\n", curl_easy_strerror(status)); ret = status; goto cleanup; } if (strcasestr(response.memory, ADSENSE_VERIFY_LOGIN_STRING) == NULL) { D("Error: Login Unsuccesful\n"); D("%s",response.memory); ret = 1000; goto cleanup; } else { D("Login Successful\n"); ret = 0; } } else { D("Where are we????"); D("%s",response.memory); ret = 1000; } goto cleanup; } D("Stage 2 Login"); D("Extract %s\n",GALX); /* STAGE 2 Adsense Login */ params = (char *) malloc(1000*sizeof(char)); sprintf(params, "%s&GALX=%s&Email=%s&Passwd=%s", ADSENSE_LOGIN_URL_STAGE2_PARAMS, GALX, username, password); encoded_params = url_encode(params); response.memory = NULL; response.size = 0; curl_easy_setopt(curl, CURLOPT_URL, ADSENSE_LOGIN_URL_STAGE2); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, encoded_params); status = curl_easy_perform(curl); if(status != 0) { D("curl error: unable to send data to ADSENSE_LOGIN_URL_STAGE2\n"); D("%s\n", curl_easy_strerror(status)); ret = status; free(encoded_params); free(params); goto cleanup; } if (strcasestr(response.memory, ADSENSE_USERNAME_PASSWORD_INCORRECT) != NULL) { D("Error: %s\n", ADSENSE_USERNAME_PASSWORD_INCORRECT); ret = 1; /* Reuse an uncommon curl error */ free(encoded_params); free(params); goto cleanup; } else if(strcasestr(response.memory, "Can&#39;t access your account?") != NULL) { D("Error: Can't access your account?\n"); free(encoded_params); free(params); ret = 1; goto cleanup; } else { D("Username Password Accepted\n"); } curl_easy_setopt(curl, CURLOPT_POST, 0); free(encoded_params); free(params); /* STAGE 3 Adsense Login */ response.memory = NULL; response.size = 0; curl_easy_setopt(curl, CURLOPT_URL, ADSENSE_LOGIN_URL_STAGE3); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); status = curl_easy_perform(curl); if(status != 0) { D("curl error: unable to send data to ADSENSE_LOGIN_URL_STAGE3\n"); D("%s\n", curl_easy_strerror(status)); ret = status; goto cleanup; } /* STAGE 4 Adsense Login */ response.memory = NULL; response.size = 0; curl_easy_setopt(curl, CURLOPT_URL, ADSENSE_LOGIN_URL_STAGE4); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); status = curl_easy_perform(curl); if(status != 0) { D("curl error: unable to send data to ADSENSE_LOGIN_URL_STAGE4\n"); D("%s\n", curl_easy_strerror(status)); ret = status; goto cleanup; } if (strcasestr(response.memory, ADSENSE_VERIFY_LOGIN_STRING) == NULL) { D("Error: Login Unsuccesful\n"); D("%s",response.memory); ret = 1; /* Reuse an uncommon curl error */ goto cleanup; } else { D("Login Successful\n"); } ret = 0; cleanup: free(response.memory); return ret; } int get_adsense_reports(void) { CURLcode status; int ret; static struct write_result response; FILE *fp, *fpreal; D("Gonna Fetch the Reports Now\n"); response.memory = NULL; response.size = 0; fp = fopen(AFC_TEMP, "w+"); fpreal = fopen(AFC_TODAYCSV,"w"); curl_easy_setopt(curl, CURLOPT_URL, AFC_TODAY_REPORT_URL); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); status = curl_easy_perform(curl); //Pseudo statement to avoid getting the main adsense page fclose(fp); fp = fopen(AFC_TEMP,"w+"); status = curl_easy_perform(curl); if(status != 0) { D("curl error: unable to send data to AFC_TODAY_REPORT_URL\n"); D("%s\n", curl_easy_strerror(status)); ret = status; goto cleanup; } fclose(fp); fp = fopen(AFC_TEMP, "r"); status = convert_to_utf8(fp, fpreal); if(status != 0) { D("Conversion to UTF8 Failed"); ret = 1; } else { ret = 0; } fclose(fpreal); fclose(fp); response.memory = NULL; response.size = 0; fp = fopen(AFC_TEMP, "w+"); fpreal = fopen(AFC_YESTERDAYCSV,"w+"); curl_easy_setopt(curl, CURLOPT_URL, AFC_YESTERDAY_REPORT_URL); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); status = curl_easy_perform(curl); if(status != 0) { D("curl error: unable to send data to AFC_YESTERDAY_REPORT_URL\n"); D("%s\n", curl_easy_strerror(status)); ret = status; goto cleanup; } fclose(fp); fp = fopen(AFC_TEMP, "r"); status = convert_to_utf8(fp, fpreal); if(status != 0) { D("Conversion to UTF8 Failed"); ret = 1; } else { ret = 0; } fclose(fpreal); fclose(fp); response.memory = NULL; response.size = 0; fp = fopen(AFC_TEMP, "w+"); fpreal = fopen(AFC_LAST7DAYSCSV,"w+"); curl_easy_setopt(curl, CURLOPT_URL, AFC_LAST7DAYS_REPORT_URL); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); status = curl_easy_perform(curl); if(status != 0) { D("curl error: unable to send data to AFC_LAST7DAYS_REPORT_URL\n"); D("%s\n", curl_easy_strerror(status)); ret = status; goto cleanup; } fclose(fp); fp = fopen(AFC_TEMP, "r"); status = convert_to_utf8(fp, fpreal); if(status != 0) { D("Conversion to UTF8 Failed"); ret = 1; } else { ret = 0; } fclose(fpreal); fclose(fp); response.memory = NULL; response.size = 0; fp = fopen(AFC_TEMP, "w+"); fpreal = fopen(AFC_THISMONTHCSV,"w+"); curl_easy_setopt(curl, CURLOPT_URL, AFC_THISMONTH_REPORT_URL); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); status = curl_easy_perform(curl); if(status != 0) { D("curl error: unable to send data to AFC_THISMONTH_REPORT_URL\n"); D("%s\n", curl_easy_strerror(status)); ret = status; goto cleanup; } fclose(fp); fp = fopen(AFC_TEMP, "r"); status = convert_to_utf8(fp, fpreal); if(status != 0) { D("Conversion to UTF8 Failed"); ret = 1; } else { ret = 0; } fclose(fpreal); fclose(fp); response.memory = NULL; response.size = 0; fp = fopen(AFC_TEMP, "w+"); fpreal = fopen(AFC_LASTMONTHCSV,"w+"); curl_easy_setopt(curl, CURLOPT_URL, AFC_LASTMONTH_REPORT_URL); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); status = curl_easy_perform(curl); if(status != 0) { D("curl error: unable to send data to AFC_LASTMONTH_REPORT_URL\n"); D("%s\n", curl_easy_strerror(status)); ret = status; goto cleanup; } fclose(fp); fp = fopen(AFC_TEMP, "r"); status = convert_to_utf8(fp, fpreal); if(status != 0) { D("Conversion to UTF8 Failed"); ret = 1; } else { ret = 0; } fclose(fpreal); fclose(fp); response.memory = NULL; response.size = 0; fp = fopen(AFC_TEMP, "w+"); fpreal = fopen(AFC_ALLTIMECSV,"w+"); curl_easy_setopt(curl, CURLOPT_URL, AFC_ALLTIME_REPORT_URL); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); status = curl_easy_perform(curl); if(status != 0) { D("curl error: unable to send data to AFC_ALLTIME_REPORT_URL\n"); D("%s\n", curl_easy_strerror(status)); ret = status; goto cleanup; } fclose(fp); fp = fopen(AFC_TEMP, "r"); status = convert_to_utf8(fp, fpreal); if(status != 0) { D("Conversion to UTF8 Failed"); ret = 1; } else { ret = 0; } fclose(fpreal); fclose(fp); ret = 0; cleanup: free(response.memory); return ret; } <file_sep>/project/jni/adsensejni.h #ifndef _ADSENSECLIENT_CURL_H #define _ADSENSECLIENT_CURL_H #include "curl/curl.h" #include "curl/easy.h" #define DEBUG 1 #if DEBUG #include <android/log.h> # define D(x...) __android_log_print(ANDROID_LOG_INFO,"adsenseclient",x) #else # define D(...) do {} while (0) #endif #define COOKIEFILE "/sdcard/humbug_adsense_client/cookies.txt" struct write_result { char *memory; size_t size; }; /* Messages */ #define ADSENSE_USERNAME_PASSWORD_INCORRECT "The username or password you entered is incorrect." #define ADSENSE_VERIFY_LOGIN_STRING "<a href=\"/adsense/signout\">" /* File Names */ #define AFC_CSV "/sdcard/humbug_adsense_client/afc.csv" #define AFC_TODAYCSV "/sdcard/humbug_adsense_client/afc_today.csv" #define AFC_YESTERDAYCSV "/sdcard/humbug_adsense_client/afc_yesterday.csv" #define AFC_LAST7DAYSCSV "/sdcard/humbug_adsense_client/afc_last7days.csv" #define AFC_THISMONTHCSV "/sdcard/humbug_adsense_client/afc_thismonth.csv" #define AFC_LASTMONTHCSV "/sdcard/humbug_adsense_client/afc_lastmonth.csv" #define AFC_ALLTIMECSV "/sdcard/humbug_adsense_client/afc_alltime.csv" #define AFC_TEMP "/sdcard/humbug_adsense_client/afc_temp.csv" /* URLS */ #define ADSENSE_LOGIN_URL "https://www.google.com/accounts/ServiceLoginBox?service=adsense&ltmpl=login&ifr=true&rm=hide&fpui=3&nui=15&alwf=true&passive=true&continue=https%3A%2F%2Fwww.google.com%2Fadsense%2Flogin-box-gaiaauth&followup=https%3A%2F%2Fwww.google.com%2Fadsense%2Flogin-box-gaiaauth&hl=en_US" #define ADSENSE_LOGIN_URL_STAGE2 "https://www.google.com/accounts/ServiceLoginBoxAuth" #define ADSENSE_LOGIN_URL_STAGE3 "https://www.google.com/accounts/CheckCookie?continue=https%3A%2F%2Fwww.google.com%2Fadsense%2Flogin-box-gaiaauth&followup=https%3A%2F%2Fwww.google.com%2Fadsense%2Flogin-box-gaiaauth&hl=en_US&service=adsense&ltmpl=login&chtml=LoginDoneHtml" #define ADSENSE_LOGIN_URL_STAGE4 "https://www.google.com/adsense" #define ADSENSE_LOGIN_URL_STAGE2_PARAMS "continue=https://www.google.com/adsense/login-box-gaiaauth&followup=https://www.google.com/adsense/login-box-gaiaauth&service=adsense&nui=15&fpui=3&ifr=true&rm=hide&ltmpl=login&hl=en_US&alwf=true" #define AFC_TODAY_REPORT_URL "https://www.google.com/adsense/report/aggregate?product=afc&dateRange.dateRangeType=simple&dateRange.simpleDate=today&reportType=property&groupByPref=date&outputFormat=TSV_EXCEL&unitPref=page" #define AFC_YESTERDAY_REPORT_URL "https://www.google.com/adsense/report/aggregate?product=afc&dateRange.dateRangeType=simple&dateRange.simpleDate=yesterday&reportType=property&groupByPref=date&outputFormat=TSV_EXCEL&unitPref=page" #define AFC_LAST7DAYS_REPORT_URL "https://www.google.com/adsense/report/aggregate?product=afc&dateRange.dateRangeType=simple&dateRange.simpleDate=last7days&reportType=property&groupByPref=date&outputFormat=TSV_EXCEL&unitPref=page" #define AFC_THISMONTH_REPORT_URL "https://www.google.com/adsense/report/aggregate?product=afc&dateRange.dateRangeType=simple&dateRange.simpleDate=thismonth&reportType=property&groupByPref=date&outputFormat=TSV_EXCEL&unitPref=page" #define AFC_LASTMONTH_REPORT_URL "https://www.google.com/adsense/report/aggregate?product=afc&dateRange.dateRangeType=simple&dateRange.simpleDate=lastmonth&reportType=property&groupByPref=date&outputFormat=TSV_EXCEL&unitPref=page" #define AFC_ALLTIME_REPORT_URL "https://www.google.com/adsense/report/aggregate?product=afc&dateRange.dateRangeType=simple&dateRange.simpleDate=alltime&reportType=property&groupByPref=date&outputFormat=TSV_EXCEL&unitPref=page" /* RE */ static char *GmailRe = "input type=\"hidden\" name=\"GALX\" value=\"[^\"]*\""; int curl_local_init(void); int adsense_login(const char *, const char *); int get_adsense_reports(void); void process_adsense_reports(void); CURL *curl; extern CURL *curl; #endif /* _ADSENSECLIENT_CURL_H */ <file_sep>/project/jni/urlcode.h #ifndef _URLCODE_H #define _URLCODE_H char from_hex(char ch); char to_hex(char code); char *url_encode(char *str); char *url_decode(char *str); #endif /* _URLCODE_H */ <file_sep>/project/src/in/humbug/adsenseclient/AccountSetupBasics.java package in.humbug.adsenseclient; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class AccountSetupBasics extends Activity implements OnClickListener { private EditText mEmailView; private EditText mPasswordView; private Button mNextButton; String TAG = "AdsenseSetupBasics"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_basics); mEmailView = (EditText)findViewById(R.id.account_email); mPasswordView = (EditText)findViewById(R.id.account_password); mNextButton = (Button)findViewById(R.id.next); String email = getSp().getString("email", null); String password = getSp().getString("password", null); if (email != null) mEmailView.setText(email); if (password != null) mPasswordView.setText(password); mNextButton.setOnClickListener(this); } public void onClick(View v) { switch (v.getId()) { case R.id.next: onNext(); break; } } private void onNext() { String email = mEmailView.getText().toString().trim(); String password = mPasswordView.getText().toString().trim(); SharedPreferences preferences = getSp(); Editor e = preferences.edit(); e.putString("email", email); e.putString("password", password); e.putInt("verified", 0); e.putInt("refresh", 0); e.commit(); startActivity(new Intent(AccountSetupBasics.this, AccountSetupCheckSettings.class)); return; } private SharedPreferences getSp() { return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); } }
447212ef30d1cc22661c581feba05c6b120faeec
[ "Java", "C", "Makefile" ]
11
C
freethinker/adsenseclient
6691085f62245d132146f1145219099628322fa9
b4aa403fc4bb18355d118dcfa1b411f78796b460
refs/heads/master
<repo_name>webmapsolutions/MapQuest-Customizable-Mobile-App<file_sep>/mobile_app/js/custom.js $(document).ready(function(){ $('.view_select').click(function(){ var list_w = $(this).attr('list_w'); var map_w = $(this).attr('map_w'); var list_left = $(this).attr('list_left'); var map_left = $(this).attr('map_left'); //if(list_left >= 0) $('#list').show(); $('#map_container').animate({width:map_w+"%", left:map_left+"%"}, 500, function(){ window.map.setSize(); $('#map').css('width', $('#map_container').width()+'px'); $('#map div:first').css('width', $('#map_container').width()+'px'); window.map.setSize(); }); $('#list_container').animate({width:list_w+"%", left:list_left+"%"}, 500, function(){ //if(list_left < 0) $('#list').hide(); }); }); MQA.EventUtil.observe(window, 'load', function() { var options={ elt:document.getElementById('map'), /*ID of element on the page where you want the map added*/ zoom:10, /*initial zoom level of the map*/ latLng:{lat:39.743943, lng:-105.020089}, /*center of map in latitude/longitude */ mtype:'map', /*map type (map)*/ bestFitMargin:0, /*margin offset from the map viewport when applying a bestfit on shapes*/ zoomOnDoubleClick:true /*zoom in when double-clicking on map*/ }; /*Construct an instance of MQA.TileMap with the options object*/ map = new MQA.TileMap(options); MQA.withModule('largezoom','traffictoggle','viewoptions','geolocationcontrol','insetmapcontrol','mousewheel', function() { map.addControl( new MQA.LargeZoom(), new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(5,5)) ); map.addControl(new MQA.TrafficToggle()); map.addControl(new MQA.ViewOptions()); map.addControl( new MQA.GeolocationControl(), new MQA.MapCornerPlacement(MQA.MapCorner.TOP_RIGHT, new MQA.Size(10,50)) ); /*Inset Map Control options*/ var options={ size:{width:150, height:125}, zoom:3, mapType:'map', minimized:true }; map.addControl( new MQA.InsetMapControl(options), new MQA.MapCornerPlacement(MQA.MapCorner.BOTTOM_RIGHT) ); map.enableMouseWheelZoom(); }); }); }); $(function() { $(".ajax_call").click(function() { var arr = this.attributes, attributes = []; var params = new Object; for(index in arr) { if(!isNaN(index)) params[arr[index]['name']] = arr[index]['value']; } $.ajax({ type: "GET", url: "details.php", data: params, cache: false, dataType: "text", success: function(data){ $(params['result']).html(data); } }); }); if(typeof params !== 'undefined') { $(params['result']).ajaxError(function(event, request, settings, exception) { $(params['result']).html("Error Calling: " + settings.url + "<br />HTPP Code: " + request.status); }); } }); <file_sep>/README.md MapQuest-Customizable-Mobile-App ================================<file_sep>/js/script.js $(document).ready(function(){ // MAP RATIO SLIDER var basicUpdateMapRatio = function(val) { //$(".map", "#basic > .demo").css("width", val+"%"); var pos = $("[name=basic_resultposition]:checked").val(); switch(pos) { case "left": case "right": //$(".map", "#basic > .demo").css(pos, (100-val)+"%"); $(".details", "#basic > .demo").css("width", (100-val)+"%"); break; case "bottom": $(".map", "#basic > .demo").width("100%"); $(".details", "#basic > .demo").width("100%"); $(".map", "#basic > .demo").css("width", "100%"); $(".details", "#basic > .demo").css("width", "100%"); break; } } generateSlider("#basic_mapratio", 0, 100, 60, basicUpdateMapRatio); // POSITION OF MAP AND DETAILS $("[name=basic_resultposition]").change(function(){ var pos = $("[name=basic_resultposition]:checked").val(); updateDetailsPosition(pos); }); function updateDetailsPosition(pos) { // reset current styles $(".details", "#basic > .demo").css("left", "").css("right", ""); $(".map", "#basic > .demo").css("left", "").css("right", ""); $(".details", "#basic > .demo").removeClass("dockleft").removeClass("dockright").removeClass("dockbottom"); switch(pos) { case "left": $(".details", "#basic > .demo").css("left", "0px"); $(".details", "#basic > .demo").addClass("dockleft"); $(".map", "#basic > .demo").width("100%"); basicUpdateMapRatio($("#basic_mapratio").slider("value")); break; case "right": $(".details", "#basic > .demo").css("right", "0px"); $(".details", "#basic > .demo").addClass("dockright"); $(".map", "#basic > .demo").width("100%"); basicUpdateMapRatio($("#basic_mapratio").slider("value")); break; case "bottom": $(".map", "#basic > .demo").css("left", "0px").width("100%"); $(".details", "#basic > .demo").addClass("dockbottom"); $(".map", "#basic > .demo").width("100%"); basicUpdateMapRatio($("#basic_mapratio").slider("value")); break; } } updateDetailsPosition($("[name=basic_resultposition]:checked").val()); // SIDEBAR OPACITY SLIDER var basicUpdateSidebarOpacity = function(val) { $(".details", "#basic").css('opacity', val/100); } generateSlider("#basic_sidebaropacity", 0, 100, 75, basicUpdateSidebarOpacity); // LOCATOR HEIGHT SLIDER var basicUpdateMapHeight = function(val) { $(".demo", "#basic").height(val); } generateSlider("#basic_locatorheight", 100, 900, 400, basicUpdateMapHeight); // LOCATOR WIDTH SLIDER var basicUpdateMapWidth = function(val) { $(".demo", "#basic").width(val); } generateSlider("#basic_locatorwidth", 100, 1100, 600, basicUpdateMapWidth); // ROUNDED CORNERS var basicUpdateRoundCorners = function(val) { $(".demo", "#basic").css("border-radius", val + "px"); $(".header", "#basic > .demo").css("border-top-left-radius", val + "px"); $(".header", "#basic > .demo").css("border-top-right-radius", val + "px"); $(".footer", "#basic > .demo").css("border-bottom-left-radius", val + "px"); $(".footer", "#basic > .demo").css("border-bottom-right-radius", val + "px"); } generateSlider("#basic_roundcorners", 0, 40, 5, basicUpdateRoundCorners); // SIDEBAR COLOR var initial_color = '#f1ede3'; $(".details", "#basic > .demo").css("backgroundColor", initial_color); $('#basic_sidebarcolorpicker').attr('data-color', initial_color); $('input', '#basic_sidebarcolorpicker').attr('value', initial_color); $('#basic_sidebarcolorpicker').colorpicker({ format: 'hex' }).on('changeColor', function(ev){ $(".details", "#basic > .demo").css("backgroundColor", ev.color.toHex()); $("#basic_sidebarcolor").attr('value', ev.color.toHex()); }); // SIDEBAR SHADOW var basicUpdateShadow = function(val) { var shadowStyle = $("#basic_shadowhoffsetamount").val() + 'px ' + $("#basic_shadowvoffsetamount").val() + 'px ' + $("#basic_shadowbluramount").val() + 'px ' + $("#basic_shadowspreadamount").val() + 'px #000'; $(".details", "#basic").css('boxShadow', shadowStyle); } generateSlider("#basic_shadowhoffset", -15, 15, 0, basicUpdateShadow); generateSlider("#basic_shadowvoffset", -15, 15, 0, basicUpdateShadow); generateSlider("#basic_shadowblur", 0, 25, 10, basicUpdateShadow); generateSlider("#basic_shadowspread", -15, 15, 0, basicUpdateShadow); function generateSlider(sliderId, min, max, val, updateFunction) { $(sliderId).slider({ orientation: "horizontal", range: "min", min: min, max: max, value: val, slide: function (event, ui) { $(sliderId+"amount").val(ui.value); updateFunction(ui.value); } }); $(sliderId+"amount").val($(sliderId).slider("value")); $(sliderId+"amount").change(function(){ $(sliderId).slider("value", $(sliderId+"amount").val()); updateFunction($(sliderId+"amount").val()); }); updateFunction($(sliderId).slider("value")); // display initial value } }); <file_sep>/mobile_app/index.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Multi-page template</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" /> <link rel="stylesheet" href="css/custom.css" /> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script> <script src="http://www.mapquestapi.com/sdk/js/v7.0.s/mqa.toolkit.js?key=<KEY>"></script> <script src="js/custom.js"></script> </head> <body> <!-- Start of first page: #main --> <div data-role="page" id="main"> <div data-role="header"> <?php Layout::NavMenu(); ?> </div><!-- /header --> <div data-role="content" > <h2>Map/List</h2> <div id="webmap_container"> <div id="list_container"> <ul id="list" data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b"> <li data-role="list-divider">Overview</li> <li><a class="ajax_call" href="#details" result="#ajaxResult">Intro to jQuery Mobile</a></li> <li><a class="ajax_call" href="#details" result="#ajaxResult">Features</a></li> <li><a class="ajax_call" href="#details" result="#ajaxResult">Accessibility</a></li> <li><a class="ajax_call" href="#details" result="#ajaxResult">Supported platforms</a></li> </ul> </div> <div id="map_container"> <div id="map"></div> </div> </div> </div><!-- /content --> <div data-role="footer" data-theme="d"> <h4>Page Footer</h4> </div><!-- /footer --> </div><!-- /page main --> <!-- Start of second page: #details --> <div data-role="page" id="details" data-theme="d"> <div data-role="header"> <?php Layout::NavMenu(); ?> </div><!-- /header --> <div data-role="content" data-theme="d"> <h2>Location Details</h2> <div id="ajaxResult"></div> <p><a href="#main" data-direction="reverse" data-role="button" data-theme="b">Back to map/list</a></p> </div><!-- /content --> <div data-role="footer" data-theme="d"> <h4>Page Footer</h4> </div><!-- /footer --> </div><!-- /page details --> </body> </html> <?php class Layout { static function NavMenu() { ?> <div class="view_select" list_w="30" map_w="100" list_left="-30" map_left="0"><a data-role="button">map</a></div> <div class="view_select" list_w="30" map_w="70" list_left="0" map_left="30"><a data-role="button">map/list</a></div> <div class="view_select" list_w="100" map_w="70" list_left="0" map_left="100"><a data-role="button">list</a></div> <div class="clear"></div> <?php } } ?>
92ee263163e5a5617a935e587d8ce4ba8a97affd
[ "JavaScript", "PHP", "Markdown" ]
4
JavaScript
webmapsolutions/MapQuest-Customizable-Mobile-App
ff879046c2e05293344ca5ce52918207e48c2956
58d37277ea89114c6153cf01431d63442da08990
refs/heads/master
<repo_name>zettajs/zetta-sphero-driver<file_sep>/README.md # Sphero Zetta Driver [Zetta](http://zettajs.io) device package for Sphero Driver. ## Install ``` npm install zetta-sphero-driver ``` ## Usage ```js var zetta = require('zetta'); var Sphero = require('zetta-sphero-driver'); zetta() .expose('*') .use(Sphero) .listen(3000, function(err) { console.log('Listening on http://localhost:3000/'); }); // or specify port zetta() .expose('*') .use(Sphero, '/dev/rfcomm0') .listen(3000, function(err) { console.log('Listening on http://localhost:3000/'); }); ``` ## License MIT <file_sep>/sphero.js var util = require('util'); var Device = require('zetta').Device; function getColor(c) { var color = c.match(/[0-9a-fA-F]{1,2}/g); while (color.length < 3) { color.push('00'); } color = parseInt(color.join(''), 16); return color; } var Sphero = module.exports = function(sphero) { Device.call(this); this.color = 'none'; this._sphero = sphero; }; util.inherits(Sphero, Device); Sphero.prototype.init = function(config) { config .type('sphero') .name('Sphero') .state('online') .when('online', { allow: ['set-color','move', 'left', 'right', 'random-color'] }) .when('moving', { allow: [] }) .map('set-color', this.setColor, [{name: 'color', type: 'color'}]) .map('move', this.move, [{name: 'time', type:'number'}]) .map('random-color', this.randomColor) .map('left', this.turnLeft) .map('right', this.turnRight); var self = this; this._sphero.on('end', function() { self.state = 'offline'; }); this._sphero.on('error', function(err) { self.state = 'offline'; }); }; Sphero.prototype.randomColor = function(cb) { var color = Math.floor(Math.random() * Math.pow(2, 24)); this.color = '#' + color.toString(16); this._sphero.setColor(color); cb(); }; Sphero.prototype.setColor = function(colorStr, cb) { var color = getColor(colorStr); this.color = colorStr; this._sphero.setColor(color); cb(); }; Sphero.prototype.move = function(time, cb) { this._sphero.forward(time); cb(); }; Sphero.prototype.turnLeft = function(cb) { this._sphero.left(); cb(); }; Sphero.prototype.turnRight = function(cb) { this._sphero.right(); cb(); }; <file_sep>/index.js var util = require('util'); var Scout = require('zetta').Scout; var simpleSphero = require('simple-sphero'); var serialport = require('serialport'); var Sphero = require('./sphero'); var SpheroScout = module.exports = function(port) { Scout.call(this); this.port = port; }; util.inherits(SpheroScout, Scout); SpheroScout.prototype.init = function(cb){ if (!this.port) { this.searchPorts(); } else { this.initDevice(this.port); } cb(); }; SpheroScout.prototype.searchPorts = function() { var self = this; serialport.list(function(err, ports) { ports.forEach(function(port) { if(port.comName.search('Sphero') !== -1) { self.initDevice(port.comName); } }); }); }; SpheroScout.prototype.initDevice = function(port) { var self = this; var hubQuery = self.server.where({ type: 'sphero' }); var sphero = simpleSphero(port); sphero._sphero = require('simple-sphero').sphero; sphero.on('ready', function() { sphero._sphero.resetTimeout(true); // helps keep bluetooth from disconnecting self.server.find(hubQuery, function(err, results){ if (results.length > 0) { self.provision(results[0], Sphero, sphero); } else { self.discover(Sphero, sphero); } }); }); };
2724b9b46fcd9e0eca57ef2485654b6174417239
[ "Markdown", "JavaScript" ]
3
Markdown
zettajs/zetta-sphero-driver
5853cdb9c8166d22a47409287d76a8e8f7063236
6423f4bd5037dbbf5d170f2c53a93487afd3bf26
refs/heads/main
<repo_name>sayah-rouas88/raqin<file_sep>/raqin-api/go.mod module raqin-api go 1.15 require ( github.com/labstack/echo/v4 v4.2.1 github.com/stretchr/testify v1.7.0 // indirect golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 // indirect ) <file_sep>/raqin-api/api/router/admin_routes.go package router import ( "net/http" "github.com/labstack/echo/v4" ) // InitAdminRouter will register all admin routes // هنا نعرف وجهات المستخدم المتحكم كالمثال الموجود func InitAdminRouter(clientRouter *echo.Group) { // profile route وجهة الصفحة الشخصية للمتحكم clientRouter.GET("/profile", func(c echo.Context) error { return c.String(http.StatusOK, "Hello, World from Admin!") }) } <file_sep>/raqin-api/api/router/router.go /* هنا نقطة عرف الوجهات اﻷساسية للـ API ثم قم بتعريف الوجهات التي تندرج تحتها كلٌ في ملفه الخاص */ package router import ( "github.com/labstack/echo/v4" ) // InitRouter starts the router // الدالة التي تقوم بتسجيل وتعريف الوجهات func InitRouter(e *echo.Echo) { // this group will have all client routes // عرف وجهة المستخدم العادي هنا ثم اضف مايندرج تحته في ملفه الخاص كالمثال الموجود // انظر الى ملف client_routes.go clientRouter := e.Group("/client") InitClientRouter(clientRouter) // this group will have all client routes // عرف وجهة المستخدم المتحكم هنا ثم اضف مايندرج تحته في ملفه الخاص كالمثال الموجود // انظر الى ملف admin_routes.go adminRouter := e.Group("/admin") InitAdminRouter(adminRouter) } <file_sep>/raqin-api/cmd/main.go /* هنا نقطة البدأ للبرنامج بأكمله */ package main import rest "raqin-api/api" func main() { // نستدعي الدالة الرئيسية لتشغيل الموجه rest.Init() } <file_sep>/raqin-api/core/service/service.go /* هنا نقوم بالعمل المرتبط بهدف البرنامج business logic will be in this package */ package service <file_sep>/raqin-api/core/controller/controller.go /* نقوم هنا بفحص البيانات القادمة من الموجه ثم نمررها اذا كانت لا مشكلة فيها */ package controller
a130c0cf40a3fb2e032ae2ec693ac25d11038df1
[ "Go", "Go Module" ]
6
Go Module
sayah-rouas88/raqin
f396ffeb95b4c677c8e3169786f373f50c42ef77
928f06933a7777104f37974e2946fecc6ad332bb
refs/heads/master
<file_sep><?php /** * PHP Exif Reader Adapter Abstract: Common functionality for adapters * * @link http://github.com/miljar/PHPExif for the canonical source repository * @copyright Copyright (c) 2013 <NAME> <<EMAIL>> * @license http://github.com/miljar/PHPExif/blob/master/LICENSE MIT License * @category PHPExif * @package Reader */ namespace PHPExif\Reader; /** * PHP Exif Reader Adapter Abstract * * Implements common functionality for the reader adapters * * @category PHPExif * @package Reader */ abstract class AdapterAbstract implements AdapterInterface { /** * Class constructor * * @param array $data Optional array of data to initialize the object with */ public function __construct(array $options = array()) { if (!empty($options)) { $this->setOptions($options); } } /** * Set array of options in the current object * * @param array $options * @return \PHPExif\Reader\AdapterAbstract */ public function setOptions(array $options) { foreach ($options as $property => $value) { $setter = $this->determinePropertySetter($property); if (method_exists($this, $setter)) { $this->$setter($value); } } return $this; } /** * Detemines the name of the getter method for given property name * * @param string $property The property to determine the getter for * @return string The name of the getter method */ protected function determinePropertyGetter($property) { $method = 'get' . ucfirst($property); return $method; } /** * Detemines the name of the setter method for given property name * * @param string $property The property to determine the setter for * @return string The name of the setter method */ protected function determinePropertySetter($property) { $method = 'set' . ucfirst($property); return $method; } /** * Get a list of the class constants prefixed with given $type * * @param string $type * @return array */ public function getClassConstantsOfType($type) { $class = new \ReflectionClass(get_called_class()); $constants = $class->getConstants(); $list = array(); $type = strtoupper($type) . '_'; foreach ($constants as $key => $value) { if (strpos($key, $type) === 0) { $list[$key] = $value; } } return $list; } /** * Returns an array notation of current instance * * @return array */ public function toArray() { $rc = new \ReflectionClass(get_class($this)); $properties = $rc->getProperties(); $arrResult = array(); foreach ($properties as $rp) { /* @var $rp \ReflectionProperty */ $getter = $this->determinePropertyGetter($rp->getName()); if (!method_exists($this, $getter)) { continue; } $arrResult[$rp->getName()] = $this->$getter(); } return $arrResult; } } <file_sep><?php /** * PHP Exif Exiftool Reader Adapter * * @link http://github.com/miljar/PHPExif for the canonical source repository * @copyright Copyright (c) 2013 <NAME> <<EMAIL>> * @license http://github.com/miljar/PHPExif/blob/master/LICENSE MIT License * @category PHPExif * @package Reader */ namespace PHPExif\Reader\Adapter; use PHPExif\Reader\AdapterAbstract; use PHPExif\Exif; use \InvalidArgumentException; use \RuntimeException; use \DateTime; /** * PHP Exif Exiftool Reader Adapter * * Uses native PHP functionality to read data from a file * * @category PHPExif * @package Reader */ class Exiftool extends AdapterAbstract { const TOOL_NAME = 'exiftool'; /** * Path to the exiftool binary * * @var string */ protected $toolPath; /** * Setter for the exiftool binary path * * @param string $path The path to the exiftool binary * @return \PHPExif\Reader\Adapter\Exiftool Current instance * @throws \InvalidArgumentException When path is invalid */ public function setToolPath($path) { if (!file_exists($path)) { throw new InvalidArgumentException( sprintf( 'Given path (%1$s) to the exiftool binary is invalid', $path ) ); } $this->toolPath = $path; return $this; } /** * Getter for the exiftool binary path * Lazy loads the "default" path * * @return string */ public function getToolPath() { if (empty($this->toolPath)) { $path = exec('which ' . self::TOOL_NAME); $this->setToolPath($path); } return $this->toolPath; } /** * Reads & parses the EXIF data from given file * * @param string $file * @return \PHPExif\Exif Instance of Exif object with data * @throws \RuntimeException If the EXIF data could not be read */ public function getExifFromFile($file) { $result = $this->getCliOutput( sprintf( '%1$s -j %2$s', $this->getToolPath(), $file ) ); $data = json_decode($result, true); $mappedData = $this->mapData(reset($data)); $exif = new Exif($mappedData); return $exif; } /** * Returns the output from given cli command * * @param string $command * @return mixed * @throws RuntimeException If the command can't be executed */ protected function getCliOutput($command) { $descriptorspec = array( 0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'a') ); $process = proc_open($command, $descriptorspec, $pipes); if (!is_resource($process)) { throw new RuntimeException( 'Could not open a resource to the exiftool binary' ); } $result = stream_get_contents($pipes[1]); fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]); proc_close($process); return $result; } /** * Maps native data to Exif format * * @param array $source * @return array */ public function mapData(array $source) { $focalLength = false; if (isset($source['FocalLength'])) { $focalLengthParts = explode(' ', $source['FocalLength']); $focalLength = (int) reset($focalLengthParts); } return array( Exif::APERTURE => (!isset($source['Aperture'])) ? false : sprintf('f/%01.1f', $source['Aperture']), Exif::AUTHOR => false, Exif::CAMERA => (!isset($source['Model'])) ? false : $source['Model'], Exif::CAPTION => false, Exif::COLORSPACE => (!isset($source[Exif::COLORSPACE]) ? false : $source[Exif::COLORSPACE]), Exif::COPYRIGHT => false, Exif::CREATION_DATE => (!isset($source['CreateDate'])) ? false : DateTime::createFromFormat('Y:m:d H:i:s', $source['CreateDate']), Exif::CREDIT => false, Exif::EXPOSURE => (!isset($source['ShutterSpeed'])) ? false : $source['ShutterSpeed'], Exif::FILESIZE => false, Exif::FOCAL_LENGTH => $focalLength, Exif::FOCAL_DISTANCE => (!isset($source['ApproximateFocusDistance'])) ? false : sprintf('%1$sm', $source['ApproximateFocusDistance']), Exif::HEADLINE => false, Exif::HEIGHT => (!isset($source['ImageHeight'])) ? false : $source['ImageHeight'], Exif::HORIZONTAL_RESOLUTION => (!isset($source['XResolution'])) ? false : $source['XResolution'], Exif::ISO => (!isset($source['ISO'])) ? false : $source['ISO'], Exif::JOB_TITLE => false, Exif::KEYWORDS => (!isset($source['Keywords'])) ? false : $source['Keywords'], Exif::MIMETYPE => false, Exif::SOFTWARE => (!isset($source['Software'])) ? false : $source['Software'], Exif::SOURCE => false, Exif::TITLE => (!isset($source['Title'])) ? false : $source['Title'], Exif::VERTICAL_RESOLUTION => (!isset($source['YResolution'])) ? false : $source['YResolution'], Exif::WIDTH => (!isset($source['ImageWidth'])) ? false : $source['ImageWidth'], ); } } <file_sep><?php class AdapterAbstractTest extends \PHPUnit_Framework_TestCase { /** * @var \PHPExif\Reader\Adapter\Exiftool */ protected $adapter; public function setUp() { $this->adapter = new \PHPExif\Reader\Adapter\Native(); } /** * @group adapter * @covers \PHPExif\Reader\AdapterAbstract::determinePropertyGetter */ public function testDeterminePropertyGetter() { $reflMethod = new \ReflectionMethod('\PHPExif\Reader\Adapter\Native', 'determinePropertyGetter'); $reflMethod->setAccessible(true); $result = $reflMethod->invoke( $this->adapter, 'foo' ); $this->assertEquals('getFoo', $result); } /** * @group adapter * @covers \PHPExif\Reader\AdapterAbstract::determinePropertySetter */ public function testDeterminePropertySetter() { $reflMethod = new \ReflectionMethod('\PHPExif\Reader\Adapter\Native', 'determinePropertySetter'); $reflMethod->setAccessible(true); $result = $reflMethod->invoke( $this->adapter, 'foo' ); $this->assertEquals('setFoo', $result); } /** * @group adapter * @covers \PHPExif\Reader\AdapterAbstract::getClassConstantsOfType */ public function testGetClassConstantsOfTypeAlwaysReturnsArray() { $result = $this->adapter->getClassConstantsOfType('sections'); $this->assertInternalType('array', $result); $result = $this->adapter->getClassConstantsOfType('foo'); $this->assertInternalType('array', $result); } /** * @group adapter * @covers \PHPExif\Reader\AdapterAbstract::getClassConstantsOfType */ public function testGetClassConstantsOfTypeReturnsCorrectData() { $expected = array( 'SECTIONS_AS_ARRAYS' => \PHPExif\Reader\Adapter\Native::SECTIONS_AS_ARRAYS, 'SECTIONS_FLAT' => \PHPExif\Reader\Adapter\Native::SECTIONS_FLAT, ); $actual = $this->adapter->getClassConstantsOfType('sections'); $this->assertEquals($expected, $actual); } /** * @group adapter * @covers \PHPExif\Reader\AdapterAbstract::toArray */ public function testToArrayReturnsPropertiesWithGetters() { $expected = array( 'requiredSections', 'includeThumbnail', 'sectionsAsArrays', ); $result = $this->adapter->toArray(); $actual = array_keys($result); $this->assertEquals($expected, $actual); } /** * @group adapter * @covers \PHPExif\Reader\AdapterAbstract::toArray */ public function testToArrayOmmitsPropertiesWithoutGetters() { $expected = array( 'iptcMapping', ); $result = $this->adapter->toArray(); $actual = array_keys($result); $diff = array_diff($expected, $actual); $this->assertEquals($expected, $diff); } /** * @group adapter * @covers \PHPExif\Reader\AdapterAbstract::setOptions */ public function testSetOptionsReturnsCurrentInstance() { $result = $this->adapter->setOptions(array()); $this->assertSame($this->adapter, $result); } /** * @group adapter * @covers \PHPExif\Reader\AdapterAbstract::setOptions */ public function testSetOptionsCorrectlySetsProperties() { $expected = array( 'requiredSections' => array('foo', 'bar', 'baz',), 'includeThumbnail' => \PHPExif\Reader\Adapter\Native::INCLUDE_THUMBNAIL, 'sectionsAsArrays' => \PHPExif\Reader\Adapter\Native::SECTIONS_AS_ARRAYS, ); $this->adapter->setOptions($expected); foreach ($expected as $key => $value) { $reflProp = new \ReflectionProperty('\PHPExif\Reader\Adapter\Native', $key); $reflProp->setAccessible(true); $this->assertEquals($value, $reflProp->getValue($this->adapter)); } } /** * @group adapter * @covers \PHPExif\Reader\AdapterAbstract::setOptions */ public function testSetOptionsIgnoresPropertiesWithoutSetters() { $expected = array( 'iptcMapping' => array('foo', 'bar', 'baz'), ); $this->adapter->setOptions($expected); foreach ($expected as $key => $value) { $reflProp = new \ReflectionProperty('\PHPExif\Reader\Adapter\Native', $key); $reflProp->setAccessible(true); $this->assertNotEquals($value, $reflProp->getValue($this->adapter)); } } /** * @group adapter * @covers \PHPExif\Reader\AdapterAbstract::__construct */ public function testConstructorSetsOptions() { $expected = array( 'requiredSections' => array('foo', 'bar', 'baz',), 'includeThumbnail' => \PHPExif\Reader\Adapter\Native::INCLUDE_THUMBNAIL, 'sectionsAsArrays' => \PHPExif\Reader\Adapter\Native::SECTIONS_AS_ARRAYS, ); $adapter = new \PHPExif\Reader\Adapter\Native($expected); foreach ($expected as $key => $value) { $reflProp = new \ReflectionProperty('\PHPExif\Reader\Adapter\Native', $key); $reflProp->setAccessible(true); $this->assertEquals($value, $reflProp->getValue($adapter)); } } } <file_sep><?php class ReaderTest extends \PHPUnit_Framework_TestCase { /** * @var \PHPExif\Reader */ protected $reader; /** * Setup function before the tests */ public function setUp() { $this->reader = new \PHPExif\Reader(); } /** * @group reader * @covers \PHPExif\Reader::setAdapter */ public function testSetAdapterInProperty() { $mock = $this->getMock('\PHPExif\Reader\AdapterInterface'); $reflProperty = new \ReflectionProperty('\PHPExif\Reader', 'adapter'); $reflProperty->setAccessible(true); $this->assertNull($reflProperty->getValue($this->reader)); $this->reader->setAdapter($mock); $this->assertSame($mock, $reflProperty->getValue($this->reader)); } /** * @group reader * @covers \PHPExif\Reader::__construct */ public function testConstructorWithAdapter() { $mock = $this->getMock('\PHPExif\Reader\AdapterInterface'); $reflProperty = new \ReflectionProperty('\PHPExif\Reader', 'adapter'); $reflProperty->setAccessible(true); $reader = new \PHPExif\Reader($mock); $this->assertSame($mock, $reflProperty->getValue($reader)); } /** * @group reader * @covers \PHPExif\Reader::getAdapter */ public function testGetAdapterFromProperty() { $mock = $this->getMock('\PHPExif\Reader\AdapterInterface'); $reflProperty = new \ReflectionProperty('\PHPExif\Reader', 'adapter'); $reflProperty->setAccessible(true); $reflProperty->setValue($this->reader, $mock); $this->assertSame($mock, $this->reader->getAdapter()); } /** * @group reader * @covers \PHPExif\Reader::getAdapter * @expectedException \PHPExif\Reader\NoAdapterException */ public function testGetAdapterThrowsException() { $this->reader->getAdapter(); } /** * @group reader * @covers \PHPExif\Reader::getExifFromFile */ public function testGetExifPassedToAdapter() { $mock = $this->getMock('\PHPExif\Reader\AdapterInterface'); $mock->expects($this->once()) ->method('getExifFromFile'); $reflProperty = new \ReflectionProperty('\PHPExif\Reader', 'adapter'); $reflProperty->setAccessible(true); $reflProperty->setValue($this->reader, $mock); $this->reader->getExifFromFile('/tmp/foo.bar'); } /** * @group reader * @covers \PHPExif\Reader::factory * @expectedException InvalidArgumentException */ public function testFactoryThrowsException() { \PHPExif\Reader::factory('foo'); } /** * @group reader * @covers \PHPExif\Reader::factory */ public function testFactoryReturnsCorrectType() { $reader = \PHPExif\Reader::factory(\PHPExif\Reader::TYPE_NATIVE); $this->assertInstanceOf('\PHPExif\Reader', $reader); } /** * @group reader * @covers \PHPExif\Reader::factory */ public function testFactoryAdapterTypeNative() { $reader = \PHPExif\Reader::factory(\PHPExif\Reader::TYPE_NATIVE); $reflProperty = new \ReflectionProperty('\PHPExif\Reader', 'adapter'); $reflProperty->setAccessible(true); $adapter = $reflProperty->getValue($reader); $this->assertInstanceOf('\PHPExif\Reader\Adapter\Native', $adapter); } /** * @group reader * @covers \PHPExif\Reader::factory */ public function testFactoryAdapterTypeExiftool() { $reader = \PHPExif\Reader::factory(\PHPExif\Reader::TYPE_EXIFTOOL); $reflProperty = new \ReflectionProperty('\PHPExif\Reader', 'adapter'); $reflProperty->setAccessible(true); $adapter = $reflProperty->getValue($reader); $this->assertInstanceOf('\PHPExif\Reader\Adapter\Exiftool', $adapter); } } <file_sep><?php class ExifTest extends \PHPUnit_Framework_TestCase { /** * @var \PHPExif\Exif */ protected $exif; /** * Setup function before the tests */ public function setUp() { $this->exif = new \PHPExif\Exif(); } /** * @group exif */ public function testGetRawData() { $reflProperty = new \ReflectionProperty('\PHPExif\Exif', 'data'); $reflProperty->setAccessible(true); $this->assertEquals($reflProperty->getValue($this->exif), $this->exif->getRawData()); } /** * @group exif */ public function testSetRawData() { $testData = array('foo', 'bar', 'baz'); $reflProperty = new \ReflectionProperty('\PHPExif\Exif', 'data'); $reflProperty->setAccessible(true); $result = $this->exif->setRawData($testData); $this->assertEquals($testData, $reflProperty->getValue($this->exif)); $this->assertEquals($this->exif, $result); } /** * * @dataProvider providerUndefinedPropertiesReturnFalse * @param string $accessor */ public function testUndefinedPropertiesReturnFalse($accessor) { $expected = false; $this->assertEquals($expected, $this->exif->$accessor()); } /** * Data provider for testUndefinedPropertiesReturnFalse * * @return array */ public function providerUndefinedPropertiesReturnFalse() { return array( array('getAperture'), array('getIso'), array('getExposure'), array('getExposureMilliseconds'), array('getFocusDistance'), array('getWidth'), array('getHeight'), array('getTitle'), array('getCaption'), array('getCopyright'), array('getKeywords'), array('getCamera'), array('getHorizontalResolution'), array('getVerticalResolution'), array('getSoftware'), array('getFocalLength'), array('getCreationDate'), array('getAuthor'), array('getHeadline'), array('getCredit'), array('getSource'), array('getJobtitle'), ); } /** * @group exif * @covers \PHPExif\Exif::getAperture */ public function testGetAperture() { $expected = 'f/8.0'; $data[\PHPExif\Exif::APERTURE] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getAperture()); } /** * @group exif * @covers \PHPExif\Exif::getIso */ public function testGetIso() { $expected = 200; $data[\PHPExif\Exif::ISO] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getIso()); } /** * @group exif * @covers \PHPExif\Exif::getExposure */ public function testGetExposure() { $expected = '1/320'; $data[\PHPExif\Exif::EXPOSURE] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getExposure()); } /** * @group exif * @covers \PHPExif\Exif::getExposureMilliseconds */ public function testGetExposureMilliseconds() { $expected = 1/320; $data[\PHPExif\Exif::EXPOSURE] = '1/320'; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getExposureMilliseconds()); } /** * @group exif * @covers \PHPExif\Exif::getFocusDistance */ public function testGetFocusDistance() { $expected = '7.94m'; $data[\PHPExif\Exif::FOCAL_DISTANCE] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getFocusDistance()); } /** * @group exif * @covers \PHPExif\Exif::getWidth */ public function testGetWidth() { $expected = 500; $data[\PHPExif\Exif::WIDTH] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getWidth()); } /** * @group exif * @covers \PHPExif\Exif::getHeight */ public function testGetHeight() { $expected = 332; $data[\PHPExif\Exif::HEIGHT] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getHeight()); } /** * @group exif * @covers \PHPExif\Exif::getTitle */ public function testGetTitle() { $expected = 'Morning Glory Pool'; $data[\PHPExif\Exif::TITLE] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getTitle()); } /** * @group exif * @covers \PHPExif\Exif::getCaption */ public function testGetCaption() { $expected = 'Foo Bar Baz'; $data[\PHPExif\Exif::CAPTION] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getCaption()); } /** * @group exif * @covers \PHPExif\Exif::getCopyright */ public function testGetCopyright() { $expected = 'Miljar'; $data[\PHPExif\Exif::COPYRIGHT] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getCopyright()); } /** * @group exif * @covers \PHPExif\Exif::getKeywords */ public function testGetKeywords() { $expected = array('18-200', 'D90', 'USA', 'Wyoming', 'Yellowstone'); $data[\PHPExif\Exif::KEYWORDS] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getKeywords()); } /** * @group exif * @covers \PHPExif\Exif::getCamera */ public function testGetCamera() { $expected = 'NIKON D90'; $data[\PHPExif\Exif::CAMERA] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getCamera()); } /** * @group exif * @covers \PHPExif\Exif::getHorizontalResolution */ public function testGetHorizontalResolution() { $expected = 240; $data[\PHPExif\Exif::HORIZONTAL_RESOLUTION] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getHorizontalResolution()); } /** * @group exif * @covers \PHPExif\Exif::getVerticalResolution */ public function testGetVerticalResolution() { $expected = 240; $data[\PHPExif\Exif::VERTICAL_RESOLUTION] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getVerticalResolution()); } /** * @group exif * @covers \PHPExif\Exif::getSoftware */ public function testGetSoftware() { $expected = 'Adobe Photoshop Lightroom'; $data[\PHPExif\Exif::SOFTWARE] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getSoftware()); } /** * @group exif * @covers \PHPExif\Exif::getFocalLength */ public function testGetFocalLength() { $expected = 18; $data[\PHPExif\Exif::FOCAL_LENGTH] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getFocalLength()); } /** * @group exif * @covers \PHPExif\Exif::getCreationDate */ public function testGetCreationDate() { $expected = '2011-06-07 20:01:50'; $input = \DateTime::createFromFormat('Y-m-d H:i:s', $expected); $data[\PHPExif\Exif::CREATION_DATE] = $input; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getCreationDate()->format('Y-m-d H:i:s')); } /** * @group exif * @covers \PHPExif\Exif::getAuthor */ public function testGetAuthor() { $expected = '<NAME>'; $data[\PHPExif\Exif::AUTHOR] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getAuthor()); } /** * @group exif * @covers \PHPExif\Exif::getHeadline */ public function testGetHeadline() { $expected = 'Foobar Baz'; $data[\PHPExif\Exif::HEADLINE] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getHeadline()); } /** * @group exif * @covers \PHPExif\Exif::getCredit */ public function testGetCredit() { $expected = '<EMAIL>'; $data[\PHPExif\Exif::CREDIT] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getCredit()); } /** * @group exif * @covers \PHPExif\Exif::getSource */ public function testGetSource() { $expected = 'FBB NEWS'; $data[\PHPExif\Exif::SOURCE] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getSource()); } /** * @group exif * @covers \PHPExif\Exif::getJobtitle */ public function testGetJobtitle() { $expected = 'Yellowstone\'s geysers and pools'; $data[\PHPExif\Exif::JOB_TITLE] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getJobtitle()); } /** * @group exif * @covers \PHPExif\Exif::getColorSpace */ public function testGetColorSpace() { $expected = 'RGB'; $data[\PHPExif\Exif::COLORSPACE] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getColorSpace()); } /** * @group exif * @covers \PHPExif\Exif::getMimeType */ public function testGetMimeType() { $expected = 'image/jpeg'; $data[\PHPExif\Exif::MIMETYPE] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getMimeType()); } /** * @group exif * @covers \PHPExif\Exif::getFileSize */ public function testGetFileSize() { $expected = '27852365'; $data[\PHPExif\Exif::FILESIZE] = $expected; $this->exif->setRawData($data); $this->assertEquals($expected, $this->exif->getFileSize()); } }<file_sep><?php /** * PHP Exif Reader: Reads EXIF metadata from a file, without having to install additional PHP modules * * @link http://github.com/miljar/PHPExif for the canonical source repository * @copyright Copyright (c) 2013 <NAME> <<EMAIL>> * @license http://github.com/miljar/PHPExif/blob/master/LICENSE MIT License * @category PHPExif * @package Exif */ namespace PHPExif; /** * PHP Exif Reader * * Responsible for all the read operations on a file's EXIF metadata * * @category PHPExif * @package Exif * @ */ class Exif { const APERTURE = 'aperture'; const AUTHOR = 'author'; const CAMERA = 'camera'; const CAPTION = 'caption'; const COLORSPACE = 'ColorSpace'; const COPYRIGHT = 'copyright'; const CREATION_DATE = 'creationdate'; const CREDIT = 'credit'; const EXPOSURE = 'exposure'; const FILESIZE = 'FileSize'; const FOCAL_LENGTH = 'focalLength'; const FOCAL_DISTANCE = 'focalDistance'; const HEADLINE = 'headline'; const HEIGHT = 'height'; const HORIZONTAL_RESOLUTION = 'horizontalResolution'; const ISO = 'iso'; const JOB_TITLE = 'jobTitle'; const KEYWORDS = 'keywords'; const MIMETYPE = 'MimeType'; const SOFTWARE = 'software'; const SOURCE = 'source'; const TITLE = 'title'; const VERTICAL_RESOLUTION = 'verticalResolution'; const WIDTH = 'width'; /** * The EXIF data * * @var array */ protected $data = array(); /** * Class constructor * * @param array $data */ public function __construct(array $data = array()) { $this->setRawData($data); } /** * Sets the EXIF data * * @param array $data The data to set * @return \PHPExif\Exif Current instance for chaining */ public function setRawData(array $data) { $this->data = $data; return $this; } /** * Returns all EXIF data in the raw original format * * @return array */ public function getRawData() { return $this->data; } /** * Returns the Aperture F-number * * @return string|boolean */ public function getAperture() { if (!isset($this->data[self::APERTURE])) { return false; } return $this->data[self::APERTURE]; } /** * Returns the Author * * @return string|boolean */ public function getAuthor() { if (!isset($this->data[self::AUTHOR])) { return false; } return $this->data[self::AUTHOR]; } /** * Returns the Headline * * @return string|boolean */ public function getHeadline() { if (!isset($this->data[self::HEADLINE])) { return false; } return $this->data[self::HEADLINE]; } /** * Returns the Credit * * @return string|boolean */ public function getCredit() { if (!isset($this->data[self::CREDIT])) { return false; } return $this->data[self::CREDIT]; } /** * Returns the source * * @return string|boolean */ public function getSource() { if (!isset($this->data[self::SOURCE])) { return false; } return $this->data[self::SOURCE]; } /** * Returns the Jobtitle * * @return string|boolean */ public function getJobtitle() { if (!isset($this->data[self::JOB_TITLE])) { return false; } return $this->data[self::JOB_TITLE]; } /** * Returns the ISO speed * * @return int|boolean */ public function getIso() { if (!isset($this->data[self::ISO])) { return false; } return $this->data[self::ISO]; } /** * Returns the Exposure * * @return string|boolean */ public function getExposure() { if (!isset($this->data[self::EXPOSURE])) { return false; } return $this->data[self::EXPOSURE]; } /** * Returns the Exposure * * @return float|boolean */ public function getExposureMilliseconds() { if (!isset($this->data[self::EXPOSURE])) { return false; } $exposureParts = explode('/', $this->data[self::EXPOSURE]); return (int)reset($exposureParts) / (int)end($exposureParts); } /** * Returns the focus distance, if it exists * * @return string|boolean */ public function getFocusDistance() { if (!isset($this->data[self::FOCAL_DISTANCE])) { return false; } return $this->data[self::FOCAL_DISTANCE]; } /** * Returns the width in pixels, if it exists * * @return int|boolean */ public function getWidth() { if (!isset($this->data[self::WIDTH])) { return false; } return $this->data[self::WIDTH]; } /** * Returns the height in pixels, if it exists * * @return int|boolean */ public function getHeight() { if (!isset($this->data[self::HEIGHT])) { return false; } return $this->data[self::HEIGHT]; } /** * Returns the title, if it exists * * @return string|boolean */ public function getTitle() { if (!isset($this->data[self::TITLE])) { return false; } return $this->data[self::TITLE]; } /** * Returns the caption, if it exists * * @return string|boolean */ public function getCaption() { if (!isset($this->data[self::CAPTION])) { return false; } return $this->data[self::CAPTION]; } /** * Returns the copyright, if it exists * * @return string|boolean */ public function getCopyright() { if (!isset($this->data[self::COPYRIGHT])) { return false; } return $this->data[self::COPYRIGHT]; } /** * Returns the keywords, if they exists * * @return array|boolean */ public function getKeywords() { if (!isset($this->data[self::KEYWORDS])) { return false; } return $this->data[self::KEYWORDS]; } /** * Returns the camera, if it exists * * @return string|boolean */ public function getCamera() { if (!isset($this->data[self::CAMERA])) { return false; } return $this->data[self::CAMERA]; } /** * Returns the horizontal resolution in DPI, if it exists * * @return int|boolean */ public function getHorizontalResolution() { if (!isset($this->data[self::HORIZONTAL_RESOLUTION])) { return false; } return $this->data[self::HORIZONTAL_RESOLUTION]; } /** * Returns the vertical resolution in DPI, if it exists * * @return int|boolean */ public function getVerticalResolution() { if (!isset($this->data[self::VERTICAL_RESOLUTION])) { return false; } return $this->data[self::VERTICAL_RESOLUTION]; } /** * Returns the software, if it exists * * @return string|boolean */ public function getSoftware() { if (!isset($this->data[self::SOFTWARE])) { return false; } return $this->data[self::SOFTWARE]; } /** * Returns the focal length in mm, if it exists * * @return float|boolean */ public function getFocalLength() { if (!isset($this->data[self::FOCAL_LENGTH])) { return false; } return $this->data[self::FOCAL_LENGTH]; } /** * Returns the creation datetime, if it exists * * @return \DateTime|boolean */ public function getCreationDate() { if (!isset($this->data[self::CREATION_DATE])) { return false; } return $this->data[self::CREATION_DATE]; } /** * Returns the colorspace, if it exists * * @return string */ public function getColorSpace() { if (!isset($this->data[self::COLORSPACE])) { return false; } return $this->data[self::COLORSPACE]; } /** * Returns the mimetype, if it exists * * @return string */ public function getMimeType() { if (!isset($this->data[self::MIMETYPE])) { return false; } return $this->data[self::MIMETYPE]; } /** * Returns the filesize, if it exists * * @return integer */ public function getFileSize() { if (!isset($this->data[self::FILESIZE])) { return false; } return $this->data[self::FILESIZE]; } } <file_sep><?php class ExiftoolTest extends \PHPUnit_Framework_TestCase { /** * @var \PHPExif\Reader\Adapter\Exiftool */ protected $adapter; public function setUp() { $this->adapter = new \PHPExif\Reader\Adapter\Exiftool(); } /** * @group exiftool * @covers \PHPExif\Reader\Adapter\Exiftool::getToolPath */ public function testGetToolPathFromProperty() { $reflProperty = new \ReflectionProperty('\PHPExif\Reader\Adapter\Exiftool', 'toolPath'); $reflProperty->setAccessible(true); $expected = '/foo/bar/baz'; $reflProperty->setValue($this->adapter, $expected); $this->assertEquals($expected, $this->adapter->getToolPath()); } /** * @group exiftool * @covers \PHPExif\Reader\Adapter\Exiftool::setToolPath */ public function testSetToolPathInProperty() { $reflProperty = new \ReflectionProperty('\PHPExif\Reader\Adapter\Exiftool', 'toolPath'); $reflProperty->setAccessible(true); $expected = '/tmp'; $this->adapter->setToolPath($expected); $this->assertEquals($expected, $reflProperty->getValue($this->adapter)); } /** * @group exiftool * @covers \PHPExif\Reader\Adapter\Exiftool::setToolPath * @expectedException InvalidArgumentException */ public function testSetToolPathThrowsException() { $this->adapter->setToolPath('/foo/bar'); } /** * @group exiftool * @covers \PHPExif\Reader\Adapter\Exiftool::getToolPath */ public function testGetToolPathLazyLoadsPath() { $this->assertInternalType('string', $this->adapter->getToolPath()); } /** * @group exiftool * @covers \PHPExif\Reader\Adapter\Exiftool::getExifFromFile */ public function testGetExifFromFile() { $file = PHPEXIF_TEST_ROOT . '/files/morning_glory_pool_500.jpg'; $result = $this->adapter->getExifFromFile($file); $this->assertInstanceOf('\PHPExif\Exif', $result); } /** * @group exiftool * @covers \PHPExif\Reader\Adapter\Exiftool::mapData */ public function testMapDataReturnsArray() { $this->assertInternalType('array', $this->adapter->mapData(array())); } /** * @group exiftool * @covers \PHPExif\Reader\Adapter\Exiftool::mapData */ public function testMapDataReturnsArrayFalseValuesIfUndefined() { $result = $this->adapter->mapData(array()); foreach ($result as $value) { $this->assertFalse($value); } } /** * @group exiftool * @covers \PHPExif\Reader\Adapter\Exiftool::mapData */ public function testMapDataResultHasAllKeys() { $reflClass = new \ReflectionClass('\PHPExif\Exif'); $constants = $reflClass->getConstants(); $result = $this->adapter->mapData(array()); $keys = array_keys($result); $diff = array_diff($constants, $keys); $this->assertEquals(0, count($diff)); } /** * @group exiftool * @covers \PHPExif\Reader\Adapter\Exiftool::mapData */ public function testMapDataFocalLengthIsCalculated() { $focalLength = '18 mm.'; $result = $this->adapter->mapData( array( 'FocalLength' => $focalLength, ) ); $this->assertEquals(18, $result[\PHPExif\Exif::FOCAL_LENGTH]); } /** * @group exiftool * @covers \PHPExif\Reader\Adapter\Exiftool::getCliOutput */ public function testGetCliOutput() { $reflMethod = new \ReflectionMethod('\PHPExif\Reader\Adapter\Exiftool', 'getCliOutput'); $reflMethod->setAccessible(true); $result = $reflMethod->invoke( $this->adapter, sprintf( '%1$s', 'pwd' ) ); $this->assertInternalType('string', $result); } }
aa654bcdacd829a692fc295f46c3880b8ecf7f34
[ "PHP" ]
7
PHP
ericduran/php-exif
afa6d4250ccc0f52fa2d63af8a4eda4f1f5251ac
9062ce788ad9b7329692fe4d4db29020bf5e76ae
refs/heads/master
<repo_name>pfctgeorge/bar<file_sep>/bar.go package bar import "github.com/pfctgeorge/foo" func Print() { foo.Print() }
d3753782569c01cb5835470b092dc7b2a872ce54
[ "Go" ]
1
Go
pfctgeorge/bar
55dbf972fcb32d4a37279e59437ceffd42e12c33
51cc63f92e8a791992c8f85b83d4fffb0418c622
refs/heads/master
<repo_name>lawso017/middleman-sprockets<file_sep>/lib/middleman-sprockets/version.rb module Middleman module Sprockets VERSION = '4.0.0.rc.3'.freeze end end
fbf04b018ed9ac9e358c0549cb47d5fbbe613dbf
[ "Ruby" ]
1
Ruby
lawso017/middleman-sprockets
ab9f3fdd7e7b2a79f143fd132b8a384e0573b4b8
04b4b8e80777926988b204c6cca0b48e729df388
refs/heads/master
<repo_name>iwansafr/spa<file_sep>/application/view/index.php <!DOCTYPE html> <html> <head> <title>spa</title> <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css') ?>"> <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/font-awesome/css/font-awesome.min.css') ?>"> </head> <body> <h1>single page application</h1> <?php include 'data/edit.php'; ?> <script type="text/javascript" src="<?php echo base_url('assets/jquery/jquery.min.js') ?>"></script> <script type="text/javascript" src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js') ?>"></script> </body> </html><file_sep>/system/helper.php <?php $url = @$config['base_url']; function base_url($base_url='') { global $url; if(!empty($base_url)) { return $url.$base_url; }else{ return $url; } } function output_json($array) { $output = '{}'; if (!empty($array)) { if (is_object($array)) { $array = (array)$array; } if (!is_array($array)) { $output = $array; }else{ if (defined('JSON_PRETTY_PRINT')) { $output = json_encode($array, JSON_PRETTY_PRINT); }else{ $output = json_encode($array); } } } header('content-type: application/json; charset: UTF-8'); header('cache-control: must-revalidate'); header('expires: ' . gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT'); echo $output; exit(); } if(!function_exists('pr')) { function pr($text='', $return = false) { $is_multiple = (func_num_args() > 2) ? true : false; if(!$is_multiple) { if(is_numeric($return)) { if($return==1 || $return==0) { $return = $return ? true : false; }else $is_multiple = true; } if(!is_bool($return)) $is_multiple = true; } if($is_multiple) { echo "<pre style='text-align:left;'>\n"; echo "<b>1 : </b>"; print_r($text); $i = func_num_args(); if($i > 1) { $j = array(); $k = 1; for($l=1;$l < $i;$l++) { $k++; echo "\n<b>$k : </b>"; print_r(func_get_arg($l)); } } echo "\n</pre>"; }else{ if($return) { ob_start(); } echo "<pre style='text-align:left;'>\n"; print_r($text); echo "\n</pre>"; if($return) { $output = ob_get_contents(); ob_end_clean(); return $output; } } } }<file_sep>/system/Db.php <?php $db['default'] = array( 'host' => 'localhost', 'username' => 'root', 'password' => '<PASSWORD>', 'database' => 'native' ); Class Db { var $mysqli_protected; var $insert_id = 0; var $data = array(); public function __construct($db) { if(!empty($db) && is_array($db)) { $db = $db['default']; $error = array(); if(empty($db['host'])) { $error[] = 'host is undefined'; } if(empty($db['username'])){ $error[] = 'username is undefined'; }if(empty($db['database'])){ $error[] = 'database is undefined'; } if(!empty($error)) { foreach ($error as $key => $value) { echo '<p style="color: red;">'.$value.'<p>'; } }else{ mysqli_report(MYSQLI_REPORT_STRICT); try{ $param = new mysqli($db['host'],$db['username'],$db['password'], $db['database']); }catch(Exception $e){ echo '<p style="color: red;">'.$e->getMessage().'</p>'; $param = array(); } $this->mysqli_protected = $param; } } return $this->mysqli_protected; } public function query($q = '') { $data = array(); if(!empty($q)) { $data = $this->mysqli_protected->query($q); $this->data = $data; $this->insert_id = @$this->mysqli_protected->insert_id; echo $this->mysqli_protected->error."\n"; return $data; } } public function result() { $data = array(); if(!empty($this->data)) { while($row = $this->data->fetch_assoc()) { $data[] = $row; } return $data; } } } $db = new db($db);<file_sep>/index.php <?php include_once('system/config.php'); include_once('system/helper.php'); include_once('system/Db.php'); include_once('application/view/index.php'); ?> <script type="text/javascript" src="<?php echo base_url('application/app.js') ?>"></script>
59b57652d6756dcc192a54b6e541693c3faa2836
[ "PHP" ]
4
PHP
iwansafr/spa
ba8bfcf1977a2a3a04fc6bc21c8efd69a7e25c76
62ba84f074a1754a18f63d99e5410ca58c5bccb1
refs/heads/master
<file_sep># Créer des widgets avec VueJS ## Résumé Ce répertoire contient un template pour construire et publier des widgets web avec VueJS. C'est le coeur de la solution utilisée par Etalab pour réaliser le [dashboard de suivi de l'épidémie de Covid19](https://github.com/etalab/covid19-dashboard-widgets) publié sur [gouvernement.fr](https://www.gouvernement.fr/info-coronavirus/carte-et-donnees). Le principe est de générer un fichier js et un fichier css permettant à n'importe quel site distant d'utiliser des éléments html customisés dans ses pages. ## Propriétés - Orienté datavisualisation - Construire des widgets html hyper customisés avec VueJS - Store de données et de paramètres mutualisé entre les widgets - Styles et polices du [système de design de l'Etat](https://www.systeme-de-design.gouv.fr/) pré-intégrés - Widgets présents dans le DOM = styles surchargeables par la page parent ## Comment ça marche ? Le concept de ce projet est assez proche de celui des [web components](https://developer.mozilla.org/fr/docs/Web/Web_Components) mais utilise les facilités offertes par VueJS pour créer le code hyper-customisés des widgets. Il repose principalement sur l'utilisation du package [vue-custom-elements](https://github.com/karol-f/vue-custom-element) pour transformer les composants Vue classiques en éléments html pouvant être directement intégrés dans le DOM du site client. L'ensemble des composants sont compilés lors du _build_ en deux fichiers js et css qu'il suffit d'ajouter dans le head de n'importe quelle page web pour pouvoir utiliser les widgets, même si la page parente ne contient pas Vue. ## Comment créer mes propres widgets ? ### Créer un nouveau widget - ajouter un nouveau fichier Vue dans /src/components - un composant générique MyComponent.vue existe dans le répertoire pour servir de modèle - importer ce nouveau composant dans /src/main.js ```js import MyComponent from './components/MyComponent' ``` - instancier le nouveau composant dans /src/main.js ```js Vue.customElement('my-component', MyComponent) ``` ### Mutualiser des imports de données - des données stockées dans l'object state du fichier /src/store/index.js sont accessibles à tous les widgets - des données peuvent stockées dans le store depuis les composants ou des fichiers indépendants comme /src/import.js - dans ce cas, la fonction d'import de données doit être déclarée dans /src/main.js ```js import { getData } from './import.js' ``` ### Mutualiser des fonctions - décrire les fonctions utilitaires dans un fichier indépendant comme /src/utils.js - exporter ces fonctions sous forme de mixins ```js export const mixin = { methods: { myCustomFunction, } } ``` - importer les mixins dans les composants qui en ont l'utilité ```js import { mixin } from '@/utils.js' ``` ## Mise en place du projet ``` npm install ``` ### Compilation et rechargement à la volée pour le dévelopement ``` npm run serve ``` ### Compilation et miniaturisation du code pour la production ``` npm run build ``` ### Lints et fixes des fichiers ``` npm run lint ``` ### Notes Webpack doit être installé comme suit : ``` npm install webpack@^4.0.0 --save-dev ``` <file_sep>import Vue from 'vue' import store from './store' import { getData } from './import.js' import MyComponent from './components/MyComponent' import vueCustomElement from 'vue-custom-element' Vue.use(getData(store)) Vue.config.productionTip = false Vue.use(vueCustomElement) Vue.customElement('my-component', MyComponent)
82d562c1dcb85380bc8e716665b2c18c13c0f40d
[ "Markdown", "JavaScript" ]
2
Markdown
etalab/dashboard-widgets-template
f86e635e596bfd51f2f3f32e076e796d92513bff
920c107e10892833740a14697fab1e5538bdfcdc
refs/heads/master
<file_sep>package main import ( "flag" "fmt" "log" "os" "text/tabwriter" "maze.io/x/esphome/cmd" ) func main() { flag.Parse() client, err := cmd.Dial() if err != nil { log.Fatalln(err) } defer client.Close() var ( entities = client.Entities() w = tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', tabwriter.Debug) ) for _, item := range entities.BinarySensor { fmt.Fprintf(w, "binary sensor\t%s\t%s\n", item.ObjectID, item.Name) } for _, item := range entities.Camera { fmt.Fprintf(w, "climate sensor\t%s\t%s\n", item.ObjectID, item.Name) } for _, item := range entities.Climate { fmt.Fprintf(w, "climate sensor\t%s\t%s\n", item.ObjectID, item.Name) } for _, item := range entities.Cover { fmt.Fprintf(w, "cover\t%s\t%s\n", item.ObjectID, item.Name) } for _, item := range entities.Fan { fmt.Fprintf(w, "fan\t%s\t%s\n", item.ObjectID, item.Name) } for _, item := range entities.Light { fmt.Fprintf(w, "light\t%s\t%s\n", item.ObjectID, item.Name) } for _, item := range entities.Sensor { fmt.Fprintf(w, "sensor\t%s\t%s\n", item.ObjectID, item.Name) } for _, item := range entities.Switch { fmt.Fprintf(w, "switch\t%s\t%s\n", item.ObjectID, item.Name) } for _, item := range entities.Sensor { fmt.Fprintf(w, "text sensor\t%s\t%s\n", item.ObjectID, item.Name) } w.Flush() } <file_sep>package esphome import ( "image/color" "math" "maze.io/x/esphome/api" ) // Entity is the base struct for all supported entities. type Entity struct { Name string ObjectID string UniqueID string Key uint32 client *Client } // Entities is a high level map of a device's entities. type Entities struct { BinarySensor map[string]*BinarySensor Camera map[string]*Camera Climate map[string]*Climate Cover map[string]*Cover Fan map[string]*Fan Light map[string]*Light Sensor map[string]*Sensor Switch map[string]*Switch TextSensor map[string]*TextSensor } // BinarySensor can be pressed, released and/or clicked. type BinarySensor struct { Entity DeviceClass string State bool } func newBinarySensor(client *Client, entity *api.ListEntitiesBinarySensorResponse) *BinarySensor { return &BinarySensor{ Entity: Entity{ Name: entity.Name, ObjectID: entity.ObjectId, UniqueID: entity.UniqueId, Key: entity.Key, client: client, }, DeviceClass: entity.DeviceClass, } } // Climate devices can represent different types of hardware, but the defining factor is that climate devices have a // settable target temperature and can be put in different modes like HEAT, COOL, AUTO or OFF. type Climate struct { Entity // Capabilities of the entity. Capabilities ClimateCapabilities } type ( // ClimateCapabilities represents the capabilities of a climate device. ClimateCapabilities struct { CurrentTemperature bool TwoPointTargetTemperature bool Modes []ClimateMode VisualMinTemperature float32 VisualMaxTemperature float32 VisualTemperatureStep float32 Away bool Action bool FanModes []ClimateFanMode SwingModes []ClimateSwingMode } // ClimateMode represents the mode for a climate device. ClimateMode int32 // ClimateFanMode represents a climate fan speed. ClimateFanMode int32 // ClimateSwingMode represents a climate (fan) swing mode. ClimateSwingMode int32 ) // Climate modes. const ( ClimateModeOff ClimateMode = iota ClimateModeAuto ClimateModeCool ClimateModeHeat ClimateModeFanOnly ClimateModeDry ) // Climate fan modes. const ( ClimateFanModeOn ClimateFanMode = iota ClimateFanModeOff ClimateFanModeAuto ClimateFanModeLow ClimateFanModeMedium ClimateFanModeHigh ClimateFanModeMiddle ClimateFanModeFocus ClimateFanModeDiffuse ) // Climate swing modes. const ( ClimateSwingModeOff ClimateSwingMode = iota ClimateSwingModeBoth ClimateSwingModeVertical ClimateSwingModeHorizontal ) func newClimate(client *Client, entity *api.ListEntitiesClimateResponse) *Climate { var ( modes = make([]ClimateMode, len(entity.SupportedModes)) fanModes = make([]ClimateFanMode, len(entity.SupportedFanModes)) swingModes = make([]ClimateSwingMode, len(entity.SupportedSwingModes)) ) for i, v := range entity.SupportedModes { modes[i] = ClimateMode(v) } for i, v := range entity.SupportedFanModes { fanModes[i] = ClimateFanMode(v) } for i, v := range entity.SupportedSwingModes { swingModes[i] = ClimateSwingMode(v) } return &Climate{ Entity: Entity{ Name: entity.Name, ObjectID: entity.ObjectId, UniqueID: entity.UniqueId, Key: entity.Key, client: client, }, Capabilities: ClimateCapabilities{ CurrentTemperature: entity.SupportsCurrentTemperature, TwoPointTargetTemperature: entity.SupportsTwoPointTargetTemperature, Modes: modes, VisualMinTemperature: entity.VisualMinTemperature, VisualMaxTemperature: entity.VisualMaxTemperature, VisualTemperatureStep: entity.VisualTemperatureStep, Away: entity.SupportsAway, Action: entity.SupportsAction, FanModes: fanModes, SwingModes: swingModes, }, } } // Cover device. type Cover struct { Entity // TODO(maze): Finish me } func newCover(client *Client, entity *api.ListEntitiesCoverResponse) *Cover { return &Cover{ Entity: Entity{ Name: entity.Name, ObjectID: entity.ObjectId, UniqueID: entity.UniqueId, Key: entity.Key, client: client, }, } } // Fan device. type Fan struct { Entity // TODO(maze): Finish me } func newFan(client *Client, entity *api.ListEntitiesFanResponse) *Fan { return &Fan{ Entity: Entity{ Name: entity.Name, ObjectID: entity.ObjectId, UniqueID: entity.UniqueId, Key: entity.Key, client: client, }, } } // Light device. type Light struct { Entity Capabilities LightCapabilities Effects []string State LightState StateIsValid bool HandleState func(on bool) HandleBrightness func(float32) HandleColor func(r, g, b, w float32) HandleColorTemperature func(float32) HandleEffect func(string) } // LightCapabilities represents the capabilities of a Light. type LightCapabilities struct { Brightness bool RGB bool WhiteValue bool ColorTemperature bool MinMired float32 MaxMired float32 } // LightState represents the state of a Light. type LightState struct { On bool Brightness float32 Red, Green, Blue, White float32 ColorTemperature float32 Effect string } func newLight(client *Client, entity *api.ListEntitiesLightResponse) *Light { effects := make([]string, len(entity.Effects)) copy(effects, entity.Effects) return &Light{ Entity: Entity{ Name: entity.Name, ObjectID: entity.ObjectId, UniqueID: entity.UniqueId, Key: entity.Key, client: client, }, Capabilities: LightCapabilities{ Brightness: entity.SupportsBrightness, RGB: entity.SupportsRgb, WhiteValue: entity.SupportsWhiteValue, ColorTemperature: entity.SupportsColorTemperature, MinMired: entity.MinMireds, MaxMired: entity.MaxMireds, }, Effects: effects, } } func (entity Light) commandRequest() *api.LightCommandRequest { return &api.LightCommandRequest{ Key: entity.Key, State: entity.State.On, HasBrightness: entity.Capabilities.Brightness, Brightness: entity.State.Brightness, HasRgb: entity.Capabilities.RGB, Red: entity.State.Red, Green: entity.State.Green, Blue: entity.State.Blue, HasWhite: entity.Capabilities.WhiteValue, White: entity.State.White, HasColorTemperature: entity.Capabilities.ColorTemperature, ColorTemperature: entity.State.ColorTemperature, HasTransitionLength: false, TransitionLength: 0, HasFlashLength: false, FlashLength: 0, HasEffect: false, Effect: entity.State.Effect, } } func (entity *Light) update(state *api.LightStateResponse) { if entity.HandleState != nil { if state.State != entity.State.On { entity.HandleState(true) } } if entity.HandleColor != nil { if !entity.StateIsValid { entity.HandleColor(state.Red, state.Green, state.Blue, state.White) } else if !equal(entity.State.Red, state.Red) || !equal(entity.State.Green, state.Green) || !equal(entity.State.Blue, state.Blue) || !equal(entity.State.White, state.White) { entity.HandleColor(state.Red, state.Green, state.Blue, state.White) } } if entity.HandleColorTemperature != nil { if !entity.StateIsValid || !equal(entity.State.ColorTemperature, state.ColorTemperature) { entity.HandleColorTemperature(state.ColorTemperature) } } if entity.HandleEffect != nil { if !entity.StateIsValid || entity.State.Effect != state.Effect { entity.HandleEffect(state.Effect) } } entity.State.On = state.State entity.State.Brightness = state.Brightness entity.State.Red = state.Red entity.State.Green = state.Green entity.State.Blue = state.Blue entity.State.White = state.White entity.State.ColorTemperature = state.ColorTemperature entity.State.Effect = state.Effect entity.StateIsValid = true } // SetBrightness sets the light's intensity (brightness). func (entity Light) SetBrightness(value float32) error { request := entity.commandRequest() request.Brightness = value return entity.client.sendTimeout(request, entity.client.Timeout) } // SetColor sets the light's red, green and blue values. func (entity Light) SetColor(value color.Color) error { r, g, b, _ := value.RGBA() request := entity.commandRequest() request.Red = float32(r>>4) / 256.0 request.Green = float32(g>>4) / 256.0 request.Blue = float32(b>>4) / 256.0 return entity.client.sendTimeout(request, entity.client.Timeout) } // SetWhite sets the light's white value. func (entity Light) SetWhite(value float32) error { request := entity.commandRequest() request.White = value return entity.client.sendTimeout(request, entity.client.Timeout) } // SetEffect selects a preconfigured effect. func (entity Light) SetEffect(effect string) error { request := entity.commandRequest() request.Effect = effect return entity.client.sendTimeout(request, entity.client.Timeout) } // SetState turns the light on or off. func (entity Light) SetState(on bool) error { request := entity.commandRequest() request.State = on return entity.client.sendTimeout(request, entity.client.Timeout) } // Sensor probes. type Sensor struct { Entity Icon string UnitOfMeasurement string AccuracyDecimals int32 ForceUpdate bool State float32 StateIsValid bool HandleState func(float32) } func newSensor(client *Client, entity *api.ListEntitiesSensorResponse) *Sensor { return &Sensor{ Entity: Entity{ Name: entity.Name, ObjectID: entity.ObjectId, UniqueID: entity.UniqueId, Key: entity.Key, client: client, }, } } func (entity *Sensor) update(state *api.SensorStateResponse) { if !state.MissingState && entity.HandleState != nil && !equal(entity.State, state.State) { entity.HandleState(state.State) } entity.State = state.State entity.StateIsValid = !state.MissingState } // Switch includes all platforms that should show up like a switch and can only be turned ON or OFF. type Switch struct { Entity Icon string AssumedState bool // State of the switch. State bool HandleState func(bool) } func newSwitch(client *Client, entity *api.ListEntitiesSwitchResponse) *Switch { return &Switch{ Entity: Entity{ Name: entity.Name, ObjectID: entity.ObjectId, UniqueID: entity.UniqueId, Key: entity.Key, client: client, }, } } func (entity *Switch) update(state *api.SwitchStateResponse) { if entity.HandleState != nil { entity.HandleState(state.State) } entity.State = state.State entity.AssumedState = false } func (entity Switch) commandRequest() *api.SwitchCommandRequest { return &api.SwitchCommandRequest{ Key: entity.Key, State: entity.State, } } // SetState updates the switch state. func (entity Switch) SetState(on bool) error { request := entity.commandRequest() request.State = on return entity.client.sendTimeout(request, entity.client.Timeout) } // TextSensor is a lot like Sensor, but where the “normal” sensors only represent sensors that output numbers, this // component can represent any text. type TextSensor struct { Entity State string StateIsValid bool } func newTextSensor(client *Client, entity *api.ListEntitiesTextSensorResponse) *TextSensor { return &TextSensor{ Entity: Entity{ Name: entity.Name, ObjectID: entity.ObjectId, UniqueID: entity.UniqueId, Key: entity.Key, client: client, }, } } func equal(a, b float32) bool { const ε = 1e-6 return math.Abs(float64(a)-float64(b)) <= ε } <file_sep>package esphome import ( "bufio" "fmt" "net" "sync" "time" proto "github.com/golang/protobuf/proto" "maze.io/x/esphome/api" ) // Client defaults. const ( DefaultTimeout = 10 * time.Second DefaultPort = 6053 defaultClientInfo = "maze.io go/esphome" ) // Client for an ESPHome device. type Client struct { // Info identifies this device with the ESPHome node. Info string // Timeout for read and write operations. Timeout time.Duration // Clock returns the current time. Clock func() time.Time conn net.Conn br *bufio.Reader entities clientEntities err error in chan proto.Message stop chan struct{} waitMutex sync.RWMutex wait map[uint64]chan proto.Message lastMessage time.Time } type clientEntities struct { binarySensor map[uint32]*BinarySensor camera map[uint32]*Camera climate map[uint32]*Climate cover map[uint32]*Cover fan map[uint32]*Fan light map[uint32]*Light sensor map[uint32]*Sensor switches map[uint32]*Switch textSensor map[uint32]*TextSensor } func newClientEntities() clientEntities { return clientEntities{ binarySensor: make(map[uint32]*BinarySensor), camera: make(map[uint32]*Camera), climate: make(map[uint32]*Climate), cover: make(map[uint32]*Cover), fan: make(map[uint32]*Fan), light: make(map[uint32]*Light), sensor: make(map[uint32]*Sensor), switches: make(map[uint32]*Switch), textSensor: make(map[uint32]*TextSensor), } } // Dial connects to ESPHome native API on the supplied TCP address. func Dial(addr string) (*Client, error) { return DialTimeout(addr, DefaultTimeout) } // DialTimeout is like Dial with a custom timeout. func DialTimeout(addr string, timeout time.Duration) (*Client, error) { conn, err := net.DialTimeout("tcp", addr, timeout) if err != nil { return nil, err } c := &Client{ Timeout: timeout, Info: defaultClientInfo, Clock: func() time.Time { return time.Now() }, conn: conn, br: bufio.NewReader(conn), in: make(chan proto.Message, 16), wait: make(map[uint64]chan proto.Message), stop: make(chan struct{}), entities: newClientEntities(), } go c.reader() return c, nil } func (c *Client) reader() { defer c.conn.Close() for { select { case <-c.stop: return default: if err := c.readMessage(); err != nil { c.err = err return } } } } func (c *Client) nextMessage() (proto.Message, error) { if c.err != nil { return nil, c.err } return <-c.in, nil } func (c *Client) nextMessageTimeout(timeout time.Duration) (proto.Message, error) { if c.err != nil { return nil, c.err } select { case message := <-c.in: return message, nil case <-time.After(timeout): return nil, ErrTimeout } } func (c *Client) waitFor(messageType uint64, in chan proto.Message) { c.waitMutex.Lock() { if other, waiting := c.wait[messageType]; waiting { other <- nil close(other) } c.wait[messageType] = in } c.waitMutex.Unlock() } func (c *Client) waitDone(messageType uint64) { c.waitMutex.Lock() { delete(c.wait, messageType) } c.waitMutex.Unlock() } func (c *Client) waitMessage(messageType uint64) proto.Message { in := make(chan proto.Message, 1) c.waitFor(messageType, in) message := <-in c.waitDone(messageType) return message } func (c *Client) waitMessageTimeout(messageType uint64, timeout time.Duration) (proto.Message, error) { in := make(chan proto.Message, 1) c.waitFor(messageType, in) defer c.waitDone(messageType) select { case message := <-in: return message, nil case <-time.After(timeout): return nil, ErrTimeout } } func (c *Client) readMessage() (err error) { var message proto.Message if message, err = api.ReadMessage(c.br); err == nil { c.lastMessage = time.Now() if !c.handleInternal(message) { c.waitMutex.Lock() in, waiting := c.wait[api.TypeOf(message)] c.waitMutex.Unlock() if waiting { in <- message } else { c.in <- message } } } return } func (c *Client) handleInternal(message proto.Message) bool { switch message := message.(type) { case *api.DisconnectRequest: _ = c.sendTimeout(&api.DisconnectResponse{}, c.Timeout) c.Close() return true case *api.PingRequest: _ = c.sendTimeout(&api.PingResponse{}, c.Timeout) return true case *api.GetTimeRequest: _ = c.sendTimeout(&api.GetTimeResponse{EpochSeconds: uint32(c.Clock().Unix())}, c.Timeout) return true case *api.FanStateResponse: if _, ok := c.entities.fan[message.Key]; ok { // TODO // entity.update(message) } case *api.CoverStateResponse: if _, ok := c.entities.cover[message.Key]; ok { // TODO // entity.update(message) } case *api.LightStateResponse: if entity, ok := c.entities.light[message.Key]; ok { entity.update(message) } case *api.SensorStateResponse: if entity, ok := c.entities.sensor[message.Key]; ok { entity.update(message) } case *api.SwitchStateResponse: if entity, ok := c.entities.switches[message.Key]; ok { entity.update(message) } } return false } func (c *Client) send(message proto.Message) error { packed, err := api.Marshal(message) if err != nil { return err } if _, err = c.conn.Write(packed); err != nil { return err } return nil } func (c *Client) sendTimeout(message proto.Message, timeout time.Duration) error { packed, err := api.Marshal(message) if err != nil { return err } if err = c.conn.SetWriteDeadline(time.Now().Add(timeout)); err != nil { return err } if _, err = c.conn.Write(packed); err != nil { return err } if err = c.conn.SetWriteDeadline(time.Time{}); err != nil { return err } return nil } func (c *Client) sendAndWaitResponse(message proto.Message, messageType uint64) (proto.Message, error) { if err := c.send(message); err != nil { return nil, err } return c.waitMessage(messageType), nil } func (c *Client) sendAndWaitResponseTimeout(message proto.Message, messageType uint64, timeout time.Duration) (proto.Message, error) { if timeout <= 0 { return c.sendAndWaitResponse(message, messageType) } if err := c.sendTimeout(message, timeout); err != nil { return nil, err } return c.waitMessageTimeout(messageType, timeout) } // Login must be called to do the initial handshake. The provided password can be empty. func (c *Client) Login(password string) error { message, err := c.sendAndWaitResponseTimeout(&api.HelloRequest{ ClientInfo: c.Info, }, api.HelloResponseType, c.Timeout) if err != nil { return err } if message, err = c.sendAndWaitResponseTimeout(&api.ConnectRequest{ Password: <PASSWORD>, }, api.ConnectResponseType, c.Timeout); err != nil { return err } connectResponse := message.(*api.ConnectResponse) if connectResponse.InvalidPassword { return ErrPassword } // Query available entities, this allows us to map sensor/actor names to keys. entities, err := c.listEntities() if err != nil { return err } for _, item := range entities { switch item := item.(type) { case *api.ListEntitiesBinarySensorResponse: c.entities.binarySensor[item.Key] = newBinarySensor(c, item) case *api.ListEntitiesCameraResponse: c.entities.camera[item.Key] = newCamera(c, item) case *api.ListEntitiesClimateResponse: c.entities.climate[item.Key] = newClimate(c, item) case *api.ListEntitiesCoverResponse: c.entities.cover[item.Key] = newCover(c, item) case *api.ListEntitiesFanResponse: c.entities.fan[item.Key] = newFan(c, item) case *api.ListEntitiesLightResponse: c.entities.light[item.Key] = newLight(c, item) case *api.ListEntitiesSensorResponse: c.entities.sensor[item.Key] = newSensor(c, item) case *api.ListEntitiesSwitchResponse: c.entities.switches[item.Key] = newSwitch(c, item) case *api.ListEntitiesTextSensorResponse: c.entities.textSensor[item.Key] = newTextSensor(c, item) default: fmt.Printf("unknown\t%T\n", item) } } // Subscribe to states, this is also used for streaming requests. if err = c.sendTimeout(&api.SubscribeStatesRequest{}, c.Timeout); err != nil { return err } return nil } // Close the device connection. func (c *Client) Close() error { _, err := c.sendAndWaitResponseTimeout(&api.DisconnectRequest{}, api.DisconnectResponseType, 5*time.Second) select { case c.stop <- struct{}{}: default: } return err } // LastMessage returns the time of the last message received. func (c *Client) LastMessage() time.Time { return c.lastMessage } // DeviceInfo contains information about the ESPHome node. type DeviceInfo struct { UsesPassword bool // The name of the node, given by "App.set_name()" Name string // The mac address of the device. For example "AC:BC:32:89:0E:A9" MacAddress string // A string describing the ESPHome version. For example "1.10.0" EsphomeVersion string // A string describing the date of compilation, this is generated by the compiler // and therefore may not be in the same format all the time. // If the user isn't using ESPHome, this will also not be set. CompilationTime string // The model of the board. For example NodeMCU Model string // HasDeepSleep indicates the device has deep sleep mode enabled when idle. HasDeepSleep bool } // DeviceInfo queries the ESPHome device information. func (c *Client) DeviceInfo() (DeviceInfo, error) { message, err := c.sendAndWaitResponseTimeout(&api.DeviceInfoRequest{}, api.DeviceInfoResponseType, c.Timeout) if err != nil { return DeviceInfo{}, err } info := message.(*api.DeviceInfoResponse) return DeviceInfo{ UsesPassword: info.UsesPassword, Name: info.Name, MacAddress: info.MacAddress, EsphomeVersion: info.EsphomeVersion, CompilationTime: info.CompilationTime, Model: info.Model, HasDeepSleep: info.HasDeepSleep, }, nil } // Entities returns all configured entities on the connected device. func (c *Client) Entities() Entities { var entities = Entities{ BinarySensor: make(map[string]*BinarySensor), Camera: make(map[string]*Camera), Climate: make(map[string]*Climate), Cover: make(map[string]*Cover), Fan: make(map[string]*Fan), Light: make(map[string]*Light), Sensor: make(map[string]*Sensor), Switch: make(map[string]*Switch), TextSensor: make(map[string]*TextSensor), } for _, item := range c.entities.binarySensor { entities.BinarySensor[item.UniqueID] = item } for _, item := range c.entities.camera { entities.Camera[item.UniqueID] = item } for _, item := range c.entities.climate { entities.Climate[item.UniqueID] = item } for _, item := range c.entities.cover { entities.Cover[item.UniqueID] = item } for _, item := range c.entities.fan { entities.Fan[item.UniqueID] = item } for _, item := range c.entities.light { entities.Light[item.UniqueID] = item } for _, item := range c.entities.sensor { entities.Sensor[item.UniqueID] = item } for _, item := range c.entities.switches { entities.Switch[item.UniqueID] = item } for _, item := range c.entities.textSensor { entities.TextSensor[item.UniqueID] = item } return entities } // LogLevel represents the logger level. type LogLevel int32 // Log levels. const ( LogNone LogLevel = iota LogError LogWarn LogInfo LogDebug LogVerbose LogVeryVerbose ) // LogEntry contains a single entry in the ESPHome system log. type LogEntry struct { // Level of the message. Level LogLevel // Tag for the message. Tag string // Message is the raw text message. Message string // SendFailed indicates a failure. SendFailed bool } // Logs streams log entries. func (c *Client) Logs(level LogLevel) (chan LogEntry, error) { if err := c.sendTimeout(&api.SubscribeLogsRequest{ Level: api.LogLevel(level), }, c.Timeout); err != nil { return nil, err } in := make(chan proto.Message, 1) c.waitMutex.Lock() c.wait[api.SubscribeLogsResponseType] = in c.waitMutex.Unlock() out := make(chan LogEntry) go func(in <-chan proto.Message, out chan LogEntry) { defer close(out) for entry := range in { entry := entry.(*api.SubscribeLogsResponse) out <- LogEntry{ Level: LogLevel(entry.Level), Tag: entry.Tag, Message: entry.Message, SendFailed: entry.SendFailed, } } }(in, out) return out, nil } // listEntities lists connected entities. func (c *Client) listEntities() (entities []proto.Message, err error) { if err = c.sendTimeout(&api.ListEntitiesRequest{}, c.Timeout); err != nil { return nil, err } for { message, err := c.nextMessageTimeout(c.Timeout) if err != nil { return nil, err } switch message := message.(type) { case *api.ListEntitiesDoneResponse: return entities, nil case *api.ListEntitiesBinarySensorResponse, *api.ListEntitiesCameraResponse, *api.ListEntitiesClimateResponse, *api.ListEntitiesCoverResponse, *api.ListEntitiesFanResponse, *api.ListEntitiesLightResponse, *api.ListEntitiesSensorResponse, *api.ListEntitiesServicesResponse, *api.ListEntitiesSwitchResponse, *api.ListEntitiesTextSensorResponse: entities = append(entities, message) } } } // Camera returns a reference to the camera. It returns an error if no camera is found. func (c *Client) Camera() (Camera, error) { for _, entity := range c.entities.camera { return *entity, nil } return Camera{}, ErrEntity } // Ping the server. func (c *Client) Ping() error { return c.PingTimeout(c.Timeout) } // PingTimeout is like ping with a custom timeout. func (c *Client) PingTimeout(timeout time.Duration) error { // ESPHome doesn't respond to ping (bug? expected?), so we fire & forget. return c.sendTimeout(&api.PingRequest{}, timeout) } <file_sep>package cmd import ( "flag" "net" "os" "strconv" "maze.io/x/esphome" ) const ( envHost = "ESPHOME_HOST" envPassword = "<PASSWORD>" ) var ( NodeFlag = flag.String("node", getenv(envHost, "esphome.local"), "node API hostname or IP ("+envHost+")") PortFlag = flag.Int("port", esphome.DefaultPort, "node API port") PasswordFlag = flag.String("password", "", "node API password ("+envPassword+")") TimeoutFlag = flag.Duration("timeout", esphome.DefaultTimeout, "network timeout") ) func Dial() (*esphome.Client, error) { addr := net.JoinHostPort(*NodeFlag, strconv.Itoa(*PortFlag)) client, err := esphome.DialTimeout(addr, *TimeoutFlag) if err != nil { return nil, err } if *PasswordFlag == "" { *PasswordFlag = os.Getenv(envPassword) } if err = client.Login(*PasswordFlag); err != nil { _ = client.Close() return nil, err } return client, nil } func getenv(key, fallback string) string { if value := os.Getenv(key); value != "" { return value } return fallback } <file_sep>package esphome import "errors" // Errors. var ( ErrPassword = errors.New("esphome: invalid password") ErrTimeout = errors.New("esphome: timeout") ErrObjectID = errors.New("esphome: unknown object identifier") ErrEntity = errors.New("esphome: entity not found") ) <file_sep>package main import ( "log" "maze.io/x/esphome" ) func main() { devices := make(chan *esphome.Device, 32) go dump(devices) if err := esphome.Discover(devices); err != nil { log.Fatalln("discovery failed:", err) } } func dump(devices <-chan *esphome.Device) { for device := range devices { log.Printf("discovered %s on %s (version %s)", device.Name, device.Addr(), device.Version) } } <file_sep>package api // API request/response types. const ( UnknownType = iota HelloRequestType HelloResponseType ConnectRequestType ConnectResponseType DisconnectRequestType DisconnectResponseType PingRequestType PingResponseType DeviceInfoRequestType DeviceInfoResponseType ListEntitiesRequestType ListEntitiesBinarySensorResponseType ListEntitiesCoverResponseType ListEntitiesFanResponseType ListEntitiesLightResponseType ListEntitiesSensorResponseType ListEntitiesSwitchResponseType ListEntitiesTextSensorResponseType ListEntitiesDoneResponseType SubscribeStatesRequestType BinarySensorStateResponseType CoverStateResponseType FanStateResponseType LightStateResponseType SensorStateResponseType SwitchStateResponseType TextSensorStateResponseType SubscribeLogsRequestType SubscribeLogsResponseType CoverCommandRequestType FanCommandRequestType LightCommandRequestType SwitchCommandRequestType SubscribeHomeAssistantServicesRequestType HomeAssistantServiceResponseType GetTimeRequestType GetTimeResponseType SubscribeHomeAssistantStatesRequestType SubscribeHomeAssistantStateResponseType HomeAssistantStateResponseType ListEntitiesServicesResponseType ExecuteServiceRequestType ListEntitiesCameraResponseType CameraImageResponseType CameraImageRequestType ListEntitiesClimateResponseType ClimateStateResponseType ClimateCommandRequestType ) <file_sep>package main import ( "flag" "image/gif" "image/jpeg" "image/png" "log" "os" "strings" "maze.io/x/esphome/cmd" ) func main() { var output = flag.String("output", "camera.jpg", "output file") flag.Parse() log.Printf("connecting to node %s:%d", *cmd.NodeFlag, *cmd.PortFlag) client, err := cmd.Dial() if err != nil { log.Fatalln(err) } defer client.Close() camera, err := client.Camera() if err != nil { log.Fatalln(err) } log.Println("requesting camera image") i, err := camera.Image() if err != nil { log.Fatalln(err) } o, err := os.Create(*output) if err != nil { log.Fatalln(err) } defer o.Close() switch strings.ToLower(*output) { case ".gif": err = gif.Encode(o, i, nil) case ".png": err = png.Encode(o, i) default: fallthrough case ".jpg", ".jpeg": err = jpeg.Encode(o, i, nil) } if err != nil { log.Fatalln(err) } else if err = o.Close(); err != nil { log.Fatalln(err) } size := i.Bounds().Size() log.Printf("saved %dx%d image to %s\n", size.X, size.Y, *output) } <file_sep>module maze.io/x/esphome go 1.13 require ( github.com/golang/protobuf v1.3.2 github.com/miekg/dns v1.1.27 golang.org/x/crypto v0.0.0-20200117160349-530e935923ad // indirect golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa // indirect golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9 // indirect ) <file_sep># esphome ESPHome client.<file_sep>package api import ( "bufio" "encoding/binary" "errors" "fmt" "io" "github.com/golang/protobuf/proto" ) var messageType = map[int]interface{}{ 1: HelloRequest{}, 2: HelloResponse{}, 3: ConnectRequest{}, 4: ConnectResponse{}, 5: DisconnectRequest{}, 6: DisconnectResponse{}, 7: PingRequest{}, 8: PingResponse{}, 9: DeviceInfoRequest{}, 10: DeviceInfoResponse{}, 11: ListEntitiesRequest{}, 12: ListEntitiesBinarySensorResponse{}, 13: ListEntitiesCoverResponse{}, 14: ListEntitiesFanResponse{}, 15: ListEntitiesLightResponse{}, 16: ListEntitiesSensorResponse{}, 17: ListEntitiesSwitchResponse{}, 18: ListEntitiesTextSensorResponse{}, 19: ListEntitiesDoneResponse{}, 20: SubscribeStatesRequest{}, 21: BinarySensorStateResponse{}, 22: CoverStateResponse{}, 23: FanStateResponse{}, 24: LightStateResponse{}, 25: SensorStateResponse{}, 26: SwitchStateResponse{}, 27: TextSensorStateResponse{}, 28: SubscribeLogsRequest{}, 29: SubscribeLogsResponse{}, 30: CoverCommandRequest{}, 31: FanCommandRequest{}, 32: LightCommandRequest{}, 33: SwitchCommandRequest{}, 34: SubscribeHomeassistantServicesRequest{}, 35: HomeassistantServiceResponse{}, 36: GetTimeRequest{}, 37: GetTimeResponse{}, 38: SubscribeHomeAssistantStatesRequest{}, 39: SubscribeHomeAssistantStateResponse{}, 40: HomeAssistantStateResponse{}, 41: ListEntitiesServicesResponse{}, 42: ExecuteServiceRequest{}, 43: ListEntitiesCameraResponse{}, 44: CameraImageResponse{}, 45: CameraImageRequest{}, 46: ListEntitiesClimateResponse{}, 47: ClimateStateResponse{}, 48: ClimateCommandRequest{}, } func Marshal(message proto.Message) ([]byte, error) { encoded, err := proto.Marshal(message) if err != nil { return nil, err } var ( packed = make([]byte, len(encoded)+17) n = 1 ) // Write encoded message length n += binary.PutUvarint(packed[n:], uint64(len(encoded))) // Write message type n += binary.PutUvarint(packed[n:], TypeOf(message)) // Write message copy(packed[n:], encoded) n += len(encoded) return packed[:n], nil } func ReadMessage(r *bufio.Reader) (proto.Message, error) { b, err := r.ReadByte() if err != nil { return nil, err } if b != 0x00 { return nil, errors.New("api: protocol error: expected null byte") } // Read encoded message length length, err := binary.ReadUvarint(r) if err != nil { return nil, err } // Read encoded message type kind, err := binary.ReadUvarint(r) if err != nil { return nil, err } // Read encoded message encoded := make([]byte, length) if _, err = io.ReadFull(r, encoded); err != nil { return nil, err } message := newMessage(kind) if message == nil { return nil, fmt.Errorf("api: protocol error: unknown message type %#x", kind) } if err = proto.Unmarshal(encoded, message); err != nil { return nil, err } return message, nil } func TypeOf(value interface{}) uint64 { switch value.(type) { case HelloRequest, *HelloRequest: return HelloRequestType case HelloResponse, *HelloResponse: return HelloResponseType case ConnectRequest, *ConnectRequest: return ConnectRequestType case ConnectResponse, *ConnectResponse: return ConnectResponseType case DisconnectRequest, *DisconnectRequest: return DisconnectRequestType case DisconnectResponse, *DisconnectResponse: return DisconnectResponseType case PingRequest, *PingRequest: return PingRequestType case PingResponse, *PingResponse: return PingResponseType case DeviceInfoRequest, *DeviceInfoRequest: return DeviceInfoRequestType case DeviceInfoResponse, *DeviceInfoResponse: return DeviceInfoResponseType case ListEntitiesRequest, *ListEntitiesRequest: return ListEntitiesRequestType case ListEntitiesBinarySensorResponse, *ListEntitiesBinarySensorResponse: return ListEntitiesBinarySensorResponseType case ListEntitiesCoverResponse, *ListEntitiesCoverResponse: return ListEntitiesCoverResponseType case ListEntitiesFanResponse, *ListEntitiesFanResponse: return ListEntitiesFanResponseType case ListEntitiesLightResponse, *ListEntitiesLightResponse: return ListEntitiesLightResponseType case ListEntitiesSensorResponse, *ListEntitiesSensorResponse: return ListEntitiesSensorResponseType case ListEntitiesSwitchResponse, *ListEntitiesSwitchResponse: return ListEntitiesSwitchResponseType case ListEntitiesTextSensorResponse, *ListEntitiesTextSensorResponse: return ListEntitiesTextSensorResponseType case ListEntitiesDoneResponse, *ListEntitiesDoneResponse: return ListEntitiesDoneResponseType case SubscribeStatesRequest, *SubscribeStatesRequest: return SubscribeStatesRequestType case BinarySensorStateResponse, *BinarySensorStateResponse: return BinarySensorStateResponseType case CoverStateResponse, *CoverStateResponse: return CoverStateResponseType case FanStateResponse, *FanStateResponse: return FanStateResponseType case LightStateResponse, *LightStateResponse: return LightStateResponseType case SensorStateResponse, *SensorStateResponse: return SensorStateResponseType case SwitchStateResponse, *SwitchStateResponse: return SwitchStateResponseType case TextSensorStateResponse, *TextSensorStateResponse: return TextSensorStateResponseType case SubscribeLogsRequest, *SubscribeLogsRequest: return SubscribeLogsRequestType case SubscribeLogsResponse, *SubscribeLogsResponse: return SubscribeLogsResponseType case CoverCommandRequest, *CoverCommandRequest: return CoverCommandRequestType case FanCommandRequest, *FanCommandRequest: return FanCommandRequestType case LightCommandRequest, *LightCommandRequest: return LightCommandRequestType case SwitchCommandRequest, *SwitchCommandRequest: return SwitchCommandRequestType case SubscribeHomeassistantServicesRequest, *SubscribeHomeassistantServicesRequest: return SubscribeHomeAssistantServicesRequestType case HomeassistantServiceResponse, *HomeassistantServiceResponse: return HomeAssistantServiceResponseType case GetTimeRequest, *GetTimeRequest: return GetTimeRequestType case GetTimeResponse, *GetTimeResponse: return GetTimeResponseType case SubscribeHomeAssistantStatesRequest, *SubscribeHomeAssistantStatesRequest: return SubscribeHomeAssistantStatesRequestType case SubscribeHomeAssistantStateResponse, *SubscribeHomeAssistantStateResponse: return SubscribeHomeAssistantStateResponseType case HomeAssistantStateResponse, *HomeAssistantStateResponse: return HomeAssistantStateResponseType case ListEntitiesServicesResponse, *ListEntitiesServicesResponse: return ListEntitiesServicesResponseType case ExecuteServiceRequest, *ExecuteServiceRequest: return ExecuteServiceRequestType case ListEntitiesCameraResponse, *ListEntitiesCameraResponse: return ListEntitiesCameraResponseType case CameraImageResponse, *CameraImageResponse: return CameraImageResponseType case CameraImageRequest, *CameraImageRequest: return CameraImageRequestType case ListEntitiesClimateResponse, *ListEntitiesClimateResponse: return ListEntitiesClimateResponseType case ClimateStateResponse, *ClimateStateResponse: return ClimateStateResponseType case ClimateCommandRequest, *ClimateCommandRequest: return ClimateCommandRequestType default: return UnknownType } } func newMessage(kind uint64) proto.Message { switch kind { case 1: return new(HelloRequest) case 2: return new(HelloResponse) case 3: return new(ConnectRequest) case 4: return new(ConnectResponse) case 5: return new(DisconnectRequest) case 6: return new(DisconnectResponse) case 7: return new(PingRequest) case 8: return new(PingResponse) case 9: return new(DeviceInfoRequest) case 10: return new(DeviceInfoResponse) case 11: return new(ListEntitiesRequest) case 12: return new(ListEntitiesBinarySensorResponse) case 13: return new(ListEntitiesCoverResponse) case 14: return new(ListEntitiesFanResponse) case 15: return new(ListEntitiesLightResponse) case 16: return new(ListEntitiesSensorResponse) case 17: return new(ListEntitiesSwitchResponse) case 18: return new(ListEntitiesTextSensorResponse) case 19: return new(ListEntitiesDoneResponse) case 20: return new(SubscribeStatesRequest) case 21: return new(BinarySensorStateResponse) case 22: return new(CoverStateResponse) case 23: return new(FanStateResponse) case 24: return new(LightStateResponse) case 25: return new(SensorStateResponse) case 26: return new(SwitchStateResponse) case 27: return new(TextSensorStateResponse) case 28: return new(SubscribeLogsRequest) case 29: return new(SubscribeLogsResponse) case 30: return new(CoverCommandRequest) case 31: return new(FanCommandRequest) case 32: return new(LightCommandRequest) case 33: return new(SwitchCommandRequest) case 34: return new(SubscribeHomeassistantServicesRequest) case 35: return new(HomeassistantServiceResponse) case 36: return new(GetTimeRequest) case 37: return new(GetTimeResponse) case 38: return new(SubscribeHomeAssistantStatesRequest) case 39: return new(SubscribeHomeAssistantStateResponse) case 40: return new(HomeAssistantStateResponse) case 41: return new(ListEntitiesServicesResponse) case 42: return new(ExecuteServiceRequest) case 43: return new(ListEntitiesCameraResponse) case 44: return new(CameraImageResponse) case 45: return new(CameraImageRequest) case 46: return new(ListEntitiesClimateResponse) case 47: return new(ClimateStateResponse) case 48: return new(ClimateCommandRequest) default: return nil } } <file_sep>package api import ( "bufio" "bytes" "encoding/hex" "testing" ) func TestReadMessage(t *testing.T) { var ( bb = bytes.NewBuffer(testHelloResponseBytes) br = bufio.NewReader(bb) ) m, err := ReadMessage(br) if err != nil { t.Fatal(err) } t.Logf("%T: %+v", m, m) } var ( testHelloResponseBytes, _ = hex.DecodeString("001f02080110031a1963616d657261302028657370686f6d652076312e31342e3329") ) <file_sep>package main import ( "flag" "fmt" "log" "maze.io/x/esphome" "maze.io/x/esphome/cmd" ) func main() { var level = flag.Int("level", int(esphome.LogVeryVerbose), "entry level (0-6)") flag.Parse() client, err := cmd.Dial() if err != nil { log.Fatalln(err) } defer client.Close() logs, err := client.Logs(esphome.LogLevel(*level)) if err != nil { log.Fatalln(err) } for entry := range logs { fmt.Println(entry.Message) } } <file_sep>package esphome import ( "context" "errors" "fmt" "net" "strconv" "strings" "sync/atomic" "time" "github.com/miekg/dns" ) // Discovery defaults. const ( DefaultMDNSService = "_esphomelib._tcp" DefaultMDNSDomain = "local" DefaultMDNSTimeout = 5 * time.Second mDNSIP4 = "192.168.127.12" mDNSIP6 = "fc00:e968:6179::de52:7100" mDNSPort = 5353 forceUnicastResponses = false ) var ( mDNSAddr4 = &net.UDPAddr{IP: net.ParseIP(mDNSIP4), Port: mDNSPort} mDNSAddr6 = &net.UDPAddr{IP: net.ParseIP(mDNSIP6), Port: mDNSPort} ) // Device is an ESPHome device (returned by Discover). type Device struct { Name string Host string Port int IP net.IP IP6 net.IP Version string sent bool } // Addr returns the device API address. func (d *Device) Addr() string { if d.IP6 != nil { return (&net.TCPAddr{IP: d.IP6, Port: d.Port}).String() } else if d.IP != nil { return (&net.TCPAddr{IP: d.IP, Port: d.Port}).String() } return net.JoinHostPort(d.Host, strconv.Itoa(d.Port)) } func (d *Device) complete() bool { return d.Host != "" && (d.IP != nil || d.IP6 != nil) } // Discover ESPHome deices on the network. func Discover(devices chan<- *Device) error { return DiscoverService(devices, DefaultMDNSService, DefaultMDNSDomain, DefaultMDNSTimeout) } // DiscoverService is used by Discover, can be used to override the default service and domain and to customize timeouts. func DiscoverService(devices chan<- *Device, service, domain string, timeout time.Duration) error { c, err := newmDNSClient() if err != nil { return err } defer c.Close() return c.query(devices, service, domain, timeout) } type mDNSClient struct { // Unicast uc4, uc6 *net.UDPConn // Multicast mc4, mc6 *net.UDPConn closed int32 closedCh chan struct{} } func newmDNSClient() (*mDNSClient, error) { uc4, _ := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: 0}) uc6, _ := net.ListenUDP("udp6", &net.UDPAddr{IP: net.IPv6zero, Port: 0}) if uc4 == nil && uc6 == nil { return nil, errors.New("esphome: failed to bind to any unicast UDP port") } mc4, _ := net.ListenMulticastUDP("udp4", nil, mDNSAddr4) mc6, _ := net.ListenMulticastUDP("udp6", nil, mDNSAddr6) if uc4 == nil && uc6 == nil { if uc4 != nil { _ = uc4.Close() } if uc6 != nil { _ = uc6.Close() } return nil, errors.New("esphome: failed to bind to any multicast TCP port") } return &mDNSClient{ uc4: uc4, uc6: uc6, mc4: mc4, mc6: mc6, closedCh: make(chan struct{}), }, nil } func (c *mDNSClient) Close() error { if !atomic.CompareAndSwapInt32(&c.closed, 0, 1) { // something else already closed it return nil } close(c.closedCh) if c.uc4 != nil { _ = c.uc4.Close() } if c.uc6 != nil { _ = c.uc6.Close() } if c.mc4 != nil { _ = c.mc4.Close() } if c.mc6 != nil { _ = c.mc6.Close() } return nil } /* query performs mDNS service discovery: client: question _esphomelib._tcp.local. IN PTR? servers: response _esphomelib._tcp.local. IN PTR <hostname>._esphomelib._tcp.local <hostname>._esphomelib._tcp.local. IN SRV <hostname>.local. <port> 0 0 <hostname>._esphomelib._tcp.local. IN TXT <record>* <hostname>.local. IN A <ipv4 address> <hostname>.local. IN AAAA <ipv6 address> */ func (c *mDNSClient) query(devices chan<- *Device, service, domain string, timeout time.Duration) error { // Create the service name addr := fmt.Sprintf("%s.%s", strings.Trim(service, "."), strings.Trim(domain, ".")) // Start listening for response packets var ( ctx, cancel = context.WithTimeout(context.Background(), timeout) msgs = make(chan *dns.Msg, 32) ) defer cancel() go c.recv(ctx, c.uc4, msgs) go c.recv(ctx, c.uc6, msgs) go c.recv(ctx, c.mc4, msgs) go c.recv(ctx, c.mc6, msgs) q := new(dns.Msg) q.SetQuestion(addr+".", dns.TypePTR) // RFC 6762, section 18.12. Repurposing of Top Bit of qclass in Question // Section // // In the Question Section of a Multicast DNS query, the top bit of the qclass // field is used to indicate that unicast responses are preferred for this // particular question. (See Section 5.4.) q.Question[0].Qclass |= 1 << 15 q.RecursionDesired = false if err := c.send(q); err != nil { return err } var partial = make(map[string]*Device) for ctx.Err() == nil { select { case replies := <-msgs: var d *Device for _, a := range append(replies.Answer, replies.Extra...) { switch rr := a.(type) { case *dns.PTR: d = c.parsePTR(addr, partial, rr) case *dns.SRV: d = c.parseSRV(addr, partial, rr) case *dns.A: d = c.parseA(domain, partial, rr) case *dns.AAAA: d = c.parseAAAA(domain, partial, rr) case *dns.TXT: d = c.parseTXT(addr, partial, rr) } } if d == nil { continue } if d.complete() { if !d.sent { select { case devices <- d: default: } d.sent = true } } case <-ctx.Done(): return nil } } return ctx.Err() } func (c *mDNSClient) parsePTR(addr string, partial map[string]*Device, rr *dns.PTR) *Device { // _esphomelib._tcp.local. IN PTR <hostname>._esphomelib._tcp.local index := strings.IndexByte(rr.Ptr, '.') if index == -1 { return nil } hostname := rr.Ptr[:index] if !strings.EqualFold(strings.Trim(rr.Hdr.Name, "."), addr) { return nil } return ensureDevice(partial, hostname) } func (c *mDNSClient) parseSRV(addr string, partial map[string]*Device, rr *dns.SRV) *Device { // <hostname>._esphomelib._tcp.local. IN SRV <hostname>.local. <port> 0 0 index := strings.IndexByte(rr.Hdr.Name, '.') if index == -1 { return nil } hostname, suffix := rr.Hdr.Name[:index], strings.Trim(rr.Hdr.Name[index+1:], ".") if !strings.EqualFold(suffix, addr) { return nil } d := ensureDevice(partial, hostname) d.Host = rr.Target d.Port = int(rr.Port) return d } func (c *mDNSClient) parseTXT(addr string, partial map[string]*Device, rr *dns.TXT) *Device { // <hostname>._esphomelib._tcp.local. IN TXT <record>* index := strings.IndexByte(rr.Hdr.Name, '.') if index == -1 { return nil } hostname, suffix := rr.Hdr.Name[:index], strings.Trim(rr.Hdr.Name[index+1:], ".") if !strings.EqualFold(suffix, addr) { return nil } d := ensureDevice(partial, hostname) for _, t := range rr.Txt { if i := strings.IndexByte(t, '='); i > -1 { switch t[:i] { case "address": d.Host = t[i+1:] case "version": d.Version = t[i+1:] } } } return d } func (c *mDNSClient) parseA(domain string, partial map[string]*Device, rr *dns.A) *Device { // <hostname>.local. IN A <ipv4 address> index := strings.IndexByte(rr.Hdr.Name, '.') if index == -1 { return nil } hostname, suffix := rr.Hdr.Name[:index], strings.Trim(rr.Hdr.Name[index+1:], ".") if !strings.EqualFold(suffix, domain) { return nil } d := ensureDevice(partial, hostname) d.IP = rr.A return d } func (c *mDNSClient) parseAAAA(domain string, partial map[string]*Device, rr *dns.AAAA) *Device { // <hostname>.local. IN AAAA <ipv6 address> index := strings.IndexByte(rr.Hdr.Name, '.') if index == -1 { return nil } hostname, suffix := rr.Hdr.Name[:index], strings.Trim(rr.Hdr.Name[index+1:], ".") if !strings.EqualFold(suffix, domain) { return nil } d := ensureDevice(partial, hostname) d.IP6 = rr.AAAA return d } func ensureDevice(partial map[string]*Device, name string) *Device { name = strings.Trim(name, ".") if d, ok := partial[name]; ok { return d } d := &Device{Name: name, Port: DefaultPort} partial[name] = d return d } func ensureDeviceAlias(partial map[string]*Device, src, dst string) { partial[dst] = ensureDevice(partial, src) } func (c *mDNSClient) recv(ctx context.Context, l *net.UDPConn, msgCh chan *dns.Msg) { if l == nil { return } buf := make([]byte, 65536) for ctx.Err() == nil { n, err := l.Read(buf) if err != nil { continue } msg := new(dns.Msg) if err := msg.Unpack(buf[:n]); err != nil { continue } select { case msgCh <- msg: case <-ctx.Done(): return } } } func (c *mDNSClient) send(q *dns.Msg) error { buf, err := q.Pack() if err != nil { return err } if c.uc4 != nil { c.uc4.WriteToUDP(buf, mDNSAddr4) } if c.uc6 != nil { c.uc6.WriteToUDP(buf, mDNSAddr6) } return nil } <file_sep>package esphome import ( "bytes" "image" "image/jpeg" "time" "github.com/golang/protobuf/proto" "maze.io/x/esphome/api" ) // Camera is an ESP32 camera. type Camera struct { Entity lastFrame time.Time } func newCamera(client *Client, entity *api.ListEntitiesCameraResponse) *Camera { return &Camera{ Entity: Entity{ Name: entity.Name, ObjectID: entity.ObjectId, UniqueID: entity.UniqueId, Key: entity.Key, client: client, }, } } // Image grabs one image frame from the camera. func (entity *Camera) Image() (image.Image, error) { if err := entity.client.sendTimeout(&api.CameraImageRequest{ Stream: true, }, entity.client.Timeout); err != nil { return nil, err } var ( in = make(chan proto.Message, 1) out = make(chan []byte) ) entity.client.waitMutex.Lock() entity.client.wait[api.CameraImageResponseType] = in entity.client.waitMutex.Unlock() go func(in <-chan proto.Message, out chan []byte) { for message := range in { if message, ok := message.(*api.CameraImageResponse); ok { out <- message.Data if message.Done { close(out) entity.lastFrame = time.Now() return } } } }(in, out) var buffer = new(bytes.Buffer) for chunk := range out { buffer.Write(chunk) } entity.client.waitMutex.Lock() delete(entity.client.wait, api.CameraImageResponseType) entity.client.waitMutex.Unlock() return jpeg.Decode(buffer) } // Stream returns a channel with raw image frame buffers. func (entity *Camera) Stream() (<-chan *bytes.Buffer, error) { if err := entity.client.sendTimeout(&api.CameraImageRequest{ Stream: true, }, entity.client.Timeout); err != nil { return nil, err } in := make(chan proto.Message, 1) entity.client.waitMutex.Lock() entity.client.wait[api.CameraImageResponseType] = in entity.client.waitMutex.Unlock() out := make(chan *bytes.Buffer) go func(in <-chan proto.Message, out chan<- *bytes.Buffer) { var ( ticker = time.NewTicker(time.Second) buffer = new(bytes.Buffer) ) defer ticker.Stop() for { select { case message := <-in: frame := message.(*api.CameraImageResponse) buffer.Write(frame.Data) if frame.Done { out <- buffer buffer = new(bytes.Buffer) entity.lastFrame = time.Now() } case <-ticker.C: if err := entity.client.sendTimeout(&api.CameraImageRequest{ Stream: true, }, entity.client.Timeout); err != nil { close(out) return } } } }(in, out) return out, nil } // ImageStream is like Stream, returning decoded frame images. func (entity *Camera) ImageStream() (<-chan image.Image, error) { in, err := entity.Stream() if err != nil { return nil, err } out := make(chan image.Image) go func(in <-chan *bytes.Buffer, out chan image.Image) { defer close(out) for frame := range in { if i, err := jpeg.Decode(frame); err == nil { out <- i } } }(in, out) return out, nil } // LastFrame returns the time of the last camera frame received. func (entity *Camera) LastFrame() time.Time { return entity.lastFrame }
4ef75e4de8152fe14e8eedac344d9fab2dcdcfaa
[ "Markdown", "Go Module", "Go" ]
15
Go
go-http/esphome
572cb0f10fd524f8b866d76322983770d34ce9c0
b135e8d4fb0d19691e41c08db3602fc2751771d5
refs/heads/master
<file_sep>#!/bin/bash cp -rf ~/.vim vim cp ~/.vimrc vimrc find vim/ -type d -name ".git" | xargs -d '\n' rm -rf
3af81507f46989aa51fe3e2ce708e6d66f7dbd4a
[ "Shell" ]
1
Shell
keitht226/vimfiles_manual
cc21b9c5c7d652cf792d1f6fd9b583c43f057c9b
374efdd9cf099f286c2c88f2f7366ee9610b2fc8
refs/heads/master
<repo_name>xli/mingle-events<file_sep>/lib/mingle_events/poller.rb module MingleEvents class Poller # Manages a full sweep of event processing across each processing pipeline # configured for specified mingle projects. processors_by_project_identifier should # be a hash where the keys are mingle project identifiers and the values are # lists of event processors. def initialize(mingle_access, processors_by_project_identifier, state_folder, from_beginning_of_time = false) @mingle_access = mingle_access @state_folder = state_folder @processors_by_project_identifier = processors_by_project_identifier @from_beginning_of_time = from_beginning_of_time end # Run a single poll for each project configured with processor(s) and # broadcast each event to each processor. def run_once puts "About to poll Mingle for new events..." @processors_by_project_identifier.each do |project_identifier, processors| begin project_feed = ProjectFeed.new(project_identifier, @mingle_access) initial_event_count = @from_beginning_of_time ? :all : 25 broadcaster = ProjectEventBroadcaster.new(project_feed, processors, state_file(project_identifier), initial_event_count) broadcaster.run_once rescue StandardError => e puts "\nUnable to retrieve events for project '#{project_identifier}':" puts e puts "Trace:\n" puts e.backtrace end end end private def state_file(project_identifier) File.join(@state_folder, "#{project_identifier}_state.yml") end end end<file_sep>/lib/mingle_events/mingle_feed_cache.rb module MingleEvents class MingleFeedCache def initialize(source, cache_dir) @source = source @cache_dir = cache_dir FileUtils.mkdir_p(@cache_dir) end def fetch_page(path) if do_not_cache(path) return @source.fetch_page(path) end cache_path = path_to_filename(path) fetch_and_cache(path, cache_path) unless File.exist?(cache_path) File.open(cache_path).readlines.join("\n") end private def do_not_cache(path) p, q = path_to_components(path) is_feed = p =~ /.*\/api\/v2\/.*\/feeds\/events\.xml/ !is_feed || q.nil? end def fetch_and_cache(path, cache_path) FileUtils.mkdir_p(File.dirname(cache_path)) File.open(cache_path, "w") do |f| f << @source.fetch_page(path) end end def path_to_components(path) path_as_uri = URI.parse(path) query = nil query = CGI.parse(path_as_uri.query) if path_as_uri.query [path_as_uri.path, query] end def path_to_filename(path) # http://devblog.muziboo.com/2008/06/17/attachment-fu-sanitize-filename-regex-and-unicode-gotcha/ path_as_uri = URI.parse(path) path = "#{path_as_uri.path}?#{path_as_uri.query}" File.expand_path(File.join(@cache_dir, path.split('/').map{|p| p.gsub(/^.*(\\|\/)/, '').gsub(/[^0-9A-Za-z.\-]/, 'x')})) end end end<file_sep>/lib/mingle_events/processors/abstract_no_retry_processor.rb module MingleEvents module Processors # Loops through the stream of events, asking the subclass to process each event, # one at a time. If the processing of a single event fails, the failure is logged # and processing continues. Allows subclasses to be concerned solely with single # event processing and not streams or error handling. #-- # TODO: Figure out a better class name class AbstractNoRetryProcessor def initialize(dead_letter_office = WarnToStdoutDeadLetterOffice.new) @dead_letter_office = dead_letter_office end def process_events(events) events.map do |event| begin process_event(event) rescue StandardError => e @dead_letter_office.deliver(e, event) end event end events end def process_event(event) raise "Subclass responsibility!" end class WarnToStdoutDeadLetterOffice def deliver(error, *events) Logger.new(STDOUT).info(%{ Unable to process event and #{self} was not constructed with a dead letter office. Event: #{events} Error: #{error} }) end end end end end<file_sep>/test/mingle_events/processors/abstract_no_retry_processor_test.rb require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper')) module MingleEvents module Processors class AbstractNoRetryProcessorTest < Test::Unit::TestCase def test_processes_all_events events = [stub_event(100), stub_event(101), stub_event(102)] processor = DummyProcessor.new(nil) processor.process_events(events) assert_equal([100, 101, 102], processor.processed_events.map(&:entry_id)) end def test_sends_unprocessable_events_to_the_dead_letter_office events = [stub_event(100), stub_event(101), stub_event(102)] dead_letter_office = DummyDeadLetterOffice.new processor = DummyProcessor.new(dead_letter_office, [101]) processor.process_events(events) assert_equal([100, 102], processor.processed_events.map(&:entry_id)) assert_equal([101], dead_letter_office.unprocessed_events.map(&:entry_id)) end def stub_event(id) OpenStruct.new(:entry_id => id) end class DummyDeadLetterOffice attr_reader :unprocessed_events def deliver(error, *events) events.each{|e| (@unprocessed_events ||= []) << e} end end class DummyProcessor < MingleEvents::Processors::AbstractNoRetryProcessor attr_reader :processed_events def initialize(dead_letter_office, explode_on_ids = []) super(dead_letter_office) @explode_on_ids = explode_on_ids end def process_event(event) raise "Exploding on event processing!" if @explode_on_ids.index(event.entry_id) (@processed_events ||= []) << event end end end end end <file_sep>/test/mingle_events/page_test.rb require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) module MingleEvents class PageTest < Test::Unit::TestCase def test_entries_are_enumerable latest_entries_page = Page.new('https://mingle.example.com/api/v2/projects/atlas/feeds/events.xml', stub_mingle_access) assert_equal([ 'https://mingle.example.com/projects/atlas/events/index/103', 'https://mingle.example.com/projects/atlas/events/index/101', 'https://mingle.example.com/projects/atlas/events/index/100' ], latest_entries_page.entries.map(&:entry_id)) end def test_next_page_returns_the_next_page_of_entries_as_specified_by_next_link latest_entries_page = Page.new('https://mingle.example.com/api/v2/projects/atlas/feeds/events.xml', stub_mingle_access) next_page = latest_entries_page.next assert_equal('https://mingle.example.com/api/v2/projects/atlas/feeds/events.xml?page=23', latest_entries_page.next.url) assert_equal(['https://mingle.example.com/projects/atlas/events/index/97'], next_page.entries.map(&:entry_id)) end def test_next_page_when_on_last_page last_page = Page.new('https://mingle.example.com/api/v2/projects/atlas/feeds/events.xml?page=23', stub_mingle_access) assert_nil(last_page.next) end end end<file_sep>/lib/mingle_events.rb require 'fileutils' require 'net/https' require 'yaml' require 'time' require 'logger' require 'rubygems' require 'nokogiri' require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'http_error')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'poller')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'mingle_basic_auth_access')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'mingle_oauth_access')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'element_support')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'project_feed')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'project_event_broadcaster')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'page')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'category')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'entry')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'author')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'processors')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'project_custom_properties')) require File.expand_path(File.join(File.dirname(__FILE__), 'mingle_events', 'mingle_feed_cache')) <file_sep>/lib/mingle_events/author.rb module MingleEvents # The user who's Mingle activity triggered this event class Author include ElementSupport # The name of the author attr_reader :name # The email address of the author attr_reader :email # The URI identifying the author as well as location of his profile data attr_reader :uri # The URI for the author's icon attr_reader :icon_uri def initialize(author_element) @name = element_text(author_element, 'name') @email = element_text(author_element, 'email', true) @uri = element_text(author_element, 'uri', true) @icon_uri = element_text(author_element, 'mingle:icon', true) end end end<file_sep>/test/mingle_events/mingle_feed_cache_test.rb require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) module MingleEvents class MingleFeedCacheTest < Test::Unit::TestCase def test_will_never_cache_latest_events source = LoggingStubMingleAccess.new( 'http://example.com/api/v2/projects/foo/feeds/events.xml' => 'foo feed content' ) cache = MingleFeedCache.new(source, temp_dir) assert_equal 'foo feed content', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/events.xml') assert_equal 'foo feed content', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/events.xml') source.assert_fetches([ 'http://example.com/api/v2/projects/foo/feeds/events.xml', 'http://example.com/api/v2/projects/foo/feeds/events.xml' ]) end def test_scheme_and_host_and_port_are_ignored_when_determining_to_not_cache source = LoggingStubMingleAccess.new( 'http://example.com/api/v2/projects/foo/feeds/events.xml' => 'foo feed content', '/api/v2/projects/foo/feeds/events.xml' => 'bogus but different feed content' ) cache = MingleFeedCache.new(source, temp_dir) assert_equal 'foo feed content', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/events.xml') assert_equal 'bogus but different feed content', cache.fetch_page('/api/v2/projects/foo/feeds/events.xml') source.assert_fetches([ 'http://example.com/api/v2/projects/foo/feeds/events.xml', '/api/v2/projects/foo/feeds/events.xml' ]) end def test_will_never_cache_latest_events_with_app_context_and_absolute_paths source = LoggingStubMingleAccess.new( 'http://example.com/context/api/v2/projects/foo/feeds/events.xml' => 'foo feed content' ) cache = MingleFeedCache.new(source, temp_dir) assert_equal 'foo feed content', cache.fetch_page('http://example.com/context/api/v2/projects/foo/feeds/events.xml') assert_equal 'foo feed content', cache.fetch_page('http://example.com/context/api/v2/projects/foo/feeds/events.xml') source.assert_fetches([ 'http://example.com/context/api/v2/projects/foo/feeds/events.xml', 'http://example.com/context/api/v2/projects/foo/feeds/events.xml' ]) end def test_will_never_cache_latest_events_with_app_context_and_relative_paths source = LoggingStubMingleAccess.new( '/context/api/v2/projects/foo/feeds/events.xml' => 'foo feed content' ) cache = MingleFeedCache.new(source, temp_dir) assert_equal 'foo feed content', cache.fetch_page('/context/api/v2/projects/foo/feeds/events.xml') assert_equal 'foo feed content', cache.fetch_page('/context/api/v2/projects/foo/feeds/events.xml') source.assert_fetches([ '/context/api/v2/projects/foo/feeds/events.xml', '/context/api/v2/projects/foo/feeds/events.xml' ]) end def test_will_cache_archived_event_pages_with_both_relative_and_absolute_paths source = LoggingStubMingleAccess.new( 'http://example.com/api/v2/projects/foo/feeds/events.xml?page=23' => 'foo feed content' ) cache = MingleFeedCache.new(source, temp_dir) assert_equal 'foo feed content', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/events.xml?page=23') assert_equal 'foo feed content', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/events.xml?page=23') assert_equal 'foo feed content', cache.fetch_page('/api/v2/projects/foo/feeds/events.xml?page=23') source.assert_fetches([ 'http://example.com/api/v2/projects/foo/feeds/events.xml?page=23' ]) end def test_scheme_and_host_and_port_are_ignored_when_reading_from_cache_for_archived_event_pages source = LoggingStubMingleAccess.new( 'http://example.com/api/v2/projects/foo/feeds/events.xml?page=23' => 'foo feed content' ) cache = MingleFeedCache.new(source, temp_dir) assert_equal 'foo feed content', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/events.xml?page=23') assert_equal 'foo feed content', cache.fetch_page('/api/v2/projects/foo/feeds/events.xml?page=23') source.assert_fetches([ 'http://example.com/api/v2/projects/foo/feeds/events.xml?page=23' ]) end def test_query_is_correctly_cached source = LoggingStubMingleAccess.new( 'http://example.com/api/v2/projects/foo/feeds/events.xml?page=23' => 'page 23 content', 'http://example.com/api/v2/projects/foo/feeds/events.xml?page=24' => 'page 24 content' ) cache = MingleFeedCache.new(source, temp_dir) assert_equal 'page 23 content', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/events.xml?page=23') assert_equal 'page 23 content', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/events.xml?page=23') assert_equal 'page 24 content', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/events.xml?page=24') assert_equal 'page 24 content', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/events.xml?page=24') source.assert_fetches([ 'http://example.com/api/v2/projects/foo/feeds/events.xml?page=23', 'http://example.com/api/v2/projects/foo/feeds/events.xml?page=24' ]) end def test_will_not_cache_a_variety_of_other_url_patterns source = LoggingStubMingleAccess.new( 'http://example.com/' => '1', 'http://example.com/api/v2/projects/foo/feeds/another.xml' => '2', 'http://example.com/api/v2/projects/foo/cards/execute_mql?MQL=boo' => '3' ) cache = MingleFeedCache.new(source, temp_dir) assert_equal '1', cache.fetch_page('http://example.com/') assert_equal '1', cache.fetch_page('http://example.com/') assert_equal '2', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/another.xml') assert_equal '2', cache.fetch_page('http://example.com/api/v2/projects/foo/feeds/another.xml') assert_equal '3', cache.fetch_page('http://example.com/api/v2/projects/foo/cards/execute_mql?MQL=boo') assert_equal '3', cache.fetch_page('http://example.com/api/v2/projects/foo/cards/execute_mql?MQL=boo') source.assert_fetches([ 'http://example.com/', 'http://example.com/', 'http://example.com/api/v2/projects/foo/feeds/another.xml', 'http://example.com/api/v2/projects/foo/feeds/another.xml', 'http://example.com/api/v2/projects/foo/cards/execute_mql?MQL=boo', 'http://example.com/api/v2/projects/foo/cards/execute_mql?MQL=boo' ]) end class LoggingStubMingleAccess include Test::Unit::Assertions def initialize(content_by_path = {}) @content_by_path = content_by_path @fetches = [] end def fetch_page(path) @fetches << path @content_by_path[path] end def assert_fetches(fetches) assert_equal(fetches, @fetches) end end end end<file_sep>/Rakefile require 'rake' require 'rake/testtask' # require 'echoe' require 'lib/mingle_events' task :default => [:test, :clean] desc "Run tests" Rake::TestTask.new do |task| task.pattern = 'test/**/*_test.rb' task.verbose = true task.warning = true end # Echoe.new('mingle-events', '0.0.1') do |p| # p.description = "A gem that lets you process Mingle events in a pipes and filters style." # p.url = "https://github.com/ThoughtWorksStudios/mingle-events" # p.author = "<NAME>" # p.email = "david.rice at gmail dot com" # p.ignore_pattern = ["test/**/*.rb", "high_level_design.graffle", "stories.textile", "Rakefile"] # p.development_dependencies = [] # end task :clean do FileUtils.rm_rf('test/tmp') end task :poll_once_example do state_folder = File.join(File.dirname(__FILE__), 'example_app_state') cache_folder = File.join(File.dirname(__FILE__), 'example_app_feed_cache') FileUtils.rm_rf(state_folder) if ENV['CLEAN'] == 'true' FileUtils.rm_rf(cache_folder) if ENV['CLEAN'] == 'true' mingle_access = MingleEvents::MingleBasicAuthAccess.new( 'https://mingle.example.com:7071', ENV['MINGLE_USER'], ENV['MINGLE_PASSWORD'] ) mingle_access_cache = MingleEvents::MingleFeedCache.new(mingle_access, cache_folder) card_data = MingleEvents::Processors::CardData.new(mingle_access_cache, 'test_project') log_commenting_on_high_priority_stories = MingleEvents::Processors::Pipeline.new([ card_data, MingleEvents::Processors::CardTypeFilter.new(['Story'], card_data), MingleEvents::Processors::CustomPropertyFilter.new('Priority', 'High', card_data), MingleEvents::Processors::CategoryFilter.new([MingleEvents::Category::COMMENT_ADDITION]), MingleEvents::Processors::PutsPublisher.new ]) processors_by_project = { 'test_project' => [log_commenting_on_high_priority_stories] } MingleEvents::Poller.new(mingle_access_cache, processors_by_project, state_folder, true).run_once end<file_sep>/lib/mingle_events/processors/card_data.rb module MingleEvents module Processors # Provides ability to lookup card data, e.g., card's type name, for any # card serving as a source for the stream of events. Implements two interfaces: # the standard event processing interface, handle_events, and also, for_card_event, # which returns of has of card data for the given event. See the project README # for additional information on using this class in a processing pipeline. class CardData def initialize(mingle_access, project_identifier, custom_properties = ProjectCustomProperties.new(mingle_access, project_identifier)) @mingle_access = mingle_access @project_identifier = project_identifier @custom_properties = custom_properties @card_data_by_number_and_version = nil end # Capture which events are card events and might require data lookup. The # actual data retrieval is lazy and will only occur as needed. def process_events(events) @card_events = events.select(&:card?) events end # Return a hash of data for the card that sourced the passed event. The data # will be for the version of the card that was created by the event and not the # current state of the card. Currently supported data keys are: :number, :version, # :card_type_name def for_card_event(card_event) if @card_data_by_number_and_version.nil? load_bulk_card_data end key = data_key(card_event.card_number, card_event.version) @card_data_by_number_and_version[key] ||= load_card_data_for_event(card_event) end private def data_key(number, version) "#{number}:#{version}" end def load_bulk_card_data @card_data_by_number_and_version = {} # TODO: figure out max number of card numbers before we have to chunk this up. or does mingle # figure out how to handle a too-large IN clause? card_numbers = @card_events.map(&:card_number).uniq path = "/api/v2/projects/#{@project_identifier}/cards/execute_mql.xml?mql=WHERE number IN (#{card_numbers.join(',')})" raw_xml = @mingle_access.fetch_page(URI.escape(path)) doc = Nokogiri::XML(raw_xml) doc.search('/results/result').map do |card_result| card_number = card_result.at('number').inner_text.to_i card_version = card_result.at('version').inner_text.to_i custom_properties = {} @card_data_by_number_and_version[data_key(card_number, card_version)] = { :number => card_number, :version => card_version, :card_type_name => card_result.at('card_type_name').inner_text, :custom_properties => custom_properties } card_result.children.each do |child| if child.name.index("cp_") == 0 value = if child['nil'] == "true" nil else child.inner_text end custom_properties[@custom_properties.property_name_for_column(child.name)] = value end end end end def load_card_data_for_event(card_event) begin page_xml = @mingle_access.fetch_page(card_event.card_version_resource_uri) doc = Nokogiri::XML(page_xml) custom_properties = {} result = { :number => card_event.card_number, :version => card_event.version, :card_type_name => doc.at('/card/card_type/name').inner_text, :custom_properties => custom_properties } doc.search('/card/properties/property').each do |property| custom_properties[property.at('name').inner_text] = property.at('value').inner_text end result rescue HttpError => httpError raise httpError unless httpError.not_found? end end end end end<file_sep>/lib/mingle_events/element_support.rb module MingleEvents # Provides some helpers for pulling values from Nokogiri Elems module ElementSupport def element_text(parent_element, element_name, optional = false) element = parent_element.at(".//#{element_name}") if optional && element.nil? nil else element.inner_text end end end end<file_sep>/lib/mingle_events/entry.rb module MingleEvents # A Ruby wrapper around an Atom entry, particularly an Atom entry # representing an event in Mingle. class Entry # Construct with the wrapped Nokogiri Elem for the entry def initialize(entry_element) @entry_element = entry_element end # The raw entry XML from the Atom feed def raw_xml @raw_xml ||= @entry_element.to_s end # The Atom entry's id value. This is the one true identifier for the entry, # and therefore the event. def entry_id @entry_id ||= @entry_element.at('id').inner_text end alias :event_id :entry_id # The Atom entry's title def title @title ||= @entry_element.at('title').inner_text end # The time at which entry was created, i.e., the event was triggered def updated @updated ||= Time.parse(@entry_element.at('updated').inner_text) end # The user who created the entry (triggered the event), i.e., changed project data in Mingle def author @author ||= Author.new(@entry_element.at('author')) end # The set of Atom categoies describing the entry def categories @categories ||= @entry_element.search('category').map do |category_element| Category.new(category_element.attribute('term').text, category_element.attribute('scheme').text) end end # Whether the entry/event was sourced by a Mingle card def card? categories.any?{|c| c == Category::CARD} end # The number of the card that sourced this entry/event. If the entry is not a card event # an error will be thrown. The source of this data is perhaps not so robust and we'll need # to revisit this in the next release of Mingle. def card_number raise "You cannot get the card number for an event that is not sourced by a card!" unless card? @card_number ||= parse_card_number end # The version number of the card or page that was created by this event. (For now, only # working with cards.) def version @version ||= CGI.parse(URI.parse(card_version_resource_uri).query)['version'].first.to_i end # The resource URI for the card version that was created by this event. Throws error if not card event. def card_version_resource_uri raise "You cannot get card version data for an event that is not sourced by a card!" unless card? @card_version_resource_uri ||= parse_card_version_resource_uri end private def parse_card_number card_number_element = @entry_element.at( "link[@rel='http://www.thoughtworks-studios.com/ns/mingle#event-source'][@type='application/vnd.mingle+xml']" ) # TODO: improve this bit of parsing :) card_number_element.attribute('href').text.split('/').last.split('.')[0..-2].join.to_i end def parse_card_version_resource_uri card_number_element = @entry_element.at( "link[@rel='http://www.thoughtworks-studios.com/ns/mingle#version'][@type='application/vnd.mingle+xml']" ) card_number_element.attribute('href').text end end end<file_sep>/lib/mingle_events/processors/author_filter.rb module MingleEvents module Processors # Removes all events from stream not triggered by the specified author class AuthorFilter def initialize(spec, mingle_access, project_identifier) unless spec.size == 1 raise "Author spec must contain 1 and only 1 piece of criteria (the only legal criteria are each unique identifiers in and of themselves so multiple criteria is not needed.)" end @author_spec = AuthorSpec.new(spec, mingle_access, project_identifier) end def process_events(events) events.select{|event| @author_spec.event_triggered_by?(event)} end class AuthorSpec def initialize(spec, mingle_access, project_identifier) @spec = spec @mingle_access = mingle_access @project_identifier = project_identifier end def event_triggered_by?(event) event.author.uri == author_uri end private def author_uri lookup_author_uri end def lookup_author_uri team_resource = "/api/v2/projects/#{@project_identifier}/team.xml" @raw_xml ||= @mingle_access.fetch_page(URI.escape(team_resource)) @doc ||= Nokogiri::XML(@raw_xml) users = @doc.search('/projects_members/projects_member/user').map do |user| { :url => user.attribute('url').inner_text, :login => user.at('login').inner_text, :email => user.at('email').inner_text } end spec_user = users.find do |user| # is this too hacky? user.merge(@spec) == user end spec_user.nil? ? nil : spec_user[:url] end end end end end<file_sep>/test/mingle_events/processors/author_filter_test.rb require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper')) module MingleEvents module Processors class AuthorFilterTest < Test::Unit::TestCase def setup @dummy_mingle_access = StubMingleAccess.new @dummy_mingle_access.register_page_content( '/api/v2/projects/atlas/team.xml', %{ <projects_members type="array"> <projects_member> <user url="http://example.com/users/10.xml"> <id type="integer">333</id> <name><NAME></name> <login>ctester</login> <email><EMAIL></email> </user> </proejcts_member> <projects_member> <user url="http://example.com/users/17.xml"> <id type="integer">444</id> <name><NAME></name> <login>jdeveloper</login> <email><EMAIL></email> </user> </proejcts_member> <projects_members> } ) @event_1 = stub_event(1, {:uri => "http://example.com/users/10.xml", :login => 'ctester'}) @event_2 = stub_event(2, {:uri => "http://example.com/users/17.xml", :login => 'jdeveloper'}) @event_3 = stub_event(3, {:uri => "http://example.com/users/10.xml", :login => 'ctester'}) @unprocessed_events = [@event_1, @event_2, @event_3] end def test_filter_can_only_be_constructed_with_a_single_criteria begin AuthorFilter.new({:url => 'foo', :email => 'bar'}, nil, nil) fail("Should not have been able to construct this filter!") rescue StandardError => e assert_equal(0, e.message.index("Author spec must contain 1 and only 1 piece of criteria")) end end def test_filter_by_author_url author_filter = AuthorFilter.new({:url => 'http://example.com/users/10.xml'}, @dummy_mingle_access, 'atlas') filtered_events = author_filter.process_events(@unprocessed_events) assert_equal([@event_1, @event_3], filtered_events) end def test_filter_by_author_login author_filter = AuthorFilter.new({:login => 'ctester'}, @dummy_mingle_access, 'atlas') filtered_events = author_filter.process_events(@unprocessed_events) assert_equal([@event_1, @event_3], filtered_events) end def test_filter_by_author_email author_filter = AuthorFilter.new({:email => '<EMAIL>'}, @dummy_mingle_access, 'atlas') filtered_events = author_filter.process_events(@unprocessed_events) assert_equal([@event_2], filtered_events) end def test_filter_returns_empty_list_when_no_match author_filter = AuthorFilter.new({:email => '<EMAIL>'}, @dummy_mingle_access, 'atlas') filtered_events = author_filter.process_events(@unprocessed_events) assert_equal([], filtered_events) end private def stub_event(entry_id, author) OpenStruct.new(:entry_id => entry_id, :author => OpenStruct.new(author)) end end end end <file_sep>/lib/mingle_events/project_event_broadcaster.rb module MingleEvents # For a given project, polls for previously unseen events and broadcasts these events # to a list of processors, all interested in the project's events. #-- # TODO: Need a better name for this class class ProjectEventBroadcaster def initialize(mingle_feed, event_processors, state_file, initial_event_count = 25, logger = Logger.new(STDOUT)) @mingle_feed = mingle_feed @event_processors = event_processors @state_file = state_file @initial_event_count = initial_event_count @logger = logger end # Perform the polling for new events and subsequent broadasting to interested processors def run_once if !initialized? process_initial_events ensure_state_initialized else process_latest_events end end private def process_initial_events initial_entries = if initial_read_is_from_beginning_of_time? @mingle_feed.entries.to_a else @mingle_feed.entries.take(@initial_event_count) end process_events(initial_entries.reverse) end def process_latest_events unseen_entries = [] @mingle_feed.entries.each do |entry| break if entry.entry_id == last_event_id unseen_entries << entry end process_events(unseen_entries.reverse) end def process_events(events) @event_processors.each do |processor| begin processor.process_events(events) rescue StandardError => e @logger.info(%{ Unable to complete event processing for processor #{processor}. There will be no re-try for one or more of the events below. Also, some of the events below may have actually been processed. In order to have a more accurate understanding of which events were processed and which were not processed you will need to add more precise error handling to your processor. If you are writing a publisher/notifier (and not a filter) you should consider writing a subclass of AbstractNoRetryProcessor in order to narrow the scope of processing failure to single events. Root Cause: #{e} Trace: #{e.backtrace.join("\n")} Events: #{events} }) end end # TODO: write unit test for not writing state when events is empty (and correlate with the init scenario) write_last_event_seen(events.last) unless events.empty? end def initial_read_is_from_beginning_of_time? @initial_event_count.nil? || @initial_event_count == :all end def last_event_id read_state[:last_event_id] end def initialized? File.exist?(@state_file) end def ensure_state_initialized write_last_event_seen(nil) unless initialized? end def read_state @state ||= YAML.load(File.new(@state_file)) end def write_last_event_seen(last_event) FileUtils.mkdir_p(File.dirname(@state_file)) File.open(@state_file, 'w') do |out| YAML.dump({:last_event_id => last_event.nil? ? nil : last_event.entry_id}, out) end end end end<file_sep>/test/mingle_events/processors/card_type_filter_test.rb require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper')) module MingleEvents module Processors class CardTypeFilterTest < Test::Unit::TestCase def test_filters_events_on_card_type event_1 = stub_event(true) event_2 = stub_event(false) event_3 = stub_event(true) event_4 = stub_event(true) event_5 = stub_event(true) card_data = { event_1 => {:card_type_name => 'story'}, event_3 => {:card_type_name => 'bug'}, event_4 => {:card_type_name => 'story'}, event_5 => {:card_type_name => 'issue'} } def card_data.for_card_event(card_event) self[card_event] end filter = CardTypeFilter.new(['story', 'issue'], card_data) filtered_events = filter.process_events([event_1, event_2, event_3, event_4, event_5]) assert_equal([event_1, event_4, event_5], filtered_events) end def test_drops_events_for_deleted_cards event_1 = stub_event(true) card_data = {} def card_data.for_card_event(card_event) self[card_event] end filter = CardTypeFilter.new(['story', 'issue'], card_data) filtered_events = filter.process_events([event_1]) assert_equal([], filtered_events) end private def stub_event(is_card) OpenStruct.new(:card? => is_card) end end end end <file_sep>/lib/mingle_events/project_custom_properties.rb module MingleEvents class ProjectCustomProperties def initialize(mingle_access, project_identifier) @mingle_access = mingle_access @project_identifier = project_identifier end def property_name_for_column(column_name) property_names_by_column_name[column_name] end private def property_names_by_column_name @property_names_by_column_name ||= lookup_property_names_by_column_name end def lookup_property_names_by_column_name as_document.search('/property_definitions/property_definition').inject({}) do |mapping, element| mapping[element.at('column_name').inner_text] = element.at('name').inner_text mapping end end def as_document @as_document ||= Nokogiri::XML(@mingle_access.fetch_page("/api/v2/projects/#{@project_identifier}/property_definitions.xml")) end end end<file_sep>/test/mingle_events/project_feed_test.rb require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) module MingleEvents class ProjectFeedTest < Test::Unit::TestCase def test_can_enumerate_entries_across_pages feed = ProjectFeed.new('atlas', stub_mingle_access) assert_equal([ 'https://mingle.example.com/projects/atlas/events/index/103', 'https://mingle.example.com/projects/atlas/events/index/101', 'https://mingle.example.com/projects/atlas/events/index/100', 'https://mingle.example.com/projects/atlas/events/index/97' ], feed.entries.map(&:entry_id)) end end end<file_sep>/lib/mingle_events/project_feed.rb module MingleEvents # Simple means of iterating over a project's events, hiding the mechanics # of pagination. class ProjectFeed def initialize(project_identifier, mingle_access) @mingle_access = mingle_access @project_identifier = project_identifier end # All entries/events for a project, starting with the most recent. Be careful # not to take all events for a project with significant history without considering # the time this will require. def entries AllEntries.new(Page.new(latest_events_path, @mingle_access)) end private def latest_events_path "/api/v2/projects/#{@project_identifier}/feeds/events.xml" end class AllEntries include Enumerable def initialize(first_page) @current_page = first_page end def each while (@current_page) @current_page.entries.each{|e| yield e} @current_page = @current_page.next end end # TODO: what do i really want to do here? def <=>(other) return 0 end end end end<file_sep>/lib/mingle_events/processors/http_post_publisher.rb module MingleEvents module Processors # Posts each event in stream to the specified URL #-- # TODO: figure out what to do with basic/digest auth and HTTPS. are they separate processors? class HttpPostPublisher < AbstractNoRetryProcessor def initialize(url) @url = url end def process_event(event) Net::HTTP.post_form(URI.parse(@url), {'event' => event.raw_xml}).body end end end end <file_sep>/test/mingle_events/processors/category_filter_test.rb require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper')) module MingleEvents module Processors class CategoryFilterTest < Test::Unit::TestCase def test_removes_events_without_matching_categories event_1 = stub_event(1, [Category::CARD, Category::COMMENT_ADDITION]) event_2 = stub_event(2, [Category::CARD, Category::PROPERTY_CHANGE]) event_3 = stub_event(3, [Category::REVISION_COMMIT]) event_4 = stub_event(4, [Category::CARD, Category::PROPERTY_CHANGE]) event_5 = stub_event(5, []) events = [event_1, event_2, event_3, event_4, event_5] filter = CategoryFilter.new([Category::CARD, Category::PROPERTY_CHANGE]) assert_equal([event_2, event_4], filter.process_events(events)) end private def stub_event(id, categories) OpenStruct.new(:entry_id => id, :categories => categories) end end end end <file_sep>/test/mingle_events/project_event_broadcaster_test.rb require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) module MingleEvents class ProjectEventBroadcasterTest < Test::Unit::TestCase def test_can_broadcast_all_events_from_beginning_of_time_passing_all_symbol processor = DummyAbstractNoRetryProcessor.new feed = DummyFeed.new event_broadcaster = ProjectEventBroadcaster.new(feed, [processor], temp_file, :all) event_broadcaster.run_once assert_equal(30, processor.processed_events.count) end def test_can_broadcast_all_events_from_beginning_of_time_passing_nil processor = DummyAbstractNoRetryProcessor.new feed = DummyFeed.new event_broadcaster = ProjectEventBroadcaster.new(feed, [processor], temp_file, nil) event_broadcaster.run_once assert_equal(30, processor.processed_events.count) end def test_can_process_only_recent_history processor = DummyAbstractNoRetryProcessor.new feed = DummyFeed.new event_broadcaster = ProjectEventBroadcaster.new(feed, [processor], temp_file) event_broadcaster.run_once assert_equal(25, processor.processed_events.count) assert_equal('http://example.com/entry/6', processor.processed_events.first.entry_id) assert_equal('http://example.com/entry/30', processor.processed_events.last.entry_id) end def test_initializes_new_project_even_when_no_new_events processor = DummyAbstractNoRetryProcessor.new feed = DummyFeed.new(0) state_file = temp_file event_broadcaster = ProjectEventBroadcaster.new(feed, [processor], state_file) event_broadcaster.run_once feed = DummyFeed.new event_broadcaster = ProjectEventBroadcaster.new(feed, [processor], state_file) event_broadcaster.run_once # we would only get beyond a page of events if previously initialized assert_equal(30, processor.processed_events.count) end def test_publishses_all_events_beyond_last_event_for_initialized_project state_file = temp_file File.open(state_file, 'w') do |io| YAML.dump({:last_event_id => 'http://example.com/entry/28'}, io) end processor = DummyAbstractNoRetryProcessor.new feed = DummyFeed.new event_broadcaster = ProjectEventBroadcaster.new(feed, [processor], state_file) event_broadcaster.run_once assert_equal( ['http://example.com/entry/29', 'http://example.com/entry/30'], processor.processed_events.map(&:entry_id) ) end def test_does_nothing_when_no_new_events processor = DummyAbstractNoRetryProcessor.new feed = DummyFeed.new(5) state_file = temp_file event_broadcaster = ProjectEventBroadcaster.new(feed, [processor], temp_file) event_broadcaster.run_once assert_equal(5, processor.processed_events.count) processor = DummyAbstractNoRetryProcessor.new feed = DummyFeed.new(0) event_broadcaster = ProjectEventBroadcaster.new(feed, [processor], temp_file) assert_equal(0, processor.processed_events.count) end def test_publishes_to_all_subscribers processor_1 = DummyAbstractNoRetryProcessor.new processor_2 = DummyAbstractNoRetryProcessor.new feed = DummyFeed.new(2) event_broadcaster = ProjectEventBroadcaster.new(feed, [processor_1, processor_2], temp_file) event_broadcaster.run_once assert_equal(2, processor_1.processed_events.count) assert_equal(2, processor_2.processed_events.count) end #-- # TODO: validate that this test is even remotely legit. i'm not feeling good # about this failure scenario :( def test_failure_during_process_events_does_not_block_other_processors_from_processing_events good_processor_1 = DummyAbstractNoRetryProcessor.new exploding_processor = DummyAbstractNoRetryProcessor.new def exploding_processor.process_events(events) events.each do |event| process_event(event) end events end def exploding_processor.process_event(event) if event.entry_id == 'http://example.com/entry/29' raise "Blowing up on 29!" else super(event) end end good_processor_2 = DummyAbstractNoRetryProcessor.new feed = DummyFeed.new(3) log_stream = StringIO.new event_broadcaster = ProjectEventBroadcaster.new( feed, [good_processor_1, exploding_processor, good_processor_2], temp_file, 25, Logger.new(log_stream)) event_broadcaster.run_once assert(log_stream.string.index('Unable to complete event processing')) assert_equal( ['http://example.com/entry/28', 'http://example.com/entry/29', 'http://example.com/entry/30'], good_processor_1.processed_events.map(&:entry_id)) assert_equal( ['http://example.com/entry/28'], exploding_processor.processed_events.map(&:entry_id)) assert_equal( ['http://example.com/entry/28', 'http://example.com/entry/29', 'http://example.com/entry/30'], good_processor_2.processed_events.map(&:entry_id)) end class DummyAbstractNoRetryProcessor < MingleEvents::Processors::AbstractNoRetryProcessor attr_reader :processed_events def initialize @processed_events = [] end def process_event(event) @processed_events << event end end class DummyFeed LAST_ENTRY = 30 def initialize(entry_count = LAST_ENTRY) @entry_count = entry_count @fixed_time_point = Time.parse('2011-02-03T01:00:52Z') end def entries (LAST_ENTRY.downto(LAST_ENTRY - @entry_count + 1)).map do |i| OpenStruct.new( :entry_id => "http://example.com/entry/#{i}", :updated => @fixed_time_point - i ) end end end class DummyDeadLetterOffice attr_reader :unprocessed_events def deliver(error, *events) events.each{|e| (@unprocessed_events ||= []) << e} end end end end<file_sep>/test/test_helper.rb require 'test/unit' require 'ostruct' require 'fileutils' require 'rubygems' require 'active_support' require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'mingle_events')) class Test::Unit::TestCase FIRST_PAGE_CONTENT = %{ <feed xmlns="http://www.w3.org/2005/Atom" xmlns:mingle="http://www.thoughtworks-studios.com/ns/mingle"> <link href="https://mingle.example.com/api/v2/projects/atlas/feeds/events.xml?page=23" rel="next"/> <entry> <id>https://mingle.example.com/projects/atlas/events/index/103</id> <title>entry 103</title> <updated>2011-02-03T08:12:42Z</updated> <author><name>Bob</name></author> </entry> <entry> <id>https://mingle.example.com/projects/atlas/events/index/101</id> <title>entry 101</title> <updated>2011-02-03T02:09:16Z</updated> <author><name>Bob</name></author> </entry> <entry> <id>https://mingle.example.com/projects/atlas/events/index/100</id> <title>entry 100</title> <updated>2011-02-03T01:58:02Z</updated> <author><name>Mary</name></author> </entry> </feed> } NEXT_PAGE_CONTENT = %{ <feed xmlns="http://www.w3.org/2005/Atom" xmlns:mingle="http://www.thoughtworks-studios.com/ns/mingle"> <entry> <id>https://mingle.example.com/projects/atlas/events/index/97</id> <title>entry 97</title> <updated>2011-02-03T01:00:52Z</updated> <author><name>Harry</name></author> </entry> </feed> } def stub_mingle_access stub = Object.new def stub.fetch_page(url) { 'https://mingle.example.com/api/v2/projects/atlas/feeds/events.xml?page=23' => NEXT_PAGE_CONTENT, 'https://mingle.example.com/api/v2/projects/atlas/feeds/events.xml' => FIRST_PAGE_CONTENT, # feed uses path only for first page, relying upon mingle access to convert # to absolute URI -- might need to revisit this 'design' :) '/api/v2/projects/atlas/feeds/events.xml' => FIRST_PAGE_CONTENT }[url] end stub end def temp_dir path = File.expand_path(File.join(File.dirname(__FILE__), 'tmp', ActiveSupport::SecureRandom.hex(16))) FileUtils.mkdir_p(path) path end def temp_file File.join(temp_dir, ActiveSupport::SecureRandom.hex(16)) end class StubMingleAccess def initialize @pages_by_path = {} @not_found_pages = [] end def register_page_content(path, content) @pages_by_path[path] = content end def register_page_not_found(path) @not_found_pages << path end def fetch_page(path) if @not_found_pages.include?(path) rsp = Net::HTTPNotFound.new(nil, '404', 'Page not found!') def rsp.body "404!!!!!" end raise MingleEvents::HttpError.new(rsp, path) end raise "Attempting to fetch page at #{path}, but your test has not registered content for this path! Registered paths: #{@pages_by_path.keys.inspect}" unless @pages_by_path.key?(path) @pages_by_path[path] end end class StubProjectCustomProperties def initialize(property_names_by_column_names) @property_names_by_column_names = property_names_by_column_names end def property_name_for_column(column_name) @property_names_by_column_names[column_name] end end end <file_sep>/lib/mingle_events/page.rb module MingleEvents # A page of Atom events. I.e., *not* a Mingle page. Most users of this library # will not use this class to access the Mingle Atom feed, but will use the # ProjectFeed class which handles paging transparently. class Page attr_accessor :url def initialize(url, mingle_access) @url = url @mingle_access = mingle_access end def entries @entries ||= page_as_document.search('feed/entry').map do |entry_element| Entry.new(entry_element) end end def next @next ||= construct_next_page end private def construct_next_page next_url_element = page_as_document.at("feed/link[@rel='next']") next_url_element.nil? ? nil : Page.new(next_url_element.attribute('href').text, @mingle_access) end def page_as_document @page_as_document ||= Nokogiri::XML(@mingle_access.fetch_page(@url)) end end end
47c6d99eeecf41b68c5313b36b7fc48e6059bb2c
[ "Ruby" ]
24
Ruby
xli/mingle-events
2b46253f27c3e6c28aad48b266c6e3b65695be48
077583c5c43eaf9c3bbc9bb9dcdaeab158732b14
refs/heads/master
<repo_name>alfchaval/InventoryFragment<file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/db/repository/DependencyRepository.java package com.example.usuario.inventoryfragment.db.repository; import com.example.usuario.inventoryfragment.pojo.Dependency; import java.util.ArrayList; import java.util.Collections; /** * @author <NAME> * Repositorio de dependencias */ public class DependencyRepository { /* Declaración */ private ArrayList<Dependency> dependencies; private static DependencyRepository dependencyRepository; /* Inicialización */ /* Inicializar todos los atributos de ámbito estático o de clase */ static { dependencyRepository = new DependencyRepository(); } public DependencyRepository() { this.dependencies = new ArrayList<>(); initialize(); } /** * El método ha de ser privado para garantizar que solo hay una instancia de Repository */ private void initialize() { addDependency(new Dependency(1, "1º Ciclo Formativo Grado Superior", "1CFGS", "1CFGS Desarrollo de aplicaciones multiplataforma")); addDependency(new Dependency(2, "2º Ciclo Formativo Grado Superior", "2CFGS", "2CFGS Desarrollo de aplicaciones multiplataforma")); addDependency(new Dependency(3, "Ejemplo 3", "EJ3", "Esto es un ejemplo")); addDependency(new Dependency(4, "Ejemplo 4", "EJ4", "Esto es un ejemplo")); addDependency(new Dependency(5, "Ejemplo 5", "EJ5", "Esto es un ejemplo")); addDependency(new Dependency(6, "Ejemplo 6", "EJ6", "Esto es un ejemplo")); addDependency(new Dependency(7, "Ejemplo 7", "EJ7", "Esto es un ejemplo")); addDependency(new Dependency(8, "Ejemplo 8", "EJ8", "Esto es un ejemplo")); addDependency(new Dependency(9, "Ejemplo 9", "EJ9", "Esto es un ejemplo")); addDependency(new Dependency(10, "Ejemplo 10", "EJ10", "Esto es un ejemplo")); addDependency(new Dependency(11, "Ejemplo 11", "EJ11", "Esto es un ejemplo")); addDependency(new Dependency(12, "Ejemplo 12", "EJ12", "Esto es un ejemplo")); addDependency(new Dependency(13, "Ejemplo 13", "EJ13", "Esto es un ejemplo")); } /* Métodos */ public static DependencyRepository getInstance() { if(dependencyRepository == null) { dependencyRepository = new DependencyRepository(); } return dependencyRepository; } /** * Método que añade una dependencia * @param dependency */ public int addDependency(Dependency dependency) { dependencies.add(dependency); return dependency.get_ID(); } public ArrayList<Dependency> getDependencies() { //El ArrayList se ordena según el criterio del método compareTo de la interfaz Comparable Collections.sort(dependencies); return dependencies; } public int getLastId() { return dependencies.get(dependencies.size() - 1).get_ID(); } public boolean nameExist(String name) { boolean result = false; int index = 0; while (!result && index < dependencies.size()) { if (name.equals(dependencies.get(index).getName())) { result = true; } else { index++; } } return result; } public boolean shortNameExist(String shortname) { boolean result = false; int index = 0; while (!result && index < dependencies.size()) { if (shortname.equals(dependencies.get(index).getShortName())) { result = true; } else { index++; } } return result; } public boolean validateDependency(String name, String shortname) { return nameExist(name) || shortNameExist(shortname); } public void editDependency(Dependency dependency) { boolean found = false; int index = 0; while (!found && index < dependencies.size()) { if (dependency.get_ID() == dependencies.get(index).get_ID()) { dependencies.get(index).setDescription(dependency.getDescription()); found = true; } else { index++; } } } public void deleteDependency(Dependency dependency) { boolean found = false; int index = 0; while (!found && index < dependencies.size()) { if (dependency.get_ID() == dependencies.get(index).get_ID()) { dependencies.remove(index); found = true; } else index++; } /** Iterator<Dependency> iterator = dependencies.iterator(); Dependency dependency; while (iterator.hasNext()) { dependency = iterator.next(); if (dependency.get_name().equals(dependency.get_name())) { iterator.remove(); } } */ } } <file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/pojo/Dependency.java package com.example.usuario.inventoryfragment.pojo; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import java.util.Comparator; /** * @author <NAME> * Clase pojo de las dependencias */ public class Dependency implements Comparable, Parcelable{ private int _ID; private String name; private String shortname; private String description; public Dependency(int _ID, String name, String shortname, String description) { this._ID = _ID; this.name = name; this.shortname = shortname; this.description = description; } protected Dependency(Parcel in) { _ID = in.readInt(); name = in.readString(); shortname = in.readString(); description = in.readString(); } public static final Creator<Dependency> CREATOR = new Creator<Dependency>() { @Override public Dependency createFromParcel(Parcel in) { return new Dependency(in); } @Override public Dependency[] newArray(int size) { return new Dependency[size]; } }; public int get_ID() { return _ID; } public void set_ID(int _ID) { this._ID = _ID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getShortName() { return shortname; } public void setShortName(String shortname) { this.shortname = shortname; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "NAME: " + name + '\n' + "SHORTNAME: " + shortname + '\n' + "DESCRIPTION: " + description; } @Override public int compareTo(@NonNull Object o) { return name.compareTo(((Dependency)o).name); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(_ID); parcel.writeString(name); parcel.writeString(shortname); parcel.writeString(description); } public static class DependencyOrderByShortName implements Comparator<Dependency> { @Override public int compare(Dependency d1, Dependency d2) { return d1.shortname.toLowerCase().compareTo(d2.shortname.toLowerCase()); } } } <file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/ui/base/BaseFragment.java package com.example.usuario.inventoryfragment.ui.base; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.view.View; public class BaseFragment extends Fragment { public void showMessage(String message) { Snackbar.make(getActivity().findViewById(android.R.id.content), message, Snackbar.LENGTH_SHORT).show(); } public void onError(View view, String message) { Snackbar.make(view, message, Snackbar.LENGTH_SHORT).show(); } } <file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/ui/inventory/InventoryApplication.java package com.example.usuario.inventoryfragment.ui.inventory; import android.app.Application; import com.example.usuario.inventoryfragment.db.repository.DependencyRepository; /** * @author <NAME> */ public class InventoryApplication extends Application { public InventoryApplication() { } @Override public void onCreate() { super.onCreate(); } public DependencyRepository getDependencyRepository() { return getDependencyRepository(); } } <file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/ui/prefs/GeneralSettingsActivity.java package com.example.usuario.inventoryfragment.ui.prefs; import android.os.Bundle; import android.preference.PreferenceActivity; import android.support.annotation.Nullable; import com.example.usuario.inventoryfragment.R; /** * @author <NAME> */ public class GeneralSettingsActivity extends PreferenceActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.general_settings); } } <file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/ui/dependency/interactor/DetailInteractor.java package com.example.usuario.inventoryfragment.ui.dependency.interactor; /** * Created by usuario on 11/23/17. */ public class DetailInteractor { } <file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/ui/dependency/contract/ListDependencyContract.java package com.example.usuario.inventoryfragment.ui.dependency.contract; import com.example.usuario.inventoryfragment.pojo.Dependency; import com.example.usuario.inventoryfragment.ui.base.BasePresenter; import com.example.usuario.inventoryfragment.ui.base.BaseView; import java.util.List; /** * Created by usuario on 11/23/17. */ public interface ListDependencyContract { interface View extends BaseView{ void showDependency(List<Dependency> list); } interface Presenter extends BasePresenter{ void addNewDependency(); void loadDependency(); void deleteDependency(Dependency dependency); } interface Interactor { void loadDependencies(OnFinishedLoadDependency onFinishedLoadDependency); void deleteDependency(Dependency dependency, OnFinishedLoadDependency listener); interface OnFinishedLoadDependency { void onSuccess(List<Dependency> dependencies); } } } <file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/ui/dependency/AddEditDependency.java package com.example.usuario.inventoryfragment.ui.dependency; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TextInputLayout; import android.support.v4.app.FragmentManager; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.example.usuario.inventoryfragment.R; import com.example.usuario.inventoryfragment.db.repository.DependencyRepository; import com.example.usuario.inventoryfragment.pojo.Dependency; import com.example.usuario.inventoryfragment.ui.base.BaseFragment; import com.example.usuario.inventoryfragment.ui.base.BasePresenter; import com.example.usuario.inventoryfragment.ui.dependency.contract.AddEditDependencyContract; import com.example.usuario.inventoryfragment.ui.dependency.contract.ListDependencyContract; import com.example.usuario.inventoryfragment.ui.dependency.interactor.AddEditInteractor; import com.example.usuario.inventoryfragment.ui.utils.AddEdit; /** * @author <NAME> */ public class AddEditDependency extends BaseFragment implements AddEditDependencyContract.View { public static final String TAG = "AddEditDependency"; public static final String EDIT_KEY = "edit"; private AddEditDependencyContract.Presenter presenter; private ListDependency.ListDependencyListener callback; private AddEdit addEditMode; private FloatingActionButton fab; private TextInputLayout tilName; private TextInputLayout tilShortName; private TextInputLayout tilDescription; private EditText edtName; private EditText edtShortName; private EditText edtDescription; int position = -1; public static AddEditDependency newInstance(Bundle arguments) { AddEditDependency addEditDependency = new AddEditDependency(); if(arguments != null) { addEditDependency.setArguments(arguments); } return addEditDependency; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { callback = (ListDependency.ListDependencyListener) activity; } catch (ClassCastException e) { throw new ClassCastException(getActivity().getLocalClassName() + " must implements ListDependencyListener"); } } @Nullable @Override public android.view.View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_add_edit_dependency, container, false); tilName = rootView.findViewById(R.id.tilName); tilShortName = rootView.findViewById(R.id.tilShortName); tilDescription = rootView.findViewById(R.id.tilDescription); edtName = rootView.findViewById(R.id.edtName); edtName.addTextChangedListener(textWatcher); edtShortName = rootView.findViewById(R.id.edtShortName); edtShortName.addTextChangedListener(textWatcher); edtDescription = rootView.findViewById(R.id.edtDescription); edtDescription.addTextChangedListener(textWatcher); fab = rootView.findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (addEditMode.getMode() == AddEdit.ADD_MODE) { presenter.addDependency(tilName.getEditText().getText().toString(), tilShortName.getEditText().getText().toString(), tilDescription.getEditText().getText().toString()); } else if (addEditMode.getMode() == AddEdit.EDIT_MODE) { Dependency dependency = getArguments().getParcelable(EDIT_KEY); dependency.setDescription(edtDescription.getText().toString()); presenter.editDependency(dependency); } } }); addEditMode = new AddEdit(); if(getArguments() != null) { edtName.setText(this.getArguments().getString("nombre")); edtShortName.setText(this.getArguments().getString("shortname")); edtDescription.setText(this.getArguments().getString("descripcion")); position = this.getArguments().getInt("posicion"); addEditMode.setMode(AddEdit.EDIT_MODE); } else { addEditMode.setMode(AddEdit.ADD_MODE); } return rootView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (addEditMode.getMode() == AddEdit.EDIT_MODE) { Dependency dependency = getArguments().getParcelable(EDIT_KEY); edtName.setText(dependency.getName()); edtName.setEnabled(false); edtShortName.setText(dependency.getShortName()); edtShortName.setEnabled(false); edtDescription.setText(dependency.getDescription()); } } @Override public void setPresenter(BasePresenter presenter) { this.presenter = (AddEditDependencyContract.Presenter) presenter; } public void showListDependency() { showMessage("Dependency saved"); FragmentManager fragmentManager = getFragmentManager(); fragmentManager.popBackStack(); //getActivity().finish(); //startActivity(getActivity().getIntent()); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public void navigateToHome() { DependencyRepository dependencyRepository = DependencyRepository.getInstance(); if(addEditMode.getMode() == AddEdit.EDIT_MODE) { dependencyRepository.getDependencies().get(position).setName(edtName.getText().toString()); dependencyRepository.getDependencies().get(position).setShortName(edtShortName.getText().toString()); dependencyRepository.getDependencies().get(position).setDescription(edtDescription.getText().toString()); } else{ dependencyRepository.addDependency(new Dependency(dependencyRepository.getDependencies().toArray().length, edtName.getText().toString(), edtShortName.getText().toString(), edtDescription.getText().toString())); } //callback.listNewDependency(); } @Override public void setNameEmptyError() { tilName.setError("El nombre no puede estar vacío"); } @Override public void setNameAlreadyExistError() { tilName.setError("Ya existe el nombre de usuario"); } @Override public void setShortNameEmptyError() { tilShortName.setError("El apodo no puede estar vacío"); } @Override public void setShortNameAlreadyExistError() { tilShortName.setError("Ya existe el apodo"); } @Override public void setValidateDependencyError() { } @Override public void onDetach() { super.onDetach(); callback = null; } public void onDestroy() { super.onDestroy(); presenter.onDestroy(); } private TextWatcher textWatcher = 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) { tilName.setError(null); tilShortName.setError(null); tilDescription.setError(null); } @Override public void afterTextChanged(Editable editable) { } }; } <file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/ui/prefs/AccountSettingsActivity.java package com.example.usuario.inventoryfragment.ui.prefs; import android.os.Bundle; import android.preference.PreferenceActivity; import android.support.annotation.Nullable; import com.example.usuario.inventoryfragment.R; /** * @author <NAME> */ public class AccountSettingsActivity extends PreferenceActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.account_settings); } } <file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/DashboardActivity.java package com.example.usuario.inventoryfragment; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayout; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import com.example.usuario.inventoryfragment.ui.dependency.DependencyActivity; import com.example.usuario.inventoryfragment.ui.inventory.InventoryActivity; import com.example.usuario.inventoryfragment.ui.prefs.AccountSettingsActivity; import com.example.usuario.inventoryfragment.ui.prefs.GeneralSettingsActivity; import com.example.usuario.inventoryfragment.ui.product.ProductActivity; import com.example.usuario.inventoryfragment.ui.sector.SectorActivity; /** * @author <NAME> * Menú de la aplicación */ public class DashboardActivity extends AppCompatActivity { private GridLayout gridDashboard; private ClickListenerDashboard listenerDashboard; private final int INVENTORY = R.drawable.inventory_icon; private final int PRODUCT = R.drawable.product_icon; private final int DEPENDENCIES = R.drawable.dependences_icon; private final int SECTOR = R.drawable.sector_icon; private final int PREFERENCES = R.drawable.preferences_icon; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard_support); gridDashboard = (GridLayout) findViewById(R.id.gridDashboard); //Definir un array de int, que contendrá el id de las imágenes Inventory int[] images = { INVENTORY, PRODUCT, DEPENDENCIES, SECTOR//, PREFERENCES }; //No se utiliza en Java/android array de objetos. Se utiliza Vector o Colecciones //ImageView[] imageViews = new ImageView[images.length]; //No utilizamos la clase Vector porque no trabajamos con hilos y no se requiere sincronización //Vector<ImageView> vectorImageViews = new Vector<ImageView>(); listenerDashboard = new ClickListenerDashboard(); ImageView imageView; float width = getResources().getDimension(R.dimen.imgDashboardWidth); float height = getResources().getDimension(R.dimen.imgDashboardHeight); for (int i = 0; i < images.length; i++) { imageView = new ImageView(this); imageView.setImageResource(images[i]); imageView.setId(images[i]); GridLayout.LayoutParams params = new GridLayout.LayoutParams(); params.width = (int) width; params.height = (int) height; params.rowSpec = GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL, 1f); params.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL, 1f); imageView.setLayoutParams(params); imageView.setOnClickListener(listenerDashboard); gridDashboard.addView(imageView); } } class ClickListenerDashboard implements View.OnClickListener{ @Override public void onClick(View view) { Intent intent = null; switch (view.getId()) { case INVENTORY: intent = new Intent(DashboardActivity.this, InventoryActivity.class); break; case PRODUCT: intent = new Intent(DashboardActivity.this, ProductActivity.class); break; case DEPENDENCIES: intent = new Intent(DashboardActivity.this, DependencyActivity.class); break; case SECTOR: intent = new Intent(DashboardActivity.this, SectorActivity.class); break; case PREFERENCES: intent = new Intent(DashboardActivity.this, null); break; } if(intent != null) startActivity(intent); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu_activity_dashboard, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_account_settings: startActivity(new Intent(DashboardActivity.this, AccountSettingsActivity.class)); break; case R.id.action_general_settings: startActivity(new Intent(DashboardActivity.this, GeneralSettingsActivity.class)); break; } return super.onOptionsItemSelected(item); } }<file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/ui/dependency/presenter/DetailPresenter.java package com.example.usuario.inventoryfragment.ui.dependency.presenter; /** * Created by usuario on 11/23/17. */ public class DetailPresenter { } <file_sep>/app/src/main/java/com/example/usuario/inventoryfragment/db/repository/ProductRepository.java package com.example.usuario.inventoryfragment.db.repository; /** * @author <NAME> * Repositorio de productos */ public class ProductRepository { }
2b3389a7b67624d355503f80b9ce292b4cb5df0c
[ "Java" ]
12
Java
alfchaval/InventoryFragment
eb5e16b77ba4d64c32d273c9f4c7c3f65113985d
c42637a6119173e6d459de74679e3f855d707182
refs/heads/master
<file_sep>class Vector{ public: Vector(int size); double &operator[](int i); int size(); private: double * elem; int sz; }; <file_sep>#ifndef Board_h_ #define Board_h_ class Board{ public: Board(int nrows, int ncols); int get(int row, int col); void set(int row, int col, int value); int *get_row(int i); void print(); private: int **readBoard; int **writeBoard; int nrows; int ncols; }; #endif <file_sep>#include <stdlib.h>//for rand #include <iostream> using namespace std; const int ROW_SIZE = 6; const int COLUMN_SIZE = 6; const int MAX_ITER = 50 ; const int ALIVE = 1; const int DEAD = 0; const int MAX_INIT_ALIVE = 4; // max live cells in a random pattern int readBoard[ROW_SIZE][COLUMN_SIZE]; int outBoard[ROW_SIZE][COLUMN_SIZE]; int mod(int a, int b) { int r = a % b; return r < 0 ? r + b : r; } int countAliveNSEO( int i, int j){ // count cells alive in the North Suth East Ovest int num = 0; /* North*/ if( readBoard[mod((i-1), ROW_SIZE)][ mod(j, COLUMN_SIZE)] == 1) num++; /* Ovest*/ if(readBoard[mod(i,ROW_SIZE)][mod((j-1),COLUMN_SIZE)] == 1 ) num++; /* Est*/ if(readBoard[mod(i, ROW_SIZE)][mod((j+1), COLUMN_SIZE)] == 1) num++; /* South */ if(readBoard[mod((i+1),ROW_SIZE)][mod(j,COLUMN_SIZE)] == 1) num++; return num; } int countAliveNeighbors( int i, int j){ int diag = 0; /* check 4 extrems alive points in diagonal of the matrix */ if( i == 0 && j == 0 ){ //first point of the first row if(readBoard[i+1][j+1] == 1) diag ++; }else if( i == 0 && j == (COLUMN_SIZE -1)){ //last point of the first row if(readBoard[i+1][j-1] == 1) diag++; }else if( i == ROW_SIZE -1 && j==0 ){ //first point of the last row if(readBoard[i-1][j+1] == 1) diag ++; } else if( (i == ROW_SIZE-1) && j == (COLUMN_SIZE -1)){ // last point of the last row if(readBoard[i-1][j-1] == 1) diag++; }else if( i == 0 || i == ROW_SIZE || j == 0 || j == COLUMN_SIZE){ /* check diagonal points in critical ROWS and columns*/ switch (i) { case 0: // first row if(readBoard[i+1][j-1] == 1) diag++; if(readBoard[i+1][j+1] == 1) diag++; break; case ROW_SIZE-1: // last row if(readBoard[i-1][j-1] == 1) diag++; if(readBoard[i-1][j+1] == 1) diag++; break; } /* Check diagonal points on critical COLUMNS of the matrix*/ switch (j) { case 0: // first column if(readBoard[i-1][j+1] == 1) diag++; if(readBoard[i+1][j+1] == 1) diag++; case COLUMN_SIZE-1: // last column if(readBoard[i-1][j-1] == 1) diag++; if(readBoard[i+1][j-1] == 1) diag++; } }else { /* check alive diagonal points of center elements*/ if(readBoard[i-1][j-1] == 1) diag++; if(readBoard[i-1][j+1] == 1) diag++; if(readBoard[i+1][j-1] == 1) diag++; if(readBoard[i+1][j+1] == 1) diag++; } /*counts alive points on North, South, Est, Ovest*/ int nseo = countAliveNSEO(i,j); int num = nseo + diag; if( num > 0) std::cout << i <<" " << j <<" diag: "<< diag <<" nseo: "<< nseo << " alive: " << readBoard[i][j]<< std::endl; return num; } void printBaseBoard(){ std::cout << "Base readBoard " << std::endl; // print outBoard for(int i = 0; i < ROW_SIZE; i++){ for(int j = 0; j < COLUMN_SIZE; j++ ){ if(j == COLUMN_SIZE-1) std::cout << readBoard[i][j] << "\n"; else std::cout << readBoard[i][j] << " "; } } } void printOutBoard(){ std::cout << "Out Board " << std::endl; // print outBoard for(int i = 0; i < ROW_SIZE; i++){ for(int j = 0; j < COLUMN_SIZE; j++ ){ if(j == COLUMN_SIZE-1) std::cout << outBoard[i][j] << "\n"; else std::cout << outBoard[i][j] << " "; } } } void copyOutToBaseBoard(){ for(int i = 0; i < ROW_SIZE; i++){ for(int j = 0; j < COLUMN_SIZE; j++ ){ readBoard[i][j] = outBoard[i][j]; } } } void setPatternBlinker(){ int tot = 3; int middle = COLUMN_SIZE / 2; for( int i = middle; i < middle+tot; i++ ){ readBoard[i][middle] = ALIVE; outBoard[i][middle] = ALIVE; } } void setPatternBlock(){ readBoard[1][1] = ALIVE; readBoard[1][2] = ALIVE; readBoard[2][1] = ALIVE; readBoard[2][2] = ALIVE; } void setPatternToad(){ readBoard[1][2] = ALIVE; readBoard[1][3] = ALIVE; readBoard[1][4] = ALIVE; readBoard[2][1] = ALIVE; readBoard[2][2] = ALIVE; readBoard[2][3] = ALIVE; } int main( int argc, char *argv[]){ // set the readBoard and outBoard all zeros for(int i = 0; i < ROW_SIZE; i++){ for(int j = 0; j < COLUMN_SIZE; j++ ){ readBoard[i][j] = DEAD; outBoard[i][j] = DEAD; } } setPatternBlinker(); //setPatternBlock(); //setPatternToad(); //printOutBoard(); int flag = 1; int numAlive = 0; while( flag == 1){ printBaseBoard(); //read the readBoard for cecking alive or die for(int i = 0; i < ROW_SIZE; i++){ for(int j = 0; j < COLUMN_SIZE; j++){ numAlive = countAliveNeighbors(i,j); if(readBoard[i][j] == DEAD && numAlive == 3) outBoard[i][j] = ALIVE; if(readBoard[i][j] == ALIVE && numAlive < 2){ std::cout << "alive-> dead "<< i <<" "<< j << " num Live "<< numAlive << std::endl; outBoard[i][j] = DEAD; } if(readBoard[i][j] == ALIVE && numAlive > 3){ std::cout << "alive-> dead "<< i <<" "<< j << " num Live "<< numAlive << std::endl; outBoard[i][j] = DEAD; } if (readBoard[i][j] == ALIVE && (numAlive == 2 || numAlive == 3)) { outBoard[i][j] = ALIVE; } } } printOutBoard(); //printOutBoard(); copyOutToBaseBoard(); std::cout << "0 : terminate \n 1: new generation" << std::endl; std::cin >> flag; } } <file_sep>#include "Board.cpp" int main( int argc, char *argv[]){ stringstream r, c, m; r << argv[1]; // number of rows c << argv[2]; // number of columns if(argv[3]){ m << argv[3]; } Board game_board = Board(r,c); } <file_sep>#include <iostream> #include "Board.hpp" int main(int arc, char *argv[]){ int r, c, m; r << strtol(argv[1],NULL,2); // number of rows c << strtol(argv[2],NULL,2); // number of columns if(argv[3]){ m << std::atoi(argv[3]); } Board * game_board; std::cout << "r" << r << " c " << c << std::endl; game_board = new Board(4,4); game_board->print(); } <file_sep>#include <iostream> using namespace std; class Vector{ public: Vector(int s): elem{new double[s]},sz{s}{} double &operator[](int i){return elem[i];} int size(){return sz;} void print(){ for(int i=0; i< sz; i++) if(i==sz-1) cout<< elem[i] <<" "<<endl; else cout<<elem[i] << " "; } private: int sz; double *elem; }; int main(int argc, char *argv[]){ Vector v(4); //new vector of 4 elements; for(int i=0; i< v.size(); i++) cin >> v[i]; v.print(); } <file_sep>#include <iostream> #include "Board.hpp" #include <cmath> Board::Board(int nrows, int ncols){ srand(time(0)); this->nrows = nrows; this->ncols = ncols; this-> readBoard = new int *[nrows]; this-> writeBoard = new int *[nrows]; for( int i=0; i<nrows; i++){ this-> readBoard[i] = new int[ncols]; this-> writeBoard[i] = new int[ncols]; //random fill of the readBoard for(int j=0; j<ncols; j++){ this->readBoard[i][j] = floor(rand()%2); } } } void Board::print(){ for(int i=0;i< this->nrows;i++){ for(int j=0; j <this->ncols;j++){ std::cout << this->readBoard[i][j]<< " "; } std::cout <<std::endl; } std::cout <<std::endl; } int Board::get(int row, int col){ return this->readBoard[row][col]; } void Board::set(int row, int col, int value){ this->writeBoard[row][col]=value; } /* int *get_row(int i){ return &(this->readBoard[i]); } */ <file_sep> /* An union is a struct in which all the menbers are allocated at the SAME ADDRESS, so that the union occupies only as much spaceas its largest member. Can hold a value for only member at time */ /* symbol table entry: name, value*/ unum Type {str,num}: struct Entry{ char *name; Type t; //wasted space for both char or integer value associated with the key name -> UNION char *s; //string value if Type is str int i; //integer value if type is num } void f( Entry *p){ if(p->t == str) cout<< p-> s; } /********** * version with UNION ************** */ union Value{ char *s; int i; } struct Entry{ char *key; Value v; Type t; } <file_sep>#include <stdlib.h>//for rand #include <iostream> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> /* compile with: g++ -std=c++11 -I /usr/local/boost_1_59_0gameoflife_dynamic.cpp -o gameoflife usage: gameoflife numrows numcolumns [maxiteration] */ using namespace std; using namespace boost::numeric::ublas; int ROW_SIZE = 0; int COLUMN_SIZE = 0; int MAX_ITER = 50 ; const int ALIVE = 1; const int DEAD = 0; const int MAX_INIT_ALIVE = 4; // max live cells in a random pattern matrix<int> readBoard; matrix<int> outBoard; //int readBoard[ROW_SIZE][COLUMN_SIZE]; //int outBoard[ROW_SIZE][COLUMN_SIZE]; int mod(int a, int b) { int r = a % b; return r < 0 ? r + b : r; } int countAliveNSEO( int i, int j){ // count cells alive in the North Suth East Ovest int num = 0; /* North*/ if( readBoard(mod((i-1), ROW_SIZE), mod(j, COLUMN_SIZE)) == 1) num++; /* Ovest*/ if(readBoard(mod(i,ROW_SIZE), mod((j-1),COLUMN_SIZE)) == 1 ) num++; /* Est*/ if(readBoard(mod(i, ROW_SIZE), mod((j+1), COLUMN_SIZE)) == 1) num++; /* South */ if(readBoard(mod((i+1),ROW_SIZE), mod(j,COLUMN_SIZE))== 1) num++; return num; } int countAliveNeighbors( int i, int j){ int diag = 0; /* check 4 extrems alive points in diagonal of the matrix */ if( i == 0 && j == 0 ){ //first point of the first row if(readBoard(i+1,j+1) == 1) diag ++; }else if( i == 0 && j == (COLUMN_SIZE -1)){ //last point of the first row if(readBoard(i+1, j-1) == 1) diag++; }else if( i == ROW_SIZE -1 && j==0 ){ //first point of the last row if(readBoard(i-1,j+1) == 1) diag ++; } else if( (i == ROW_SIZE-1) && j == (COLUMN_SIZE -1)){ // last point of the last row if(readBoard(i-1,j-1) == 1) diag++; }else if( i == 0 || i == ROW_SIZE || j == 0 || j == COLUMN_SIZE){ /* check diagonal points in critical ROWS and columns*/ switch (i) { case 0: // first row if(readBoard(i+1, j-1) == 1) diag++; if(readBoard(i+1,j+1) == 1) diag++; break; case ROW_SIZE-1: // last row if(readBoard(i-1,j-1) == 1) diag++; if(readBoard(i-1,j+1) == 1) diag++; break; } /* Check diagonal points on critical COLUMNS of the matrix*/ switch (j) { case 0: // first column if(readBoard(i-1,j+1) == 1) diag++; if(readBoard(i+1,j+1) == 1) diag++; case COLUMN_SIZE-1: // last column if(readBoard(i-1,j-1) == 1) diag++; if(readBoard(i+1, j-1) == 1) diag++; } }else { /* check alive diagonal points of center elements*/ if(readBoard(i-1,j-1) == 1) diag++; if(readBoard(i-1,j+1) == 1) diag++; if(readBoard(i+1, j-1) == 1) diag++; if(readBoard(i+1,j+1) == 1) diag++; } /*counts alive points on North, South, Est, Ovest*/ int nseo = countAliveNSEO(i,j); int num = nseo + diag; if( num > 0) std::cout << i <<" " << j <<" diag: "<< diag <<" nseo: "<< nseo << " alive: " << readBoard(i,j)<< std::endl; return num; } void printBaseBoard(){ std::cout << "Base readBoard " << std::endl; // print outBoard for(int i = 0; i < ROW_SIZE; i++){ for(int j = 0; j < COLUMN_SIZE; j++ ){ if(j == COLUMN_SIZE-1) std::cout << readBoard(i,j) << "\n"; else std::cout << readBoard(i,j) << " "; } } } void printOutBoard(){ std::cout << "Out Board " << std::endl; // print outBoard for(int i = 0; i < ROW_SIZE; i++){ for(int j = 0; j < COLUMN_SIZE; j++ ){ if(j == COLUMN_SIZE-1) std::cout << outBoard(i,j) << "\n"; else std::cout << outBoard(i,j) << " "; } } } void copyOutToBaseBoard(){ for(int i = 0; i < ROW_SIZE; i++){ for(int j = 0; j < COLUMN_SIZE; j++ ){ readBoard(i,j) = outBoard(i,j); } } } void setPatternBlinker(){ int tot = 3; int middle = COLUMN_SIZE / 2; for( int i = middle; i < middle+tot; i++ ){ readBoard(i, middle) = ALIVE; outBoard(i, middle) = ALIVE; } } void setPatternBlock(){ readBoard(1,1) = ALIVE; readBoard(1,2) = ALIVE; readBoard(2,1) = ALIVE; readBoard(2,2) = ALIVE; } void setPatternToad(){ readBoard(1,2) = ALIVE; readBoard(1,3) = ALIVE; readBoard(1,4) = ALIVE; readBoard(2,1) = ALIVE; readBoard(2,2) = ALIVE; readBoard(2,3) = ALIVE; } int main( int argc, char *argv[]){ string usage = "usage: gameoflife nrows ncolumns [maxtieration" << std::endl; /* \n \t\t nrows : number of rows in the board \n \t\t ncolumns: number of columns in the board \n \t\t maxiteration: max iteration of the game, default = 50" <<std::endl; */ if(argc < 3) std::cout << usage << std::endl; else { ROW_SIZE = argv[1]; COLUMN_SIZE = argv[2]; if( argc == 4) MAX_ITER = argv[3]; } readBoard.resize(ROW_SIZE, COLUMN_SIZE); outBoard.resize(ROW_SIZE, COLUMN_SIZE); // set the readBoard and outBoard all zeros for(int i = 0; i < ROW_SIZE; i++){ for(int j = 0; j < COLUMN_SIZE; j++ ){ readBoard(i,j) = DEAD; outBoard(i,j) = DEAD; } } //setPatternBlinker(); //setPatternBlock(); setPatternToad(); //printOutBoard(); int flag = 1; int numAlive = 0; while( flag == 1){ printBaseBoard(); //read the readBoard for cecking alive or die for(int i = 0; i < ROW_SIZE; i++){ for(int j = 0; j < COLUMN_SIZE; j++){ numAlive = countAliveNeighbors(i,j); if(readBoard(i,j) == DEAD && numAlive == 3) outBoard(i,j) = ALIVE; if(readBoard(i,j) == ALIVE && numAlive < 2){ std::cout << "alive-> dead "<< i <<" "<< j << " num Live "<< numAlive << std::endl; outBoard(i,j) = DEAD; } if(readBoard(i,j) == ALIVE && numAlive > 3){ std::cout << "alive-> dead "<< i <<" "<< j << " num Live "<< numAlive << std::endl; outBoard(i,j) = DEAD; } if (readBoard(i,j) == ALIVE && (numAlive == 2 || numAlive == 3)) { outBoard(i,j) = ALIVE; } } } printOutBoard(); //printOutBoard(); copyOutToBaseBoard(); std::cout << "0 : terminate \n 1: new generation" << std::endl; std::cin >> flag; } } <file_sep>#incude <vector_main.cpp> <file_sep>#include <iostream> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; //g++ opencv.cpp -o app `pkg-config --cflags --libs opencv` Mat readBoard; Mat outBoard; int COLUMN_SIZE = 0; int ROW_SIZE = 0; const uchar ALIVE = 255; const uchar DEAD = 0; void setPatternBlinker(Mat img, int row, int col){ //perdiodic pattern: three points vertical. for( int i = 0; i < 3; i++) img.at<uchar>(row + i,col) = ALIVE; //white } int mod(int a, int b) { int r = a % b; return r < 0 ? r + b : r; } void setPatternToad(Mat img){ /* dynamic pattern * x * x x x x x * x x x -> x x * x */ img.at<uchar>(1, 2) = ALIVE; img.at<uchar>(1, 3) = ALIVE; img.at<uchar>(1, 4) = ALIVE; img.at<uchar>(2, 1) = ALIVE; img.at<uchar>(2, 2) = ALIVE; img.at<uchar>(2, 3) = ALIVE; } void setPatternGlider(Mat img){ /* Spaceships pattern * - - x * x - x * - x x * */ img.at<uchar>(0, 2) = ALIVE; img.at<uchar>(1, 0) = ALIVE; img.at<uchar>(1, 2) = ALIVE; img.at<uchar>(2, 1) = ALIVE; img.at<uchar>(2, 2) = ALIVE; } void setPatternCritical(Mat img){ /*Critical pattern * x - x x * x - - - * - - - - * x x - - */ img.at<uchar>(1, img.cols-1) = ALIVE; img.at<uchar>(0, img.cols-1) = ALIVE; img.at<uchar>(0, 0) = ALIVE; img.at<uchar>(1, 0) = ALIVE; img.at<uchar>(img.rows - 1, 0) = ALIVE; img.at<uchar>(img.rows - 1, 1) = ALIVE; } void setPatternRandom(Mat img) { // Random pattern generator RNG rng (ALIVE); int tot = img.rows * img.cols; int randRow, randColumn; for( int i = 0; i < tot/2 ; i++){ randRow = rng.uniform(0, img.rows); randColumn= rng.uniform(0, img.cols); img.at<uchar>(randRow, randColumn) = ALIVE; } } void nextGeneration( Mat& readBoard, Mat& writeBoard); int eval_alive_regular_neighbours(uchar* previous, uchar* current, uchar* next, int col); uchar get_status(uchar currentStatus, int numAlive); int main(int argc, char** argv ) { int max_iter = 10; stringstream r, c, m; r << argv[1]; // number of rows r >> ROW_SIZE; c << argv[2]; // number of columns c >> COLUMN_SIZE; if(argv[3]){ m << argv[3]; m >> max_iter; } //set baseBoard image readBoard = Mat(ROW_SIZE,COLUMN_SIZE, CV_8UC1, Scalar(DEAD)); //set OutBoard image outBoard = Mat(ROW_SIZE,COLUMN_SIZE, CV_8UC1, Scalar(DEAD)); //create windows for board //char board_window[] = "Game of life"; namedWindow( "Game of life", WINDOW_NORMAL ); // Set initial pattern //setPatternBlinker(readBoard,2, 2); //setPatternToad(readBoard); //setPatternCritical(readBoard); //setPatternGlider(readBoard); setPatternRandom(readBoard); imshow("Game of life", readBoard); waitKey(0); while(max_iter > 0) { nextGeneration(readBoard, outBoard); imshow("Game of life", outBoard); waitKey(50); max_iter --; } return(0); } void nextGeneration( Mat& readBoard, Mat& writeBoard){ /* Calculate the next generation of the game. * Reads the baseBoard and calculate the alive/dead cells * and implements the tule of the game. * Writes the new generation in the outBoard. * Overwrite the baseBoard with the value of the outBoard */ CV_Assert(readBoard.depth() == CV_8U); // accept only char type matrices const int nChannels = readBoard.channels(); for (int row = 0; row < readBoard.rows ; ++row) { uchar * previous = readBoard.ptr<uchar>(mod(row -1 , readBoard.rows)); uchar * current = readBoard.ptr<uchar>(row ); uchar * next = readBoard.ptr<uchar>(mod(row + 1, readBoard.rows)); uchar* output = writeBoard.ptr<uchar>(row); for (int col = 0; col < nChannels*readBoard.cols; col++) { //pass the starting pointer of the three vectors, int numAlive = eval_alive_regular_neighbours(previous, current, next, col); uchar status = get_status(current[col], numAlive); // if( numAlive > 0) // std::cout << "Alive [" << row << "," << col <<"] numALive: " << numAlive << " "<< (int)current[col] << " ->"<< (int)status << std::endl; output[col] = status; } } writeBoard.copyTo(readBoard); } int eval_alive_regular_neighbours( uchar* previous, uchar* current, uchar* next, int col) { /* * Takes the pointers to previous, current, next rows vectors. * Return the status: ALIVE or DEAD according to the values of the neighbours * Check the toroidal neighbours. */ int numAlive = 0; for(int i = -1; i < 2; i++) { if(previous[mod(col + i, readBoard.cols)] == ALIVE) numAlive++; if(current[mod(col + i, readBoard.cols)] == ALIVE && i!= 0) numAlive++; if(next[mod(col + i,readBoard.cols)] == ALIVE) numAlive++; } return numAlive; } uchar get_status(uchar currentStatus, int numAlive){ uchar nextStatus; if(currentStatus == DEAD && numAlive == 3) nextStatus = ALIVE; if(currentStatus == ALIVE && numAlive < 2) nextStatus = DEAD; if(currentStatus == ALIVE && numAlive > 3) nextStatus = DEAD; if(currentStatus == ALIVE && (numAlive == 2 || numAlive == 3)) nextStatus = ALIVE; return nextStatus; } <file_sep>#include "vector.h" using namespace std; double sqrt_sum(Vector &v){ double sum = 0; for(int i =0; i<v.size(); i++) sum+=v[i]; return sum; }; int main(){ return(0); } <file_sep>#include <iostream> #include "Board.hpp" int main(int arc, char *argv[]){ int r, c, m; r << std::atoi(argv[1]); // number of rows c << std::atoi(argv[2]); // number of columns if(argv[3]){ m << std::atoi(argv[3]); } Board * game_board; game_board = new Board(r,c); } <file_sep>#include <cstdlib> #include <iostream> using namespace std; struct Vector { int sz; // size of the vector double * elem; // pointer to the first element }; void vector_init(Vector &v, int size) { v.sz = size; v.elem = new double[size]; //allocate an array of number of size elements in the heap } double read_and_sum(Vector& v) { //read s integers from cin and return their sum, s is assumed positive int i; for(i=0; i<v.sz; i++) { cout << "Inserisci un intero positivo" << endl; cin >> v.elem[i]; } double sum = 0; for(i=0; i<v.sz;i++) { //std::cout << v.elem[i] << " "<<std::endl; sum += v.elem[i]; } return sum; } void print_size(Vector v, Vector &rv, Vector *pv) { cout<<v.sz <<"vector name" <<endl; cout<<rv.sz <<"vector references" <<endl; cout<<pv->sz <<"vector pointer" <<endl; } int main(int argc, char* argv[]){ int x; if(argc>1) x = atoi(argv[1]); Vector v; vector_init(v,x); int sum = read_and_sum(v); cout << "somma " << sum << endl; print_size(v, v, &v); return(0); }
3ae8687e5514ab59f84278f0b0773a71750f44c7
[ "C++" ]
14
C++
dido18/gameoflife
5c2368c8ee970cc49e3cd1831972d9169eea6374
a10c3fd3dfdce7523a9c1c604e7578e70023a883
refs/heads/master
<repo_name>kazmi066/react-production-boilerplate<file_sep>/src/navigation/RouterConfig.js import React from "react"; import { Switch, Route } from "react-router-dom"; import Home from "pages/Home"; import Dashboard from "pages/Dashboard"; import { NotFound } from "navigation/NotFound"; import { ROOT, DASHBOARD, PAGE1, AUTH_PAGE1 } from "navigation/CONSTANTS"; import { Page1 } from "pages/Page1"; import Login from "./Auth/Login"; import { AuthorizedPage1 } from "pages/AuthorizedPage1"; import PrivateRoute from "./Auth/PrivateRoute"; export const RouterConfig = () => { return ( <div> <Switch> {/* List all public routes here */} <Route exact path={ROOT} component={Home} /> <Route exact path={DASHBOARD} component={Dashboard} /> <Route exact path={PAGE1} component={Page1} /> <Route path="/login"> <Login /> </Route> {/* List all private/auth routes here */} <PrivateRoute path={AUTH_PAGE1}> <AuthorizedPage1 /> </PrivateRoute> {/* Do not hesitate to play around by moving some routes from public to private and vice-versa */} {/* <PrivateRoute path={DASHBOARD}> <Dashboard /> </PrivateRoute> */} {/* List a generic 404-Not Found route here */} <Route path="*"> <NotFound /> </Route> </Switch> </div> ); };
e3b2959d1753a38176a8683934e4834fe031323f
[ "JavaScript" ]
1
JavaScript
kazmi066/react-production-boilerplate
fb360b6fb33cf14d49f9b3930874366814a76b53
2e31333fa36190aae712da7e62be568f6899962b
refs/heads/master
<repo_name>farhandewapb7/project-KKSI-7<file_sep>/tambah_produk.php <html class="no-js" lang="zxx"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>HANTOK</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link rel="manifest" href="site.webmanifest"> --> <link rel="icon" type="image/icon" href="Images/Logo.jpg"> <!-- Place favicon.ico in the root directory --> <!-- CSS here --> <link rel="stylesheet" href="assets/sunshine/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/sunshine/css/owl.carousel.min.css"> <link rel="stylesheet" href="assets/sunshine/css/magnific-popup.css"> <link rel="stylesheet" href="assets/sunshine/css/themify-icons.css"> <link rel="stylesheet" href="assets/sunshine/css/nice-select.css"> <link rel="stylesheet" href="assets/sunshine/css/flaticon.css"> <link rel="stylesheet" href="assets/sunshine/css/animate.css"> <link rel="stylesheet" href="assets/sunshine/css/slicknav.css"> <link rel="stylesheet" href="assets/sunshine/css/style.css"> <link rel="stylesheet" href="assets/divisima/css/bootstrap.min.css"/> <link rel="stylesheet" href="assets/divisima/css/jquery-ui.min.css"/> <link rel="stylesheet" href="assets/divisima/css/style.css"/> <script src="assets/divisima/js/jquery-3.2.1.min.js"></script> <script src="assets/divisima/js/bootstrap.min.js"></script> <script src="assets/divisima/js/main.js"></script> <!-- <link rel="stylesheet" href="css/responsive.css"> --> </head> <body background="images/background1.jpg"> <div id="preloder"> <div class="loader"></div> </div> <?php include("koneksi.php"); ?> <center><h2 style="color:pink">UPLOAD SWEATER</h2></center> <div class="container"> <div class="row"> <div class="col-md-6 offset-md-3"> <form action="tambah_produk2.php" method="post" enctype="multipart/form-data"> <table width="319" border="0" class="table table-info"> <tr> <td width="152" style="color:hotpink">Kode sweater</td> <td style="color:hotpink">:</td> <td width="157"><input name="kode" type="text" class="form-control" id="kode" size="20" /></td> </tr> <tr> <td width="152" style="color:hotpink">Nama sweater</td> <td style="color:hotpink">:</td> <td width="157"><input name="barang" type="text" class="form-control" id="barang" size="20" /></td> </tr> <tr> <td width="152" style="color:hotpink">Harga</td> <td style="color:hotpink">:</td> <td width="157"><input name="harga" type="text" class="form-control" id="harga" size="20" /></td> </tr> <tr> <td width="152" style="color:hotpink">Keterangan</td> <td style="color:hotpink">:</td> <td width="157"><input name="keterangan" type="text" class="form-control" id="keterangan" size="20" /></td> </tr> <tr> <td width="152" style="color:hotpink">Kategori</td> <td style="color:hotpink">:</td> <td width="157"><input name="kategori" type="text" class="form-control" id="kategori" size="20" /></td> </tr> <tr> <td width="152" style="color:hotpink">Gambar</td> <td style="color:hotpink">:</td> <td width="157"><input name="file" type="file" size="20" /></td> </tr> <tr> <td width="92"><input class="btn btn-info" name="upload" type="submit"></a></input></td> <td width="92"><a href="index.php" button class="btn btn-info" type="button">Batal</a></button></td> </tr> </table> <br> </form> </div> </div> </div> <!--====== Javascripts & Jquery ======--> <script src="assets/divisima/js/jquery-3.2.1.min.js"></script> <script src="assets/divisima/js/bootstrap.min.js"></script> <script src="assets/divisima/js/jquery.slicknav.min.js"></script> <script src="assets/divisima/js/owl.carousel.min.js"></script> <script src="assets/divisima/js/jquery.nicescroll.min.js"></script> <script src="assets/divisima/js/jquery.zoom.min.js"></script> <script src="assets/divisima/js/jquery-ui.min.js"></script> <script src="assets/divisima/js/main.js"></script> <script src="assets/sunshine/js/vendor/modernizr-3.5.0.min.js"></script> <script src="assets/sunshine/js/vendor/jquery-1.12.4.min.js"></script> <script src="assets/sunshine/js/popper.min.js"></script> <script src="assets/sunshine/js/bootstrap.min.js"></script> <script src="assets/sunshine/js/owl.carousel.min.js"></script> <script src="assets/sunshine/js/isotope.pkgd.min.js"></script> <script src="assets/sunshine/js/ajax-form.js"></script> <script src="assets/sunshine/js/waypoints.min.js"></script> <script src="assets/sunshine/js/jquery.counterup.min.js"></script> <script src="assets/sunshine/js/imagesloaded.pkgd.min.js"></script> <script src="assets/sunshine/js/scrollIt.js"></script> <script src="assets/sunshine/js/jquery.scrollUp.min.js"></script> <script src="assets/sunshine/js/wow.min.js"></script> <script src="assets/sunshine/js/nice-select.min.js"></script> <script src="assets/sunshine/js/jquery.slicknav.min.js"></script> <script src="assets/sunshine/js/jquery.magnific-popup.min.js"></script> <script src="assets/sunshine/js/plugins.js"></script> <!--contact js--> <script src="assets/sunshine/js/contact.js"></script> <script src="assets/sunshine/js/jquery.ajaxchimp.min.js"></script> <script src="assets/sunshine/js/jquery.form.js"></script> <script src="assets/sunshine/js/jquery.validate.min.js"></script> <script src="assets/sunshine/js/mail-script.js"></script> <script src="assets/sunshine/js/main.js"></script> </body> </html><file_sep>/assets/sunshine/gallery.html <!doctype html> <html class="no-js" lang="zxx"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Weeding</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link rel="manifest" href="site.webmanifest"> --> <!-- <link rel="shortcut icon" type="image/x-icon" href="img/favicon.png"> --> <!-- Place favicon.ico in the root directory --> <!-- CSS here --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/owl.carousel.min.css"> <link rel="stylesheet" href="css/magnific-popup.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/themify-icons.css"> <link rel="stylesheet" href="css/nice-select.css"> <link rel="stylesheet" href="css/flaticon.css"> <link rel="stylesheet" href="css/flaticon.css"> <link rel="stylesheet" href="css/gijgo.css"> <link rel="stylesheet" href="css/slicknav.css"> <link rel="stylesheet" href="css/style.css"> <!-- <link rel="stylesheet" href="css/responsive.css"> --> </head> <body> <!--[if lte IE 9]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience and security.</p> <![endif]--> <!-- header--> <header> <div class="header-area "> <div id="sticky-header" class="main-header-area"> <div class="container"> <div class="row align-items-center"> <div class="col-xl-3 col-lg-3"> <div class="logo-img"> <a href="index.html"> <img src="img/logo.png" alt=""> </a> </div> </div> <div class="col-xl-9 col-lg-9"> <div class="main-menu d-none d-lg-block"> <nav> <ul id="navigation"> <li><a href="index.html">home</a></li> <li><a href="story.html">Our Story</a></li> <li><a class="active" href="Gallery.html">Gallery</a></li> <li><a href="#">blog <i class="ti-angle-down"></i></a> <ul class="submenu"> <li><a href="blog.html">blog</a></li> <li><a href="single-blog.html">single-blog</a></li> </ul> </li> <li><a href="#">pages <i class="ti-angle-down"></i></a> <ul class="submenu"> <li><a href="Accommodation.html">Accommodation</a></li> <li><a href="elements.html">elements</a></li> </ul> </li> <li><a href="contact.html">Contact</a></li> </ul> </nav> </div> </div> <div class="col-12"> <div class="mobile_menu d-block d-lg-none"></div> </div> </div> </div> </div> </div> </header> <!--/ header--> <div class="container"> <div class="container text-center"> <img src="Images/Logo.jpg"> <h1>TOKO HanTok</h1> <p>Visi,Misi,Tujuan,Dan Moto</p> </div> </div> <br> <div class="container"> <div class="row"> <div class="col"> <h3>VISI</h3><br> Menjadi toko baju Online yang mampu memberikan kesan puas dan nyaman di hati pelanggannya <h3>TUJUAN</h3><br> -Ingin mempermudah bagi siapa saja yang ingin berbelanja pakaian (baju) tanpa harus repot-repot keluar rumah<br> -Menjadi toko online yang selalu di percaya para pelanggan<br> -Memberikan produk dengan berbagai macam merk dengan harga yang bersaing<br> -Memberikan produk dengan kualitas tinggi namun dengan harga yang terjangkau<br> -Menjadi toko online yang selalu memberikan kepuasan bagi pelanggan dengan menjamin keaslian barang yang di beli, serta pengiriman yang relatif aman dan cepat<br> KEPUASAN KONSUMEN ADALAH KEPUASAN KAMI JUGA </div> <div class="col-6" > <h3>MISI</h3><br> - Kepuasan pelanggan adalah tujuan utama kami<br> `- Mempermudah kalangan masyarakat yang mempunyai kesibukan yang teramat sangat dalam memenuhi kebutuhan sehari-harinya<br> - Mampu menyediakan variasi pilihan baju yang selalu mengikuti trend masa kini <br><h3>MOTO</h3><br> try and never stop to try </div> </body> </html><file_sep>/beli.php <?php include("koneksi.php"); $kode=$_POST['no']; $nama=$_POST['nama']; $jumlah=$_POST['jumlah']; $ukuran=$_POST['ukuran']; $nohp=$_POST['nomerhp']; $email=$_POST['email']; $alamat=$_POST['alamat']; $input="insert into pembelian(kodeproduk, nama, alamat, nomerhp, jumlah, ukuran, email) values ('$kode', '$nama', '$alamat', '$nohp', '$jumlah', '$ukuran', '$email')"; if ($nama=="" or $jumlah=="" or $nohp=="" or $alamat==""){ echo '<script type="text/javascript"> var answer = alert("Data masih belum lengkap") window.location = "produk_detail.php"; </script>'; } else{ $hasil=mysqli_query($conn, $input); if ($hasil){ header('location:index.php?update=2'); } else{ echo '<script type="text/javascript"> var answer = alert("Sudah ada user dengan username tersebut") window.location = "produk_detail.php"; </script>'; } } ?><file_sep>/produk_detail.php <html class="no-js" lang="zxx"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>HANTOK</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link rel="manifest" href="site.webmanifest"> --> <link rel="icon" type="image/icon" href="Images/Logo.jpg"> <!-- Place favicon.ico in the root directory --> <!-- CSS here --> <link rel="stylesheet" href="assets/sunshine/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/sunshine/css/owl.carousel.min.css"> <link rel="stylesheet" href="assets/sunshine/css/magnific-popup.css"> <link rel="stylesheet" href="assets/sunshine/css/themify-icons.css"> <link rel="stylesheet" href="assets/sunshine/css/nice-select.css"> <link rel="stylesheet" href="assets/sunshine/css/flaticon.css"> <link rel="stylesheet" href="assets/sunshine/css/animate.css"> <link rel="stylesheet" href="assets/sunshine/css/slicknav.css"> <link rel="stylesheet" href="assets/sunshine/css/style.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css?family=Josefin+Sans:300,300i,400,400i,700,700i" rel="stylesheet"> <!-- Stylesheets --> <link rel="stylesheet" href="assets/divisima/css/bootstrap.min.css"/> <link rel="stylesheet" href="assets/divisima/css/font-awesome.min.css"/> <link rel="stylesheet" href="assets/divisima/css/flaticon.css"/> <link rel="stylesheet" href="assets/divisima/css/slicknav.min.css"/> <link rel="stylesheet" href="assets/divisima/css/jquery-ui.min.css"/> <link rel="stylesheet" href="assets/divisima/css/owl.carousel.min.css"/> <link rel="stylesheet" href="assets/divisima/css/animate.css"/> <link rel="stylesheet" href="assets/divisima/css/style.css"/> <!-- <link rel="stylesheet" href="css/responsive.css"> --> </head> <body> <div id="preloder"> <div class="loader"></div> </div> <?php include ('koneksi.php'); $no = $_GET['id']; ?> <div class="container"> <div class="container text-center"> <img src="Images/Logo.jpg"> </div> <center><h3>Welcome to HanTok</h3></center> <br><br> <div class="container"> <div class="row"> <?php $slider = mysqli_query($conn, "SELECT * FROM produk WHERE kodeproduk = '$no'"); while($row = mysqli_fetch_array($slider)){ ?> <div class="col"><br><br><br><br><center> <img src="file/<?php echo $row['gambar'] ?>" width="450" height="550"></Center> </div> <div class="col"> <br><br> <center><h3>Sweater Hodie</h3></center> <br> <?php echo $row['keterangan'] ?><br><br> <p>Tersedia Dalam Ukuran:</p> <p>L</p> <p>M</p> <p>XL</p> <p>XXL</p> <br> <br> <br> <tr> <td>Harga</td><br><br> <td class="text-right"><?php echo $row['harga']?></td> </tr> <br> <br> <br> <tr> <td width="92"><button class="btn btn-info" name="upload" type="button" data-toggle="modal" data-target="#exampleModal">Beli sekarang</button></td> <td width="92"><a href="clothes.php" button class="btn btn-info" type="button">Back</a></td> </tr> </div> <?php } ?> </div> <form method="post" action="beli.php"> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Pesan Sekarang</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <?php $no = $_GET['id']; ?> <form> <div class="form-group"> <input type="hidden" name="no" value="<?php echo $no; ?>"> Nama <input name="nama" type="text" class="form-control" id="name" placeholder="Masukan Nama Disini"> <br> Jumlah <input name="jumlah" type="number" class="form-control" id="name" placeholder="Masukan Jumlahnya"> <br> ukuran <select class="form-control" name="ukuran"> <option>M</option> <option>L</option> <option>XL</option> <option>XXL</option> </select> <br> Nomer HP <input name="nomerhp" type="text" class="form-control" id="name" placeholder="+62"> <br> Email <input name="email" type="text" class="form-control" id="name" placeholder="Masukan Email Disini"> <br> Alamat <textarea name="alamat" rows="5" class="form-control" id="message" placeholder="Masukan Alamat Disini" ></textarea> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button> <button type="submit" class="btn btn-primary">Kirim</button> </div> </div> </div> </div> </div> </div> </form> <!-- Footer section end --> <!--====== Javascripts & Jquery ======--> <script src="assets/divisima/js/jquery-3.2.1.min.js"></script> <script src="assets/divisima/js/bootstrap.min.js"></script> <script src="assets/divisima/js/jquery.slicknav.min.js"></script> <script src="assets/divisima/js/owl.carousel.min.js"></script> <script src="assets/divisima/js/jquery.nicescroll.min.js"></script> <script src="assets/divisima/js/jquery.zoom.min.js"></script> <script src="assets/divisima/js/jquery-ui.min.js"></script> <script src="assets/divisima/js/main.js"></script> <script src="assets/sunshine/js/vendor/modernizr-3.5.0.min.js"></script> <script src="assets/sunshine/js/vendor/jquery-1.12.4.min.js"></script> <script src="assets/sunshine/js/popper.min.js"></script> <script src="assets/sunshine/js/bootstrap.min.js"></script> <script src="assets/sunshine/js/owl.carousel.min.js"></script> <script src="assets/sunshine/js/isotope.pkgd.min.js"></script> <script src="assets/sunshine/js/ajax-form.js"></script> <script src="assets/sunshine/js/waypoints.min.js"></script> <script src="assets/sunshine/js/jquery.counterup.min.js"></script> <script src="assets/sunshine/js/imagesloaded.pkgd.min.js"></script> <script src="assets/sunshine/js/scrollIt.js"></script> <script src="assets/sunshine/js/jquery.scrollUp.min.js"></script> <script src="assets/sunshine/js/wow.min.js"></script> <script src="assets/sunshine/js/nice-select.min.js"></script> <script src="assets/sunshine/js/jquery.slicknav.min.js"></script> <script src="assets/sunshine/js/jquery.magnific-popup.min.js"></script> <script src="assets/sunshine/js/plugins.js"></script> <!--contact js--> <script src="assets/sunshine/js/contact.js"></script> <script src="assets/sunshine/js/jquery.ajaxchimp.min.js"></script> <script src="assets/sunshine/js/jquery.form.js"></script> <script src="assets/sunshine/js/jquery.validate.min.js"></script> <script src="assets/sunshine/js/mail-script.js"></script> <script src="assets/sunshine/js/main.js"></script> </body><file_sep>/tambah_produk2.php <?php include ("koneksi.php"); if($_POST['upload']){ $ekstensi_diperbolehkan = array('png','jpg','jpeg'); $nama =$_FILES['file']['name']; $x = explode('.', $nama); $ekstensi = strtolower(end($x)); $ukuran =$_FILES['file']['size']; $file_tmp =$_FILES['file']['tmp_name']; $kode = $_POST['kode']; $barang =$_POST['barang']; $harga =$_POST['harga']; $keterangan =$_POST['keterangan']; $kategori =$_POST['kategori']; if(in_array($ekstensi,$ekstensi_diperbolehkan) === true ){ if($ukuran < 104407031234444){ move_uploaded_file($file_tmp,'file/'.$nama); $query = mysqli_query($conn,"INSERT into produk(kodeproduk,nama_sweater,harga,keterangan,kategori,gambar) values('$kode','$barang','$harga','$keterangan','$kategori','$nama')"); if($query){ echo 'GAMBAR BERHASIL DIUPLOAD'; header('location:pakaian.php'); }else{ echo 'GAGAL MENGUPLOAD GAMBAR'; } }else{ echo 'UKURAN FILE TERLALU BESAR'; } } else{ echo 'EKSTENSI FILE YANG DI UPLOAD TIDAK DIPERBOLEHKAN'; } } ?><file_sep>/index.php <html> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>HANTOK</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link rel="manifest" href="site.webmanifest"> --> <link rel="icon" type="image/icon" href="Images/Logo.jpg"> <!-- Place favicon.ico in the root directory --> <!-- CSS here --> <link rel="stylesheet" href="assets/sunshine/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/sunshine/css/owl.carousel.min.css"> <link rel="stylesheet" href="assets/sunshine/css/magnific-popup.css"> <link rel="stylesheet" href="assets/sunshine/css/themify-icons.css"> <link rel="stylesheet" href="assets/sunshine/css/nice-select.css"> <link rel="stylesheet" href="assets/sunshine/css/flaticon.css"> <link rel="stylesheet" href="assets/sunshine/css/animate.css"> <link rel="stylesheet" href="assets/sunshine/css/slicknav.css"> <link rel="stylesheet" href="assets/sunshine/css/style.css"> <link rel="stylesheet" href="assets/divisima/css/bootstrap.min.css"/> <link rel="stylesheet" href="assets/divisima/css/jquery-ui.min.css"/> <link href="https://fonts.googleapis.com/css?family=Josefin+Sans:300,300i,400,400i,700,700i" rel="stylesheet"> <!-- Stylesheets --> <link rel="stylesheet" href="assets/divisima/css/bootstrap.min.css"/> <link rel="stylesheet" href="assets/divisima/css/font-awesome.min.css"/> <link rel="stylesheet" href="assets/divisima/css/flaticon.css"/> <link rel="stylesheet" href="assets/divisima/css/slicknav.min.css"/> <link rel="stylesheet" href="assets/divisima/css/jquery-ui.min.css"/> <link rel="stylesheet" href="assets/divisima/css/owl.carousel.min.css"/> <link rel="stylesheet" href="assets/divisima/css/animate.css"/> <link rel="stylesheet" href="assets/divisima/css/style.css"/> <link rel="stylesheet" href="assets/divisima/css/bootstrap.min.css"/> <link rel="stylesheet" href="assets/divisima/css/jquery-ui.min.css"/> <link rel="stylesheet" href="assets/divisima/css/style.css"/> <script src="assets/divisima/js/jquery-3.2.1.min.js"></script> <script src="assets/divisima/js/bootstrap.min.js"></script> <script src="assets/divisima/js/main.js"></script> <!-- <link rel="stylesheet" href="css/responsive.css"> --> </head> <body> <div id="preloder"> <div class="loader"></div> </div> <!--[if lte IE 9]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience and security.</p> <![endif]--> <!-- header--> <header> <div class="header-area "> <div id="sticky-header" class="main-header-area"> <div class="row align-items-center"> <div class="col-xl-3 col-lg-3"> <div class="logo-img"> <a href="index.php"> <h4>HANTOK</h4> </a> </div> </div> <div class="col-xl-9 col-lg-9"> <div class="main-menu d-none d-lg-block"> <nav> <ul id="navigation"> <li><a class="active" href="index.php">home</a></li> <li><a href="profil.php">profil</a></li> <li><a href="clothes.php">clothes</a></li> <li><a href="contact.php">Contact</a></li> </ul> </nav> </div> </div> <div class="col-12"> <div class="mobile_menu d-block d-lg-none"></div> </div> </div> </div> </div> </div> </header> <div class="container"> <div class="container text-center"> <img src="Images/Logo.jpg"> <h1>TOKO HanTok</h1> <p><NAME></p> </div> </div> <div class="container"> <div class="bd-example"> <?php include ('koneksi.php'); $slider = mysqli_query($conn, "SELECT * FROM produk WHERE kategori ='Terbaru' ORDER BY kodeproduk DESC"); ?> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <?php $no = 0; for($no;$no<3;$no++){ ?> <li data-target="#carouselExampleIndicators" data-slide-to="<?php echo $no ?>" class="<?php if($no == 0){echo 'active';}else{echo 'notactive';}?>"></li> <?php } ?> </ol> <div class="carousel-inner"> <?php $no = 0; while($row = mysqli_fetch_array($slider)){ ?> <div class="carousel-item <?php if($no == 0){echo 'active';}else{echo 'notactive';}?>"> <img src="file/<?php echo $row['gambar']?>" class="d-block w-100" alt="..."> </div> <?php $no++; } ?> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div><div class="jumbotron jumbotron-fluid"> <center><h1 class="display-4"><NAME></h1></center> </div> </div> <center> <section class="footer-section"> <div class="social-links-warp"> <div class="social-links"> <a href="https://www.instagram.com/darussa_adah/" class="instagram"><i class="fa fa-instagram"></i><span>instagram</span></a> <a href="https://www.facebook.com/darussaadah.bogor/" class="facebook"><i class="fa fa-facebook"></i><span>facebook</span></a> <a href="https://www.youtube.com/channel/UCk-dPqy4rV3EnkYONoVAMRg/videos" class="youtube"><i class="fa fa-youtube"></i><span>youtube</span></a> </div> <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --> <p class="text-white text-center mt-5"> &copy;<script>document.write(new Date().getFullYear());</script> All rights reserved | This template is made <i class="fa fa-heart-o" aria-hidden="true"></i> by <a href="https://www.facebook.com/FarhanYulianto13/" target="_blank">FARHAN</a></p> <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --> </div> </div> </section> <!-- Footer section end --> <!--====== Javascripts & Jquery ======--> <script src="assets/divisima/js/jquery-3.2.1.min.js"></script> <script src="assets/divisima/js/bootstrap.min.js"></script> <script src="assets/divisima/js/jquery.slicknav.min.js"></script> <script src="assets/divisima/js/owl.carousel.min.js"></script> <script src="assets/divisima/js/jquery.nicescroll.min.js"></script> <script src="assets/divisima/js/jquery.zoom.min.js"></script> <script src="assets/divisima/js/jquery-ui.min.js"></script> <script src="assets/divisima/js/main.js"></script> <script src="assets/sunshine/js/vendor/modernizr-3.5.0.min.js"></script> <script src="assets/sunshine/js/vendor/jquery-1.12.4.min.js"></script> <script src="assets/sunshine/js/popper.min.js"></script> <script src="assets/sunshine/js/bootstrap.min.js"></script> <script src="assets/sunshine/js/owl.carousel.min.js"></script> <script src="assets/sunshine/js/isotope.pkgd.min.js"></script> <script src="assets/sunshine/js/ajax-form.js"></script> <script src="assets/sunshine/js/waypoints.min.js"></script> <script src="assets/sunshine/js/jquery.counterup.min.js"></script> <script src="assets/sunshine/js/imagesloaded.pkgd.min.js"></script> <script src="assets/sunshine/js/scrollIt.js"></script> <script src="assets/sunshine/js/jquery.scrollUp.min.js"></script> <script src="assets/sunshine/js/wow.min.js"></script> <script src="assets/sunshine/js/nice-select.min.js"></script> <script src="assets/sunshine/js/jquery.slicknav.min.js"></script> <script src="assets/sunshine/js/jquery.magnific-popup.min.js"></script> <script src="assets/sunshine/js/plugins.js"></script> <!--contact js--> <script src="assets/sunshine/js/contact.js"></script> <script src="assets/sunshine/js/jquery.ajaxchimp.min.js"></script> <script src="assets/sunshine/js/jquery.form.js"></script> <script src="assets/sunshine/js/jquery.validate.min.js"></script> <script src="assets/sunshine/js/mail-script.js"></script> <script src="assets/sunshine/js/main.js"></script> </body> </html><file_sep>/pesan.php <?php include("koneksi.php"); $nama=$_POST['nama']; $email=$_POST['email']; $subject=$_POST['subject']; $pesan=$_POST['pesan']; $input="insert into pesan(nama, email, subject, pesan) values ('$nama', '$email', '$subject', '$pesan')"; if ($nama=="" or $email=="" or $subject=="" or $pesan==""){ echo '<script type="text/javascript"> var answer = alert("Kalo Kirim Pesan Yang Bener dong Bang") window.location = "contact.php"; </script>'; } else{ $hasil=mysqli_query($conn, $input); if ($hasil){ header('location:contact.php?update=2'); } else{ echo '<script type="text/javascript"> var answer = alert("Maaf ni bukannya ngga bisa tapi emang udah ada") window.location = "contact.php"; </script>'; } } ?><file_sep>/clothes.php <html> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>HANTOK</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link rel="manifest" href="site.webmanifest"> --> <link rel="icon" type="image/icon" href="Images/Logo.jpg"> <!-- Place favicon.ico in the root directory --> <!-- CSS here --> <link rel="stylesheet" href="assets/sunshine/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/sunshine/css/owl.carousel.min.css"> <link rel="stylesheet" href="assets/sunshine/css/magnific-popup.css"> <link rel="stylesheet" href="assets/sunshine/css/themify-icons.css"> <link rel="stylesheet" href="assets/sunshine/css/nice-select.css"> <link rel="stylesheet" href="assets/sunshine/css/flaticon.css"> <link rel="stylesheet" href="assets/sunshine/css/animate.css"> <link rel="stylesheet" href="assets/sunshine/css/slicknav.css"> <link rel="stylesheet" href="assets/sunshine/css/style.css"> <link rel="stylesheet" href="assets/divisima/css/bootstrap.min.css"/> <link rel="stylesheet" href="assets/divisima/css/jquery-ui.min.css"/> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css?family=Josefin+Sans:300,300i,400,400i,700,700i" rel="stylesheet"> <!-- Stylesheets --> <link rel="stylesheet" href="assets/divisima/css/bootstrap.min.css"/> <link rel="stylesheet" href="assets/divisima/css/font-awesome.min.css"/> <link rel="stylesheet" href="assets/divisima/css/flaticon.css"/> <link rel="stylesheet" href="assets/divisima/css/slicknav.min.css"/> <link rel="stylesheet" href="assets/divisima/css/jquery-ui.min.css"/> <link rel="stylesheet" href="assets/divisima/css/owl.carousel.min.css"/> <link rel="stylesheet" href="assets/divisima/css/animate.css"/> <link rel="stylesheet" href="assets/divisima/css/style.css"/> <link rel="stylesheet" href="assets/divisima/css/bootstrap.min.css"/> <link rel="stylesheet" href="assets/divisima/css/jquery-ui.min.css"/> <link rel="stylesheet" href="assets/divisima/css/style.css"/> <script src="assets/divisima/js/jquery-3.2.1.min.js"></script> <script src="assets/divisima/js/bootstrap.min.js"></script> <script src="assets/divisima/js/main.js"></script> <!-- <link rel="stylesheet" href="css/responsive.css"> --> </head> <body> <div id="preloder"> <div class="loader"></div> </div> <!--[if lte IE 9]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience and security.</p> <![endif]--> <!-- header--> <header> <div class="header-area "> <div id="sticky-header" class="main-header-area"> <div class="row align-items-center"> <div class="col-xl-3 col-lg-3"> <div class="logo-img"> <a href="index.php"> <h4>HANTOK</h4> </a> </div> </div> <div class="col-xl-9 col-lg-9"> <div class="main-menu d-none d-lg-block"> <nav> <ul id="navigation"> <li><a href="index.php">home</a></li> <li><a href="profil.php">profil</a></li> <li><a class="active" href="clothes.php">clothes</a></li> <li><a href="contact.php">Contact</a></li> </ul> </nav> </div> </div> <div class="col-12"> <div class="mobile_menu d-block d-lg-none"></div> </div> </div> </div> </div> </div> </header> <div class="container text-center"> <img src="Images/Logo.jpg"> <h1>TOKO HanTok</h1> <p>Sweather</p> </div> </div> <center><h2>Terbaru</h2></center> <?php include ('koneksi.php'); $slider = mysqli_query($conn, "SELECT * FROM produk WHERE kategori ='Terbaru' ORDER BY kodeproduk DESC"); ?> <div class="container"> <div class="row"> <?php $no = 0; while($row = mysqli_fetch_array($slider)){ ?> <div class="col-sm-3"> <div class="section-title" style="width:253 height:253"> <img src="file/<?php echo $row['gambar']?>" class="card-img-top"> <div class="add-card" style="width:253 height:253"> <h5 class="card-title"><?php echo $row['nama_sweater']?></h5> <p class="card-text"><?php echo substr( $row['keterangan'],0,15)?></p> <p class="card-text"><?php echo $row['harga']?></p> <a href="produk_detail.php?id=<?php echo $row['kodeproduk'];?>" class="btn btn-danger">Pesan Sekarang</a> </div> </div> </div> <?php $no++; } ?> </div> </div><br><br> <center><h2>Terlaris</h2></center> <?php include ('koneksi.php'); $slider = mysqli_query($conn, "SELECT * FROM produk WHERE kategori ='Terlaris' ORDER BY kodeproduk DESC"); ?> <div class="container"> <div class="row"> <?php $no = 0; while($row = mysqli_fetch_array($slider)){ ?> <div class="col-sm-3"> <div class="section-title" style="width:253 height:253"> <img src="file/<?php echo $row['gambar']?>" class="card-img-top"> <div class="add-card" style="width:253 height:253"> <h5 class="card-title"><?php echo $row['nama_sweater']?></h5> <p class="card-text"><?php echo substr( $row['keterangan'],0,15)?></p> <p class="card-text"><?php echo $row['harga']?></p> <a href="produk_detail.php?id=<?php echo $row['kodeproduk'];?>" class="btn btn-primary">Pesan Sekarang</a> </div> </div> </div> <?php $no++; } ?> </div> </div><br><br> <center><h2>Terkeren</h2></center> <?php include ('koneksi.php'); $slider = mysqli_query($conn, "SELECT * FROM produk WHERE kategori ='Terkeren' ORDER BY kodeproduk DESC"); ?> <div class="container"> <div class="row"> <?php $no = 0; while($row = mysqli_fetch_array($slider)){ ?> <div class="col-sm-3"> <div class="section-title" style="width:253 height:253"> <img src="file/<?php echo $row['gambar']?>" class="card-img-top"> <div class="add-card" style="width:253 height:253"> <h5 class="card-title"><?php echo $row['nama_sweater']?></h5> <p class="card-text"><?php echo substr( $row['keterangan'],0,15)?></p> <p class="card-text"><?php echo $row['harga']?></p> <a href="produk_detail.php?id=<?php echo $row['kodeproduk'];?>" class="btn btn-primary">Pesan Sekarang</a> </div> </div> </div> <?php $no++; } ?> </div> </div><br><br> <center> <section class="footer-section"> <div class="social-links-warp"> <div class="social-links"> <a href="https://www.instagram.com/darussa_adah/" class="instagram"><i class="fa fa-instagram"></i><span>instagram</span></a> <a href="https://www.facebook.com/darussaadah.bogor/" class="facebook"><i class="fa fa-facebook"></i><span>facebook</span></a> <a href="https://www.youtube.com/channel/UCk-dPqy4rV3EnkYONoVAMRg/videos" class="youtube"><i class="fa fa-youtube"></i><span>youtube</span></a> </div> <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --> <p class="text-white text-center mt-5"> &copy;<script>document.write(new Date().getFullYear());</script> All rights reserved | This template is made <i class="fa fa-heart-o" aria-hidden="true"></i> by <a href="https://www.instagram.com/darussa_adah/" target="_blank">DARSAED</a></p> <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --> </div> </section> </center> <!-- Footer section end --> <!--====== Javascripts & Jquery ======--> <script src="assets/divisima/js/jquery-3.2.1.min.js"></script> <script src="assets/divisima/js/bootstrap.min.js"></script> <script src="assets/divisima/js/jquery.slicknav.min.js"></script> <script src="assets/divisima/js/owl.carousel.min.js"></script> <script src="assets/divisima/js/jquery.nicescroll.min.js"></script> <script src="assets/divisima/js/jquery.zoom.min.js"></script> <script src="assets/divisima/js/jquery-ui.min.js"></script> <script src="assets/divisima/js/main.js"></script> <script src="assets/sunshine/js/vendor/modernizr-3.5.0.min.js"></script> <script src="assets/sunshine/js/vendor/jquery-1.12.4.min.js"></script> <script src="assets/sunshine/js/popper.min.js"></script> <script src="assets/sunshine/js/bootstrap.min.js"></script> <script src="assets/sunshine/js/owl.carousel.min.js"></script> <script src="assets/sunshine/js/isotope.pkgd.min.js"></script> <script src="assets/sunshine/js/ajax-form.js"></script> <script src="assets/sunshine/js/waypoints.min.js"></script> <script src="assets/sunshine/js/jquery.counterup.min.js"></script> <script src="assets/sunshine/js/imagesloaded.pkgd.min.js"></script> <script src="assets/sunshine/js/scrollIt.js"></script> <script src="assets/sunshine/js/jquery.scrollUp.min.js"></script> <script src="assets/sunshine/js/wow.min.js"></script> <script src="assets/sunshine/js/nice-select.min.js"></script> <script src="assets/sunshine/js/jquery.slicknav.min.js"></script> <script src="assets/sunshine/js/jquery.magnific-popup.min.js"></script> <script src="assets/sunshine/js/plugins.js"></script> <!--contact js--> <script src="assets/sunshine/js/contact.js"></script> <script src="assets/sunshine/js/jquery.ajaxchimp.min.js"></script> <script src="assets/sunshine/js/jquery.form.js"></script> <script src="assets/sunshine/js/jquery.validate.min.js"></script> <script src="assets/sunshine/js/mail-script.js"></script> <script src="assets/sunshine/js/main.js"></script> </body><file_sep>/datapembeli.php <!DOCTYPE html> <html> <head> <title>Data Pembeli | HanTok</title> <link rel="icon" type="image/icon" href="Images/logo.jpg"> <link rel="stylesheet" href="assets/divisima/css/bootstrap.min.css"/> <link rel="stylesheet" href="assets/divisima/css/jquery-ui.min.css"/> <link rel="stylesheet" href="assets/divisima/css/style.css"/> <script src="assets/divisima/js/jquery-3.2.1.main.js"></script> <script src="assets/divisima/js/bootstrap.min.js"></script> <script src="assets/divisima/js/main.js"></script> <link rel="stylesheet" href="assets/sunshine/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/sunshine/css/owl.carousel.min.css"> <link rel="stylesheet" href="assets/sunshine/css/magnific-popup.css"> <link rel="stylesheet" href="assets/sunshine/css/font-awesome.min.css"> <link rel="stylesheet" href="assets/sunshine/css/themify-icons.css"> <link rel="stylesheet" href="assets/sunshine/css/nice-select.css"> <link rel="stylesheet" href="assets/sunshine/css/flaticon.css"> <link rel="stylesheet" href="assets/sunshine/css/flaticon.css"> <link rel="stylesheet" href="assets/sunshine/css/gijgo.css"> <link rel="stylesheet" href="assets/sunshine/css/slicknav.css"> <link rel="stylesheet" href="assets/sunshine/css/style.css"> </head> <body background="images/logo.jpg"> <?php include("koneksi.php"); ?> <div class="container"><center><div class="alert alert-dark" role="alert"><h1>DATA PEMBELI HANTOK</h1></center> <?php if (!empty($_GET['update'])){ if ($_GET['update']==1) echo "<p class='message'> <h4>Data siswa berhasil diupdate</h4></p>"; else if ($_GET['update']==2) echo "<p class='message'> <h4>Data siswa berhasil ditambahkan</h4></p>"; else if ($_GET['update']==3) echo "<p class='message'> <h4>Data siswa berhasil dihapus</h4></p>"; } ?> <?php $no=1; $sqlCount = "select count(kodeproduk) from pembelian"; $query = mysqli_query($conn, $sqlCount) or die(mysqli_error($conn)); $rsCount = mysqli_fetch_array($query); $banyakData = $rsCount[0]; $page = isset($_GET['page']) ? $_GET['page'] : 1; $limit = 6; $mulai_dari = $limit * ($page - 1); $sql_limit = "select * from pembelian order by kodeproduk limit $mulai_dari, $limit"; $hasil = mysqli_query($conn, $sql_limit) or die(mysqli_error($conn)); if(mysqli_num_rows($hasil)==0){ echo "<p class='message'>Data tidak ditemukan!</p>"; } ?> <table class="table table-striped table-dark"> <thead> <tr class="success"> <td>Kode_Produk</td> <td>Nama</td> <td>alamat</td> <td>NoHP</td> <td>Ukuran</td> <td>jumlah</td> <td>email</td> </tr> </thead> <tbody> <?php $no=$no+(($page-1)*$limit); //Buang field ke dalam array while ($data=mysqli_fetch_array($hasil)){ ?> <tr class="success"> <td><?php echo $data[1]; ?></td> <td><?php echo $data[2]; ?></td> <td><?php echo $data[3]; ?></td> <td><?php echo $data[4]; ?></td> <td><?php echo $data[0]; ?></td> <td><?php echo $data[5]; ?></td> <td><?php echo $data[6]; ?></td> <td> </td> </tr> <?php $no++; }?> </tbody> </table> <?php {}?> <div class="pagination pagination-right"> <?php $banyakHalaman = ceil($banyakData / $limit); echo 'Page '; for($i = 1; $i <= $banyakHalaman; $i++){ if($page != $i){ echo '<a href="data_siswa.php?page='.$i.'">'.$i.' </a> '; }else{ echo "$i "; } } ?> </div> </div> </div> </body> </html>
4fb08eba2541ce634ffd8525a906a86ae72a16db
[ "HTML", "PHP" ]
9
PHP
farhandewapb7/project-KKSI-7
cacf652ca90fcee97448bc135fdee5381aee7604
2ca593c768c52b12d6f926f9f7db8559b8cb3be5
refs/heads/master
<repo_name>AlokeDeepGanguly/node-course-3-todo-api<file_sep>/server/db/mongoose.js var mongoose = require('mongoose'); mongoose.Promise=global.Promise; mongoose.connect(process.env.MONGODB_URI); module.export={mongoose};
bbae5a48da697a4147cd314bda4807a74536229c
[ "JavaScript" ]
1
JavaScript
AlokeDeepGanguly/node-course-3-todo-api
6f3cf99ac6db2ec83fb3a6ceacf629cb36ec3a75
3119a50c8d1c065532dbac18888ecf21d5df5a75
refs/heads/master
<repo_name>seanfinnessy/typing-test<file_sep>/autotyping.py from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from bs4 import BeautifulSoup import pyautogui import time from timeit import default_timer as timer import random print('What length of test would you like? Please enter 1, 3, or 5.') length = input() print('Would you like Random Text, Sentences, or Words?') test = input() if test == 'Random Text': test = '#text5' elif test == 'Sentences': test = '#text3' elif test == 'Words': test = '#text1' else: print('Defaulting to Random Text') test = '#text5' print('Starting test...') with webdriver.Firefox(executable_path=r'C:\PythonLearning\geckodriver.exe') as driver: wait = WebDriverWait(driver, 10) PAGE = "https://typingtest.com" driver.get(PAGE) driver.find_element_by_css_selector(f'#time{length}').click() driver.find_element_by_css_selector('.start-btn').click() time.sleep(5) html = driver.page_source soup = BeautifulSoup(html, 'html.parser') wordList = soup.find_all('span') char = [] for word in range(10, len(wordList)-11): try: char.append(wordList[word].text) except: break print(len(char)) print(len(wordList)) start = timer() for appendedWord in range(len(char)): pyautogui.typewrite(str(char[appendedWord])) pyautogui.press('space') end = timer() print(end) if (end-start) > 60: break time.sleep(10) typingSpeed = driver.find_element_by_css_selector('.speed > span:nth-child(2)').text print(f'You typed at {typingSpeed} wpm.')
c089458f9b7d041e7563298dcb68a6dfdcf17823
[ "Python" ]
1
Python
seanfinnessy/typing-test
0adfecb6d2bb1f042f9424bcb738f60a9121b5ef
e146ec7937fdfbb401da13ab573f96dbb00c9b3b
refs/heads/master
<repo_name>CarlosLopGarcia/Practica-MP<file_sep>/src/Servidor/PrincipalServidor.java package Servidor; public class PrincipalServidor { public static void main(String[] args) { System.out.println("SERVIDOR INICIADO"); ModeloServidor modeloM = new ModeloServidor(); ControladorServidor controladorM = new ControladorServidor(modeloM); } }<file_sep>/src/Cliente/PuntosCliente.java package Cliente; import java.util.Observable; import java.util.Observer; public class PuntosCliente extends javax.swing.JFrame implements Observer{ public PuntosCliente() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { puntuacion = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); puntuacion.setBackground(new java.awt.Color(0, 0, 0)); puntuacion.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N puntuacion.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); puntuacion.setText("0"); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("PUNTUACIÓN"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(puntuacion, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(puntuacion, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold> // Variables declaration - do not modify private javax.swing.JLabel jLabel2; private javax.swing.JLabel puntuacion; // End of variables declaration @Override public void update(Observable o, Object o1) { if(o1.equals(1)){ ControladorCliente.ConectorCliente con = (ControladorCliente.ConectorCliente) o; puntuacion.setText(String.valueOf(con.getPuntos())); } } }<file_sep>/README.md ## SNAKE GAME ------------ Este código está creado por el gupo de MP formado por <NAME>, <NAME> y <NAME>, para la práctica obligatoria de la asignatura Metodología de la Programación. El objetivo de esta práctica es familiarizarnos con los patrones de diseño, en concreto con el Modelo-Vista-Controlador (MVC) y el Observer. Para ello, se nos pide contruir el famoso juego de la serpiente. La aplicación de los patrones descritos anteriormente se realiza dividiendo el juego en 2 partes: un servidor y un cliente; cada uno con sus clases de modelo, vista y controlador. Además, el servidor observa lo que hace el cliente. Para ejecutar con éxito esta aplicación, primero tenemos que importar el proyecto en nuestro IDE (preferiblemente NetBeans, donde ha sido desarrollado), después, se tiene que ejecutar primero el archivo PrincipalServidor.java, para que el mismo se inicie y, a continuación, el archivo PrincipalCliente.java. Al abrir el archivo PrincipalCliente.java, se nos mostrará una ventana principal con los botones de iniciar el juego, cerrar la aplicación, y los nombres de los integrantes del grupo. Una vez se haga clic sobre iniciar juego, se deben insertar como IP: 127.0.0.1 y, como puerto, el 8000, dado que se realiza sobre un servidor local. Una vez hecho esto, se iniciará el juego de la serpiente y solo queda disfrutar. Cabe decir que esta ventana posee un boton para salir de ella. ------------ ## ANEXO ------------ A continuación, se muestras imágenes de las distintas pantallas de la aplicación: * Pantalla de servidor: ![Server Screen](screenshots/serverscreen.png) * Pantalla principal del juego: ![Main Screen](screenshots/snakescreen.png) * Pantallas de introducción de IP y puerto: ![IP Screen](screenshots/ipscreen.png) ![Port Screen](screenshots/portscreen.png) * Pantalla de juego con puntuación: ![Game Screen](screenshots/gamescreen.png) ------------
01585afa843ea84178b413574d0e2271feafa8f9
[ "Markdown", "Java" ]
3
Java
CarlosLopGarcia/Practica-MP
8d8a4f58e93b0fbe0b8103c8766bd4fa596172d1
cf1cea4d3924a3feda008e6f98c1e1d673530817
refs/heads/master
<repo_name>Penaus/Informatik<file_sep>/Experimente/007UngeradeZahl.c #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> int main(void) { int iEingabe = 0; printf("Programm um zu testen, ob die eingegeben Zahl ungerade ist.\n""Bitte Zahl vom Typ Integer eingeben: "); scanf("%d", &iEingabe); rewind(stdin); if (iEingabe % 2 == 1) { printf("\nZahl ungerade."); } else { printf("\nZahl gerade."); } printf("\n\n""Ende des Programms. Enter zum Beenden"); getchar(); return(0); }<file_sep>/Experimente/005PfeilOperator.c #include<stdio.h> int main(void) { struct foo { int x; float y; }; struct foo var; var.x = 5; (&var)->y = 14.3; (&var)->y = 22.4; getchar(); return(0); }<file_sep>/Experimente/001FizzBuzz.c #include<stdio.h> int main(void) { for (int i = 1; i <= 100; i++) { if ((i % 3 == 0) && !(i % 5 == 0)) { printf("Fiz \t"); } else if (!(i % 3 == 0) && (i % 5 == 0)) { printf("Buzz \t"); } else if ((i % 3 == 0) && (i % 5 == 0)) { printf("FizBuzz \t"); } else { printf("%d \t", i); } if (i % 10 == 0) printf("\n"); } getchar(); return(0); }<file_sep>/Experimente/003Struct.c _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<string.h> typedef struct { char name[50]; int alter; }sPerson; void ausgabePerson(sPerson *person) { printf("Name: %s\n", (*person).name); printf("Alter: %d\n", person->alter); } int main() { sPerson kurt; strcpy(kurt.name, "<NAME>"); kurt.alter = 33; ausgabePerson(&kurt); return 0; }<file_sep>/Experimente/002Umdrehen.c #include<stdio.h> #define NMAX 20 int main(void) { int iLaenge=0; char szText[NMAX]; char szUmgedreht[NMAX]; printf("Bitte das umzudrehende Wort eingeben (max 20 Zeichen lang): "); fgets(szText, NMAX, stdin); rewind(stdin); iLaenge = strlen(szText); printf("Eingelesen: %s \nLaenge des Textes(+1 da Zaehlen ab 0): %d \n", szText,iLaenge); for (int i = 0; i <= iLaenge; i++) { szUmgedreht[i] = szText[iLaenge - i]; } for (int i = 0; i <= iLaenge; i++) { printf("%c",szUmgedreht[i]); } getchar(); return(0); }
3cf8836a53b1f930262bd42e2b92b71c0adb9bbe
[ "C" ]
5
C
Penaus/Informatik
0176d8ccdbecb650dcf0d2b99772ce571401f908
2aa121b99a0749feebcf87257b99d8efcff190b7
refs/heads/main
<file_sep># Personal Code Notes, Recipes, and Research Feel free to look around. This is not comprehensive, just a bunch of random notes as I experiment and discover different things, sort of like a repo full of Gists. * [Smallest Docker Go Image](docker/go/smallest) * [Smallest Docker Go Image(without Go)](docker/go/smallest-nogo) * [Experimenting with Go Contexts](go/context) * [Go SQLite Notes](go/sqlite) ## Caveats * This is one of the few repos where I commit directly to `main` <file_sep># Minimal Possible Go Docker Image * Remember that `FROM scratch` is unique * Explicit `WORKDIR` and `AS` might save your from a bad day <file_sep>#!/bin/sh docker build --tag hello . <file_sep>package main import ( C "context" "log" "sync" "gitlab.com/rwxrob/cmdtab" ) func main() { wg := new(sync.WaitGroup) ctx, cancel := C.WithCancel(C.Background()) go first(ctx, wg) go second(ctx, wg) go third(ctx, wg) cmdtab.WaitForInterrupt(cancel) wg.Wait() } func first(ctx C.Context, wg *sync.WaitGroup) { log.Println("starting first") wg.Add(1) <-ctx.Done() log.Println("stopping first") wg.Done() } func second(ctx C.Context, wg *sync.WaitGroup) { log.Println("starting second") wg.Add(1) <-ctx.Done() log.Println("stopping second") wg.Done() } func third(ctx C.Context, wg *sync.WaitGroup) { log.Println("starting third") wg.Add(1) <-ctx.Done() log.Println("stopping third") wg.Done() } <file_sep># Minimal Possible Go Docker Image * Remember that `FROM scratch` is unique * This requires `go` be installed on the local system <file_sep>FROM golang AS gobuild ADD hello.go / WORKDIR / RUN go build hello.go FROM scratch COPY --from=gobuild hello / CMD ["/hello"] <file_sep>#!/bin/sh go build hello.go docker build --tag hello . <file_sep>module gitlab.com/rwxrob/codebook/go/context go 1.15 replace gitlab.com/rwxrob/cmdtab => ../../../cmdtab require gitlab.com/rwxrob/cmdtab v0.0.0-00010101000000-000000000000 <file_sep># Go SQLite Setup ```sh go get github.com/mattn/go-sqlite3 export CGO_ENABLED=1 ``` 1. Install `gcc` 1. Install `sqlite` <file_sep>package main import "fmt" func main() { fmt.Println("Hello there, again! [built with gobuild image]") } <file_sep># Experimenting with Go Contexts 1. Make sure to pass `context.WithCancel` correctly 1. Make sure to deal with `<-ctx.Done()` 1. Make sure not to block out `<-ctx.Done()` 1. Confirm that `cancel` will affect *all* goroutines
e38044d78c8441b178ce627b9a44c90423098afc
[ "Markdown", "Go", "Go Module", "Dockerfile", "Shell" ]
11
Markdown
Playfloor/codebook
96a8d769283fecd01a9060af28f0fdd25c25a800
19320f892dee5d0c977c2ab829e2a8149b2a0dbf
refs/heads/master
<repo_name>VishalHasija/ChatApp<file_sep>/internal/handlers/handlers.go package handlers import ( "net/http" "log" "github.com/CloudyKit/jet/v6" "github.com/gorilla/websocket" ) var views = jet.NewSet( jet.NewOSFileSystemLoader("./html"), jet.InDevelopmentMode(), ) var upgradeConnection = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, } func Home(rw http.ResponseWriter, r *http.Request) { err := renderPage(rw, "home.jet", nil) if err != nil { log.Println("Error rendering page : ", err) } } //WsJsonResponse defines the response sent back from websocket type WsJsonResponse struct { Action string `json:"action"` Message string `json:"messsage"` MessageType string `json:"messsage_type"` } //WsEndpoint upgrades connection to websocket. func WsEndpoint(rw http.ResponseWriter, r *http.Request) { ws, err := upgradeConnection.Upgrade(rw, r, nil) if err != nil { log.Println("Upgrade to websocket error : ", err) } log.Println("Client connected to Websocket endpoint") var response WsJsonResponse response.Message = `<em><small>Connected to server</small></em>` err = ws.WriteJSON(response) if err != nil { log.Println("Error parsing and sending json response : ", err) } } func renderPage(rw http.ResponseWriter, tmpl string, data jet.VarMap) error { view, err := views.GetTemplate(tmpl) if err != nil { log.Println("Error rendering page : ", err) return err } err = view.Execute(rw, data, nil) if err != nil { log.Println("Error rendering page : ", err) return err } return nil } <file_sep>/go.mod module github.com/VishalHasija/ChatApp go 1.16 require ( github.com/CloudyKit/jet/v6 v6.1.0 github.com/bmizerany/pat v0.0.0-20210406213842-e4b6760bdd6f github.com/gorilla/websocket v1.4.2 )
b441a0162fc595226f7180a948f283b4e8e97693
[ "Go Module", "Go" ]
2
Go
VishalHasija/ChatApp
9626ba8becbc04fd6bed698b047b8cabdd043581
49ec3c2bdd48e63ae7a68e956edf70a3c6368206
refs/heads/master
<file_sep>package main import "sync" // setup const ( N = 1000 Conc = 1000 ) type adder struct { sum int N int } func (a *adder) add() { for i := 0; i < Conc; i++ { a.sum++ } wg.Done() } func newAdder(n int) *adder { return &adder{sum: 0, N: n} } var adders = make([]*adder, Conc) var wg = sync.WaitGroup{} func main() { N := 1000 wg.Add(Conc) for i := 0; i < Conc; i++ { adders[i] = newAdder(N) go adders[i].add() } wg.Wait() println(getTotal()) } func getTotal() int { total := 0 for i := 0; i < Conc; i++ { total += adders[i].sum } return total } <file_sep>package filemd5 import ( "encoding/hex" // "fmt" "path/filepath" "testing" ) // http://stackoverflow.com/questions/15311969/checking-the-equality-of-two-slices func testEq(a, b []byte) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } func TestMd5OnFile(t *testing.T) { abs_path, _ := filepath.Abs("input_file.txt") actual := RunOnFile(abs_path) expected_result, err := hex.DecodeString("5eb63bbbe01eeed093cb22bb8f5acdc3") if err != nil { panic(err) } eq := testEq(actual[:], expected_result[:]) if !eq { t.Errorf("Does not match expected result. actual:%x, expected:%x ", actual, expected_result) } } func TestOnString(t *testing.T) { actual := RunOnString("hello world") expected_result, err := hex.DecodeString("5eb63bbbe01eeed093cb22bb8f5acdc3") if err != nil { panic(err) } eq := testEq(actual[:], expected_result[:]) if !eq { t.Errorf("Does not match expected result. actual:%x, expected:%x ", actual, expected_result) } } <file_sep>// Must run from . folder for file path to work package filemd5 import ( "crypto/md5" "io/ioutil" ) func RunOnFile(file_path string) [16]byte { data1, err := ioutil.ReadFile(file_path) if err != nil { panic(err) } result := (md5.Sum(data1)) return result } // silly function, but this is an exercise to expose the package elsewhere func RunOnString(s string) [16]byte { result := md5.Sum([]byte(s)) return result } <file_sep>package main import ( "sync" ) // setup const ( N = 1000 Conc = 1000 ) var mutex = &sync.Mutex{} func adder(acc *int, done chan bool) { for i := 0; i < N; i++ { mutex.Lock() *acc++ mutex.Unlock() } done <- true } func main() { acc := 0 done := make(chan bool) for i := 0; i < Conc; i++ { go adder(&acc, done) } // Wait for all goroutines to complete for i := 0; i < Conc; i++ { <-done } println(acc) // Should == Conc x N } <file_sep>package main // setup const ( N = 1000 Conc = 1000 ) func adder() { sum := 0 for i := 0; i < N; i++ { sum++ } results <- sum } var results chan int func main() { // done := make(chan bool) results = make(chan int) for i := 0; i < Conc; i++ { go adder() } total := 0 for i := 0; i < Conc; i++ { nextResult := <-results total += nextResult } println(total) // Should == Conc x N } <file_sep>package main import "time" // setup const ( N = 1000 Conc = 1000 ) type adder struct { isDone bool sum int N int } func (a *adder) add() { for i := 0; i < Conc; i++ { a.sum++ } a.isDone = true } func newAdder(n int) *adder { return &adder{isDone: false, sum: 0, N: n} } var adders = make([]*adder, Conc) func main() { N := 1000 for i := 0; i < Conc; i++ { adders[i] = newAdder(N) go adders[i].add() } for { if !allDone() { time.Sleep(250 * time.Millisecond) } else { break } } println(getTotal()) } func allDone() bool { for i := 0; i < Conc; i++ { if !adders[i].isDone { return false } } return true } func getTotal() int { total := 0 for i := 0; i < Conc; i++ { total += adders[i].sum } return total }
91d22ee786c37b95d1808f399fcbde82f4729eb8
[ "Go" ]
6
Go
jasonsatran/go_learning
423dbf7167dfaf0820c26efe8c98a88aefc57b3a
eb7e4a1c2b6e5cc9371e25eeaa9027d856a4b364
refs/heads/master
<repo_name>alekseef/game<file_sep>/index.js window.onload = function() { for (let i=0; i<50; i++) { update_stocks(); } update(); setTimeout("create_led(0)",0); setTimeout("led_go()",1); setTimeout("delete_led()",1700*speed_led); }; var div_money = document.getElementById("money"); var div_income_total = document.getElementById('income_total'); var div_outlay_total = document.getElementById('outlay_total'); var div_potok = document.getElementById('potok_money'); var div_imcome_name = document.getElementById('imcome_name'); var div_imcome_money = document.getElementById('imcome_money'); var div_outlay_name = document.getElementById('outlay_name'); var div_outlay_money = document.getElementById('outlay_money'); var div_active_type = document.getElementById('active_type'); var div_active_name = document.getElementById('active_name'); var div_active_count = document.getElementById('active_count'); var div_active_profit = document.getElementById('active_profit'); var div_active_price = document.getElementById('active_price'); var div_passive_type = document.getElementById('passive_type'); var div_passive_name = document.getElementById('passive_name'); var div_passive_pay = document.getElementById('passive_pay'); var div_passive_debt = document.getElementById('passive_debt'); var div_passive_type_bank = document.getElementById('bank_passive_type'); var div_passive_name_bank = document.getElementById('bank_passive_name'); var div_passive_pay_bank = document.getElementById('bank_passive_pay'); var div_passive_debt_bank = document.getElementById('bank_passive_debt'); var led = document.getElementById('led'); var progress; var currency = "₽"; //Процентная ставка для банка var bank_rate = 30; var bank_rate_deposit = 10; //Стартовые деньги var money = 1000; var money_income; var money_outlay; var potok_money; //Банк var diolog_banker = document.getElementById('diolog_banker'); var min_sum_credit = 30000; var max_sum_credit; var card_limit = 300000; var card = card_limit; var card_commission = 7; var card_rate = 12; var card_payout = 0; var base_imcome_name = ["Заработаная плата"]; var base_imcome_money = [80000]; var imcome_name = []; var imcome_money = []; var base_outlay_name = ["Квартплата", "Питание", "Дети"]; var base_outlay_money = [30000, 20000, 25000]; var outlay_name = []; var outlay_money = []; var names_actives = //Тип Название Количество Доход Цена ["type", "name", "count", "profit", "price"]; var active = [ [], ["Недвижимость", "2x-ком кв.", 1, 16000, 200000], ["Облигации", "<NAME>", 20, 2000, 20000], ]; var names_passives = //Тип Название Выплаты Долг ["type", "name", "pay", "debt"]; var passive = [ [], ["Кредит", "<NAME>", 2500, 10000], ["Кредит", "<NAME>", 3000, 5000], ["Кредит", "<NAME>у", 15000, 20000], ]; var stocks = [ [], ["Газпром", 1500], ["Лукоил", 1200], ["Роснефть", 1000], ["Мтс", 500], ["Яндекс", 700], ["АвтоВАЗ", 200] ]; function update() { update_stocks(); //Высчитываем сумму выплаты по кредиту var arr_yes = in_array("Кредит в Банке", passive, 1); if (arr_yes != false) { passive[arr_yes][2] = Math.round((passive[arr_yes][3] / 100 * bank_rate) / 12); } var arr_yes = in_array("Кредитка", passive, 1); if (arr_yes != false) { passive[arr_yes][2] = Math.round((passive[arr_yes][3] / 100 * card_rate) / 12); card_payout = passive[arr_yes][2]; if (passive[arr_yes][2] < 50) { card_payout = 1; } } var arr_yes = in_array("Кредитка", passive, 1); if (arr_yes != false) { if (passive[arr_yes][3] <= 0) { passive.splice(arr_yes, 1); } } //Высчитываем выплаты по депозиту var arr_yes = in_array("Вклад под 10%", active, 1); if (arr_yes != false) { active[arr_yes][3] = Math.round((active[arr_yes][4] / 100 * bank_rate_deposit) / 12); } imcome_name = []; imcome_name = imcome_name.concat(base_imcome_name); imcome_money = []; imcome_money = imcome_money.concat(base_imcome_money); outlay_name = []; outlay_name = outlay_name.concat(base_outlay_name); outlay_money = []; outlay_money = outlay_money.concat(base_outlay_money); //Добавляем в Доходы актуальные Активы active.forEach(function(item, i, elem) { if (active[i][3] > 0) { imcome_name.push(active[i][1]); imcome_money.push(active[i][3]); } }); passive.forEach(function(item, i, elem) { if (passive[i][2] > 0) { outlay_name.push(passive[i][1]); outlay_money.push(passive[i][2]); } }); //Подсчитываем доходы,расходы money_income = 0; imcome_money.forEach(function(item, i, elem) { money_income = money_income + item; }); money_outlay = 0; outlay_money.forEach(function(item, i, elem) { money_outlay = money_outlay + item; }); money_outlay = -money_outlay; potok_money = money_income + money_outlay; //Высчитываем какая сумма кредита доступна var arr_yes = in_array("Кредит в Банке", passive, 1); if (arr_yes != false) { max_sum_credit = (((money_income * 12 * 100) / bank_rate) / 100 * 30) - (passive[arr_yes][3]); } else { max_sum_credit = (((money_income * 12 * 100) / bank_rate) / 100 * 30); } google.charts.load('current', {packages: ['corechart', 'line']}); google.charts.setOnLoadCallback(drawLineColors); display(); } function next() { money = money + potok_money; update(); } function create_klad() { active.splice(-1,1); update(); } //------------------------------------------------------------ //Выводим актуальные значения function display() { display_div(imcome_name, "text", div_imcome_name, ":", ""); display_div(imcome_money, "money", div_imcome_money, " "+currency, "+ "); display_div(outlay_name, "text", div_outlay_name, ":", ""); display_div(outlay_money, "money", div_outlay_money, " "+currency, "- "); names_actives.forEach(function(item, i, elem) { display_div_new(active, window["div_active_"+item], i); }); names_passives.forEach(function(item, i, elem) { display_div_new(passive, window["div_passive_"+item], i); }); names_passives.forEach(function(item, i, elem) { display_div_new(passive, window["div_passive_"+item+"_bank"], i); }); div_money.innerHTML = money; div_income_total.innerHTML = minus_plus(money_income); div_outlay_total.innerHTML = minus_plus(money_outlay); div_potok.innerHTML = minus_plus(potok_money); div_income_total.classList.add("green"); div_outlay_total.classList.add("red"); div_potok.classList.remove("green"); div_potok.classList.remove("red"); potok_money >= 0 ? div_potok.classList.add("green") : div_potok.classList.add("red") close_deposit_update(); document.getElementById('card_limit').innerHTML = "Кредитный лимит на карте: "+card_limit+" ₽."; document.getElementById('card').innerHTML = "Доступно: "+card+" ₽."; document.getElementById('card_commission').innerHTML = "Коммисия за снятие наличных: "+card_commission+" %."; document.getElementById('card_payout').innerHTML = "Выплаты по кредитной карте: "+card_payout+" ₽."; document.getElementById('card_dolg').innerHTML = "Задолжность: "+int(card-card_limit)+" ₽."; } function display_div(elem, name_class, div_elem, pin, sign) { while (div_elem.firstChild) { div_elem.removeChild(div_elem.firstChild);} elem.forEach(function(item, i, elem) { var elem_name = document.createElement('div'); elem_name.classList.add(name_class) var elem_text = document.createTextNode(sign+item+pin); elem_name.appendChild(elem_text); div_elem.appendChild(elem_name); }); } function display_div_new(elem, div_elem, k) { var pin; var sign; while (div_elem.firstChild) { div_elem.removeChild(div_elem.firstChild); } elem.forEach(function(item, i, elem) { if (i != 0) { var elem_name = document.createElement('div'); elem_name.classList.add("text"); if (div_elem === div_active_profit || div_elem === div_active_price || div_elem === div_passive_pay || div_elem === passive_debt) { pin = " "+currency;} else {pin = ""; } if (div_elem === div_active_profit) { sign = "+ ";} else {sign = "";} if (div_elem === div_passive_pay) { sign = "- ";} else {sign = "";} var elem_text = document.createTextNode(sign+item[k]+pin); elem_name.appendChild(elem_text); div_elem.appendChild(elem_name); if (div_elem === div_passive_name_bank) { elem_name.setAttribute('onclick', 'return choose_credit("'+elem_name.innerHTML+'");'); } } }); } //////////////////////////////////////////////////////////////////////// /////////// Светодиодный дисплэй //////////////////////////////////////////////////////////////////////// var speed_led = 7; var text_time_led; var what_rate; function led_go(i) { var elements = document.querySelectorAll("div.rate"); for (let elem of elements) { let obj = elem.style.left; obj.substring(0, obj.length - 2); obj = int(obj) - 1; elem.setAttribute('style', 'left: '+obj+'px;'); } setTimeout("led_go()",speed_led); } function create_led(i) { i = i + 1; if (i == stocks.length) i = 1; let elem_name = document.createElement('div'); elem_name.classList.add("rate"); elem_name.setAttribute('style', 'left: 1230px;'); let div_led_name = document.createElement('div'); div_led_name.classList.add("rate_name"); let div_led_value = document.createElement('div'); div_led_value.classList.add("rate_value"); let text = stocks[i][0]; let value; if (stocks[i][stocks[i].length - 1] < stocks[i][stocks[i].length - 2]) { value = stocks[i][stocks[i].length - 1]+"▼"; div_led_value.classList.add("rate_color_red"); } else if (stocks[i][stocks[i].length - 1] == stocks[i][stocks[i].length - 2]) { value = stocks[i][stocks[i].length - 1]+" "; } else { value = stocks[i][stocks[i].length - 1]+"▲"; div_led_value.classList.add("rate_color_green"); } div_led_name.appendChild(document.createTextNode(text)); div_led_value.appendChild(document.createTextNode(value)); led.appendChild(elem_name); elem_name.appendChild(div_led_name); elem_name.appendChild(div_led_value); //text_time_led = int(text.length) + int(value.length); text_time_led = elem_name.offsetWidth / 13; setTimeout(create_led, speed_led*20*text_time_led, i); } function delete_led() { led.removeChild(led.firstChild); setTimeout(delete_led, speed_led*20*text_time_led); } //////////////////////////////////////////////////////////////////////// /////////// Курс акций //////////////////////////////////////////////////////////////////////// //пока так... потом сделаю более интересно. function update_stocks() { for (let i=1; i<stocks.length; i++) { let last_value = stocks[i][stocks[i].length - 1]; if (last_value > 0 ) { if (last_value < 10) { random_value = random_int( 0, 3); } else if (last_value >= 10 && last_value < 25) { random_value = random_int( -2, 5); } else if (last_value >= 25 && last_value < 50) { random_value = random_int( random_int( -5, 0), random_int( 5, 10)); } else if (last_value >= 50 && last_value < 100) { random_value = random_int( random_int( -10, 0), random_int( 0, 10)); } else if (last_value >= 100 && last_value < 200) { random_value = random_int( random_int( -25, 0), random_int( 0, 25)); } else if (last_value >= 200 && last_value < 500) { random_value = random_int( random_int( -50, -10), random_int( 10, 50)); } else { random_value = random_int( random_int( -100, -50), random_int( 50, 100)); } } stocks[i].push(last_value+random_value); } } //////////////////////////////////////////////////////////////////////// /////////// Банкомат //////////////////////////////////////////////////////////////////////// function get_cash_bankomat() { var input_cash_bankomat = document.getElementById('input_cash_bankomat'); if (input_cash_bankomat.value != "" && input_cash_bankomat.value >= 50 && input_cash_bankomat.value <= int(card)) { var arr_yes = in_array("Кредитка", passive, 1); if (arr_yes != false) { passive[arr_yes][3] = int(input_cash_bankomat.value) + int(passive[arr_yes][3]); money = int(money + (int(input_cash_bankomat.value) - int(input_cash_bankomat.value) / 100 * card_commission)); card = card - int(input_cash_bankomat.value); } else { passive.push(["Кредитная карта", "Кредитка", 0, input_cash_bankomat.value]); money = int(money + (int(input_cash_bankomat.value) - int(input_cash_bankomat.value) / 100 * card_commission)); card = card - int(input_cash_bankomat.value); } } input_cash_bankomat.value = ""; update(); } function refill_bankomat() { var input_cash_bankomat = document.getElementById('input_cash_bankomat'); if (input_cash_bankomat.value != "" && card_limit-card > 0) { if (input_cash_bankomat.value > card_limit-card) { input_cash_bankomat.value = card_limit-card; } var arr_yes = in_array("Кредитка", passive, 1); if (input_cash_bankomat.value >= passive[arr_yes][3]) { input_cash_bankomat.value = passive[arr_yes][3]; } if (money >= input_cash_bankomat.value) { card = card + int(input_cash_bankomat.value); money = money - int(input_cash_bankomat.value); passive[arr_yes][3] = int(passive[arr_yes][3]) - input_cash_bankomat.value; } input_cash_bankomat.value = ""; update(); } } //////////////////////////////////////////////////////////////////////// /////////// Bank //////////////////////////////////////////////////////////////////////// var bank_what_pay; function credit() { var input_sum_credit = document.getElementById('input_credit').value; var arr_yes = in_array("Кредит в Банке", passive, 1); if (input_sum_credit != "") { if (input_sum_credit >= min_sum_credit && input_sum_credit <= max_sum_credit) { if (arr_yes != false) { passive[arr_yes][3] = parseInt(input_sum_credit, 10) + parseInt(passive[arr_yes][3], 10); money = money + parseInt(input_sum_credit); update(); } else { passive.push(["Кредит", "Кредит в Банке", 0, input_sum_credit]); money = money + parseInt(input_sum_credit); update(); } diolog_banker.innerHTML = "Приятно с вами соотрудничать. Ваша сумма " + input_sum_credit + " ₽ уже зачислена на ваш счет."; } else { if (input_sum_credit < min_sum_credit) { diolog_banker.innerHTML = "Наш банк, выдает кредиты только от "+min_sum_credit+" ₽."; } if (input_sum_credit > max_sum_credit) { diolog_banker.innerHTML = "Мы не можем выдать вам сумму превышающую "+max_sum_credit+" ₽, так как выплаты по кредиту привышают сумму вашего дохода."; } } document.getElementById('input_credit').value = ''; } else { diolog_banker.innerHTML = "Друг мой, о какой сумме идет речь?"; } } function deposit() { var input_sum_deposit = document.getElementById('input_deposit').value; var arr_yes = in_array("Вклад под 10%", active, 1); if (input_sum_deposit != "") { if (input_sum_deposit >= 50000) { if(input_sum_deposit <= money) { if (arr_yes != false) { active[arr_yes][4] = parseInt(input_sum_deposit, 10) + parseInt(active[arr_yes][4], 10); money = money - parseInt(input_sum_deposit); update(); } else { active.push(["Вклад", "Вклад под 10%", "-", 1000, input_sum_deposit]); money = money - parseInt(input_sum_deposit); update(); } } else { diolog_banker.innerHTML = "Дружище, как найдешь деньги, тогда приходи. Не трать не мое время не свое..."; } } else { diolog_banker.innerHTML = "Наш банк принимает вклады только от 50000 ₽."; } document.getElementById('input_deposit').value = ''; } else { diolog_banker.innerHTML = "Друг мой, мы не принимаем пустые вклады..."; } } function out_bank() { diolog_banker.innerHTML = "Наш банк может одобрить вам кредит до "+max_sum_credit+" ₽."; } function go_credit(){ diolog_banker.innerHTML = "Наш банк может одобрить вам кредит до "+max_sum_credit+" ₽."; } function go_vklad(){ diolog_banker.innerHTML = "Так же Вы можете вложить свое деньги в наш вклад под процент."; } function choose_credit(id) { diolog_banker.innerHTML = "Вы хотите рассчитаться с вашим долгом по "+id+" ?"; bank_what_pay = id; } function close_deposit_update() { var close_deposit = document.getElementById('close_deposit'); var arr_yes = in_array("Вклад под 10%", active, 1); if (arr_yes != false) { close_deposit.classList.remove("not_show"); } else { close_deposit.classList.add("not_show"); } } function close_deposit(){ var arr_yes = in_array("Вклад под 10%", active, 1); money = money + parseInt(active[arr_yes][4], 10); active.splice(arr_yes, 1); update(); } function credit_pay() { var input_credit_pay = document.getElementById('input_credit_pay').value; if (bank_what_pay != undefined) { var arr_yes = in_array(bank_what_pay, passive, 1); if (input_credit_pay != "") { if (arr_yes != false) { if (passive[arr_yes][3] <= input_credit_pay) { input_credit_pay = passive[arr_yes][3]; } if (money >= input_credit_pay) { money = money - input_credit_pay; passive[arr_yes][3] = parseInt(passive[arr_yes][3], 10) - input_credit_pay; if (passive[arr_yes][3] <= 0) { passive.splice(arr_yes, 1); diolog_banker.innerHTML = "Ваш долг по "+bank_what_pay+" полностью."; } else { diolog_banker.innerHTML = "Ваш долг по "+bank_what_pay+" частично погашен."; } } else { diolog_banker.innerHTML = "Хм. У вас не хватает денег друг мой..."; } } document.getElementById('input_credit_pay').value = ""; update(); } else { diolog_banker.innerHTML = "Сколько вы хотите погасить по "+bank_what_pay+" ?"; } } else { diolog_banker.innerHTML = "За что вы хотите совершить выплату?"; } } function in_array(value, array, k) { for(var i = 0; i < array.length; i++) { if(array[i][k] == value) return i; } return false; } function minus_plus(money) { if (money >= 0) { money = "+ " +String(money); return money; } else { money = String(money); money = "- " +money.replace('-', ''); return money; } } function int(value) { return parseInt(value, 10); } function random_int(min, max) { return Math.floor(Math.random() * (max - min)) + min; } //////////////////////////////////////////////////////////////////////// /////////// График фондовой биржи //////////////////////////////////////////////////////////////////////// function drawLineColors() { var data = new google.visualization.DataTable(); data.addColumn('number', 'X'); for (let i=1; i<stocks.length; i++) { data.addColumn('number', stocks[i][0]); } var stocks_new = []; for (let i=0; i<stocks[1].length-1; i++) { stocks_new[i] = [i]; for (let j=1; j<stocks.length; j++) { stocks_new[i].push(stocks[j][i+1]); } } data.addRows(stocks_new); var options = { hAxis: { title: 'Время' }, height: 600, vAxis: { title: 'Цена' }, // ["Газпром", 987], // ["Лукоил", 355], // ["Роснефть", 382], // ["Мтс", 122], // ["Яндекс", 477], // ["Пятерочка", 33] colors: ['#002EA4','#a52714', '#FFDD00','#FF0000','#FFBF00','#00CA00'] }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); }
d440e1813fed25197e144177dd6758db6aaba540
[ "JavaScript" ]
1
JavaScript
alekseef/game
884f37ada86e325d739e2047cfca3c4035b3d673
e214ba93af4c127192376df3e1669c4d8fc17dba
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Boking { public class ViewManager : Singleton<ViewManager> { private Dictionary<string, ViewController> m_ControllerDict = new Dictionary<string, ViewController>(); private List<string> m_ShowingList = new List<string>(); private List<string> m_HidingList = new List<string>(); private ViewManager() { } public override void Init() { } private void Register<T>(string viewName) where T : ViewController, new() { if (!m_ControllerDict.ContainsKey(viewName)) { m_ControllerDict.Add(viewName, new T()); } } public bool GetController(string viewName, out ViewController controller) { return m_ControllerDict.TryGetValue(viewName, out controller); } private void RemoveFromShowingList(string viewName) { if (m_ShowingList.Contains(viewName)) { m_ShowingList.Remove(viewName); } } /// <summary> /// 显示某一视图 /// </summary> /// <param name="viewName">模块名称</param> /// <param name="cleanly">是否关闭其他已打开的模块</param> /// <param name="args">传入的参数</param> public void Show(string viewName, bool cleanly, object args) { if (GetController(viewName, out ViewController controller)) { if (m_HidingList.Contains(viewName)) { controller.Display(args); m_HidingList.Remove(viewName); } else { controller.Show(args); } m_ShowingList.Add(viewName); if (cleanly) { Clean(true); } } } public void Remove(string viewName) { if (GetController(viewName, out ViewController controller)) { if (!controller.IsResident) { controller.Remove(); RemoveFromShowingList(viewName); } else { Hide(viewName); RemoveFromShowingList(viewName); } } } /// <summary> /// 隐藏某一视图,内部方法,禁止外部调用 /// </summary> /// <param name="viewName"></param> private void Hide(string viewName) { if (GetController(viewName, out ViewController controller)) { controller.Hide(); m_HidingList.Add(viewName); } } /// <summary> /// 清空所有已打开的视图 /// </summary> /// <param name="isRetainTop">是否保留栈顶的视图</param> public void Clean(bool isRetainTop) { while (m_ShowingList.Count > 0) { Remove(m_ShowingList[0]); m_ShowingList.RemoveAt(0); } if (!isRetainTop) { Remove(m_ShowingList[0]); m_ShowingList.RemoveAt(0); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Boking { public class ViewController { public View SelfView { get; set; } /// <summary> /// 视图是否需要常驻内存,如果指定,则打开后就不在释放,除非显式指定 /// </summary> public bool IsResident { get; set; } private readonly Dictionary<int, EventListener> m_EventListenerDict = new Dictionary<int, EventListener>(); public ViewController() { SelfView = null; IsResident = false; InitEvent(); } /// <summary> /// 初始化模块事件监听 /// </summary> public void InitEvent() { } /// <summary> /// 初始化View组件 /// </summary> /// <param name="obj">初始化参数</param> public virtual async void InitView(object args) { // 加载Prefab // GameObject gameObject; // await ResouceManager.LoadPrefab(this.m_PrefabPath, out gameObject); // gameObject.AddComponent(gameObject); // this.m_View = gameObject.GetComponent(); // this.m_View.SetController(this); // this.m_View.InitData(args); } /// <summary> /// 显示视图 /// </summary> /// <param name="args"></param> public void Show(object args) { if (SelfView == null) { InitView(args); SelfView.Transition(); } SelfView.SetActive(true); } /// <summary> /// 显示视图,此前视图已经存在 /// </summary> /// <param name="args"></param> public void Display(object args) { if (SelfView != null) { SelfView.Reinit(args); SelfView.Transition(); SelfView.SetActive(true); } } public void Hide() { if (SelfView) { SelfView.SetActive(false); } } public void Remove() { if (SelfView) { SelfView.Remove(); } RemoveAllEvent(); } public void AddEvent(int key, EventListener listener) { m_EventListenerDict.Add(key, listener); EventManager.Instance.AddEvent(key, listener); } public void RemoveAllEvent() { foreach(var item in m_EventListenerDict) { EventManager.Instance.RemoveEvent(item.Key, item.Value); } m_EventListenerDict.Clear(); } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Boking { public class LifeCycleManager : Singleton<LifeCycleManager> { private LifeCycleManager() { } public override void Init() { } public void Update() { } public void FixedUpdate() { } public void Pause() { } public void Resume() { } public void Destory() { } /// <summary> /// 游戏切到后台 /// </summary> public void OnBackground() { } /// <summary> /// 游戏切到前台 /// </summary> public void OnForeground() { } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Boking { public class Timer { /// <summary> /// 启动时的时间戳 /// </summary> private float m_TimestampLaunch; /// <summary> /// 总时间 /// </summary> private float m_Duration; /// <summary> /// 步长-默认1s /// </summary> private float m_Stride; /// <summary> /// 当前流失时间 /// </summary> private float m_CurrentElapsedTime; /// <summary> /// 总流失时间 /// </summary> private float m_TotalElapsedTime; /// <summary> /// 剩余的时间 /// </summary> private float m_RemainingTime; /// <summary> /// 是否循环 /// </summary> private bool m_IsLoop; /// <summary> /// 是否被暂停了 /// </summary> private bool m_IsPaused; private bool m_IsFirstTikTok; /// <summary> /// 倒计时完成的回调 /// </summary> private Action m_CallbackCompleted; /// <summary> /// 指定时间间隔的回调 /// </summary> private Action<float, float> m_CallbackProcess; /// <summary> /// 倒计时是否完成 /// </summary> public bool IsCompleted { get; set; } public bool IsPaused { get; set; } public Timer(float duration, bool isLoop, Action completed, Action<float, float> process, float stride) { m_Duration = duration; m_IsLoop = isLoop; m_CallbackCompleted = completed; m_CallbackProcess = process; m_Stride = stride; m_IsPaused = false; m_IsFirstTikTok = false; m_RemainingTime = duration; } public static Timer Create(float duration, Action completed) { return new Timer(duration, false, completed, null, 1f); } public static Timer Create(float duration, Action completed, Action<float, float> process) { return new Timer(duration, false, completed, process, 1f); } public static Timer Create(float duration, bool isLoop, Action<float, float> process) { return new Timer(duration, isLoop, null, process, 1f); } public static Timer Create(float duration, bool isLoop, Action completed, Action<float, float> process) { return new Timer(duration, isLoop, completed, process, 1f); } public static Timer Create(float duration, bool isLoop, Action<float, float> process, float stride) { return new Timer(duration, isLoop, null, process, stride); } public static Timer Create(float duration, bool isLoop, Action completed, Action<float, float> process, float stride) { return new Timer(duration, isLoop, completed, process, stride); } public void Update() { if (m_IsFirstTikTok == false) { m_IsFirstTikTok = true; m_CurrentElapsedTime = 0f; } else { m_CurrentElapsedTime += Time.deltaTime; if (m_CurrentElapsedTime >= m_Stride) { m_RemainingTime -= m_Stride; m_CurrentElapsedTime -= m_Stride; m_TotalElapsedTime += m_Stride; m_CallbackProcess?.Invoke(m_RemainingTime, m_TotalElapsedTime); } if (m_RemainingTime <= 0.005f) { if (m_IsLoop) { m_RemainingTime = m_Duration; } else { IsCompleted = true; m_CallbackCompleted?.Invoke(); } } } } public void Pause() { m_IsPaused = true; } public void Resume() { m_IsPaused = false; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Boking { public class Model : IEventProtocol { private readonly EventProtocol m_Event = new EventProtocol(); public void AddEvent(int key, EventListener listener) { m_Event.AddEvent(key, listener); } public void RemoveEvent(int key) { m_Event.RemoveEvent(key); } public void RemoveEvent(int key, EventListener listener) { m_Event.RemoveEvent(key, listener); } public void DispatchEvent(int key, params object[] args) { m_Event.DispatchEvent(key, args); } } } <file_sep>using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Boking { public interface ISingleton { void Init(); } public abstract class Singleton<T> : ISingleton where T : Singleton<T> { protected static T s_Instance; private static readonly object s_Lock = new object(); public static T Instance { get { lock(s_Lock) { if (s_Instance == null) { s_Instance = CreateSingleton<T>(); } } return s_Instance; } } private static X CreateSingleton<X>() where X : class, ISingleton { var ctors = typeof(X).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic); var ctor = Array.Find(ctors, c => c.GetParameters().Length == 0); if (ctor == null) { throw new Exception("Non-Public Constructor() not found! in " + typeof(X)); } var instance = ctor.Invoke(null) as X; instance.Init(); return instance; } public virtual void Dispose() { s_Instance = null; } public virtual void Init() { } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Boking { public class ControllerManager : MonoSingleton<ControllerManager> { public Dictionary<string, DialogController> m_DialogControllers = new Dictionary<string, DialogController>(); public Dictionary<string, ViewController> m_ViewControllers = new Dictionary<string, ViewController>(); /// <summary> /// 注册弹窗Controller /// </summary> public void Register(string controllerName, DialogController controller) { m_DialogControllers.Add(controllerName, controller); } /// <summary> /// 注册视图Controller /// </summary> public void Register(string controllerName, ViewController controller) { m_ViewControllers.Add(controllerName, controller); } public bool GetDialogController(string controllerName, out DialogController controller) { return m_DialogControllers.TryGetValue(controllerName, out controller); } public bool GetViewController(string controllerName, out ViewController controller) { return m_ViewControllers.TryGetValue(controllerName, out controller); } public void Show(string controllerName) { } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour, new() { public static T s_Instance; /// <summary> /// 获取实例对象 /// </summary> public static T Instance { get { if (s_Instance == null) { s_Instance = new T(); } return s_Instance; } } /// <summary> /// 初始化方法 /// </summary> public virtual void Init() { } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Boking { public class DialogManager : Singleton<DialogManager> { private Dictionary<string, DialogController> m_ControllerDict = new Dictionary<string, DialogController>(); private List<DialogParams> m_WaittingList = new List<DialogParams>(); private List<Dialog> m_ShowingList = new List<Dialog>(); private DialogStatus m_DialogStatus; private bool m_IsDelayingPrepare; public bool IsUpwardEnabled { get; set; } // 是否可以执行上拉操作 private DialogManager() { } public override void Init() { } private void Register<T>(string controllerName) where T : DialogController, new() { if (!m_ControllerDict.ContainsKey(controllerName)) { m_ControllerDict.Add(controllerName, new T()); } } public bool GetController(string controllerName, out DialogController controller) { return m_ControllerDict.TryGetValue(controllerName, out controller); } public bool GetDialog(int id, out Dialog dialog) { foreach(Dialog d in m_ShowingList) { if (d.Id == id) { dialog = d; return true; } } dialog = null; return false; } public bool GetDialog(string alias, out Dialog dialog) { foreach (Dialog d in m_ShowingList) { if (d.Alias == alias) { dialog = d; return true; } } dialog = null; return false; } /// <summary> /// 把需要打开的弹窗的数据放入m_WaittingList中 /// </summary> /// <param name="args">弹窗数据</param> /// <param name="index">插入的编号,默认插入最前面</param> /// <returns></returns> public int Push(ref DialogParams args, int index = 1) { // 判断数据是否有误 if (args.DialogClassName == "" || args.DialogPrefabPath == "") { return -1; } if (index >= 0 && index < m_WaittingList.Count) { m_WaittingList.Insert(index, args); } else { m_WaittingList.Add(args); } return args.Id; } /// <summary> /// 检查是否可以打开下一个弹窗 /// </summary> /// <param name="stay"></param> /// <returns></returns> public bool CanPop(bool stay) { if (m_WaittingList.Count <= 0) { return false; } else if (m_ShowingList.Count > 0) { Dialog dialog = m_ShowingList[0]; if (stay) { if (dialog.IsActived) { return false; } } if (dialog.IsActived && dialog.IsTop) { if (!m_WaittingList[0].IsTop) { return false; } } } return true; } /// <summary> /// 打开m_WaittingList中第一个弹窗并打开 /// </summary> /// <param name="stay">是否需要延迟打开</param> public void Pop(bool stay = false) { if (CanPop(stay)) { DialogParams dialogParams = m_WaittingList[0]; m_WaittingList.RemoveAt(0); if (dialogParams.ShowType == DialogShowType.NORMAL) { Hide(ref dialogParams); Unique(ref dialogParams); Show(ref dialogParams); } else if (dialogParams.ShowType == DialogShowType.EVENT) { // 派发事件通知可以打开此弹窗了 } } } private void Hide(ref DialogParams dialogParams) { if (m_ShowingList.Count > 0) { Dialog dialog = m_ShowingList[m_ShowingList.Count - 1]; if (!dialog.IsAlwaysShow) { dialog.Hide(); } } } private void Unique(ref DialogParams dialogParams) { if (m_ShowingList.Count > 0) { for (int i = 0; i < m_ShowingList.Count; i++) { if (m_ShowingList[i].DialogClassName == dialogParams.DialogClassName && dialogParams.IsUnique) { // 移除此弹窗,序号i m_ShowingList.RemoveAt(i); i--; } } } } private void Show(ref DialogParams dialogParams) { GameObject gameObject = UnityEngine.Object.Instantiate(new GameObject()); Type type = Type.GetType("Boking." + dialogParams.DialogClassName); Dialog dialog = gameObject.GetComponent(type) as Dialog; if (dialog == null) { dialog = gameObject.AddComponent(type) as Dialog; } m_ShowingList.Add(dialog); dialog.RequestData(); dialog.Show(); } /// <summary> /// 移除一个弹窗 /// </summary> /// <param name="id"></param> private void RemoveOne(int id) { for (int i = 0; i < m_ShowingList.Count; i++) { if (m_ShowingList[i].Id == id) { m_ShowingList[i].Remove(); m_ShowingList.RemoveAt(i); return; } } } /// <summary> /// 移除一组弹窗 /// </summary> /// <param name="idList"></param> public void Remove(params int[] idList) { for (int i = 0; i < idList.Length; i++) { RemoveOne(idList[i]); } Check(); } /// <summary> /// 移除所有弹窗,除了id /// </summary> public void Clear(int id = -1) { m_WaittingList.Clear(); for (int i = 0; i < m_ShowingList.Count; i++) { if (id == -1 || id != m_ShowingList[i].Id) { m_ShowingList[i].Remove(); m_ShowingList.RemoveAt(i); i--; } } m_ShowingList.Clear(); RemoveBackgroundIfNoDialog(); } private void Check() { if (m_ShowingList.Count > 0 && m_ShowingList[m_ShowingList.Count - 1].IsTop) { m_ShowingList[m_ShowingList.Count - 1].Display(); } else if (m_WaittingList.Count > 0 && m_WaittingList[0].IsPrior) { Prepare(); } else if (m_ShowingList.Count > 0) { m_ShowingList[m_ShowingList.Count - 1].Display(); } else if (m_WaittingList.Count > 0) { Prepare(); } else { RemoveBackgroundIfNoDialog(); } } private void Prepare() { if (m_IsDelayingPrepare) { return; } m_IsDelayingPrepare = true; TimerManager.Instance.Delay(0, () => { m_IsDelayingPrepare = false; Pop(); }); } private void RemoveBackgroundIfNoDialog() { } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Boking { public class CacheManager : Singleton<CacheManager> { private readonly Dictionary<int, object> m_Cache = new Dictionary<int, object>(); private CacheManager() { } public T Get<T>(int key) { m_Cache.TryGetValue(key, out object value); return (T)value; } public void Set<T>(int key, T value) { m_Cache.Add(key, value); } } } <file_sep>using System; using System.Collections.Generic; namespace Boking { public delegate void EventListener(params object[] args); public interface IEventProtocol { void AddEvent(int key, EventListener listener); void RemoveEvent(int key); void RemoveEvent(int key, EventListener listener); void DispatchEvent(int key, params object[] args); } public class EventProtocol : IEventProtocol { private class ListenerWrapper { private readonly List<EventListener> m_ListenerList = new List<EventListener>(); public int Key { get; } public ListenerWrapper(int key) { Key = key; } public void Add(EventListener listener) { m_ListenerList.Add(listener); } public void Remove(EventListener listener) { m_ListenerList.Remove(listener); } public void Dispatch(params object[] args) { foreach(EventListener listener in m_ListenerList) { listener(args); } } } private readonly Dictionary<int, ListenerWrapper> m_EventDict = new Dictionary<int, ListenerWrapper>(); public void AddEvent(int key, EventListener listener) { if (!m_EventDict.TryGetValue(key, out ListenerWrapper wrapper)) { wrapper = new ListenerWrapper(key); m_EventDict.Add(key, wrapper); } wrapper.Add(listener); } public void RemoveEvent(int key) { m_EventDict.Remove(key); } public void RemoveEvent(int key, EventListener listener) { if (m_EventDict.TryGetValue(key, out ListenerWrapper wrapper)) { wrapper.Remove(listener); } } public void DispatchEvent(int key, params object[] args) { if (m_EventDict.TryGetValue(key, out ListenerWrapper wrapper)) { wrapper.Dispatch(args); } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Boking { public class TimerManager : Singleton<TimerManager> { private static int s_TimerId; /// <summary> /// Timer字典 /// </summary> private Dictionary<int, Timer> m_TimerDict = new Dictionary<int, Timer>(); /// <summary> /// 将要删除的Timer Id列表 /// </summary> private List<int> m_RemovingTimerIdList = new List<int>(); private Dictionary<int, MonoBehaviour> m_TimerBehaviourDict = new Dictionary<int, MonoBehaviour>(); private int TimerId => s_TimerId++; private TimerManager() { } /// <summary> /// 倒计时 /// </summary> /// <param name="duration">需要倒计时的时间</param> /// <param name="completed">倒计时完成时的回调</param> /// <returns></returns> public int Delay(float duration, Action completed) { Timer timer = Timer.Create(duration, completed); return Register(timer); } /// <summary> /// 倒计时,每次步进均有回调 /// </summary> /// <param name="duration">需要倒计时的时间</param> /// <param name="completed">倒计时完成时的回调</param> /// <param name="process">每次步进的回调</param> /// <returns></returns> public int Clock(float duration, Action completed, Action<float, float> process) { Timer timer = Timer.Create(duration, false, completed, process); return Register(timer); } /// <summary> /// 无限循环的倒计时 /// </summary> /// <param name="duration">每隔这么时间步进一次</param> /// <param name="process">每次步进的回调</param> /// <returns></returns> public int Loop(float duration, Action<float, float> process) { Timer timer = Timer.Create(duration, true, process, duration); return Register(timer); } private int Register(Timer timer) { int id = TimerId; m_TimerDict.Add(id, timer); return id; } public void Update() { m_RemovingTimerIdList.Clear(); foreach(KeyValuePair<int, Timer> vk in m_TimerDict) { if (vk.Value.IsCompleted) { m_RemovingTimerIdList.Add(vk.Key); } else if (vk.Value.IsPaused) { // 被暂停了 } else { vk.Value.Update(); } } foreach(int id in m_RemovingTimerIdList) { Remove(id); } } public void Pause(int id) { if (m_TimerDict.TryGetValue(id, out Timer timer)) { timer.Pause(); } } public void Resume(int id) { if (m_TimerDict.TryGetValue(id, out Timer timer)) { timer.Resume(); } } /// <summary> /// 移除一个倒计时 /// </summary> /// <param name="id"></param> public void Remove(int id) { m_TimerDict.Remove(id); m_TimerBehaviourDict.Remove(id); } /// <summary> /// 把定时器与一个脚本绑定在一起 /// </summary> /// <param name="id"></param> /// <param name="behavior"></param> public void Bind(int id, MonoBehaviour behavior) { m_TimerBehaviourDict.Add(id, behavior); } public void Adjust() { } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Boking { public enum DialogActionType { NONE, // 无 SCALE, // 缩放 POSITION // 从指定位置缩放弹出 } public enum DialogShowType { NORMAL, // 正常打开弹窗 EVENT // 需要派发事件,由监听方再次判定是否需要打开弹窗 } public enum DialogStatus { NORMAL, // 正常状态 UPWARD // 上拉状态 } public delegate void DialogCompletedCallback(); public class DialogParams { private static int s_DialogId; private static int DialogId => s_DialogId++; public int Id { get; set; } public string Alias { get; set; } /// <summary> /// 弹窗打开类型为指定位置缩放打开时,指定的起始位置 /// </summary> public Vector2 InitialPosition { get; set; } /// <summary> /// 正常位置,默认屏幕中心 /// </summary> public Vector2 NormalPosition { get; set; } /// <summary> /// 弹窗创建时,传入的参数 /// </summary> public object InitialParams { get; set; } /// <summary> /// 执行进入动画的类型 /// </summary> public DialogActionType EnterActionType { get; set; } /// <summary> /// 执行退出动画的类型 /// </summary> public DialogActionType ExitActionType { get; set; } /// <summary> /// 显示弹窗时,需要怎么做? /// </summary> public DialogShowType ShowType { get; set; } /// <summary> /// 此弹窗是否保持在最上层 /// 如果有两个弹窗同时声明,则后来者居上 /// </summary> public bool IsTop { get; set; } /// <summary> /// 此弹窗是否一直显示 /// </summary> public bool IsAlwaysShow { get; set; } /// <summary> /// 此弹窗是否被锁定了,如果是,则不能进行其他操作,比如上拉弹窗层 /// </summary> public bool IsLocked { get; set; } /// <summary> /// 此弹窗是否唯一 /// </summary> public bool IsUnique { get; set; } /// <summary> /// 此弹窗是否需要从服务器请求数据 /// </summary> public bool IsNeedRequestData { get; set; } /// <summary> /// 是否优先显示此弹窗(是否比隐藏的弹窗更优先弹出) /// </summary> public bool IsPrior { get; set; } /// <summary> /// 弹窗视图脚本的类名 /// </summary> public string DialogClassName { get; set; } /// <summary> /// 此弹窗所使用的预制体Prefab /// </summary> public string DialogPrefabPath { get; set; } /// <summary> /// 弹窗进入动画完成回调 /// </summary> public DialogCompletedCallback ShowCompletedCallback; public DialogParams() { Id = DialogId; Alias = "__Unkown__"; InitialPosition = new Vector2(); NormalPosition = new Vector2(); InitialParams = null; EnterActionType = DialogActionType.NONE; ExitActionType = DialogActionType.NONE; ShowType = DialogShowType.NORMAL; IsTop = false; IsAlwaysShow = false; IsLocked = false; IsUnique = true; IsNeedRequestData = true; IsPrior = false; DialogClassName = ""; DialogPrefabPath = ""; ShowCompletedCallback = null; } } public class Dialog : MonoBehaviour { private DialogCompletedCallback CloseCompletedCallback; /// <summary> /// 标记是否正在执行进入或退出动作 /// </summary> private bool m_IsActing; /// <summary> /// 弹窗进入的过渡动画完成 /// </summary> private bool m_IsEnterCompleted; /// <summary> /// 是否存在背景 /// </summary> private bool m_IsHasBackgroud; /// <summary> /// 此弹窗服务器数据是否请求完成(是否有回包) /// </summary> public bool m_IsDataLoadingCompleted; private DialogParams m_DialogParams; /// <summary> /// 此弹窗相关的Controller /// </summary> public DialogController Controller { get { DialogManager.Instance.GetController(ControllerName, out DialogController controller); return controller; } } public int Id { get => m_DialogParams.Id; } public string Alias { get => m_DialogParams.Alias; } public bool IsTop { get => m_DialogParams.IsTop; } public bool IsUnique { get => m_DialogParams.IsUnique; } public bool IsLock { get => m_DialogParams.IsLocked; } public bool IsAlwaysShow { get => m_DialogParams.IsAlwaysShow; } public string DialogClassName { get => m_DialogParams.DialogClassName; } /// <summary> /// 此弹窗相关的Controller的Name /// </summary> private string ControllerName { get; set; } private void Awake() { m_IsActing = false; m_IsEnterCompleted = false; m_IsHasBackgroud = false; m_IsDataLoadingCompleted = false; } private void Start() { InitData(); InitUI(); InitInternationalLanguageUI(); } /// <summary> /// 获取激活状态 /// </summary> public bool IsActived => gameObject.activeSelf; /// <summary> /// 设置弹窗打开时的外部传进来的参数 /// </summary> /// <param name="dialogParams"></param> public void SetShowParams(ref DialogParams dialogParams) { m_DialogParams = dialogParams; } /// <summary> /// 初始化数据 /// 继承者根据自己的业务逻辑,完成此接口 /// </summary> private void InitData() { } /// <summary> /// 初始化UI /// 继承者需要在此接口中完成所有UI的引用赋值 /// </summary> private void InitUI() { } /// <summary> /// 初始化国际化语言 /// </summary> public void InitInternationalLanguageUI() { } /// <summary> /// 初始化点击事件、滑动事件、触摸事件 /// </summary> private void InitClick() { } /// <summary> /// 进入动作开始 /// </summary> private void OnEnterActionStart() { m_IsActing = true; m_IsEnterCompleted = false; } /// <summary> /// 进入动作完成 /// </summary> private void OnEnterActionCompleted() { m_IsActing = false; m_IsEnterCompleted = true; SetNormalStatus(); InitClick(); if (m_IsDataLoadingCompleted) { UpdateUI(); } m_DialogParams.ShowCompletedCallback?.Invoke(); } private void StartEnterAction() { OnEnterActionStart(); if (m_DialogParams.EnterActionType == DialogActionType.SCALE) { StartScaleEnterAction(); } else if (m_DialogParams.EnterActionType == DialogActionType.POSITION) { StartPositionEnterAction(); } else { OnEnterActionCompleted(); } } private void StartScaleEnterAction() { OnEnterActionCompleted(); } private void StartPositionEnterAction() { OnEnterActionCompleted(); } private void OnExitActionStart() { m_IsActing = true; } /// <summary> /// 退出动作完成 /// </summary> private void OnExitActionCompleted() { CloseCompletedCallback?.Invoke(); CloseCompletedCallback = null; } private void StartExitAction() { OnExitActionStart(); if (m_DialogParams.ExitActionType == DialogActionType.SCALE) { StartScaleExitAction(); } else { OnExitActionCompleted(); } } private void StartScaleExitAction() { OnExitActionCompleted(); } /// <summary> /// 设置弹窗进入正常状态 /// </summary> private void SetNormalStatus() { } /// <summary> /// 数据请求完成并回包 /// </summary> public void OnDataLoadingCompleted() { m_IsDataLoadingCompleted = true; if (m_IsEnterCompleted) { UpdateUI(); } } /// <summary> /// 请求此界面的服务器数据 /// </summary> public void RequestData() { } /// <summary> /// 更新界面UI /// </summary> public void UpdateUI() { } /// <summary> /// 打开此界面 /// </summary> public void Show() { StartEnterAction(); } /// <summary> /// 直接显示此界面 /// 用于隐藏界面后重新显示界面 /// </summary> public void Display() { SetNormalStatus(); gameObject.SetActive(true); } /// <summary> /// 关闭此界面 /// </summary> public void Close(DialogCompletedCallback callback) { CloseCompletedCallback = callback; StartExitAction(); } /// <summary> /// 关闭此界面 /// </summary> public void Close() { StartExitAction(); } /// <summary> /// 隐藏此界面 /// 如果被隱藏時有被打開的動作,則先停止,並設置爲正常模式,執行完成回調 /// </summary> public void Hide() { gameObject.SetActive(false); } /// <summary> /// 移除此界面 /// </summary> public void Remove() { Destroy(gameObject); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Boking { public class Main : MonoBehaviour { public GameObject m_ObjView; public GameObject m_ObjDialog; public GameObject m_ObjGlobal; public Text m_LblCountDown; public Text m_LblClock; public Text m_LblLoop; // Start is called before the first frame update void Start() { Text lblCountDown = m_LblCountDown.GetComponent<Text>(); lblCountDown.text = ""; TimerManager.Instance.Delay(5f, () => { lblCountDown.text = "Delay-Completed"; }); Text lblClock = m_LblClock.GetComponent<Text>(); lblClock.text = ""; TimerManager.Instance.Clock(10f, () => { lblClock.text = "Clock-Completed"; }, (remainTime, elapsedTime) => { lblClock.text = remainTime.ToString(); }); Text lblLoop = m_LblLoop.GetComponent<Text>(); lblLoop.text = ""; TimerManager.Instance.Loop(1.0f, (remainTime, elapsedTime) => { lblLoop.text = "Loop - " + elapsedTime.ToString(); }); CacheManager.Instance.Set<int>(1, 2); CacheManager.Instance.Set<int>(2, 10); CacheManager.Instance.Set<string>(3, "v1"); print(CacheManager.Instance.Get<int>(1)); print(CacheManager.Instance.Get<int>(2)); print(CacheManager.Instance.Get<string>(3)); EventManager.Instance.AddEvent(1, UpdateEvent); EventManager.Instance.AddEvent(1, UpdateEvent2); EventManager.Instance.DispatchEvent(1); EventManager.Instance.RemoveEvent(1, UpdateEvent); EventManager.Instance.DispatchEvent(1); } public void UpdateEvent(params object[] args) { print("==UpdateEvent=="); } public void UpdateEvent2(params object[] args) { print("==UpdateEvent2=="); } // Update is called once per frame void Update() { TimerManager.Instance.Update(); } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Boking { public class View : MonoBehaviour { private bool m_NeedRefreshUI; // 标记是否需要刷新UI private bool m_RefreshedUI; // 标记UI是否已经刷新过 private bool m_IsTransitionCompleted; // 过渡动画是否已经完成 public ViewController m_Controller; public string ClassName { get => "View"; } public void Remove() { Destroy(gameObject); } public void SetActive(bool active) { gameObject.SetActive(active); } public void SetController(ViewController controller) { m_Controller = controller; } public void Awake() { m_RefreshedUI = false; m_NeedRefreshUI = false; m_IsTransitionCompleted = false; } public void Start() { InitUI(); InitInternationalLanguageUI(); InitClick(); InitChildListen(); } /// <summary> /// 初始化视图 /// </summary> /// <param name="args"></param> public void Init(object args) { } /// <summary> /// 重新对此视图进行初始化 /// </summary> /// <param name="args"></param> public void Reinit(object args) { m_RefreshedUI = false; m_NeedRefreshUI = false; m_IsTransitionCompleted = false; } /// <summary> /// 初始化UI /// </summary> public void InitUI() { } /// <summary> /// 初始化国际化语言 /// </summary> public void InitInternationalLanguageUI() { } /// <summary> /// 初始化事件点击 /// </summary> public void InitClick() { } /// <summary> /// 初始化对子节点的事件监听 /// </summary> public void InitChildListen() { } /// <summary> /// 执行过渡动画 /// </summary> public void Transition() { OnTransitionCompleted(); } /// <summary> /// 过渡动画完成之后调用,如果完成后,服务器已经回包了,则直接刷新 /// </summary> public void OnTransitionCompleted() { m_IsTransitionCompleted = true; if (m_NeedRefreshUI) { RefreshView(); } } public bool CheckTransitionCompleted() { return m_IsTransitionCompleted; } /// <summary> /// 服务器回包,Controller中调用刷新View /// 如果过渡动画还没结束,则不刷新UI,在调用之前需要检查过渡动画是否完成 /// </summary> public void RefreshView() { m_NeedRefreshUI = true; if (!CheckTransitionCompleted()) { return; } RefreshUI(); m_NeedRefreshUI = false; m_RefreshedUI = true; } /// <summary> /// 刷新界面UI /// </summary> public void RefreshUI() { } } }
28edd4715ab0542ca53ec84cf3602c8d02e9d4af
[ "C#" ]
15
C#
bokingtomas/BokingUnity3D
6ed60f2a4bf7534183acb40372d9c88719461134
b4e3291c213357d3264528e1b22a23d80907f73c
refs/heads/master
<repo_name>marmibv/bitbot_binance_price-fluctuations-Noise<file_sep>/README.md # Bitbot Binance This program is Cryptocurrency trading bot for Binance. Written in Javascript , running on NodeJS. ### Installation ``` git clone https://github.com/indy99/bitbot_binance (if you don't have "git" download and extarct) cd bitbot_binance npm install ``` Installation is done. ### Configure first Signup Binance ( Referral url: https://www.binance.com/?ref=16102823 )<br> Go to API Setting, Crete new key<br> 'config/config.json' -> enter your Binance APIKEY and APISECRET 'config/exchange.json' -> enter your exchange parameters Note: a- This version makes order fee with BNB to less fee. So get some BNB before you trade. And activate this option from your Binance account: ``` Using BNB to pay for fees(50% discount)-> make ON ``` b- There is no limit amount for now, so uses all your balance when making ORDER! *** Then to run ``` node bitbot.js ``` Web GUI -> Browse http://127.0.0.1:8088/ ### Notes for more info: https://kartimbu.com/bitbot/ Pro version is here : https://bitbot.kartimbu.com/ ### Thank You Thanks jaggedsoft for repo: https://github.com/jaggedsoft/node-binance-api *** If you like this bot you can send some coins <a href="https://kartimbu.com/pay-acik.php" target="_blank">here</a> to developing the project. <file_sep>/files/funcs_bitbot.js const bitbot = require('../bitbot'); const bnc=bitbot.binance; //const bnc = require('node-binance-api'); module.exports = { html_parse: function (x) { var ret = []; var i = x.indexOf('/*'); ret[0] = x.substring(0, i); ret[1] = x.substring(i + 4); return ret; }, b_options: function (k, s, t, flog) { bnc.options({ APIKEY: k, APISECRET: s, useServerTime: true, test: t, log: log => { flog(log); } }); }, getCurrNames: function(CURR){ var cr= []; var first, last; if (CURR.substr(CURR.length-4) == "USDT") last=4; else last=3; first=CURR.length-last; cr[0]= CURR.substr(0, first); cr[1] = CURR.substr(first); cr[2] = "BNB"; return cr; }, getBalance: function (CURR, x, callback) { let str=this.getCurrNames(CURR)[x]; var bal = -1; bnc.balance((error, balances) => { if (error) { callback(1, str + " get balance error !: "+error.body); return; } for (var key in balances) { if (JSON.stringify(key) == JSON.stringify(str)) { bal = balances[key].available; break; } } if (bal == -1) callback(1, str + " currency is not available !"); else callback(0, bal); }); }, b_candlesticks: function (CURR, callback) { // Periods: 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M bnc.candlesticks(CURR, "5m", (error, ticks, symbol) => { if (error) { callback(1, "candlesticks error!"); return; } //console.log("candlesticks()", ticks); let last_tick = ticks[ticks.length - 1]; let [time, open, high, low, close, volume, closeTime, assetVolume, trades, buyBaseVolume, buyAssetVolume, ignored] = last_tick; //console.log(symbol + " last close: " + close); callback(0); }); } }; <file_sep>/start.sh #!/bin/bash app="bitbot" prg="node bitbot.js 0" log="/tmp/bitbot_crash.log" stopfile="/tmp/bitbotstop" if pgrep -f 'node bitbot.js' > /dev/null; then echo "Program is already running"; exit 0; fi ( rm -f $stopfile while [ 1 ] do d=$(date +"%d%m%y:%H%M%S") echo "$d > $app starting ... " >> $log $prg ret=$? d=$(date +"%d%m%y:%H%M%S") if [ $ret -eq 11 ]; then echo "$d > $app config orr api key fail " >> $log break fi if [ -f $stopfile ]; then echo "$d > $app stopped manually " >> $log break fi echo "$d > $app exit code $ret. Respawning... " >> $log sleep 10 done ) & <file_sep>/bitbot.js try {const check = require('syntax-error');} catch (ex){} const binance = require('node-binance-api'); const minimums = require('./files/minimums.json'); const package = require('./package.json'); var fs = require("fs"); var configfile="./config/exchange.json"; var keyfile="./config/config.json"; module.exports = { binance } const fbb = require('./files/funcs_bitbot.js'); const is_order = 1; //test var is_printon = 1; //test //const api_order_test=true; //test const api_order_test=false; const buy = 1; const sell = 2; //********************* //const CURR = "BNBBTC"; var CURR; //var exchange_fee = 0.05 + 0.05; //no bnb var exchange_fee = 0; //enable bnb var virgul = 3; //amount after point var virgul_price = 3; var proggress = 0; var alimvalue = 0; var satimvalue = 0; /* var proggress = sell; var alimvalue = 0.00050700; var satimvalue = 0; */ const LIMIT_SAY_MAX = 3; const LIMITALT_SAY_MAX = 3; var NOISE = 0.1; //noise yuzde var KAR = 0 //kar yuzde configten //********************* var balance1, balance2, balance_bnb; var limit_say = 0; var limitalt_say = 0; var limit_ust = 0; var value_buy, value_sell = 0; var orderid = 0; var count = 0; var to_server; var log_sonsatir; var log_sonsatir_err = ""; var log_sonsatir_opt = ""; var wait_order = 0; var fark_yuzde; var config; var config_curr; var main_config; var web_str = []; var teststr=""; var is_check_order_balance=true; const console_cl_red="\x1b[41m"; const console_cl_green="\x1b[42m"; const console_cl_res="\x1b[0m"; var order_paused=false; function b_depthCache() { // Maintain Market Depth Cache Locally via WebSocket binance.websockets.depthCache([CURR], function (symbol, depth) { let max = 2; // Only show closest 10 bids/asks let bids = binance.sortBids(depth.bids, max); let asks = binance.sortAsks(depth.asks, max); console.log(symbol + " depth cache update"); console.log("asks", asks); console.log("bids", bids); console.log("best ask: " + binance.first(asks)); console.log("best bid: " + binance.first(bids)); value_buy = binance.first(asks); value_sell = binance.first(bids); main(); }); } function main() { if (!(count%30)) { getbalances(); if (!(is_check_order_balance=check_order_balance()) ) console.log(console_cl_red,"\n****************Your balance is not enough to ORDER!*************\n",console_cl_res); } if (!(count%3600)) { binance.useServerTime(()=>{ console.log(console_cl_green,"**** Server time synchronized *****",console_cl_res); }) } if (order_paused) console.log(console_cl_red,"**** ORDERS PAUSED *****",console_cl_res); if (proggress == sell) { if ((alimvalue == 0) && (satimvalue == 0)) alimvalue = value_buy; fark_yuzde = ((value_sell - alimvalue) / alimvalue).toFixedNR(8); to_server = teststr+CURR + ": SELL, peak:" + limit_ust + ", val: " + value_sell + ", val last buy: " + alimvalue + " <br> profit: " + fark_yuzde + ", bal1: " + balance1 + ", bal2: " + balance2 + " ++" + count++; console.log(to_server); if (value_sell > limit_ust) { limit_say++; if (limit_say > LIMIT_SAY_MAX) { limit_say = 0; limit_ust = value_sell; console.log("peak = " + limit_ust); } } else limit_say = 0; if (value_sell < limit_ust) { var yuzdenoise = limit_ust * NOISE / 100; var yuzdelimit = parseFloat(limit_ust) - parseFloat(yuzdenoise); if (value_sell > yuzdelimit) { console.log("Noise : " + yuzdelimit.toFixedNR(8)); limitalt_say = 0; return; } limitalt_say++; console.log("peak_count: " + limitalt_say); if (limitalt_say > LIMITALT_SAY_MAX) { limitalt_say = 0; var karyuzde = alimvalue * KAR / 100; if (value_sell < (parseFloat(alimvalue) + parseFloat(karyuzde))) { console.log("Sell profit is low : " + fark_yuzde); return; } satisemri(value_sell); } } } else if (proggress == buy) { if ((alimvalue == 0) && (satimvalue == 0)) satimvalue = value_sell; if (limit_ust == 0) limit_ust = value_buy; fark_yuzde = (1 - (value_buy / satimvalue)).toFixedNR(8); to_server = teststr+CURR + ": BUY, peak:" + limit_ust + ", val: " + value_buy + ", val last sell: " + satimvalue + " <br> profit: " + fark_yuzde + ", bal1: " + balance1 + ", bal2: " + balance2 + " ++" + count++; console.log(to_server); if (value_buy < limit_ust) { limit_say++; if (limit_say > LIMIT_SAY_MAX) { limit_say = 0; limit_ust = value_buy; console.log("peak = " + limit_ust); } } else limit_say = 0; if (value_buy > limit_ust) { var yuzdenoise = limit_ust * NOISE / 100; var yuzdelimit = parseFloat(limit_ust) + parseFloat(yuzdenoise); if (value_buy < yuzdelimit) { console.log("Noise : " + yuzdelimit.toFixedNR(8)); limitalt_say = 0; return; } limitalt_say++; console.log("peak_count: " + limitalt_say); if (limitalt_say > LIMITALT_SAY_MAX) { limitalt_say = 0; var karyuzde = satimvalue * KAR / 100; if (value_buy > (satimvalue - karyuzde)) { console.log("Buy profit is low : " + fark_yuzde); return; } alisemri(value_buy); } } } else { log_sonsatir_err = CURR + ": ORDER WAITING ++" + count++; console.log(log_sonsatir_err); if (is_order == 1) { if (wait_order == 1) return; wait_order = 1; //binance.orderStatus(CURR, orderid, function (orderStatus, symbol) { binance.orderStatus(CURR, orderid, (error, orderStatus, symbol) => { if (error) {logD("Order status Error:\n"+error.body,1); return; } console.log(symbol + " order status:" + JSON.stringify(orderStatus)); if (orderStatus.status == "FILLED") { logD("Order FILLED", 1); if (alimvalue == 0) { proggress = buy; config.proggress = "buy"; config.sellvalue = parseFloat(satimvalue); writeconfigfile(); getbalances(); } else if (satimvalue == 0) { proggress = sell; config.proggress = "sell"; config.buyvalue = parseFloat(alimvalue); writeconfigfile(); getbalances(); } } wait_order = 0; }); } else { if (alimvalue == 0) { proggress = buy; config.proggress = "buy"; config.sellvalue = parseFloat(satimvalue); writeconfigfile(); getbalances(); } else if (satimvalue == 0) { proggress = sell; config.proggress = "sell"; config.buyvalue = parseFloat(alimvalue); writeconfigfile(); getbalances(); } } } } function satisemri(val) { if (!is_check_order_balance) {console.log(console_cl_red,"SELL ORDER:Balance not enough, cancelled!",console_cl_res); return;} if (order_paused) {console.log(console_cl_red,"ORDERS PAUSED!",console_cl_res); return;} proggress = 0; satimvalue = parseFloat(val).toFixedNR(virgul_price); var quantity = ((balance1 - (balance1 * exchange_fee / 100))).toFixedNR(virgul); var str = "Entering SELL order, buy_value: " + alimvalue + ", sell_value: " + val + ", order: " + satimvalue + ", quantity: " + quantity + ", profit : " + ((val - alimvalue) / alimvalue); console.log(str); logD(str, 0); alimvalue = 0; limit_ust = 0; if (is_order == 1) { wait_order = 1; binance.sell(CURR, parseFloat(quantity), parseFloat(satimvalue), {type:'LIMIT'}, (error, response) => { if (error) { logD("Sell Order error:\n" + error.body, 1,()=>{ exit_program(1); }); return; } console.log("Limit Sell response", JSON.stringify(response)); if (response.orderId === undefined) { logD("Sell Order error1:\n" + JSON.stringify(response), 1,()=>{ exit_program(2); }); } else { orderid = response.orderId; wait_order = 0; } }); } } function alisemri(val) { if (!is_check_order_balance) {console.log(console_cl_red,"BUY ORDER:Balance not enough, cancelled!",console_cl_res); return;} if (order_paused) {console.log(console_cl_red,"ORDERS PAUSED!",console_cl_res); return;} proggress = 0; alimvalue = parseFloat(val).toFixedNR(virgul_price); var quantity = ((balance2 - (balance2 * exchange_fee / 100)) / alimvalue).toFixedNR(virgul); var str = "Entering BUY order, sell_value: " + satimvalue + ", buy_value: " + val + ", order: " + alimvalue + ", quantity: " + quantity + ", profit : " + (1 - (alimvalue / satimvalue)); console.log(str); logD(str, 0); satimvalue = 0; limit_ust = 0; if (is_order == 1) { wait_order = 1; binance.buy(CURR, parseFloat(quantity), parseFloat(alimvalue), {type:'LIMIT'}, (error, response) => { if (error) { logD("Buy Order error:\n" + error.body, 1,()=>{ exit_program(3); }); return; } console.log("Limit Buy response", JSON.stringify(response)); if (response.orderId === undefined) { logD("Buy Order error1:\n" + JSON.stringify(response), 1,()=>{ exit_program(4); }); } else { orderid = response.orderId; wait_order = 0; } }); } } function check_order_balance(){ if (proggress==sell) { var sv = parseFloat(value_sell).toFixedNR(virgul_price); var sq = ((balance1 - (balance1 * exchange_fee / 100))).toFixedNR(virgul); if ((sv*sq) < minimums[CURR].minNotional) { console.log(console_cl_red,"sell value: "+sv*sq+" < "+minimums[CURR].minNotional,console_cl_res); return false; } } else if (proggress==buy) { var av = parseFloat(value_buy).toFixedNR(virgul_price); var aq = ((balance2 - (balance2 * exchange_fee / 100)) / av).toFixedNR(virgul); if ((av*aq) < minimums[CURR].minNotional) { console.log(console_cl_red,"buy value: "+av*aq+" < "+minimums[CURR].minNotional,console_cl_res); return false; } } return true; } function logD(d, is_err, callback) { var fs = require('fs'); var dt=new Date().toLocaleString().replace(/T/, ' ').replace(/\..+/, '') var satir = teststr+dt + " > " + d; if (is_err == 1) {log_sonsatir_err = satir; console.log("logD->"+satir);} else log_sonsatir = satir; fs.appendFile('log/bot.log', '\n' + satir, function (err) { if (err) console.log("Log file write error!"); if (callback) callback(); }); }; function log_options(log){ console.log(console_cl_red,"[optlog] "+log,console_cl_res); var dt=new Date().toLocaleString().replace(/T/, ' ').replace(/\..+/, '') log_sonsatir_opt="[modlog] " + dt + " > " + log.toString().replace('\n', ' ').escapeSpecialChars(); } function writeconfigfile(callback) { var fs = require('fs'); var data = JSON.stringify(config); fs.writeFile(configfile, data, function (err) { if (err) { var errmsg='There has been an error saving your configuration data.'; logD(errmsg,1); console.log(errmsg); console.log(err.message); if (callback) callback(1); return; } else { if (callback) callback(0); } }); } function getbalances(){ fbb.getBalance(CURR, 0, function (x, e) { if (x != 0) {logD(e, 1); return;} balance1 = e; }); fbb.getBalance(CURR, 1, function (x, e) { if (x != 0) {logD(e, 1); return;} balance2 = e; }); fbb.getBalance(CURR, 2, function (x, e) { if (x != 0) {logD(e, 1); return;} balance_bnb = e; }); } Number.prototype.toFixedNR = function (dig) { var dig1 = Math.pow(10, dig); return (Math.trunc(this.valueOf() * dig1) / dig1); } String.prototype.escapeSpecialChars = function () { return this.replace(/\\n/g, "\\n") .replace(/\\'/g, "\\'") .replace(/\\"/g, '\\"') .replace(/\\&/g, "\\&") .replace(/\\r/g, "\\r") .replace(/\\t/g, "\\t") .replace(/\\b/g, "\\b") .replace(/\\f/g, "\\f") .replace("'", " "); }; function get_html_file() { fs.readFile("files/www.html", "utf8", function (err, data) { if (err) web_str[0] = "No html file!"; else web_str = fbb.html_parse(data); }); } function getPoint(x){ if (Math.trunc(x) != 0) return 0; var say=0; while (true){ if (Math.trunc(Math.pow(10, say)*x) != 0) break; else say++; if (say>8) return 0; } return say; } function log_control() { var cli = require('readline').createInterface(process.stdin, process.stdout); var log = console.log; console.log = function () { if (is_printon == 0) return; // cli.pause(); //cli.output.write('\x1b[2K\r'); log.apply(console, Array.prototype.slice.call(arguments)); // cli.resume(); //cli._refreshLine(); } } function init() { fbb.b_options(main_config.api_key,main_config.api_secret,api_order_test, (log)=>{ log_options(log); }); binance.useServerTime(function(){ fbb.getBalance(CURR, 0, function (x, e) { if (x != 0) {console.log(e); /*process.exit(11);*/} log_control(); balance1 = e; fbb.getBalance(CURR, 1, function (x, e) { if (x != 0) {logD(e, 1); return; } balance2 = e; fbb.b_candlesticks(CURR, function (x, e) { if (x != 0) {logD(e, 1); return; } b_depthCache(); }); }); }); }); /* binance.exchangeInfo(function(error, data) { let minimums = {}; for ( let obj of data.symbols ) { let filters = {minNotional:0.001,minQty:1,maxQty:10000000,stepSize:1,minPrice:0.00000001,maxPrice:100000}; for ( let filter of obj.filters ) { if ( filter.filterType == "MIN_NOTIONAL" ) { filters.minNotional = filter.minNotional; } else if ( filter.filterType == "PRICE_FILTER" ) { filters.minPrice = filter.minPrice; filters.maxPrice = filter.maxPrice; } else if ( filter.filterType == "LOT_SIZE" ) { filters.minQty = filter.minQty; filters.maxQty = filter.maxQty; filters.stepSize = filter.stepSize; } } minimums[obj.symbol] = filters; } console.log(minimums); fs.writeFile("minimums.json", JSON.stringify(minimums, null, 4), function(err){}); }); */ } var exit_program = function (x) { setTimeout(function () { process.exit(x); }, 2000); } /**********************************************************************/ if (api_order_test) teststr="**Test**"; logD("Start ***********************************\n", 0); try { main_config = require(keyfile); } catch (ex) { console.log("Error: "+keyfile+ " not found!"); process.exit(11); } try { config = require(configfile); } catch (ex) { config={"currency":"ETHBTC","proggress":"sell","buyvalue":0,"sellvalue":0,"profit":10,"noise":1}; console.log("Error: "+configfile+ " not found!, default loaded ..."); } config_curr = JSON.parse(JSON.stringify(config)); if (config.proggress == "buy") proggress = buy; else if (config.proggress == "sell") proggress = sell; CURR = config.currency; alimvalue = config.buyvalue; satimvalue = config.sellvalue; KAR = config.profit; NOISE = config.noise; try { virgul=getPoint(minimums[CURR].minQty); virgul_price=getPoint(minimums[CURR].minPrice); init(); } catch (ex){ logD(CURR+" is not available !",1); } //console.log(val, satimvalue, quantity); //exit_program(1); let Currs=fbb.getCurrNames(CURR); get_html_file(); var http = require('http'); var url = require('url'); http.createServer(function (req, res) { var val1; if (proggress == buy) { val1 = value_buy; } else if (proggress == sell) { val1 = value_sell; } else if (proggress == 0) {} var web_json = { "CURR": CURR, "c1name": Currs[0], "c2name": Currs[1], "proggress": proggress, "limit_top": limit_ust, "value_now_buy": value_buy, "value_now_sell": value_sell, "value_last_buy": alimvalue, "value_last_sell": satimvalue, "profit_now": fark_yuzde, "balance_1": balance1, "balance_2": balance2, "balance_bnb": balance_bnb, "alive": count, "obok": is_check_order_balance, "order_paused": order_paused, "version": package.version, "log_info": log_sonsatir.replace('\n', ' ').escapeSpecialChars(), "log_err": log_sonsatir_err.replace('\n', ' ').escapeSpecialChars(), "log_opt": log_sonsatir_opt }; if (req.url.indexOf('/values?c=resetlogs') >= 0) { log_sonsatir_err=log_sonsatir_opt=web_json.log_err=web_json.log_opt=""; res.write(`${JSON.stringify(web_json)}`); } else if (req.url.indexOf('/values?c=getval') >= 0) res.write(`${JSON.stringify(web_json)}`); else if (req.url.indexOf('/values?c=getconf') >= 0) res.write(`${JSON.stringify(config)}`); else if (req.url.indexOf('/values?c=getcurrconf') >= 0) res.write(`${JSON.stringify(config_curr)}`); else if (req.url.indexOf('/values?c=setrestart') >= 0) { res.write(`${JSON.stringify(config)}`); writeconfigfile(function (x) { var str = "Restarting with new values ...\n" console.log(str + ", is_file_err: " + x); logD(str, 0); exit_program(99); }); } else if (req.url.indexOf('/values?c=restart') >= 0) { res.write(`${JSON.stringify(config)}`); var str = "Restarting ...\n" console.log(str); logD(str, 0); exit_program(99); } else if (req.url.indexOf('/values?c=order_paused') >= 0) { var url_parts = url.parse(req.url, true); var query = url_parts.query; order_paused = (query.pause == 'true'); web_json.order_paused=order_paused; res.write(`${JSON.stringify(web_json)}`); } else if (req.url.indexOf('/values?c=setconf') >= 0) { var url_parts = url.parse(req.url, true); var query = url_parts.query; //console.log(query); if (query.currency != "" && query.buyvalue != "" && query.sellvalue != "" && query.profit != "" && query.noise != "") { config.currency = query.currency.escapeSpecialChars(); config.proggress = query.proggress.escapeSpecialChars(); config.buyvalue = parseFloat(query.buyvalue); config.sellvalue = parseFloat(query.sellvalue); config.profit = parseFloat(query.profit); config.noise = parseFloat(query.noise); console.log(config); } res.write(`${JSON.stringify(config)}`); } else if (req.url == '/') res.write(`${web_str[0]}'${JSON.stringify(web_json)}'${web_str[1]}`); else res.write("?"); res.end(); }).listen(main_config.port); var arg = process.argv.slice(2); //if (arg[1]) host=arg[1]; if (arg[0]) { if (arg[0] == 0) is_printon = 0; } process.stdin.pause; <file_sep>/stop.sh #!/bin/bash touch /tmp/bitbotstop ret=$(pgrep -f 'node bitbot.js') kill -9 $ret
e60ab800243d680be55b79f5529bb871341c4e6b
[ "Markdown", "JavaScript", "Shell" ]
5
Markdown
marmibv/bitbot_binance_price-fluctuations-Noise
237fd05cfdd55c19bf6f426d8b279b02f2ea41c8
c55ca9843ff20fdf5f176e28f1b85917516fe385
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class SaveResultInfo { private int flag = 1; private string desc = ""; public string Desc { get => desc; set => desc = value; } public int Flag { get => flag; set => flag = value; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Windows.Forms; using IqaController.entity; namespace IqaController { public partial class popFileInfo : Form { private FileProcess m_zipfileInfo = null; public popFileInfo() { InitializeComponent(); } internal FileProcess ZipfileInfo { get => m_zipfileInfo; set => m_zipfileInfo = value; } public void setControl() { txtFileNameB.Text = m_zipfileInfo.ZipFileName; txtFilePathB.Text = m_zipfileInfo.ZipfileFullPath; } private void btnFileNameModify_Click(object sender, EventArgs e) { if (txtFileNameA.Text == "") { MessageBox.Show("변경후 파일명을 입력하여 주십시요."); return; } m_zipfileInfo.WorkZipFileName = txtFileNameA.Text; File.Move(m_zipfileInfo.ZipfileFullPath + "\\" + m_zipfileInfo.ZipFileName, m_zipfileInfo.ZipfileFullPath + "\\" + m_zipfileInfo.WorkZipFileName); MessageBox.Show("변경되었습니다."); } private void btnFileMove_Click(object sender, EventArgs e) { if (txtFilePathA.Text == "") { MessageBox.Show("파일 이동할 경로를 설정해 주십시요."); return; } File.Move(m_zipfileInfo.ZipfileFullPath + "\\" + m_zipfileInfo.ZipFileName, txtFilePathA.Text + "\\" + m_zipfileInfo.WorkZipFileName); m_zipfileInfo.ZipfileFullPath = txtFilePathA.Text; MessageBox.Show("이동하였습니다."); } private void btnMoveDirSel_Click(object sender, EventArgs e) { FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.ShowDialog(); txtFilePathA.Text = dialog.SelectedPath; //선택한 다이얼로그 경로 저장 } private void popFileInfo_Load(object sender, EventArgs e) { setControl(); this.Show(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class CommonResultEntity { private string flag = Define.con_FAIL; private object result = null; public string Flag { get => flag; set => flag = value; } public object Result { get => result; set => result = value; } } } <file_sep>using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Runtime.InteropServices; using IqaController.entity; namespace IqaController { class util { [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); public static void Log(string flag , string logMessage) { try{ //w.WriteLine("{0} : {1} {2} : {3}", flag, DateTime.Now.ToLongTimeString(), //DateTime.Now.ToLongDateString(), logMessage); DirectoryInfo diChk = new DirectoryInfo(".\\log\\"); if (diChk.Exists == false) { diChk.Create(); } string cur = DateTime.Now.ToString("yyyyMMdd"); System.IO.File.AppendAllText(".\\log\\" + cur +".txt", String.Format("[{0}] : [{1} {2}] : [{3}]", flag, DateTime.Now.ToLongDateString() , DateTime.Now.ToLongTimeString(), logMessage) + Environment.NewLine); } catch (Exception ex) { Console.WriteLine(ex.Message); } } public static void LogDrm(string flag, string logMessage) { try { //w.WriteLine("{0} : {1} {2} : {3}", flag, DateTime.Now.ToLongTimeString(), //DateTime.Now.ToLongDateString(), logMessage); DirectoryInfo diChk = new DirectoryInfo(".\\log\\drm\\"); if (diChk.Exists == false) { diChk.Create(); } string cur = DateTime.Now.ToString("yyyyMMdd"); System.IO.File.AppendAllText(".\\log\\drm\\" + cur + ".txt", String.Format("[{0}] : [{1} {2}] : [{3}]", flag, DateTime.Now.ToLongDateString() , DateTime.Now.ToLongTimeString(), logMessage) + Environment.NewLine); } catch (Exception ex) { Console.WriteLine(ex.Message); } } public static Boolean ParseDate(string sFileDate , ref DateTime date) { Boolean bSuccess = false; try{ date = DateTime.ParseExact(sFileDate, "yyyyMMdd", null); bSuccess = true; } catch (Exception ex) { Console.WriteLine(ex.Message); bSuccess = false; } return bSuccess; } public static void SetIniWriteString(string section, string key, string val, string filePath) { WritePrivateProfileString(section, key, val, filePath); } public static void GetIniString(string section, string key, string def, StringBuilder retVal, int size, string filePath) { GetPrivateProfileString(section, key, def, retVal, size, filePath); } public static Boolean AllDeleteInDirectory(string dirPath) { try { //읽기 전용 삭제 하기 위해 변경한다. DirectoryInfo dir = new DirectoryInfo(dirPath); System.IO.FileInfo[] files = dir.GetFiles("*.*", SearchOption.AllDirectories); foreach (System.IO.FileInfo file in files) { file.Attributes = FileAttributes.Normal; } //Directory.Delete(dirPath, true); //파일 삭제 string[] filePaths = Directory.GetFiles(dirPath); foreach (string filePath in filePaths) { FileInfo fi = new FileInfo(filePath); fi.Delete(); } string[] dirs = Directory.GetDirectories(dirPath); foreach (string subDirPath in dirs) { Directory.Delete(subDirPath, true); } return true; } catch (Exception ex) { util.Log("ERR:directoryDelete", ex.Message); Console.WriteLine(ex.Message.ToString()); return false; } } public static Boolean Wait2FileAccessible(string fullPath,int maxMin, ref string errFlag) { while (true) { try { //복사중일경우 Exception 발생한다. using (var file = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { break; } } catch (FileNotFoundException ex) { //파일을 찾을수 없을경우 즉 FTP전송되다 취소될경우 return false; } catch (IOException ex) { Thread.Sleep(1000); }catch(Exception ex) { //ACCESS DEnined 발생 errFlag = Define.con_STATE_ERR_FILE_DENIED; return false; } } return true; } public static Boolean FindDir2File(string dirPath,string findFile , ref string finedFullPath) { Boolean bFind = false; string[] filePaths = Directory.GetFiles(dirPath); string tmpFile = ""; foreach (string filePath in filePaths) { tmpFile = Path.GetFileName(filePath); if (tmpFile == findFile) { bFind = true; finedFullPath = filePath; break; } } return bFind; } public static long CalculateDirectorySize(DirectoryInfo directory, bool includeSubdirectories) { long totalSize = 0; FileInfo[] files = directory.GetFiles(); foreach (FileInfo file in files) { totalSize += file.Length; } if (includeSubdirectories) { DirectoryInfo[] dirs = directory.GetDirectories(); foreach (DirectoryInfo dir in dirs) { totalSize += CalculateDirectorySize(dir, true); } } return totalSize; } public static string GetCurrentDate(string format) { DateTime dt = DateTime.Now; string curDate = String.Format(format, dt); return curDate; } public static Boolean FileSave(string flag, string sourceFileName, string destiFileName) { int nMax = 2000; int nAttemptCnt = 0; Boolean bDo = true; Boolean bSuccess = false; while (bDo) { try { if (flag == "copy") { File.Copy(sourceFileName, destiFileName, true); } else { File.Move(sourceFileName, destiFileName); } bDo = false; bSuccess = true; } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); if (ex.HResult == -2147024864) { Thread.Sleep(1500); nAttemptCnt++; if (nAttemptCnt > nMax) { bDo = false; util.Log("[ERR]:fileSave", "파일권한 무한 대기 발생"); } } else { util.Log("[ERR]:fileSave", ex.Message); bDo = false; } } } return bSuccess; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class ZipfileInfoEntity { private string zipfile_nm = ""; private string cur_state = ""; public string Zipfile_nm { get => zipfile_nm; set => zipfile_nm = value; } public string Cur_state { get => cur_state; set => cur_state = value; } } } <file_sep>using System; using System.Collections.Generic; using System.Web; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class FileProcess { private string uploadDate = ""; // DB 상의 파티션 잡혀있음 private string measuDate = ""; // Zip파일 측정일 정보 Upload_date에 해당 값 넣는다. private string filePos = ""; // 파일 private string processServer = ""; // 처리서버 private string measuGroup = ""; // 측정조 private string measuBranch = ""; // 측정본부 private string zipFileName = ""; // zip 파일 작업가공 이름 - 뒤에 시스템 날짜 추가됨 private string orgZipFileName = ""; // zip 파일 이름 원본이름 - 파일 원래 이름 KEY 임(문제되는 이름 가공된 버전) 2018-12-10일 추가 콤마 자동 변환처리 추가 private string workZipFileName = ""; // 임시 작업성 zip파일 명 private string inoutType = ""; private string comp = ""; private string serviceType = ""; //서비스 타입 // private string fileName = ""; // 파일 이름 private string fileNameRule = ""; // 파일명 규칙 private string fileNameFlag = ""; // 파일명 규칙 에러 플래그 private string extractFlag = ""; // 압축해제 에러 플래그 private string conversionFlag = ""; // 컨버전에러 플래그 private string ftpSendFlag = ""; // ftp 전송 시도 여부 private string ftpSuccessFlag = ""; // ftp 전송 성공여부 - qms 파일 하나라도 실패시 "0" private string backupFlag = ""; // 백업 private string zipDupFlag = ""; // zip파일 중복 private Boolean pass = false; // 해당파일 패스할지 여부 private Boolean complete = false; // 전체 성고 여부 private string fileSize = ""; //파일 사이즈 private string unzipfileCnt = ""; private string dupfileCnt = ""; private string completefileCnt = ""; private string parsingCompleteCnt = ""; private string zipfileFullPath = ""; //Zip 파일경로 private string curState = Define.con_STATE_WAIT; private string ftpSendServer = ""; private string flagFtpSend = "0"; private int ftpSendSuccessCnt = 0; private int ftpSendFileCnt = 0; private string errFlagFileAccess = ""; //private List<QmsFileInfo> qmsFileList = new List<QmsFileInfo>(); private List<ZipFileDetailEntity> zipfileDetailList = new List<ZipFileDetailEntity>(); public string FilePos { get => filePos; set => filePos = value; } public string ProcessServer { get => processServer; set => processServer = value; } public string MeasuGroup { get => measuGroup; set => measuGroup = value; } public string MeasuBranch { get => measuBranch; set => measuBranch = value; } public string ZipFileName { get => zipFileName; set => zipFileName = value; } // public string FileName { get => fileName; set => fileName = value; } public string FileNameRule { get => fileNameRule; set => fileNameRule = value; } public string ExtractFlag { get => extractFlag; set => extractFlag = value; } public string ConversionFlag { get => conversionFlag; set => conversionFlag = value; } public string FtpSendFlag { get => ftpSendFlag; set => ftpSendFlag = value; } public string BackupFlag { get => backupFlag; set => backupFlag = value; } public bool Complete { get => complete; set => complete = value; } public bool Pass { get => pass; set => pass = value; } public string FileSize { get => fileSize; set => fileSize = value; } public string FileSize1 { get => fileSize; set => fileSize = value; } public string UnzipfileCnt { get => unzipfileCnt; set => unzipfileCnt = value; } public string DupfileCnt { get => dupfileCnt; set => dupfileCnt = value; } public string CompletefileCnt { get => completefileCnt; set => completefileCnt = value; } public string ParsingCompleteCnt { get => parsingCompleteCnt; set => parsingCompleteCnt = value; } public string CurState { get => curState; set => curState = value; } public string ZipfileFullPath { get => zipfileFullPath; set => zipfileFullPath = value; } public string FileNameFlag { get => fileNameFlag; set => fileNameFlag = value; } public string FtpSendServer { get => ftpSendServer; set => ftpSendServer = value; } public string FlagFtpSend { get => flagFtpSend; set => flagFtpSend = value; } public int FtpSendSuccessCnt { get => ftpSendSuccessCnt; set => ftpSendSuccessCnt = value; } public int FtpSendFileCnt { get => ftpSendFileCnt; set => ftpSendFileCnt = value; } public string ZipDupFlag { get => zipDupFlag; set => zipDupFlag = value; } public string FtpSuccessFlag { get => ftpSuccessFlag; set => ftpSuccessFlag = value; } public string InoutType { get => inoutType; set => inoutType = value; } public string Comp { get => comp; set => comp = value; } public string OrgZipFileName { get => orgZipFileName; set => orgZipFileName = value; } public string WorkZipFileName { get => workZipFileName; set => workZipFileName = value; } public string MeasuDate { get => measuDate; set => measuDate = value; } public string ServiceType { get => serviceType; set => serviceType = value; } //internal List<QmsFileInfo> QmsFileList { get => qmsFileList; set => qmsFileList = value; } internal List<ZipFileDetailEntity> ZipfileDetailList { get => zipfileDetailList; set => zipfileDetailList = value; } public string OrgZipFIleFullName { get => this.zipfileFullPath + "\\" + this.orgZipFileName; } //Path+orgZipFileName public string ZipFileFullFileName { get => this.zipfileFullPath + "\\" + this.zipFileName; } //Path+zipFileName public string UploadDate { get => uploadDate; set => uploadDate = value; } public string ErrFlagFileAccess { get => errFlagFileAccess; set => errFlagFileAccess = value; } public ZipFileDetailEntity findZipfileDetail(string flag , string key) { ZipFileDetailEntity find = null; foreach(ZipFileDetailEntity detail in this.zipfileDetailList) { if (flag == "unzipNm") { if (detail.UnzipfileNm == key) { find = detail; break; } }else if (flag == "qmsNm") { if (detail.QmsfileNm == key) { find = detail; break; } } else if (flag == "onlyUnzipNm") { if (Path.GetFileNameWithoutExtension(detail.UnzipfileNm) == key) { find = detail; break; } } } return find; } public string GetWorkFileFullPathName() { return this.zipfileFullPath + "\\" + this.zipFileName; } public string GetErr2MovFileDirPath(string path, string dirFlag) { string fullPathName = ""; string withoutExtensionZipfileName = Path.GetFileNameWithoutExtension(this.zipFileName); fullPathName = path + "\\" + dirFlag + "\\" + withoutExtensionZipfileName; return fullPathName; } /* 시스템 날짜 포함한 ZIP 파일 풀경로 */ public string GetZipfileFullPathName(string path, string dirFlag) { string fullPathName = ""; fullPathName = path + "\\" + dirFlag + "\\" + this.ZipFileName; return fullPathName; } public string GetErr2MovFileFullPathName(string path , string dirFlag) { string fullPathName = ""; string withoutExtensionZipfileName = Path.GetFileNameWithoutExtension(this.zipFileName); fullPathName = path + "\\" + dirFlag + "\\" + withoutExtensionZipfileName + "\\" + this.orgZipFileName; return fullPathName; } /*2018-12-12 작성하다 우선 보류한다.*/ public string GetConvertorCallServiceType() { /* O. 서비스망유형 확인하여, 해당 컨버터 명령 실행 시 체크방식 * DRM파일명을 대문자로 변환하여 o. CSFB 1) DRM파일명 상 'CSFB_' 또는 '_CSFB' 또는 ' CSFB ' 또는 '3G음성' 2) DRM파일명 상 'VOICE_' 또는 '_O_' 또는 '_T_' 또는 ' 발신 ' 또는 ' 착신 ' 이면서, ZIP파일명 상 'CSFB_' 또는 'CSFBML_' 인 경우 3) 위의 1) 또는 2) 의 해당하지 않는 경우는 ZIP파일명 상의 정보 기준으로 처리 o. HDVOICE 1) DRM파일명 상 'HDV_' 또는 '_HDV' 또는 ' HDV ' 또는 'VOLTE_' 또는 'VOLTE ' 2) DRM파일명 상 'VOICE_' 또는 '_O_' 또는 '_T_' 또는 ' 발신 ' 또는 ' 착신 ' 이면서, ZIP파일명 상 'HDV_' 또는 'HDVML_' 인 경우 3) 위의 1) 또는 2) 의 해당하지 않는 경우는 ZIP파일명 상의 정보 기준으로 처리 o. HSDPA 1) DRM파일명 상 'HSDPA_' 또는 ' W DATA ' 2) DRM파일명 상 'MC_FTP_' 또는 'FTP_' 이면서, ZIP파일명 상 'HSDPA_' 인 경우 3) 위의 1) 또는 2) 의 해당하지 않는 경우는 ZIP파일명 상의 정보 기준으로 처리 o. LTED 1) DRM파일명 상 'LTED_' 또는 ' LTE DATA ' 2) DRM파일명 상 'MC_FTP_' 또는 'FTP_' 또는 'APP_FTP' 이면서, ZIP파일명 상 'LTED_' 인 경우 3) 위의 1) 또는 2) 의 해당하지 않는 경우는 ZIP파일명 상의 정보 기준으로 처리 */ string zipfileNm = this.orgZipFileName; string serviceType = this.serviceType; string drmFileNm = ""; zipfileNm = zipfileNm.ToUpper(); foreach (ZipFileDetailEntity zd in this.zipfileDetailList) { drmFileNm = zd.UnzipfileNm; drmFileNm = drmFileNm.ToUpper(); if (drmFileNm.IndexOf("CSFB") >= 0 || drmFileNm.IndexOf("3G음성") >= 0) { serviceType = "CSFB"; } else if((zipfileNm.IndexOf("CSFB_") >=0 || zipfileNm.IndexOf("CSFBML_") >=0) && ( drmFileNm.IndexOf("VOICE_") >=0 || drmFileNm.IndexOf("_O_") >= 0 || drmFileNm.IndexOf("_T_") >= 0) || drmFileNm.IndexOf("발신") >= 0 || drmFileNm.IndexOf("착신") >= 0 ) { serviceType = "CSFB"; } } return serviceType; } public Dictionary<string, Object> getDomain(Boolean bDetail) { Dictionary<string, Object> domain = new Dictionary<string, object>(); Dictionary<string, Object> domainZM = new Dictionary<string, object>(); //ZipFileMain domainZM.Add("zipfileNm", HttpUtility.UrlEncode(this.zipFileName)); domainZM.Add("measuBranch", HttpUtility.UrlEncode(this.measuBranch)); domainZM.Add("measuGroup", HttpUtility.UrlEncode(this.measuGroup)); domainZM.Add("inoutType", this.inoutType); domainZM.Add("comp", this.Comp); domainZM.Add("zipfileSize", this.fileSize); domainZM.Add("procServer", this.processServer); domainZM.Add("ftpServer", this.ftpSendServer); domainZM.Add("unzipfileCnt", this.unzipfileCnt); domainZM.Add("dupfileCnt", this.dupfileCnt); domainZM.Add("completefileCnt", this.completefileCnt); domainZM.Add("parsingCompleteCnt", this.parsingCompleteCnt); domainZM.Add("curState", this.curState); domainZM.Add("uploadDate", this.uploadDate); domain.Add("zipfileMain", domainZM); if (zipfileDetailList.Count > 0 && bDetail) { List <Dictionary<string, Object>> lstDomain = new List<Dictionary<string, object>>(); foreach (ZipFileDetailEntity zd in this.zipfileDetailList) { Dictionary<string, Object> domainPart = zd.getDomain(); lstDomain.Add(domainPart); } domain.Add("zipfileDetailList", lstDomain); } return domain; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { static class Define { public const string CON_DEFAULT_DIR = @"D:\FTP"; #if DEBUG public const string CON_WEB_SERVICE = "http://localhost:8080/IQA/"; public const string CON_WEB_SERVICE2 = "http://localhost:8080/IQA/"; public const string CON_ZIP_EXE_PATH = @"C:\Program Files (x86)\7-Zip\"; #else public const string CON_WEB_SERVICE = "http://172.16.17.32:8080/IQA/"; public const string CON_WEB_SERVICE2 = "http://172.16.58.3:8080/IQA/"; public const string CON_ZIP_EXE_PATH = @"C:\Program Files\7-Zip\"; #endif public const string con_SERVICE_CON_FAIL = "ConnectFail"; //MSG 상수 public const string CON_MSG_COMPLETE = "완료"; public const string CON_MSG_WAIT = "대기"; public const string CON_MSG_ING = "진행중"; public const string CON_MSG_ERROR = "Error"; public const string CON_MSG_ERROR_CONV_LEN = "Drm 파일길이 Error"; public const string CON_MSG_CANCEL = "취소"; //진행단계 //public const string con_ING_START = "START"; //public const string con_ING_UNZIP = "UNZIP"; //public const string con_ING_FTPUPLOAD = "FTPUPLOAD"; //public const string con_ING_CONV = "CONV"; public const string con_FTP_QMS = "QMS"; public const string con_FTP_WAV = "WAV"; public const string con_FTP_DRM = "DRM"; public const string con_EVENT_DRM_STATE_DRM = "UZ"; //DRM 파일 추출중 public const string con_EVENT_DRM_STATE_FTP = "FTP"; //DRM 파일 추출중 public const string con_EVENT_DRM_STATE_END = "WORK_END"; //작업 끝 public const string con_DIR_WORK = "WORK"; public const string con_DIR_NAMING = "NAMING_ERROR"; public const string con_DIR_PARSING = "PARSING_ERROR"; public const string con_DIR_UPLOAD = "UPLOAD_ERROR"; public const string con_DIR_ZIPDUP = "ZIPDUP_ERROR"; public const string con_DIR_CONVERT = "CONVERT_ERROR"; public const string con_DIR_BACK = "BACKUP"; public const string con_DIR_EVENT_ORIFILE = "EVENT_ORIFILE_WORK"; public const string con_STATE_START_NAMING = "S_NM"; //네이밍 시작 public const string con_STATE_START_UNZIP = "S_UZ"; //UNZIP 시작 public const string con_STATE_START_CONV = "S_CONV"; //CONVERTOR 시작 public const string con_STATE_START_FTP = "S_FTP"; //FTP 완료 //의미 있나 바로 모두 완료 될텐데 public const string con_STATE_WAIT = "WAIT"; public const string con_STATE_WORK = "WORK"; public const string con_STATE_WORK_COMPLETE = "CP"; //모든 작업 완료 public const string con_STATE_COMPLETE_NAMING = "NM"; //네이밍 완료 public const string con_STATE_COMPLETE_UNZIP = "UZ"; //UNZIP 완료 public const string con_STATE_COMPLETE_CONV = "CONV"; //CONVERTOR 완료 public const string con_STATE_COMPLETE_FTP = "FTP"; //FTP 완료 public const string con_STATE_CANCEL = "CANCEL"; //중간 취소 public const string con_STATE_ERR_NAMING = "E_NM"; public const string con_STATE_ERR_UNZIP = "E_UZ"; public const string con_STATE_ERR_CONV = "E_CONV"; public const string con_STATE_ERR_CONV_LEN = "E_CONV_LEN"; public const string con_STATE_ERR_FTP = "E_FTP"; public const string con_STATE_ERR_DUP_DRM = "E_DD"; //DRP 중복 public const string con_STATE_ERR_DUP_ZIP = "E_DZ"; //ZIP파일 중복 public const string con_STATE_ERR_DUP_ALL = "E_DD_ALL"; //DRM 모든파일 중복 DRM public const string con_STATE_ERR_ZERO_QMS = "E_ZERO_QMS"; //컨버터 실행후 QMS파일 미생성된 오류 public const string con_STATE_ERR_ZERO_DRM = "E_ZERO_DRM"; //압축해제후 DRM 파일 미존재 public const string con_STATE_ERR_NO_FILE = "E_NO_FILE"; //Zip파일 존재 하지 않음(원격 DRM 전송중 최소되는 경우) public const string con_STATE_ERR_FILE_DENIED = "E_FILE_DENIED"; public const string con_STATE_ERR_CONV_ABNORMAL = "E_CONV_ABNORMAL"; //컨버터 비정상 종료 및 멈춤 public const string con_FOLDER_UPLOAD_ERROR = "UPLOAD_ERROR"; public const string con_SUCCESS = "1"; public const string con_FAIL = "0"; public const int con_KEY_PROCESS_COLIDX = 10; public const int con_KEY_PROCESSLOG_COLIDX = 5; public const int con_KEY_PROCESSERROR_COLIDX = 6; public const int con_KEY_EVENTDRM_COLIDX = 0; } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace IqaController { public partial class ucLoadingBar : UserControl { public ucLoadingBar() { InitializeComponent(); } public void On(string msg) { this.Invoke(new Action(delegate () { this.Show(); lblTitle.Text = msg; })); } public void Off() { this.Invoke(new Action(delegate () { this.Hide(); lblTitle.Text = ""; })); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace IqaController { class DataGridViewEx : DataGridView { public DataGridViewEx() { this.AllowUserToAddRows = false; this.RowCount = 0; this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing; this.ColumnHeadersHeight = 23; this.ReadOnly = true; } /* 해당 cell을 기본 Text 형식으로 설정한다. * */ public void setCell(string value, int col, int row) { DataGridViewRow r = this.Rows[row]; r.Cells[col] = new DataGridViewTextBoxCell(); ((DataGridViewTextBoxCell)r.Cells[0]).Value = value; } /* 해당 cell을 Button 형식으로 설정한다. * */ public void setCellButton(string value, int col,int row) { DataGridViewRow r = this.Rows[row]; r.Cells[col] = new DataGridViewButtonCell(); ((DataGridViewButtonCell)r.Cells[col]).Value = value; } public void addColumn(string headerText, int width) { DataGridViewTextBoxColumn tmp = new DataGridViewTextBoxColumn(); //tmp.Name = "항목"; tmp.HeaderText = headerText; tmp.Width = width; tmp.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; this.Columns.Add(tmp); } public void addColumnCheckBox(string headerText,bool selected, int width) { DataGridViewCheckBoxColumn tmp = new DataGridViewCheckBoxColumn(); tmp.HeaderText = headerText; tmp.Width = width; //tmp.Selected(true); this.Columns.Add(tmp); } public void addColumnButton(string headerText, string buttonText, int width) { DataGridViewButtonColumn tmp = new DataGridViewButtonColumn(); tmp.HeaderText = headerText; tmp.Text = buttonText; tmp.Width = width; tmp.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; //btn.Name = "btn"; tmp.UseColumnTextForButtonValue = true; this.Columns.Add(tmp); } public int getFindZipFile2RowIndex(string zipFileNm, int nCol) { int nRow = -1; foreach (DataGridViewRow r in this.Rows) { string tmpZipFileName = (string)((DataGridViewTextBoxCell)r.Cells[nCol]).Value; if (tmpZipFileName == zipFileNm) { nRow = r.Index; break; } } return nRow; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.IO; using System.Net; using System.IO.Compression; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; using System.Collections.Specialized; using System.Web; using System.Timers; //using System.IO.Compression; using System.Diagnostics; //using System.Linq; using Renci.SshNet; using IqaController.entity; using IqaController.service; /* Filesystemwatcher * https://msdn.microsoft.com/ko-kr/library/system.io.filesystemwatcher(v=vs.110).aspx * * rest APi Call example * https://stackoverflow.com/questions/9620278/how-do-i-make-calls-to-a-rest-api-using-c * * // 오라클 클라이언트 접속 * http://kin33.tistory.com/60 * * //Visual studio 자주쓰는 팁 * https://msdn.microsoft.com/ko-kr/library/dn600331.aspx * * //circle loading bar * https://github.com/falahati/CircularProgressBar * https://www.youtube.com/watch?v=o7MGaf8YW6s * */ namespace IqaController { public partial class frmMain : Form { private Queue<FileProcess> m_QueueZipfileParsing = new Queue<FileProcess>(); //시작 ~ 알집해제까지 private Queue<FileProcess> m_QueueZipfileParsing_2 = new Queue<FileProcess>(); //컨버터 실행 ~ FTP 전송 이후까지(컨버터 처리가 오래걸려서 작업큐 나눈다) private Dictionary<string, FileProcess> m_dicFileProcess = new Dictionary<string, FileProcess>(); // private Dictionary<string, FileProcess> m_dicFileProcessErr = new Dictionary<string, FileProcess>(); //Error 파일 따로 관리(로딩시 디렉토리에서도 읽어와야함) private FileSystemWatcher m_zipFileWatcher = null; private string m_ftpId = "14"; private Boolean m_formClose = false; private Boolean m_bServiceOnOffButton = false; //서비스 On Off 버튼 토글 private Boolean m_ServiceOnIng = false; //서비스 처리 프로세스 진행중 여부 (true:진행중 , false:완료) private System.Timers.Timer timer = new System.Timers.Timer(); private Dictionary<string, ControllerServerEntity> m_dicFtpInfo = new Dictionary<string, ControllerServerEntity>(); private List<ControllerServerEntity> m_lstServer = null; //환경설정 수집서버 private List<ControllerFileKeepEntity> m_lstFile = null; //환경설정 파일 보관주기 private List<ControllerEnvEntity> m_lstEnv = new List<ControllerEnvEntity>(); private int m_eventOrifileLoopCnt = 0; private Boolean m_debug = true; private string m_checkedkDay = ""; //일단위 체크날짜 private const string m_version = "1.0.7.7"; /* version Log * 1.0.1 : 2018-12-11 : 파일명 규칙 사업자는 제외한다 * 1.0.2 : 2018-12-12 : 파일명 규칙 서비스타입 추가처리 * 1.0.3 : 2018-12-13 : 모두 중복 drm일시 처리 보완처리(중복 drml삭제해도 나머지 파일이 있어서 파일사이즈로 기존 처리하는부분 보완처리함) * 1.0.4 : 2018-12-13 : 화면 및 zipfile key값 orgZipfileName -> zipfileName로 변경 FTP04같은경우 분단위로 같은 파일을 보내서 꼬일경우 발생 ㅠㅠ * 1.0.5 : 2018-12-17 : DB 컬럼 UPLOAD_DATE MAIN 과 DETAIL 동일하게 처리요청 * 1.0.6 : 2018-12-21 : 컨버터 비정상에 인한 파일 복사시 문제 버그 수정 * 1.0.7 : 2018-12-26 : 취소기능 추가 - 서버 작업 완료되면 배포예정 2018-12-28 : zip 파일 Access Denied 발생(파일 자체를 제어할수 없음) 따라 해당 로그테이블에 이력 남기기 기능 추가 이전버전은 예외발생함에 따라 멈춤 발생 2019-01-02 : 비정상 종료 처리에 따른 수동 처리 자동화 기능 추가(DB 삭제후 해당 Zip파일 찾아서(backup , FTP루트폴더,WORK 폴더) FTP 루트 폴더로 옮기기 및 DB처리) 2019-01-03 : Event DRM 정보 처리시 그시점에 가져오는 방식으로 변경처리(기존은 컨트롤로 로딩시 한번 가져온다.) * 1.0.7.1 : : 비정상 종료 체크 안되는 버그 수정 * 1.0.7.2 : 2019-01-17 : 비정상 종료 Zip파일명으로 찾기 기능 추가처리 * 1.0.7.3 : 2019-01-17 : 비정상 종료 컨버터 에러처리 기능 보이게 추가 처리 * 1.0.7.4 : 2019-01-18 : 작업완료 저장시 DB오류 오류값 로그에 남긴다. (iqaService.updateZipFileAllInfo) * 1.0.7.5 : 2019-01-19 : 강제로 웹서비스 IQA 바라볼수있는 기능 추가(배포시 필요) * 1.0.7.6 : 2019-01-22 : zip파일명 검사 single quote , double quote 추가 오류처리(서버에서 오류난다고 함) * 1.0.7.7 : 2019-04-09 : 이노 컨버터 Windows 시스템 파일 경로 문자열 길이 문제 건 에러 처리 방안 추가 D:\INNOWHB\Check_List\file path check_날짜.txt 파일을 파일명 변경(file path check_날짜_시분초.txt)하여 이동 처리 -> D:\00_file_path_check\해당 파일 처리 진행 pass 후 다음 파일 진행 ZipfileBackupProc : 추후 안정화 되면 BACKUP 처리 젤 마지막에 처리하자 */ delegate void TimerEventFiredDelegate(); public frmMain() { InitializeComponent(); } private void StartTmrServiceBtn() { //tmrServiceBtn.Change(0, 2000); if (timer != null) { if (!timer.Enabled) { timer.Enabled = true; timer.Start(); } } } private void EndTimerServiceBtn() { //tmrServiceBtn.Change(Timeout.Infinite, Timeout.Infinite); if (timer != null) { timer.Enabled = false; timer.Stop(); } } private void KillConvertor(Boolean bSti) { string findProcessName = ""; if (bSti) { findProcessName = "QMS Export.exe"; } else { findProcessName = "QMS-W"; } Process[] allProc = Process.GetProcesses(); foreach (Process p in allProc) { if (p.ProcessName.IndexOf(findProcessName) >= 0) { p.Kill(); break; } } } private void TestProc() { /* runServyceType2RunConvertor("CSFB", @"D:\FTP16\WORK\본사_도로2조_CSFB_SKT_AUTO_청주시서원십_20180829", false); Thread.Sleep(2000); runServyceType2RunConvertor("LTED", @"D:\FTP16\WORK\본사_도로501조_LTED_SKT_AUTO_테스트_20180602", false); Thread.Sleep(2000); runServyceType2RunConvertor("LTED", @"D:\FTP16\WORK\인천본부_인빌딩46조_LTED_SKT_AUTO_소래포구 종합어시장_20180827", false); //FileProcess row = GetFilePath2FileProcessInfo(@"D:\FTP16\WORK\충북본부_도로49조_HSDPA__KT_청주대2일차_20181210.zip"); //FileProcess row = GetFilePath2FileProcessInfo(@"D:\FTP16\WORK\경남본부_도로41조_HDV_LGU_부산지하철2호선aaa_20181210.zip"); string extractDir = @"D:\FTP14\test2"; string zipFilefullPath = @"D:\FTP14\7ziptest.zip"; SevenZipCall("x -o\"" + extractDir + "\" -r -y \"" + zipFilefullPath + "\""); return; */ //FileProcess row = GetFilePath2FileProcessInfo(@"D:\FTP16\WORK\강북본부_도로47조_LTEV_SKT_AUTO_동대문구청 보건소_20181214.zip"); //ZipFileNamingParsing(row); /* FileInfo file = new FileInfo(@"D:\FTP16\WORK\본사_도로2조_LTED_SKT_L5_고양시 일산동구_20181115_20181207134958.zip"); if (file.Exists) { MessageBox.Show("존재"); } else { MessageBox.Show("미존재"); } */ //FileProcess row = GetFilePath2FileProcessInfo(@"D:\FTP16\WORK\강북본부_도로407조_LTEV_SKT_AUTO_롯데_20181205.zip"); //DeleteWorkZipFile(@"D:\FTP16\WORK\강북본부_도로407조_LTEV_SKT_AUTO_롯데_20181205"); //Boolean bAccessible = util.Wait2FileAccessible(@"D:\FTP16\WORK\본사_도로2조_LTED_SKT_L5_고양시 일산동구_20181115_20181207134958.zip", 9999); /* string zipFileName = "강북본부_도로407조_LTEV_SKT_AUTO_롯데_20181201_20181205132239.zip"; string[] arFileInfo = zipFileName.Split('_'); var fileWorkDate = arFileInfo[arFileInfo.Length - 1]; fileWorkDate = Path.GetFileNameWithoutExtension(fileWorkDate); fileWorkDate = fileWorkDate = fileWorkDate.Substring(0, 8); DateTime dtFileWirkDate = new DateTime(); Boolean isDate = util.ParseDate(fileWorkDate, ref dtFileWirkDate); if (!isDate) { Console.WriteLine("1"); } else { Console.WriteLine("0"); } */ var zipFileName = "본사_도로2조_LTED_SKT_L5_고양시 일산동구_20181115_20181207134958.zip"; //string zipFileName = $@"<div>""{title}""</div>" if (zipFileName.IndexOf("\"") >= 0) { Console.WriteLine("1"); } } private void frmMain_Load(object sender, EventArgs e) { this.Text = String.Format("IQA 컨트롤러 ver : [{0}]", m_version); ; //최소 윈도우 사이즈 this.MinimumSize = new Size(800, 600); iqaService.mainForm = this; //TestProc(); //return; #if DEBUG m_debug = true; #else m_debug = false; #endif if (!DBContollerSetInfo(false)) { MessageBox.Show("컨트롤러 실행에 필요한 데이타를 가져오는데 실패하였습니다.\n관리자에게 문의하십시요."); this.Close(); Application.Exit(); return; } SetControl(); UpdateRowEnv(); //findDirErrorInfo(Define.con_DIR_ZIPDUP); zip파일 중복체크 안하기로 함 FindDirErrorInfo(Define.con_DIR_NAMING); FindDirErrorInfo(Define.con_DIR_UPLOAD); FindDirErrorInfo(Define.con_DIR_CONVERT); CreateFolderWatching(); m_bServiceOnOffButton = false; ServiceOnOff(); } /* 작업중 비정상 종료된 Zip파일 리스트를 가져온다. */ private void GetAbnormalZipfileList2Grid() { string startDate = dtpStartDate.Value.Date.ToString("yyyyMMdd"); string endDate = dtpEndDate.Value.Date.ToString("yyyyMMdd"); string procServer = GetFtpName(m_ftpId); dgvAbnormalZipfile.Rows.Clear(); List<ZipfileInfoEntity> abNormalZipfiles = iqaService.getAbnormalZipfileList(startDate, endDate, procServer); if (abNormalZipfiles == null || abNormalZipfiles.Count <=0) { return; } string fullPath = ""; string findZipfileNm = ""; string defaultPath = GetDefaultFtpPath(); string backupDir = defaultPath + "\\" + Define.con_DIR_BACK; string wokrDir = defaultPath + "\\" + Define.con_DIR_WORK; Boolean bFine = false; string findDirFlag = ""; foreach(ZipfileInfoEntity zipfileInfo in abNormalZipfiles) { //기본 FTP 폴더에서 찾는다 findZipfileNm = GetSystemZipfileNm2OrgFIleName(zipfileInfo.Zipfile_nm); bFine = util.FindDir2File(defaultPath, findZipfileNm, ref fullPath); if (!bFine) { //BACKUP 폴더에서 찾는다. findZipfileNm = zipfileInfo.Zipfile_nm; bFine = util.FindDir2File(backupDir, findZipfileNm, ref fullPath); if (bFine) { findDirFlag = "backup"; } else { //WORK 폴더에서 찾는다. bFine = util.FindDir2File(wokrDir, findZipfileNm, ref fullPath); if (bFine) { findDirFlag = "work"; } } } else { findDirFlag = "root"; } dgvAbnormalZipfile.RowCount = dgvAbnormalZipfile.RowCount + 1; int nRow = dgvAbnormalZipfile.RowCount - 1; DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dgvAbnormalZipfile.Rows[nRow].Cells[0]; chk.Value = true; dgvAbnormalZipfile.Rows[nRow].Cells[1].Value = zipfileInfo.Zipfile_nm; dgvAbnormalZipfile.Rows[nRow].Cells[2].Value = zipfileInfo.Cur_state; if (bFine) { dgvAbnormalZipfile.Rows[nRow].Cells[3].Value = "발견"; dgvAbnormalZipfile.Rows[nRow].Cells[4].Value = fullPath; dgvAbnormalZipfile.Rows[nRow].Cells[5].Value = findDirFlag; } else { dgvAbnormalZipfile.Rows[nRow].Cells[3].Value = "미발견"; dgvAbnormalZipfile.Rows[nRow].Cells[4].Value = ""; dgvAbnormalZipfile.Rows[nRow].Cells[5].Value = ""; } } //전체 선택 해제시 체크 선택되있을시 안그려지는 갱신 안되는 문제 때문(화면상에만) if (dgvAbnormalZipfile.Rows.Count > 0) { dgvAbnormalZipfile.CurrentCell = dgvAbnormalZipfile.Rows[0].Cells[1]; } } /* 이벤트 DRM 파일 요청건 FTP 전송 및 DB 처리 */ private void EventOrifileSendProc() { //그떄그떄 가져온다. CommonResultEntity resServer = iqaService.getControllerServer(true); if (resServer.Flag == Define.con_FAIL) { util.Log("ERR:eventOrifileSendProc", "이벤트 DRM FTP 서버 정보 가져오기 실패"); return; } m_lstServer = (List<ControllerServerEntity>)resServer.Result; //ControllerServerEntity freeFtpServer = m_dicFtpInfo[Define.con_FTP_DRM]; ControllerServerEntity freeFtpServer = m_lstServer[0]; if (freeFtpServer == null) { util.LogDrm("ERR:eventOrifileSendProc", "이벤트 DRM FTP 서버 정보 가져오기 실패"); return; } //util.Log("INFO", "Drm 요청파일 가져오기"); string procServer = GetFtpName(m_ftpId); CommonResultEntity res = iqaService.getEventOrifileList(procServer); if (res.Flag == Define.con_FAIL) { util.LogDrm("ERR", "Drm 요청파일 가져오기 실패"); return; } List<EventOriFileEntity> sendFileInfos = (List<EventOriFileEntity>)res.Result; if (sendFileInfos == null || sendFileInfos.Count <=0) { util.LogDrm("INFO", "Drm 요청건수 0"); return; } util.LogDrm("INFO", "EVENT DRM 요청 발생 처리 시작 ##################################START"); //sendFileInfos 발견여부도 추후 DB에 남기자 EventOriFileProcResult eventOriFileResult = new EventOriFileProcResult(); eventOriFileResult.ProcServer = procServer; eventOriFileResult.FtpServer = freeFtpServer.Name; //BACKUP 폴도에서 해당 ZIP파일 찾아서 FTP로 전송한다. string findZipFileName = sendFileInfos[0].Zipfile_nm; eventOriFileResult.ZipfileNm = findZipFileName; updateRowEventDrmFileSend(eventOriFileResult); //추후 테스트후 적용하자 //iqaService.updateEventOrifileSendResult(eventOriFileResult, sendFileInfos); string defaultPath = GetDefaultFtpPath(); string backupDir = defaultPath + "\\" + Define.con_DIR_BACK; string[] filePaths = Directory.GetFiles(backupDir); string orgZipFilePath = ""; int nfindPos = 0; Boolean bFindZipFile = false; eventOriFileResult.CurState = Define.con_EVENT_DRM_STATE_DRM; foreach (string filePath in filePaths) { nfindPos = filePath.LastIndexOf('_'); if (nfindPos >= 0) { //orgZipFilePath = filePath.Substring(0, nfindPos); //DB에 Zip파일 원본이름 줄경우 orgZipFilePath = filePath; //DB에 해당날짜까지 시스템날짜까지 들어있는 ZIPfileName 정보를 줄경우 if (Path.GetFileNameWithoutExtension(findZipFileName) == Path.GetFileNameWithoutExtension(orgZipFilePath)) { util.LogDrm("INFO", "ZIP파일 발견 및 복사: "+ Path.GetFileNameWithoutExtension(findZipFileName)); //폴더이동후 필요한 drm파일만 남기고 삭제한후 다시 압축후 전송한다. if (!util.FileSave("copy", filePath, defaultPath + '\\' + Define.con_DIR_EVENT_ORIFILE+'\\'+ findZipFileName)) { return; } string zipPath = defaultPath + "\\" + Define.con_DIR_EVENT_ORIFILE +"\\"+ findZipFileName; string extractPath = defaultPath + "\\" + Define.con_DIR_EVENT_ORIFILE + "\\" + Path.GetFileNameWithoutExtension(findZipFileName); string eventZipFileName = getEventCompressName(); try { //ZipFile.ExtractToDirectory(zipPath, extractPath); //압축 해제 string extractDir = extractPath + @"\"; SevenZipCall("x -o\"" + extractDir + "\" -r -y \"" + zipPath + "\""); string[] extractFilePaths = Directory.GetFiles(extractPath); string sendFilePath = defaultPath + @"\" + Define.con_DIR_EVENT_ORIFILE + @"\" + eventZipFileName; //FTP 전송 요청한 파일만 담는 작업 폴더 만든다. DirectoryInfo diChk = new DirectoryInfo(sendFilePath); if (diChk.Exists == false) { diChk.Create(); } Boolean bMatch = false; int nOriFileCnt = 0; foreach (string extractFilePath in extractFilePaths) { //string extractFileName = Path.GetFileName(extractFilePath); string extractFileName = Path.GetFileNameWithoutExtension(extractFilePath); string extenstion = Path.GetExtension(extractFilePath); if (!(extenstion.ToUpper() == ".DRM" || extenstion.ToUpper() == ".DRMMP" || extenstion.ToUpper() == ".DML")) { continue; } //string remQmsFileNm = ""; foreach (EventOriFileEntity sendFileInfo in sendFileInfos) { //Event 요청 파일명과 같을경우 작업 폴더에 복사한다. //확장자 drm , drmmp 같이 복사한다 string sendFileName = Path.GetFileNameWithoutExtension(sendFileInfo.Qmsfile_nm); if (sendFileName == extractFileName) { util.LogDrm("INFO", "DRM 파일 발견 및 복사: " + sendFileName); bFindZipFile = true; bMatch = true; //DRM , DRMMP 같은 이름 유지하기위해 실제 DRMMP는 DB쪽 요청정보에는 없기떄문에 같은이름으로 파일을 관리해야한다 if (sendFileInfo.Qmsfile_nmChg.Length <= 0) { //if (remQmsFileNm != sendFileInfo.Qmsfile_nmChg) //{ nOriFileCnt++; // remQmsFileNm = sendFileInfo.Qmsfile_nmChg; //} sendFileInfo.Qmsfile_nmChg = eventZipFileName + "_" + nOriFileCnt; } //util.FileSave("copy", extractFilePath, sendFilePath + "\\" + extractFileName + extenstion); util.FileSave("copy", extractFilePath, sendFilePath + "\\" + sendFileInfo.Qmsfile_nmChg + extenstion); util.LogDrm("INFO", "DRM 파일 발견 및 복사 완료: " + sendFileName); sendFileInfo.FlagFind = "1"; } } } if (!bMatch) { break; } //요청한 파일 압축한다. ㅠㅠ 실제 FTP서버에서 같은 닷넷프레임워크 버전인데 특정파일에 대해 ZipFIle 처리 안됨 //ZipFile.CreateFromDirectory(sendFilePath, defaultPath + "\\" + Define.con_DIR_EVENT_ORIFILE + "\\" + eventZipFileName + ".zip", CompressionLevel.Fastest, false, Encoding.Default); util.LogDrm("INFO", "DRM 요청파일 압축"); string compressZipFile = defaultPath + "\\" + Define.con_DIR_EVENT_ORIFILE + "\\" + eventZipFileName + ".zip"; SevenZipCall("a \"" + compressZipFile + "\" \"" + sendFilePath + "\"" + @"\*"); //압축시 해당 파일만 압축하기위해 \* 을 추가함 eventOriFileResult.FlagUnzip = Define.con_SUCCESS; } catch (Exception ex) { eventOriFileResult.FlagUnzip = Define.con_FAIL; eventOriFileResult.UnzipErrLog = ex.Message.ToString(); util.LogDrm("ERR", ex.Message.ToString()); } if (eventOriFileResult.FlagUnzip == Define.con_SUCCESS) { eventOriFileResult.CurState = Define.con_EVENT_DRM_STATE_FTP; updateRowEventDrmFileSend(eventOriFileResult); //FTP로 전송한다. //bool bSuccess = sendFtpEventOrifile(freeFtpServer, defaultPath + "\\" + Define.con_DIR_EVENT_ORIFILE + "\\" + eventZipFileName + ".zip"); util.LogDrm("INFO", "DRM파일요청 FTP 전송"); bool bSuccess = sendSftpEventOrifile(defaultPath + "\\" + Define.con_DIR_EVENT_ORIFILE + "\\" + eventZipFileName + ".zip", freeFtpServer); if (bSuccess) { util.LogDrm("INFO", "DRM파일요청 FTP 전송 성공"); eventOriFileResult.FlagSendFtp = Define.con_SUCCESS; eventOriFileResult.ChgCompressFileNm = eventZipFileName + ".zip"; } else { util.LogDrm("ERR", "DRM파일요청 FTP 전송 실패"); eventOriFileResult.FlagSendFtp = Define.con_FAIL; } updateRowEventDrmFileSend(eventOriFileResult); } //작업파일 모두 삭제 한다. util.AllDeleteInDirectory(defaultPath + "\\" + Define.con_DIR_EVENT_ORIFILE); break; } } } eventOriFileResult.CurState = Define.con_EVENT_DRM_STATE_END; if (bFindZipFile) { eventOriFileResult.IsDrmFind = "1"; } else { eventOriFileResult.IsDrmFind = "0"; } iqaService.updateEventOrifileSendResult(eventOriFileResult, sendFileInfos); updateRowEventDrmFileSend(eventOriFileResult); util.Log("INFO", "EVENT DRM 요청 발생 처리 완료 #####################################END"); } private void compressTest() { // 참조 소스 // https://docs.microsoft.com/ko-kr/dotnet/api/system.io.compression.zipfile?view=netframework-4.7.2 try { //압축 하기 string startPath = @"D:\FTP14\TEST\본사_도로501조_LTED_SKT_AUTO_압축테스트_20180602"; string zipPath = @"D:\FTP14\TEST\test.zip"; ZipFile.CreateFromDirectory(startPath, zipPath ,CompressionLevel.Fastest,false,Encoding.Default); /*압축해제 예제 string zipPath = @"D:\FTP14\TEST\본사_도로2조_CSFB_SKT_AUTO_청주시서원구_20180829.zip"; string extractPath = @"D:\FTP14\TEST\본사_도로2조_CSFB_SKT_AUTO_청주시서원구_20180829"; ZipFile.ExtractToDirectory(zipPath, extractPath); */ } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return; //ZipFile.ExtractToDirectory(zipPath, extractPath); } /* 환경설정 파일 보관주기에 따른 삭제 처리 * */ private void FilePeriodChk2Proc() { string path = GetDefaultFtpPath(); if (!(m_lstFile != null && m_lstFile.Count > 0)) { return; } string ftpName = GetFtpName(m_ftpId); foreach (ControllerFileKeepEntity filePeriodInfo in m_lstFile) { string dirPath = filePeriodInfo.DirPath; if (dirPath.Length <= 0) { continue; } //해당 FTP서버 속하면 삭제 처리한다. if (dirPath.IndexOf(ftpName) <= 0) { continue; } if (!Directory.Exists(dirPath)){ continue; } //해당 디렉토리내 파일 삭제 string[] files = Directory.GetFiles(dirPath); int period = Convert.ToInt16(filePeriodInfo.Period); foreach (string file in files) { FileInfo fi = new FileInfo(file); /* string fileName = Path.GetFileName(fi.Name); if (fileName == "인천본부_도로54조_HSDPA_SKT_AUTO_덕적도_20181109_20181107162054.zip") { Console.WriteLine("dd"); } */ DateTime dtDate = fi.LastWriteTime; dtDate = dtDate.AddDays(period); //보관 기간 int nCompare = DateTime.Compare(dtDate, DateTime.Now); if (nCompare < 0) { fi.Delete(); } } //해당 폴더내 서브 디렉토리 삭제 처리 string[] dirs = Directory.GetDirectories(dirPath); foreach (string dir in dirs) { DirectoryInfo dirInfo = new DirectoryInfo(dir); DateTime dtDate = dirInfo.LastWriteTime; dtDate = dtDate.AddDays(period); //보관 기간 int nCompare = DateTime.Compare(dtDate, DateTime.Now); if (nCompare < 0) { dirInfo.Delete(true); } } } } /* 서비스 감시 버튼 깜빡깜빡 처리 */ void serviceBtnBlinkProc() { if (m_bServiceOnOffButton) { if (btnService.BackColor == Color.Silver) btnService.BackColor = Color.Red; else btnService.BackColor = Color.Silver; } else { if (!m_ServiceOnIng) btnService.BackColor = Color.Silver; } } void tmr_ServiceBtnBlink(object sender, ElapsedEventArgs e) { if (this.IsHandleCreated) { BeginInvoke(new TimerEventFiredDelegate(serviceBtnBlinkProc)); } } private void SetControlServiceBtnOnOff() { if (m_bServiceOnOffButton) { cboFtpServer.Enabled = false; btnService.Text = "서비스 On 상태"; StartTmrServiceBtn(); } else { cboFtpServer.Enabled = true; if (m_ServiceOnIng) { btnService.Text = "서비스 Off 처리중..."; btnService.Enabled = false; } else { EndTimerServiceBtn(); btnService.Text = "서비스 Off 상태"; btnService.Enabled = true; btnService.BackColor = Color.Silver; } } } /* private void setControlServiceOnOff() { if (m_bServiceOnOffButton) { cboFtpServer.Enabled = false; btnService.Text = "서비스 On 상태"; serviceOnMainProc(); } else { cboFtpServer.Enabled = true; if (m_ServiceOnIng) { btnService.Text = "서비스 Off 처리중..."; btnService.Enabled = false; } else { EndTimerServiceBtn(); btnService.Text = "서비스 Off 상태"; btnService.Enabled = true; btnService.BackColor = Color.Silver; } } } */ private void SetLog(FileProcess row, string flag , string message) { AddLogFile(row, flag, message); this.Invoke(new Action(delegate () { dgvProcessLog.RowCount = dgvProcessLog.RowCount + 1; int nRow = dgvProcessLog.RowCount - 1; dgvProcessLog.Rows[nRow].Cells[0].Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); ; if (row != null) { dgvProcessLog.Rows[nRow].Cells[1].Value = row.MeasuBranch; dgvProcessLog.Rows[nRow].Cells[2].Value = row.MeasuGroup; dgvProcessLog.Rows[nRow].Cells[3].Value = row.ZipFileName; //dgvProcessLog.Rows[nRow].Cells[Define.con_KEY_PROCESSLOG_COLIDX].Value = row.OrgZipFileName; dgvProcessLog.Rows[nRow].Cells[Define.con_KEY_PROCESSLOG_COLIDX].Value = row.ZipFileName; } else { dgvProcessLog.Rows[nRow].Cells[3].Value = "Global"; } dgvProcessLog.Rows[nRow].Cells[4].Value = message; })); //Console.WriteLine(message); } private void UpdateRowEnv() { m_lstEnv.Clear(); if (m_lstServer == null || m_lstServer.Count <= 0) { util.Log("ERR:DBContollerSetInfo", "기본설정정보 없음"); return; } foreach (ControllerServerEntity server in m_lstServer) { ControllerEnvEntity env = new ControllerEnvEntity(); env.Flag = "server"; env.Item = server.Name; env.Info1 = "IP : " + server.Ip; env.Info2 = "ID : " + server.Id; env.Info3 = "PW : " + server.Password; m_lstEnv.Add(env); #if DEBUG if (server.Name == "TEST_APP") { m_dicFtpInfo[Define.con_FTP_WAV] = server; //m_dicFtpInfo[Define.con_FTP_DRM] = server; m_dicFtpInfo[Define.con_FTP_QMS] = server; } #else if (server.Name == "QMS3_WAV") { m_dicFtpInfo[Define.con_FTP_WAV] = server; } else if (server.Name == "QM3_DRM") { //m_dicFtpInfo[Define.con_FTP_DRM] = server; 처리시점에 가져오는방법으로 추가 요청 } else if (server.Name == "APP02") { m_dicFtpInfo[Define.con_FTP_QMS] = server; } #endif } foreach (ControllerFileKeepEntity file in m_lstFile) { ControllerEnvEntity env = new ControllerEnvEntity(); env.Flag = "file"; env.Item = file.Item; env.Info1 = "IP : " + file.DirPath; env.Info2 = "ID : " + file.Period.ToString() + "일"; env.Info3 = ""; m_lstEnv.Add(env); } int nRow = 0; this.Invoke(new Action(delegate () { dgvEnv.Rows.Clear(); //dgvEnv.RowCount = 0; foreach (ControllerEnvEntity env in m_lstEnv) { dgvEnv.RowCount = dgvEnv.RowCount + 1; nRow = dgvEnv.RowCount - 1; dgvEnv.Rows[nRow].Cells[1].Value = env.Item; dgvEnv.Rows[nRow].Cells[2].Value = env.Info1; dgvEnv.Rows[nRow].Cells[3].Value = env.Info2; dgvEnv.Rows[nRow].Cells[4].Value = env.Info3; } })); } /* 디렉토리 탐색후 Error 파일정보를 가져온다. */ private void FindDirErrorInfo(string flagErr) { string defaultPath = GetDefaultFtpPath(); string[] dirs = Directory.GetDirectories(defaultPath + "\\" + flagErr); string findExtention = ""; if (flagErr == Define.con_DIR_UPLOAD) { findExtention = "qms"; } else { findExtention = "zip"; } foreach (string dir in dirs) { string zipfileFullPath = ""; string[] files = Directory.GetFiles(dir, "*."+ findExtention); string zipfileNm = Path.GetFileName(dir+".zip"); //즉 폴더이름에 확장자 zip을 붙인다 - 오류 발생시 zip파일 이름 유지하기 위해 if (files.Length > 0) { zipfileFullPath = Path.GetDirectoryName(files[0]); //zipfileNm = Path.GetFileName(files[0]); FileProcess row = new FileProcess(); row.ZipFileName = zipfileNm; //zipfile 명 즉 폴더 이름 row.OrgZipFileName = files[0]; //zip파일명 시스템 날짜 붙이기전 원래 이름 row.ProcessServer = GetFtpName(m_ftpId); //process서버 명 row.ZipfileFullPath = zipfileFullPath; //파일명 규칙 오류 if (flagErr == Define.con_DIR_NAMING) { row.FileNameRule = Define.CON_MSG_ERROR; } else if (flagErr == Define.con_DIR_CONVERT) { row.ConversionFlag = Define.CON_MSG_ERROR; } else if (flagErr == Define.con_DIR_UPLOAD) { row.FtpSendFlag = Define.CON_MSG_COMPLETE; row.FtpSuccessFlag = Define.con_FAIL; string qmsFileNm = ""; //string qmsFileNmChg = ""; int nIdx = 0; foreach(string filePath in files) { //FileInfo file = new FileInfo(filePath); nIdx++; qmsFileNm = Path.GetFileName(filePath); ZipFileDetailEntity detail = new ZipFileDetailEntity(); detail.QmsfileNm = qmsFileNm; detail.QmsfileNmChg = GetQmsNameChange(Convert.ToString(nIdx)); row.ZipfileDetailList.Add(detail); ; } } else if (flagErr == Define.con_DIR_ZIPDUP) { row.ZipDupFlag = Define.CON_MSG_ERROR; } UpdateRowErrorFile(row); } } } //서버쪽 파일명 꺠지는 현상으로 qms파일 변경 처리 한다. private string GetQmsNameChange(string seq) { DateTime curDate = DateTime.Now; string qmsNmChg = GetFtpName(m_ftpId) + "_" + seq + "_" + curDate.ToString("yyyyMMddHHmmss.ffff") + ".qms"; return qmsNmChg; } private string getEventCompressName() { DateTime curDate = DateTime.Now; string eventZipName = GetFtpName(m_ftpId) + "_" + "Event" + "_" + curDate.ToString("yyyyMMddHHmmss"); return eventZipName; } private void UpdateRowErrorFile(FileProcess row) { //string sFileNm = row.OrgZipFileName; string sFileNm = row.ZipFileName; this.Invoke(new Action(delegate () { if (m_dicFileProcessErr.ContainsKey(sFileNm)) { m_dicFileProcessErr[sFileNm] = row; } else { m_dicFileProcessErr.Add(sFileNm, row); } dgvErrorFile.RowCount = dgvErrorFile.RowCount + 1; int nRow = dgvErrorFile.RowCount - 1; dgvErrorFile.Rows[nRow].Cells[1].Value = row.ProcessServer; dgvErrorFile.Rows[nRow].Cells[3].Value = row.ZipfileFullPath; dgvErrorFile.Rows[nRow].Cells[4].Value = row.ZipFileName; if (row.FileNameRule == Define.CON_MSG_ERROR) { dgvErrorFile.Rows[nRow].Cells[2].Value = "파일명규칙 Error"; dgvErrorFile.setCellButton("수정/파일이동", 5, nRow); } else if (row.FtpSendFlag == Define.CON_MSG_COMPLETE && row.FtpSuccessFlag == Define.con_FAIL) { dgvErrorFile.Rows[nRow].Cells[2].Value = "FTP 전송 Error"; dgvErrorFile.setCellButton("FTP 전송", 5, nRow); } else if (row.ZipDupFlag == Define.CON_MSG_ERROR) { dgvErrorFile.Rows[nRow].Cells[2].Value = "ZIP 파일 중복"; dgvErrorFile.setCellButton("수정/파일이동", 5, nRow); } else if (row.ConversionFlag == Define.CON_MSG_ERROR || row.ConversionFlag == Define.CON_MSG_ERROR_CONV_LEN) { dgvErrorFile.Rows[nRow].Cells[2].Value = "컨버전 Error"; dgvErrorFile.Rows[nRow].Cells[5].Value = "품질분석실-측정기장비업체 확인요망"; } //dgvErrorFile.Rows[nRow].Cells[Define.con_KEY_PROCESSERROR_COLIDX].Value = row.OrgZipFileName; dgvErrorFile.Rows[nRow].Cells[Define.con_KEY_PROCESSERROR_COLIDX].Value = row.ZipFileName; })); } /* * drm파일 */ private void updateRowEventDrmFileSend(EventOriFileProcResult eventDrmResult) { string sFileNm = eventDrmResult.ZipfileNm; int nRow = -1; this.Invoke(new Action(delegate () { //log파일 및 DB상에 기록 다 남기때문에 화면상 크게 기능이 없어서 최대 100건만 화면상 보여준다. if (dgvDrmFileSend.RowCount > 100) { dgvDrmFileSend.Rows.Clear(); //dgvDrmFileSend.RowCount = 0; } if (dgvDrmFileSend.RowCount <= 0) { dgvDrmFileSend.RowCount = dgvDrmFileSend.RowCount + 1; nRow = 0; } else { nRow = dgvDrmFileSend.getFindZipFile2RowIndex(sFileNm, Define.con_KEY_EVENTDRM_COLIDX); if (nRow <= 0) { nRow = dgvDrmFileSend.RowCount; dgvDrmFileSend.RowCount = dgvDrmFileSend.RowCount + 1; } } dgvDrmFileSend.Rows[nRow].Cells[0].Value = sFileNm; if (eventDrmResult.CurState == Define.con_EVENT_DRM_STATE_END) { if (eventDrmResult.IsDrmFind == "0") { dgvDrmFileSend.Rows[nRow].Cells[1].Value = "요청 Drm 파일 없음"; } } else { dgvDrmFileSend.Rows[nRow].Cells[1].Value = Define.CON_MSG_WAIT; dgvDrmFileSend.Rows[nRow].Cells[2].Value = Define.CON_MSG_WAIT; if (eventDrmResult.CurState == Define.con_EVENT_DRM_STATE_DRM || eventDrmResult.CurState == Define.con_EVENT_DRM_STATE_FTP) { if (eventDrmResult.FlagUnzip == Define.con_FAIL) { dgvDrmFileSend.Rows[nRow].Cells[1].Value = "Error"; } else if (eventDrmResult.FlagUnzip == Define.con_SUCCESS) { dgvDrmFileSend.Rows[nRow].Cells[1].Value = Define.CON_MSG_COMPLETE; } else { dgvDrmFileSend.Rows[nRow].Cells[1].Value = Define.CON_MSG_ING; } } if (eventDrmResult.CurState == Define.con_EVENT_DRM_STATE_FTP) { if (eventDrmResult.FlagSendFtp == Define.con_FAIL) { dgvDrmFileSend.Rows[nRow].Cells[2].Value = "Error"; } else if (eventDrmResult.FlagSendFtp == Define.con_SUCCESS) { dgvDrmFileSend.Rows[nRow].Cells[2].Value = Define.CON_MSG_COMPLETE; } else { dgvDrmFileSend.Rows[nRow].Cells[2].Value = Define.CON_MSG_ING; } } } })); } /* 파일처리현황 그리드에 값 반영한다. * */ private void UpdateRowFileProcess(FileProcess row) { //string sFileNm = row.OrgZipFileName; string sFileNm = row.ZipFileName; int nRow = -1; this.Invoke(new Action(delegate () { if (m_dicFileProcess.ContainsKey(sFileNm)) { nRow = dgvProcess.getFindZipFile2RowIndex(sFileNm, Define.con_KEY_PROCESS_COLIDX); if (nRow < 0) { if (dgvProcess.RowCount == 0) { nRow = 0; } else { nRow = dgvProcess.RowCount; } dgvProcess.RowCount = dgvProcess.RowCount + 1; } //m_dicFileProcess[sFileNm] = row; } else { dgvProcess.RowCount = dgvProcess.RowCount + 1; nRow = dgvProcess.RowCount - 1; m_dicFileProcess.Add(sFileNm, row); } dgvProcess.Rows[nRow].Cells[1].Value = row.ProcessServer; dgvProcess.Rows[nRow].Cells[2].Value = row.MeasuBranch; dgvProcess.Rows[nRow].Cells[3].Value = row.MeasuGroup; dgvProcess.Rows[nRow].Cells[4].Value = row.ZipFileName; dgvProcess.Rows[nRow].Cells[5].Value = row.FileNameRule; dgvProcess.Rows[nRow].Cells[6].Value = row.ExtractFlag; dgvProcess.Rows[nRow].Cells[7].Value = row.ConversionFlag; dgvProcess.Rows[nRow].Cells[8].Value = row.FtpSendFlag; dgvProcess.Rows[nRow].Cells[9].Value = row.BackupFlag; dgvProcess.Rows[nRow].Cells[Define.con_KEY_PROCESS_COLIDX].Value = row.ZipFileName; dgvProcess.Rows[nRow].Cells[11].Value = row.ZipfileFullPath; //선택된 row 활성화 스크롤 되게 dgvProcess.CurrentCell = dgvProcess.Rows[nRow].Cells[1]; // row.DefaultCellStyle.BackColor = Color.Red; /* 신규일경우 무조건 앞열에 추가하는 방법 - 테스트 필요 DataGridViewRow row1 = new DataGridViewRow(); row1.Cells[1].Value = row.ProcessServer; dgvProcess.Rows.Insert(0, row1); */ })); //Application.DoEvents(); } /* 원본 zip파일명 + sysdate * * */ private string GetZipfileNameAddSysdate(string orgFileName) { string onlyFileName = Path.GetFileNameWithoutExtension(orgFileName); string cur = DateTime.Now.ToString("yyyyMMddHHmmss"); onlyFileName = onlyFileName + "_" + cur; onlyFileName = onlyFileName + Path.GetExtension(orgFileName); return onlyFileName; } private string GetFtpName(string serverIdx) { return String.Format("FTP{0:00}", Convert.ToInt32(serverIdx)); } private string GetDir2FtpName() { string[] dirNames = Directory.GetDirectories(@"D:\"); string dirFtpName = ""; foreach(string dirName in dirNames) { if (dirName.IndexOf("FTP") >= 0) { dirFtpName = Path.GetFileName(dirName); break; } } return dirFtpName; } private void SetControlComboFtpServer() { //FTP Combo Setting string[] ftpServers = new string[16]; string tmpFtpName = ""; StringBuilder retSelFtp = new StringBuilder(); util.GetIniString("FTP", "SELECT", "", retSelFtp, 32, Application.StartupPath + "\\controllerSet.Ini"); string iniSelFtp = retSelFtp.ToString(); //저장된값이 없을경우 if (iniSelFtp.Length <= 0) { //D:\디렉토리에서 FTP정보 추출한다. iniSelFtp = GetDir2FtpName(); if (iniSelFtp.Length <= 0) { iniSelFtp = GetFtpName(m_ftpId); } } int nFtpSelIdx = -1; for (int idx = 0; idx < 16; idx++) { tmpFtpName = String.Format("FTP{0:00}", idx + 1); ftpServers[idx] = tmpFtpName; if (iniSelFtp == tmpFtpName) { nFtpSelIdx = idx; } } cboFtpServer.Items.AddRange(ftpServers); if (nFtpSelIdx < 0) { cboFtpServer.SelectedIndex = 13; } else { cboFtpServer.SelectedIndex = nFtpSelIdx; } } private void SetControl() { /* column percent example https://nickstips.wordpress.com/2010/11/10/c-listview-dynamically-sizing-columns-to-fill-whole-control/ //데이타 쓰기 http://blog.naver.com/PostView.nhn?blogId=inho860&logNo=220053153176&beginTime=0&jumpingVid=&from=search&redirect=Log&widgetTypeCall=true */ timer.Interval = 1000; // 1 시간 timer.Elapsed += new ElapsedEventHandler(tmr_ServiceBtnBlink); //tmrServiceBtn = new System.Threading.Timer(tmr_ServiceBtnBlink2); StartTmrServiceBtn(); SetControlComboFtpServer(); dgvProcess.addColumnButton("위치", "파일", 60); dgvProcess.addColumn("처리서버", 60); dgvProcess.addColumn("측정본부", 78); dgvProcess.addColumn("측정조", 80); dgvProcess.addColumn("zip 파일명", 300); dgvProcess.addColumn("파일명규칙", 100); dgvProcess.addColumn("압축해제", 80); dgvProcess.addColumn("컨버전", 80); dgvProcess.addColumn("FTP 전송", 95); dgvProcess.addColumn("백업", 80); dgvProcess.addColumn("원본 zip 파일명", 300); dgvProcess.addColumn("최종작업폴더", 300); dgvProcess.Columns[Define.con_KEY_PROCESS_COLIDX].Visible = false; dgvProcess.Columns[11].Visible = false; dgvProcessLog.addColumn("일시", 120); dgvProcessLog.addColumn("측정본부", 78); dgvProcessLog.addColumn("측정조", 80); dgvProcessLog.addColumn("zip 파일명", 400); dgvProcessLog.addColumn("로그", 200); dgvProcessLog.addColumn("원본 zip 파일명", 300); dgvProcessLog.Columns[Define.con_KEY_PROCESSLOG_COLIDX].Visible = false; dgvErrorFile.addColumnButton("위치", "파일", 60); dgvErrorFile.addColumn("처리서버", 60); dgvErrorFile.addColumn("Error 분류", 120); dgvErrorFile.addColumn("파일 Path", 200); dgvErrorFile.addColumn("zip 파일명", 320); dgvErrorFile.addColumn("파일 재처리", 150); dgvErrorFile.addColumn("원본 zip 파일명", 300); dgvErrorFile.Columns[Define.con_KEY_PROCESSERROR_COLIDX].Visible = false; //dgvEnv.addColumnButton("관리", "위치",60); dgvEnv.addColumnButton("관리","수정", 60); dgvEnv.addColumn("항목", 200); dgvEnv.addColumn("등록정보1", 250); dgvEnv.addColumn("등록정보2", 150); dgvEnv.addColumn("등록정보3", 150); dgvDrmFileSend.addColumn("zip 파일명", 400); dgvDrmFileSend.addColumn("drm 파일 추출", 150); dgvDrmFileSend.addColumn("FTP 전송", 100); dgvAbnormalZipfile.addColumnCheckBox("적용", true, 40); dgvAbnormalZipfile.addColumn("zip 파일명", 400); dgvAbnormalZipfile.addColumn("CUR_STATE", 100); dgvAbnormalZipfile.addColumn("존재여부", 60); dgvAbnormalZipfile.addColumn("파일 위치", 550); dgvAbnormalZipfile.addColumn("파일위치FLAG", 550); dgvAbnormalZipfile.Columns[5].Visible = false; } private void btnWindowFinder_Click(object sender, EventArgs e) { Exec("explorer.exe", ""); } private Boolean isFileValidate(string fileName) { return true; } /* Zip 파일 명 체크 modify log : 2018-12-11 파일명 규칙은 구분자 , 도로/인빌딩 구분 , 날짜형식 및 날짜 유효기간만 체크한다. */ private Boolean ZipFileNamingParsing(FileProcess row ) { //진행중 보여줘야하면 아래 풀자 //row.CurState = Define.con_STATE_START_NAMING; //iqaService.updateZipfileInfo(row, Define.con_ING_START); //복사할 경로에 해당 파일 유무 체크 string path = GetDefaultFtpPath(); //string onlyFileName = Path.GetFileName(fileName); string withoutExtensionName = Path.GetFileNameWithoutExtension(row.ZipFileName); string sMoveDir = Path.GetFileNameWithoutExtension(row.ZipFileName); string sWorkFileFullName = row.ZipfileFullPath + "\\" + row.ZipFileName; string sMoveFileFullName = path + "\\" + Define.con_DIR_NAMING + "\\" + sMoveDir + "\\" + row.OrgZipFileName; string[] arFileName = withoutExtensionName.Split('_'); string sFileDate = ""; DateTime dtDate = new DateTime(); DateTime dtMaxDate; string comp = ""; //오류나더라도 기본정보는 WEB 화면에 보여주게 하기 위해서 if (arFileName.Length >= 4) { row.MeasuBranch = arFileName[0]; row.MeasuGroup = arFileName[1]; row.ServiceType = arFileName[2]; comp = arFileName[3]; } if (arFileName.Length != 8) //뒤에 시스템 날짜 더 붙임 { SetLog(row, "WARN", "구분자 오류"); return false; } if (row.ZipFileName.IndexOf("'") >= 0) { SetLog(row, "WARN", "quote"); return false; } if (row.ZipFileName.IndexOf("\"") >= 0) { SetLog(row, "WARN", "double quote"); return false; } //<START> ############# 파일 유효 기간 체크 sFileDate = arFileName[6]; //bool bSuccess = DateTime.TryParse(sFileDate, out dtDate); Boolean isDate = util.ParseDate(sFileDate, ref dtDate); if (!isDate) { SetLog(row, "WARN", "날짜형식 오류"); return false; } //dtDate = DateTime.ParseExact(sFileDate, "yyyyMMdd", null); dtMaxDate = dtDate.AddDays(30); //최대 30일 유효범위임 int nCompare = DateTime.Compare(dtMaxDate, DateTime.Now); if (nCompare < 0) { SetLog(row, "WARN", "유효기간 오류"); return false; } string serviceType = row.ServiceType; serviceType = serviceType.ToUpper(); if (!(serviceType == "LTED" || serviceType == "LTEV" || serviceType == "HDV" || serviceType == "HDVML" || serviceType == "CSFB" || serviceType == "CSFBML" || serviceType == "HSDPA" || serviceType == "5G")) { SetLog(row, "WARN", "서비스 유형 오류"); return false; } /* row.MeasuBranch = arFileName[0]; row.MeasuGroup = arFileName[1]; row.ServiceType = arFileName[2]; row.Comp = arFileName[3]; */ //아래 부분 null인경우 체크할지는 서버단 필요시 처리 if (row.MeasuGroup.IndexOf("도로") >= 0) { row.InoutType = "OUTDOOR"; } else if (row.MeasuGroup.IndexOf("인빌딩") >= 0) { row.InoutType = "INDOOR"; } else { row.InoutType = ""; } if (comp == "SKT") { row.Comp = "011"; } else if (comp == "KT") { row.Comp = "016"; } else if (comp == "LGU") { row.Comp = "019"; } else { row.Comp = ""; } /* 2018-12-11 체크 하지 않는다. if (!(row.Comp == "011" || row.Comp == "016" || row.Comp == "019")) { row.Comp = ""; SetLog(row, "WARN", "사업자 오류"); return false; } */ if (row.InoutType == "") { SetLog(row, "WARN", "Outdoor/Indoor 오류"); return false; } row.MeasuDate = sFileDate; row.FileNameRule = Define.CON_MSG_COMPLETE; row.CurState = Define.con_STATE_COMPLETE_NAMING; //iqaService.updateZipfileInfo(row, Define.con_ING_START); return true; } private void AddLogFile(FileProcess row , string flag , string msg) { string zipfileName = ""; if (row != null) { zipfileName = row.ZipFileName; } else { zipfileName = "Global"; } util.Log(flag, zipfileName + " ==> " + msg); } private Boolean setFilePeriodInfo() { CommonResultEntity resFile = iqaService.getControllerFilePeriod(false); if (resFile == null) { util.Log("ERR:DBContollerSetInfo", "Web Server 연결 실패"); return false; } if (resFile.Flag == Define.con_FAIL) { util.Log("ERR:DBContollerSetInfo", "파일보관주기 정보 없음"); m_lstFile = null; return false; } else { m_lstFile = (List<ControllerFileKeepEntity>)resFile.Result; } return true; } private Boolean DBContollerSetInfo(bool bWait) { CommonResultEntity resFile = iqaService.getControllerFilePeriod(bWait); if (resFile == null) { util.Log("ERR:DBContollerSetInfo", "Web Server 연결 실패"); return false; } if (resFile.Flag == Define.con_FAIL) { util.Log("ERR:DBContollerSetInfo", "파일보관주기 정보 없음"); return false; } else { m_lstFile = (List<ControllerFileKeepEntity>)resFile.Result; } CommonResultEntity resServer = iqaService.getControllerServer(false); if (resServer.Flag == Define.con_FAIL) { util.Log("ERR:DBContollerSetInfo", "서버정보 없음"); return false; } else { m_lstServer = (List<ControllerServerEntity>)resServer.Result; } m_lstEnv.Clear(); if (m_lstServer == null || m_lstServer.Count <= 0) { util.Log("ERR:DBContollerSetInfo", "기본설정정보 없음"); return false; } /* foreach (ControllerServerEntity server in m_lstServer) { ControllerEnvEntity env = new ControllerEnvEntity(); env.Flag = "server"; env.Item = server.Name; env.Info1 = "IP : " + server.Ip; env.Info2 = "ID : " + server.Id; env.Info3 = "PW : " + server.Password; m_lstEnv.Add(env); #if DEBUG if (server.Name == "TEST_APP") { m_dicFtpInfo[Define.con_FTP_WAV] = server; m_dicFtpInfo[Define.con_FTP_DRM] = server; m_dicFtpInfo[Define.con_FTP_QMS] = server; } #else if (server.Name == "QMS3_WAV") { m_dicFtpInfo[Define.con_FTP_WAV] = server; } else if (server.Name == "QM3_DRM") { m_dicFtpInfo[Define.con_FTP_DRM] = server; } else if (server.Name == "APP02") { m_dicFtpInfo[Define.con_FTP_QMS] = server; } #endif } foreach (ControllerFileKeepEntity file in m_lstFile) { ControllerEnvEntity env = new ControllerEnvEntity(); env.Flag = "file"; env.Item = file.Item; env.Info1 = "IP : " + file.DirPath; env.Info2 = "ID : " + file.Period.ToString() + "일"; env.Info3 = ""; m_lstEnv.Add(env); } */ return true; } /* DB 중복 ZIP FILE 명 체크 - */ /* private Boolean dbZipFileDupChk(string zipFileNm) { NameValueCollection postData = new NameValueCollection(); postData.Add("zipfileNm", HttpUtility.UrlEncode(zipFileNm)); string uri = Define.CON_WEB_SERVICE + "manage/getZipFileDupChk.do"; WebClient webClient = new WebClient(); string pagesource = Encoding.UTF8.GetString(webClient.UploadValues(uri, postData)); try { SaveResultInfo result = (SaveResultInfo)Newtonsoft.Json.JsonConvert.DeserializeObject(pagesource, typeof(SaveResultInfo)); if (result.Flag == 1) return true; else return false; } catch (Exception ex) { util.Log("ERR:dbZipFileDupChk", ex.Message); Console.WriteLine(ex.Message.ToString()); return false; } } */ /* 사용안함 private Boolean dbUpdateQmsFile(FileProcess row) { if (row.QmsFileList.Count <= 0) { return true; } List<string> lstQmsfile = new List<string>(); List<string> lstChgFlie = new List<string>(); List<string> lstFlagSend = new List<string>(); foreach (QmsFileInfo qmsInfo in row.QmsFileList) { lstQmsfile.Add(HttpUtility.UrlEncode(qmsInfo.FileName)); lstChgFlie.Add(qmsInfo.ChgFlieName); lstFlagSend.Add(qmsInfo.FlagSend); } string qmsStr = getJsonStr(lstQmsfile); string chgQmsStr = getJsonStr(lstChgFlie); string flagSendStr = getJsonStr(lstFlagSend); NameValueCollection postData = new NameValueCollection(); postData.Add("zipfileNm", HttpUtility.UrlEncode(row.ZipFileName)); postData.Add("qmsFileNm", qmsStr); postData.Add("chgQmsFileNm", chgQmsStr); postData.Add("flagFtpSend", flagSendStr); return true; } */ //unzip 파일정보 업데이트 한다. private void unzipFileDetailProc(FileProcess row , string dupChkDir) { string[] fileEntries = Directory.GetFiles(dupChkDir); string extension = ""; string onlyFileName = ""; foreach (string fileName in fileEntries) { extension = Path.GetExtension(fileName); onlyFileName = Path.GetFileName(fileName); if (extension == ".drm" || extension == ".dml") { ZipFileDetailEntity detail = new ZipFileDetailEntity(); detail.UnzipfileNm = onlyFileName; row.ZipfileDetailList.Add(detail); } } CommonResultEntity res = iqaService.setUnzipFileInfoUpdateAndGetDupInfo(row); if (res.Flag == Define.con_FAIL) { return; } List<CodeNameEntity> dupList = (List<CodeNameEntity>)res.Result; if (dupList == null) { return; } if (dupList.Count > 0) { //컨버전에서 제외하기 위해 해당 파일 제거한다. foreach (CodeNameEntity tmp in dupList) { File.Delete(dupChkDir + "\\" + tmp.Code); } } } private void Err2FileMoveConversion(FileProcess row) { string path = GetDefaultFtpPath(); //string sMoveDir = Path.GetFileNameWithoutExtension(row.ZipFileName); //string sWorkFileFullName = row.GetWorkFileFullPathName(); string sWorkFileFullName = row.GetZipfileFullPathName(path, Define.con_DIR_WORK); string sMoveDir = row.GetErr2MovFileDirPath(path, Define.con_DIR_CONVERT); string sMoveFileFullPathName = row.GetErr2MovFileFullPathName(path, Define.con_DIR_CONVERT); DirectoryInfo diChk = new DirectoryInfo(sMoveDir); if (diChk.Exists == false) { diChk.Create(); } row.ConversionFlag = Define.CON_MSG_ERROR; util.FileSave("move", sWorkFileFullName, sMoveFileFullPathName); row.ZipfileFullPath = sMoveDir; } /* FTP 전송실패 또는 FTP 전송 못한 QMS파일 백업 */ private void Err2FileMoveFtpError(FileProcess row) { if (row.FtpSendFileCnt <= row.FtpSendSuccessCnt) { return; } /* 오류 폴더는 ZIP파일내임은 MOVE내임으로 안에는 오리지날 파일내임으로 한다. 추후 폴더구조로 로딩시 Zip 파일내임과 orgZip파일이름 동일시 하기 위해 */ //string movePath = GetDefaultFtpPath(); //movePath += movePath + "\\" + Define.con_DIR_UPLOAD + "\\" + row.ZipFileName; string movePath = row.GetErr2MovFileDirPath(GetDefaultFtpPath(),Define.con_DIR_UPLOAD); //UPLOAD ERROR 폴더 생성 DirectoryInfo diChk = new DirectoryInfo(movePath); if (diChk.Exists == false) { diChk.Create(); } row.ZipfileFullPath = movePath; foreach (ZipFileDetailEntity detail in row.ZipfileDetailList) { if (detail.FlagFtpSend != Define.con_SUCCESS) { util.FileSave("move", row.ZipfileFullPath + "\\" + detail.QmsfileNm, movePath + "\\" + detail.QmsfileNm); } } } private String ConvertorRunProc(FileProcess row , string extractDir) { //<START> ############# 컨버터 실행 SetLog(row, "INFO", "컨버터 실행"); row.ConversionFlag = Define.CON_MSG_ING; row.CurState = Define.con_STATE_START_CONV; UpdateRowFileProcess(row); iqaService.updateZipfileMainInfo(row, Define.con_STATE_START_CONV); string[] dmlFind = Directory.GetFiles(extractDir, "*.dml"); string sConvertorLogFileName = ""; //컨버터 실행 비정상일경우 최대 3번 호출한다. int nConvertCallCnt = 0; Boolean bSti = false; while (nConvertCallCnt <= 3 && sConvertorLogFileName.Length <= 0) { nConvertCallCnt++; SetLog(row, "INFO", "컨버터 실행 횟수 : " + nConvertCallCnt.ToString()); string runConvertorTime = DateTime.Now.ToString("yyyyMMddHHmmss"); if (dmlFind.Length > 0) { bSti = true; runServyceType2RunConvertor(row.ServiceType, extractDir, bSti); } else { runServyceType2RunConvertor(row.ServiceType, extractDir, bSti); } //생각보다 컨트롤러 처리 오래 걸림 Thread.Sleep(40 * 1000); sConvertorLogFileName = GetConvertLogFileName(runConvertorTime, bSti, 8); if (sConvertorLogFileName.Length <= 0) { SetLog(row, "INFO", "컨버터 강제 종료"); //컨버터 프로세스 죽인다. KillConvertor(bSti); Thread.Sleep(3 * 1000); } } if (sConvertorLogFileName.Length <= 0) { row.ConversionFlag = Define.CON_MSG_ERROR; row.CurState = Define.con_STATE_ERR_CONV; UpdateRowFileProcess(row); SetLog(row, "ERR", "Convertor 비정상"); iqaService.updateZipFileAllInfo(row); row.Pass = true; return ""; } SetLog(row, "INFO", "컨버터 종료 대기중..."); string sConvertorLogEndFileName = ""; while (sConvertorLogEndFileName == "") { sConvertorLogEndFileName = isConvertorRunComplete(sConvertorLogFileName, bSti); if (isConvertorError(row, bSti)) { sConvertorLogEndFileName = "ERROR"; //강제 죽이기 KillConvertor(bSti); Thread.Sleep(2 * 1000); } //Application.DoEvents(); //SetLog(row, "INFO", "컨버터 종료 대기중..."); Thread.Sleep(10 * 1000); } if (sConvertorLogEndFileName == "ERROR") { row.ConversionFlag = Define.CON_MSG_ERROR_CONV_LEN; //SetLog(row, "INFO", "컨버터 실행 완료"); SetLog(row, "ERR", "DRM 파일 길이 오류 발생"); UpdateRowFileProcess(row); } else { row.ConversionFlag = Define.CON_MSG_COMPLETE; SetLog(row, "INFO", "컨버터 실행 완료"); UpdateRowFileProcess(row); } return sConvertorLogEndFileName; } private string[] GetDir2OriFileList(string extractDir) { List<string> oriFiles = new List<string>(); string[] extractFile = Directory.GetFiles(extractDir); foreach (string extractFilePath in extractFile) { //string extractFileName = Path.GetFileName(extractFilePath); string extractFileName = Path.GetFileNameWithoutExtension(extractFilePath); string extenstion = Path.GetExtension(extractFilePath); if (extenstion.ToUpper() == ".DRM" || extenstion.ToUpper() == ".DML") { oriFiles.Add(extractFilePath); } } return oriFiles.ToArray(); } private Boolean ZipfileCancelCheckProc(FileProcess row , string delFlag) { string isCancel = iqaService.IsZipfileCancel(row); if (isCancel != "1") { return false; } string delPath = ""; if (delFlag == "all") { delPath = row.ZipfileFullPath; } else if (delFlag == "zip") { delPath = row.ZipFileFullFileName; } row.Pass = true; row.CurState = Define.con_STATE_CANCEL; SetLog(row, "INFO", "작업 취소"); DeleteWorkZipFile(delPath); return true; } /* Zip 파일 분석 처리 프로세스 */ private void ZipfileParsing(FileProcess row) { string tmpZipfilePath = ""; string path = GetDefaultFtpPath(); string withoutExtensionZipFileName = Path.GetFileNameWithoutExtension(row.ZipFileName); row.CurState = Define.con_STATE_WORK; UpdateRowFileProcess(row); try { //Log 그리드 초기화 /* this.Invoke(new Action(delegate () { dgvProcessLog.RowCount = 0; })); */ if (m_QueueZipfileParsing_2.Count <= 0 && m_QueueZipfileParsing.Count <=0) { //로그 그리드 초기화 this.Invoke(new Action(delegate () { dgvProcessLog.Rows.Clear(); })); } SetLog(row, "INFO", "#####작업 처리 시작#####"); //등록되고 파일 Wait2FileAccessible 시점 시스템 예외 발생되어 멈추는 현상 발생 if (row.ErrFlagFileAccess == Define.con_STATE_ERR_FILE_DENIED) { row.Pass = true; row.BackupFlag = "Zip 파일 Access Denied"; row.CurState = Define.con_STATE_ERR_FILE_DENIED; SetLog(row, "ERR", "Access Denied 발생"); UpdateRowFileProcess(row); iqaService.updateZipfileMainInfo(row, ""); return; } string fileName = row.OrgZipFIleFullName; FileInfo file = new FileInfo(fileName); if (!file.Exists) { row.Pass = true; row.BackupFlag = "Zip 파일 미존재"; row.CurState = Define.con_STATE_ERR_NO_FILE; SetLog(row, "ERR", "해당파일 존재 하지 않음-중간 취소됨"); UpdateRowFileProcess(row); iqaService.updateZipfileMainInfo(row, ""); return; } SetLog(row, "INFO", "작업폴더 파일이동"); tmpZipfilePath = path + "\\" + Define.con_DIR_WORK; //row.ZipfileFullPath = path + "\\" + Define.con_DIR_WORK; if (!util.FileSave("move", fileName, tmpZipfilePath + "\\" + row.ZipFileName)) { //파일이동 자체가 실패하였기 떄문에 오류로 오류폴더로 파일을 이동하는게 의미 없음 row.Pass = true; SetLog(row, "WARN", "작업폴더 파일이동 실패"); return; } row.ZipfileFullPath = tmpZipfilePath; FileInfo fInfo = new FileInfo(row.ZipfileFullPath + "\\" + row.ZipFileName); row.FileSize = fInfo.Length.ToString(); SetLog(row, "INFO", "작업폴더 파일이동 완료"); //<START> ############# 파일 백업 및 작업 디렉토리로 이동 //추후 안정화 되면 백업 최후단계에서 move 하자 row.BackupFlag = Define.CON_MSG_ING; UpdateRowFileProcess(row); SetLog(row, "INFO", "백업"); if (!util.FileSave("copy", row.ZipfileFullPath + "\\" + row.ZipFileName, path + "\\"+ Define.con_DIR_BACK + "\\" + row.ZipFileName)) { row.Pass = true; SetLog(row, "WARN", "백업 실패"); row.BackupFlag = Define.CON_MSG_ERROR; UpdateRowFileProcess(row); return; } SetLog(row, "WARN", "백업 완료"); row.BackupFlag = Define.CON_MSG_COMPLETE; //<END> if (ZipfileCancelCheckProc(row, "zip")) { row.FileNameRule = Define.CON_MSG_CANCEL; UpdateRowFileProcess(row); return; } //<START> ########### 파일명 규칙 분석####################### iqaService.updateZipfileMainInfo(row, Define.con_STATE_START_NAMING); SetLog(row, "INFO", "파일명 규칙 분석"); if (!ZipFileNamingParsing(row)) { row.Pass = true; row.FileNameRule = Define.CON_MSG_ERROR; row.CurState = Define.con_STATE_ERR_NAMING; UpdateRowFileProcess(row); //string sWorkFileFullName = row.GetWorkFileFullPathName(); string sWorkFileFullName = row.GetZipfileFullPathName(path,Define.con_DIR_WORK); string sMoveFileFullName = row.GetErr2MovFileFullPathName(path, Define.con_DIR_NAMING); string sMoveDir = row.GetErr2MovFileDirPath(path, Define.con_DIR_NAMING); DirectoryInfo diChk = new DirectoryInfo(sMoveDir); if (diChk.Exists == false) { diChk.Create(); } util.FileSave("move", sWorkFileFullName, sMoveFileFullName); row.ZipfileFullPath = sMoveDir; UpdateRowErrorFile(row); iqaService.updateZipfileMainInfo(row,Define.con_STATE_START_NAMING); return; } UpdateRowFileProcess(row); SetLog(row, "INFO", "파일명 규칙 완료"); //<END> if (ZipfileCancelCheckProc(row, "zip")) { row.ExtractFlag = Define.CON_MSG_CANCEL; UpdateRowFileProcess(row); return; } //<START> ############# 압축 해제 처리 ###################### SetLog(row, "INFO", "압축해제"); if (!UnZIpProc(row)){ row.Pass = true; UpdateRowErrorFile(row); iqaService.updateZipfileMainInfo(row, ""); return; } SetLog(row, "INFO", "압축해제 완료"); UpdateRowFileProcess(row); iqaService.updateZipfileMainInfo(row, ""); //<END> 압축 해제 완료 Thread.Sleep(1500); string extractDir = getUnzipPath(row); //string[] filters = new[] { "*.drm", "*.dml" }; //string[] unzipFile = filters.SelectMany(f => Directory.GetFiles(extractDir, f)).ToArray(); string[] unzipFile = GetDir2OriFileList(extractDir); if (unzipFile.Length <= 0) { row.Pass = true; row.CurState = Define.con_STATE_ERR_ZERO_DRM; SetLog(row, "ERR", "Drm/Dml 파일 미존재"); //UpdateRowErrorFile(row); iqaService.updateZipfileMainInfo(row, ""); DeleteWorkZipFile(extractDir); return; } //<START> ############# Unzip 파일 정보 DB 업로드및 중복 Drm 제거 처리 //이곳에서 unzip 파일 및 dup파일 정보 업데이트 한다. SetLog(row, "INFO", "중복 Drm 체크"); unzipFileDetailProc(row , extractDir); SetLog(row, "INFO", "중복 Drm 체크 완료"); //#############################################</END> //모두 중복 제거일경우 컨버터 호출하지 않는다. //string[] extractFile = Directory.GetFiles(extractDir); string[] extractFile = GetDir2OriFileList(extractDir); //2018-12-07 drm파일이 존제 안할수도있따고 함 위에서 체크 조건 더주기로 함 if (extractFile.Length <= 0) //압축 로그정보파일 떄문에 1개파일은 존재한다. { row.Pass = true; row.CurState = Define.con_STATE_ERR_DUP_ALL; SetLog(row, "INFO", "모든 파일 중복 Drm"); iqaService.updateZipfileMainInfo(row,""); DeleteWorkZipFile(extractDir); return; } Thread.Sleep(2000); AddLogFile(row, "INFO", "Que Dequeue2 Enqueue(등록)"); m_QueueZipfileParsing_2.Enqueue(row); } catch (Exception ex) { SetLog(row, "ERR", "[ERR]:[ZipfileParsing]:" + ex.Message); //복사 진행중인 파일 //파일이 다른 프로세스에서 사용되고 있으므로 프로세스에서 파일에 액세스할 수 없습니다. if (ex.HResult == -2147024864) { //파일 해당 폴더로 전송중인 상태라 전송 완료시점에 다시 처리 하기 위해 row.Pass = false; } else { row.Pass = true; } Console.WriteLine(ex.Message); } } /* convertor 부터 나머지 처리 */ private void ZipfileParsing2(FileProcess row) { /* string onlyFileName = Path.GetFileName(fileName); string withoutExtensionName = Path.GetFileNameWithoutExtension(fileName); //처리 완료또는 패스할 조건일경우 if (m_dicFileProcess.ContainsKey(onlyFileName)) { if (m_dicFileProcess[onlyFileName].Pass || m_dicFileProcess[onlyFileName].Complete) return; } */ try { /* //Log 그리드 초기화 this.Invoke(new Action(delegate () { dgvProcessLog.RowCount = 0; })); */ //<START> - 컨버터 실행 string extractDir = getUnzipPath(row); if (ZipfileCancelCheckProc(row, "all")) { row.ConversionFlag = Define.CON_MSG_CANCEL; UpdateRowFileProcess(row); return; } string sConvertorEndFileName = ConvertorRunProc(row, extractDir); if (sConvertorEndFileName.Length <= 0 || sConvertorEndFileName == "ERROR") { row.Pass = true; if (sConvertorEndFileName == "ERROR") { row.CurState = Define.con_STATE_ERR_CONV_LEN; //DRM 파일길이 ERROR } else { row.CurState = Define.con_STATE_ERR_CONV; } iqaService.updateZipfileMainInfo(row, ""); Err2FileMoveConversion(row); UpdateRowErrorFile(row); DeleteWorkZipFile(extractDir); return; } //#############################################</END> if (sConvertorEndFileName.Length > 0) { if (!ConvertResultProc(row, sConvertorEndFileName)) { row.Pass = true; return; } if (ZipfileCancelCheckProc(row, "all")) { row.FtpSendFlag = Define.CON_MSG_CANCEL; UpdateRowFileProcess(row); return; } SetLog(row, "INFO", "FTP 파일전송"); ControllerServerEntity freeFtpServer = m_dicFtpInfo[Define.con_FTP_QMS]; if (freeFtpServer == null) { row.Pass = true; row.FtpSuccessFlag = Define.con_FAIL; SetLog(row, "WARN", "FTP 서버 정보 가져오기 실패"); Err2FileMoveFtpError(row); UpdateRowErrorFile(row); DeleteWorkZipFile(extractDir); return; } Boolean bFtpSuccess = false; //FTP 전송 (모듈이 나뉘고 있어서 상용도 SFTP로 요청하자) string[] qmsFiles = Directory.GetFiles(extractDir, "*.qms"); if (qmsFiles.Length > 0) { row.FtpSendFlag = Define.CON_MSG_ING; UpdateRowFileProcess(row); iqaService.updateZipfileMainInfo(row, Define.con_STATE_START_FTP); bFtpSuccess = SendFtp(row, freeFtpServer, extractDir, false); if (!bFtpSuccess) { row.Pass = <PASSWORD>; row.FtpSendFlag = Define.CON_MSG_ERROR; row.CurState = Define.con_STATE_ERR_FTP; Err2FileMoveFtpError(row); SetLog(row, "INFO", "파일전송 실패"); } else { row.CurState = Define.con_STATE_COMPLETE_FTP; row.FtpSendFlag = Define.CON_MSG_COMPLETE; SetLog(row, "INFO", "파일전송 완료"); } } else { row.CurState = Define.con_STATE_ERR_ZERO_QMS; SetLog(row, "INFO", "QMS 파일 미존재"); } } //정상 처리 로그 남긴다. 1 SetLog(row, "INFO", "#####작업 처리 완료#####"); SaveResultInfo res = iqaService.updateZipFileAllInfo(row); if (res.Flag == 0) { SetLog(row, "ERR", "작업처리 완료 저장 실패(로그확인)"); AddLogFile(row, "ERR:ZipfileParsing2", res.Desc); } UpdateRowFileProcess(row); //안정화 되면 이단계에서 BACKUP 폴더로 MOVE 시키자 //worK 작업 파일 관련 삭제 처리 if (DeleteWorkZipFile(extractDir)) { SetLog(row, "INFO", "작업파일 삭제 완료"); } else { SetLog(row, "INFO", "작업파일 삭제 실패"); } row.Complete = true; } catch (Exception ex) { SetLog(row, "ERR", "[ERR]:[ZipfileParsing]:" + ex.Message); //복사 진행중인 파일 //파일이 다른 프로세스에서 사용되고 있으므로 프로세스에서 파일에 액세스할 수 없습니다. row.Pass = true; Console.WriteLine(ex.Message); } } private Boolean ZipfileBackupProc(FileProcess row) { string defaultPath = GetDefaultFtpPath(); string dirPath = row.GetErr2MovFileDirPath(defaultPath, Define.con_DIR_WORK); string sBackupFileFullName = row.GetZipfileFullPathName(defaultPath, Define.con_DIR_BACK); bool bSuccess = util.FileSave("move", row.ZipFileFullFileName, sBackupFileFullName); DirectoryInfo di = new DirectoryInfo(dirPath); if (di.Exists) { di.Delete(true); } return bSuccess; } private Boolean DeleteWorkZipFile(string dirPath) { Thread.Sleep(1000); try { if (dirPath.Length <= 0) { return true; } Boolean bUnzip = true; string ext = Path.GetExtension(dirPath); if (ext == ".zip" || ext == ".ZIP") { bUnzip = false; } if (bUnzip) { DirectoryInfo di = new DirectoryInfo(dirPath); if (di.Exists) { di.Delete(true); } FileInfo file = new FileInfo(dirPath + ".zip"); if (file.Exists) { file.Delete(); } } else { FileInfo file = new FileInfo(dirPath); if (file.Exists) { file.Delete(); } } } catch(Exception ex) { Console.WriteLine(ex.Message); //SetLog(row, "[ERROR(deleteDir)]" + ex.Message); util.Log("ERR:DeleteWorkZipFile", ex.Message.ToString()); return false; } return true; } //추후 시간날때 검토해보자 private string getJsonStr(List<string> data) { string tmp = Newtonsoft.Json.JsonConvert.SerializeObject(data); tmp = tmp.Remove(0, 1); // '[' 제거 tmp = tmp.Remove(tmp.Length - 1, 1); // ']' 제거 tmp = tmp.Replace(@"""", @""); // string "" 제거 return tmp; } /* 압축 해제 완료 체크 */ private void unZipCompleteChk(string unZipLogPath,string chkDirPath) { //파일 새성 여부 체크 FileInfo fi = null; Boolean bfileChk = false; while (!bfileChk) { fi = new FileInfo(unZipLogPath); if (fi.Exists) { bfileChk = true; } Thread.Sleep(1000); } //FileStream ReadData = new FileStream(unZipLogPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //파일 생성되었는지 여부 확인 string[] lines = System.IO.File.ReadAllLines(unZipLogPath, Encoding.Default); int lastRow = -1; for(int nIdx = lines.Length - 1; nIdx >= 0; nIdx--) { if (lines[nIdx].Trim() != "") { lastRow = nIdx; break; } } string result = ""; if (lastRow >= 0) { Boolean bDataY = false; string totalSize = ""; result = lines[lastRow]; foreach(char tmp in result) { if (tmp.ToString() != " ") { totalSize += tmp.ToString(); bDataY = true; } else { if (bDataY) { break; } } } Console.WriteLine(totalSize); if (totalSize == "Errors:") { Console.WriteLine("ERROR 발생"); } else { /* 실제 로그에 찍힌 총 바이트수가 틀릴경우가 발생해서 */ long unzipTotalSize = Convert.ToInt64(totalSize); Thread.Sleep(4000); //최대 횟수 제한하자 long dirTotalSize = 0; while (unzipTotalSize > dirTotalSize) { //ZIP파일 생성 이후 시점 마지막 생성된 날짜 로그를 본다._END가 있는지 dirTotalSize = GetDirectoryTotalSize(chkDirPath); //Application.DoEvents(); Thread.Sleep(2000); } } } } private long GetDirectoryTotalSize(string sDirPath) { // Get array of all file names. /* string[] a = Directory.GetFiles(sDirPath, "*.*"); long b = 0; foreach (string name in a) { FileInfo info = new FileInfo(name); if (info.Extension == ".drm" || info.Extension == ".dml") { b += info.Length; } } return b; */ DirectoryInfo dir = new DirectoryInfo(sDirPath); long totalSize = util.CalculateDirectorySize(dir, true); return totalSize; } private Boolean ConvertResultProc(FileProcess row, string filePath) { string[] lines = System.IO.File.ReadAllLines(filePath, Encoding.Default); // string array string flag = ""; string desc = ""; string[] tmpResult = null; Boolean bConvertError = false; int nQmsFileCnt = 0; foreach (string log in lines) { // System.Console.WriteLine(log); tmpResult = log.Split(';'); if (tmpResult.Length == 3) { if (tmpResult[2].ToUpper() == "END") { flag = "1"; desc = ""; } else { flag = "0"; desc = tmpResult[2]; bConvertError = true; } ZipFileDetailEntity detail = row.findZipfileDetail("unzipNm", tmpResult[0]); if (detail != null) { nQmsFileCnt++; detail.QmsfileNm = tmpResult[1]; detail.FlagConvertorResult = flag; detail.DescConvertorResult = desc; detail.QmsfileNmChg = GetQmsNameChange(Convert.ToString(nQmsFileCnt)); } } else { ZipFileDetailEntity detail = row.findZipfileDetail("unzipNm", tmpResult[0]); if (detail != null) { //nQmsFileCnt++; detail.QmsfileNm = ""; //파생 안됨 detail.FlagConvertorResult = "0"; detail.DescConvertorResult = log; //detail.QmsfileNmChg = getQmaNameChange(Convert.ToString(nQmsFileCnt)); } } } //오류가 발생시 오류항목은 따로 컨버터 오류 폴더에 백업한다. if (bConvertError) { string path = GetDefaultFtpPath(); string sMoveDir = Path.GetFileNameWithoutExtension(row.OrgZipFileName); DirectoryInfo diChk = new DirectoryInfo(path + "\\" + Define.con_DIR_CONVERT + "\\" + sMoveDir); if (diChk.Exists == false) { diChk.Create(); } row.ConversionFlag = Define.CON_MSG_ERROR; File.Move(path + "\\WORK\\" + row.ZipFileName, path + "\\" + Define.con_DIR_CONVERT + "\\" + sMoveDir + "\\" + row.OrgZipFileName); row.ZipfileFullPath = path + "\\" + Define.con_DIR_CONVERT + "\\"+ sMoveDir; UpdateRowErrorFile(row); } else { row.CurState = Define.con_STATE_COMPLETE_CONV; } SaveResultInfo res = iqaService.updateZipFileAllInfo(row); if (res.Flag == 0) { //이럴일 있을까? SetLog(row, "ERR", res.Desc); AddLogFile(row, "ERR:ConvertResultProc", res.Desc); return false; } return true; } /* private Boolean unZipFileChk(string zipFileNm, string unzipPath) { string extension = ""; string onlyFileName = ""; string[] fileEntries = Directory.GetFiles(unzipPath); List<string> unZipFile = new List<string>(); foreach (string fileName in fileEntries) { extension = Path.GetExtension(fileName); onlyFileName = Path.GetFileNameWithoutExtension(fileName); if (extension == ".drm" || extension == ".dml") { unZipFile.Add(onlyFileName); } } string unZipStr = Newtonsoft.Json.JsonConvert.SerializeObject(unZipFile); //string uri = "http://localhost:8080/IQA/map/getTestList.do"; string uri = Define.CON_WEB_SERVICE + "map/unzipFileDupProc.do"; WebClient webClient = new WebClient(); //webClient.Headers[HttpRequestHeader.ContentType] = "application/json"; //webClient.Encoding = UTF8Encoding.UTF8; NameValueCollection postData = new NameValueCollection() { { "zipFileName", HttpUtility.UrlEncode(zipFileNm) } , { "unZipFile", HttpUtility.UrlEncode(unZipStr)} }; string pagesource = Encoding.UTF8.GetString(webClient.UploadValues(uri, postData)); try { string sTest = pagesource; } catch (Exception ex) { util.Log("ERR:unZipFileChk", ex.Message); Console.WriteLine(ex.Message.ToString()); } return true; } */ private void ServiceOnOff() { SetControlServiceBtnOnOff(); if (m_bServiceOnOffButton) { ServiceOnMain(); } else { if (m_zipFileWatcher.EnableRaisingEvents) { m_zipFileWatcher.EnableRaisingEvents = false; } m_eventOrifileLoopCnt = 0; } } private void ServiceOnMain() { Thread thread = new Thread(new ThreadStart(delegate () { ServiceOnQueueStartProc(); })); thread.Start(); } /* Queue 방식으로 변경처리후 아래 실제 사용안함 나중 Queue 방식 문제 없을시 삭제 처리 private void serviceOnMainProc() { Thread thread = new Thread(new ThreadStart(delegate () { serviceOnThreadProc(); })); thread.Start(); } */ /* 작업에 필요한 폴더를 생성한다. */ private void AppWorkDirMake(string path) { //Work Directory 생성 DirectoryInfo diChk = new DirectoryInfo(path + "\\" + Define.con_DIR_WORK); if (diChk.Exists == false) { diChk.Create(); } // 중복 backup 백업 폴더 diChk = new DirectoryInfo(path + "\\" + Define.con_DIR_BACK); if (diChk.Exists == false) { diChk.Create(); } // CONVERT_ERROR diChk = new DirectoryInfo(path + "\\" + Define.con_DIR_CONVERT ); if (diChk.Exists == false) { diChk.Create(); } // NAMING ERROR diChk = new DirectoryInfo(path + "\\" + Define.con_DIR_NAMING); if (diChk.Exists == false) { diChk.Create(); } // ZipfileName 중복 - ZIP파일 중복은 사용안함 diChk = new DirectoryInfo(path + "\\" + Define.con_DIR_ZIPDUP); if (diChk.Exists == false) { diChk.Create(); } // qms 파일 전송 ERROR diChk = new DirectoryInfo(path + "\\" + Define.con_DIR_UPLOAD); if (diChk.Exists == false) { diChk.Create(); } diChk = new DirectoryInfo(path + "\\" + Define.con_DIR_EVENT_ORIFILE); if (diChk.Exists == false) { diChk.Create(); } } private void DeleteVariableFileProcessProc() { if (m_dicFileProcess.Count <= 0) { return; } List<string> lstDelKey = new List<string>(); foreach (var key in m_dicFileProcess.Keys.ToList()) { /* 어짜피 로그파일에 다 남는다 삭제 안할 이유가 없음 if (!(m_dicFileProcess[key].Complete || m_dicFileProcess[key].Pass)) { continue; } */ string zipFileName = m_dicFileProcess[key].ZipFileName; string[] arFileInfo = zipFileName.Split('_'); //zip파일명에서 마지막구분자 시스템 날짜를 추출한다. var fileWorkDate = arFileInfo[arFileInfo.Length - 1]; fileWorkDate = Path.GetFileNameWithoutExtension(fileWorkDate); fileWorkDate = fileWorkDate = fileWorkDate.Substring(0, 8); DateTime dtFileWirkDate = new DateTime(); Boolean isDate = util.ParseDate(fileWorkDate, ref dtFileWirkDate); if (!isDate) { continue; } DateTime dtCurDate = DateTime.Now; //DateTime dtFileWirkDate = DateTime.ParseExact(fileWorkDate, "yyyyMMddHHmmss", null); dtFileWirkDate = dtFileWirkDate.AddDays(15); int nCompare = DateTime.Compare(dtFileWirkDate, dtCurDate); if (nCompare < 0) { //삭제 대상 : 15 일 지난 파일 리스트는 삭제 한다. lstDelKey.Add(key); } } foreach(string key in lstDelKey){ if (key != null && key != "") { //화면 그리드 삭제 한다. int nDeleteRow = 0; this.Invoke(new Action(delegate () { nDeleteRow = dgvProcess.getFindZipFile2RowIndex(key, Define.con_KEY_PROCESS_COLIDX); if (nDeleteRow >= 0) { dgvProcess.Rows.RemoveAt(nDeleteRow); } })); m_dicFileProcess.Remove(key); } } } private void ServiceOnQueueStartProc() { //로딩시 해당폴더 기존에 있던 Zip파일 읽어들인다. SetControlServiceBtnOnOff(); Dir2ZipfileQueueAdd(); //그이후 추가되는 Zip파일 감시 m_zipFileWatcher.EnableRaisingEvents = true; //시작부터~ 압축 해제전까지 작업 큐 Thread thread = new Thread(new ThreadStart(delegate () { RunQueueZIpfileWork(); })); thread.Start(); //컨버터 부터 ~ FTP 전송까지 작업큐(컨버터 작업이 오래걸려 작업하는동안 압축해제전까지 미리 처리하기 위해 나눈다.) Thread thread2 = new Thread(new ThreadStart(delegate () { RunQueueZIpfileWork2(); })); thread2.Start(); } private string GetSystemZipfileNm2OrgFIleName(string fileName) { //fileName = "강북본부_도로407조_LTEV_SKT_AUTO_롯데_20181201_20181205132239.zip"; string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); int nPos = fileNameWithoutExtension.LastIndexOf("_"); fileNameWithoutExtension = fileNameWithoutExtension.Substring(0, nPos); return fileNameWithoutExtension + ".zip"; } private FileProcess GetFilePath2FileProcessInfo(string fileName) { string onlyFileName = Path.GetFileName(fileName); string moveFileName = GetZipfileNameAddSysdate(fileName); string fullPath = Path.GetDirectoryName(fileName); //int systemDatePos = moveFileName.LastIndexOf('_'); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(moveFileName); string[] arInfo = fileNameWithoutExtension.Split('_'); string uploadDate = arInfo[arInfo.Length-1]; uploadDate = uploadDate.Substring(0, 8); FileProcess row = new FileProcess(); row.ProcessServer = GetFtpName(m_ftpId); row.ZipFileName = moveFileName; //2018-06-14 : Zip 파일명도 시스템 날짜 추가된거로 관리하는거로 요청옴 row.OrgZipFileName = onlyFileName; row.ZipfileFullPath = fullPath; row.CurState = Define.con_STATE_WAIT; row.UploadDate = uploadDate; return row; } private string GetUseableZIpFileName(string zipfileName) { string useableZipfileName = zipfileName; useableZipfileName = useableZipfileName.Replace(",", "%%"); return useableZipfileName; } private void Dir2ZipfileQueueAdd() { string path = GetDefaultFtpPath(); if (Directory.Exists(path)) { m_ServiceOnIng = true; AppWorkDirMake(path); //요청한 DRM파일을 FTP로 전송한다. //eventOrifileSendProc(); //하루 지난거만 초기화 한다. //DeleteVariableFileProcessProc(); string[] fileEntries = Directory.GetFiles(path, "*.zip"); //ZIP파일정보 미리 DB 업뎃하기 위해 List<FileProcess> dbInsertList = new List<FileProcess>(); foreach (string fileName in fileEntries) { FileProcess row = GetFilePath2FileProcessInfo(fileName); //m_dicFileProcess.Add(row.OrgZipFileName, row); m_dicFileProcess.Add(row.ZipFileName, row); dbInsertList.Add(row); } //DRM 중복체크는 안하는거로 함 어짜피 drm 중복체크를 하고 또 ZIP파일을 다시 올릴수도있어서 중간 실패시 문제가 될수있어 체크 안함 if (dbInsertList.Count > 0) { SaveResultInfo res = iqaService.insertZipfileInfos(dbInsertList); if (res.Flag == 0) { util.Log("ERR:DirLoad2ZipFileProc", "ZIP File 대기 정보 저장 실패"); //DB 저장이 안되어 그이후 행위 의미 없음 } else { foreach (FileProcess row in dbInsertList) { AddLogFile(row, "INFO", "IQA Controller Service Start Zipfile Que Enqueue(등록)"); m_QueueZipfileParsing.Enqueue(row); } } } else { m_ServiceOnIng = false; } } else { m_ServiceOnIng = false; MessageBox.Show("해당 경로의 디렉토리가 존재 하지 않습니다."); } SetControlServiceBtnOnOff(); } private void CreateFolderWatching() { m_zipFileWatcher = new System.IO.FileSystemWatcher(); m_zipFileWatcher.Path = GetDefaultFtpPath(); m_zipFileWatcher.Filter = "*.zip"; m_zipFileWatcher.Created += new FileSystemEventHandler(ZipFileCreated); } private void SetVariableServiceOnIng() { //Que작업이 완전히 없을경우 if (m_QueueZipfileParsing.Count <=0 && m_QueueZipfileParsing_2.Count <= 0) { m_ServiceOnIng = false; } else { m_ServiceOnIng = true; } } private void RunQueueZIpfileWork2() { try { while (m_bServiceOnOffButton) { //m_ServiceOnIng = true; while (m_QueueZipfileParsing_2.Count > 0) { m_ServiceOnIng = true; FileProcess row = m_QueueZipfileParsing_2.Dequeue(); AddLogFile(row, "INFO", "Work_2 Que Dequeue 작업시작"); ZipfileParsing2(row); Thread.Sleep(1000); } //m_ServiceOnIng = false; SetVariableServiceOnIng(); SetControlServiceBtnOnOff(); Thread.Sleep(1000 * 1); //1초마다 순회 체크 } } catch (Exception ex) { m_ServiceOnIng = false; StopFtpFoldWatch(); SetLog(null, "ERR", "RunQueueZIpfileWork2 예외발생_2:" + ex.Message.ToString()); SetLog(null, "ERR", "FTP 폴더 감시 중지"); Thread.Sleep(1000 * 2); } } private void RunQueueZIpfileWork() { try { while (m_bServiceOnOffButton) { try { //DRM 요청파일 전송처리 m_eventOrifileLoopCnt++; //5분마다 체크한다. if (m_eventOrifileLoopCnt % (60*5) == 0) { #if (!DEBUG) m_ServiceOnIng = true; EventOrifileSendProc(); SetVariableServiceOnIng(); #endif m_eventOrifileLoopCnt = 0; } //하루에 한번 체크한다. string curDate = util.GetCurrentDate("{0:yyyyMMdd}"); if (m_checkedkDay != curDate) { m_ServiceOnIng = true; m_checkedkDay = curDate; //파일 보관주기에 따른 삭제 처리 if (setFilePeriodInfo()) { util.Log("INFO", "FilePeriodChk2Proc:파일보관주기 삭제 처리"); FilePeriodChk2Proc(); } //한달 지난 그리드 데이타는 초기화 한다. DeleteVariableFileProcessProc(); SetVariableServiceOnIng(); } } catch (Exception ex) { //m_ServiceOnIng = false; SetLog(null, "ERR", "RunQueueZIpfileWork - 기타 작업 오류 발생:" + ex.Message.ToString()); } while (m_QueueZipfileParsing.Count > 0) { m_ServiceOnIng = true; FileProcess row = m_QueueZipfileParsing.Dequeue(); //FileProcess row = m_QueueZipfileParsing.Peek(); if (!m_dicFileProcess.ContainsKey(row.ZipFileName)) { m_dicFileProcess.Add(row.ZipFileName, row); } else { //이미 등록 되있을경우 처리 패스 해야하나? - 이럴일 없음 m_dicFileProcess[row.ZipFileName] = row; } AddLogFile(row, "INFO", "Work_1 Que Dequeue 작업시작"); //DRM서버로 전송되는 중간에 취소 되는경우 발생함 string errFlag = ""; Boolean bAccessible = util.Wait2FileAccessible(row.OrgZipFIleFullName, 9999, ref errFlag); row.ErrFlagFileAccess = errFlag; Thread.Sleep(1000); ZipfileParsing(row); /* 추후 모든 작업 쓰레드 처리 할경우 Thread thread = new Thread(new ThreadStart(delegate () { ZipfileParsing(row.OrgZipFIleFullName); })); thread.Start(); */ //ZipfileParsing(row.OrgZipFIleFullName); Thread.Sleep(1000); } //작업 2단계까지의 작없이 없다면 작업중 상태 off 한다. SetVariableServiceOnIng(); SetControlServiceBtnOnOff(); Thread.Sleep(1000); //10초마다 순회 체크 } } catch (Exception ex) { m_ServiceOnIng = false; StopFtpFoldWatch(); SetLog(null, "ERR", "RunQueueZIpfileWork - 예외발생:" + ex.Message.ToString()); SetLog(null, "ERR", "FTP 폴더 감시 중지"); //Thread.Sleep(1000 * 5); } } private void StopFtpFoldWatch() { if (m_zipFileWatcher.EnableRaisingEvents) { m_zipFileWatcher.EnableRaisingEvents = false; } } /* FTP 폴더 감시에 따른 파일 추가시 Callback 함수 */ private void ZipFileCreated(Object source, FileSystemEventArgs e) { string zipfileFullPath = e.FullPath; FileProcess row = GetFilePath2FileProcessInfo(zipfileFullPath); List<FileProcess> dbInsertList = new List<FileProcess>(); dbInsertList.Add(row); SaveResultInfo res = iqaService.insertZipfileInfos(dbInsertList); if (res.Flag == 0) { AddLogFile(row, "ERR:ZipFileCreated", "ZIP File 대기 정보 저장 실패"); return; } AddLogFile(row, "INFO", "Zipfile Add Queue Enqueue(등록)"); //기존 키에 중복되는애가 있을경우 완료나 처리중일경우? -FTP04경우 동일한 zip파일명이 들어옴 m_QueueZipfileParsing.Enqueue(row); } /* private void serviceOnThreadProc() { string path = GetDefaultFtpPath(); if (Directory.Exists(path)) { m_ServiceOnIng = true; AppWorkDirMake(path); //요청한 DRM파일을 FTP로 전송한다. //eventOrifileSendProc(); //하루 지난거만 초기화 한다. //DeleteVariableFileProcessProc(); string[] fileEntries = Directory.GetFiles(path,"*.zip"); //ZIP파일정보 미리 DB 업뎃하기 위해 List<FileProcess> dbInsertList = new List<FileProcess>(); foreach (string fileName in fileEntries) { FileProcess row = GetFilePath2FileProcessInfo(fileName); m_dicFileProcess.Add(row.OrgZipFileName, row); dbInsertList.Add(row); } //DRM 중복체크는 안하는거로 함 어짜피 drm 중복체크를 하고 또 ZIP파일을 다시 올릴수도있어서 중간 실패시 문제가 될수있어 체크 안함 if (dbInsertList.Count > 0) { SaveResultInfo res = iqaService.insertZipfileInfos(dbInsertList); if (res.Flag == 0) { //DB 저장이 안되어 그이후 행위 의미 없음 util.Log("ERR:serviceOnThreadProc", "ZIP File 대기 정보 저장 실패"); return; } } //m_dicFileProcess 변수로 처리할지 좀더 고민 //foreach (string fileName in fileEntries) //foreach (var key in m_dicFileProcess.Keys.ToList()) //컬렉션이 수정되었습니다. 열거 작업이 실행되지 않을 수도 있습니다.' 아래 참조 //http://www.jumptovb.net/tag/%EC%97%B4%EA%B1%B0%20%EC%9E%91%EC%97%85%EC%9D%B4%20%EC%8B%A4%ED%96%89%EB%90%98%EC%A7%80%20%EC%95%8A%EC%9D%84%20%EC%88%98%EB%8F%84%20%EC%9E%88%EC%8A%B5%EB%8B%88%EB%8B%A4 //foreach (KeyValuePair <string, FileProcess> pair in m_dicFileProcess) foreach (var key in m_dicFileProcess.Keys.ToList()) { //중도 중단 시켰을경우 if (!m_bServiceOnOffButton) break; //ZipfileParsing(pair.Value.ZipfileFullPath+"\\"+ pair.Value.OrgZipFileName); ZipfileParsing(m_dicFileProcess[key].ZipfileFullPath + "\\" + m_dicFileProcess[key].OrgZipFileName); //ZipfileParsing(fileName); Thread.Sleep(4000); } m_ServiceOnIng = false; Thread.Sleep(500); //주기를 주자 //파일 보관주기에 따른 삭제 처리 //FilePeriodChk2Proc(); if (m_bServiceOnOffButton) { if (!m_formClose) { //서비스 On 상태면 재귀호출한다. StartTmrServiceBtn(); serviceOnThreadProc(); } } else { //m_bServiceOn = false; EndTimerServiceBtn(); setControlServiceOnOff(); } } else { MessageBox.Show("해당 경로의 디렉토리가 존재 하지 않습니다."); btnService.PerformClick(); //서비스 멈춘다. } } */ private string GetDefaultFtpPath() { return @"D:\" + GetFtpName(m_ftpId); //return Define.CON_DEFAULT_DIR + m_ftpId; } private string GetConvertLogFileName(string sRunTime, Boolean bSti, int maxSec) { //해당 파일을 찾는다. string path = ""; if (bSti) { path = @"D:\STI\Check List"; } else { path = @"D:\INNOWHB\Check List"; } DateTime dtConvertorRunDate = DateTime.ParseExact(sRunTime, "yyyyMMddHHmmss", null); int nWaitSec = 0; string sConvertorLogFile = ""; while (sConvertorLogFile.Length <= 0 && maxSec >= nWaitSec) { string[] fileEntries = Directory.GetFiles(path); string sDirFileName = ""; string sWithoutExtensionName = ""; foreach (string fileName in fileEntries) { sWithoutExtensionName = Path.GetFileNameWithoutExtension(fileName); string[] arFileName = sWithoutExtensionName.Split('_'); sDirFileName = arFileName[0] + arFileName[1]; DateTime dtDirFileDate = DateTime.ParseExact(sDirFileName, "yyyyMMddHHmmss", null); //컨버터 실행시점보다 로그 파일시점이 이후이고 _END로 되있을경우 완료임 int nCompare = DateTime.Compare(dtConvertorRunDate, dtDirFileDate); if (nCompare < 0) { if (arFileName[2] == "END" || arFileName[2] == "CON" || arFileName[2] == "ERR") { sConvertorLogFile = sWithoutExtensionName; break; } } } Thread.Sleep(1000); nWaitSec++; } if (sConvertorLogFile.Length <= 0) { return ""; } SetLog(null, "INFO", "컨버전로그 파일 : " + sConvertorLogFile); /* 로그를 가장 나중에 쌓을떄도 있어서 우선 아래 부분 막는다. //파일은 찾았으나 해당 파일에 로그가 안찍힐 경우 컨버터 비정상임 - 프로세스 사용중 에러 발생으로 사이즈 체크한다. Thread.Sleep(1000); Boolean bConvertError = true; int nFindCnt = 0; while (nFindCnt <=5 && bConvertError) { string tmpCopyFile = GetDefaultFtpPath(); tmpCopyFile+= "\\copyLog.txt"; File.Copy(sConvertorLogFile, tmpCopyFile, true); string[] lines = System.IO.File.ReadAllLines(tmpCopyFile, Encoding.Default); foreach (string log in lines) { // System.Console.WriteLine(log); if (log.IndexOf("dml") > 0 || log.IndexOf("qms") > 0 || log.IndexOf("drm") > 0) { bConvertError = false; break; } } Thread.Sleep(2000); nFindCnt++; } if (bConvertError) { sConvertorLogFile = ""; } */ return sConvertorLogFile; } private bool isConvertorError(FileProcess row , Boolean bSti) { bool bError = false; //STI는 해당 기능을 제공하지 않는다. STI일경우는 분기한다. if (bSti) { return bError; } string curDate = util.GetCurrentDate("{0:yyyyMMdd}"); string path = ""; if (bSti) { path = @"D:\STI\Check List"; } else { path = @"D:\INNOWHB\Check List"; } string chkFileNm = "file_path_check_" + curDate; path += "\\" + chkFileNm; FileInfo file = new FileInfo(path + ".txt"); if (file.Exists) { string defaultPath = GetDefaultFtpPath(); string destPath = defaultPath + "\\BACKUP_FILE_PATH_CHECK\\"; //백업 디렉토리 유무 확인 DirectoryInfo di = new DirectoryInfo(destPath); if (di.Exists == false) { di.Create(); } //혹시 컨버터에서 아직도 쓰고 있을수 있어서 1.5초 후에 백업 폴더로 이동한다. Thread.Sleep(1500); string cur = DateTime.Now.ToString("yyyyMMddHHmmss"); if (!util.FileSave("move", path + ".txt", destPath + "\\" + chkFileNm + "_" + cur + ".txt")) { //MessageBox.Show("파일 처리중 실패 하였습니다."); SetLog(row, "ERR", chkFileNm + " 파일 백업 실패"); return true; } return true; } return bError; } /* 컨버터 실행시 컨버터가 처리 완료되었는지 확인 처리 * */ private string isConvertorRunComplete(string sLogFiileName , Boolean bSti) { string path = ""; if (bSti) { path = @"D:\STI\Check List"; } else { path = @"D:\INNOWHB\Check List"; } string[] arFileName = sLogFiileName.Split('_'); string sFindLogFileName = arFileName[0] + arFileName[1]; //DateTime dtConvertorRunDate = DateTime.ParseExact(sRunTime, "yyyyMMddHHmmss", null); string[] fileEntries = Directory.GetFiles(path); string sDirFileName = ""; string sWithoutExtensionName = ""; string sFindFileName = ""; foreach (string fileName in fileEntries) { /* sWithoutExtensionName = Path.GetFileNameWithoutExtension(fileName); string[] arFileName = sWithoutExtensionName.Split('_'); DateTime dtDirFileDate = DateTime.ParseExact(sDirFileName, "yyyyMMddHHmmss", null); //컨버터 실행시점보다 로그 파일시점이 이후이고 _END로 되있을경우 완료임 int nCompare = DateTime.Compare(dtConvertorRunDate, dtDirFileDate); if (nCompare < 0) { if (arFileName[2] == "END") { sFindFileName = fileName; break; } } */ sWithoutExtensionName = Path.GetFileNameWithoutExtension(fileName); string[] arTmpDirFileName = sWithoutExtensionName.Split('_'); sDirFileName = arTmpDirFileName[0] + arTmpDirFileName[1]; if (sFindLogFileName == sDirFileName) { if (arTmpDirFileName[2] == "END") { sFindFileName = fileName; break; } } } return sFindFileName; } private string getUnzipPath(FileProcess row) { string defaultPath = GetDefaultFtpPath(); string sWithoutExtensionName = Path.GetFileNameWithoutExtension(row.ZipfileFullPath + "\\" + row.ZipFileName); string extractDir = defaultPath + "\\WORK\\" + sWithoutExtensionName; return extractDir; } /* 압축 해제 한다. (실패시 어떻게 파악하나? 압축해제 실패시 확인방법 찾기) * */ private Boolean UnZIpProc(FileProcess row) { row.ExtractFlag = Define.CON_MSG_ING; row.CurState = Define.con_STATE_START_UNZIP; iqaService.updateZipfileMainInfo(row, Define.con_STATE_START_UNZIP); UpdateRowFileProcess(row); string extractDir = getUnzipPath(row); string orgExtractDir = extractDir; try { //7Zip 이용방식 - 기존 컨트롤러 처리 방식 //https://m.blog.naver.com/PostView.nhn?blogId=koromoon&logNo=120208838111&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F DirectoryInfo di = new DirectoryInfo(extractDir); if (di.Exists == false) { di.Create(); } extractDir += @"\"; /* execUnzipList("l " + row.ZipfileFullPath + "\\" + row.ZipFileName + " > " + "D:\\FTP14" + "\\unzipInfo.txt"); Exec(Define.CON_ZIP_EXE_PATH + "7z.exe", "x -o" + extractDir + "\\ -r -y " + row.ZipfileFullPath + "\\" + row.ZipFileName); unZipCompleteChk(extractDir + "\\" + "unzipInfo.txt", extractDir); */ //string extractDir = @"D:\FTP14\WORK\본사_도로2조_LTED_SKT_L5_고양시 일산동구_20181015_20181017113119\"; //string zipfileFullPath = @"D:\FTP14\WORK\본사_도로2조_LTED_SKT_L5_고양시 일산동구_20181015_20181017113119.zip"; string zipFilefullPath = row.ZipfileFullPath + @"\" + row.ZipFileName; SevenZipCall("x -o\"" + extractDir + "\" -r -y \"" + zipFilefullPath + "\""); /*.Net Framework 이용 ㅠㅠ FTP서버에서 같은 닷넷버전인데 오류발생에 따른 7zip 이용한다. string zipPath = row.ZipfileFullPath + "\\" + row.ZipFileName; //string extractPath = @"D:\FTP14\TEST\본사_도로2조_CSFB_SKT_AUTO_청주시서원구_20180829"; ZipFile.ExtractToDirectory(zipPath, extractDir); */ } catch (Exception ex) { row.ExtractFlag = Define.CON_MSG_ERROR; row.CurState = Define.con_STATE_ERR_UNZIP; SetLog(row,"ERR", "압축 해제 실패 : " + ex.ToString()); //AddLogFile(row, "ERR:UnZIpProc", "압축 해제 실패" + ex.ToString()); return false; } row.ExtractFlag = Define.CON_MSG_COMPLETE; row.CurState = Define.con_STATE_COMPLETE_UNZIP; row.ZipfileFullPath = orgExtractDir; return true; //바로 파싱 들어가기 떄문에 굳이 여기서 업뎃 할필요 없을듯함 //iqaService.updateZipfileInfo(row, ""); } /* private void extractFile(string sourceFile, string destinationFile) { try { ZipFile.ExtractToDirectory(sourceFile, destinationFile); } catch (Exception ex) { Console.WriteLine("exception: {0}", ex.ToString()); } } */ /* 파일 이동 한다. * */ private async void MoveFile(string sourceFile, string destinationFile) { try { using (FileStream sourceStream = File.Open(sourceFile, FileMode.Open)) { using (FileStream destinationStream = File.Create(destinationFile)) { await sourceStream.CopyToAsync(destinationStream); sourceStream.Close(); File.Delete(sourceFile); } } } catch (IOException ioex) { //MessageBox.Show("An IOException occured during move, " + ioex.Message); //result = ioex.HResult; util.Log("ERR:MoveFile", ioex.Message); throw ioex; } catch (Exception ex) { //MessageBox.Show("An Exception occured during move, " + ex.Message); //result = ex.HResult; util.Log("ERR:MoveFile", ex.Message); throw ex; } } private void btnTerminal_Click(object sender, EventArgs e) { Exec("cmd.exe", ""); } private void btnConvertorRun_Click(object sender, EventArgs e) { MenuItem[] menuItems = new MenuItem[]{ new MenuItem("Inno LTE Data 컨버터",new System.EventHandler(this.onClickMenuConvertor)) , new MenuItem("Inno HSDPA Data",new System.EventHandler(this.onClickMenuConvertor)) , new MenuItem("Inno LTE 음성(M to M) 컨버터",new System.EventHandler(this.onClickMenuConvertor)) , new MenuItem("-") , new MenuItem("STI 컨버터",new System.EventHandler(this.onClickMenuConvertor)) }; ContextMenu buttonMenu = new ContextMenu(menuItems); buttonMenu.Show(btnConvertorRun, new System.Drawing.Point(0, 20)); } private void runServyceType2RunConvertor(string serviceType,string path,Boolean bSti) { int nIdx = 0; if (bSti) { nIdx = 4; } else { serviceType = serviceType.ToUpper(); if (serviceType == "LTED") { nIdx = 0; } else if (serviceType == "LTEV" || serviceType == "HDV" || serviceType == "HDVML" || serviceType == "CSFB" || serviceType == "CSFBML") { nIdx = 2; } else if (serviceType == "HSDPA") { nIdx = 1; } else if (serviceType == "5G") { nIdx = 3; } } execConvertor(nIdx, path); } private void execConvertor(int index , string path) { //추후 정리하자 ㅠㅠ string type = ""; switch (index) { case 0: type = "From/Ax`L "; break; case 1: type = "From/Ax`H "; break; case 2: type = "From/Ax`L "; break; case 3: type = "From/Ax`5G "; break; } if (path.Length > 0) { type = ""; } switch (index) { case 0: case 3: // Inno LTE Data 컨버터 //Exec("D:\\INNOWHB\\QMS-W.exe", type + path + " L_Data.cfg "); Exec("D:\\INNOWHB\\QMS-W.exe", type + "\"" + path + "\"" +" L_Data.cfg "); break; case 1: // Inno HSDPA Data Exec("D:\\INNOWHB\\QMS-W.exe", type + "\"" + path + "\"" + " H_Data.cfg"); break; case 2: // Inno LTE 음성(M to M) 컨버터 Exec("D:\\INNOWHB\\QMS-W.exe", type + "\"" + path + "\"" + " L_Voice.cfg"); break; case 4: // STI 컨버터 if (path.Length <= 0) { Exec("D:\\STI\\QMS Export.exe", ""); } else { Exec("D:\\STI\\QMSExportConsole.exe", path + " " + @"D:\STI\Check List"); } break; default: Console.WriteLine("Default case"); break; } } private void reSendFtp(FileProcess row, string localPath) { //ControllerServerEntity freeFtpServer = iqaService.getFreeFtpServerInfo(); ControllerServerEntity freeFtpServer = m_dicFtpInfo[Define.con_FTP_QMS]; if (freeFtpServer == null) { SetLog(row, "ERR", "FTP 서버 정보 가져오기 실패"); AddLogFile(row, "ERR:reSendFtp", "FTP 서버 정보 가져오기 실패"); return; } SendFtp(row, freeFtpServer, localPath, true); //성공시 폴더 삭제 //dbUpdate한다. row.FtpSendFlag = Define.CON_MSG_COMPLETE; row.Complete = true; SetLog(row, "INFO", "처리 완료"); UpdateRowFileProcess(row); row.CurState = Define.con_STATE_WORK_COMPLETE; //dbUpdateZipfileComplete(row); iqaService.updateZipFileAllInfo(row); } private Boolean SendSFtp(FileProcess row , ControllerServerEntity freeServerInfo , string localPath, Boolean flagResend) { WebClient webClient = new WebClient(); NameValueCollection postData = new NameValueCollection(); int nFtpFileCnt = 0; int nFtpSuccessCnt = 0; string fileName = ""; try { using (var client = new SftpClient(freeServerInfo.Ip , Convert.ToInt32(freeServerInfo.Port), freeServerInfo.Id, freeServerInfo.Password)) { client.Connect(); client.ChangeDirectory(freeServerInfo.Path); string[] files = Directory.GetFiles(localPath); foreach (string filepath in files) { string extension = Path.GetExtension(filepath); //qms만 전송한다. if (extension.ToUpper() != ".QMS") { continue; } fileName = Path.GetFileName(filepath); ZipFileDetailEntity detail = row.findZipfileDetail("qmsNm", fileName); if (detail != null) { nFtpFileCnt++; try { using (FileStream fs = new FileStream(filepath, FileMode.Open)) { long totalLength = fs.Length; client.BufferSize = (uint)totalLength; client.UploadFile(fs, detail.QmsfileNmChg); nFtpSuccessCnt++; detail.FlagFtpSend = Define.con_SUCCESS; } } catch (Exception exFtp) { SetLog(row, "ERR", "[ERR]:[SendSFtp]:" + exFtp.Message); //AddLogFile(row, "ERR:SendSFtp", exFtp.Message); if (detail != null) { detail.FlagFtpSend = Define.con_FAIL; } } } } row.FtpSendServer = freeServerInfo.Name; row.FtpSendFileCnt = nFtpFileCnt; row.FtpSendSuccessCnt = nFtpSuccessCnt; row.FtpSendFlag = Define.CON_MSG_COMPLETE; //client.ChangeDirectory(freeServerInfo.Path); //WAV FILE 전송 string[] directories = Directory.GetDirectories(localPath); client.ChangeDirectory(freeServerInfo.Path+"/MOV/"); String waveFolder = ""; string sUnzipFile = ""; foreach (string directoryPath in directories) { sUnzipFile = Path.GetFileNameWithoutExtension(directoryPath); ZipFileDetailEntity detail = row.findZipfileDetail("onlyUnzipNm", sUnzipFile); if (detail == null) { continue; } //WAVE 폴더 Qms내부 이름으로 디렉토리 생성 //확장자 포함으로 폴더 생성요청 waveFolder = Path.GetFileName(detail.QmsfileNmChg); client.CreateDirectory(freeServerInfo.Path + "/MOV/" + waveFolder); client.ChangeDirectory(freeServerInfo.Path + "/MOV/"+ waveFolder + "/"); List<SendFileInfo> lstWaveFileInfo = new List<SendFileInfo>(); string[] wavFiles = Directory.GetFiles(directoryPath); foreach (string wavFilePath in wavFiles) { string extension = Path.GetExtension(wavFilePath); string wavFileName = Path.GetFileName(wavFilePath); if (extension.ToUpper() != ".WAV") { continue; } SendFileInfo wavInfo = new SendFileInfo(); wavInfo.FileName = wavFileName; //WAV면 전송한다. try { using (FileStream fs = new FileStream(wavFilePath, FileMode.Open)) { long totalLength = fs.Length; client.BufferSize = (uint)totalLength; client.UploadFile(fs, wavFileName); wavInfo.FlagSend = "1"; } } catch (Exception exFtp) { SetLog(row, "ERR", "[ERR]:[SendSFtp Wav]:" + exFtp.Message); //AddLogFile(row, "ERR:SendSFtp Wav", exFtp.Message); wavInfo.FlagSend = "0"; } lstWaveFileInfo.Add(wavInfo); } if (lstWaveFileInfo.Count > 0) { detail.IsWaveFile = "1"; detail.WaveFileInfo = lstWaveFileInfo; } else { detail.IsWaveFile = "0"; } } client.Disconnect(); } } catch(Exception exception) { SetLog(row, "ERR", "[ERR]:[SendSFtp]:" + exception.Message); //AddLogFile(row, "ERR:SendSFtp", exception.Message); return false; } return true; } private Boolean sendSFtpWav(FileProcess row , string localPath) { ControllerServerEntity freeServerInfo = m_dicFtpInfo[Define.con_FTP_WAV]; try { //string fileName = ""; //int nFtpFileCnt = 0; //int nFtpSuccessCnt = 0; using (var client = new SftpClient(freeServerInfo.Ip, Convert.ToInt32(freeServerInfo.Port), freeServerInfo.Id, freeServerInfo.Password)) { client.Connect(); client.ChangeDirectory(freeServerInfo.Path); //WAV FILE 전송 string[] directories = Directory.GetDirectories(localPath); client.ChangeDirectory(freeServerInfo.Path); String waveFolder = ""; string sUnzipFile = ""; foreach (string directoryPath in directories) { sUnzipFile = Path.GetFileNameWithoutExtension(directoryPath); ZipFileDetailEntity detail = row.findZipfileDetail("onlyUnzipNm", sUnzipFile); if (detail == null) { continue; } //WAVE 폴더 Qms내부 이름으로 디렉토리 생성 //확장자 포함으로 폴더 생성요청 waveFolder = Path.GetFileName(detail.QmsfileNmChg); client.CreateDirectory(freeServerInfo.Path + waveFolder); client.ChangeDirectory(freeServerInfo.Path + waveFolder + "/"); List<SendFileInfo> lstWaveFileInfo = new List<SendFileInfo>(); string[] wavFiles = Directory.GetFiles(directoryPath); foreach (string wavFilePath in wavFiles) { string extension = Path.GetExtension(wavFilePath); string wavFileName = Path.GetFileName(wavFilePath); if (extension.ToUpper() != ".WAV") { continue; } SendFileInfo wavInfo = new SendFileInfo(); wavInfo.FileName = wavFileName; //WAV면 전송한다. try { using (FileStream fs = new FileStream(wavFilePath, FileMode.Open)) { long totalLength = fs.Length; client.BufferSize = (uint)totalLength; client.UploadFile(fs, wavFileName); wavInfo.FlagSend = "1"; } } catch (Exception exFtp) { SetLog(row, "ERR", "sendSFtpWav:" + exFtp.Message); //AddLogFile(row, "ERR:SendSFtp Wav", exFtp.Message); wavInfo.FlagSend = "0"; } lstWaveFileInfo.Add(wavInfo); } if (lstWaveFileInfo.Count > 0) { detail.IsWaveFile = "1"; detail.WaveFileInfo = lstWaveFileInfo; } else { detail.IsWaveFile = "0"; } } client.Disconnect(); } } catch (Exception exception) { SetLog(row, "ERR", "sendSFtpWav:" + exception.Message); return false; } return true; } private Boolean SendFtp(FileProcess row , ControllerServerEntity freeServerInfo , string localPath , Boolean flagResend) { int nFtpFileCnt = 0; int nFtpSuccessCnt = 0; string fileName = ""; string ftpUrl = "ftp://" + freeServerInfo.Ip + ":" + freeServerInfo.Port + "/" + freeServerInfo.Path; try { Ftp ftpClient = new Ftp(ftpUrl, freeServerInfo.Id, freeServerInfo.Password); string[] files = Directory.GetFiles(localPath); foreach (string filepath in files) { string extension = Path.GetExtension(filepath); //qms만 전송한다. if (extension.ToUpper() != ".QMS") { continue; } fileName = Path.GetFileName(filepath); ZipFileDetailEntity detail = row.findZipfileDetail("qmsNm", fileName); if (detail != null) { nFtpFileCnt++; Boolean bSuccess = ftpClient.upload(detail.QmsfileNmChg, filepath); if (bSuccess) { nFtpSuccessCnt++; detail.FlagFtpSend = Define.con_SUCCESS; } else { SetLog(row, "ERR", "[ERR]:[SendSFtp]:" + fileName + " FTP 전송 에러발생"); detail.FlagFtpSend = Define.con_FAIL; } } else { SetLog(row, "ERR", "[ERR]:[SendSFtp]:" + fileName + "QMS파일 매칭 못함"); } } row.FtpSendServer = freeServerInfo.Name; row.FtpSendFileCnt = nFtpFileCnt; row.FtpSendSuccessCnt = nFtpSuccessCnt; row.FtpSendFlag = Define.CON_MSG_COMPLETE; //WAV는 SFTP로 보내야 한다고 함 ㅠㅠ #if DEBUG #else sendSFtpWav(row, localPath); #endif //WAV FILE 전송 /* FTP 방식 WAV는 SFTP로 보내야 한다고 함 ㅠㅠ string[] directories = Directory.GetDirectories(localPath); String waveFolder = ""; string sUnzipFile = ""; foreach (string directoryPath in directories) { sUnzipFile = Path.GetFileNameWithoutExtension(directoryPath); ZipFileDetailEntity detail = row.findZipfileDetail("onlyUnzipNm", sUnzipFile); if (detail == null) { continue; } //WAVE 폴더 Qms내부 이름으로 디렉토리 생성 //확장자 포함으로 폴더 생성요청 waveFolder = Path.GetFileName(detail.QmsfileNmChg); ftpClient.createDirectory("MOV/" + waveFolder); List<SendFileInfo> lstWaveFileInfo = new List<SendFileInfo>(); string[] wavFiles = Directory.GetFiles(directoryPath); foreach (string wavFilePath in wavFiles) { string extension = Path.GetExtension(wavFilePath); string wavFileName = Path.GetFileName(wavFilePath); if (extension.ToUpper() != ".WAV") { continue; } SendFileInfo wavInfo = new SendFileInfo(); wavInfo.FileName = wavFileName; Boolean bSuccess = ftpClient.upload("MOV/"+ waveFolder + "/" + wavFileName, wavFilePath); if (bSuccess) { nFtpSuccessCnt++; detail.FlagFtpSend = Define.con_SUCCESS; wavInfo.FlagSend = "1"; } else { SetLog(row, "ERR", "[ERR]:[SendSFtp Wav]:" + fileName + " FTP 전송 에러발생"); detail.FlagFtpSend = Define.con_FAIL; wavInfo.FlagSend = "0"; } lstWaveFileInfo.Add(wavInfo); } if (lstWaveFileInfo.Count > 0) { detail.IsWaveFile = "1"; detail.WaveFileInfo = lstWaveFileInfo; } else { detail.IsWaveFile = "0"; } } */ } catch (Exception exception) { SetLog(row, "ERR", "[ERR]:[SendFtp]:" + exception.Message); //AddLogFile(row, "ERR:SendFtp", exception.Message); return false; } return true; } private Boolean sendSftpEventOrifile(string localPath, ControllerServerEntity freeServerInfo) { //ControllerServerEntity freeServerInfo = m_dicFtpInfo[Define.con_FTP_DRM]; try { using (var client = new SftpClient(freeServerInfo.Ip, Convert.ToInt32(freeServerInfo.Port), freeServerInfo.Id, freeServerInfo.Password)) { //string curFolder = util.GetCurrentDate("{0:yyyyMMdd}"); string remoteFileName = Path.GetFileName(localPath); string curFolder = remoteFileName.Split('_')[2]; curFolder = curFolder.Substring(0, 8); client.Connect(); client.ChangeDirectory(freeServerInfo.Path + curFolder + "/"); try { using (FileStream fs = new FileStream(localPath, FileMode.Open)) { long totalLength = fs.Length; client.BufferSize = (uint)totalLength; client.UploadFile(fs, remoteFileName); } } catch (Exception exFtp) { SetLog(null, "ERR", "sendSftpEventOrifile:" + exFtp.Message.ToString()); } client.Disconnect(); } } catch (Exception ex) { SetLog(null, "ERR", "sendSftpEventOrifile:" + ex.Message.ToString()); return false; } return true; } private Boolean sendFtpEventOrifile(ControllerServerEntity freeServerInfo , string localPath) { Boolean bSuccess = false; string ftpUrl = "ftp://" + freeServerInfo.Ip + ":" + freeServerInfo.Port + "/" + freeServerInfo.Path; try { Ftp ftpClient = new Ftp(ftpUrl, freeServerInfo.Id, freeServerInfo.Password); string remoteFileName = Path.GetFileName(localPath); bSuccess = ftpClient.upload(remoteFileName , localPath); if (bSuccess) { } else { //SetLog(row, "[ERR]:[SendSFtp]:" + fileName + " FTP 전송 에러발생"); //detail.FlagFtpSend = Define.con_FAIL; } /* row.FtpSendServer = freeServerInfo.Name; row.FtpSendFileCnt = nFtpFileCnt; row.FtpSendSuccessCnt = nFtpSuccessCnt; row.FtpSendFlag = Define.CON_MSG_COMPLETE; */ } catch (Exception exception) { //SetLog(row, "[ERR]:[SendFtp]:" + exception.Message); util.Log("ERR:sendFtpEventOrifile", exception.Message); } return bSuccess; } private void onClickMenuConvertor(Object sender, System.EventArgs e) { int nMenuIdx = ((MenuItem)sender).Index; execConvertor(nMenuIdx,""); } private Boolean SevenZipCall (string arg) { Boolean bComplete = false; try { string zPath = Define.CON_ZIP_EXE_PATH + "7z.exe"; System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo(); proc.FileName = zPath; proc.Arguments = arg; //proc.RedirectStandardInput = true; //proc.RedirectStandardOutput = true; //proc.RedirectStandardError = true; //proc.UseShellExecute = false; //proc.CreateNoWindow = true; proc.WindowStyle = ProcessWindowStyle.Hidden; System.Diagnostics.Process p = System.Diagnostics.Process.Start(proc); /* while (!p.HasExited) { outPut = p.StandardOutput.ReadLine(); outPut += "\n" + outPut; } p.Close(); */ p.WaitForExit(); bComplete = true; } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); throw ex; } return bComplete; } private void Exec(string path , string arg) { try { if (arg.Length <= 0) { System.Diagnostics.Process.Start(path); } else { System.Diagnostics.Process.Start(path, arg); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void runConvertor(String flag) { try { System.Diagnostics.Process.Start("D:\\INNOWHB\\QMS-W.exe", flag); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void cboFtpServer_SelectedIndexChanged(object sender, EventArgs e) { //서비스 감시중에는 변경 못하도록 한다. m_ftpId = Convert.ToString(cboFtpServer.SelectedIndex + 1); util.SetIniWriteString("FTP", "SELECT", GetFtpName(m_ftpId), Application.StartupPath + "\\controllerSet.Ini"); } private void btnService_Click(object sender, EventArgs e) { if (m_ServiceOnIng && btnService.Enabled) { //우선 새로 들어오는 Zip파일들 감시는 중지 시킨다. if (m_zipFileWatcher.EnableRaisingEvents) { m_zipFileWatcher.EnableRaisingEvents = false; } } else if (m_ServiceOnIng && btnService.Enabled == false) //서비스 중지 요청중... { return; } m_bServiceOnOffButton = !m_bServiceOnOffButton; ServiceOnOff(); } private void dgvProcess_Click(object sender, EventArgs e) { } private void dgvProcess_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 0) { DataGridViewTextBoxCell cell = (DataGridViewTextBoxCell)dgvProcess.Rows[e.RowIndex].Cells[11]; string fileDir = (string)cell.Value; Exec("explorer.exe", fileDir); } } private void PopFileModify(string zipfileNm) { popFileInfo dlg = new popFileInfo(); dlg.ZipfileInfo = m_dicFileProcessErr[zipfileNm]; dlg.StartPosition = FormStartPosition.CenterParent; if (dlg.ShowDialog(this) == DialogResult.OK) { // Read the contents of testDialog's TextBox. } } private void dgvErrorFile_CellClick(object sender, DataGridViewCellEventArgs e) { string zipfileNm = ""; DataGridViewTextBoxCell cell = (DataGridViewTextBoxCell)dgvErrorFile.Rows[e.RowIndex].Cells[Define.con_KEY_PROCESSERROR_COLIDX]; zipfileNm = (string)cell.Value; if (e.ColumnIndex == 0) { if (m_dicFileProcessErr.ContainsKey(zipfileNm)) { string fileDir = m_dicFileProcessErr[zipfileNm].ZipfileFullPath; Exec("explorer.exe", fileDir); } }else if (e.ColumnIndex == 5) { if (m_dicFileProcessErr.ContainsKey(zipfileNm)) { FileProcess selInfo = m_dicFileProcessErr[zipfileNm]; if (selInfo.FileNameRule == Define.CON_MSG_ERROR) { PopFileModify(zipfileNm); }else if (selInfo.FtpSendFlag == Define.CON_MSG_COMPLETE && selInfo.FtpSuccessFlag == Define.con_FAIL) { //FTP 재전송 한다. DialogResult result = MessageBox.Show("FTP 재전송 하시겠습니까?", "FTP 재전송", MessageBoxButtons.YesNoCancel); if (result == DialogResult.Yes) { reSendFtp(selInfo, selInfo.ZipfileFullPath); } } } } } private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { if (m_bServiceOnOffButton && m_ServiceOnIng) { MessageBox.Show("아직 작업 처리중입니다. 잠시후 다시 종료하여 주십시요."); e.Cancel = true; } m_bServiceOnOffButton = false; m_formClose = true; EndTimerServiceBtn(); timer.Dispose(); //Application.ExitThread(); //Environment.Exit(0); } private void dgvEnv_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 0) { popEnvSet dlg = new popEnvSet(); dlg.LstFile = m_lstFile; dlg.LstServer = m_lstServer; //dlg.Parent = this; dlg.StartPosition = FormStartPosition.CenterParent; if (dlg.ShowDialog(this) == DialogResult.OK) { // Read the contents of testDialog's TextBox. if (dlg.m_bSaved) { //재조회한다. if (!DBContollerSetInfo(false)) { MessageBox.Show("컨트롤러 실행에 필요한 데이타를 가져오는데 실패하였습니다.\n관리자에게 문의하십시요."); this.Close(); return; } UpdateRowEnv(); } } } } public void loadingOn(string url) { ucLoadingBar.On(url); } public void loadingOff() { ucLoadingBar.Off(); } private void frmMain_FormClosed(object sender, FormClosedEventArgs e) { } private void frmMain_Resize(object sender, EventArgs e) { } private void btnWorkQueCOnfirm_Click(object sender, EventArgs e) { } private void btnAbnormalSearch_Click(object sender, EventArgs e) { GetAbnormalZipfileList2Grid(); } private void btnAbnormalApply_Click(object sender, EventArgs e) { string defaultPath = GetDefaultFtpPath(); string zipfileNm = ""; string fullPath = "" , dirFlag= ""; List<string> zipfileNms = new List<string>(); ucLoadingBar.On("처리중..."); string flagSave = "copy"; /* if (rdbMove.Checked) { flagSave = "move"; } */ try { foreach (DataGridViewRow r in dgvAbnormalZipfile.Rows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)r.Cells[0]; if ((bool)chk.Value) { zipfileNm = (string)((DataGridViewTextBoxCell)r.Cells[1]).Value; fullPath = (string)((DataGridViewTextBoxCell)r.Cells[4]).Value; dirFlag = (string)((DataGridViewTextBoxCell)r.Cells[5]).Value; zipfileNms.Add(zipfileNm); //WOKR 폴더로 COPY한다. if (dirFlag != "root" && dirFlag.Length > 0) { if (!util.FileSave(flagSave, fullPath, defaultPath + "\\" + GetSystemZipfileNm2OrgFIleName(zipfileNm))) { ucLoadingBar.Off(); MessageBox.Show("파일 처리중 실패 하였습니다."); return; } } } } //DB 삭제 처리 SaveResultInfo result = iqaService.deleteAbnomalZipfile(zipfileNms); ucLoadingBar.Off(); if (result.Flag == 1) { MessageBox.Show("정상처리 되었습니다 확인후 서비스를 구동하여 주십시요."); Exec("explorer.exe", defaultPath); //선택된 그리드 삭제한다. foreach (string key in zipfileNms) { if (key != null && key != "") { //화면 그리드 삭제 한다. int nDeleteRow = dgvAbnormalZipfile.getFindZipFile2RowIndex(key, 1); if (nDeleteRow >= 0) { dgvAbnormalZipfile.Rows.RemoveAt(nDeleteRow); } } } } else { ucLoadingBar.Off(); MessageBox.Show("삭제처리중 오류가 발생했습니다 확인해주십시요."); } } catch (Exception ex) { ucLoadingBar.Off(); Console.WriteLine(ex.Message.ToString()); MessageBox.Show(ex.Message.ToString()); } } private void btnWorkDirDel_Click(object sender, EventArgs e) { string defaultPath = GetDefaultFtpPath(); if (util.AllDeleteInDirectory(defaultPath + "\\" + Define.con_DIR_WORK)) { MessageBox.Show("WORK 폴더 정리 되었습니다."); } else { MessageBox.Show("WORK 폴더 정리 실패 로그를 참조하여주십시요."); } } private void dgvAbnormalZipfile_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.ColumnIndex == 0 && e.RowIndex == -1) { e.PaintBackground(e.ClipBounds, false); Point pt = e.CellBounds.Location; // where you want the bitmap in the cell int nChkBoxWidth = 15; int nChkBoxHeight = 15; int offsetx = (e.CellBounds.Width - nChkBoxWidth) / 2; int offsety = (e.CellBounds.Height - nChkBoxHeight) / 2; pt.X += offsetx; pt.Y += offsety; CheckBox cb = new CheckBox(); cb.Size = new Size(nChkBoxWidth, nChkBoxHeight); cb.Location = pt; cb.Checked = true; cb.CheckedChanged += new EventHandler(dgvAbnormalZipfile_CheckedChanged); ((DataGridView)sender).Controls.Add(cb); e.Handled = true; } } private void dgvAbnormalZipfile_CheckedChanged(Object sender , EventArgs e) { //전체 선택 해제시 체크 선택되있을시 안그려지는 갱신 안되는 문제 때문(화면상에만) if (dgvAbnormalZipfile.Rows.Count > 0) { dgvAbnormalZipfile.CurrentCell = dgvAbnormalZipfile.Rows[dgvAbnormalZipfile.CurrentRow.Index].Cells[1]; } foreach (DataGridViewRow r in dgvAbnormalZipfile.Rows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)r.Cells[0]; chk.Value = ((CheckBox)sender).Checked; } } private void btnConvertorError_Click(object sender, EventArgs e) { string defaultPath = GetDefaultFtpPath(); string zipfileNm = ""; string fullPath = "", dirFlag = ""; List<string> zipfileNms = new List<string>(); ucLoadingBar.On("처리중..."); try { foreach (DataGridViewRow r in dgvAbnormalZipfile.Rows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)r.Cells[0]; if ((bool)chk.Value) { zipfileNm = (string)((DataGridViewTextBoxCell)r.Cells[1]).Value; fullPath = (string)((DataGridViewTextBoxCell)r.Cells[4]).Value; dirFlag = (string)((DataGridViewTextBoxCell)r.Cells[5]).Value; zipfileNms.Add(zipfileNm); if (dirFlag == "work" && dirFlag.Length > 0) { string zipfileDir = Path.GetFileNameWithoutExtension(zipfileNm); string sMoveDir = defaultPath + "\\" + Define.con_DIR_CONVERT + "\\" + zipfileDir; DirectoryInfo diChk = new DirectoryInfo(sMoveDir); if (diChk.Exists == false) { diChk.Create(); } //convert error 폴더로 이동한다. if (!util.FileSave("move", fullPath, sMoveDir + "\\" + GetSystemZipfileNm2OrgFIleName(zipfileNm))) { ucLoadingBar.Off(); MessageBox.Show("파일 이동 실패 하였습니다."); return; } Directory.Delete(defaultPath + "\\" + Define.con_DIR_WORK + "\\" + zipfileDir, true); } } } //컨버터 비정상 오류 처리 SaveResultInfo result = iqaService.updateZipfileState(zipfileNms,Define.con_STATE_ERR_CONV_ABNORMAL); ucLoadingBar.Off(); if (result.Flag == 1) { MessageBox.Show("컨버터 오류 폴더에 백업하였으며 DB 업데이트 완료하였습니다."); Exec("explorer.exe", defaultPath + "\\" + Define.con_DIR_CONVERT); //선택된 그리드 삭제한다. foreach (string key in zipfileNms) { if (key != null && key != "") { //화면 그리드 삭제 한다. int nDeleteRow = dgvAbnormalZipfile.getFindZipFile2RowIndex(key, 1); if (nDeleteRow >= 0) { dgvAbnormalZipfile.Rows.RemoveAt(nDeleteRow); } } } } else { MessageBox.Show("컨버터 오류 처리중 오류가 발생했습니다 확인해주십시요."); } } catch (Exception ex) { ucLoadingBar.Off(); Console.WriteLine(ex.Message.ToString()); MessageBox.Show(ex.Message.ToString()); } } private void dgvAbnormalZipfile_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 0) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dgvAbnormalZipfile.Rows[e.RowIndex].Cells[e.ColumnIndex]; chk.Value = !(bool)chk.Value; //DataGridViewCheckBoxColumn cell = (DataGridViewCheckBoxColumn)dgvAbnormalZipfile.Rows[e.RowIndex].Cells[e.ColumnIndex]; } } private void btnZipfileAdd_Click(object sender, EventArgs e) { //기본 FTP 폴더에서 찾는다 string fullPath = ""; string findZipfileNm = ""; string defaultPath = GetDefaultFtpPath(); string backupDir = defaultPath + "\\" + Define.con_DIR_BACK; string wokrDir = defaultPath + "\\" + Define.con_DIR_WORK; string zipfileNm = txtZipfileNm.Text; string findDirFlag = ""; Boolean bFine = false; findZipfileNm = GetSystemZipfileNm2OrgFIleName(zipfileNm); bFine = util.FindDir2File(defaultPath, findZipfileNm, ref fullPath); if (!bFine) { //BACKUP 폴더에서 찾는다. findZipfileNm = zipfileNm; bFine = util.FindDir2File(backupDir, findZipfileNm, ref fullPath); if (bFine) { findDirFlag = "backup"; } else { //WORK 폴더에서 찾는다. bFine = util.FindDir2File(wokrDir, findZipfileNm, ref fullPath); if (bFine) { findDirFlag = "work"; } } } else { findDirFlag = "root"; } dgvAbnormalZipfile.RowCount = dgvAbnormalZipfile.RowCount + 1; int nRow = dgvAbnormalZipfile.RowCount - 1; DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dgvAbnormalZipfile.Rows[nRow].Cells[0]; chk.Value = false; dgvAbnormalZipfile.Rows[nRow].Cells[1].Value = zipfileNm; dgvAbnormalZipfile.Rows[nRow].Cells[2].Value = "확인요망"; if (bFine) { dgvAbnormalZipfile.Rows[nRow].Cells[3].Value = "발견"; dgvAbnormalZipfile.Rows[nRow].Cells[4].Value = fullPath; dgvAbnormalZipfile.Rows[nRow].Cells[5].Value = findDirFlag; } else { dgvAbnormalZipfile.Rows[nRow].Cells[3].Value = "미발견"; dgvAbnormalZipfile.Rows[nRow].Cells[4].Value = ""; dgvAbnormalZipfile.Rows[nRow].Cells[5].Value = ""; } /* //WOKR 폴더로 COPY한다. if (findDirFlag != "root" && findDirFlag.Length > 0) { if (!util.FileSave("copy", fullPath, defaultPath + "\\" + GetSystemZipfileNm2OrgFIleName(zipfileNm))) { ucLoadingBar.Off(); MessageBox.Show("파일 복사중 실패 하였습니다."); return; } } */ } private void btnForceWebService_Click(object sender, EventArgs e) { if (rdoServer.Checked) { iqaService.IsForceWeb1 = false; } else { iqaService.IsForceWeb1 = true; } } /* not used : 추후 확인후 삭제 private void execUnzipList(string path) { try { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.FileName = "CMD.exe"; startInfo.WorkingDirectory = Define.CON_ZIP_EXE_PATH; //startInfo.Arguments = "7z.exe l D:\\FTP14\\WORK\\본사_도로501조_LTED_SKT_AUTO_테스트_20180402_20180417130636.zip > D:\\FTP14\\WORK\\test2.txt"; startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; process.EnableRaisingEvents = false; process.StartInfo = startInfo; process.Start(); //process.StandardInput.Write("7z.exe l D:\\FTP14\\WORK\\본사_도로501조_LTED_SKT_AUTO_테스트_20180402_20180417130636.zip > D:\\FTP14\\WORK\test2.txt" + Environment.NewLine); process.StandardInput.Write("7z.exe " + path + Environment.NewLine); process.StandardInput.Close(); process.Close(); } catch (Exception ex) { } } */ } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class ControllerEnvEntity { private string flag = null; private string item = null; private string info1 = null; private string info2 = null; private string info3 = null; public string Flag { get => flag; set => flag = value; } public string Item { get => item; set => item = value; } public string Info1 { get => info1; set => info1 = value; } public string Info2 { get => info2; set => info2 = value; } public string Info3 { get => info3; set => info3 = value; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class ControllerFileKeepEntity { private string item = ""; private string dirPath = ""; private string period = ""; public string Period { get => period; set => period = value; } public string Item { get => item; set => item = value; } public string DirPath { get => dirPath; set => dirPath = value; } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Web; using System.IO; using System.Threading; using IqaController.entity; namespace IqaController.service { static class iqaService { public static frmMain mainForm = null; private static bool isForceWeb1 = false; public static bool IsForceWeb1 { get => isForceWeb1; set => isForceWeb1 = value; } /* 서비스 공통 */ public static string serviceCall(Dictionary<string, Object> param, string url) { string result; var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(param); try { using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { streamWriter.Write(jsonStr); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { result = streamReader.ReadToEnd(); } return result; } catch (WebException ex) { Boolean bConnectFail = false; var status = ex.Status; if (status != null) { //원격서버 죽어있음(배포중) - 재기동까지 대기 모드? if (status == WebExceptionStatus.ConnectFailure) { bConnectFail = true; } else if (status == WebExceptionStatus.ReceiveFailure) { bConnectFail = true; } } if (bConnectFail) { //재호출 한다. return Define.con_SERVICE_CON_FAIL; } else { string errDesc = ex.Message.ToString(); util.Log("sendService : error url = ", url); util.Log("sendService : error desc = ", errDesc); Console.WriteLine(errDesc); return "NOK::" + ex.Message.ToString(); } } catch (Exception ex) { string errDesc = ex.Message.ToString(); util.Log("sendService : error url = ", url); util.Log("sendService : error desc = ", errDesc); Console.WriteLine(errDesc); return "NOK::" + ex.Message.ToString(); } } public static string sendService(Dictionary<string, Object> param, string url, Boolean bWait = true) { //톰캣 배포시 끊기는 현상떄문에 오류 막기위해 재전송처리 Boolean bUrlToggle = true; string fullUrl = ""; //fullUrl = Define.CON_WEB_SERVICE + url; mainForm.loadingOn(url); Boolean bReSend = false; string result = "start"; while ((result == Define.con_SERVICE_CON_FAIL && bWait) || result == "start") { if (bReSend) { mainForm.loadingOn("[재시도중..]:" + url); } //WEB SERVER CHANGE if (bUrlToggle) { fullUrl = Define.CON_WEB_SERVICE + url; //WEB_SERVER2 } else { fullUrl = Define.CON_WEB_SERVICE2 + url; //기존 WEB SERVER } //무조건 IQA WEB 서비스 호출한다. 강제 처리 했을경우 if (isForceWeb1) { fullUrl = Define.CON_WEB_SERVICE2 + url; } bUrlToggle = !bUrlToggle; result = iqaService.serviceCall(param, fullUrl); if (result == "ConectFail" && bWait) { bReSend = true; util.Log("sendService : error url = ", url); util.Log("sendService : error desc = ", "ConnectFail로 인한 server start wait..."); Console.WriteLine("ConnectFail로 인한 server start wait..."); Thread.Sleep(2000); } } mainForm.loadingOff(); return result; } public static String IsZipfileCancel(FileProcess row) { String flagCancel = "0"; CommonResultEntity res = null; Dictionary<string, Object> domain = new Dictionary<string, object>(); domain.Add("zipfileNm", HttpUtility.UrlEncode(row.ZipFileName)); string uri = "manage/isZipfileCancel.do"; String result = iqaService.sendService(domain, uri); if (result.IndexOf("NOK") < 0) { res = (CommonResultEntity)Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(CommonResultEntity)); flagCancel = (string)res.Result; } return flagCancel; } /* 컨트롤러 한 Zip 파일 완료 업데이트 */ public static SaveResultInfo updateZipFileAllInfo(FileProcess row) { SaveResultInfo res = null; string uri = "manage/setUpdateZipFileAllInfo.do"; Dictionary<string, Object> domain = row.getDomain(true); //domain.Add("zipfileInfo", domain); String result = iqaService.sendService(domain, uri); if (result.IndexOf("NOK") < 0) { res = (SaveResultInfo)Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(SaveResultInfo)); } else { res = new SaveResultInfo(); res.Flag = 0; res.Desc = "zip파일 완료 DB 저장오류 발생"; } return res; } public static SaveResultInfo updateEventOrifileSendResult(EventOriFileProcResult eventOrifileProc, List<EventOriFileEntity> drmFileResults) { string uri = "manage/setUpdateEventOrifileSendResult.do"; Dictionary<string, Object> domain = eventOrifileProc.getDomain(); List<Dictionary<string, Object>> lstDomain = new List<Dictionary<string, object>>(); foreach (EventOriFileEntity drmResult in drmFileResults) { lstDomain.Add(drmResult.getDomain()); } //domain.Add("drmFileResult", drmFileResults); domain.Add("drmFileResult", lstDomain); String result = iqaService.sendService(domain, uri); SaveResultInfo res = null; if (result.IndexOf("NOK") < 0) { res = (SaveResultInfo)Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(SaveResultInfo)); } else { res = new SaveResultInfo(); res.Flag = 0; res.Desc = "Event Drm File Ftp Send Error"; } return res; } public static SaveResultInfo updateZipfileMainInfo(FileProcess row, String flag) { string uri = "manage/insertZipFileInfo.do"; Dictionary<string, Object> domain = row.getDomain(false); Dictionary<string, Object> domainZipMain = (Dictionary<string, Object>)domain["zipfileMain"]; if (flag == Define.con_STATE_START_NAMING) { domainZipMain.Add("startTime", "Y"); //처리 시작시간 } else if (flag == Define.con_STATE_START_UNZIP) { domainZipMain.Add("unzipStartTime", "Y"); //UnZip 시작 시점 업데이트 } else if (flag == Define.con_STATE_START_FTP) { domainZipMain.Add("uploadStartTime", "Y"); //업로드 시작 시점 업데이트 - 화면설계상 없어서 사용안함 } else if (flag == Define.con_STATE_START_CONV) { domainZipMain.Add("convStartTime", "Y"); //컨버터 시작시간 } String result = iqaService.sendService(domain, uri); SaveResultInfo res = null; if (result.IndexOf("NOK") < 0) { res = (SaveResultInfo)Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(SaveResultInfo)); if (res.Flag == 0) { util.Log("[ERR]", "[" + row.ZipFileName + "==>" + res.Desc + "]"); } } else { res = new SaveResultInfo(); res.Flag = 0; res.Desc = "zIP파일 정보 DB 업데이트 오류"; } return res; } /* unzip 파일정보를 업데이트 하고 중복 drm 정보를 얻는다. */ public static CommonResultEntity setUnzipFileInfoUpdateAndGetDupInfo(FileProcess row) { string uri = "manage/setUnzipFileInfoUpdateAndGetDupInfo.do"; Dictionary<string, Object> domain = row.getDomain(true); CommonResultEntity output = new CommonResultEntity(); List<CodeNameEntity> result = null; String jsonResult = iqaService.sendService(domain, uri); if (jsonResult.IndexOf("NOK") < 0) { result = (List<CodeNameEntity>)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResult, typeof(List<CodeNameEntity>)); output.Flag = Define.con_SUCCESS; output.Result = result; } else { string errDesc = jsonResult.Split(':')[1]; output.Result = errDesc; } return output; } public static SaveResultInfo updateZipfileState(List<string> zipfileNms , string curState) { SaveResultInfo output = new SaveResultInfo(); string uri = "manage/updateZipfileState.do"; Dictionary<string, Object> domain = new Dictionary<string, object>(); List<string> encodingZipfileNms = new List<string>(); foreach (string zipfileNm in zipfileNms) { encodingZipfileNms.Add(HttpUtility.UrlEncode(zipfileNm)); } domain.Add("curState", curState); domain.Add("zipfileNms", encodingZipfileNms); String jsonResult = iqaService.sendService(domain, uri); //List<ZipfileInfoEntity> result = null; if (jsonResult.IndexOf("NOK") < 0) { output = (SaveResultInfo)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResult, typeof(SaveResultInfo)); } else { output.Flag = 0; } return output; } public static SaveResultInfo deleteAbnomalZipfile(List<string>zipfileNms) { SaveResultInfo output = new SaveResultInfo(); string uri = "manage/deleteAbnormalZipfile.do"; Dictionary<string, Object> domain = new Dictionary<string, object>(); List<string> encodingZipfileNms = new List<string>(); foreach(string zipfileNm in zipfileNms) { encodingZipfileNms.Add(HttpUtility.UrlEncode(zipfileNm)); } domain.Add("zipfileNms", encodingZipfileNms); String jsonResult = iqaService.sendService(domain, uri); //List<ZipfileInfoEntity> result = null; if (jsonResult.IndexOf("NOK") < 0) { output = (SaveResultInfo)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResult, typeof(SaveResultInfo)); } else { output.Flag = 0; } return output; } /* 비정상 종료된 이력을 DB에서 가져온다. */ public static List<ZipfileInfoEntity> getAbnormalZipfileList(string startDate , string endDate , string procServer) { string uri = "manage/getAbnormalityZipfileList.do"; Dictionary<string, Object> domain = new Dictionary<string, object>(); domain.Add("startDate", startDate); domain.Add("endDate", endDate); domain.Add("procServer", procServer); String jsonResult = iqaService.sendService(domain, uri); CommonResultEntity output = new CommonResultEntity(); //List<ZipfileInfoEntity> result = null; if (jsonResult.IndexOf("NOK") < 0) { output = (CommonResultEntity)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResult, typeof(CommonResultEntity)); } List<ZipfileInfoEntity> result = null; if (output.Flag == "1" && output.Result != null) { jsonResult = output.Result.ToString(); result = (List<ZipfileInfoEntity>)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResult, typeof(List<ZipfileInfoEntity>)); } return result; } /* 전송해야할 Event Drm 파일정보를 가져온다. - FTP 전송을 위해서 * */ public static CommonResultEntity getEventOrifileList(string procServer) { string uri = "manage/getEventOriFileList.do"; Dictionary<string, Object> domain = new Dictionary<string, object>(); domain.Add("isSingleZipFile", "1"); domain.Add("procServer", procServer); String jsonResult = iqaService.sendService(domain, uri); CommonResultEntity output = new CommonResultEntity(); List <EventOriFileEntity> result = null; if (jsonResult.IndexOf("NOK") < 0) { result = (List<EventOriFileEntity>)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResult, typeof(List<EventOriFileEntity>)); output.Flag = Define.con_SUCCESS; output.Result = result; } else { string errDesc = jsonResult.Split(':')[1]; //util.Log("[ERR]:getEventOrifileList", errDesc); output.Result = errDesc; } return output; } /* */ public static SaveResultInfo insertZipfileInfos(List<FileProcess> dbInsertList) { string uri = "manage/insertZipFileInfos.do"; Dictionary<string, Object> domain = new Dictionary<string, object>(); List<Dictionary<string, Object>> lstDomain = new List <Dictionary<string, Object>>(); foreach (FileProcess row in dbInsertList) { Dictionary<string, Object> domainPart = row.getDomain(false); ; lstDomain.Add(domainPart); } domain.Add("zipfileInfos", lstDomain); String result = iqaService.sendService(domain, uri); SaveResultInfo res = null; if (result.IndexOf("NOK") < 0) { res = (SaveResultInfo)Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(SaveResultInfo)); } else { res = new SaveResultInfo(); res.Flag = 0; res.Desc = "통신오류 발생"; } return res; } /* public static ControllerServerEntity getFreeFtpServerInfo() { string uri = Define.CON_WEB_SERVICE + "manage/geFreeServerList.do"; WebClient webClient = new WebClient(); NameValueCollection postData = new NameValueCollection(); ControllerServerEntity freeServerInfo = null; string pagesource = Encoding.UTF8.GetString(webClient.UploadValues(uri, postData)); try { freeServerInfo = (ControllerServerEntity)Newtonsoft.Json.JsonConvert.DeserializeObject(pagesource, typeof(ControllerServerEntity)); } catch (Exception ex) { util.Log("[ERROR(geFreeServerList.do)]", ex.Message); Console.WriteLine(ex.Message.ToString()); } return freeServerInfo; } */ public static CommonResultEntity getControllerFilePeriod(bool bWait) { string uri = "manage/getControllerFilePeriod.do"; Dictionary<string, Object> domain = new Dictionary<string, object>(); String jsonResult = iqaService.sendService(domain, uri, bWait); if (jsonResult == Define.con_SERVICE_CON_FAIL) { return null; } CommonResultEntity output = new CommonResultEntity(); List<ControllerFileKeepEntity> result = null; if (jsonResult.IndexOf("NOK") < 0) { result = (List<ControllerFileKeepEntity>)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResult, typeof(List<ControllerFileKeepEntity>)); output.Flag = Define.con_SUCCESS; output.Result = result; } else { string errDesc = jsonResult.Split(':')[1]; //util.Log("[ERR]:getEventOrifileList", errDesc); output.Result = errDesc; } return output; } public static CommonResultEntity getControllerServer(bool bDrm) { string uri = "manage/getControllerServer.do"; Dictionary<string, Object> domain = new Dictionary<string, object>(); if (bDrm) { domain.Add("flagDrm", "1"); } String jsonResult = iqaService.sendService(domain, uri); CommonResultEntity output = new CommonResultEntity(); List<ControllerServerEntity> result = null; if (jsonResult.IndexOf("NOK") < 0) { result = (List<ControllerServerEntity>)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResult, typeof(List<ControllerServerEntity>)); output.Flag = Define.con_SUCCESS; output.Result = result; } else { string errDesc = jsonResult.Split(':')[1]; output.Result = errDesc; } return output; } } } <file_sep>using System; using System.Collections.Generic; using System.Web; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class SendFileInfo { private string fileName = ""; private string chgFlieName = ""; private string flagSend = ""; public string FileName { get => fileName; set => fileName = value; } public string FlagSend { get => flagSend; set => flagSend = value; } public string ChgFlieName { get => chgFlieName; set => chgFlieName = value; } public SendFileInfo(string fileName, string flagSend, string chgFlieName) { this.fileName = fileName; this.flagSend = flagSend; this.chgFlieName = chgFlieName; } public SendFileInfo() { } public Dictionary<string, Object> getDomain() { Dictionary<string, Object> domain = new Dictionary<string, object>(); domain.Add("fileName", HttpUtility.UrlEncode(this.fileName)); domain.Add("flagSend", this.flagSend); return domain; } } } <file_sep>using System; using System.Collections.Generic; using System.Web; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class EventOriFileEntity { private string zipfile_nm = ""; private string qmsfile_nm = ""; private string qmsfile_nmChg = ""; private string flagFind = ""; public string Zipfile_nm { get => zipfile_nm; set => zipfile_nm = value; } public string Qmsfile_nm { get => qmsfile_nm; set => qmsfile_nm = value; } public string FlagFind { get => flagFind; set => flagFind = value; } public string Qmsfile_nmChg { get => qmsfile_nmChg; set => qmsfile_nmChg = value; } public Dictionary<string, Object> getDomain() { Dictionary<string, Object> domain = new Dictionary<string, object>(); domain.Add("zipfileNm", HttpUtility.UrlEncode(this.zipfile_nm)); domain.Add("qmsfileNm", HttpUtility.UrlEncode(this.qmsfile_nm)); domain.Add("qmsfileNmChg", Qmsfile_nmChg); domain.Add("flagFind", this.flagFind); return domain; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Threading.Tasks; namespace IqaController.entity { class EventOriFileProcResult { private string procServer = ""; private string zipfileNm = ""; private string ftpServer = ""; private string flagUnzip = ""; private string unzipErrLog = ""; private string flagSendFtp = ""; private string ftpErrLog = ""; private string chgCompressFileNm = ""; private string isDrmFind = ""; private string curState = Define.CON_MSG_WAIT; public string ProcServer { get => procServer; set => procServer = value; } public string ZipfileNm { get => zipfileNm; set => zipfileNm = value; } public string FlagUnzip { get => flagUnzip; set => flagUnzip = value; } public string UnzipErrLog { get => unzipErrLog; set => unzipErrLog = value; } public string FlagSendFtp { get => flagSendFtp; set => flagSendFtp = value; } public string FtpErrLog { get => ftpErrLog; set => ftpErrLog = value; } public string FtpServer { get => ftpServer; set => ftpServer = value; } public string ChgCompressFileNm { get => chgCompressFileNm; set => chgCompressFileNm = value; } public string CurState { get => curState; set => curState = value; } public string IsDrmFind { get => isDrmFind; set => isDrmFind = value; } public Dictionary<string, Object> getDomain() { Dictionary<string, Object> domain = new Dictionary<string, object>(); domain.Add("procServer", this.procServer); domain.Add("zipfileNm", HttpUtility.UrlEncode(this.zipfileNm)); domain.Add("ftpServer", this.ftpServer); domain.Add("flagUnzip", this.flagUnzip); domain.Add("unzipErrLog", HttpUtility.UrlEncode(this.unzipErrLog)); domain.Add("flagSendFtp", this.flagSendFtp); domain.Add("ftpErrLog", HttpUtility.UrlEncode(this.ftpErrLog)); domain.Add("chgCompressFileNm", this.chgCompressFileNm); domain.Add("flagFind", this.isDrmFind); return domain; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class ConvertorResult { private string unzipfileNm = ""; private string qmsFileNm = ""; private string flag = ""; private string desc = ""; public string UnzipfileNm { get => unzipfileNm; set => unzipfileNm = value; } public string QmsFileNm { get => qmsFileNm; set => qmsFileNm = value; } public string Flag { get => flag; set => flag = value; } public string Desc { get => desc; set => desc = value; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using IqaController.entity; using System.IO; using System.Net; using System.Web; using System.Collections.Specialized; namespace IqaController { public partial class popEnvSet : Form { public Boolean m_bSaved = false; private List<ControllerServerEntity> m_lstServer = null; //환경설정 수집서버 private List<ControllerFileKeepEntity> m_lstFile = null; //환경설정 파일 보관주기 internal List<ControllerServerEntity> LstServer { get => m_lstServer; set => m_lstServer = value; } internal List<ControllerFileKeepEntity> LstFile { get => m_lstFile; set => m_lstFile = value; } public popEnvSet() { InitializeComponent(); } private void popEnvSet_Load(object sender, EventArgs e) { setControl(); setData(); } private void DBControlsetServer() { NameValueCollection postData = new NameValueCollection(); string uri = Define.CON_WEB_SERVICE + "manage/getControllerServer.do"; WebClient webClient = new WebClient(); string pagesource = Encoding.UTF8.GetString(webClient.UploadValues(uri, postData)); try { m_lstServer = (List<ControllerServerEntity>)Newtonsoft.Json.JsonConvert.DeserializeObject(pagesource, typeof(List<ControllerServerEntity>)); } catch (Exception ex) { } } private void DBControlsetFile() { NameValueCollection postData = new NameValueCollection(); string uri = Define.CON_WEB_SERVICE + "manage/getControllerFilePeriod.do"; WebClient webClient = new WebClient(); string pagesource = Encoding.UTF8.GetString(webClient.UploadValues(uri, postData)); try { m_lstFile = (List<ControllerFileKeepEntity>)Newtonsoft.Json.JsonConvert.DeserializeObject(pagesource, typeof(List<ControllerFileKeepEntity>)); } catch (Exception ex) { } } private void setControl() { dgvServer.addColumn("수집서버 No", 150); dgvServer.addColumn("서버 IP", 150); dgvServer.addColumn("ID", 150); dgvServer.addColumn("PW", 150); dgvServer.addColumn("Path", 150); dgvFile.addColumn("항목", 150); dgvFile.addColumn("디렉토리 Path", 150); dgvFile.addColumn("보관주기", 150); } private void SetDataServer() { foreach (ControllerServerEntity server in m_lstServer) { updateRowServer(server); } } private void setDataFile() { foreach (ControllerFileKeepEntity file in m_lstFile) { updateRowFile(file); ; } } private void setData() { SetDataServer(); setDataFile(); } private void updateRowFile(ControllerFileKeepEntity row) { int nRow = 0; dgvFile.RowCount = dgvFile.RowCount + 1; nRow = dgvFile.RowCount - 1; dgvFile.Rows[nRow].Cells[0].Value = row.Item; dgvFile.Rows[nRow].Cells[1].Value = row.DirPath; dgvFile.Rows[nRow].Cells[2].Value = row.Period + "일"; } private void updateRowServer(ControllerServerEntity row) { int nRow = 0; dgvServer.RowCount = dgvServer.RowCount + 1; nRow = dgvServer.RowCount - 1; dgvServer.Rows[nRow].Cells[0].Value = row.Name; dgvServer.Rows[nRow].Cells[1].Value = row.Ip; dgvServer.Rows[nRow].Cells[2].Value = row.Id; dgvServer.Rows[nRow].Cells[3].Value = row.Password; dgvServer.Rows[nRow].Cells[3].Value = row.Path; } private void btnSave_Click(object sender, EventArgs e) { if (txtServerName.Text == "") { MessageBox.Show("서버명을 입력하여 주십시요."); return; } if (txtServerIp.Text == "") { MessageBox.Show("IP를 입력하여 주십시요."); return; } if (txtServerId.Text == "") { MessageBox.Show("ID를 입력하여 주십시요."); return; } if (txtServerPw.Text == "") { MessageBox.Show("PW를 입력하여 주십시요."); return; } string uri = Define.CON_WEB_SERVICE + "manage/saveContollerServerSet.do"; WebClient webClient = new WebClient(); NameValueCollection postData = new NameValueCollection(); postData.Add("name", HttpUtility.UrlEncode(txtServerName.Text)); postData.Add("ip", txtServerIp.Text); postData.Add("id", txtServerId.Text); postData.Add("password", <PASSWORD>); string pagesource = Encoding.UTF8.GetString(webClient.UploadValues(uri, postData)); try { SaveResultInfo result = (SaveResultInfo)Newtonsoft.Json.JsonConvert.DeserializeObject(pagesource, typeof(SaveResultInfo)); if (result.Flag == 1) { //다시 조회한다. DBControlsetServer(); SetDataServer(); txtServerIp.Text = ""; txtServerId.Text = ""; txtServerPw.Text = ""; MessageBox.Show("저장하였습니다."); m_bSaved = true; } else { MessageBox.Show(result.Desc); } } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } } private void btnSaveFile_Click(object sender, EventArgs e) { if (txtItem.Text == "") { MessageBox.Show("항목을 입력하여 주십시요."); return; } if (txtDirPath.Text == "") { MessageBox.Show("디렉토리를 설정해 주십시요."); return; } if (txtPeriod.Text == "") { MessageBox.Show("보관주기를 입력해주십시요."); return; } string uri = Define.CON_WEB_SERVICE + "manage/saveContollerFileSet.do"; WebClient webClient = new WebClient(); NameValueCollection postData = new NameValueCollection(); postData.Add("item", HttpUtility.UrlEncode(txtItem.Text)); postData.Add("dirPath", txtDirPath.Text); postData.Add("period", txtPeriod.Text); string pagesource = Encoding.UTF8.GetString(webClient.UploadValues(uri, postData)); try { SaveResultInfo result = (SaveResultInfo)Newtonsoft.Json.JsonConvert.DeserializeObject(pagesource, typeof(SaveResultInfo)); if (result.Flag == 1) { //다시 조회한다. DBControlsetFile(); setDataFile(); txtItem.Text = ""; txtDirPath.Text = ""; txtPeriod.Text = ""; MessageBox.Show("저장하였습니다."); m_bSaved = true; } else { MessageBox.Show(result.Desc); } } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } } private void popEnvSet_FormClosing(object sender, FormClosingEventArgs e) { } private void btnDirSel_Click(object sender, EventArgs e) { FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.ShowDialog(); txtDirPath.Text = dialog.SelectedPath; //선택한 다이얼로그 경로 저장 } } } <file_sep>using System; using System.Collections.Generic; using System.Web; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class ZipFileDetailEntity { private string unzipfileNm = ""; private string qmsfileNm = ""; private string qmsfileNmChg = ""; private string flagConvertorResult = ""; private string descConvertorResult = ""; private string flagFtpSend = ""; private string isWaveFile = "0"; private List<SendFileInfo> waveFileInfo = new List<SendFileInfo>(); public string UnzipfileNm { get => unzipfileNm; set => unzipfileNm = value; } public string QmsfileNm { get => qmsfileNm; set => qmsfileNm = value; } public string FlagConvertorResult { get => flagConvertorResult; set => flagConvertorResult = value; } public string DescConvertorResult { get => descConvertorResult; set => descConvertorResult = value; } public string QmsfileNmChg { get => qmsfileNmChg; set => qmsfileNmChg = value; } public string FlagFtpSend { get => flagFtpSend; set => flagFtpSend = value; } public string IsWaveFile { get => isWaveFile; set => isWaveFile = value; } internal List<SendFileInfo> WaveFileInfo { get => waveFileInfo; set => waveFileInfo = value; } public Dictionary<string, Object> getDomain() { Dictionary<string, Object> domain = new Dictionary<string, object>(); domain.Add("unzipfileNm", HttpUtility.UrlEncode(this.unzipfileNm)); domain.Add("qmsfileNm", HttpUtility.UrlEncode(this.qmsfileNm)); domain.Add("qmsfileNmChg", this.qmsfileNmChg); domain.Add("flag", this.flagConvertorResult); domain.Add("desc", HttpUtility.UrlEncode(this.descConvertorResult)); domain.Add("flagFtpSend", this.flagFtpSend); domain.Add("isWaveFile", this.isWaveFile); if (waveFileInfo.Count > 0) { List<Dictionary<string, Object>> lstDomain = new List<Dictionary<string, object>>(); foreach (SendFileInfo wf in this.waveFileInfo) { Dictionary<string, Object> domainPart = wf.getDomain(); lstDomain.Add(domainPart); } domain.Add("waveFileInfo", lstDomain); } return domain; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class ControllerSetInfo { private List<ControllerFileKeepEntity> file = new List<ControllerFileKeepEntity>(); internal List<ControllerFileKeepEntity> File { get => file; set => file = value; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace IqaController { public partial class ButtonEx : Button { public ButtonEx() { InitializeComponent(); this.BackColor = SystemColors.WindowFrame; this.FlatStyle = FlatStyle.Flat; this.ForeColor = SystemColors.Window; } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IqaController.entity { class ControllerServerEntity { private string name = null; private string ip = null; private string id = null; private string password = null; private string path = null; private string port = null; public string Name { get => name; set => name = value; } public string Ip { get => ip; set => ip = value; } public string Id { get => id; set => id = value; } public string Password { get => password; set => password = value; } public string Path { get => path; set => path = value; } public string Port { get => port; set => port = value; } } }
1ad04e4ac71de9ab2db020ec2534877ec81568ec
[ "C#" ]
22
C#
hiphopddori/Controller
9486401e7470357f9819832e210286200544f487
8a2a6410ca5a780c883c70a53fcfff8b8e3343d8
refs/heads/master
<file_sep>let {Cc, Ci} = require('chrome'); let querystring = require('sdk/querystring'); let cookie_service = Cc["@mozilla.org/cookieService;1"].getService(Ci['nsICookieService']); let io_service = Cc["@mozilla.org/network/io-service;1"].getService(Ci['nsIIOService']); let get, set, remove, CookieManager; get = function (domain, key) { var uri = io_service.newURI(domain, null, null); // String containing all cookies for given domain. cookies_string = cookie_service.getCookieString(uri, null); cookie_pairs = querystring.parse(cookies_string, '; ', '='); cookie_val = cookie_pairs[key]; return cookie_val; }; set = function (domain, key, val, expiration) { // String representing all data for this cookie. params_string = ''; params_string += key + '=' + val + ';'; // Domain should start with a dot, so that the cookie is valid for all the // subdomains. E.g. cookie saved with domain '.google.com' is valid for // 'google.com' and 'mail.google.com'. uri = io_service.newURI(domain, null, null); params_string += 'domain=.' + uri.host + ';'; // Expiration timestamp must be added as GMT string. if (typeof expiration === 'number') { now_stamp = (new Date).getTime(); expire_stamp = now_stamp + expiration; expire_string = (new Date(expire_stamp)).toGMTString(); params_string += 'expires=' + expire_string + ';'; } cookie_service.setCookieString(uri, null, params_string, null); }; remove = function (domain, key) { // Remove cookie by saving it with expiration timestamp in the past. set(domain, key, null, -1) } // Convenience object that remembers default values for domain and expiration. // Expiration is set in days instead of milliseconds, as this is the most // common case. CookieManager = (function() { function CookieManager(domain, expiration_days) { this.domain = domain; this.expiration = expiration_days * 24 * 60 * 60 * 1000; } CookieManager.prototype.set = function(key, val) { set(this.domain, key, val, this.expiration); }; CookieManager.prototype.get = function(key) { return get(this.domain, key); }; CookieManager.prototype.remove = function(key) { remove(this.domain, key); }; return CookieManager; })(); // Expose methods to the export object. exports.get = get; exports.set = set; exports.remove = remove; exports.CookieManager = CookieManager; <file_sep>Cookie Manager for Firefox SDK (Jetpack) ======================================== Reusable module for cookie management in Firefox addons. It lets you set, get and remove cookies. Usage ----- ```javascript // Import the module. let cookieManager = require("cookie-manager"); // Set the cookie. // Cookie with key 'aaa' and value 'bbb' will be saved. It will be accessible // on domain 'google.com' and all it's subdomains. The cookie will be valid // for 7 days (expiration time is set in microseconds). cookieManager.set('http://google.com/', 'aaa', 'bbb', 7*24*60*60*1000); // Get cookie's value. var cookie_value = cookieManager.get('http://google.com/', 'aaa'); // => 'bbb' // Remove cookie. cookieManager.remove('http://google.com/', 'aaa'); // Removed or non-existing cookies will return null. removed_cookie = cookieManager.get(domain, 'aaa'); // => null non_existing_cookie = cookieManager.get(domain, 'zzz'); // => null ``` Convenience object ------------------ When working with cookies, most of the time you just want to set and get cookies, that are specified for your project's domain. Also, you usualy set cookie's expiration in days instead of milliseconds. That's why there's a handy convenience object: ```javascript // Import the module. let CookieManager = require('cookie-manager').CookieManager; // Create your object with default values. All cookies will be saved for // domain '.google.com' and will be valid for 7 days. var MyCookies = new CookieManager('http://google.com/', 7); MyCookies.set('aaa', 'bbb'); MyCookies.get('aaa'); // => 'bbb' MyCookies.remove('aaa'); ``` Instalation ----------- You can follow the [official documentation for installing modules][1], which recommends downloading and extracting the source code of module manually. But I think the better approach is to **clone the module from the GIT**, because it is easier and it will allow you to simply update the module anytime. You can clone the module to the ```packages``` directory in your SDK folder (it will be available for all your existing and future addons), or you can clone it to the ```packages``` directory in your addon (it will be available only for that addon). ```sh # go to the packages directory cd packages # clone the repository (this will create the 'cookie-manager' directory) git clone https://github.com/fczbkk/cookie-manager.git ``` Don't forget to **add the module dependency** to your addons' ```package.json```: ```json ... "dependencies": ["cookie-manager"] ... ``` If you want to **update the module** later, just pull the most recent version from GIT: ```sh cd packages/cookie-manager git pull ``` [1]: https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/tutorials/adding-menus.html
00568cca64c309eea28ec1042d2d84159141997c
[ "JavaScript", "Markdown" ]
2
JavaScript
fczbkk/cookie-manager
0b8861ffef97b37a090fbfb3e5879242337d1da4
721ff5c4a026b9eddd27d4b4b6ecac28bf188ad6
refs/heads/master
<file_sep>[assembly: ObjCRuntime.LinkWith ("Gzip.framework")] [assembly: ObjCRuntime.LinkWith ("SwiftyBeaver.framework")] [assembly: ObjCRuntime.LinkWith ("SQLite.framework")] [assembly: ObjCRuntime.LinkWith ("Pods_HyperTrack.framework")] [assembly: ObjCRuntime.LinkWith ("CocoaAsyncSocket.framework")] [assembly: ObjCRuntime.LinkWith ("JustLog.framework")] [assembly: ObjCRuntime.LinkWith ("Alamofire.framework")] [assembly: ObjCRuntime.LinkWith ("HyperTrack.framework")] <file_sep>using System; namespace HTBind { public enum HyperTrackEventType : int { TrackingStarted = 0, TrackingEnded = 1, StopStarted = 2, StopEnded = 3, LocationChanged = 4, ActivityChanged = 5, PowerChanged = 6, RadioChanged = 7, LocationConfigChanged = 8, InfoChanged = 9, ActionCompleted = 10 } } <file_sep>using System; using System.Collections.Generic; namespace htapp { public partial class App { public static bool UseMockDataStore = true; public static string BackendUrl = "http://localhost:5000"; public App() { } public static void Initialize() { if (UseMockDataStore) ServiceLocator.Instance.Register<IDataStore<Item>, MockDataStore>(); else ServiceLocator.Instance.Register<IDataStore<Item>, CloudDataStore>(); #if __IOS__ ServiceLocator.Instance.Register<IMessageDialog, iOS.MessageDialog>(); #else ServiceLocator.Instance.Register<IMessageDialog, Droid.MessageDialog>(); #endif } public static IDictionary<string, string> LoginParameters => null; } } <file_sep># hypertrack-xamarin Xamarin bindings for native HyperTrack SDKs ## In the repo + HTBind : Hypertrack Xamarin Bindings for iOS + HTApp : Example iOS Xamarin App with Hypertrack integration ## Usage #### Using dlls The .dll files are available in [releases](https://github.com/hypertrack/hypertrack-xamarin/releases/). + Add the dll files to the project by going to References -> Edit References -> Browse -> PATH_TO_HYPERTRACK_DLL + Add the following swift packages to your app * Xamarin.Swift3 * Xamarin.Swift3.Core * Xamarin.Swift3.CoreGraphics * Xamarin.Swift3.CoreImage * Xamarin.Swift3.CoreLocation * Xamarin.Swift3.Darwin * Xamarin.Swift3.Dispatch * Xamarin.Swift3.Foundation * Xamarin.Swift3.MapKit * Xamarin.Swift3.ObjectiveC * Xamarin.Swift3.QuartzCore * Xamarin.Swift3.UIKit + Add the following keys and respective descriptions to your info.plist * NSLocationWhenInUseUsageDescription * NSLocationAlwaysUsageDescription * NSMotionUsageDescription + Add the following background modes to your info.plist * fetch * location * remote-notification ## APIs ```csharp using HTBind; ``` #### Initialize SDK ```csharp HyperTrack.Initialize("YOUR_PUBLISHABLE_KEY"); ``` #### Start Tracking ```csharp HyperTrack.StartTracking(); ``` #### Stop Tracking ```csharp HyperTrack.StopTracking(); ``` #### Get Or Create User ```csharp HyperTrack.GetOrCreateUser("Ravi", "9990300128", "9990300128", (HyperTrackUser arg1, HyperTrackError arg2) => { if(arg1 != null){ System.Console.WriteLine("user created"); }); ``` #### Create and Assign Action ```csharp HyperTrackPlace place = new HyperTrackPlace(); place.SetAddressWithAddress("2200 Sand Hill Road, Menlo Park, CA, USA"); HyperTrackActionParams actionParams = new HyperTrackActionParams(); actionParams.SetLookupIdWithLookupId("9990300128"); actionParams.SetTypeWithType("visit"); actionParams.SetExpectedPlaceWithExpectedPlace(place); HyperTrack.CreateAndAssignAction(actionParams, (HyperTrackAction action, HyperTrackError error) =>{ if (action != null){ System.Console.WriteLine("action created"); } }); ``` <file_sep>using System; using System.Collections.Generic; using System.Text; namespace htapp { public interface IMessageDialog { void SendMessage(string message, string title = null); void SendToast(string message); void SendConfirmation(string message, string title, Action<bool> confirmationAction); } } <file_sep>using System; using UIKit; using static htapp.iOS.Utils; namespace htapp.iOS { public class MessageDialog : IMessageDialog { public void SendMessage(string message, string title = null) { EnsureInvokedOnMainThread(() => { var alertView = new UIAlertView(title ?? string.Empty, message, null, "OK"); alertView.Show(); }); } public void SendToast(string message) { SendMessage(message); } public void SendConfirmation(string message, string title, Action<bool> confirmationAction) { EnsureInvokedOnMainThread(() => { var alertView = new UIAlertView(title ?? string.Empty, message, null, "OK", "Cancel"); alertView.Clicked += (sender, e) => { confirmationAction(e.ButtonIndex == 0); }; alertView.Show(); }); } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace htapp { public static class MessagingCenter { static Dictionary<Tuple<string, Type, Type>, List<Tuple<WeakReference, Action<object, object>>>> callbacks = new Dictionary<Tuple<string, Type, Type>, List<Tuple<WeakReference, Action<object, object>>>>(); public static void Subscribe<TSender, TArgs>(object subscriber, string message, Action<TSender, TArgs> callback, TSender source = null) where TSender : class { if (subscriber == null) throw new ArgumentNullException("subscriber"); if (callback == null) throw new ArgumentNullException("callback"); Action<object, object> wrap = (sender, args) => { var send = (TSender)sender; if (source == null || send == source) callback((TSender)sender, (TArgs)args); }; InnerSubscribe(subscriber, message, typeof(TSender), typeof(TArgs), wrap); } public static void Subscribe<TSender>(object subscriber, string message, Action<TSender> callback, TSender source = null) where TSender : class { if (subscriber == null) throw new ArgumentNullException("subscriber"); if (callback == null) throw new ArgumentNullException("callback"); Action<object, object> wrap = (sender, args) => { var send = (TSender)sender; if (source == null || send == source) callback((TSender)sender); }; InnerSubscribe(subscriber, message, typeof(TSender), null, wrap); } public static void Unsubscribe<TSender, TArgs>(object subscriber, string message) where TSender : class { InnerUnsubscribe(message, typeof(TSender), typeof(TArgs), subscriber); } public static void Unsubscribe<TSender>(object subscriber, string message) where TSender : class { InnerUnsubscribe(message, typeof(TSender), null, subscriber); } public static void Send<TSender, TArgs>(TSender sender, string message, TArgs args) where TSender : class { if (sender == null) throw new ArgumentNullException("sender"); InnerSend(message, typeof(TSender), typeof(TArgs), sender, args); } public static void Send<TSender>(TSender sender, string message) where TSender : class { if (sender == null) throw new ArgumentNullException("sender"); InnerSend(message, typeof(TSender), null, sender, null); } internal static void ClearSubscribers() { callbacks.Clear(); } static void InnerUnsubscribe(string message, Type senderType, Type argType, object subscriber) { if (subscriber == null) throw new ArgumentNullException("subscriber"); if (message == null) throw new ArgumentNullException("message"); var key = new Tuple<string, Type, Type>(message, senderType, argType); if (!callbacks.ContainsKey(key)) return; callbacks[key].RemoveAll(tuple => !tuple.Item1.IsAlive || tuple.Item1.Target == subscriber); if (!callbacks[key].Any()) callbacks.Remove(key); } static void InnerSubscribe(object subscriber, string message, Type senderType, Type argType, Action<object, object> callback) { if (message == null) throw new ArgumentNullException("message"); var key = new Tuple<string, Type, Type>(message, senderType, argType); var value = new Tuple<WeakReference, Action<object, object>>(new WeakReference(subscriber), callback); if (callbacks.ContainsKey(key)) { callbacks[key].Add(value); } else { var list = new List<Tuple<WeakReference, Action<object, object>>> { value }; callbacks[key] = list; } } static void InnerSend(string message, Type senderType, Type argType, object sender, object args) { if (message == null) throw new ArgumentNullException("message"); var key = new Tuple<string, Type, Type>(message, senderType, argType); if (!callbacks.ContainsKey(key)) return; var actions = callbacks[key]; if (actions == null || !actions.Any()) return; // should not be reachable // ok so this code looks a bit funky but here is the gist of the problem. It is possible that in the course // of executing the callbacks for this message someone will subscribe/unsubscribe from the same message in // the callback. This would invalidate the enumerator. To work around this we make a copy. However if you unsubscribe // from a message you can fairly reasonably expect that you will therefor not receive a call. To fix this we then // check that the item we are about to send the message to actually exists in the live list. var actionsCopy = actions.ToList(); foreach (var action in actionsCopy) { if (action.Item1.IsAlive && actions.Contains(action)) action.Item2(sender, args); } } } } <file_sep>using System; using UIKit; namespace htapp.iOS { public partial class LoginViewController : UIViewController { public LoginViewModel ViewModel; public LoginViewController(IntPtr handle) : base(handle) { ViewModel = new LoginViewModel(); } public override void ViewDidLoad() { base.ViewDidLoad(); NavigationItem.Title = ViewModel.Title; } partial void NotNowButton_TouchUpInside(UIButton sender) => NavigateToTabbed(); partial void LoginButton_TouchUpInside(UIButton sender) { if (Settings.IsLoggedIn) NavigateToTabbed(); } void NavigateToTabbed() { InvokeOnMainThread(() => { var app = (AppDelegate)UIApplication.SharedApplication.Delegate; app.Window.RootViewController = UIStoryboard.FromName("Main", null) .InstantiateViewController("tabViewController") as UITabBarController; }); } } } <file_sep>using System; using System.Threading.Tasks; using UIKit; namespace htapp.iOS { public partial class ItemNewViewController : UIViewController { public Item Item { get; set; } public ItemsViewModel viewModel { get; set; } public BaseViewModel baseModel { get; set; } public ItemNewViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. btnSaveItem.TouchUpInside += (sender, e) => { var _item = new Item(); _item.Text = txtTitle.Text; _item.Description = txtDesc.Text; MessagingCenter.Send(this, "AddItem", _item); NavigationController.PopToRootViewController(true); }; } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } } } <file_sep>using System; using CoreGraphics; using CoreLocation; using Foundation; using MapKit; using ObjCRuntime; using UIKit; namespace HTBind { // @interface HyperTrack : NSObject [BaseType(typeof(NSObject), Name = "_TtC10HyperTrack10HyperTrack")] [Protocol] interface HyperTrack { // +(void)initialize:(NSString * _Nonnull)publishableKey; [Static] [Export("initialize:")] void Initialize(string publishableKey); // +(NSString * _Nullable)getPublishableKey __attribute__((warn_unused_result)); [Static] [NullAllowed, Export("getPublishableKey")] string PublishableKey { get; } // +(void)setUserId:(NSString * _Nonnull)userId; [Static] [Export("setUserId:")] void SetUserId(string userId); // +(NSString * _Nullable)getUserId __attribute__((warn_unused_result)); [Static] [NullAllowed, Export("getUserId")] string UserId { get; } // @property (readonly, nonatomic, class) BOOL isTracking; [Static] [Export("isTracking")] bool IsTracking { get; } // +(void)createUser:(NSString * _Nonnull)name; [Static] [Export("createUser:")] void CreateUser(string name); // +(void)startTracking; [Static] [Export("startTracking")] void StartTracking(); // +(void)startMockTracking; [Static] [Export("startMockTracking")] void StartMockTracking(); // +(void)stopTracking; [Static] [Export("stopTracking")] void StopTracking(); // +(void)stopTrackingWithCompletionHandler:(void (^ _Nonnull)(HyperTrackError * _Nullable))completionHandler; // +(void)stopMockTracking; [Static] [Export("stopMockTracking")] void StopMockTracking(); // +(CLAuthorizationStatus)locationAuthorizationStatus __attribute__((warn_unused_result)); [Static] [Export("locationAuthorizationStatus")] CLAuthorizationStatus LocationAuthorizationStatus { get; } // +(void)requestWhenInUseAuthorization; [Static] [Export("requestWhenInUseAuthorization")] void RequestWhenInUseAuthorization(); // +(void)requestAlwaysAuthorization; [Static] [Export("requestAlwaysAuthorization")] void RequestAlwaysAuthorization(); // +(void)requestMotionAuthorization; [Static] [Export("requestMotionAuthorization")] void RequestMotionAuthorization(); // +(BOOL)locationServicesEnabled __attribute__((warn_unused_result)); [Static] [Export("locationServicesEnabled")] bool LocationServicesEnabled { get; } // +(void)registerForNotifications; [Static] [Export("registerForNotifications")] void RegisterForNotifications(); // +(void)didRegisterForRemoteNotificationsWithDeviceTokenWithDeviceToken:(NSData * _Nonnull)deviceToken; [Static] [Export("didRegisterForRemoteNotificationsWithDeviceTokenWithDeviceToken:")] void DidRegisterForRemoteNotificationsWithDeviceTokenWithDeviceToken(NSData deviceToken); // +(void)didFailToRegisterForRemoteNotificationsWithErrorWithError:(NSError * _Nonnull)error; [Static] [Export("didFailToRegisterForRemoteNotificationsWithErrorWithError:")] void DidFailToRegisterForRemoteNotificationsWithErrorWithError(NSError error); // +(void)didReceiveRemoteNotificationWithUserInfo:(NSDictionary * _Nonnull)userInfo; [Static] [Export("didReceiveRemoteNotificationWithUserInfo:")] void DidReceiveRemoteNotificationWithUserInfo(NSDictionary userInfo); // +(BOOL)isHyperTrackNotificationWithUserInfo:(NSDictionary * _Nonnull)userInfo __attribute__((warn_unused_result)); [Static] [Export("isHyperTrackNotificationWithUserInfo:")] bool IsHyperTrackNotificationWithUserInfo(NSDictionary userInfo); // +(void)createUser:(NSString * _Nonnull)name completionHandler:(void (^ _Nonnull)(HyperTrackUser * _Nullable, HyperTrackError * _Nullable))completionHandler; [Static] [Export("createUser:completionHandler:")] void CreateUser(string name, Action<HyperTrackUser, HyperTrackError> completionHandler); // +(void)createUser:(NSString * _Nonnull)name :(NSString * _Nonnull)phone :(NSString * _Nonnull)lookupID :(UIImage * _Nullable)photo completionHandler:(void (^ _Nonnull)(HyperTrackUser * _Nullable, HyperTrackError * _Nullable))completionHandler; [Static] [Export("createUser::::completionHandler:")] void CreateUser(string name, string phone, string lookupID, [NullAllowed] UIImage photo, Action<HyperTrackUser, HyperTrackError> completionHandler); // +(void)getOrCreateUser:(NSString * _Nonnull)name _phone:(NSString * _Nonnull)_phone :(NSString * _Nonnull)lookupID completionHandler:(void (^ _Nonnull)(HyperTrackUser * _Nullable, HyperTrackError * _Nullable))completionHandler; [Static] [Export("getOrCreateUser:_phone::completionHandler:")] void GetOrCreateUser(string name, string _phone, string lookupID, Action<HyperTrackUser, HyperTrackError> completionHandler); // +(void)getOrCreateUser:(NSString * _Nonnull)name :(NSString * _Nonnull)phone :(NSString * _Nonnull)lookupID :(UIImage * _Nullable)photo completionHandler:(void (^ _Nonnull)(HyperTrackUser * _Nullable, HyperTrackError * _Nullable))completionHandler; [Static] [Export("getOrCreateUser::::completionHandler:")] void GetOrCreateUser(string name, string phone, string lookupID, [NullAllowed] UIImage photo, Action<HyperTrackUser, HyperTrackError> completionHandler); // +(void)createAndAssignAction:(HyperTrackActionParams * _Nonnull)actionParams :(void (^ _Nonnull)(HyperTrackAction * _Nullable, HyperTrackError * _Nullable))completionHandler; [Static] [Export("createAndAssignAction::")] void CreateAndAssignAction(HyperTrackActionParams actionParams, Action<HyperTrackAction, HyperTrackError> completionHandler); // +(void)assignActionsWithActionIds:(NSArray<NSString *> * _Nonnull)actionIds :(void (^ _Nonnull)(HyperTrackUser * _Nullable, HyperTrackError * _Nullable))completionHandler; [Static] [Export("assignActionsWithActionIds::")] void AssignActionsWithActionIds(string[] actionIds, Action<HyperTrackUser, HyperTrackError> completionHandler); // +(void)getAction:(NSString * _Nonnull)actionId completionHandler:(void (^ _Nonnull)(HyperTrackAction * _Nullable, HyperTrackError * _Nullable))completionHandler; [Static] [Export("getAction:completionHandler:")] void GetAction(string actionId, Action<HyperTrackAction, HyperTrackError> completionHandler); // +(void)trackActionForActionID:(NSString * _Nonnull)actionID completionHandler:(void (^ _Nullable)(HyperTrackAction * _Nullable, HyperTrackError * _Nullable))completionHandler; [Static] [Export("trackActionForActionID:completionHandler:")] void TrackActionForActionID(string actionID, [NullAllowed] Action<HyperTrackAction, HyperTrackError> completionHandler); // +(void)trackActionForShortCode:(NSString * _Nonnull)shortCode completionHandler:(void (^ _Nullable)(HyperTrackAction * _Nullable, HyperTrackError * _Nullable))completionHandler; [Static] [Export("trackActionForShortCode:completionHandler:")] void TrackActionForShortCode(string shortCode, [NullAllowed] Action<HyperTrackAction, HyperTrackError> completionHandler); // +(void)trackActionForLookUpId:(NSString * _Nonnull)lookUpId completionHandler:(void (^ _Nullable)(NSArray<HyperTrackAction *> * _Nullable, HyperTrackError * _Nullable))completionHandler; // +(void)removeActions:(NSArray<NSString *> * _Nullable)actionIds; [Static] [Export("removeActions:")] void RemoveActions([NullAllowed] string[] actionIds); // +(void)completeAction:(NSString * _Nonnull)actionId; [Static] [Export("completeAction:")] void CompleteAction(string actionId); // +(void)cancelPendingActionsWithCompletionHandler:(void (^ _Nonnull)(HyperTrackUser * _Nullable, HyperTrackError * _Nullable))completionHandler; [Static] [Export("cancelPendingActionsWithCompletionHandler:")] void CancelPendingActionsWithCompletionHandler(Action<HyperTrackUser, HyperTrackError> completionHandler); } [BaseType(typeof(NSObject), Name = "_TtC10HyperTrack17HTGeoJSONLocation")] [DisableDefaultCtor] interface HTGeoJSONLocation { // @property (readonly, copy, nonatomic) NSString * _Nonnull type; [Export("type")] string Type { get; } // @property (readonly, copy, nonatomic) NSArray<NSNumber *> * _Nonnull coordinates; [Export("coordinates", ArgumentSemantic.Copy)] NSNumber[] Coordinates { get; } // -(instancetype _Nonnull)initWithType:(NSString * _Nonnull)type coordinates:(CLLocationCoordinate2D)coordinates __attribute__((objc_designated_initializer)); [Export("initWithType:coordinates:")] [DesignatedInitializer] IntPtr Constructor(string type, CLLocationCoordinate2D coordinates); // -(NSDictionary<NSString *,id> * _Nonnull)toDict __attribute__((warn_unused_result)); [Export("toDict")] NSDictionary<NSString, NSObject> ToDict { get; } // -(NSString * _Nullable)toJson __attribute__((warn_unused_result)); [NullAllowed, Export("toJson")] string ToJson { get; } // +(HTGeoJSONLocation * _Nullable)fromDictWithDict:(NSDictionary<NSString *,id> * _Nonnull)dict __attribute__((warn_unused_result)); [Static] [Export("fromDictWithDict:")] [return: NullAllowed] HTGeoJSONLocation FromDictWithDict(NSDictionary<NSString, NSObject> dict); } [BaseType(typeof(NSObject), Name = "_TtC10HyperTrack14HyperTrackUser")] [DisableDefaultCtor] interface HyperTrackUser { // @property (readonly, copy, nonatomic) NSString * _Nullable id; [NullAllowed, Export("id")] string Id { get; } // @property (readonly, copy, nonatomic) NSString * _Nullable name; [NullAllowed, Export("name")] string Name { get; } // @property (readonly, copy, nonatomic) NSString * _Nullable phone; [NullAllowed, Export("phone")] string Phone { get; } // @property (readonly, copy, nonatomic) NSString * _Nullable photo; [NullAllowed, Export("photo")] string Photo { get; } // @property (readonly, copy, nonatomic) NSDate * _Nullable lastHeartbeatAt; [NullAllowed, Export("lastHeartbeatAt", ArgumentSemantic.Copy)] NSDate LastHeartbeatAt { get; } // @property (readonly, nonatomic, strong) HyperTrackLocation * _Nullable lastLocation; [NullAllowed, Export("lastLocation", ArgumentSemantic.Strong)] HyperTrackLocation LastLocation { get; } // -(NSString * _Nullable)toJson __attribute__((warn_unused_result)); [NullAllowed, Export("toJson")] string ToJson { get; } } [BaseType(typeof(NSObject), Name = "_TtC10HyperTrack18HyperTrackLocation")] [DisableDefaultCtor] interface HyperTrackLocation { // @property (readonly, nonatomic, strong) HTGeoJSONLocation * _Nonnull location; [Export("location", ArgumentSemantic.Strong)] HTGeoJSONLocation Location { get; } // @property (readonly, nonatomic, strong) CLLocation * _Nonnull clLocation; [Export("clLocation", ArgumentSemantic.Strong)] CLLocation ClLocation { get; } // @property (readonly, nonatomic) CLLocationAccuracy horizontalAccuracy; [Export("horizontalAccuracy")] double HorizontalAccuracy { get; } // @property (readonly, nonatomic) CLLocationAccuracy verticalAccuracy; [Export("verticalAccuracy")] double VerticalAccuracy { get; } // @property (readonly, nonatomic) CLLocationSpeed speed; [Export("speed")] double Speed { get; } // @property (readonly, nonatomic) CLLocationDirection bearing; [Export("bearing")] double Bearing { get; } // @property (readonly, nonatomic) CLLocationDistance altitude; [Export("altitude")] double Altitude { get; } // @property (copy, nonatomic) NSString * _Nonnull activity; [Export("activity")] string Activity { get; set; } // @property (nonatomic) NSInteger activityConfidence; [Export("activityConfidence")] nint ActivityConfidence { get; set; } // @property (readonly, copy, nonatomic) NSString * _Nonnull provider; [Export("provider")] string Provider { get; } // @property (copy, nonatomic) NSDate * _Nonnull recordedAt; [Export("recordedAt", ArgumentSemantic.Copy)] NSDate RecordedAt { get; set; } } [BaseType(typeof(NSObject), Name = "_TtC10HyperTrack22HyperTrackActionParams")] interface HyperTrackActionParams { // @property (copy, nonatomic) NSString * _Nullable userId; [NullAllowed, Export("userId")] string UserId { get; set; } // @property (copy, nonatomic) NSString * _Nullable expectedPlaceId; [NullAllowed, Export("expectedPlaceId")] string ExpectedPlaceId { get; set; } // @property (nonatomic, strong) HyperTrackPlace * _Nullable expectedPlace; [NullAllowed, Export("expectedPlace", ArgumentSemantic.Strong)] HyperTrackPlace ExpectedPlace { get; set; } // @property (copy, nonatomic) NSString * _Nonnull type; [Export("type")] string Type { get; set; } // @property (copy, nonatomic) NSString * _Nonnull lookupId; [Export("lookupId")] string LookupId { get; set; } // @property (nonatomic) BOOL lookupIdAsShortCode; [Export("lookupIdAsShortCode")] bool LookupIdAsShortCode { get; set; } // @property (copy, nonatomic) NSString * _Nullable expectedAt; [NullAllowed, Export("expectedAt")] string ExpectedAt { get; set; } // -(HyperTrackActionParams * _Nonnull)setUserIdWithUserId:(NSString * _Nonnull)userId __attribute__((warn_unused_result)); [Export("setUserIdWithUserId:")] HyperTrackActionParams SetUserIdWithUserId(string userId); // -(HyperTrackActionParams * _Nonnull)setExpectedPlaceWithExpectedPlace:(HyperTrackPlace * _Nonnull)expectedPlace __attribute__((warn_unused_result)); [Export("setExpectedPlaceWithExpectedPlace:")] HyperTrackActionParams SetExpectedPlaceWithExpectedPlace(HyperTrackPlace expectedPlace); // -(HyperTrackActionParams * _Nonnull)setExpectedPlaceIdWithExpectedPlaceId:(NSString * _Nonnull)expectedPlaceId __attribute__((warn_unused_result)); [Export("setExpectedPlaceIdWithExpectedPlaceId:")] HyperTrackActionParams SetExpectedPlaceIdWithExpectedPlaceId(string expectedPlaceId); // -(HyperTrackActionParams * _Nonnull)setTypeWithType:(NSString * _Nonnull)type __attribute__((warn_unused_result)); [Export("setTypeWithType:")] HyperTrackActionParams SetTypeWithType(string type); // -(HyperTrackActionParams * _Nonnull)setLookupIdWithLookupId:(NSString * _Nonnull)lookupId __attribute__((warn_unused_result)); [Export("setLookupIdWithLookupId:")] HyperTrackActionParams SetLookupIdWithLookupId(string lookupId); // -(HyperTrackActionParams * _Nonnull)setLookupIdAsShortCode __attribute__((warn_unused_result)); [Export("setLookupIdAsShortCode")] HyperTrackActionParams SetLookupIdAsShortCode { get; } // -(HyperTrackActionParams * _Nonnull)setExpectedAtExpectedAt:(NSString * _Nonnull)expectedAt __attribute__((warn_unused_result)); [Export("setExpectedAtExpectedAt:")] HyperTrackActionParams SetExpectedAtExpectedAt(string expectedAt); } // @interface HyperTrackPlace : NSObject [BaseType(typeof(NSObject), Name = "_TtC10HyperTrack15HyperTrackPlace")] interface HyperTrackPlace { // @property (copy, nonatomic) NSString * _Nullable id; [NullAllowed, Export("id")] string Id { get; set; } // @property (copy, nonatomic) NSString * _Nullable name; [NullAllowed, Export("name")] string Name { get; set; } // @property (nonatomic, strong) HTGeoJSONLocation * _Nullable location; [NullAllowed, Export("location", ArgumentSemantic.Strong)] HTGeoJSONLocation Location { get; set; } // @property (copy, nonatomic) NSString * _Nullable address; [NullAllowed, Export("address")] string Address { get; set; } // @property (copy, nonatomic) NSString * _Nullable locality; [NullAllowed, Export("locality")] string Locality { get; set; } // @property (copy, nonatomic) NSString * _Nullable landmark; [NullAllowed, Export("landmark")] string Landmark { get; set; } // @property (copy, nonatomic) NSString * _Nullable zipCode; [NullAllowed, Export("zipCode")] string ZipCode { get; set; } // @property (copy, nonatomic) NSString * _Nullable city; [NullAllowed, Export("city")] string City { get; set; } // @property (copy, nonatomic) NSString * _Nullable state; [NullAllowed, Export("state")] string State { get; set; } // @property (copy, nonatomic) NSString * _Nullable country; [NullAllowed, Export("country")] string Country { get; set; } // -(HyperTrackPlace * _Nonnull)setNameWithName:(NSString * _Nonnull)name __attribute__((warn_unused_result)); [Export("setNameWithName:")] HyperTrackPlace SetNameWithName(string name); // -(HyperTrackPlace * _Nonnull)setLocationWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude __attribute__((warn_unused_result)); [Export("setLocationWithLatitude:longitude:")] HyperTrackPlace SetLocationWithLatitude(double latitude, double longitude); // -(HyperTrackPlace * _Nonnull)setLocationWithCoordinates:(CLLocationCoordinate2D)coordinates __attribute__((warn_unused_result)); [Export("setLocationWithCoordinates:")] HyperTrackPlace SetLocationWithCoordinates(CLLocationCoordinate2D coordinates); // -(HyperTrackPlace * _Nonnull)setAddressWithAddress:(NSString * _Nonnull)address __attribute__((warn_unused_result)); [Export("setAddressWithAddress:")] HyperTrackPlace SetAddressWithAddress(string address); } [BaseType(typeof(NSObject), Name = "_TtC10HyperTrack16HyperTrackAction")] [DisableDefaultCtor] interface HyperTrackAction { // @property (readonly, copy, nonatomic) NSString * _Nullable id; [NullAllowed, Export("id")] string Id { get; } // @property (readonly, nonatomic, strong) HyperTrackUser * _Nullable user; [NullAllowed, Export("user", ArgumentSemantic.Strong)] HyperTrackUser User { get; } // @property (readonly, copy, nonatomic) NSString * _Nullable type; [NullAllowed, Export("type")] string Type { get; } // @property (readonly, nonatomic, strong) HyperTrackPlace * _Nullable expectedPlace; [NullAllowed, Export("expectedPlace", ArgumentSemantic.Strong)] HyperTrackPlace ExpectedPlace { get; } // @property (readonly, copy, nonatomic) NSDate * _Nullable expectedAt; [NullAllowed, Export("expectedAt", ArgumentSemantic.Copy)] NSDate ExpectedAt { get; } // @property (readonly, nonatomic, strong) HyperTrackPlace * _Nullable completedPlace; [NullAllowed, Export("completedPlace", ArgumentSemantic.Strong)] HyperTrackPlace CompletedPlace { get; } // @property (readonly, copy, nonatomic) NSDate * _Nullable completedAt; [NullAllowed, Export("completedAt", ArgumentSemantic.Copy)] NSDate CompletedAt { get; } // @property (readonly, copy, nonatomic) NSDate * _Nullable endedAt; [NullAllowed, Export("endedAt", ArgumentSemantic.Copy)] NSDate EndedAt { get; } // @property (readonly, copy, nonatomic) NSDate * _Nullable assignedAt; [NullAllowed, Export("assignedAt", ArgumentSemantic.Copy)] NSDate AssignedAt { get; } // @property (readonly, nonatomic, strong) HyperTrackPlace * _Nullable startedPlace; [NullAllowed, Export("startedPlace", ArgumentSemantic.Strong)] HyperTrackPlace StartedPlace { get; } // @property (readonly, copy, nonatomic) NSDate * _Nullable startedAt; [NullAllowed, Export("startedAt", ArgumentSemantic.Copy)] NSDate StartedAt { get; } // @property (readonly, copy, nonatomic) NSString * _Nullable status; [NullAllowed, Export("status")] string Status { get; } // @property (readonly, copy, nonatomic) NSDate * _Nullable eta; [NullAllowed, Export("eta", ArgumentSemantic.Copy)] NSDate Eta { get; } // @property (readonly, copy, nonatomic) NSDate * _Nullable initialEta; [NullAllowed, Export("initialEta", ArgumentSemantic.Copy)] NSDate InitialEta { get; } // @property (readonly, copy, nonatomic) NSString * _Nullable trackingUrl; [NullAllowed, Export("trackingUrl")] string TrackingUrl { get; } // @property (readonly, copy, nonatomic) NSString * _Nullable lookupId; [NullAllowed, Export("lookupId")] string LookupId { get; } // @property (readonly, nonatomic, strong) HyperTrackActionDisplay * _Nullable display; [NullAllowed, Export("display", ArgumentSemantic.Strong)] HyperTrackActionDisplay Display { get; } // @property (readonly, copy, nonatomic) NSString * _Nullable encodedPolyline; [NullAllowed, Export("encodedPolyline")] string EncodedPolyline { get; } // @property (readonly, copy, nonatomic) NSString * _Nullable timeAwarePolyline; [NullAllowed, Export("timeAwarePolyline")] string TimeAwarePolyline { get; } // -(NSString * _Nullable)toJson __attribute__((warn_unused_result)); [NullAllowed, Export("toJson")] string ToJson { get; } } // @interface HyperTrackActionDisplay : NSObject [BaseType(typeof(NSObject), Name = "_TtC10HyperTrack23HyperTrackActionDisplay")] [DisableDefaultCtor] interface HyperTrackActionDisplay { // @property (readonly, copy, nonatomic) NSString * _Nullable statusText; [NullAllowed, Export("statusText")] string StatusText { get; } // @property (readonly, copy, nonatomic) NSString * _Nullable subStatusText; [NullAllowed, Export("subStatusText")] string SubStatusText { get; } // @property (readonly, copy, nonatomic) NSString * _Nullable distanceUnit; [NullAllowed, Export("distanceUnit")] string DistanceUnit { get; } // @property (nonatomic) BOOL showSummary; [Export("showSummary")] bool ShowSummary { get; set; } } // @interface HyperTrackError : NSObject [BaseType(typeof(NSObject), Name = "_TtC10HyperTrack15HyperTrackError")] [DisableDefaultCtor] interface HyperTrackError { } }<file_sep>using Newtonsoft.Json; using System; namespace htapp { public class BaseDataObject : ObservableObject, IBaseDataObject { public BaseDataObject() { Id = Guid.NewGuid().ToString(); } /// <summary> /// Id for item /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Azure created at time stamp /// </summary> [JsonProperty(PropertyName = "createdAt")] public DateTimeOffset CreatedAt { get; set; } } }
c467497653a9b7f4c856c8cd156cb3a4e49ada62
[ "Markdown", "C#" ]
11
C#
hypertrack/hypertrack-xamarin
add8e0b9a0c6ce3180827a17617beaf0455dabcb
1edaf54851253ff2f7eb9871bd84e338bed3099d
refs/heads/main
<file_sep>import { Component, OnInit, NgZone } from '@angular/core'; // import { HttpClient } from '@angular/common/http'; // import { map } from 'rxjs/operators'; import recognizeMicrophone from 'watson-speech/speech-to-text/recognize-microphone'; import synthesize from 'watson-speech/text-to-speech/synthesize'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { constructor(private ngZone: NgZone) {} title = 'voice-recognition'; voiceText: string; isListening: boolean; stream: any; ttsToken = {}; ngOnInit() { console.log('Initiating...'); } onVoiceListen() { console.log('listening...'); this.voiceText = ''; this.isListening = true; fetch('/api/stt/token') .then((res) => { return res.json(); }) .then((token) => { try { this.stream = recognizeMicrophone( Object.assign(token, { objectMode: true, format: false, }) ); } catch (error) { alert('Voice recognition not supported in this browser.'); } this.stream.on('data', (data) => { console.log('data is', data); if (data.results && data.results[0] && data.results[0].final) { this.ngZone.run(() => { this.stream.stop(); console.log('stopping to listen'); this.isListening = false; this.setTtsToken(); }); } else if (data.results && data.results.length) { this.ngZone.run(() => { const { transcript } = data.results[0].alternatives[0]; console.log(transcript); this.voiceText = transcript; }); } }); this.stream.on('error', (err) => { console.log(err); }); }) .catch(console.error); } async setTtsToken() { const res = await fetch('/api/tts/token'); const ttsToken = await res.json(); this.ttsToken = ttsToken; } speak() { const audio = synthesize( Object.assign(this.ttsToken, { text: this.voiceText, }) ); audio.onerror = (err) => { console.log('audio error: ', err); }; } onVoiceStop() { this.isListening = false; this.stream.stop(); } }
598e54ff5e04f20f2e108902fe229f3f239c671f
[ "TypeScript" ]
1
TypeScript
Ramgopalbhat10/watson-speech-demo
597ae5dec8b97cc36949d82dfa4afc5cf52d3e59
3dbab2054ca268475ad72e41df7098c9af0f902e
refs/heads/master
<file_sep>const db = require('../database/dbConfig.js'); module.exports = { findRecipes, findRecipesById, findBy, addRecipe, updateRecipe, removeRecipe, findRecipesByChefId, getChefsById }; function findRecipes(){ return db('recipes'); } function findRecipesById(id){ return db('recipes as r') .where({ id }) .first(); } function getChefsById(id) { return db("chefs").where({ id }).first(); } function findBy(filter){ return db('recipes').where(filter) } function addRecipe(recipe){ return db('recipes') .insert(recipe) } function updateRecipe(changes, id){ return db('recipes') .where({ id }) .update(changes) .then(recipe => { return recipe }) } function removeRecipe(id){ return db('recipes') .where({ id }) .delete(); } function findRecipesByChefId(id){ return db('recipes as r') .where('r.chef_id', id); }<file_sep>const express = require('express'); const cors = require('cors'); const helmet = require('helmet'); const recipeRouter = require('../recipes/recipes-router.js'); const chefRouter = require('../chefs/chefs-router.js'); const server = express(); server.use(helmet()); server.use(cors()); server.use(express.json()); server.use('/docs', express.static('./docs')); server.use('/api/recipes', recipeRouter); server.use('/api/chefs', chefRouter); server.get('/', (req, res) => { res.status(200).json('Chef Portfolio'); }); module.exports = server;<file_sep>const express = require('express'); const authenticate = require('../auth/authenticate-middleware'); const Recipes = require('./recipes-model.js'); const router = express.Router(); /** * @api {get} /api/recipes Get all recipes * @apiName GetRecipes * @apiGroup Recipes * * @apiSuccess {Number} id Recipe id * @apiSuccess {string} recipe_title Recipe Title * @apiSuccess {string} image Recipe Img * @apiSuccess {string} ingredients Recipe Ingredients * @apiSuccess {string} instructions Recipe Instructions * @apiSuccess {string} meal_type Recipe Meal Type * @apiSuccess {Number} chef_id Chef's Id * * @apiSuccessExample Successful Response: * HTTP/1.1 200 OK * [ * { * "id": 1, * "recipe_title": "PB&J Sandwich", * "image": "https://images.unsplash.com/photo-1557275357-072087771588?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2850&q=80", * "ingredients": "tbsp of peanut butter, tbsp of jelly, and 2 slices of bread", * "instructions": "Spread peanut butter on one slice of bread. Spread jelly on other. Combine and bam!", * "meal_type": "Snack", * "chef_id": 1 * }, * { * "id": 2, * "recipe_title": "Scrambled eggs", * "image": "https://images.unsplash.com/photo-1551185618-5d8656fd00b1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2978&q=80", * "ingredients": "2 eggs, black pepper, and salt", * "instructions": "Heat pan. Lightly coat pan with non-stick cooking spray. Beat eggs in bowl. Add a pinch of salt and pepper to taste. Add eggs to pan and stir. Heat until cooked. Enjoy.", * "meal_type": "Breakfast", * "chef_id": 1 * }, *] */ // GET all recipes /api/recipes router.get('/', (req, res) => { Recipes.findRecipes() .then(recipes => { res.status(200).json(recipes); }) .catch(error => { res.status(500).json({ error: "Recipes could not be retrieved." }); }); }); /** * @api {get} /api/recipes/:id Get specific recipe * @apiName GetSpecificRecipe * @apiGroup Recipes * * @apiParam {Number} id Recipe id * * @apiSuccess {Number} id Recipe id * @apiSuccess {string} recipe_title Recipe Title * @apiSuccess {string} image Recipe Img * @apiSuccess {string} ingredients Recipe Ingredients * @apiSuccess {string} instructions Recipe Instructions * @apiSuccess {string} meal_type Recipe Meal Type * @apiSuccess {Number} chef_id Chef's Id * @apiSuccess {object} chef Chef Info * * @apiSuccessExample Successful Response: * HTTP/1.1 200 OK * { * "id": 1, * "recipe_title": "PB&J Sandwich", * "image": "https://images.unsplash.com/photo-1557275357-072087771588?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2850&q=80", * "ingredients": "tbsp of peanut butter, tbsp of jelly, and 2 slices of bread", * "instructions": "Spread peanut butter on one slice of bread. Spread jelly on other. Combine and bam!", * "meal_type": "Snack", * "chef_id": 1, * "chef": { * "id": 1, * "name": "<NAME>", * "username": "user1", * "password": "<PASSWORD>", * "location": "Pittsburgh, PA", * "contact_info": "<EMAIL>" * } * } * **/ // GET specific recipe /api/recipes/:id router.get('/:id', (req, res) =>{ const { id } = req.params; Recipes.findRecipesById(id) .then(recipe => { if(recipe){ Recipes.getChefsById(id) .then(chef => { let chefInfo = [] if(chef){ chefInfo = chef } res.json({...recipe, chef: chefInfo}) }) .catch(error => { res.status(500).json({ message: 'Failed at chef info nested'}); }); } else { res.status(404).json({message: "Could not get recipe with provided id"}) } }) .catch(error => { res.status(500).json({ error: "Recipe could not be retrieved" }); }); }); /** * @api {post} /api/recipes Create/Post new recipe * @apiName CreateRecipe * @apiGroup Recipes * * @apiParam {string} recipe_title Recipe Title * @apiParam {string} image Recipe Img * @apiParam {string} ingredients Recipe Ingredients * @apiParam {string} instructions Recipe Instructions * @apiParam {string} meal_type Recipe Meal Type * @apiParam {Number} chef_id Chef's Id * * @apiParamExample Example Body: * { * "recipe_title": "Chocolate Milk 2.0", * "image": "https://images.unsplash.com/photo-1554654402-d506f91a1a64?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=80", * "ingredients": "Chocolate syrup, 1 cup of milk", * "instructions": "Mix chocolate syrup with cold milk and stir", * "meal_type": "Snack", * "chef_id": 2 * } * * @apiSuccessExample Successful Response: * HTTP/1.1 200 OK * { * "message": "New Recipe Added!" * } * */ // POST (create) new recipe /api/recipes router.post('/', authenticate, (req, res) => { let newRecipe = req.body; Recipes.addRecipe(newRecipe) .then(newRecipe =>{ if(newRecipe){ res.status(201).json({message: 'New Recipe Added!'}); }else{ res.status(409).json({message: 'Could not create recipe'}) } }) .catch(error => { res.status(500).json(error); }) }) module.exports = router;
5c9148a19493c915f7c80cb748aeb7674b398774
[ "JavaScript" ]
3
JavaScript
chefPassport/backend
34f2420cb59d0f5d217be1835c130c8a51884d74
9e932923d7693300fbb072aa1db23069af94f558
refs/heads/master
<file_sep># Tools Hacking-CTF-Bounty :) <file_sep>#!/bin/bash #Copyright 2016 <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. if [ -e "./socat" ]; then echo "socat already compiled in current directory" echo "moving on to establishing connection" else echo "socat NOT compiled in current dir, extracting and compiling" # check for gcc and make if [ -z `which gcc` ] || [ -z `which make` ]; then echo "Unfortunately gcc or make is not installed" echo "we won't be able to compile socat on this target today" exit -1 fi # unpack socak source tar xf socat-1.7.0.1.tar echo "Extracted socat to: socat-1.7.3.1" # change working directory cd socat-1.7.0.1 echo "Changed directory to: " `pwd` ./configure &> ../configure-log.txt # hide the output make &> ../make-log.txt # hide the output if [ -e "./socat" ]; then echo "compilation successful, socat found." cp socat ../ cd ../ echo "Changed directory to: " `pwd` else echo "$file not found, check log files configure-log.txt & make-log.txt" exit -1 fi fi # if we get here then socat binary has been compiled and we have a copy in this directory echo "====================" echo "Start listener on attacker's host:" echo "user@attacker ~: socat -,raw,echo=0 tcp-listen:4545" echo "====================" echo "Run socat from victim to connect back:" echo "user@victim ~: socat tcp:<host>:<port> exec:\"bash -i\",pty,stderr,setsid,sigint,sane" echo "=====================" if [ -z "$1" ] && [ -z "$2" ]; then echo "No arguments provided, please enter the command shown above with host and port" exit -1 else echo "Attempting to execute against host $1 and port $2" ./socat tcp:$1:$2 exec:"bash -i",pty,stderr,setsid,sigint,sane fi <file_sep>package main import ( "bufio" "crypto/tls" "flag" "fmt" "net/http" "os" "strings" "sync" "time" ) type probeArgs []string func (p *probeArgs) Set(val string) error { *p = append(*p, val) return nil } func (p probeArgs) String() string { return strings.Join(p, ",") } func main() { // concurrency flag var concurrency int flag.IntVar(&concurrency, "c", 20, "set the concurrency level") // probe flags var probes probeArgs flag.Var(&probes, "p", "add additional probe (proto:port)") // skip default probes flag var skipDefault bool flag.BoolVar(&skipDefault, "s", false, "skip the default probes (http:80 and https:443)") // timeout flag var to int flag.IntVar(&to, "t", 10000, "timeout (milliseconds)") // verbose flag var verbose bool flag.BoolVar(&verbose, "v", false, "output errors to stderr") flag.Parse() // make an actual time.Duration out of the timeout timeout := time.Duration(to * 1000000) var tr = &http.Transport{ MaxIdleConns: 30, IdleConnTimeout: time.Second, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } re := func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } client := &http.Client{ Transport: tr, CheckRedirect: re, Timeout: timeout, } // we send urls to check on the urls channel, // but only get them on the output channel if // they are accepting connections urls := make(chan string) // Spin up a bunch of workers var wg sync.WaitGroup for i := 0; i < concurrency; i++ { wg.Add(1) go func() { for url := range urls { if isListening(client, url) { fmt.Println(url) continue } if verbose { fmt.Fprintf(os.Stderr, "failed: %s\n", url) } } wg.Done() }() } // accept domains on stdin sc := bufio.NewScanner(os.Stdin) for sc.Scan() { domain := strings.ToLower(sc.Text()) // submit http and https versions to be checked if !skipDefault { urls <- "http://" + domain urls <- "https://" + domain } // submit any additional proto:port probes for _, p := range probes { pair := strings.SplitN(p, ":", 2) if len(pair) != 2 { continue } urls <- fmt.Sprintf("%s://%s:%s", pair[0], domain, pair[1]) } } // once we've sent all the URLs off we can close the // input channel. The workers will finish what they're // doing and then call 'Done' on the WaitGroup close(urls) // check there were no errors reading stdin (unlikely) if err := sc.Err(); err != nil { fmt.Fprintf(os.Stderr, "failed to read input: %s\n", err) } // Wait until all the workers have finished wg.Wait() } func isListening(client *http.Client, url string) bool { req, err := http.NewRequest("GET", url, nil) if err != nil { return false } req.Header.Add("Connection", "close") req.Close = true resp, err := client.Do(req) if resp != nil { defer resp.Body.Close() } if err != nil { return false } return true }
98bd197185a80b46ca3d803ff2b7ba66364d9f0d
[ "Markdown", "Go", "Shell" ]
3
Markdown
MatiaCornejo/Tools
df79a30fc38f728a53c392f7d9d97211015b07bb
c71c74971cb687a2c79866cc5431c3c0f6bade70
refs/heads/master
<file_sep>class Owner attr_accessor :pets attr_reader :species attr_writer :name @@all = [] def initialize(species) @pets = {fishes: [], cats: [], dogs: []} @species = species @name = name @@all << self end def self.all @@all end def self.count @@all.length end def self.reset_all @@all.clear end def say_species "I am a #{@species}." end def name self.name = @name end def save @pets << self end def buy_fish(name) fish = Fish.new(name) #create new fish @pets.map do |key, value| #iterate through hash to find fish key if key == :fishes #once found value << fish #add fish to the value end end end #repeat above for cats & dogs def buy_cat(name) cat = Cat.new(name) @pets.map do |key, value| if key == :cats value << cat end end end def buy_dog(name) dog = Dog.new(name) @pets.map do |key, value| if key == :dogs value << dog end end end def walk_dogs @pets[:dogs][0].mood = "happy" #find the value within the key and change mood to happy end def play_with_cats @pets[:cats][0].mood = "happy" end def feed_fish @pets[:fishes][0].mood = "happy" end def sell_pets @pets.each do |type, pet| #iterate through hash pet.each do |name| #find array of names of pet instances if name.mood == "happy" #if pet's mood was happy name.mood = "nervous" #change to nervous end end end @pets.map {|type, pet| pet.clear} #iterate through hash, find pet arrays, and clear end def list_pets dog_count = @pets[:dogs].count cat_count = @pets[:cats].count fish_count = @pets[:fishes].count "I have #{fish_count} fish, #{dog_count} dog(s), and #{cat_count} cat(s)." end end
a6f7d81e6eb52d82b168e32fcc87a1a07dbddd1d
[ "Ruby" ]
1
Ruby
helloimiskra/oo-my-pets-online-web-pt-041519
699192e238678d793fb5d49af45cc4e9db906e87
5b933cfd73103eb5487ac0457c27bfeddf8ef30e
refs/heads/master
<repo_name>arivera40/Computer-Architecture-Asst-2-One-Shot-Learning<file_sep>/OneShot.c #include<stdio.h> #include<stdlib.h> void multiply1DMatrices(double **matrix1, double *matrix2, double *result, int rowCount1, int colCount1); void multiply1DMatrices(double **matrix1, double *matrix2, double *result, int rowCount1, int colCount1){ double num = 0; int r = 0; int i; for(i=0; i<colCount1; i++){ num = num + (matrix1[r][i] * matrix2[i]); if(i == colCount1 - 1){ result[r] = num; num = 0; r++; i = -1; } if(r == rowCount1){ //rethink break; } } return; } void multiplyMatrices(double **matrix1, double **matrix2, double **result, int rowCount1, int colCount1, int colCount2); void multiplyMatrices(double **matrix1, double **matrix2, double **result, int rowCount1, int colCount1, int colCount2){ double num = 0; int r = 0; int c = 0; int i; for(i=0; i<colCount1; i++){ num = num + (matrix1[r][i] * matrix2[i][c]); if(i == colCount1 - 1){ result[r][c] = num; num = 0; c++; i = -1; if(c == colCount2){ r++; c = 0; } } if(r == rowCount1){ break; } } return; } void concatMatrices(double **matrix1, double **matrix2, double **concat, int rows, int cols); void concatMatrices(double **matrix1, double **matrix2, double **concat, int rows, int cols){ int halfCols = rows; int i; int j; int k = 0; for(i=0; i < rows; i++){ for(j=0; j < halfCols; j++){ concat[i][j] = matrix1[i][j]; } } for(i=0; i < rows; i++){ for(j=halfCols; j < cols; j++){ concat[i][j] = matrix2[i][k]; k++; } k = 0; } return; } void rowDivision(double** matrix, int row1, double constant, int sizeV); void rowDivision(double** matrix, int row1, double constant, int sizeV){ int col; for(col = 0; col < (sizeV * 2); col++){ matrix[row1][col] = matrix[row1][col] / constant; } return; } void rowSubMultiply(double** matrix, int row1, int row2, double constant, int sizeV); void rowSubMultiply(double** matrix, int row1, int row2, double constant, int sizeV){ int col; for(col=0; col < (sizeV * 2); col++){ matrix[row1][col] = matrix[row1][col] - constant * matrix[row2][col]; } return; } int main(int argc, char** argv){ int N; // # of examples in a training set int K; // # of attributes in an example double **X; // Matrix representing training set Matrix N x (K + 1) double **T; // Matrix representing transpose of Matrix X double *Y; // Matrix representing prices of the houses N x 1 double *W; // Matrix representing weights of the houses (K + 1) x 1 FILE *fp = fopen(argv[1], "r"); fscanf(fp, "%d\n", &K); fscanf(fp, "%d\n", &N); //training set Matrix created N (rows) x (K + 1) (cols) int i; int j; X = (double**)malloc(sizeof(double*) * N); for(i=0; i < N; i++){ X[i] = (double*)malloc(sizeof(double) * (K + 1)); } //transpose Matrix created (K + 1) (rows) x N (cols) T = (double**)malloc(sizeof(double*) * (K + 1)); for(i=0; i < (K + 1); i++){ T[i] = (double*)malloc(sizeof(double) * N); } //price Matrix created N (rows) x 1 (cols) Y = (double*)malloc(sizeof(double) * N); //weight Matrix created (K + 1) (rows) x 1 (cols) W = (double*)malloc(sizeof(double) * (K + 1)); //Loads training set Matrix and price Matrix double input; int lastIndex = 0; //boolean to determine to skip a comma or new-line i = 0; j = 0; while(i < N){ if(j == 0){ X[i][j] = 1; j++; continue; } fscanf(fp, "%lf%*c" , &input); X[i][j] = input; if(lastIndex == 1){ fscanf(fp, "%lf\n", &input); Y[i] = input; i++; j = 0; lastIndex = 0; continue; } if(j == (K - 1)){ lastIndex = 1; } j++; } //Loads transpose Matrix of X for(i=0; i < N; i++){ //possible here for(j=0; j < (K + 1); j++){ T[j][i] = X[i][j]; } } //Creates empty Matrix of X(Matrix) * T(Matrix)-creating K+1(rows) x K+1(cols) double **XT; //Multiplication of X * T Matrix XT = (double**)malloc(sizeof(double*) * (K+1)); for(i=0; i < (K+1); i++){ XT[i] = (double*)malloc(sizeof(double) * (K+1)); } //XT is now loaded after multiplyMatrices function runs multiplyMatrices(T, X, XT, (K+1), N, (K+1)); //possible overflow here //Creates and loads Identity Matrix (K+1)(rows) x (K+1)(cols) double **I; I = (double**)malloc(sizeof(double*) * (K+1)); for(i=0; i < (K+1); i++){ I[i] = (double*)malloc(sizeof(double) * (K+1)); } for(i=0; i < (K+1); i++){ for(j=0; j < (K+1); j++){ if(i == j){ I[i][j] = 1; }else{ I[i][j] = 0; } } } //Creates empty Matrix of XT concatenated with I -creating N(rows) x 2*N(cols) double **augXTI; augXTI = (double**)malloc(sizeof(double*) * (K+1)); for(i=0; i < (K+1); i++){ augXTI[i] = (double*)malloc(sizeof(double) * (2*(K+1))); } //augXTI is now loaded after concatMatrices function runs concatMatrices(XT, I, augXTI, (K+1), (2*(K+1))); //possible overflow here for(i=0; i < (K+1); i++){ for(j=0; j < ((K+1)*2); j++){ if(i == j){ if(augXTI[i][j] != 1){ rowDivision(augXTI, i, augXTI[i][j], (K+1)); break; //restart as it hits pivot point } }else{ if(augXTI[i][j] != 0){ rowSubMultiply(augXTI, i, j, augXTI[i][j], (K+1)); } } } } int otherHalf = (K+1)-2; for(i = (K+1)-2; i > -1; i--){ for(j = (K+1)-1; j != otherHalf; j--){ if(augXTI != 0){ rowSubMultiply(augXTI, i, j, augXTI[i][j], (K+1)); //possible } } otherHalf--; } //matrix following W = (Inverse) * T (Part of the equation) double **IT; IT = (double**)malloc(sizeof(double*) * (K+1)); for(i=0; i < (K+1); i++){ IT[i] = (double*)malloc(sizeof(double) * N); } //Identity matrix converted to inverse matrix and multiplied with the transpose matrix for(i=0; i < (K+1); i++){ for(j=0; j < (K+1); j++){ I[i][j] = augXTI[i][j + (K+1)]; } } multiplyMatrices(I, T, IT, (K+1), (K+1), N); multiply1DMatrices(IT, Y, W, (K+1), N); //Creating testFile Matrix size V (rows) x K (cols) double **testFile; int V; //Represents # of rows in testFile FILE* fp2 = fopen(argv[2], "r"); fscanf(fp2, "%d\n", &V); testFile = (double**)malloc(sizeof(double*) * V); for(i=0; i < V; i++){ testFile[i] = (double*)malloc(sizeof(double) * (K+1)); } for(i=0; i < V; i++){ for(j=0; j < K+1; j++){ if(j == 0){ testFile[i][j] = 1; continue; } if(j == K){ fscanf(fp2, "%lf\n", &input); testFile[i][j] = input; }else{ fscanf(fp2, "%lf%*c", &input); testFile[i][j] = input; } } } double *result; result = (double*)malloc(sizeof(double) * V); multiply1DMatrices(testFile, W, result, V, (K+1)); for(i=0; i < V; i++){ printf("%0.0f\n", result[i]); } return 0; }
0e55424e6673da9cbe3e2199143b814f5bd1f8ea
[ "C" ]
1
C
arivera40/Computer-Architecture-Asst-2-One-Shot-Learning
ec5749cc0703507b7e947e9e366b4fb34ddb6eb0
750ab6f8f52ce01f1fa71e308134b40ba14885ee
refs/heads/master
<file_sep>package com.hoomi.rxjava.third; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import rx.Observable; import rx.functions.Action1; import java.io.PrintStream; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; /** * Created by hos05 on 3/15/16. */ public class ThirdExampleTest { private ThirdExample thirdExample; @Mock private PrintStream mockedPrintStream; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); thirdExample = new ThirdExample(mockedPrintStream); } @Test public void testMapIteration() throws Exception { List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> expected = Arrays.asList(1, 4, 9, 16, 25, 36); assertEquals(expected, thirdExample.mapIteration(integers, value -> value * value)); } @Test public void testMapReactive() throws Exception { List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> expected = Arrays.asList(1, 4, 9, 16, 25, 36); Observable<List<Integer>> mappedObservable = thirdExample.mapReactive(integers, value -> value * value); mappedObservable.subscribe(integers1 -> { assertEquals(expected, integers1); }); } }<file_sep>rootProject.name = 'HelloRxJava' include 'first' <file_sep>package com.hoomi.rxjava.second; import rx.Observable; import rx.Subscriber; import rx.observables.ConnectableObservable; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.regex.Pattern; /** * Created by hos05 on 3/15/16. */ public class SecondExample { public static final String EXIT = "exit"; private final PrintStream printStream; private final InputStream inputStream; public SecondExample() { this(System.out, System.in); } SecondExample(PrintStream printStream, InputStream inputStream) { this.printStream = printStream; this.inputStream = inputStream; } public ReactiveSum connect() { ConnectableObservable<String> input = from(inputStream); Observable<Double> a = varStream("a", input); Observable<Double> b = varStream("b", input); ReactiveSum sum = new ReactiveSum(a, b, printStream); input.connect(); return sum; } private Observable<Double> varStream(String varName, ConnectableObservable<String> input) { final Pattern pattern = Pattern.compile("^\\s*" + varName + "\\s*[:|=]\\s*(-?\\d+\\.?\\d*)\\n*$"); return input .map(pattern::matcher) .filter(matcher -> matcher.matches() && matcher.group(1) != null) .map(matcher -> Double.parseDouble(matcher.group(1))); } private ConnectableObservable<String> from(InputStream inputStream) { return from(new BufferedReader(new InputStreamReader(inputStream))); } private ConnectableObservable<String> from(BufferedReader bufferedReader) { return Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { if (subscriber.isUnsubscribed()) { return; } try { String line; while (!subscriber.isUnsubscribed() && (line = bufferedReader.readLine()) != null) { if (line.equals(EXIT)) { break; } subscriber.onNext(line); } } catch (Exception e) { subscriber.onError(e); } if (!subscriber.isUnsubscribed()) { subscriber.onCompleted(); } } }).publish(); } } <file_sep>package com.hoomi.rxjava.first; import rx.Observable; import rx.functions.Action0; import rx.functions.Action1; import java.io.PrintStream; import java.util.Arrays; import java.util.List; /** * Created by hoomanostovari on 14/03/2016. */ public class FirstExample { private final List<String> stringList; private final PrintStream printStream; FirstExample(PrintStream printStream) { this.stringList = Arrays.asList("One", "Two", "Three", "Four", "Five"); this.printStream = printStream; } public FirstExample() { this(System.out); } public void runIterate() { stringList.forEach(printStream::println); printStream.println("Complete"); } public void runRxJava() { Observable.from(stringList).subscribe(printStream::println, throwable -> printStream.println("There was an error"), () -> printStream.println("Complete")); } } <file_sep>group 'com.hoomi' version '1.0-SNAPSHOT' repositories { mavenCentral() } apply plugin: 'java' dependencies { compile 'io.reactivex:rxjava:1.0.10' testCompile 'org.mockito:mockito-all:2.0.2-beta' testCompile 'junit:junit:4.12' }
556738ffee767bae9fdf4206efc8b1d3d8ca52f7
[ "Java", "Gradle" ]
5
Java
hoomi/RXJavaExperiments
d1b48614b2841167202ef5cc94c1563b14eeb4f8
58207ae3f0272596d0745a59b49edd22ef8e5f64
refs/heads/main
<file_sep>from market.models import User from flask_wtf import FlaskForm from wtforms import BooleanField, StringField,PasswordField, SubmitField, IntegerField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError class RegisterForm(FlaskForm): def validate_username(self, username): user = User.query.filter_by(username = username.data).first() if user: raise ValidationError('Username already exists.') def validate_email(self, email): user = User.query.filter_by(email = email.data).first() if user: raise ValidationError('Eamil already exists.') username = StringField(label='Username', validators=[DataRequired(), Length(min=2, max=30)]) email = StringField(label='Email',validators=[DataRequired(), Email()]) password = <PASSWORD>Field(label='<PASSWORD>',validators=[DataRequired(), Length(min=6)]) confirm_password= PasswordField(label='Confirm Password',validators=[DataRequired(), EqualTo('password')]) submit = SubmitField(label='Register') class LoginForm(FlaskForm): username = StringField(label='Username',validators=[DataRequired()]) password = <PASSWORD>Field(label='<PASSWORD>',validators=[DataRequired(), Length(min=6)]) submit = SubmitField(label='Login') class PurchaseItemForm(FlaskForm): submit = SubmitField(label='Purchase Item') class SellItemForm(FlaskForm): submit = SubmitField(label='Sell Item') class AddItemForm(FlaskForm): name = StringField(label='Name', validators=[DataRequired()]) price = IntegerField(label='Price', validators=[DataRequired()]) barcode = StringField(label='Barcode', validators=[DataRequired(), Length(max=12)]) description = StringField(label='Description', validators=[DataRequired()]) submit = SubmitField(label='Add Item')<file_sep> from threading import current_thread from market import app, db, bcrypt from flask import render_template, redirect, url_for, flash, request from market.models import Item, User from market.forms import RegisterForm, LoginForm, PurchaseItemForm, SellItemForm, AddItemForm from flask_login import login_user, logout_user, login_required, current_user @app.route('/') @app.route('/home') def home_page(): return render_template('home.html') @app.route('/market', methods = ['GET', 'POST']) @login_required def market_page(): purchase_form= PurchaseItemForm() selling_form = SellItemForm() if request.method == 'POST': #Purchase Item purchased_item = request.form.get('purchased_item') p_item_object = Item.query.filter_by(name=purchased_item).first() if p_item_object: if current_user.budget >= p_item_object.price: p_item_object.owner = current_user.id current_user.budget -= p_item_object.price db.session.commit() flash(f"Congratulations, you purchased {p_item_object.name} for {p_item_object.price}$", 'success') else: flash(f'Insufficient Budget for {p_item_object.name}', 'danger') #Sell Item sold_item = request.form.get('sold_item') s_item_object = Item.query.filter_by(name=sold_item).first() print(s_item_object) if s_item_object: if s_item_object in current_user.items: s_item_object.owner = None current_user.budget += s_item_object.price db.session.commit() flash(f"Congratulations, you sold {s_item_object.name} for {s_item_object.price}$", 'info') else: flash(f"Something went wrong in selling!", 'danger') return redirect(url_for('market_page')) if request.method == 'GET': items = Item.query.filter_by(owner=None) owned_items = Item.query.filter_by(owner = current_user.id) return render_template('market.html', title = 'Market', items = items, purchase_form=purchase_form, owned_items=owned_items,selling_form=selling_form) @app.route('/register', methods = ['GET', 'POST']) def register_page(): form = RegisterForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user_to_create = User(username= form.username.data, email=form.email.data, password_hash=<PASSWORD>) db.session.add(user_to_create) db.session.commit() flash(f'Account Created!', 'success') return redirect(url_for('market_page')) return render_template('register.html', title='Register', form=form) @app.route('/login', methods = ['GET', 'POST']) def login_page(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user and bcrypt.check_password_hash(user.password_hash, form.password.data): login_user(user) flash(f'Success! You are logged in as: {user.username}', category='success') return redirect(url_for('market_page')) else: flash('Username or password did not match! Please try again.', category='danger') return redirect(url_for('login_page')) if request.method == 'GET': return render_template('login.html', title='Login', form=form) @app.route('/logout') def logout_page(): logout_user() flash('You have been logged out', 'info') return redirect(url_for("home_page")) @app.route('/add_item', methods = ['GET', 'POST']) @login_required def add_item(): form = AddItemForm() if request.method == "POST": item = Item(name = form.name.data, price = form.price.data, barcode = form.barcode.data, description = form.description.data) db.session.add(item) db.session.commit() flash(f"Congratulations, you have added {item.name} for {item.price}$", 'info') return redirect(url_for('market_page')) if request.method == 'GET': return render_template ('add_item.html', title = 'Add Item',form=form) <file_sep>{% extends "layout.html" %} {% block content %} <body> <div class="container"> <form method="POST" class="form-register" style="color: white;"> {{ form.hidden_tag() }} <img class="mb-4 img-fluid img-thumbnail mx-auto d-block rounded-circle", src="https://cdn.discordapp.com/attachments/553868150186311683/862588242049630228/2019-12-14.jpg"> <h1 class="h3 mb-3 front-weight-normal container">Create Your Account</h1> <fieldset> <div class="container"> {{form.username.label()}} {% if form.username.errors %} {{ form.username(class = "form-control is-invalid ") }} <div class="invalid-feedback"> {% for error in form.username.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.username(class = "form-control bg-dark text-white") }} {% endif %} </div> <div class="container"> {{form.email.label()}} {% if form.email.errors %} {{ form.email(class = "form-control is-invalid ") }} <div class="invalid-feedback"> {% for error in form.email.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.email(class = "form-control bg-dark text-white") }} {% endif %} </div> <div class="container"> {{ form.password.label() }} {% if form.password.errors %} {{ form.password(class = "form-control is-invalid") }} <div class="invalid-feedback"> {% for error in form.password.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.password(class = "form-control bg-dark text-white") }} {% endif %} </div> <div class="container"> {{ form.confirm_password.label() }} {% if form.confirm_password.errors %} {{ form.confirm_password(class = "form-control is-invalid ") }} <div class="invalid-feedback"> {% for error in form.confirm_password.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.confirm_password(class = "form-control bg-dark text-white") }} {% endif %} </div> </fieldset> <br> <div class="container"> {{ form.submit(class = "btn btn-outline-info") }} </div> </form> </div> <div class="container" pt-3> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="{{url_for('login_page')}}">Sign In</a> </small> </div> <br> </body> {% endblock content %}<file_sep>{% extends "layout.html" %} {% block content %} <h2 style="margin-top: 20px; margin-left: 20px;">Add Items to the Market</h2> <form method="POST" class="form-add" style="color: white;"> {{ form.hidden_tag() }} <fieldset class="mt-5"> <div class="container"> {{form.name.label()}} {% if form.name.errors %} {{ form.name(class="col-sm-2 col-form-label") }} <div class="invalid-feedback"> {% for error in form.name.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.name(class = "form-control bg-dark text-white") }} {% endif %} </div> <div class="container"> {{form.price.label()}} {% if form.price.errors %} {{ form.price(class="col-sm-2 col-form-label") }} <div class="invalid-feedback"> {% for error in form.price.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.price(class = "form-control bg-dark text-white") }} {% endif %} </div> <div class="container"> {{form.barcode.label()}} {% if form.barcode.errors %} {{ form.barcode(class="col-sm-2 col-form-label") }} <div class="invalid-feedback"> {% for error in form.barcode.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.barcode(class = "form-control bg-dark text-white") }} {% endif %} </div> <div class="container"> {{form.description.label()}} {% if form.description.errors %} {{ form.description(class="col-sm-2 col-form-label") }} <div class="invalid-feedback"> {% for error in form.description.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.description(class = "form-control bg-dark text-white") }} {% endif %} </div> </fieldset> <br> <div class="container"> {{ form.submit(class = "btn btn-outline-info") }} </div> </form> <br> <br> {% endblock content %}
7a67a74d556e9f4353b14f6c91982391b64abac6
[ "Python", "HTML" ]
4
Python
MaulikPandya06/Flask_Market
d4fcca392e0e6828177b7bdd4773d7358e31da04
52ab6e885d93e835b5b398a320d3746d70da1a79
refs/heads/master
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>jjoulestest</groupId> <artifactId>jjoules-test</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>Jjoules test </name> <url>http://maven.apache.org</url> <properties> <junit-jupiter-version>5.6.2</junit-jupiter-version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>${maven.compiler.source}</maven.compiler.target> <!-- Config for jacoco --> <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin> <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis> <sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath> <sonar.language>java</sonar.language> </properties> <scm> <connection>scm:git:[email protected]:Mamadou59/jjoules-jjoulestest.git</connection> <developerConnection>scm:git:[email protected]:Mamadou59/jjoules-jjoulestest.git</developerConnection> <url>https://github.com/Mamadou59/jjoules-jjoulestest</url> <tag>HEAD</tag> </scm> <dependencies> <dependency> <groupId>org.powerapi.junitjjoules</groupId> <artifactId>junit-jjoules</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.21.0</version> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> <version>1.2.0-M1</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.2.0</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.1</version> <configuration> <source>1.8</source> <target>1.8</target> <compilerArgument>-proc:none</compilerArgument> </configuration> </plugin> <!-- plugin for jacoco report --> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.4</version> <executions> <execution> <id>prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report</id> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin> <!-- jjoules maven plugin --> <plugin> <groupId>org.powerapi.jjoulesmaven</groupId> <artifactId>jjoules-maven-plugin</artifactId> <version>1.0-SNAPSHOT</version> <executions> <execution> <!-- <phase>jjoulestest</phase> <configuration> <outputDirectory>${basedir}/target/jjoules-reports</outputDirectory> </configuration> --> <goals> <goal>prepare-output</goal> <goal>save-result</goal> </goals> </execution> </executions> </plugin> <!-- <plugin> <groupId>com.jjoules</groupId> <artifactId>jjoules-maven-plugin</artifactId> <version>1.0-SNAPSHOT</version> <executions> <execution> <phase>phase</phase> <configuration>some-configuration</configuration> <goals> <goal>some-goal</goal> <goal>saveResult</goal> </goals> </execution> </executions> </plugin> --> </plugins> </build> </project> <file_sep>package jjoulestest; public class ClassOne { private int x; public ClassOne(int x) { this.x = x; } public void firstMethodSleepFor25ms() throws InterruptedException { Thread.sleep(25); } public void secondMethodSleepFor50ms() throws InterruptedException { Thread.sleep(50); } public int getX() { return this.x; } } <file_sep>package jjoulestest; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.powerapi.junitjjoules.mesureit.MesureIt; @MesureIt class ClassTwoTest { private ClassTwo clazz = new ClassTwo("jjoules"); @Test void testGetName() { assertEquals(this.clazz.getName(),"jjoules"); } @Test void testFirstMethodSleepFor75ms() throws InterruptedException { this.clazz.firstMethodSleepFor75ms(); } @Test void testSecondMethodSleepFor100ms() throws InterruptedException { this.clazz.secondMethodSleepFor100ms(); } } <file_sep># jjoules-test This project is used for jjoules plugins (maven and sonar) <file_sep>package jjoulestest; public class ClassTwo { private String name; public ClassTwo(String name) { this.name = name; } public String getName() { return this.name; } public void firstMethodSleepFor75ms() throws InterruptedException { Thread.sleep(75); } public void secondMethodSleepFor100ms() throws InterruptedException { Thread.sleep(100); } } <file_sep>FROM maven:3.6.0-jdk-11-slim AS build COPY src /home/jjoules-plugin/src COPY pom.xml /home/jjoules-plugin RUN mvn -f /home/jjoules-plugin/pom.xml clean install workdir /home/jjoules-plugin CMD mvn jjoules:runtest
2bb9d92c482d0d97c1502a9ce36e491c2e1bd633
[ "Markdown", "Java", "Maven POM", "Dockerfile" ]
6
Maven POM
sunssy59/jjoules-test
4d7baf44f4d7de3102a540f381949c16f748d32a
c5ee83e794d14ceaebc70dfa7dd962035ae6c48c
refs/heads/master
<repo_name>cef2010/fall_dev_15<file_sep>/cheat_sheet.rb require 'pry' # Open to main menu def main_menu puts "Cheat Sheet:\n\t0. Quit\n\t1. Command Line\n\t2. Vim\n\t3. Search\nChoose an Option: " input = gets.to_i if input == 0 exit elsif input == 1 command_line_menu elsif input == 2 vim_menu elsif input == 3 print 'Search for: ' search = gets.strip puts `man #{search}` main_menu else puts "I'm sorry, I didn't quite get that." main_menu end end def command_line_menu puts "Command Line Cheat Sheet: 0. Main Menu 1. copy - cp - cp <source filename> <destination filename> 2. move - mv - mv <source filename> <destination directory> 3. make directory - mkdir - mkdir <directory name>" input = gets.to_i if input == 0 main_menu elsif input == 1 puts `man cp` command_line_menu elsif input == 2 puts `man mv` command_line_menu elsif input == 3 puts `man mkdir` command_line_menu else puts "I didn't quite get that. Try again." command_line_menu end end def vim_menu puts "Vim Cheat Sheet:\n\tmove cursor left - h\n\tmove cursor right - l\n\tmove cursor up - k\n\tmove cursor down - j\n\n\tinsert mode - i\n\tescape inset mode - esc\n\n\twrite and quit vim - :wq\n\tquit vim without writing - :q\n\nPress 1 for vim documentation\nPress 0 to return to main menu" input = gets.to_i if input == 0 main_menu elsif input == 1 puts `man vim` main_menu else puts "I'm sorry, I didn't quite get that." end end main_menu <file_sep>/rps.rb # Intro game to user # prompt user for choice # gets user choice # generate computer choice # compare to determine winner # output results # BONUS # have game loop until player quit [x] # organize as methods to call one another [ ] # track score and games played [x] # add lizard/spock [ ] player_score = 0 cpu_score = 0 games = 0 begin choices = ['rock', 'paper', 'scissors'] puts "-----------\nChoose one!\n-----------\nRock\tPaper\tScissors" player = gets.chomp.downcase cpu = choices.sample if player == cpu puts "We both threw #{cpu}: Tie!" elsif ((player == 'rock') && (cpu == 'scissors')) || ((player == 'paper') && (cpu == 'rock')) || ((player == 'scissors') && (cpu == 'rock')) puts "You threw #{player} and I threw #{cpu}: You Win!" player_score += 1 elsif ((cpu == 'rock') && (player == 'scissors')) || ((cpu == 'paper') && (player == 'rock')) || ((cpu == 'scissors') && (player == 'rock')) puts "You threw #{player} and I threw #{cpu}: You Lose!" cpu_score += 1 else puts "Pick another!" games -= 1 end games += 1 puts "-----------\nGAMES: #{games}\n-----------\nYOU: #{player_score}\nCPU: #{cpu_score}" puts "-----------\nPlay Again?\n y/n \n-----------" again = gets.chomp.downcase end while again == 'y' <file_sep>/palindrome.rb require 'pry' def sanitize(input) @sani = input.delete(' ') @sani.downcase! end def revstring(string_to_reverse) @revcheck = [] binding.pry string_to_reverse.length.times do |t| @revcheck.shift(string_to_reverse(t)) end end def comparison if @revcheck.join('') == @sani puts "#{@input} is a palindrome!" else puts "#{@input} is not a palindrome!" end end def program puts "Enter a string to check for panidromes: " input = gets.chomp while input != 'exit' revstring(sanitize(input)) comparison end end program <file_sep>/day1_contact_list.rb contact_list = ['<NAME>: 816-970-3100', '<NAME>: 660-654-1183', '<NAME>: 867-5309', '<NAME>: 702-883-6969'] puts "Select an option:\n1) List Contacts\t2) Add New Contact\t3) Sort Contacts\n4) Edit Contact\t\t5) Delete a Contact" option = gets.chomp case option # OPTION list all contacts when '1' puts contact_list # OPTION create new contact when '2' print "Enter First Name: " first_name = gets.chomp print "Enter Last Name: " last_name = gets.chomp print "Enter Phone Number: " phone_number = gets.chomp contact_list << "#{last_name}, #{first_name}: #{phone_number}" puts "\nNew contact list:\n", contact_list # OPTION sort contacts when '3' contact_list = contact_list.sort puts "\nNew contact list:\n", contact_list # OPTION edit contact when '4' puts "Which contact would you like to edit?" puts contact_list, "> " to_edit = gets.chomp to_edit_index = contact_list.index{ |t| t.include?(to_edit) } puts "What would you like to change #{contact_list[to_edit_index]} to?" print "First Name: " first_name_edit = gets.chomp print "Last Name: " last_name_edit = gets.chomp print "Phone Number: " phone_number_edit = gets.chomp contact_list[to_edit_index] = "#{last_name_edit}, #{first_name_edit}: #{phone_number_edit}" puts "\nNew contact list:\n", contact_list # OPTION delete contact when '5' puts "Which contact should we delete?" puts contact_list, "> " contact_delete = gets.chomp contact_delete_index = contact_list.index{ |t| t.include?(contact_delete) } contact_list.delete_at(contact_delete_index) puts "\nNew contact list:\n", contact_list # ELSE print directions else puts 'Please select one of the numbered options!' end <file_sep>/cheat_sheet2.rb #require 'pry' #diag # Open to main menu def main_menu # puts "Cheat Sheet:\n\t0. Quit\n\t1. Command Line\n\t2. Vim\n\t3. Search\nChoose an Option: " # FIND A WAY TO STORE AND CALL METHODS IN HASH main = { '1' => ['command_line_menu', 'Command Line'], '2' => ['vim_menu', 'Vim'], '3' => ['sublime_menu', 'Sublime'] } # DON'T RUN UNTIL METHOD CAN BE CALLED FROM HASH puts "\tCheat Sheet:\n\t------------" main.length.times do |choice| puts "\t#{(choice + 1).to_s}. #{main[(choice + 1).to_s][1]}" end puts "\tS. Search" input = gets.chomp if input == 's' || input == 'S' print 'Search for: ' search = gets.strip puts `man #{search}` main_menu elsif input.to_i == 0 exit elsif input.to_i <= main.length method = main[input][0] #binding.pry #diag send(method.to_sym) else puts "I'm sorry, I didn't quite get that." main_menu end end def command_line_menu command_line = { '1' => ['copy', 'cp', 'cp <source filename> <destination filename>'], '2' => ['move', 'mv', 'mv <source filename> <destination filename>'], '3' => ['make directory', 'mkdir', 'mkdir <directory name>'], '4' => ['list', 'ls', 'ls <options>'], '5' => ['remove', 'rm', 'rm <options>'] } puts "\tCommand Line\n\t------------\n\t0. Return" command_line.length.times do |choice| puts "\t#{(choice + 1).to_s}. #{command_line[(choice + 1).to_s].join(' - ')}" end input = gets.to_i if input == 0 main_menu elsif input <= command_line.length puts `man #{command_line[input.to_s][1]}` command_line_menu else puts "I didn't quite get that. Try again." command_line_menu end end def vim_menu # puts "Vim Cheat Sheet:\n\tmove cursor left - h\n\tmove cursor right - l\n\tmove cursor up - k\n\tmove cursor down - j\n\n\tinsert mode - i\n\tescape inset mode - esc\n\n\twrite and quit vim - :wq\n\tquit vim without writing - :q\n\nPress 1 for vim documentation\nPress 0 to return to main menu" vim = { '1' => ['move cursor left', 'h'], '2' => ['move cursor right', 'l'], '3' => ['move cursor up', 'k'], '4' => ['move cursor down', 'j'], '5' => ['insert mode', 'i'], '6' => ['escape insert mode', 'esc'], '7' => ['write and quit', ':wq'], '8' => ['quit without writing', ':q'] } puts "\tVIM\n\t---\n\t0. Return" vim.length.times do |choice| puts "\t#{vim[(choice + 1).to_s].join(' - ')}" end puts "\tPress 'm' for VIM documentation." input = gets.chomp if input == 'm' puts `man vim` vim_menu elsif input == '0' main_menu else puts "I'm sorry, I didn't quite get that." vim_menu end end def sublime_menu sublime = { '1' => ['duplicate', 'CMD-SHFT-D'], '2' => ['indent left/right', 'CMD-[ OR ]'], '3' => ['move line up/down', 'CMD-CTRL-Up OR Down'], '4' => ['move cursor to end of line', 'CMD-Left OR Right'], '5' => ['comment out lines', 'CMD-/'], '6' => ['enter new line after comment', 'CMD-Enter'], '7' => ['enter line before current', 'CMD-SHFT-Enter'], '8' => ['select text w/ arrow keys', 'HOLD SHFT-Left OR Right'], '9' => ['delete row where cursor is', 'CTRL-SHFT-K'], '10' => ['multiple cursors', 'HOLD CMD-Click'], '11' => ['save as', 'CMD-SHFT-S'] } puts "\tSUBLIME\n\t-------\n\t0. Return" sublime.length.times do |choice| puts "\t#{sublime[(choice + 1).to_s].join(': ')}" end input = gets.to_i if input == 0 main_menu else puts "I'm sorry, I didn't quite get that." end end main_menu <file_sep>/encrypt.rb def encrypt(key, str) output = '' x = ('a'..'z').to_a str.length.times do |n| output << "#{str[n]}" key.times do |m| output << "#{x.sample}" end end output end def function print "Enter an encryption key as an integer: " k = gets.chomp.to_i print "Enter a string to be encrypted: " s = gets.chomp puts "Your encrypted string is: #{encrypt(k, s)}" end function <file_sep>/lunchlady.rb #build a menu @menu = { 'entree' => { 'chicken' => ['good chicken', '5'], 'burger' => ['good burger', '6'], 'steak' => ['good steak', '10'], 'meatloaf' => ['eh', '7'], 'hotdog' => ['good hotdog', '4'] }, 'side' => { 'fries' => ['crispy', '2'], 'chips' => ['crispy', '1.5'], "mac'n'cheese" => ['gooey', '3'], 'mashed potatoes' => ['mashed', '3'], 'corn' => ['corny', '2.5'] } } @total = 0 @side_counter = 0 def item_choice(type) #Prompt for entree if type == 'entree' puts "\nSelect an entree: \n-----------------" elsif type == 'side' puts "\nSelect a side: \n--------------" end @menu[type].length.times do |item| puts "#{@menu[type].keys[item]}: #{@menu[type].values[item][0]}, $#{@menu[type].values[item][1]}" end puts "\n" gets.chomp end def your_order if @side_counter <= 2 @order = "You chose #{@entree} with #{@side1} and #{@side2}." end # if @side_counter > 2 # @order = @order + "\nExtra: #{}" ### # end end def price(type, selection) @total += (@menu[type][selection][1]).to_f if type == 'side' @side_counter += 1 end end def your_total puts "Your total is: #{@total}" end def more_sides puts "Would you like any more sides?" if gets.chomp == 'yes' price('side', item_choice('side')) # your_order() more_sides end end def lunchlady @entree = item_choice('entree') price('entree', @entree) @side1 = item_choice('side') price('side', @side1) @side2 = item_choice('side') price('side', @side2) #MORE SIDES more_sides your_order your_total end lunchlady #print order #print total <file_sep>/reverse.rb def reverse(string) arr = string.to_s.downcase.split('') revarr = [] arr.each do |i| revarr.unshift(i) end revstr = "" v = 0 revarr.each do |e| if e != " " && v % 2 == 0 revstr << e.upcase v += 1 elsif e != " " revstr << e v += 1 else revstr << e end end puts revstr end usr = gets.chomp reverse(usr) <file_sep>/reverse.js // Reverse function reverse(str){ var input = str.split(''); var revstr = []; for(i = 0; i <= input.length; i++){ revstr.unshift(input[i]); }; return revstr.join(''); }; <file_sep>/calc.rb @operators = ['+','-','*','/'] def welcome print " Enter the equation you would like to calculate, remember to use spaces between your operator and numbers. " end def user_input print "" input = gets.chomp @input = input.split(" ") return @input # input is array at this point end def valid(arr) # iterate through array, #CHECK FOR LETTER z = 1 unless /[a-z]/.match(arr.join('')) z = 0 end if z == 1 return false elsif z == 0 end #Is there an operator present x = 0 while arr.length > x if @operators.include?(arr[x]) #puts 'found an operator' #diag #puts "#{arr[x]}"#diag if arr[x - 1].to_f.is_a?(Numeric) && arr[x + 1].to_f.is_a?(Numeric) #puts "#{arr[x - 1]} and #{arr[x + 1]}" # diag else #puts " #{return false} " # diag return false end end x += 1 end # Take user_input # Verify it is a normal math problem # Return true if valid, return true end def extract @n1 = @input[0].to_f @n2 = @input[2].to_f @op = @input[1] end def compute if @op == '+' #puts "addition" diag @answer = @n1 + @n2 elsif @op == '-' #puts "subtraction" diag @answer = @n1 - @n2 elsif @op == '/' #puts 'division' diag @answer = @n1 / @n2 elsif @op == '*' #puts 'multiplication' diag @answer = @n1 * @n2 end puts " ------\n #{@answer}" end def error puts "Input not recognized. Please only use provided options." end def output if valid == false return error else compute end end def calc welcome if valid(user_input) extract compute else error calc end # Welcome message # Get user input to calculate # Validate user input # Compute user input # Output user input or error end calc <file_sep>/reverse2.rb def reverse(string) input = string.to_s.downcase revstr = "" input.each_char do |i| revstr.insert(0, i) end v = 0 revstr.each_char do |e| if e != " " && v % 2 == 0 revstr e.upcase! v += 1 elsif e != " " v += 1 else end end puts revstr end usr = gets.chomp reverse(usr) <file_sep>/largestint.rb def largest(arr) compare = 0 arr.each do |e| if e > compare compare = e end end puts "The largest number in #{arr} is #{compare}." end usr = [] print "How many numbers will be compared? " q = gets.chomp.to_i q.times do |n| print "Enter number #{n}: " usr[n] = gets.chomp.to_i end largest(usr) <file_sep>/repeating_letters.rb def sanitize(input) input.downcase.split(' ') end def letter_count(word) length = word.length m = 0 length.times do |i| n = word.count(word[i]) if n > m m = n end end return m end def compare(str_arr) high = [] count = 2 str_arr.each do |str| if letter_count(str) == count high << str count = letter_count(str) elsif letter_count(str) > count high = [] high << str count = letter_count(str) end end return high end def program puts "Input words to compare, separated by spaces: " input = gets.chomp output = compare(sanitize(input)) if output == [] puts "No words contained repeating characters." elsif output.length == 1 puts "The word with the most repeating characters is: #{output[0]}" else puts "Multiple words had the same number of repeating characters: " output.each { |word| puts word } end end program <file_sep>/fizzbuzzint.rb def fizzbuzz(i1, i2) (i1..i2).each do |n| if (n % 3 == 0) && (n % 5 == 0) puts 'FizzBuzz' elsif (n % 3 == 0) puts 'Fizz' elsif (n % 5 == 0) puts 'Buzz' else puts n end end end x1 = gets.chomp.to_i x2 = gets.chomp.to_i fizzbuzz(x1, x2) <file_sep>/magicnumber.rb require 'humanize' def input print "Enter a number: " @num = gets.chomp end def magicnumber(i) if i == '4' puts "4 is the magic number." elsif i == '' elsif i == 'im cold' puts "Go buy a snuggie." elsif i == '123456789' puts "#{i} was a stupid choice. Put some thought into this." elsif i == '69' puts "\nlol. good call.\n\n" elsif i == '80085' puts "\nlol boobs\n\n" elsif i == 'B==D' puts "\nthats a penis\n\n" else i != '4' count = i.to_i.humanize.length puts "#{i} is #{count}." end end def program while @num != '' magicnumber(input) end end program <file_sep>/todo.rb require 'pry' class List attr_accessor :name, :item_array def initialize(name) @name = name @item_array = [] end def display_menu insults = ["\tTRY AGAIN LOSER", "\tYOU'RE TERRIBLE AT THIS", "\tYOUR MOM WAS BETTER AT THIS LAST NIGHT", "\tREALLY...", "\tITS NOT ME ITS YOU", "\tJUST GIVE UP"] insult_counter = 0 while true puts """ What would you like to do? 1. Display List 2. Add item 3. Remove item 4. Mark an item complete 5. Exit """ choice = gets.chomp if choice == '1' display_list elsif choice == '2' puts 'Name of list item: ' item_name = gets.chomp puts 'Add a description: ' description = gets.chomp add_item(item_name, description) elsif choice == '3' display_list puts 'Type name of item to remove: ' to_delete = gets.chomp delete_item(to_delete) elsif choice == '4' display_list puts 'Type item name to mark completed: ' mark = gets.chomp completed(mark) elsif choice == '5' return false else if insult_counter <= insults.length - 2 puts insults[insult_counter] else puts insults[insults.length - 1] end insult_counter += 1 end end end def add_item(name, description) @item_array << Item.new(name, description) end def display_list @item_array.each do |item| print "\t", item.item_name + ' -- ' + item.description, "\n" end end def delete_item(to_delete) @item_array.delete_if {|arr| arr.item_name == to_delete} end def completed(mark) completed_index = @item_array.index {|x| x.item_name == mark} @item_array[completed_index].description << ' [x]' end end class Item attr_accessor :item_name, :description def initialize(item_name, description) @item_name = item_name @description = description end end l = List.new('l') l.display_menu
5841146e8716cfc0a8424569ff2b87c797ba6ca9
[ "JavaScript", "Ruby" ]
16
Ruby
cef2010/fall_dev_15
e4358d64d029389e3cca40731f53b8f1416c3a07
7c1a6db90909420284662f6d59a24ef5e43b056f
refs/heads/master
<file_sep>package com.example.wheredidyougo; import java.util.ArrayList; import java.util.List; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseImageView; import com.parse.ParseObject; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Gallery; @SuppressWarnings("deprecation") public class GalleryImageAdapter extends BaseAdapter { private Context mContext; public ArrayList<ParseFile> photos = new ArrayList<ParseFile>(); LayoutInflater inflater; List<ParseObject> objects; public GalleryImageAdapter(Context context, List<ParseObject> objects) { mContext = context; for(ParseObject obj:objects) { photos.add(obj.getParseFile("image")); } Log.i("SIZE", " " + photos.size()); } public int getCount() { return photos.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int index, View view, ViewGroup viewGroup) { // TODO Auto-generated method stub ParseImageView image = new ParseImageView(mContext); ParseFile test = photos.get(index); try { Bitmap bm = BitmapFactory.decodeByteArray(test.getData(), 0, test.getData().length); image.setImageBitmap(bm); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } image.setLayoutParams(new Gallery.LayoutParams(150, 150)); image.setScaleType(ParseImageView.ScaleType.FIT_XY); return image; } } <file_sep>package com.example.wheredidyougo; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ListView; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; public class FollowMap extends ListActivity implements TextWatcher { AutoCompleteTextView mAutoComplete; ParseUser mUser; ArrayList<String> dictionary; ArrayList<String> followers; List<ParseObject> objects; UserObjects utility = new UserObjects(); Button btn_Find; static int pos; static ArrayAdapter<String> adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.follower_activity); Intent in = getIntent(); dictionary = in.getStringArrayListExtra("users"); followers = in.getStringArrayListExtra("users"); mUser = ParseUser.getCurrentUser(); mAutoComplete = (AutoCompleteTextView) findViewById(R.id.follower_search); mAutoComplete.addTextChangedListener(this); mAutoComplete.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, dictionary)); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, followers); setListAdapter(adapter); btn_Find = (Button) findViewById(R.id.btn_map); btn_Find.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String search; search = mAutoComplete.getText().toString(); utility.removeFollowers(search, mUser.getUsername(), followers); adapter.notifyDataSetChanged(); } }); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); pos = position; AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); // set title alertDialogBuilder.setTitle("View " + followers.get(position) + "'s locations?") .setCancelable(false) .setNegativeButton("Yes",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { Intent in = new Intent(FollowMap.this, MyMap.class); in.putExtra("user", followers.get(pos)); in.putExtra("count", utility.getCount(followers.get(pos))); startActivity(in); } }) .setPositiveButton("No",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // if this button is clicked, just close // the dialog box and do nothing dialog.dismiss(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); // // Intent in = new Intent(FollowMap.this, MyMap.class); // in.putExtra("user", followers.get(position)); // startActivity(in); } @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } public ArrayList<String> getObj() throws ParseException { ArrayList<String> followers = new ArrayList<String>(); ParseQuery<ParseObject> query = ParseQuery.getQuery(mUser.getUsername()); query.whereExists("following"); query.addAscendingOrder("following"); objects = query.find(); Log.i("TAG", mUser.getUsername()); for (ParseObject obj:objects){ Log.i("TAG", obj.getString("following")); followers.add(obj.getString("following")); } return followers; } } <file_sep>package com.example.wheredidyougo; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Bitmap.Config; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Gallery; import android.widget.TextView; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseImageView; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; //redirected here upon clicking My Images from home screen. @SuppressWarnings("deprecation") public class MyImages extends Activity { private ParseUser mUser = ParseUser.getCurrentUser(); ParseFile file; ArrayList<ParseFile> photos = new ArrayList<ParseFile>(); ArrayList<String> comments = new ArrayList<String>(); ParseImageView imgView; Gallery gallery; Context context = this; List<ParseObject> objects; TextView text; TextView address; TextView address2; ParseObject initial; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.images); gallery = (Gallery) findViewById(R.id.gallery); gallery.setSpacing(1); imgView = (ParseImageView) findViewById(R.id.imageView); text = (TextView) findViewById(R.id.comment); address = (TextView) findViewById(R.id.address); address2 = (TextView)findViewById(R.id.address2); try { ParseQuery<ParseObject> queryView = ParseQuery.getQuery(mUser.getUsername()); queryView.whereDoesNotExist("following"); initial = queryView.getFirst(); setImageView(initial); } catch (ParseException e2) { e2.printStackTrace(); } try { ParseQuery<ParseObject> query = ParseQuery.getQuery(mUser.getUsername()); query.whereDoesNotExist("following"); objects = query.find(); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } gallery.setAdapter(new GalleryImageAdapter(this, objects)); gallery.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ParseObject obj = objects.get(position); setImageView(obj); } }); } public void setImageView(ParseObject obj) { String com = obj.getString("comment"); String add = obj.getString("address"); int ch = add.indexOf(","); String add2; if (add.equalsIgnoreCase("noaddress") || add.equalsIgnoreCase("no address")) add2 = ""; else{ add2 = add.substring(ch, add.length()); add2 = add2.replaceFirst(",", ""); } add = add.substring(0,ch); ParseFile test = obj.getParseFile("image"); try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inPreferredConfig = Config.RGB_565; options.inDither = true; Bitmap bm = BitmapFactory.decodeByteArray(test.getData(), 0, test.getData().length,options); //Log.i("WW", bm.getWidth() + " " + bm.getHeight()); //int width = bm.getWidth(); //int height = bm.getHeight(); //int newWidth = 200; //int newHeight = 200; //float scaleWidth = ((float) newWidth) / width; //float scaleHeight = ((float) newHeight) / height; //Log.i("AAAAA", scaleWidth + " " +scaleHeight); // Matrix matrix = new Matrix(); //matrix.postScale(scaleWidth, scaleHeight); // recreate the new Bitmap // Bitmap bit = Bitmap.createBitmap(bm, 0, 0, // width, height, matrix, true); Bitmap bitm = Bitmap.createBitmap(bm); imgView.setImageBitmap(bitm); text.setText(com); address.setText(add); address2.setText(add2); Log.i("IMG", imgView.getWidth() + " " + imgView.getMeasuredWidth()); Log.i("IMG", imgView.getHeight() + " " + imgView.getMeasuredHeight()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package com.example.wheredidyougo; import java.util.ArrayList; import java.util.List; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ListView; public class UserSearch extends ListActivity implements TextWatcher { Button btn_Find; AutoCompleteTextView mAutoComplete; static ArrayAdapter<String> adapter; ArrayList<String> usernames; ArrayList<String> dictionary; List<ParseObject> temp; ParseUser mUser; List<ParseUser> obj; UserObjects utility = new UserObjects(); static int pos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.user_search_activity); Intent in = getIntent(); dictionary = in.getStringArrayListExtra("users"); usernames = in.getStringArrayListExtra("users"); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dictionary); setListAdapter(adapter); mUser = ParseUser.getCurrentUser(); mAutoComplete = (AutoCompleteTextView) findViewById(R.id.search_user); mAutoComplete.addTextChangedListener(this); mAutoComplete.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,dictionary)); btn_Find = (Button) findViewById(R.id.btn_find); btn_Find.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String search; search = mAutoComplete.getText().toString(); utility.removeUsers(search, usernames); adapter.notifyDataSetChanged(); } }); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); mUser = ParseUser.getCurrentUser(); ParseQuery<ParseObject> query = ParseQuery.getQuery(mUser.getUsername()); query.whereEqualTo("following", usernames.get(position)); try { temp = query.find(); } catch (ParseException e) { e.printStackTrace(); } pos = position; if (temp.size() == 0) { AlertDialog.Builder alertDialogBuilder = followDialog(); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } else if(temp.size() == 1) { AlertDialog.Builder alertDialogBuilder = removeDialog(); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } } private AlertDialog.Builder followDialog() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); // set dialogue alertDialogBuilder .setTitle("Follow user?") .setMessage(usernames.get(pos)) .setCancelable(false) .setNegativeButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { ParseObject mObject = new ParseObject(mUser.getUsername()); mObject.put("following", usernames.get(pos)); mObject.saveInBackground(); dialog.dismiss(); } }) .setPositiveButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); return alertDialogBuilder; } private AlertDialog.Builder removeDialog() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder .setTitle("Delete user?") .setMessage(usernames.get(pos)) .setCancelable(false) .setNegativeButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { temp.get(0).deleteInBackground(); dialog.dismiss(); } }) .setPositiveButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); return alertDialogBuilder; } @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } }
dcbb8f172d9d310e29ef7efc9dfefa2ffe98ef5d
[ "Java" ]
4
Java
willhnation/WhereDidYouGo
b83417798b437801c0e5bdfa324aa1fd29b3a050
2172544039096f044de327fd2998f610c008ebec
refs/heads/master
<repo_name>guilhermemaster/parametros_basicos_php<file_sep>/inverter_data.php  <?php function troca_data($data){ $str = $data; $arr1 = str_split($str); $aux=$arr1[0]; $arr1[0]=$arr1[8]; $arr1[8]=$aux; $aux=$arr1[1]; $arr1[1]=$arr1[9]; $arr1[9]=$aux; $aux=$arr1[2]; $arr1[2]=$arr1[7]; $arr1[7]=$aux; $aux=$arr1[3]; $arr1[3]=$arr1[5]; $arr1[5]=$aux; $aux=$arr1[4]; $arr1[4]=$arr1[6]; $arr1[6]=$aux; $aux=$arr1[5]; $arr1[5]=$arr1[6]; $arr1[6]=$aux; $aux=$arr1[6]; $arr1[6]=$arr1[9]; $arr1[9]=$aux; $aux=$arr1[6]; $arr1[6]=$arr1[8]; $arr1[8]=$aux; $aux=$arr1[7]; $arr1[7]=$arr1[8]; $arr1[8]=$aux; $segun = implode("", $arr1); print $segun; } $data="2014-02-20"; print troca_data($data); ?> <file_sep>/conexao.php <?php $conexao = mysql_connect("localhost", "root", "leticia") or die ("Erro na conexão com o bd"); $db = mysql_select_db("Centroespi") or die ("Erro na seleção da base de dados!"); ?><file_sep>/select_com_form.php <?php include_once "../conexao_pagina/conexao_pagina.php"; ?> <?php $sql="SELECT * FROM SiteGeral"; $resultado1 = mysql_query($sql) or die ("Não é possivel realiza a consuta"); if(@mysql_num_rows($resultado1)==0) die ("Nenhum registro encontrado"); while($linha1=mysql_fetch_array($resultado1)) { print" <form action=\"../paginas/edithome_validar.php\" method=\"get\"> <p>Titutlo primário:<textarea name=\"text1\" rows=\"10\" cols=\"30\" />".$linha1['Tituloprimario']."</textarea></p> <p>Texto primário:<textarea name=\"text2\" rows=\"10\" cols=\"30\" />".$linha1['TexoPrimario']."</textarea></p> <p>Título secundario:<textarea name=\"text3\" rows=\"10\" cols=\"30\" />".$linha1['Titulosecundario']."</textarea></p> <p>Texto secundario:<textarea name=\"text4\" rows=\"10\" cols=\"30\" />".$linha1['TextoSecundario']."</textarea></p> <p>Texto Lateral 1º:<textarea name=\"text5\" rows=\"10\" cols=\"30\" />".$linha1['TextLateral1']."</textarea></p> <p>Texto Lateral 2º:<textarea name=\"text6\" rows=\"10\" cols=\"30\" />".$linha1['TextLateral2']."</textarea></p> <p>Texto Lateral 3º:<textarea name=\"text7\" rows=\"10\" cols=\"30\" />".$linha1['TextLateral3']."</textarea></p> <input type=\"submit\" /> </form>"; } ?>
9ec57338aa0774daf52c99653e346f7c6b67f300
[ "PHP" ]
3
PHP
guilhermemaster/parametros_basicos_php
d9698efccbe7c7692884783b930502dd4c8428d5
27980489a90eaf4bcd4d6457b97ef6cccbeb4cfb
refs/heads/master
<file_sep>require "pry" # Helper Method def position_taken?(board, index) !(board[index].nil? || board[index] == " ") end # Define your WIN_COMBINATIONS constant WIN_COMBINATIONS = [ [0, 1, 2], # Top row [3, 4, 5], # Middle row [6, 7, 8], # Bottom row [0, 3, 6], # Left vertical [1, 4, 7], # Middle vertical [2, 5, 8], # Right vertical [0, 4, 8], # Upper left diagonal [2, 4, 6] # Upper right diagonal ] def won?(board) WIN_COMBINATIONS.each do |win_combo| win_index1 = win_combo[0] win_index2 = win_combo[1] win_index3 = win_combo[2] if (board[win_index1] == "X" && board[win_index2] == "X" && board[win_index3] == "X") return win_combo elsif (board[win_index1] == "O" && board[win_index2] == "O" && board[win_index3] == "O") return win_combo end end if (board.none? {|position| position == " " || position == "" || position == nil}) return false elsif (board == [" ", " ", " ", " ", " ", " ", " ", " ", " "] || board == ["","","","","","","","",""]) # return false else return false end end def full?(board) board.all? do |position| position == "X" || position == "O" end end def draw?(board) if (won?(board) == false && full?(board) == true) return true else return false end end def over?(board) if won?(board) != false return true elsif full?(board) == true return true end end def winner(board) if (won?(board)) win_combo = won?(board) binding.pry sample_index = win_combo[0] if board[sample_index] == "X" return "X" elsif board[sample_index] == "O" return "O" end end return nil end
b6776e77305663be73e51984cb5bad0ca6f7c1e0
[ "Ruby" ]
1
Ruby
adamclayman/ttt-game-status-bootcamp-prep-000
dcf40da65eea7733dd190b65966e59cf7ae0bbe1
853318fe09704f3c349452a99c9014f9430ea68c
refs/heads/master
<file_sep>#ifdef LKSJDKJGBSFJKD #include <cspace/cspace.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "frametable.h" #include "frametable_tests.h" #include <assert.h> #define verbose 5 #include <sys/debug.h> #include <sys/panic.h> void ftest(){ int page; // locate 10 pages and make sure you can touch them all for (int i = 0; i < 10; i++) { /* Allocate a page */ seL4_Word ret; frame_alloc(&ret); assert(ret); uint32_t * vaddr = (uint32_t *) ret; /* Test you can touch the page */ *vaddr = 0x37; assert(*vaddr == 0x37); printf("Page #%lu allocated at %p\n", i, (void *) vaddr); } /* Test that you never run out of memory if you always free frames. */ for (int i = 0; i < 10000; i++) { //[> Allocate a page <]/ seL4_Word ret; page = frame_alloc(&ret); assert(ret); uint32_t * vaddr = (uint32_t *) ret; //[> Test you can touch the page <] *vaddr = 0x37; assert(*vaddr == 0x37); //[> print every 1000 iterations <] if (i % 1000 == 0) { printf("Page #%d allocated at %p\n", i, vaddr); } frame_free(page); } /* Test that you eventually run out of memory gracefully, and doesn't crash */ while (1) { /*Allocate a page */ seL4_Word ret; frame_alloc(&ret); /*assert(ret);*/ uint32_t * vaddr = (uint32_t *) ret; if (!vaddr) { printf("Out of memory!\n"); break; } /*[>Test you can touch the page <]*/ *vaddr = 0x37; assert(*vaddr == 0x37); } } void ftest_cap() { seL4_Word page[10]; /* Allocate 10 pages */ for (int i = 0; i < 10; i++) { /* Allocate a page */ seL4_Word ret; frame_alloc(&page[i]); assert(page[i]); uint32_t * vaddr = (uint32_t *) page[i]; /* Test you can touch the page */ *vaddr = 0x37; assert(*vaddr == 0x37); printf("Page #%lu allocated at %p\n", i, (void *) vaddr); } /* De-allocate the 10 pages */ for (int i = 0; i < 10; i++) { frame_free(page[i]); assert(page[i]); uint32_t * vaddr = (uint32_t *) page[i]; /* Should generate cap fault */ *vaddr = 0x37; assert(*vaddr == 0x37); } } #endif <file_sep>#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <sel4/sel4.h> #include <sos/rpc.h> void rpc_call(seL4_MessageInfo_t tag, seL4_Word endpoint) { seL4_SetTag(tag); seL4_Call(endpoint, tag); } void rpc_call_data(seL4_MessageInfo_t tag, void *vData, size_t count, seL4_Word endpoint){ seL4_SetMR(1, vData); seL4_SetMR(2, count); rpc_call(tag, endpoint); } void rpc_call_mr(seL4_MessageInfo_t tag, seL4_Word endpoint) { rpc_call(tag, endpoint); } <file_sep>/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #ifndef _TIMER_H_ #define _TIMER_H_ #include <sel4/sel4.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <clock/epit.h> #include <clock/clock.h> /* * Return codes for driver functions */ #define CLOCK_R_OK 0 /* success */ #define CLOCK_R_UINT (-1) /* driver not initialised */ #define CLOCK_R_CNCL (-2) /* operation cancelled (driver stopped) */ #define CLOCK_R_FAIL (-3) /* operation failed for other reason */ #define CLOCK_MAX_TIMERS 32 typedef struct callback_node_t callback_node_t; struct callback_node_t { callback_node_t *next; timer_callback_t callback; void* data; int id; uint64_t timestamp; }; typedef struct { callback_node_t *head; } callback_queue; /* * Register callback timer, add to the linked list of callbacks, change timer if necessary */ /* * Get the next free identifier */ int allocate_timer_id(); /* * Deallocate free identifier */ int deallocate_timer_id(int id); /* * Initialise driver. Performs implicit stop_timer() if already initialised. * interrupt_ep: A (possibly badged) async endpoint that the driver should use for deliverying interrupts to * * Returns CLOCK_R_OK iff successful. */ int start_timer(seL4_CPtr interrupt_ep); /* * Register a callback to be called after a given delay * delay: Delay time in microseconds before callback is invoked * callback: Function to be called * data: Custom data to be passed to callback function * * Returns 0 on failure, otherwise an unique ID for this timeout */ uint32_t register_timer(uint64_t delay, timer_callback_t callback, void *data); /* * Remove a previously registered callback by its ID * id: Unique ID returned by register_time * Returns CLOCK_R_OK iff successful. */ int remove_timer(uint32_t id); /* * Handle an interrupt message sent to 'interrupt_ep' from start_timer * * Returns CLOCK_R_OK iff successful */ int timer_interrupt(void); /* * Returns present time in microseconds since booting. * * Returns a negative value if failure. */ timestamp_t time_stamp(void); /* * Stop clock driver operation. * * Returns CLOCK_R_OK iff successful. */ int stop_timer(void); void handle_irq(timer timer); void handle_irq_callback(); void clock_irq(void); #endif /* _TIMER_H_ */ <file_sep>/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ /**************************************************************************** * * $Id: $ * * Description: Simple milestone 0 code. * Libc will need sos_write & sos_read implemented. * * Author: <NAME> * ****************************************************************************/ #include <stdarg.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include "ttyout.h" #include <sel4/sel4.h> void ttyout_init(void) { /* Perform any initialisation you require here */ } static size_t sos_debug_print(const void *vData, size_t count) { size_t i; const char *realdata = vData; for (i = 0; i < count; i++) seL4_DebugPutChar(realdata[i]); return count; } /*size_t sos_write(void *vData, size_t count) {*/ /*const char *realdata = vData;*/ /*int left = count;*/ /*int read = 0;*/ /*while(left > 0 ) {*/ /*int j;*/ /*seL4_SetMR(0, 1);*/ /*for(j = 1; j <= left && j <= seL4_MsgMaxLength; j++) {*/ /*seL4_SetMR(j, realdata[read + (j - 1)]);*/ /*}*/ /*seL4_MessageInfo_t tag = seL4_MessageInfo_new(0, 0, 0, j+1);*/ /*seL4_SetTag(tag);*/ /*seL4_Call(SYSCALL_ENDPOINT_SLOT, tag);*/ /*int sent = (int)seL4_GetMR(0);*/ /*read = read + sent;*/ /*left = left - sent;*/ /*}*/ /*return read;*/ /*}*/ /*size_t sos_read(void *vData, size_t count) {*/ /*//implement this to use your syscall*/ /*return 0;*/ /*}*/ <file_sep>#include "addrspace.h" #include "ut_manager/ut.h" #include "frametable.h" #include "mapping.h" #include "vmem_layout.h" #define verbose 5 #include "sys/debug.h" #include "sys/panic.h" pageDirectory* pageTable_create(void){ //Create a new Page Directory pageDirectory* pd = malloc(sizeof(pageDirectory)); conditional_panic(pd == NULL, "Couldn't allocate memory for the Page Directory!"); pd->PD_addr = ut_alloc(seL4_PageDirBits); int err = cspace_ut_retype_addr(pd->PD_addr, seL4_ARM_PageDirectoryObject, seL4_PageDirBits, cur_cspace, &(pd->PageD)); memset(pd->pTables, 0, VM_PDIR_LENGTH*sizeof(seL4_Word)); //seL4 zeros memory except when it doesn't if(err){ dprintf(0,"Could not retype memory in pageTable_create!\n"); } pd->regions = NULL; return pd; } int vm_fault(pageDirectory * pd, seL4_Word addr) { region * reg = find_region(pd, addr); if(reg == NULL){ return -1; } else{ int frame = frame_alloc(); if(!frame){ dprintf(0,"Memory Allocation Failed!\n"); return -2; } int err = sos_map_page(pd, frame, addr, seL4_AllRights, seL4_ARM_Default_VMAttributes); if(err){ dprintf(0,"Page mapping at %x failed with error code %d\n",addr, err); return -3; } } return 0; } region * new_region(pageDirectory * pd, seL4_Word start, size_t len, seL4_Word flags){ // A define a new region, that we can compare against when we try // to declare a new frame if(!start || find_region(pd, start) || find_region(pd,start + len)) { return NULL; } if(start > PROCESS_IPC_BUFFER || (start + len > PROCESS_IPC_BUFFER && !( flags & REGION_STACK))){ return NULL; } region * reg = malloc(sizeof(region)); if(!reg){ return NULL; } dprintf(0,"Adding New Region at %x , for %d bytes\n", start, len); reg->vbase = start; reg->size = len; reg->flags = flags; region * head = pd->regions; if(!head){ pd->regions = reg; } else{ while(head->next){ if((reg->vbase < head->vbase) && ((reg->vbase + len) > (head->vbase + head->size))) { return NULL; } head = head->next; } head->next = reg; } return reg; } void PD_destroy(pageDirectory * pd){ for(int i = 0; i < VM_PDIR_LENGTH; i++){ if(pd->pTables[i]){ PT_destroy(pd->pTables[i]); cspace_delete_cap(cur_cspace, pd->pTables_CPtr[i]); ut_free(pd->pTables_pAddr[i], seL4_PageTableBits); } } cspace_delete_cap(cur_cspace, pd->PageD); ut_free(pd->PD_addr, seL4_PageDirBits); free(pd); pd = NULL; } void PT_destroy(pageTable * pt){ for(int i = 0; i < VM_PTABLE_LENGTH; i++){ if(pt->frameIndex[i]){ frame_free(pt->frameIndex[i]); } } } region * find_region(pageDirectory * pd, seL4_Word vAddr){ if(pd){ region * head = pd->regions; while(head){ if((head->flags & REGION_STACK) == 0){// Regions grow up, Unless they are stacks. if((vAddr >= head->vbase) && vAddr < (head->vbase + head->size)){ return head; } }else{ if(vAddr <= head->vbase && vAddr > (head->vbase - head->size)){ return head; } } head = head->next; } } return NULL; //Either no regions are defined, or we couldn't find one that fits. So return NULL } void free_region_list(region * head){ while(head){ region * tmp = head; head = head->next; free(tmp); } } void get_shared_buffer(region *shared_region, size_t count, char *buf) { dprintf(0, "shared_region_1 addr 0x%x, size %d \n", shared_region->vbase, shared_region->size); int buffer_index = 0; while(shared_region) { memcpy(buf, (void *)shared_region->vbase, shared_region->size); buffer_index += shared_region->size; shared_region = shared_region->next; } return buf; } void free_shared_buffer(char * buf, size_t count) { for(int i = 0; i<count; i++) { free(&(buf[i])); } } //the regions struct is only maintained by kernel is thus trusted. void put_to_shared_region(region *shared_region, char *buf) { char *page_start; int buffer_index; while(shared_region) { page_start = shared_region->vbase; memcpy(page_start, (void *)shared_region->vbase. shared_region->size); shared_region = shared_region->next; } } region * get_shared_region(seL4_Word user_vaddr, size_t len, pageDirectory * user_pd) { //Reuse region structs to define our regions of memory region *head = malloc(sizeof(region)); region *tail = head; while(len > 0) { //check defined user regions if(!pt_ckptr(user_vaddr, len, user_pd)) { dprintf(0,"Invalid memory region\n"); free_region_list(head); return NULL; } //get the sos_vaddr that corresponds to the user_vaddr seL4_Word sos_vaddr = get_user_translation(user_vaddr, user_pd); if(!sos_vaddr) { dprintf(0, "Mapping does not exist.\n"); free_region_list(head); return NULL; } //this is the start address on this page tail->vbase = sos_vaddr + PAGE_OFFSET(user_vaddr); //the length left on this page size_t page_len = PAGE_ALIGN(user_vaddr + (1 << seL4_PageBits)) - user_vaddr; //we need more regions if( len > page_len ) { tail->size = page_len; len -= page_len; tail->next = malloc(sizeof(region)); //increment user_vaddr to find the next start of the page user_vaddr += tail->size; tail = tail->next; //no more regions } else { tail->size = len; len = 0; } tail->flags = seL4_AllRights; tail->next = NULL; } return head; } //get the kernel_vaddr representation of user_vaddr seL4_Word get_user_translation(seL4_Word user_vaddr, pageDirectory * user_pd) { uint32_t dindex = VADDR_TO_PDINDEX(user_vaddr); uint32_t tindex = VADDR_TO_PTINDEX(user_vaddr); uint32_t index = user_pd->pTables[dindex]->frameIndex[tindex]; return VMEM_START + (ftable[index].index << seL4_PageBits); } int pt_ckptr(seL4_Word user_vaddr, size_t len, pageDirectory * user_pd) { region *start_region = find_region(user_pd, user_vaddr); region *end_region = find_region(user_pd, user_vaddr + len); //TODO CHECK FLAGS if((start_region && end_region) && //the buffer should not be spanning multiple regions (start_region->vbase == end_region->vbase)){ return 1; } return 0; } <file_sep>#ifndef EPIT_H #define EPIT_H typedef struct { uint32_t REG_Control; uint32_t REG_Status; uint32_t REG_Load; uint32_t REG_Compare; uint32_t REG_Counter; } EPIT; #define EPIT_CLK_PERIPHERAL (1 << 24); #define EPIT_CLK_MSK (3 << 24); #define EPIT_STOP_EN (1 << 21); #define EPIT_WAIT_EN (1 << 19); #define EPIT_I_OVW (1 << 17); #define EPIT_SW_R (1 << 16); #define EPIT_PRESCALE_CONST (3300 << 4); #define EPIT_PRESCALE_MSK (0xFFF << 4); #define EPIT_RLD (1 << 3); #define EPIT_OCI_EN (1 << 2); #define EPIT_EN_MOD (1 << 1); #define EPIT_EN (1 << 0); void epit_init(EPIT timer); void epit_setTime(EPIT timer, uint32_t milliseconds, int reset); void epit_startTimer(EPIT timer); void epit_stopTimer(EPIT timer); int epit_timerRunning(EPIT timer); uint32_t epit_getCount(EPIT timer); uint32_t epit_currentCompare(EPIT timer); #endif <file_sep>#ifndef _ADDRSPACE_H_ #define _ADDRSPACE_H_ #include "sel4/types.h" #include <cspace/cspace.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #define VM_PDIR_LENGTH 4096 #define VM_PTABLE_LENGTH 256 #define REGION_STACK 0x10000000 #define STACK_BOTTOM 0x60000000 #define HEAP_BUFFER 0x00010000 #define PAGE_OFFSET(a) ((a) & ((1 << seL4_PageBits) - 1)) #define PAGE_ALIGN(a) ((a) & ~((1 << seL4_PageBits) -1)) #define VM_FAULT_READ 0x1 #define VM_FAULT_WRITE 0x2 #define VM_FAULT_READONLY 0x4 typedef struct region_t { seL4_Word vbase; seL4_Word size; seL4_Word flags; struct region_t *next; } region; typedef struct sos_PageTable{ uint32_t frameIndex[VM_PTABLE_LENGTH]; }pageTable; typedef struct sos_PageDirectory { region *regions; seL4_ARM_PageDirectory PageD; //CPtr for seL4 Free seL4_Word PD_addr; //UT * for ut_free pageTable * pTables[VM_PDIR_LENGTH]; //SOS Pagetable //may move to pagetable seL4_Word pTables_pAddr[VM_PDIR_LENGTH]; //seL4 Memory location seL4_ARM_PageTable pTables_CPtr[VM_PDIR_LENGTH]; //seL4 Cap Pointer } pageDirectory; pageDirectory* pageTable_create(void); void PD_destroy(pageDirectory * pd); void PT_destroy(pageTable * pt); region * new_region(pageDirectory * pd, seL4_Word start, size_t len, seL4_Word flags); region * find_region(pageDirectory * pd, seL4_Word vAddr); void free_region_list(region* head); int vm_fault(pageDirectory * pd,seL4_Word addr); region * get_shared_region(seL4_Word user_vaddr, size_t len, pageDirectory * user_pd); seL4_Word get_user_translation(seL4_Word user_vaddr, pageDirectory * user_pd); int pt_ckptr(seL4_Word user_vaddr, size_t len, pageDirectory * user_pd); void get_shared_buffer(region *shared_region, size_t count, char *buf); void free_shared_buffer(char * buf, size_t count); #endif <file_sep>/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #ifndef _MAPPING_H_ #define _MAPPING_H_ #include <sel4/sel4.h> #include <vm/addrspace.h> #define VADDR_TO_PDINDEX(x) x >> 20 #define VADDR_TO_PTINDEX(x) (x << 12) >> 24 #define VADDR_TO_PDALIGN(x) (x >> 20) << 20 /** * Maps a page into a page table. * A 2nd level table will be created if required * * @param frame_cap a capbility to the page to be mapped * @param pd A capability to the page directory to map to * @param vaddr The virtual address for the mapping * @param rights The access rights for the mapping * @param attr The VM attributes to use for the mapping * @return 0 on success */ int map_phy_mem(int low, int high, seL4_Word cur_cspace); int map_page(seL4_CPtr frame_cap, seL4_ARM_PageDirectory pd, seL4_Word vaddr, seL4_CapRights rights, seL4_ARM_VMAttributes attr); int sos_map_page(pageDirectory * pd, uint32_t frame, seL4_Word vAddr, seL4_CapRights rights, seL4_ARM_VMAttributes attr); /** * Maps a device to virtual memory * A 2nd level table will be created if required * * @param paddr the physical address of the device * @param size the number of bytes that this device occupies * @return The new virtual address of the device */ void* map_device(void* paddr, int size); #endif /* _MAPPING_H_ */ <file_sep>#ifndef EPIT_H #define EPIT_H typedef struct { uint32_t REG_Control; uint32_t REG_Status; uint32_t REG_Load; uint32_t REG_Compare; uint32_t REG_Counter; } EPIT; typedef struct { EPIT *reg; seL4_IRQHandler cap; uint32_t source; } timer; #define EPIT_CLK_PERIPHERAL (1 << 24) #define EPIT_CLK_MSK (3 << 24) #define EPIT_STOP_EN (1 << 21) #define EPIT_OM (3 << 22) #define EPIT_WAIT_EN (1 << 19) #define EPIT_DB_EN (1 << 18) #define EPIT_I_OVW (1 << 17) #define EPIT_SW_R (1 << 16) #define EPIT_PRESCALE_CONST (3300 << 4) #define EPIT_PRESCALE_MSK (0xFFF << 4) #define EPIT_RLD (1 << 3) #define EPIT_OCI_EN (1 << 2) #define EPIT_EN_MOD (1 << 1) #define EPIT_EN (1 << 0) #define EPIT_TICK 0.05 #define EPIT_TICK_PER_MS 20 #define EPIT_CLOCK_TICK 0.06206 //#define EPIT_CLOCK_TICK 0.00001515 #define EPIT_CLOCK_OVERFLOW 266546000 //#define EPIT_CLOCK_OVERFLOW 65069 //void epit_init(EPIT timer); void epit_init(EPIT *timer); void epit_setTime(EPIT *timer, uint64_t milliseconds, int reset); void epit_startTimer(EPIT *timer); void epit_stopTimer(EPIT *timer); uint64_t epit_getCurrentTimestamp(); void epit_setTimerClock(EPIT *timer); int epit_timerRunning(EPIT *timer); uint32_t epit_getCount(EPIT *timer); uint32_t epit_currentCompare(EPIT *timer); #endif <file_sep>#ifndef _VM_H_ #define _VM_H_ #endif <file_sep>/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #include "mapping.h" #include "frametable.h" #include <ut_manager/ut.h> #include "vmem_layout.h" #define USER_VIRT(paddr) (paddr + USER_PSY_START) #define verbose 5 #include <sys/panic.h> #include <sys/debug.h> #include <assert.h> #include <cspace/cspace.h> extern const seL4_BootInfo* _boot_info; /** * Maps a page table into the root servers page directory * @param vaddr The virtual address of the mapping * @return 0 on success */ static int _map_page_table(seL4_ARM_PageDirectory pd, seL4_Word vaddr){ seL4_Word pt_addr; seL4_ARM_PageTable pt_cap; int err; /* Allocate a PT object */ pt_addr = ut_alloc(seL4_PageTableBits); if(pt_addr == 0){ return !0; } /* Create the frame cap */ err = cspace_ut_retype_addr(pt_addr, seL4_ARM_PageTableObject, seL4_PageTableBits, cur_cspace, &pt_cap); if(err){ return !0; } /* Tell seL4 to map the PT in for us */ err = seL4_ARM_PageTable_Map(pt_cap, pd, vaddr, seL4_ARM_Default_VMAttributes); return err; } /*int map_phy_mem(int low, int high, seL4_Word cur_cspace) {*/ /*int err;*/ /*int i = PAGE_OFFSET(low);*/ /*dprintf(0, "Mapping phy memory 0x%x -> 0x%x\n high is 0x%x",i, USER_VIRT(i), high);*/ /*while(i < high) {*/ /*seL4_CPtr *cap;*/ /*//create the frame cap */ /*err = cspace_ut_retype_addr(i, seL4_ARM_SmallPageObject, */ /*seL4_PageBits, cur_cspace, cap);*/ /*[>assert(!err);<]*/ /*//Map in the frame */ /*err = map_page(cur_cspace, seL4_CapInitThreadPD, USER_VIRT(i),*/ /*seL4_AllRights, 0);*/ /*[>assert(!err);<]*/ /*i = i + (1 << seL4_PageBits);*/ /*}*/ /*}*/ int map_page(seL4_CPtr frame_cap, seL4_ARM_PageDirectory pd, seL4_Word vaddr, seL4_CapRights rights, seL4_ARM_VMAttributes attr){ int err; /* Attempt the mapping */ err = seL4_ARM_Page_Map(frame_cap, pd, vaddr, rights, attr); if(err == seL4_FailedLookup){ /* Assume the error was because we have no page table */ err = _map_page_table(pd, vaddr); if(!err){ /* Try the mapping again */ err = seL4_ARM_Page_Map(frame_cap, pd, vaddr, rights, attr); } } return err; } static int sos_map_page_table(pageDirectory * pd, seL4_Word vaddr){ int err; int index = VADDR_TO_PDINDEX(vaddr); vaddr = VADDR_TO_PDALIGN(vaddr); dprintf(1,"Attempting to map Page Table %p\n", vaddr); /* Allocate a PT object */ pd->pTables_pAddr[index] = ut_alloc(seL4_PageTableBits); if(pd->pTables_pAddr[index] == 0){ return seL4_NotEnoughMemory; } /* Create the frame cap */ err = cspace_ut_retype_addr(pd->pTables_pAddr[index], seL4_ARM_PageTableObject, seL4_PageTableBits, cur_cspace, &(pd->pTables_CPtr[index])); if(err){ ut_free(pd->pTables_pAddr[index], seL4_PageTableBits); pd->pTables_pAddr[index] = 0; return err; } /* Tell seL4 to map the PT in for us */ err = seL4_ARM_PageTable_Map(pd->pTables_CPtr[index], pd->PageD, vaddr, seL4_ARM_Default_VMAttributes); if(!err){ assert(index < VM_PDIR_LENGTH); pd->pTables[index] = malloc(sizeof(pageTable)); if(!pd->pTables[index]){ return seL4_NotEnoughMemory; } } return err; } int sos_map_page(pageDirectory * pd, uint32_t frame, seL4_Word vaddr, seL4_CapRights rights, seL4_ARM_VMAttributes attr){ int err; uint32_t dindex, tindex; dindex = VADDR_TO_PDINDEX(vaddr); //Grab the top 12 bits. tindex = VADDR_TO_PTINDEX(vaddr); //Grab the next 8 bits. assert(dindex < VM_PDIR_LENGTH); assert(tindex < VM_PTABLE_LENGTH); assert(frame); vaddr = vaddr >> seL4_PageBits; //Page Align the vaddress. vaddr = vaddr << seL4_PageBits; if(pd->pTables[dindex] == NULL){ err = sos_map_page_table(pd, vaddr); if(err){ return err; } } err = seL4_ARM_Page_Map(ftable[frame].cptr, pd->PageD, vaddr, rights, attr); if(err == seL4_NoError){ assert(pd->pTables[dindex] != NULL); pd->pTables[dindex]->frameIndex[tindex] = frame; } /* Map the user_phy_addr to sos */ /*dprintf(0, "MAPPING paddr 0x%x -> 0x%x \n", ftable[frame].p_addr, VMEM_START + ftable[frame].p_addr);*/ map_page(ftable[frame].kern_cptr, seL4_CapInitThreadPD, VMEM_START + (ftable[frame].index << seL4_PageBits), seL4_AllRights, seL4_ARM_Default_VMAttributes); return err; } void* map_device(void* paddr, int size){ static seL4_Word virt = DEVICE_START; seL4_Word phys = (seL4_Word)paddr; seL4_Word vstart = virt; dprintf(1, "Mapping device memory 0x%x -> 0x%x (0x%x bytes)\n", phys, vstart, size); while(virt - vstart < size){ seL4_Error err; seL4_ARM_Page frame_cap; /* Retype the untype to a frame */ err = cspace_ut_retype_addr(phys, seL4_ARM_SmallPageObject, seL4_PageBits, cur_cspace, &frame_cap); conditional_panic(err, "Unable to retype device memory"); /* Map in the page */ err = map_page(frame_cap, seL4_CapInitThreadPD, virt, seL4_AllRights, 0); conditional_panic(err, "Unable to map device"); /* Next address */ phys += (1 << seL4_PageBits); virt += (1 << seL4_PageBits); } return (void*)vstart; } <file_sep>/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #include <stdarg.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include <sos.h> #include <sos/rpc.h> #include <sel4/sel4.h> #define SYSCALL_ENDPOINT_SLOT 1 int sos_sys_open(const char *path, fmode_t mode) { assert(!"You need to implement this"); return -1; } int sos_sys_read(int file, char *buf, size_t nbyte) { assert(!"You need to implement this"); return -1; } size_t sos_write(void *vData, size_t count) { const char *realdata = vData; seL4_MessageInfo_t tag = seL4_MessageInfo_new(0,0,0,3); seL4_SetMR(0, SOS_SYS_WRITE); rpc_call_data(tag, vData, count, SYSCALL_ENDPOINT_SLOT); return seL4_GetMR(0); } void sos_sys_usleep(int msec) { seL4_MessageInfo_t tag = seL4_MessageInfo_new(0,0,0,2); seL4_SetMR(0, SOS_SYS_SLEEP); seL4_SetMR(1, msec); rpc_call_mr(tag, SYSCALL_ENDPOINT_SLOT); } int64_t sos_sys_time_stamp(void) { seL4_MessageInfo_t tag = seL4_MessageInfo_new(0,0,0,1); seL4_SetMR(0, SOS_SYS_TIMESTAMP); rpc_call_mr(tag, SYSCALL_ENDPOINT_SLOT); int64_t time = seL4_GetMR(0); time = time << 32; time += seL4_GetMR(1); return time; } int sos_sys_write(int file, const char *vData, size_t count) { return 0; } <file_sep>#include <clock/clock.h> #include <cspace/cspace.h> #include "platsupport/plat/epit_constants.h" #include <assert.h> #include <clock/epit.h> #include "mapping.h" #include "timer.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <autoconf.h> #define verbose 5 #include <sys/debug.h> #include <sys/panic.h> //Number of timer overflows for the periodic timer uint64_t timestamp_overflows; //Our two timer registers timer timers[2]; //The timer id allocation list int freelist[CLOCK_MAX_TIMERS]; //The callback queue callback_queue queue; /******************* *** IRQ handler *** *******************/ int timer_interrupt(void) { /* Handle IRQ */ if(timers[0].reg->REG_Status) { handle_irq(timers[0]); handle_irq_callback(); } if(timers[1].reg->REG_Status) { timestamp_overflows += 1; handle_irq(timers[0]); } return 0; } void handle_irq_callback() { //timer overflow, need more time uint64_t timestamp = epit_getCurrentTimestamp(); if(queue.head->timestamp > timestamp) { uint64_t delay = queue.head->timestamp - timestamp; epit_setTime(timers[0].reg, delay, 1); } else { //temp pointer callback_node_t *temp = queue.head; //change queue queue.head = queue.head->next; //In the simple case of one timer, we will reset timer before the callback. //In the harder case where multiple timers need to fire we have to fire the callbacks first. while(queue.head && queue.head->timestamp <= timestamp){ callback_node_t *temp2 = queue.head; queue.head = queue.head->next; temp2->callback(temp2->id, temp2->data); free(temp2); deallocate_timer_id(temp2->id); } if(queue.head){ uint64_t delay = queue.head->timestamp - timestamp; epit_setTime(timers[0].reg, delay, 1); } else { epit_stopTimer(timers[0].reg); } temp->callback(temp->id, temp->data); free(temp); deallocate_timer_id(temp->id); } } void handle_irq(timer timer) { int err; timer.reg->REG_Status = 1; err = seL4_IRQHandler_Ack(timer.cap); assert(!err); } static void testfunc_print(int number, void* data) { dprintf(0, "In callback, number: %d, timestamp is %llu\n", number, epit_getCurrentTimestamp()); } static seL4_CPtr enable_irq(int irq, seL4_CPtr aep) { seL4_CPtr cap; int err; /* Create an IRQ handler */ cap = cspace_irq_control_get_cap(cur_cspace, seL4_CapIRQControl, irq); assert(cap); /* Assign to an end point */ err = seL4_IRQHandler_SetEndpoint(cap, aep); /* Ack the handler before continuing */ err = seL4_IRQHandler_Ack(cap); assert(!err); return cap; } int start_timer(seL4_CPtr interrupt_ep){ //badged copy of the asyncEP seL4_CPtr _irq_ep = interrupt_ep; //create interrupt handling cap timers[0].cap = enable_irq( EPIT1_INTERRUPT, _irq_ep); timers[1].cap = enable_irq( EPIT2_INTERRUPT, _irq_ep); //Map the device into the drivers virtual address space uintptr_t pstart_EPIT1 = (uintptr_t)EPIT1_DEVICE_PADDR; uintptr_t pstart_EPIT2 = (uintptr_t)EPIT2_DEVICE_PADDR; timers[0].reg = (EPIT *) map_device((void*)pstart_EPIT1, 20); timers[1].reg = (EPIT *) map_device((void*)pstart_EPIT2, 20); //Set up periodic clock timers[0].source = 1; timers[1].source = 2; epit_init(timers[0].reg); epit_init(timers[1].reg); //Start timer epit1 for timestamps updates epit_setTimerClock(timers[1].reg); epit_startTimer(timers[1].reg); queue.head = NULL; return 0; } /* Functions to Manage hardware. Defines located in epit.h. Init will clear Enabled, Input Overwrite and Output Mode. It will enable Peripheral Clock, Enable mode 1 (LR or 0xFFFF_FFFF), interupts and Sets Reload mode The Prescale is 3300, or 1 count every 0.00005 seconds. */ void epit_init(EPIT *timer){ volatile uint32_t *CR = &(timer->REG_Control); //Set Prescaler to defined prescale value, set to periph clock, and enable reloading *CR |= (EPIT_PRESCALE_CONST | EPIT_CLK_PERIPHERAL | EPIT_RLD); timer->REG_Status = 1; //Clear Status Register *CR |= (EPIT_EN_MOD | EPIT_OCI_EN); //Timer will reset from 0xFFFF_FFFF or Load Value } void epit_setTimerClock(EPIT *timer) { timer->REG_Control &= (0xFFFFFFFF ^ (EPIT_EN_MOD)); timer->REG_Control &= (0xFFFFFFFF ^ (EPIT_RLD)); timer->REG_Control |= EPIT_PRESCALE_MSK; timer->REG_Status = 1; } uint64_t epit_getCurrentTimestamp() { //Get number of ticks int status[2]; int offset = 0; status[0] = timers[1].reg->REG_Status; if(status[0]){ offset = 1; }; uint64_t count = 0xFFFFFFFF - timers[1].reg->REG_Counter; status[1] = timers[1].reg->REG_Status; //The clock rolled over as we read the value, so we might need to add a full cycle. if(status[0] != status[1]){ if(count > 0xF0000000){ offset = 1; //If the count is high, then we read after rollover, add a cycle. } else{ offset = 0; //The count is low, so we read before the rollover, we don't need an extra cycle } } //Convert to ms count *= EPIT_CLOCK_TICK; //Add overflow values uint64_t timestamp = (timestamp_overflows + offset) * EPIT_CLOCK_OVERFLOW; timestamp = timestamp + count; return timestamp; } void epit_setTime(EPIT *timer, uint64_t milliseconds, int reset){ //IF reset is non-zero We'll tell the timer to restart from our new value. if(reset){ timer->REG_Control |= EPIT_I_OVW; } epit_stopTimer(timer); uint32_t newCount; milliseconds *= EPIT_TICK_PER_MS; if(milliseconds > 0xFFFFFFFF) { newCount = 0xFFFFFFFF; } else { newCount = (uint32_t)milliseconds; } timer->REG_Load = newCount; epit_startTimer(timer); if(reset){ timer->REG_Control &= (0xFFFFFFFF ^(EPIT_I_OVW)); } } void epit_startTimer(EPIT *timer){ //The timer needs a tick to realise what is going on asm("nop"); timer->REG_Control |= EPIT_EN; } void epit_stopTimer(EPIT *timer){ timer->REG_Control &= (0xFFFFFFFF ^ EPIT_EN); asm("nop"); } int epit_timerRunning(EPIT *timer){ return (timer->REG_Control & EPIT_EN); } uint32_t epit_getCount(EPIT *timer){ return (timer->REG_Counter); } uint32_t epit_currentCompare(EPIT *timer){ return (timer->REG_Compare); } int allocate_timer_id() { int i; for(i = 1; i < CLOCK_MAX_TIMERS; i++) { if(!freelist[i]){ freelist[i]++; return i; } } return -1; } int deallocate_timer_id(int id) { if(freelist[id]){ freelist[id] = 0; return 0; } return -1; } // On Failure, returns 0. Calling function must check! uint32_t register_timer(uint64_t delay, timer_callback_t callback, void *data) { //create node callback_node_t *node = malloc(sizeof(callback_node_t)); if(!node){ dprintf(0, "Failed to Acquire Memory for Timer\n"); return 0; } node->callback = callback; int id = allocate_timer_id(); if(id == -1) { dprintf(0,"No Free Timer ID\n"); free(node); return 0; } node->id = id; uint64_t timestamp = epit_getCurrentTimestamp() + delay; node->timestamp = timestamp; node->data = data; node->next = NULL; //if the timer is already activated if(queue.head != NULL) { //the current timer is before the new timer if(queue.head->timestamp <= timestamp) { callback_node_t *cur = queue.head; while(cur->next && cur->next->timestamp <= timestamp){ cur = cur->next; } node->next = cur->next; cur->next = node; } else { //activate the new timer node->next = queue.head; queue.head = node; epit_stopTimer(timers[0].reg); epit_setTime(timers[0].reg, delay, 1); epit_startTimer(timers[0].reg); } } else { queue.head = node; epit_stopTimer(timers[0].reg); epit_setTime(timers[0].reg, delay, 1); epit_startTimer(timers[0].reg); } return id; } timestamp_t time_stamp(void){ return epit_getCurrentTimestamp(); } int stop_timer(void){ epit_stopTimer(timers[0].reg); epit_stopTimer(timers[1].reg); callback_node_t *temp = queue.head; while(queue.head) { queue.head = temp->next; free(temp); deallocate_timer_id(temp->id); temp = queue.head; } return CLOCK_R_OK; } int remove_timer(uint32_t id) { callback_node_t *temp = queue.head; while(temp) { if(temp->id == id) break; temp = temp->next; } if(!temp) { return -1; } else { //if temp is head we need to stop timer if(temp == queue.head) { epit_stopTimer(timers[0].reg); //if there is more timers, activate them queue.head = temp->next; if(queue.head) { uint64_t timestamp = epit_getCurrentTimestamp(); epit_setTime(timers[0].reg, queue.head->timestamp - timestamp, 1); epit_startTimer(timers[0].reg); } } } return id; } <file_sep>#ifndef _FRAMETABLE_H_ #define _FRAMETABLE_H_ #include <cspace/cspace.h> #define VMEM_START 0x20000000 typedef struct frameNode{ uint32_t index; seL4_Word p_addr; seL4_CPtr cptr; seL4_CPtr kern_cptr; struct frameNode * next; } frame; frame* ftable; void frametable_init(seL4_Word low, seL4_Word high, cspace_t *cur_cspace); uint32_t frame_alloc(void); int frame_free(uint32_t index); void freeList_init(seL4_Word count); frame * nextFreeFrame(void); void freeList_freeFrame(frame * fNode); #endif <file_sep>#include "timer_tests.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void timerCallback(uint32_t id, void* data){ register_timer(100, timerCallback, (void*)NULL); dprintf(0, "Good Morning Vietnam! time is %llu \n", epit_getCurrentTimestamp()); } void timerCallbackz(uint32_t id, void* data){ register_timer(250, timerCallbackz, (void*)NULL); dprintf(0, "Hello World, time is %llu \n", epit_getCurrentTimestamp()); } <file_sep>#include "cspace/cspace.h" #define verbose 5 #include <sys/debug.h> #include <sys/panic.h> #include "syscall.h" #include "stdlib.h" #include "timer.h" int sos_sleep(int msec, seL4_CPtr reply_cap){ seL4_CPtr* data = malloc(sizeof(seL4_CPtr)); if(data == NULL){ dprintf(0,"Failed malloc in sos_sleep\n"); return -1; } *data = reply_cap; uint32_t timer = register_timer(msec, &sos_wake, (void*)data); if(!timer){ dprintf(0,"Help I'm stuck in an operating system %d\n", timer); return 1; } return 0; } uint32_t sos_brk(long newbreak, pageDirectory * pd, region * heap){ dprintf(0, "PD is 0x%x, Heap is 0x%x\n", pd, heap); if(newbreak == 0){ return heap->vbase; } if(newbreak < heap->vbase || find_region(pd, newbreak)){ return 0; } heap->size = newbreak - heap->vbase; return newbreak; } void sos_wake(int* id, void* data){ seL4_CPtr reply = *((seL4_CPtr*)data); free(data); seL4_MessageInfo_t tag = seL4_MessageInfo_new(0,0,0,1); seL4_SetMR(0, 0); seL4_Send(reply, tag); cspace_free_slot(cur_cspace, reply); } <file_sep>#include "clock/clock.h" int start_timer(seL4_CPtr interrupt_ep){ } <file_sep>#include "frametable.h" #include "ut_manager/ut.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <mapping.h> #define verbose 5 #include <sys/debug.h> #include <sys/panic.h> extern frame* ftable; frame * freeList; int _ftInit = 0; seL4_CPtr pd; int bootstrapFrames; void frametable_init(seL4_Word low, seL4_Word high, cspace_t *cur_cspace) { assert(!_ftInit); pd = seL4_CapInitThreadPD; seL4_Word size = high - low; seL4_Word count = size >> seL4_PageBits; int err; seL4_CPtr tmp; bootstrapFrames = (count*sizeof(frame) >> seL4_PageBits) + 1; for(int i = 0; i < bootstrapFrames; i++){ seL4_CPtr f = ut_alloc(seL4_PageBits); err = cspace_ut_retype_addr(f, seL4_ARM_SmallPageObject, seL4_PageBits, cur_cspace, &tmp); conditional_panic(err,"Failed to allocate memory for frame table!\n"); map_page(tmp, pd, (VMEM_START + (i << seL4_PageBits)), seL4_AllRights, seL4_ARM_PageCacheable); } dprintf(0,"Frametable Initialised with %d frames.\n", count); ftable = (frame*) VMEM_START; freeList = &ftable[bootstrapFrames + 1]; freeList_init(count); _ftInit = 1; } void freeList_init(seL4_Word count){ for(int i = bootstrapFrames + 1; i < count-1; i++){ ftable[i].index = i; ftable[i].next = &ftable[i + 1]; } } /* * The physical memory is reserved via the ut_alloc, the memory is retyped into a frame, and the frame is mapped into the SOS * window at a fixed offset of the physical address. */ uint32_t frame_alloc(void) { frame* fNode = nextFreeFrame(); if(!fNode){ dprintf(0,"Next Frame Not Found\n"); return 0; } int index = fNode->index; ftable[index].next = NULL; ftable[index].p_addr = ut_alloc(seL4_PageBits); if(!ftable[index].p_addr){ dprintf(0,"Ut alloc failed\n"); freeList_freeFrame(fNode); return 0; } int err; //retype memory and save cap for user err = cspace_ut_retype_addr(ftable[index].p_addr, seL4_ARM_SmallPageObject, seL4_PageBits, cur_cspace,&(ftable[index].cptr)); if(err){ dprintf(0,"Retype Failed at index %d with error code %d\n", index, err); ut_free(ftable[index].p_addr, seL4_PageBits); ftable[index].p_addr = 0; freeList_freeFrame(fNode); return 0; } //save cap for kernel ftable[index].kern_cptr = cspace_copy_cap(cur_cspace, cur_cspace, ftable[index].cptr, seL4_AllRights); if(!ftable[index].kern_cptr){ dprintf(0,"Kernel cap failed at index %d with error code %d\n", index, err); ut_free(ftable[index].p_addr, seL4_PageBits); ftable[index].p_addr = 0; freeList_freeFrame(fNode); return 0; } return index; } /* * The physical memory is no longer mapped in the window, the frame object is destroyed, and the physical memory ranged * is returned via ut_free */ int frame_free(uint32_t index) { if(ftable[index].next == NULL){ freeList_freeFrame(&ftable[index]); seL4_ARM_Page_Unmap(ftable[index].cptr); cspace_delete_cap(cur_cspace, ftable[index].cptr); ut_free(ftable[index].p_addr, seL4_PageBits); ftable[index].cptr = (seL4_CPtr) NULL; ftable[index].p_addr = (seL4_Word) NULL; } else return -1; return 0; } frame * nextFreeFrame( void ){ frame* fNode; if(freeList){ fNode = freeList; freeList = freeList->next; return fNode; } return NULL; } void freeList_freeFrame(frame * fNode){ fNode->next = freeList; freeList = fNode; } //vspace is represented by a PD object //PDs map page tables //PTs map pages //creating a PD (by retyping) creates the vspace //deleting the PD deletes the vspace //Code example: //get untyped memory (a page size) //seL4_Word frame_addr = ut_alloc(seL4_PageBits); //retype memory to type seL4_ARM_Page //cspace_ut_retype_addr(frame_addr, seL4_ARM_Page, seL4_ARM_Default_VMAttributes); //insert mapping //map_page(frame_cap, pd_cap, 0xA00000000, seL4_AllRights, seL4_ARM_Default_VMAttributes); //zero the new memory //bzero((void *)0xA0000000, PAGESIZE); //each mapping requeires its own frame cap even for the same fram, and has: //virtual_address, phys_address, address_space and frame_cap //address_space struct identifies the level 1 page_directory cap //you need to keep track of (frame_cap, PD_cap, v_adr, p_adr) // //sizes of memory objects // //OBJECT Size in bytes (and alignment) //Frame 2^12 //PageD 2^14 //PageT 2^10 <file_sep>/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ /**************************************************************************** * * $Id: $ * * Description: Simple milestone 0 test. * * Author: <NAME> * Original Author: <NAME> * ****************************************************************************/ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <sel4/sel4.h> #include "sos.h" #include "ttyout.h" // Block a thread forever // we do this by making an unimplemented system call. static void thread_block(void){ seL4_MessageInfo_t tag = seL4_MessageInfo_new(0, 0, 0, 1); seL4_SetTag(tag); seL4_SetMR(0, 213); seL4_Call(SYSCALL_ENDPOINT_SLOT, tag); } int malloc_hammer(){ int* bob; int i = 0; printf("\nStarting New Test\n"); while(1){ bob = malloc(1024*sizeof(int)); if(!(i % 1000)){ printf("At i = %d, Bob = %x\n", i, bob); } if(!bob){ break; } bob[3] = 25; i++; } printf("Out Of Memory\n"); return 0; } #define NPAGES 27 #define TEST_ADDRESS 0x20000000 #define PAGE_SIZE_4K 4096 /* called from pt_test */ static void do_pt_test(char *buf) { int i; /* set */ for (int i = 0; i < NPAGES; i++) { buf[i * PAGE_SIZE_4K] = i; } /* check */ for (int i = 0; i < NPAGES; i++) { assert(buf[i * PAGE_SIZE_4K] == i); } } static void pt_test( void ) { /* need a decent sized stack */ char buf1[NPAGES * PAGE_SIZE_4K], *buf2 = NULL; /* check the stack is above phys mem */ assert((void *) buf1 > (void *) TEST_ADDRESS); /* stack test */ do_pt_test(buf1); printf("Stack Okay\n"); /* heap test */ buf2 = malloc(NPAGES * PAGE_SIZE_4K); assert(buf2); do_pt_test(buf2); printf("Heap Okay\n"); free(buf2); } int main(void){ do { printf("task:\tHello world, I'm\ttty_test!\n"); thread_block(); } while(1); return 0; } <file_sep>#ifndef _RPC_H_ #define _RPC_H_ void rpc_call(seL4_MessageInfo_t tag, seL4_Word endpoint); void rpc_call_data(seL4_MessageInfo_t tag, void *vData, size_t count, seL4_Word endpoint); void rpc_call_mr(seL4_MessageInfo_t tag, seL4_Word endpoint); #endif <file_sep>#include "sel4/types.h" #include "vm/addrspace.h" #define SOS_SYS_BRK 50 #define SOS_SYS_USLEEP 126 #define SOS_SYS_TIMESTAMP 127 int sos_sleep(int msec, seL4_CPtr reply_cap); uint32_t sos_brk(long newbreak, pageDirectory * pd, region * heap); void sos_wake(int* id, void* data); <file_sep>#ifndef _TIMER_TESTS_H_ #define _TIMER_TESTS_H_ #include <cspace/cspace.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "timer_tests.h" #define verbose 5 #include <sys/debug.h> #include <sys/panic.h> void timerCallback(uint32_t id, void* data); void timerCallback(uint32_t id, void* data); #endif <file_sep>#include "vm.h" <file_sep>#ifndef _FRAMETABLE_TESTS_H_ #define _FRAMETABLE_TESTS_H_ void ftest(); void ftest_cap(); #endif
fc6cf99c85acbb896857b04e4963ed4f5438e55f
[ "C" ]
24
C
cthsvedani/aos2016
bbd0b41030dde8e816040821d9c8a5cf376bcdf6
e62b05622e861b8d2973c7e12ffc296a1b5be867
refs/heads/master
<repo_name>mihneawalker/youtube<file_sep>/index.php <?php error_reporting(E_ALL); ini_set('display_errors', 1); class ChannelFeed { function __construct($username, $page = 1) { // $gallery = 'uploads', 'favorites', etc... $gallery = 'uploads'; $this->username=$username; $this->feedUrl=$url='http://gdata.youtube.com/feeds/api/users/'.$username.'/'.$gallery.'?start-index='.$page.'&max-results=10'; //$this->feedUrl=$url='http://gdata.youtube.com/feeds/api/users/'.$username; $this->feed=simplexml_load_file($url); } //public function getYTid() { public function getYTid($ytURL = null) { if(empty($ytURL)) { $ytURL = $this->feed->entry->link['href']; } $ytvIDlen = 11; // This is the length of YouTube's video IDs // The ID string starts after "v=", which is usually right after // "youtube.com/watch?" in the URL $idStarts = strpos($ytURL, "?v="); // In case the "v=" is NOT right after the "?" (not likely, but I like to keep my // bases covered), it will be after an "&": if($idStarts === FALSE) $idStarts = strpos($ytURL, "&v="); // If still FALSE, URL doesn't have a vid ID if($idStarts === FALSE) die("YouTube video ID not found. Please double-check your URL."); // Offset the start location to match the beginning of the ID string $idStarts +=3; // Get the ID string and return it $ytvID = substr($ytURL, $idStarts, $ytvIDlen); return $ytvID; } public function showFullFeed() { foreach($this->feed->entry as $video){ $vidarray[] = $video->link['href']; } return $vidarray; } }; $youtube = new ChannelFeed('IndalLighting'); //$youtube = new ChannelFeed('guiwargo'); $vids = $youtube->showFullFeed(); //$vidIDs = array_map($youtube->getYTid(),$vids); function debug($array) { echo '<pre>'; print_r($array); echo '</pre>'; } foreach($vids as $vid) { $id = $youtube->getYTid((string)$vid); echo ' <object style="height: 390px; width: 640px"><param name="movie" value="http://www.youtube.com/v/' . $id . '?version=3"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><embed src="http://www.youtube.com/v/' . $id . '?version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="360"></object> '; }
9e667d90263d5bbc0f0e9915134d9d219b274219
[ "PHP" ]
1
PHP
mihneawalker/youtube
5e602998ba8cf6e20b2b83e5732dc203201e3631
5b7f0261755a5b5293af9a6f814e779730483901
refs/heads/master
<file_sep>#include<stdio.h> void dfs(int position, int *num, int n, int *r, int length) { int i; if(length == 6) { for(i = 0 ; i < 5; ++i) printf("%d ", r[i]); printf("%d", r[i]); printf("\n"); return; } if(position >= n) return; r[length++] = num[position++]; dfs(position, num, n, r, length); length--; dfs(position, num, n, r, length); } int main(void) { int n; int num[49]; int r[6]; int length = 0; int flag = 0; scanf("%d", &n); while(n != 0) { int i; if(flag != 0) printf("\n"); flag++; for(i = 0; i < n; ++i) { scanf("%d", &num[i]); } length = 0; dfs(0, num, n, r, length); scanf("%d", &n); } return 0; } <file_sep>#include<stdio.h> int main(void) { int n; scanf("%d", &n); int count = 0; while(n--) { count++; if(count > 1) printf("\n"); int days; int D[18]; int i; int j; int map[2][22][22]; scanf("%d", &days); for(i = 0 ; i < 16; ++i) scanf("%d", &D[i]); for(i = 0 ; i < 20; ++i) for(j = 0 ; j < 20; ++j) { scanf("%d", &map[0][i][j]); } int sou = 0; int des = 1; while(days--) { for(i = 0; i < 20; ++i) for(j = 0; j < 20; ++j) { int sum = 0; sum += map[sou][i][j]; if(i > 0) sum += map[sou][i-1][j]; if(j > 0) sum += map[sou][i][j - 1]; if(i < 19) sum += map[sou][i + 1][j]; if(j < 19) sum += map[sou][i][j + 1]; sum = D[sum] + map[sou][i][j]; if(sum < 0) sum = 0; if(sum > 3) sum = 3; map[des][i][j] = sum; } int tmp; tmp = sou; sou = des; des = tmp; } for(i = 0; i < 20; ++i) { for(j = 0; j < 20; ++j) { switch(map[sou][i][j]) { case 0: printf(".");break; case 1: printf("!");break; case 2: printf("X");break; case 3: printf("#");break; } } printf("\n"); } count++; } return 0; } <file_sep>#include<stdio.h> struct point{ int x; int y; }; struct point stack[500]; int head; int dx[]= {0,0,1,-1,1,-1,1,-1}; int dy[]= {1,-1,0,0,1,-1,-1,1}; void push(struct point p) { stack[head++] = p; } int isempty() { return head == 0; } struct point pop() { return stack[--head]; } int main(void) { int n,m,x,y; int perimeters; int map[21][21]; scanf("%d %d %d %d", &m, &n, &x, &y); while(n != 0) { int i,j; for(i = 0 ; i < m; ++i) { char s[20]; scanf("%s", s); for(j = 0; j < n; ++j) { if(s[j] == '.') map[i][j] = 0; else map[i][j] = 1; } } x--; y--; perimeters = 0; head = 0; struct point tmp; if(x >= 0 && x < m && y >= 0 && y < n && map[x][y] == 1) { tmp.x = x; tmp.y = y; map[x][y] = 2; push(tmp); } while(!isempty()) { struct point now = pop(); for(i = 0; i < 8; ++i) { int tmpx, tmpy; tmpx = now.x + dx[i]; tmpy = now.y + dy[i]; if(tmpx >= 0 && tmpx < m && tmpy >=0 && tmpy < n) { if(map[tmpx][tmpy] == 0 && i < 4) perimeters++; if(map[tmpx][tmpy] == 1) { map[tmpx][tmpy] = 2; tmp.x = tmpx; tmp.y = tmpy; push(tmp); } } else { if(i < 4) perimeters++; } } } printf("%d\n", perimeters); scanf("%d %d %d %d", &m, &n, &x, &y); } return 0; } <file_sep>#include<stdio.h> #include<string.h> struct mat{ int m; int n; }; struct mat mats[26]; struct mat stack[100]; int head; int sum; void push(struct mat m) { stack[head++] = m; } struct mat pop() { struct mat tmp; tmp.m = -2; tmp.n = -2; if(head == 0) return tmp; return stack[--head]; } int main(void) { int n; scanf("%d", &n); int i; char c[2]; int a, b; for(i = 0; i < 26; ++i) { mats[i].m = 0 ; mats[i].n = 0; } for(i = 0 ; i < n; ++i) { scanf("%s %d %d", &c, &a,&b); mats[c[0] - 'A'].m = a; mats[c[0] - 'A'].n = b; } char s[100]; int length; while(scanf("%s", s) != EOF) { int flag = 0; struct mat tmpm; head = 0; sum = 0; length = strlen(s); for(i = 0; i < length; ++i) { if(flag == 1) break; if(s[i] == '(') { tmpm.m = -1; push(tmpm); } if(s[i] <= 'Z' && s[i] >= 'A') push(mats[s[i] - 'A']); if(s[i] == ')') { tmpm = pop(); struct mat tmpm2 = pop(); while(tmpm2.m != -1) { if(tmpm2.n != tmpm.m) { flag = 1; break; } sum = sum + tmpm2.m * tmpm2.n * tmpm.n; tmpm.m = tmpm2.m; tmpm2 = pop(); } push(tmpm); } } if(flag == 1) printf("error\n"); else printf("%d\n", sum); } return 0; } <file_sep>#include<stdio.h> int flaga = 0, flagb = 0, flagab = 0; int iteration(long a, long b, int n); int main(void) { long a, b; while(scanf("%d%d", &a, &b) != EOF) { if(a < b) { long tmp = a; a = b; b = tmp; } flagab = 0; flagb = 0; flaga = 0; iteration(a, b, 2); if(flagab || (!flagb && flaga)) printf("%d\n", a); else printf("%d\n", b); } return 0; } int iteration(long a, long b, int n) { if(a == 1) { flaga = 1; } if(b == 1) { flagb = 1; } if(a == 1 && b == 1) { flagab = 1; return 1; } if(n > 100) return 0; while(a % n != 0 && b % n != 0 && n <= 100) ++n; if(n > 100) return 0; if(a % n == 0) { if(iteration(a / n, b, n + 1)) return 1; } if(b % n == 0) { if(iteration(a, b / n, n + 1)) return 1; } if(iteration(a, b, n + 1)) return 1; return 0; } <file_sep>#include<stdio.h> #include<string.h> int main(void) { int n; scanf("%d", &n); int i; for(i = 0 ; i < n; ++i) { if(i > 0) printf("\n"); int m; int j; char s[200]; char *ps, *pe; scanf("%d", &m); fgets(s, 199, stdin); for(j = 0; j < m; ++j) { fgets(s, 199, stdin); ps = s; pe = s; while(*ps != '\0' && *ps != '\n') { pe = ps; while(*pe!= ' ' && *pe != '\0' && *pe != '\n') pe++; char *tmp; tmp = pe - 1; while(tmp >= ps) { putchar(*tmp); tmp--; } ps = pe; if(*ps == ' ') { putchar(' '); ps++; } } printf("\n"); } } return 0; } <file_sep>#include<stdio.h> #define bool int #define true 1 #define false 0 #define position(x, y) ((x)*((b) + 1) + (y)) void iteration(int ina, int inb, bool *map, int* road, int pr, int* bestroad); int a; int b; int N; int min = 1000*1000; void print_best(int * bestroad) { int i; for(i = 0; i < min; ++i) { switch(bestroad[i]) { case 0: printf("fill A\n");break; case 1: printf("fill B\n");break; case 2: printf("empty A\n");break; case 3: printf("empty B\n"); break; case 4: printf("pour A B\n"); break; case 5: printf("pour B A\n"); break; } } printf("success\n"); } int main(void) { int i; int j; while(scanf("%d%d%d", &a, &b, &N) != EOF) { bool map[(a+1)* (b+1)]; int road[(a+1)* (b+1)]; int pr = 0; int bestroad[(a+1)*(b+1)]; min = 1000*1000; for(i = 0; i <= a; ++i) for(j = 0; j <= b; ++j) map[position(i,j)] = false; iteration(0,0,map, road, pr, bestroad); print_best(bestroad); } return 0; } void iteration(int ina, int inb, bool *map, int* road, int pr, int* bestroad) { int i; if(inb == N) { if(pr < min) { min = pr; for(i = 0; i < min; ++i) bestroad[i] = road[i]; } return; } if(map[position(ina,inb)]) return; map[position(ina,inb)] = true; for(i = 0; i < 6; ++i) { switch(i) { case 0: road[pr++] = 0; iteration(a, inb, map,road,pr,bestroad); pr--; break; case 1: road[pr++] = 1; iteration(ina, b, map,road,pr,bestroad); pr--; break; case 2: road[pr++] = 2; iteration(0, inb, map, road, pr, bestroad); pr--; break; case 3: road[pr++] = 3; iteration(ina, 0, map,road, pr, bestroad); pr--; break; case 4: road[pr++] = 4; if(ina + inb < b) { iteration(0, ina + inb, map, road, pr, bestroad); } else { iteration(ina + inb - b, b, map, road, pr, bestroad); } pr--; break; case 5: road[pr++] = 5; if(ina + inb < a) { iteration(ina + inb, 0, map, road,pr,bestroad); } else { iteration(a, ina + inb -a, map,road,pr,bestroad); } pr--; } } map[position(ina,inb)] = false; } <file_sep>#include<stdio.h> void change(int *p, int *w, int n) { int parenthese[43]; int num_l; int i,pp = 0; i = 0; num_l = 0; for(pp = 0; pp < n; ++pp) { while(num_l < p[pp]) { parenthese[i++] = 1; num_l++; } parenthese[i++] = 2; } i = 0; for(pp = 0; pp < 2 * n; ++pp) { if(parenthese[pp] == 2) { int pr = 1; int re = 1; int j = pp - 1; while(pr > 0) { if(parenthese[j] == 2) { pr++; re++; } if(parenthese[j] == 1) pr--; j--; } w[i++] = re; } } } int main(void) { int l; int P[21]; int W[21]; scanf("%d", &l); int i; for(i = 0; i < l; ++i) { int n; scanf("%d", &n); int j; for(j = 0; j < n; ++j) scanf("%d", &P[j]); change(P,W,n); for(j = 0; j < n - 1; ++j) { printf("%d ", W[j]); } printf("%d\n", W[j]); } }<file_sep>#include<stdio.h> int gcd(int a, int b) { int c; while(b > 0) { c = a % b; a = b; b =c; } return a; } int main(void) { int n; scanf("%d", &n); int i; int num; int wheel[21]; for(i = 0; i < n; ++i) { scanf("%d", &num); int j; for(j = 0; j < num; ++j) scanf("%d", &a[j]); int rnum; scanf("%d", &rnum); if(i > 0) printf("\n"); printf("Scenario #%d:\n", i + 1); int k; for(k = 0; k <= rnum; ++k) { int a,b; scanf("%d %d", &a, &b); if(dfs(a,b,)) } } return 0; }<file_sep>#include<stdio.h> #include<string.h> int x_seq[64]; int y_seq[64]; int length; int map[8][8]; const x_step[8] = {1,-1,2,-2,-1,1,2,-2}; const y_step[8] = {2,-2,1,-1,2,-2,-1,1}; int bfs(int x1, int y1, int x2, int y2) { int tmpx, tmpy; int p; map[x1][y1] = 1; x_seq[length] = x1; y_seq[length] = y1; if(x1 == x2 && y1 == y2) return 1; length++; p = 0; while(p < length) { tmpx = x_seq[p]; tmpy = y_seq[p]; p++; int nx,ny; int i, j; for(i = 0; i < 8; ++i) { nx = tmpx + x_step[i]; ny = tmpy + y_step[i]; if(nx >= 0 && nx < 8 && ny >= 0 && ny < 8 && map[nx][ny] == 0) { x_seq[length] = nx; y_seq[length] = ny; length++; map[nx][ny] = map[tmpx][tmpy] + 1; if(nx == x2 && ny == y2) return map[nx][ny]; } } } } int main(void) { char s1[5]; char s2[5]; while(scanf("%s", &s1) != EOF) { int x1, y1, x2, y2; x1 = s1[0] - 'a'; y1 = s1[1] - '1'; scanf("%s2", &s2); x2 = s2[0] - 'a'; y2 = s2[1] - '1'; length = 0; int i,j; for(i = 0; i < 8; ++i) for(j = 0; j < 8; ++j) map[i][j] = 0; int n_move = bfs(x1,y1,x2,y2); printf("To get from %s to %s takes %d knight moves.\n", s1, s2, n_move - 1); } return 0; } <file_sep>#include<stdio.h> #include<string.h> int length; int k; void str2num(char* s, int* cip) { int i; for(i = 0 ; i < length; i++) { if(s[i] == '.') cip[i] = 27; if(s[i] == '_') cip[i] = 0; if(s[i] <= 'z' && s[i] >= 'a') cip[i] = s[i] - 'a' + 1; } } void cipher2plain(int* cipher, int* plain) { int i; for(i = 0; i < length; i++) { plain[(i*k)%length] = (cipher[i] + i) % 28; } } void num2str(int *plain, char* s) { int i; for(i = 0; i < length; i++) { if(plain[i] == 0) s[i] = '_'; if(plain[i] == 27) s[i] = '.'; if(plain[i] >= 1 && plain[i] <= 26) s[i] = 'a' + plain[i] -1; } s[length] = '\0'; } int mmod(int a, int b) { a = a % b; if(a < 0) a = a + b; return a; } int main(void) { char s[71]; int ciphercode[71]; int plaincode[71]; char result[71]; scanf("%d", &k); while(k != 0) { scanf("%s", s); length = strlen(s); int i; str2num(s, ciphercode); cipher2plain(ciphercode, plaincode); num2str(plaincode, result); printf("%s\n", result); scanf("%d", &k); } return 0; } <file_sep>import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) { int count = 1; Scanner in = new Scanner(System.in); int n; n = in.nextInt(); while(n!=0) { HashMap<String, Integer> name = new HashMap<String, Integer>(); int i; for(i = 0; i < n; ++i) { String s = new String(); s = in.next(); name.put(s, i); } int m; m = in.nextInt(); double[][] map = new double[n][n]; for(i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) map[i][j] = 0.0; map[i][i] = 1.0; } for(i = 0; i < m; ++i) { String s1 = new String(); String s2 = new String(); double rate; s1 = in.next(); rate = in.nextDouble(); s2 = in.next(); map[name.get(s1)][name.get(s2)] = rate; } for(int k = 0; k < n; ++k) for(i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { double tmp = map[i][k] * map[k][j]; if(tmp > map[i][j]) map[i][j] = tmp; } } System.out.print("Case " + count + ": "); for(i = 0; i < n; ++i) if(map[i][i] > 1.0) { System.out.println("Yes"); break; } if(i == n) System.out.println("No"); count++; n = in.nextInt(); } } } <file_sep>#include<stdio.h> struct node{ int up; int down; int left; int right; int num; }; int n; struct node mats[30]; int len; int map[6][6]; void put_mats(int up, int right, int down, int left) { int i; for(i = 0 ; i < len; ++i) { if(mats[i].right == right && mats[i].left == left && mats[i].down == down && mats[i].up == up) { mats[i].num++; break; } } if(i >= len) { mats[len].right = right; mats[len].left = left; mats[len].up = up; mats[len].down = down; mats[len].num = 1; len++; } } int check(struct node p, int i , int j) { if(i > 0) if(p.up != mats[map[i-1][j]].down) return 0; if(j > 0) if(p.left != mats[map[i][j - 1]].right) return 0; return 1; } int dfs(int i, int j) { if(i >= n) return 1; int k; for(k = 0 ; k < len; ++k) { if(mats[k].num > 0 && check(mats[k], i, j)) { map[i][j] = k; mats[k].num--; if(dfs(i + (j + 1) / n, (j + 1) % n)) return 1; mats[k].num++; } } return 0; } int main(void) { int i; int flag =0; scanf("%d", &n); while(n != 0) { len = 0; for(i = 0 ; i < n * n; ++i) { int up, down, right, left; scanf("%d %d %d %d", &up, &right, &down, &left); put_mats(up, right, down, left); } if(flag > 0) printf("\n"); printf("Game %d: ", flag + 1); if(dfs(0,0)) printf("Possible\n"); else printf("Impossible\n"); scanf("%d", &n); flag++; } return 0; } <file_sep>#include<stdio.h> void printhumble(int n, long hnum) { printf("The %d", n); if(n % 10 == 1 && (n % 100 <10 || n % 100 > 20)) printf("st"); else if(n % 10 == 2 && (n % 100 < 10 || n % 100 >20)) printf("nd"); else if(n % 10 == 3 && (n % 100 < 10 || n % 100> 20)) printf("rd"); else printf("th"); printf(" humble number is %ld.\n", hnum); } int main(void) { long humblenumbers[5843]; int num = 1; humblenumbers[1] = 1; int p2 = 1, p3 = 1, p5 = 1, p7 = 1; int n; long min; int pd; scanf("%d", &n); while(n != 0) { while(num < n) { min = 2 * humblenumbers[p2]; pd = 2; if(min > 3 * humblenumbers[p3]) { pd = 3; min = 3 * humblenumbers[p3]; } if(min > 5 * humblenumbers[p5]) { pd = 5; min = 5 * humblenumbers[p5]; } if(min > 7 * humblenumbers[p7]) { pd = 7; min = 7 * humblenumbers[p7]; } if(min > humblenumbers[num]) humblenumbers[++num] = min; switch(pd) { case 2: ++p2;break; case 3: ++p3;break; case 5: ++p5;break; case 7: ++p7;break; } } if(n <= num) printhumble(n, humblenumbers[n]); scanf("%d", &n); } return 0; } <file_sep>#include<stdio.h> #include<math.h> int main(void) { double a, b, c; int count = 1; scanf("%lf %lf %lf", &a, &b, &c); while(a!=0 || b!=0 || c != 0) { printf("Triangle #%d\n", count); if(a == -1) { if(c <= b) printf("Impossible.\n"); else printf("a = %.3lf\n", sqrt(c * c - b * b)); } if(b == -1) { if(c <= a) printf("Impossible.\n"); else printf("b = %.3lf\n", sqrt(c * c - a * a)); } if(c == -1) { printf("c = %.3lf\n", sqrt(a * a + b * b)); } count++; printf("\n"); scanf("%lf %lf %lf", &a, &b, &c); } return 0; } <file_sep>#include<stdio.h> #include<math.h> #define PI 3.1415926554 int main(void) { int n; scanf("%d", &n); int i; for(i = 0; i < n; ++i) { double x, y; scanf("%lf %lf", &x, &y); double r2 = x * x + y * y; double k = PI * r2 / 100; k = ceil(k); printf("Property %d: This property will begin eroding in year %.0lf.\n", i + 1, k); } printf("END OF OUTPUT.\n"); return 0; } <file_sep>#include<stdio.h> int main(void) { int n = 12; int i; double sum = 0; double money; for(i = 0; i < n; ++i) { scanf("%lf", &money); sum += money; } printf("$%.2lf\n", sum / 12.0); return 0; } <file_sep>#include<stdio.h> #include<stdlib.h> #include<math.h> double absl(double a) { return (a > 0)?a : -a; } int main(void) { double precision = 0.5e-12; double data[2001]; data[1000] = 1; data[2000] = 0.75; int i; double num; for(i = 0 ; i < 2001; ++i) { double x = i / 1000.0; if(i == 1000) continue; num = round(absl((1-x)*(2-x)) / 3.0 / precision); num = pow(num, 1.0/3.0) + 10; int j; double sum = data[1000] + (x - 1) * (data[2000] - data[1000]); for(j = 1; j <= num; j++) sum = sum + (1-x)*(2-x) / j/(j+1)/(j+2)/(j+x); data[i] = sum; } for(i = 0; i < 2001; ++i) { printf("%5.3f %16.12f\n", i / 1000.0, data[i]); } return 0; } <file_sep>#include<stdio.h> main() { unsigned long a,b,c,multi; int i,flag; while(scanf("%d%d",&a,&b)!=EOF) { flag=0; if(b>a) { c=b; b=a; a=c; } c=0; i=100; multi=a; while(i>1) { if(multi%i==0) { multi=multi/i; } i=i-1; } if(multi==1) { c=a; flag++; } i=100; multi=b; while(i>1) { if(multi%i==0) { multi=multi/i; } i=i-1; } if(multi==1) { c=b; flag++; } multi=a*b; i=100; while(i>1) { if(multi%i==0) { multi=multi/i; } i=i-1; } if(multi==1&&flag==2) { c=a; } printf("%d\n",c); } return 0; } //155 = 5 * 31 //195 = 5 * 39<file_sep>#include<stdio.h> int map[1001][1001]; int min[1001][1001]; int main(void) { int n,m; scanf("%d %d", &n, &m); while(n != 0 || m != 0) { int x, y; int i,j,k; for(i = 0; i < n; ++i) for( j = 0; j < n; ++j) { map[i][j] = 2000; min[i][j] = 2000; } for(i = 0 ; i < m; ++i) { scanf("%d %d", &x, &y); x--; y--; map[x][y] = 1; map[y][x] = 1; } int tmp; for(k = 0; k < n; ++k) for(i = 0; i < n; ++i) for(j = 0; j < n; ++j) { if(i != j && j != k && i != k) { tmp = map[i][k] + map[k][j]; if(tmp < min[i][j]) { min[i][j] = tmp; min[j][i] = tmp; } else { tmp = min[i][k] + min[k][j]; if(tmp < min[i][j]) { min[i][j] = tmp; min[j][i] = tmp; } } } } int flag = 0; for(i = 0; i < n; ++i) { for(j = 0; j < n; ++j) { if(map[i][j] == 1 && min[i][j] != 2) { flag = 1; break; } } if(flag) break; } if(flag) printf("Imperfect\n\n"); else printf("Perfect\n\n"); scanf("%d %d", &n, &m); } return 0; } <file_sep>#include<stdio.h> struct exon{ int start; int end; int length; int previous; int index; }; void sort(struct exon *exons, int n) { int i; int j; for(i = 1 ; i <= n; ++i) for( j = i + 1; j <= n; ++j) { if(exons[i].start > exons[j].start || (exons[i].start == exons[j].start && exons[i].end > exons[j].end)) { struct exon tmp; tmp = exons[i]; exons[i] = exons[j]; exons[j] = tmp; } } } int main(void) { int n; struct exon exons[1005]; scanf("%d", &n); while(n) { int i; int j; exons[0].start = -1; exons[0].end = -1; exons[0].previous = 0; exons[0].length = 0; for(i = 1; i <= n; ++i) { scanf("%d %d", &(exons[i].start), &(exons[i].end)); exons[i].previous = 0; exons[i].length = 1; exons[i].index = i; } sort(exons, n); for(i = 1; i <= n; ++i) for(j = 0; j < i; ++j) { if(exons[i].start > exons[j].end && 1 + exons[j].length > exons[i].length) { exons[i].length = 1 + exons[j].length; exons[i].previous = j; } } int max = 0; int maxp; int step_n = 0; int step[1005]; for(i = 1; i <= n; ++i) { if(exons[i].length > max) { max = exons[i].length; maxp = i; } } while(maxp != 0) { step[step_n++] = exons[maxp].index; maxp = exons[maxp].previous; } for(i = step_n - 1; i > 0; --i) printf("%d ", step[i]); printf("%d", step[i]); printf("\n"); scanf("%d", &n); } return 0; } <file_sep>#include<stdio.h> int main(void) { int i; for(i = 1; i < 5001; ++i) printf("%d %d ", 1, i); }<file_sep>#include<stdio.h> int map[100][100]; int get(int i, int j) { if(i < 0 || j < 0) return 0; else return map[i][j]; } int count(int i, int j) { int tmp; tmp = get(i - 1, j) + get(i , j - 1) + get(i, j) - get(i-1, j-1); return tmp; } int main(void) { int n; scanf("%d", &n); int i; int j; for(i = 0; i < n; ++i) { for(j = 0; j < n; ++j) { scanf("%d", &map[i][j]); } } for(i = 0; i < n; ++i) for(j = 0; j < n; ++j) { map[i][j] = count(i,j); } int max = 0; int k; int l; for(i = 0; i < n; ++i) for(j = 0 ; j < n; ++j) for(k = 0 ; k < i; ++k) for(l = 0; l < j; ++l) { int tmp = get(i,j) - get(k-1, j) - get(i, l - 1) + get(k - 1, l - 1); if(tmp > max) max = tmp; } printf("%d\n", max); return 0; } <file_sep>#include<stdio.h> #include<math.h> void swap(int *a, int* b) { int c; c = *a; *a = *b; *b = c; } int main(void) { int l; scanf("%d", &l); int i; for(i = 0; i < l; ++i) { int m,n; double result; scanf("%d %d", &m, &n); if(n % 2 == 0) swap(&m,&n); if(m % 2 == 0) result = (m - 2) * (n - 2) + 2 * (n - 1) + 2 * (m - 1); else result = (m - 3) * (n - 2) + n - 2 + 2 * (m - 1) + 2 * (n - 1) -1 + sqrt(2); printf("Scenario #%d:\n%.2lf\n\n", i + 1, result); } return 0; } <file_sep>#include<stdio.h> #include<string.h> char source[100]; int ps; char destination[100]; int pd; char stack[100]; int shead; char result[100]; int pr; int length; void push(int c) { stack[shead++] = c; } int pop() { if(shead == 0) return -1; else return stack[--shead]; } int isempty() { return shead == 0; } void print_result() { int i; for(i = 0 ; i < pr; ++i) printf("%c ", result[i]); printf("\n"); } void dfs() { if(ps == length) { int pd_b = pd; int ps_b = ps; int pr_b = pr; int shead_b = shead; while(pd < length && pop()== destination[pd]) { pd++; result[pr++] = 'o'; } if(pd == length && shead == 0) { print_result(); } pd = pd_b; ps = ps_b; pr = pr_b; shead = shead_b; return; } push(source[ps++]); result[pr++] = 'i'; dfs(); pop(); ps--; pr--; int tmp = pop(); if(tmp != -1) { if(tmp == destination[pd]) { pd++; result[pr++] = 'o'; dfs(); pr--; pd--; } push(tmp); } } int main(void) { while(scanf("%s %s", source, destination) != EOF) { ps = 0; pd = 0; pr = 0; length = strlen(source); int length2 = strlen(destination); printf("[\n"); if(length == length2) dfs(); printf("]\n"); } return 0; } <file_sep>#include<stdio.h> struct point{ double x; double y; }; double line_point(struct point point1, struct point point2, struct point point3) { double tmp = ((point3.y-point1.y)*(point1.x-point2.x) - (point1.y-point2.y)*(point3.x-point1.x)); if(tmp < 1e-5 && tmp > -1e-5) tmp = 0; return tmp; } int iscross(struct point point1, struct point point2, struct point point3, struct point point4) { if(line_point(point1, point2, point3)* line_point(point1, point2, point4) < 0 && line_point(point3, point4, point1)* line_point(point3, point4, point2) < 0) return 1; if(line_point(point1, point2, point3) == 0 && line_point(point1, point2, point4) == 0 && line_point(point3, point4, point1) == 0 && line_point(point3, point4, point2) == 0) return 2; if(line_point(point1, point2, point3)* line_point(point1, point2, point4) == 0 || line_point(point3, point4, point1)* line_point(point3, point4, point2) == 0) return 1; return 0; } int check(struct point* points, int n) { if(n < 3) return 0; int i; int j; for(i = 0 ; i < n; ++i) { for(j = i + 1; j < n; ++j) { int flag; if(j - i == 1 && (j + 1)% n == i) flag = 1; else flag = 0; if(flag) } } return 1; } double caculate_tri(struct point point2, struct point point3) { return (point2.x*point3.y-point2.y*point3.x) / 2.0; } double caculate_area(struct point* points, int n) { double area = 0.0; int i; for(i = 0; i < n; ++i) { area += caculate_tri(points[i], points[(i + 1) % n]); } return area>=0?area:-area; } int main(void) { int n; int flag; double area; int count = 1; struct point points[1001]; scanf("%d", &n); while(n != 0) { int i; for(i = 0 ; i < n; ++i) { scanf("%lf %lf", &(points[i].x), &(points[i].y)); } flag = 0; if(count > 1) printf("\n"); if(check(points, n)) area = caculate_area(points, n); else flag = 1; if(flag) printf("Figure %d: Impossible\n", count); else printf("Figure %d: %.2lf\n", count, area); count++; scanf("%d", &n); } return 0; } <file_sep>#include<stdio.h> int l[5000]; int w[5000]; int n; void swap(int *a, int* b, int* d, int* e) { int c; c = *a; *a = *b; *b = c; c = *d; *d = *e; *e = c; } void badsort(int *a, int *d, int start, int end) { int i,j; for(i = start; i < end; ++i) for(j = i; j < end; ++j) { if(a[i] > a[j] || (a[i] == a[j] && d[i] > d[j])) { swap(&a[i],&a[j],&d[i],&d[j]); } } } /* void sort(int* a, int *d,int start, int end) { if(end - start < 10) { badsort(a, d, start, end); return; } int middle = (start + end) / 2; int w1 = a[start]; int w2 = a[middle]; int w3 = a[end - 1]; int l1 = d[start]; int l2 = d[middle]; int l3 = d[end - 1]; if(w1 > w2 || (w1 == w2 && l1 > l2) ) swap(&w1, &w2, &l1, &l2); if(w2 > w3 || (w2 == w3 && l2 > l3) ) swap(&w2, &w3, &l2, &l3); if(w1 > w2 || (w1 == w2 && l1 > l2) ) swap(&w1, &w2, &l1, &l2); a[start] = w1; d[start] = l1; a[end - 1] = w3; d[end - 1] = l3; if(end -start == 2) return; a[middle] = a[start + 1]; d[middle] = d[start + 1]; int p1 = start + 1; int p2 = end - 2; while(p1 < p2) { while(a[p2] > w2 && p1 < p2) p2--; a[p1] = a[p2]; d[p1] = d[p2]; while(a[p1] < w2 && p1 < p2) p1++; a[p2] = a[p1]; d[p2] = d[p1]; } a[p1] = w2; d[p1] = l2; int i; for(i = 0; i < n; ++i) printf("%d ", a[i]); printf("\n"); sort(a,d,start,p1); sort(a,d,p1 + 1, end); }*/ int count(int *a, int n) { int max = 0; int now_max = 0; int maxs[5000]; int i; int j; for(i = 0; i < n; ++i) { now_max = 0; maxs[i] =0; for(j = 0; j <= i; ++j) if(a[j] > a[i] && now_max < maxs[j] + 1) now_max = maxs[j] + 1; maxs[i] = now_max; if(now_max > max) max = now_max; } return max + 1; } int main(void) { int k; scanf("%d", &k); int i; for(i = 0 ; i < k; ++i) { scanf("%d", &n); int j; for(j = 0; j < n; ++j) { scanf("%d %d", &l[j], &w[j]); } badsort(l, w,0, n); /*for(j = 0; j < n; ++j) { printf("%d ", l[j]); } printf("\n"); for(j = 0; j < n; ++j) { printf("%d ", w[j]); } printf("\n");*/ int num = count(w, n); printf("%d\n", num); } return 0; } <file_sep>#include<stdio.h> #include<string.h> #include<ctype.h> #include<stdlib.h> char buff[100]; int buff_size = 0; void print_buff() { int i; for(i = 0; i < buff_size; ++i) { printf("%c", buff[i]); } printf("\n"); buff_size = 0; } void print_() { int i; for(i = 0; i < 80; ++i) printf("-"); printf("\n"); } void dobuff(char *ps, char *pe, int num) { switch(num) { case 2: print_buff(); buff_size = 0; break; case 3: if(buff_size != 0) { print_buff(); buff_size = 0; } print_(); break; case 1: if(buff_size == 0) { if(pe - ps + buff_size > 80) { print_buff(); buff_size = 0; } while(ps != pe) { buff[buff_size++] = *ps; ps++; } } else { if(pe - ps + buff_size + 1 > 80) { print_buff(); buff_size = 0; } else buff[buff_size++] = ' '; while(ps != pe) { buff[buff_size++] = *ps; ps++; } } break; } } int main(void) { char s[100]; char *ps, *pe; while(fgets(s, 99, stdin) != NULL) { ps = s; pe = s; while(*ps != '\0') { while(*ps != '\0' && isspace(*ps)) { ++ps; ++pe; } if(*ps == '\0') break; if(*ps == '<') { if(*(++ps) == 'b') dobuff(ps,pe,2); else dobuff(ps,pe,3); ps = ps + 3; pe = pe + 4; } else { while(*pe != '\0' && !isspace(*pe)) pe++; dobuff(ps, pe, 1); } ps = pe; } } int i; for(i = 0; i < buff_size; ++i) printf("%c", buff[i]); return 0; } <file_sep>#include<stdio.h> struct box{ int a; int b; int c; }; struct box boxs[100]; int len; void swap(int* a, int *b) { int c = *a; *a = *b; *b = c; } void put_boxs(int a, int b, int c) { if(a < b) swap(&a, &b); if(b < c) swap(&b, &c); if(a < b) swap(&a, &b); boxs[len].a = a; boxs[len].b = b; boxs[len].c = c; len++; boxs[len].a = b; boxs[len].b = c; boxs[len].c = a; len++; boxs[len].a = a; boxs[len].b = c; boxs[len].c = b; len++; } int main(void) { int n,i,j,k,max,flag; int map[100][100]; flag = 1; scanf("%d", &n); while(n != 0) { len = 0; max = 0; boxs[len].a = 1000000; boxs[len].b = 1000000; boxs[len].c = 0; len++; for(i = 0 ; i < n; ++i) { int a, b, c; scanf("%d %d %d", &a, &b, &c); put_boxs(a,b,c); } for(i = 0; i < len; ++i) for(j = 0; j < len; ++j) map[i][j] = 0; for(i = 0; i < len; ++i) for(j = 0; j < len; ++j) { if(boxs[i].a > boxs[j].a && boxs[i].b > boxs[j].b) { map[i][j] = boxs[j].c; if(boxs[j].c > max) max = boxs[j].c; } } for(k = 0; k < len; ++k) for(i = 0 ; i < len; ++i) for(j = 0; j < len; ++j) { if(map[i][k] > 0 && map[k][j] > 0) { int tmp = map[i][k] + map[k][j]; if(tmp > map[i][j]) map[i][j] = tmp; if(tmp > max) max = tmp; } } printf("Case %d: maximum height = %d\n", flag, max); scanf("%d", &n); flag++; } return 0; } <file_sep>#include<stdio.h> #include<string.h> void print_num(int * a, int n) { int i; for(i = n - 1; i >= 0; --i) printf("%d", a[i]); } void multi(int *a, int m, int *b, int n) { int i; for(i = 0 ; i < n; ++i) b[i] = 0; int c = 0; for(i = 0; i < n; ++i) { c = a[i] * m + c; b[i] = c % 10; c = c / 10; } if(c > 0) b[0] = -1; } int check(int *a, int *b, int n) { int i; int as, an, bs, bn; for(i = 0 ; i < n; ++i) { as = 0; an = 0; bs = i; bn = 0; while(an <n && bn < n && a[(as + an) % n] == b[(bs + bn) % n]) { an++; bn++; } if(an == n) return 1; } return 0; } int main(void) { char s[62]; int a[62]; int b[62]; while(scanf("%s", s) != EOF) { int i; int n = strlen(s); for(i = 0 ; i < n; ++i) a[n - i - 1] = s[i] - '0'; for(i = 2; i <= n; ++i) { multi(a, i, b, n); if(b[0] == -1 || !check(a, b, n)) break; } print_num(a,n); if(i != n+1) printf(" is not cyclic\n"); else printf(" is cyclic\n"); } return 0; } <file_sep>#include<stdio.h> int main(void) { double hangover; double hangs[20000]; hangs[1] = 0.5; long n = 1; scanf("%lf", &hangover); while(hangover > 0.0001) { int i = 1; while(hangover > hangs[i]) { if(i >= n) { hangs[i + 1] = hangs[i] + 1.0 / (i + 2); n++; } i++; } printf("%d card(s)\n", i); scanf("%lf", &hangover); } return 0; } <file_sep>#include<stdio.h> int main(void) { int n; printf("# Cards Overhang\n"); while(scanf("%d", &n) !=EOF) { double result = 0; int i; for(i = 1; i <=n; ++i) result += 1.0 / 2.0 / i; printf("%5d %.3lf\n", n, result); } return 0; } <file_sep>#include<stdio.h> #define PI 3.141592653589793 int main(void) { double x1, x2, x3, y1, y2, y3; while(scanf("%lf %lf %lf %lf %lf %lf", &x1, &y1, &x2, &y2, &x3, &y3) != EOF) { double a,b,c; double vx1,vy1,vx2,vy2,vx3,vy3; vx1 = x1 - x2; vy1 = y1 - y2; vx2 = x2 - x3; vy2 = y2 - y3; vx3 = x3 - x1; vy3 = y3 - y1; a = sqrt(vx1*vx1 + vy1*vy1); b = sqrt(vx2*vx2 + vy2*vy2); c = sqrt(vx3*vx3 + vy3*vy3); double ctheta = (vx1 * -vx3 + vy1 * -vy3) / a/c; double stheta = sqrt(1 - ctheta * ctheta); double s = a * c * stheta / 2; double r = a*b*c / s/4; printf("%.2lf\n", 2*PI*r); } return 0; } <file_sep>#include <iostream> #include <vector> #include <stack> #include <string> using namespace std; string s1,s2; stack<char> cs; vector<char> io; int l;//当前案例,字符串的长度 void Prints() { for(int i=0;i<io.size();i++) cout<<io[i]<<" "; cout<<endl; } //in表示入栈数量,out表示出栈数量 void dfs(int in,int out) { char t; if( in==l && out==l )//如果入栈和出栈数量都等于字符串长度,则表示已得到一个成功解 { Prints(); return; } if( in<l ) { cs.push(s1[in]); io.push_back('i'); dfs(in+1,out); cs.pop(); io.pop_back(); } if( out<in && out <l && cs.top()==s2[out] ) { t = cs.top(); cs.pop(); io.push_back('o'); dfs(in,out+1); cs.push(t); io.pop_back(); } } int main() { while(cin>>s1>>s2) { l=s1.length(); cout<<"["<<endl; dfs(0,0); cout<<"]"<<endl; } return 0; }<file_sep>#include<stdio.h> #include<string.h> int map[26][26]; void print_sequence(int n) { int i, j; int seq[28]; for(i = 0 ; i < n; ++i) { int sum = 0; for(j = 0 ; j < n; ++j) { if(map[i][j] != 0) sum++; } seq[n - 1 - sum] = i + 'A'; } for(i = 0; i < n; ++i) printf("%c", seq[i]); printf(".\n"); } int main(void) { int n, m; int l1, l2; scanf("%d %d", &n, &m); while(n!= 0 || m != 0) { int i,j; int sum = 0; int flag = 0; int step = 0; char s[5]; for(i = 0; i < n; ++i) for(j = 0; j < n; ++j) map[i][j] = 0; for(i = 0; i < m; ++i) { scanf("%s", s); int x, y; x = s[0] - 'A'; y = s[2] - 'A'; if(map[y][x] != 0) { flag = 2; step = i + 1; break; } if(map[x][y] == 0) { map[x][y] = 1; sum++; int i1, i2; for(i1 = 0 ; i1 < n; ++i1) { if(map[i1][x] != 0) { if(map[y][i1] == 1) { flag = 2; step = i + 1; break; } if(map[i1][y] == 0) { sum++; map[i1][y] = 1; } } } for(i2 = 0; i2 < n; ++i2) { if(map[y][i2] != 0) { if(map[i2][x] == 1) { flag = 2; step = i + 1; break; } if(map[x][i2] == 0) { sum++; map[x][i2] = 1; } } } for(i1 = 0; i1 < n; ++i1) { for(i2 = 0; i2 < n; ++i2) { if(map[i1][x] != 0 && map[y][i2] != 0) { if(map[i2][i1] != 0) { flag = 2; step = i + 1; break; } if(map[i1][i2] == 0) { sum ++; map[i1][i2] = 1; } } } if(flag == 2) break; } } if(flag == 2) break; if(sum == n * (n - 1) / 2 && flag == 0) { flag = 1; step = i + 1; break; } /* for(l1 = 0; l1 < n; ++l1) { for(l2 = 0; l2 < n; ++l2) { printf("%d ", map[l1][l2]); } printf("\n"); }*/ } /* for(l1 = 0; l1 < n; ++l1) { for(l2 = 0; l2 < n; ++l2) { printf("%d ", map[l1][l2]); } printf("\n"); }*/ for(i = i + 1; i < m; ++i) { scanf("%s", s); } switch(flag) { case 0: printf("Sorted sequence cannot be determined.\n");break; case 1: printf("Sorted sequence determined after %d relations: ", step); print_sequence(n); break; case 2: printf("Inconsistency found after %d relations.\n", step); } scanf("%d %d", &n, &m); } return 0; } <file_sep>#include<stdio.h> int max = 0; int n; void dfs(int, int, char[4][4], int); int check(int x, int y, char map[4][4]); int main(void) { scanf("%d", &n); char map[4][4]; while(n != 0) { int i; for(i = 0; i < n; i++) scanf("%s", map[i]); max = 0; dfs(0,0,map, 0); printf("%d\n", max); scanf("%d", &n); } } void dfs(int x, int y, char map[4][4], int num) { if(x >= n) return; while(x < n && map[x][y] != '.') { y = y + 1; x = x + y / n; y = y % n; } if(x >= n) return; if(map[x][y] == '.') { if(check(x,y,map)) { map[x][y] = 'o'; num++; if(num > max) max = num; dfs(x + (y + 1) / n, (y + 1) % n, map, num); map[x][y] = '.'; num--; } dfs(x + (y + 1) / n, (y + 1) % n, map, num); } } int check(int x, int y, char map[4][4]) { return up(x,y,map) && down(x,y,map) &&right(x,y,map) &&left(x,y,map); } int up(int x, int y, char map[4][4]) { if(x == 0) return 1; x--; while(x >=0 && map[x][y] == '.') x--; if(x < 0 || map[x][y] == 'X') return 1; return 0; } int down(int x, int y, char map[4][4]) { if(x == n) return 1; x++; while(x < n && map[x][y] == '.') x++; if(x >= n || map[x][y] == 'X') return 1; return 0; } int left(int x, int y, char map[4][4]) { if(y == 0) return 1; y--; while(y >=0 && map[x][y] == '.') y--; if(y < 0 || map[x][y] == 'X') return 1; return 0; } int right(int x, int y, char map[4][4]) { if(y == n) return 1; y++; while(y <n && map[x][y] == '.') y++; if(y >= n || map[x][y] == 'X') return 1; return 0; } <file_sep>#include<stdio.h> #include<string.h> #define L 100000 int bi[3 * L]; int dec[3 * L]; int ldec; int tmpd[3 * L]; int ltmpd; int length; char s[L]; int n; void print_array(int* a, int ll) { int i; for(i = ll - 1; i >= 0; --i) printf("%d", a[i]); } void Oct2Bi() { int i; for(i = 0; i < n - 2; ++i) { int tmp = s[i + 2] - '0'; bi[i * 3] = tmp >> 2; bi[i * 3 + 1] = (tmp >> 1) & 1; bi[i * 3 + 2] = tmp & 1; } /* print_array(bi, length);*/ } int multi(int * a, int l, int m) { int c; int i; c = 0; for(i = 0 ; i < l; ++i) { c = a[i] * m + c; a[i] = c % 10; c = c / 10; } if(c > 0) { a[l++] = c; } return l; } int add(int *a, int la, int *b, int lb, int step) { int c = 0; int i; int re[L * 3]; int lre = 0; for( i = 0; i < (step - la); ++i) { re[lre++] = b[i]; } for(i = (step - la); i < lb; ++i) { c = c + b[i] + a[i - (step - la)]; re[lre++] = c % 10; c = c / 10; } for(i = lb; i < step; ++i) { c = c + a[i - (step - la)]; re[lre++] = c % 10; c = c / 10; } for(i = 0 ; i < lre; ++i) a[i] = re[i]; return lre; } int cat(int *a, int la, int *b, int lb, int step) { int c = 0; int i; int re[L * 3]; int lre = 0; for( i = 0; i < lb; ++i) { re[lre++] = b[i]; } for(i = lb; i < step- la; ++i) { re[lre++] = 0; } for(i = step - la; i < step; ++i) { re[lre++] = a[i - (step - la)]; } for(i = 0 ; i < lre; ++i) a[i] = re[i]; return lre; } void Bi2Dec() { int i; tmpd[0] = 1; ltmpd = 1; ldec = 0; for(i = 0; i < length; ++i) { ltmpd = multi(tmpd, ltmpd, 5); /* printf("tmp = "); print_array(tmpd, ltmpd);*/ if(bi[i] == 1) { if(ldec + ltmpd > i + 1) ldec = add(dec, ldec, tmpd, ltmpd, i + 1); else ldec = cat(dec, ldec, tmpd, ltmpd, i + 1); } /* printf("dec = "); print_array(dec, ldec);*/ } } int main(void) { while(scanf("%s", s) != EOF) { n = strlen(s); length = 3 * (n - 2); ldec = 0; ltmpd = 0; if(s[0] == '1') { printf("%s [8] = 1 [10]\n", s); } else { Oct2Bi(); Bi2Dec(); printf("%s [8] = 0", s); if(ldec > 0) printf("."); print_array(dec, ldec); printf(" [10]\n"); } } return 0; } <file_sep>#include<stdio.h> #include<string.h> int main(void) { int n; int count = 0; scanf("%d", &n); while(n != 0) { count++; char name[31][100]; double map[31][31]; int i; int j; for(i = 0 ; i < n; ++i) scanf("%s", name[i]); for(i = 0 ; i < n; ++i) { for(j = 0; j < n; ++j) map[i][j] = 0.0; map[i][i] = 1.0; } int m; scanf("%d", &m); for(j = 0; j < m; ++j) { char s1[100], s2[100]; double rate; scanf("%s %lf %s", s1, &rate, s2); int n1, n2; for(n1 = 0; n1 < n; ++ n1) if(strcmp(name[n1], s1) == 0) break; for(n2 = 0; n2 < n; ++n2) if(strcmp(name[n2], s2) == 0) break; map[n1][n2] = rate; } int k; for(k = 0; k < n; ++k) for(i = 0; i < n; ++i) for(j = 0; j < n; ++j) { double tmp = map[i][k] * map[k][j]; if(tmp > map[i][j]) map[i][j] = tmp; } for(i = 0; i < n; ++i) if(map[i][i] > 1.0) break; printf("Case %d: ", count); if(i < n) printf("Yes\n"); else printf("No\n"); scanf("%d", &n); } return 0; } <file_sep>#include<stdio.h> long win_p; int know[3000000]; long dele_remain(long remain, int c) { int i; for(i = 1; i <= (20 / c); ++i) { if((1 << (i*c)) > remain) break; remain = remain & ~(1 << (i * c)); } for(i = 2; i < 21; ++i) { if(remain < (1 << i)) break; if(!(remain & (1 << i))) { int j; for(j = 1; j <= (21 - i) /c; ++j) if((1 << (j * c + i)) <= remain) remain = remain & ~(1 << (j * c + i)); else break; } } /* printf("dele %d: ", c); for(i = 2; i < 21; ++i) { if(remain & (1 << i)) printf("%d ", i); } printf("\n");*/ return remain; } int win_stat(long remain) { long remain_copy; int i; if(remain == 0 || know[remain] == 2) return 0; else if(know[remain] == 1) return 1; for(i = 2; i < 21; ++i) { if((remain & (1 << i))) { remain_copy = remain; remain_copy = dele_remain(remain_copy, i); if(!win_stat(remain_copy)) { know[remain] = 1; return 1; } } } know[remain] = 2; return 0; } void iteration(long remain) { long remain_copy; int i; for(i = 2; i < 21; i++) { if(remain & (1 << i)) { remain_copy = remain; remain_copy = dele_remain(remain_copy, i); if(win_stat(remain_copy)) continue; else { win_p = win_p | (1 << i); } } } } int main(void) { int n; int i; scanf("%d", &n); for(i = 0; i < 2100000; ++i) know[i] = 0; for(i = 0; i < n; ++i) { long remain; int j; remain = 0; win_p = 0; int remain_num; scanf("%d", &remain_num); for(j = 0; j < remain_num; ++j) { int tmp; scanf("%d", &tmp); remain = remain | (1 << tmp); } iteration(remain); printf("Scenario #%d:\n", i + 1); if(win_p > 0) { printf("The winning moves are:"); for(j = 0; j < 21; ++j) if(win_p & (1 << j)) printf(" %d", j); printf(".\n\n"); } else printf("There is no winning move.\n\n"); } return 0; } <file_sep>#include<stdio.h> int main(void) { int n; int flag = 0; scanf("%d", &n); while(n != 0) { int i; int A = 0; int B = 0; int ac[20],bc[20]; for(i = 0; i < n; ++i) { scanf("%d", &ac[i]); } for(i = 0; i < n; ++i) { scanf("%d", &bc[i]); } for(i = 0; i < n; ++i) { int tmpa = ac[i]; int tmpb = bc[i]; if(tmpa > tmpb + 1) A += tmpa; else if(tmpb > tmpa + 1) B += tmpb; else if(tmpa == 1 && tmpb == 2) A += 6; else if(tmpa == 2 && tmpb == 1) B += 6; else if(tmpa == tmpb + 1) B += (tmpa + tmpb); else if(tmpb == tmpa + 1) A += (tmpa + tmpb); } if(flag > 0) printf("\n"); printf("A has %d points. B has %d points.\n", A, B); flag++; scanf("%d", &n); } return 0; } <file_sep>#include<stdio.h> struct node{ int x; int y; int pre_x; int pre_y; }; int map[51][51]; struct node snake[20]; int n; int go_snake(char c) { int i; map[snake[19].x][snake[19].y] = 0; for(i = 19; i > 0; i--) { snake[i] = snake[i - 1]; } int headx,heady; switch(c) { case 'N': headx = snake[0].x - 1; heady = snake[0].y; break; case 'S': headx = snake[0].x + 1; heady = snake[0].y; break; case 'W': headx = snake[0].x; heady = snake[0].y - 1; break; case 'E': headx = snake[0].x; heady = snake[0].y + 1; break; } if(headx > 50 || headx < 1 || heady > 50 || heady < 1) return 1; if(map[headx][heady] == 1) return 2; map[headx][heady] = 1; snake[0].x = headx; snake[0].y = heady; snake[1].pre_x = headx; snake[1].pre_y = heady; return 0; } int main(void) { scanf("%d", &n); while(n != 0) { int i, j; for(i = 1; i <= 50; ++i) for(j = 1; j <= 50; ++j) map[i][j] = 0; for(i = 0; i < 20 ; ++i) { snake[i].x = 25; snake[i].y = 30 - i; snake[i].pre_x = 25; snake[i].pre_y = 30 - i + 1; map[25][30-i] = 1; } char s[100]; int flag; scanf("%s", s); for(i = 0; i < n; ++i) { flag = go_snake(s[i]); if(flag != 0) break; } if(flag == 0) printf("The worm successfully made all %d moves.\n", n); else if(flag == 1) printf("The worm ran off the board on move %d.\n", i + 1); else if(flag == 2) printf("The worm ran into itself on move %d.\n", i + 1); scanf("%d", &n); } return 0; } <file_sep>#include<stdio.h> #include<math.h> int main(void) { int i; int R[16],G[16],B[16]; for(i = 0; i < 16; ++i) { scanf("%d %d %d", &R[i], &G[i], &B[i]); } int r, g, b; scanf("%d %d %d", &r, &g, &b); while(r != -1 || g != -1 || b != -1) { double min = 200000; int num; for(i = 0 ; i < 16; ++i) { double tmp = sqrt(pow(r - R[i], 2.0)+ pow(g - G[i], 2.0)+ pow(b - B[i], 2.0)); if(tmp < min) { min = tmp; num = i; } } printf("(%d,%d,%d) maps to (%d,%d,%d)\n", r, g, b, R[num], G[num], B[num]); scanf("%d %d %d", &r, &g, &b); } return 0; } <file_sep>import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()) { String s1 = in.next(); String s2 = in.next(); int[] result = new int[102]; int c = 0; int p1, p2; p1 = s1.length() - 1; p2 = s2.length() - 1; int count = 0; while(p1 >= 0 || p2 >= 0) { c = c + c2n(s1, p1--) + c2n(s2, p2--); result[count++] = c % 20; c = c / 20; } if(c > 0) result[count++] = c; for(int i = count - 1; i >=0; --i) System.out.print(n2c(result[i])); System.out.println(); } } public static int c2n(String s, int i) { if(i < 0) return 0; if(s.charAt(i) >= '0' && s.charAt(i) <= '9') return s.charAt(i) - '0'; else return s.charAt(i) - 'a' + 10; } public static char n2c(int n) { if(n >= 0 && n <= 9) return (char)(n +'0'); if(n >= 10 && n <= 19) return (char)('a' + n - 10); return '0'; } } <file_sep>#include<stdio.h> int main(void) { int n; int m; int map[150]; scanf("%d", &n); while(n != 0) { m = 1; while(1) { int i; for(i = 0 ; i < n; ++i) map[i] = 1; int now = 0; int exist = n; while(now != 1) { map[now] = 0; exist--; int count = 0; while(count < m) { now = (now + 1) % n; if(map[now] == 1) count++; } } if(exist == 1) break; m++; } printf("%d\n", m); scanf("%d",&n); } return 0; } <file_sep>#include<stdio.h> #include<string.h> char forwardstack[100][80]; int forwardhead; char backwardstack[100][80]; int backwardhead; char current[80]; char ins[80]; int main(void) { int n; int i; int flag; scanf("%d", &n); fgets(ins, 80, stdin); fgets(ins, 80,stdin); for(i = 0 ; i < n; ++i) { strcpy(current, "http://www.acm.org/\n"); forwardhead = 0; backwardhead = 0; fgets(ins, 80,stdin); flag = 0; if(i > 0) printf("\n"); while(ins[0] != '\n' && flag == 0) { switch(ins[0]) { case 'V': strcpy(backwardstack[backwardhead++], current); strcpy(current, ins + 6); forwardhead = 0; printf("%s", current); break; case 'B': if(backwardhead == 0) { printf("%s\n", "Ignored"); break; } strcpy(forwardstack[forwardhead++], current); strcpy(current, backwardstack[--backwardhead]); printf("%s", current); break; case 'F': if(forwardhead == 0) { printf("%s\n", "Ignored"); break; } strcpy(backwardstack[backwardhead++], current); strcpy(current, forwardstack[--forwardhead]); printf("%s", current); break; case 'Q': flag = 1; break; } fgets(ins, 80,stdin); } } return 0; } <file_sep>#include<stdio.h> #include<string.h> void str2num(char *s, int *g, int l) { int i; for(i = 1; i <= l; ++i) { switch(s[i - 1]) { case 'A':g[i] = 0;break; case 'C':g[i] = 1; break; case 'G':g[i] = 2; break; case 'T':g[i] = 3;break; } } } int main(void) { int n; int i; int map[105][105]; int score[5][5] = {{5,-1,-2,-1,-3},{-1,5,-3,-2,-4},{-2,-3,5,-2,-2},{-1,-2,-2,5,-1},{-3,-4,-2,-1,-1000}}; int g1[105]; int g2[105]; scanf("%d", &n); for(i = 0; i < n; ++i) { int l1,l2; int j,k; char s1[102]; char s2[102]; scanf("%d %s", &l1, s1); scanf("%d %s", &l2, s2); str2num(s1,g1,l1); str2num(s2,g2,l2); map[0][0] = 0; for(k = 1; k <= l2; ++k) map[0][k] = map[0][k - 1] + score[4][g2[k]]; for(j = 1; j <= l1; ++j) map[j][0] = map[j - 1][0] + score[g1[j]][4]; for(j = 1; j <= l1; ++j) for(k = 1; k <= l2; ++k) { int tmp; map[j][k] = map[j-1][k-1] + score[g1[j]][g2[k]]; tmp = map[j-1][k] + score[g1[j]][4]; if(tmp > map[j][k]) map[j][k] = tmp; tmp = map[j][k-1] + score[4][g2[k]]; if(tmp > map[j][k]) map[j][k] = tmp; } printf("%d\n", map[l1][l2]); /* for(j = 0 ; j < l1; ++j) { for(k = 0; k < l2; ++k) printf("%-3d ", map[j][k]); printf("\n"); }*/ } return 0; } <file_sep>#include<stdio.h> int check(int n, int base) { int num[20]; int length = 0; while(n > 0) { num[length++] = n % base; n = n / base; } int i; for(i = 0; i <= length / 2; ++i) if(num[i] != num[length - i - 1]) break; if(i <= length / 2) return 0; return 1; } int main(void) { int n; int flag; scanf("%d", &n); while(n != 0) { int i; flag = 0; printf("Number %d is ", n); for(i = 2; i < 17; ++i) { if(check(n, i)) { if(flag == 0) printf("palindrom in basis"); printf(" %d", i); flag++; } } if(flag == 0) printf("not a palindrom"); printf("\n"); scanf("%d", &n); } return 0; }
f3dc6fc831a0b2345441ed9f8b47b5daf0c9c752
[ "Java", "C", "C++" ]
47
C
dogeyes/zoj
23f18f2b1d575d4bbfc4c94352dd3253e91814a0
aef28795b28bae481893547953f5ec21a588816f
refs/heads/main
<repo_name>VisheshCoderBoy/Live-Clock<file_sep>/Live Clock.py from tkinter import* root = Tk() root.title("Clock") root.geometry("800x125") # W X H root.maxsize("1000","125") import datetime now = datetime.datetime.now() time = now.strftime("%H : %M : %S ") Hour= now.strftime("%H") Hour = (int(Hour)) if Hour >= 12 : Clock = Label(root,font=("ds-digital",80), bg = "black" , fg = "cyan", text = time+"PM") Clock.pack(fill = X) else: Clock = Label(root,font=("ds-digital",80), bg = "black" , fg = "cyan", text = time+"AM") Clock.pack(fill = X) root.mainloop()
242138e7389720349a6089d3dc6128c718d6f00f
[ "Python" ]
1
Python
VisheshCoderBoy/Live-Clock
a0a24d39cba5d6c3b63dd8fb5b1d464148d92872
a4553ce0b46fc7f521c6eb350a2e4a13f2251122
refs/heads/master
<file_sep>class CreateStudents < ActiveRecord::Migration def change create_table :students do |t| t.string :first_name t.string :last_name t.timestamps null: false end end end
b26f95dfa3bd134681f609b604ae66862b6e98b9
[ "Ruby" ]
1
Ruby
Connieh1/rails-activerecord-model-rails-lab-v-000
fb99a47ed18dfa85123611dcd16ca96b33a6d157
676e600c1523895f7855b71a4e2791673ad6dc6b
refs/heads/master
<repo_name>jonfriese/Family<file_sep>/README.md # Family App ###### This app was created to show the differences between using the 'Ancestry' gem and nesting resources the traditional way in Rails. <file_sep>/app/models/father.rb class Father < ActiveRecord::Base attr_accessible :name has_many :sons end <file_sep>/test/unit/helpers/fathers_helper_test.rb require 'test_helper' class FathersHelperTest < ActionView::TestCase end <file_sep>/app/controllers/fathers_controller.rb class FathersController < ApplicationController # GET /fathers # GET /fathers.json def index @fathers = Father.all respond_to do |format| format.html # index.html.erb format.json { render json: @fathers } end end # GET /fathers/1 # GET /fathers/1.json def show @father = Father.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @father } end end # GET /fathers/new # GET /fathers/new.json def new @father = Father.new respond_to do |format| format.html # new.html.erb format.json { render json: @father } end end # GET /fathers/1/edit def edit @father = Father.find(params[:id]) end # POST /fathers # POST /fathers.json def create @father = Father.new(params[:father]) respond_to do |format| if @father.save format.html { redirect_to @father, notice: 'Father was successfully created.' } format.json { render json: @father, status: :created, location: @father } else format.html { render action: "new" } format.json { render json: @father.errors, status: :unprocessable_entity } end end end # PUT /fathers/1 # PUT /fathers/1.json def update @father = Father.find(params[:id]) respond_to do |format| if @father.update_attributes(params[:father]) format.html { redirect_to @father, notice: 'Father was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @father.errors, status: :unprocessable_entity } end end end # DELETE /fathers/1 # DELETE /fathers/1.json def destroy @father = Father.find(params[:id]) @father.destroy respond_to do |format| format.html { redirect_to fathers_url } format.json { head :no_content } end end end <file_sep>/app/models/son.rb class Son < ActiveRecord::Base attr_accessible :father_id, :name belongs_to :father end <file_sep>/app/controllers/sons_controller.rb class SonsController < ApplicationController before_filter :load_father # GET /sons # GET /sons.json def index @son = @father.sons.all respond_to do |format| format.html # index.html.erb format.json { render json: @sons } end end # GET /sons/1 # GET /sons/1.json def show @son = @father.sons.find(params[:id]) end # GET /sons/new # GET /sons/new.json def new @son = @father.sons.new end # GET /sons/1/edit def edit @son = @father.sons.find(params[:id]) end # POST /sons # POST /sons.json def create @son = @father.sons.new(params[:son]) @son.father_id = @father.id respond_to do |format| if @son.update_attributes(params[:father]) format.html { redirect_to [@father, @son], notice: 'son was successfully created!!!' } format.json { render json: @son, status: :created, location: @son } else format.html { render action: "new" } format.json { render json: @son.errors, status: :unprocessable_entity } end end end # PUT /sons/1 # PUT /sons/1.json def update @son = @father.sons.find(params[:id]) respond_to do |format| if @son.update_attributes(params[:son]) format.html { redirect_to father_sons_path, notice: 'son was successfully updated!!!' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @son.errors, status: :unprocessable_entity } end end end # DELETE /sons/1 # DELETE /sons/1.json def destroy @son = @father.sons.find(params[:id]) @son.destroy respond_to do |format| format.html { redirect_to father_sons_url } end end private def load_father @father = Father.find(params[:father_id]) end end <file_sep>/test/functional/fathers_controller_test.rb require 'test_helper' class FathersControllerTest < ActionController::TestCase setup do @father = fathers(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:fathers) end test "should get new" do get :new assert_response :success end test "should create father" do assert_difference('Father.count') do post :create, father: { name: @father.name } end assert_redirected_to father_path(assigns(:father)) end test "should show father" do get :show, id: @father assert_response :success end test "should get edit" do get :edit, id: @father assert_response :success end test "should update father" do put :update, id: @father, father: { name: @father.name } assert_redirected_to father_path(assigns(:father)) end test "should destroy father" do assert_difference('Father.count', -1) do delete :destroy, id: @father end assert_redirected_to fathers_path end end
6a0749cb690aba34bf856197df8c72af816ddfc3
[ "Markdown", "Ruby" ]
7
Markdown
jonfriese/Family
0d14c9be4ae3067b870536bb9985fed65182b2c3
faa18104cc0e80b3ddc1bd31f5ab45601eccdf22
refs/heads/master
<file_sep>import { Router } from "express" import middlewares from "../../../middlewares" const route = Router() export default app => { app.use("/users", route) route.get("/", middlewares.wrap(require("./list-users").default)) route.get("/:user_id", middlewares.wrap(require("./get-user").default)) route.post("/", middlewares.wrap(require("./create-user").default)) route.post( "/password-token", middlewares.wrap(require("./reset-password-token").default) ) route.post( "/reset-password", middlewares.wrap(require("./reset-password").default) ) route.post("/:user_id", middlewares.wrap(require("./update-user").default)) route.delete("/:user_id", middlewares.wrap(require("./delete-user").default)) return app } <file_sep>import { MedusaError, Validator } from "medusa-core-utils" export default async (req, res) => { try { const oauthService = req.scope.resolve("oauthService") const data = await oauthService.list({}) res.status(200).json({ apps: data }) } catch (err) { throw err } }
8353b2d7b8e21523f3a63a2f9606d5a9b133d08d
[ "JavaScript" ]
2
JavaScript
aloks98/medusa
f0c371f9870236483a15dd48e815076a6d726a78
1d780ba17270b684fcef73709ac889d317e39d1a