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
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrchestraBookingTicketsApp.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Abstractions;
using OrchestraBookingTicketsApp.Repositories;
using OrchestraBookingTicketsApp.Services;
using OrchestraBookingTicketsApp.Areas.Identity.Services;
namespace OrchestraBookingTicketsApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
var connection = @"Server=(localdb)\mssqllocaldb;Database=TestEntityFrameworkDb;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<OrchestraContext>(options =>
options.UseSqlServer(connection));
//services.AddDbContext<OrchestraContext>(options =>
// options.UseSqlServer(
// Configuration.GetConnectionString("DefaultConnection")));
//services.AddDefaultIdentity<IdentityUser>()
// .AddEntityFrameworkStores<OrchestraContext>();
//
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<OrchestraContext>(
options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"))
);
//Adding the identity role
services.AddIdentity<IdentityUser, IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
// add constraints
services.Configure<IdentityOptions>(options =>
{
options.User.RequireUniqueEmail = true;
options.Password.RequireDigit = true;
options.Password.RequiredLength = 10;
options.Password.RequireNonAlphanumeric = true;
options.Lockout.MaxFailedAccessAttempts = 3;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(30);
});
//add repo
services.AddScoped<IOrchestraRepository, OrchestraRepository>();
services.AddScoped<IOrchestraHistoryRepository, OrchestraHistoryRepository>();
services.AddScoped<ILocationRepository, LocationRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<ILeadArtistRepository, LeadArtistRepositorycs>();
services.AddScoped<IInstrumentRepository, InstrumentRepository>();
//add services
services.AddScoped<OrchestraService>();
services.AddScoped<OrchestraHistoryService>();
services.AddScoped<LocationService>();
services.AddScoped<UserService>();
services.AddScoped<LeadArtistService>();
services.AddScoped<InstrumentServices>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, UserManager<IdentityUser> userManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
// added seeder
DbSeeder.SeedDb(userManager);
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
<file_sep>using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Abstractions
{
public interface ILeadArtistRepository : IRepository<LeadArtist>
{
LeadArtist GetLeadArtistByOrchestraId(int orchestraId);
}
}
<file_sep>using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Data
{
public static class DbSeeder
{
public static void SeedDb(UserManager<IdentityUser> userManager)
{
if (!userManager.Users.Any(u => u.UserName == "<EMAIL>"))
{
IdentityUser user = new IdentityUser
{
UserName = "<EMAIL>",
Email = "<EMAIL>"
};
userManager.CreateAsync(user, "P@ulAlbastru77").Wait();
userManager.AddToRoleAsync(user, "User").Wait();
}
if (!userManager.Users.Any(u => u.UserName == "<EMAIL>"))
{
IdentityUser admin = new IdentityUser
{
UserName = "<EMAIL>",
Email = "<EMAIL>"
};
userManager.CreateAsync(admin, "P@ulAlbastru77").Wait();
userManager.AddToRoleAsync(admin, "Administrator").Wait();
}
if (!userManager.Users.Any(u => u.UserName == "<EMAIL>"))
{
IdentityUser admin2 = new IdentityUser
{
UserName = "<EMAIL>",
Email = "<EMAIL>"
};
userManager.CreateAsync(admin2, "P@ulAlbastru77").Wait();
userManager.AddToRoleAsync(admin2, "Administrator").Wait();
}
}
}
}
<file_sep>using OrchestraBookingTicketsApp.Abstractions;
using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Services
{
public class InstrumentServices
{
private readonly IInstrumentRepository instrumentRepository;
public InstrumentServices(IInstrumentRepository instrumentRepository)
{
this.instrumentRepository = instrumentRepository;
}
public IEnumerable<Models.Instrument> GetInstrumentsByOrchestraId(int orchestraId)
{
if (orchestraId < 0)
{
throw new Exception("Invalid Id");
}
return instrumentRepository.GetInstrumentsByOrchestraId(orchestraId);
}
public void AddInstrument(string name, string type, int orchestraid)
{
instrumentRepository.Add(new Instrument() { Name = name, Type = type, OrchestraId = orchestraid });
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
using OrchestraBookingTicketsApp.Services;
using OrchestraBookingTicketsApp.ViewModels.InstrumentModel;
namespace OrchestraBookingTicketsApp.Controllers
{
public class InstrumentsController : Controller
{
private readonly OrchestraContext _context;
private readonly InstrumentServices instrumentServices;
public InstrumentsController(OrchestraContext context, InstrumentServices instrumentServices)
{
_context = context;
this.instrumentServices = instrumentServices;
}
public IActionResult Index(int id)
{
var instruments = instrumentServices.GetInstrumentsByOrchestraId(id);
return View(instruments);
}
[Authorize(Roles = "Administrator")]
[HttpGet]
public IActionResult AddInstrument()
{
return View();
}
[HttpPost]
public IActionResult AddInstrument([FromForm]AddInstrumentViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
instrumentServices.AddInstrument(model.Name, model.Type, model.OrchestraId);
return Redirect(Url.Action("Index", "Instruments"));
}
}
}
<file_sep>using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.ViewModels.OrchestraHistoryModel
{
public class OrchestraHistoryViewModel
{
public IEnumerable<OrchestraHistory> OrchestraHistories { get; set; }
}
}
<file_sep>using OrchestraBookingTicketsApp.Abstractions;
using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Services
{
public class LocationService
{
private readonly IOrchestraRepository orchestraRepository;
private readonly ILocationRepository locationRepository;
public LocationService(IOrchestraRepository orchestraRepository, ILocationRepository locationRepository)
{
this.orchestraRepository = orchestraRepository;
this.locationRepository = locationRepository;
}
public IEnumerable<Models.Location> GetLocationByOrchestraId(int orchestraId)
{
if(orchestraId < 0)
{
throw new Exception("Invalid Id");
}
return locationRepository.GetLocationByOrchestraId(orchestraId);
}
public IEnumerable<Models.Location> GetLocations()
{
return locationRepository.GetLocations();
}
public void AddLocation(string city, string country, string address, int orchestraid)
{
locationRepository.Add(new Location() { City = city, Country = country, Address = address, OrchestraId = orchestraid });
}
}
}
<file_sep>using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Abstractions
{
public interface IOrchestraHistoryRepository : IRepository<OrchestraHistory>
{
IEnumerable<OrchestraHistory> GetOrchestrasHistoryByUserId(int userId);
OrchestraHistory GetOrchestraHistoryById(int orchestraHistoryId);
OrchestraHistory GetOrchestraHistoryByUserId(int orchestraHistoryId, int userId);
}
}
<file_sep>using OrchestraBookingTicketsApp.Abstractions;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Repositories
{
public class UserRepository : BaseRepository<User>, IUserRepository
{
public UserRepository(OrchestraContext dbContext) : base(dbContext)
{
}
public User GetUserById(int userId)
{
var user = dbContext.Users.Where(u => u.UserId == userId).SingleOrDefault();
return user;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.ViewModels.OrchestraModel
{
public class BuyTicketViewModel
{
public int OrchestraId { get; set; }
public int SeatNumber { get; set; }
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.DataAccess
{
public class OrchestraContext : DbContext
{
public OrchestraContext(DbContextOptions<OrchestraContext> options) : base(options)
{
}
public DbSet<Orchestra> Orchestras { get; set; }
public DbSet<LeadArtist> LeadArtists { get; set; }
public DbSet<Instrument> Instruments { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<OrchestraHistory> OrchestraHistories { get; set; }
public DbSet<Award> Awards { get; set; }
public DbSet<BuildingFacilities> BuildingFacilities { get; set; }
public DbSet<User> Users { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
namespace OrchestraBookingTicketsApp.Controllers
{
public class AwardsController : Controller
{
private readonly OrchestraContext _context;
public AwardsController(OrchestraContext context)
{
_context = context;
}
// GET: Awards
public async Task<IActionResult> Index()
{
var orchestraContext = _context.Awards.Include(a => a.Artists);
return View(await orchestraContext.ToListAsync());
}
// GET: Awards/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var award = await _context.Awards
.Include(a => a.Artists)
.FirstOrDefaultAsync(m => m.AwardId == id);
if (award == null)
{
return NotFound();
}
return View(award);
}
// GET: Awards/Create
public IActionResult Create()
{
ViewData["LeadArtistId"] = new SelectList(_context.LeadArtists, "LeadArtistId", "LeadArtistId");
return View();
}
// POST: Awards/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("AwardId,Title,Year,Amount,LeadArtistId")] Award award)
{
if (ModelState.IsValid)
{
_context.Add(award);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["LeadArtistId"] = new SelectList(_context.LeadArtists, "LeadArtistId", "LeadArtistId", award.LeadArtistId);
return View(award);
}
// GET: Awards/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var award = await _context.Awards.FindAsync(id);
if (award == null)
{
return NotFound();
}
ViewData["LeadArtistId"] = new SelectList(_context.LeadArtists, "LeadArtistId", "LeadArtistId", award.LeadArtistId);
return View(award);
}
// POST: Awards/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("AwardId,Title,Year,Amount,LeadArtistId")] Award award)
{
if (id != award.AwardId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(award);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AwardExists(award.AwardId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["LeadArtistId"] = new SelectList(_context.LeadArtists, "LeadArtistId", "LeadArtistId", award.LeadArtistId);
return View(award);
}
// GET: Awards/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var award = await _context.Awards
.Include(a => a.Artists)
.FirstOrDefaultAsync(m => m.AwardId == id);
if (award == null)
{
return NotFound();
}
return View(award);
}
// POST: Awards/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var award = await _context.Awards.FindAsync(id);
_context.Awards.Remove(award);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool AwardExists(int id)
{
return _context.Awards.Any(e => e.AwardId == id);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Abstractions
{
interface IBuildingFacilitiesRepository
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Models
{
public class User
{
public int UserId { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public ICollection<OrchestraHistory> OrchestraHistory { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Abstractions
{
interface IAwardRepository
{
}
}
<file_sep>using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.ViewModels.OrchestraHistoryModel
{
public class DeleteOrchestraHistoryViewModel
{
public int OrchestraHistoryId { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.ViewModels.OrchestraHistoryModel
{
public class AddOrchestraHistoryViewModel
{
public string Status { get; set; }
public int SeatNumber { get; set; }
public int Rating { get; set; }
public int OrchestraId { get; set; }
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using OrchestraBookingTicketsApp.Abstractions;
using OrchestraBookingTicketsApp.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Repositories
{
public class LeadArtistRepositorycs: BaseRepository<Models.LeadArtist>, ILeadArtistRepository
{
public LeadArtistRepositorycs(OrchestraContext dbContext) : base(dbContext)
{
}
public Models.LeadArtist GetLeadArtistByOrchestraId(int orchestraId)
{
var leadArtist = dbContext.LeadArtists.Include(pt => pt.Orchestra)
.Where(l => l.OrchestraId == orchestraId).SingleOrDefault();
return leadArtist;
}
}
}
<file_sep>using OrchestraBookingTicketsApp.Abstractions;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Repositories
{
public class OrchestraRepository : BaseRepository<Orchestra>, IOrchestraRepository
{
public OrchestraRepository(OrchestraContext dbContext) : base(dbContext)
{
}
public Orchestra GetOrchestraById(int orchestraId)
{
var orchestra = dbContext.Orchestras.Where(o => o.OrchestraId == orchestraId).SingleOrDefault();
return orchestra;
}
public IEnumerable<Orchestra> GetOrchestras()
{
var orchestras = dbContext.Orchestras.AsEnumerable();
return orchestras;
}
public IEnumerable<Orchestra> GetOrchestrasByDate(DateTime dateTime)
{
var orchestras = dbContext.Orchestras.Where(o => o.Date == dateTime).AsEnumerable();
return orchestras;
}
}
}
<file_sep>using Microsoft.CodeAnalysis;
using OrchestraBookingTicketsApp.Abstractions;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Repositories
{
public class LocationRepository : BaseRepository<Models.Location>, ILocationRepository
{
public LocationRepository(OrchestraContext dbContext) : base(dbContext)
{
}
public IEnumerable<Models.Location> GetLocationByOrchestraId(int orchestraId)
{
var locations = dbContext.Locations.Where(l => l.OrchestraId == orchestraId).AsEnumerable();
return locations;
}
public IEnumerable<Models.Location> GetLocations()
{
var locations = dbContext.Locations.AsEnumerable();
return locations;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.ViewModels.LeadArtistModel
{
public class AddLeadArtistViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public int OrchestraId { get; set; }
}
}
<file_sep>using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.ViewModels.OrchestraModel
{
public class OrchestraViewModel
{
public IEnumerable<Orchestra> Orchestras { get; set; }
}
}
<file_sep>using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SignInResult = Microsoft.AspNetCore.Identity.SignInResult;
namespace OrchestraBookingTicketsApp.Areas.Identity.Services
{
public class UserService
{
private SignInManager<IdentityUser> _signInManager;
private UserManager<IdentityUser> _userManager;
public UserService(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager)
{
_signInManager = signInManager;
_userManager = userManager;
}
// Register
public Task<IdentityResult> GetResultRegister(string userName, string email, string password)
{
var user = new IdentityUser { UserName = userName, Email = email };
return _userManager.CreateAsync(user, password);
}
public Task SignIn(IdentityUser user)
{
return _signInManager.SignInAsync(user, isPersistent: false);
}
// Login
public Task<SignInResult> GetResultLogin(string email, string password, bool rememberMe)
{
return _signInManager.PasswordSignInAsync(email, password, rememberMe, lockoutOnFailure: true);
}
//Logout
public Task LogOut()
{
return _signInManager.SignOutAsync();
}
}
}
<file_sep>using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.ViewModels.LocationModel
{
public class LocationViewModel
{
public IEnumerable<Location> Locations { get; set; }
}
}
<file_sep>using Microsoft.AspNetCore.Identity;
using OrchestraBookingTicketsApp.Abstractions;
using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Services
{
public class OrchestraHistoryService
{
private IOrchestraHistoryRepository orchestraHistoryRepository;
private IOrchestraRepository orchestraRepository;
private IUserRepository userRepository;
public OrchestraHistoryService(IOrchestraHistoryRepository orchestraHistoryRepository, IOrchestraRepository orchestraRepository, IUserRepository userRepository)
{
this.orchestraHistoryRepository = orchestraHistoryRepository;
this.userRepository = userRepository;
this.orchestraRepository = orchestraRepository;
}
public IEnumerable<OrchestraHistory> GetOrchestrasHistoryByUserId(int userId)
{
return orchestraHistoryRepository.GetOrchestrasHistoryByUserId(userId);
}
public void DeleteOrchestraHistory(int orchestraHistory, int userId)
{
var orchestraHistoryItem = orchestraHistoryRepository.GetOrchestraHistoryByUserId(orchestraHistory, userId);
orchestraHistoryRepository.Delete(orchestraHistoryItem);
}
public OrchestraHistory GetOrchestraHistoryBy(int orchestraHistoryId)
{
return orchestraHistoryRepository.GetOrchestraHistoryById(orchestraHistoryId);
}
public void AddOrchestraInHistory(int orchestraId, int userId, string status, int seatNumber, int rating)
{
var orchestra = orchestraRepository.GetOrchestraById(orchestraId);
var user = userRepository.GetUserById(userId);
var orchestraDummyList = new List<Orchestra>
{
orchestra
};
orchestraHistoryRepository.Add(new OrchestraHistory() { Status = status, SeatNumber = seatNumber, Rating = rating, User = user, Orchestra = orchestraDummyList });
}
public void SaveRating(int userId, int orchestraHistoryId, int rating)
{
var historyTrip = orchestraHistoryRepository.GetOrchestraHistoryByUserId(orchestraHistoryId, userId);
historyTrip.Rating = rating;
orchestraHistoryRepository.Update(historyTrip);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OrchestraBookingTicketsApp.Models;
namespace OrchestraBookingTicketsApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
[Authorize(Roles = "User")]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Popup()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
public ActionResult Gallery()
{
ViewBag.Message = "Some of the pictures with Important Philharmonics that hosted our Orchestras";
return View();
}
public ActionResult Gallery2()
{
ViewBag.Message = "Some of the shots taken during Orchestras concerts ";
return View();
}
[Authorize(Roles = "User")]
public IActionResult BookSeats()
{
ViewBag.Message = "Choose an available seat";
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>using OrchestraBookingTicketsApp.Abstractions;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Repositories
{
public class InstrumentRepository : BaseRepository<Models.Instrument>, IInstrumentRepository
{
public InstrumentRepository(OrchestraContext dbContext) : base(dbContext)
{
}
public IEnumerable<Instrument> GetInstrumentsByOrchestraId(int orchestraId)
{
var instruments = dbContext.Instruments.Where(i => i.OrchestraId == orchestraId).AsEnumerable();
return instruments;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Models
{
public class BuildingFacilities
{
public int BuildingFacilitiesId { get; set; }
public int MaxSeats { get; set; }
public bool HasAirConditioning { get; set; }
public bool HasSmokingArea { get; set; }
public int LocationId { get; set; }
public Location Location { get; set; }
}
}<file_sep>using OrchestraBookingTicketsApp.Abstractions;
using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Services
{
public class OrchestraService
{
private IOrchestraRepository orchestraRepository;
public OrchestraService(IOrchestraRepository orchestraRepository)
{
this.orchestraRepository = orchestraRepository;
}
public IEnumerable<Orchestra> GetOrchestraByDate(DateTime dateTime)
{
if (dateTime == null)
{
throw new Exception("Null string");
}
return orchestraRepository.GetOrchestrasByDate(dateTime);
}
public IEnumerable<Orchestra> GetOrchestras()
{
return orchestraRepository.GetOrchestras();
}
public void AddOrchestra(string title, DateTime date, int price)
{
orchestraRepository.Add(new Orchestra() { Title = title, Date = date, Price = price});
}
public void DeleteOrchestra(int orchestraId)
{
var orchestraItem = orchestraRepository.GetOrchestraById(orchestraId);
orchestraRepository.Delete(orchestraItem);
}
}
}
<file_sep>using OrchestraBookingTicketsApp.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Services
{
public class LeadArtistService
{
private readonly IOrchestraRepository orchestraRepository;
private readonly ILeadArtistRepository leadArtistRepository;
public LeadArtistService(IOrchestraRepository orchestraRepository, ILeadArtistRepository leadArtistRepository)
{
this.orchestraRepository = orchestraRepository;
this.leadArtistRepository = leadArtistRepository;
}
public Models.LeadArtist GetLeadArtistByOrchestraId(int orchestraId)
{
if (orchestraId < 0)
{
throw new Exception("Invalid Id");
}
return leadArtistRepository.GetLeadArtistByOrchestraId(orchestraId);
}
public void AddLeadArtist(string name, int age, int orchestraid)
{
leadArtistRepository.Add(new Models.LeadArtist() {Age = age, Name = name, OrchestraId = orchestraid });
}
}
}
<file_sep>using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Abstractions
{
public interface IUserRepository
{
User GetUserById(int userId);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
using OrchestraBookingTicketsApp.Services;
using OrchestraBookingTicketsApp.ViewModels.LocationModel;
namespace OrchestraBookingTicketsApp.Controllers
{
public class LocationsController : Controller
{
private readonly LocationService locationService;
private readonly OrchestraService orchestraService;
public LocationsController(LocationService locationService, OrchestraService orchestraService)
{
this.orchestraService = orchestraService;
this.locationService = locationService;
}
public ActionResult Index()
{
try
{
var locations = locationService.GetLocations();
return View(new LocationViewModel { Locations = locations });
}
catch (Exception)
{
return BadRequest("Invalid request received");
}
}
[HttpGet]
public IActionResult Details(int id)
{
var locations = locationService.GetLocationByOrchestraId(id);
return View(locations);
}
[Authorize(Roles = "Administrator")]
[HttpGet]
public IActionResult AddLocation()
{
return View();
}
[HttpPost]
public IActionResult AddLocation([FromForm]AddLocationViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
locationService.AddLocation(model.City, model.Country, model.Address, model.OrchestraId);
return Redirect(Url.Action("Index", "Locations"));
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using OrchestraBookingTicketsApp.Abstractions;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Repositories
{
public class OrchestraHistoryRepository : BaseRepository<OrchestraHistory>, IOrchestraHistoryRepository
{
public OrchestraHistoryRepository(OrchestraContext dbContext) : base(dbContext)
{
}
public OrchestraHistory GetOrchestraHistoryById(int orchestraHistoryId)
{
var orchestraHistory = dbContext.OrchestraHistories .Include(pt => pt.Orchestra)
.Where(h => h.OrchestraHistoryId == orchestraHistoryId)
.SingleOrDefault();
return orchestraHistory;
}
//added
public OrchestraHistory GetOrchestraHistoryByUserId(int orchestraHistoryId, int userId)
{
var orchestraHistory = dbContext.OrchestraHistories.Include(pt => pt.User)
.Include(pt => pt.Orchestra)
.Where(h => h.User.UserId == userId && h.OrchestraHistoryId == orchestraHistoryId).SingleOrDefault();
return orchestraHistory;
}
public IEnumerable<OrchestraHistory> GetOrchestrasHistoryByUserId(int userId)
{
var orchestraHistory = dbContext.OrchestraHistories.Include(pt => pt.User)
.Include(pt => pt.Orchestra)
.Where(h => h.User.UserId == userId)
.AsEnumerable();
foreach (var item in orchestraHistory)
{
foreach(var orchestra in item.Orchestra)
{
if (orchestra.Date < DateTimeOffset.Now)
{
item.Status = "Completed";
}
else
{
item.Status = "In progress";
}
}
}
dbContext.SaveChanges();
return orchestraHistory;
}
}
}
<file_sep>using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace OrchestraBookingTicketsApp.Migrations
{
public partial class InitalMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
UserId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Email = table.Column<string>(nullable: true),
FirstName = table.Column<string>(nullable: true),
LastName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.UserId);
});
migrationBuilder.CreateTable(
name: "OrchestraHistories",
columns: table => new
{
OrchestraHistoryId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Status = table.Column<string>(nullable: true),
SeatNumber = table.Column<int>(nullable: false),
Rating = table.Column<int>(nullable: false),
UsersUserId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_OrchestraHistories", x => x.OrchestraHistoryId);
table.ForeignKey(
name: "FK_OrchestraHistories_Users_UsersUserId",
column: x => x.UsersUserId,
principalTable: "Users",
principalColumn: "UserId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Orchestras",
columns: table => new
{
OrchestraId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Title = table.Column<string>(nullable: true),
Date = table.Column<DateTime>(nullable: false),
Price = table.Column<int>(nullable: false),
OrchestraHistoriesOrchestraHistoryId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Orchestras", x => x.OrchestraId);
table.ForeignKey(
name: "FK_Orchestras_OrchestraHistories_OrchestraHistoriesOrchestraHistoryId",
column: x => x.OrchestraHistoriesOrchestraHistoryId,
principalTable: "OrchestraHistories",
principalColumn: "OrchestraHistoryId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Instruments",
columns: table => new
{
InstrumentId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(nullable: true),
Type = table.Column<string>(nullable: true),
OrchestraId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Instruments", x => x.InstrumentId);
table.ForeignKey(
name: "FK_Instruments_Orchestras_OrchestraId",
column: x => x.OrchestraId,
principalTable: "Orchestras",
principalColumn: "OrchestraId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "LeadArtists",
columns: table => new
{
LeadArtistId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(nullable: true),
Age = table.Column<int>(nullable: false),
OrchestraId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_LeadArtists", x => x.LeadArtistId);
table.ForeignKey(
name: "FK_LeadArtists_Orchestras_OrchestraId",
column: x => x.OrchestraId,
principalTable: "Orchestras",
principalColumn: "OrchestraId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Locations",
columns: table => new
{
LocationId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
City = table.Column<string>(nullable: true),
Country = table.Column<string>(nullable: true),
Address = table.Column<string>(nullable: true),
OrchestraId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Locations", x => x.LocationId);
table.ForeignKey(
name: "FK_Locations_Orchestras_OrchestraId",
column: x => x.OrchestraId,
principalTable: "Orchestras",
principalColumn: "OrchestraId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Awards",
columns: table => new
{
AwardId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Title = table.Column<string>(nullable: true),
Year = table.Column<int>(nullable: false),
Amount = table.Column<int>(nullable: false),
LeadArtistId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Awards", x => x.AwardId);
table.ForeignKey(
name: "FK_Awards_LeadArtists_LeadArtistId",
column: x => x.LeadArtistId,
principalTable: "LeadArtists",
principalColumn: "LeadArtistId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BuildingFacilities",
columns: table => new
{
BuildingFacilitiesId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
MaxSeats = table.Column<int>(nullable: false),
HasAirConditioning = table.Column<bool>(nullable: false),
HasSmokingArea = table.Column<bool>(nullable: false),
LocationId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BuildingFacilities", x => x.BuildingFacilitiesId);
table.ForeignKey(
name: "FK_BuildingFacilities_Locations_LocationId",
column: x => x.LocationId,
principalTable: "Locations",
principalColumn: "LocationId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Awards_LeadArtistId",
table: "Awards",
column: "LeadArtistId");
migrationBuilder.CreateIndex(
name: "IX_BuildingFacilities_LocationId",
table: "BuildingFacilities",
column: "LocationId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Instruments_OrchestraId",
table: "Instruments",
column: "OrchestraId");
migrationBuilder.CreateIndex(
name: "IX_LeadArtists_OrchestraId",
table: "LeadArtists",
column: "OrchestraId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Locations_OrchestraId",
table: "Locations",
column: "OrchestraId");
migrationBuilder.CreateIndex(
name: "IX_OrchestraHistories_UsersUserId",
table: "OrchestraHistories",
column: "UsersUserId");
migrationBuilder.CreateIndex(
name: "IX_Orchestras_OrchestraHistoriesOrchestraHistoryId",
table: "Orchestras",
column: "OrchestraHistoriesOrchestraHistoryId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Awards");
migrationBuilder.DropTable(
name: "BuildingFacilities");
migrationBuilder.DropTable(
name: "Instruments");
migrationBuilder.DropTable(
name: "LeadArtists");
migrationBuilder.DropTable(
name: "Locations");
migrationBuilder.DropTable(
name: "Orchestras");
migrationBuilder.DropTable(
name: "OrchestraHistories");
migrationBuilder.DropTable(
name: "Users");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
namespace OrchestraBookingTicketsApp.Controllers
{
public class BuildingFacilitiesController : Controller
{
private readonly OrchestraContext _context;
public BuildingFacilitiesController(OrchestraContext context)
{
_context = context;
}
// GET: BuildingFacilities
public async Task<IActionResult> Index()
{
var orchestraContext = _context.BuildingFacilities.Include(b => b.Location);
return View(await orchestraContext.ToListAsync());
}
// GET: BuildingFacilities/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var buildingFacilities = await _context.BuildingFacilities
.Include(b => b.Location)
.FirstOrDefaultAsync(m => m.BuildingFacilitiesId == id);
if (buildingFacilities == null)
{
return NotFound();
}
return View(buildingFacilities);
}
// GET: BuildingFacilities/Create
public IActionResult Create()
{
ViewData["LocationId"] = new SelectList(_context.Locations, "LocationId", "LocationId");
return View();
}
// POST: BuildingFacilities/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("BuildingFacilitiesId,MaxSeats,HasAirConditioning,HasSmokingArea,LocationId")] BuildingFacilities buildingFacilities)
{
if (ModelState.IsValid)
{
_context.Add(buildingFacilities);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["LocationId"] = new SelectList(_context.Locations, "LocationId", "LocationId", buildingFacilities.LocationId);
return View(buildingFacilities);
}
// GET: BuildingFacilities/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var buildingFacilities = await _context.BuildingFacilities.FindAsync(id);
if (buildingFacilities == null)
{
return NotFound();
}
ViewData["LocationId"] = new SelectList(_context.Locations, "LocationId", "LocationId", buildingFacilities.LocationId);
return View(buildingFacilities);
}
// POST: BuildingFacilities/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("BuildingFacilitiesId,MaxSeats,HasAirConditioning,HasSmokingArea,LocationId")] BuildingFacilities buildingFacilities)
{
if (id != buildingFacilities.BuildingFacilitiesId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(buildingFacilities);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BuildingFacilitiesExists(buildingFacilities.BuildingFacilitiesId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["LocationId"] = new SelectList(_context.Locations, "LocationId", "LocationId", buildingFacilities.LocationId);
return View(buildingFacilities);
}
// GET: BuildingFacilities/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var buildingFacilities = await _context.BuildingFacilities
.Include(b => b.Location)
.FirstOrDefaultAsync(m => m.BuildingFacilitiesId == id);
if (buildingFacilities == null)
{
return NotFound();
}
return View(buildingFacilities);
}
// POST: BuildingFacilities/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var buildingFacilities = await _context.BuildingFacilities.FindAsync(id);
_context.BuildingFacilities.Remove(buildingFacilities);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool BuildingFacilitiesExists(int id)
{
return _context.BuildingFacilities.Any(e => e.BuildingFacilitiesId == id);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Models
{
public class Instrument
{
public int InstrumentId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public int OrchestraId { get; set; }
public Orchestra Orchestra { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
using OrchestraBookingTicketsApp.Services;
using OrchestraBookingTicketsApp.ViewModels.OrchestraModel;
namespace OrchestraBookingTicketsApp.Controllers
{
public class OrchestrasController : Controller
{
private readonly OrchestraService orchestraService;
private readonly OrchestraHistoryService orchestrahistoryService;
private readonly UserManager<IdentityUser> userManager;
public OrchestrasController(OrchestraService orchestraService, OrchestraHistoryService orchestrahistoryService, UserManager<IdentityUser> userManager)
{
this.orchestraService = orchestraService;
this.orchestrahistoryService = orchestrahistoryService;
this.userManager = userManager;
}
public ActionResult Index()
{
try
{
var orchestras = orchestraService.GetOrchestras();
return View(new OrchestraViewModel { Orchestras = orchestras });
}
catch (Exception)
{
return BadRequest("Invalid request received");
}
}
[Authorize(Roles = "Administrator")]
[HttpGet]
public IActionResult AddOrchestra()
{
return View();
}
[Authorize(Roles = "Administrator")]
[HttpGet]
public IActionResult DeleteOrchestra()
{
return View();
}
[Authorize(Roles = "Administrator")]
[HttpPost]
public IActionResult AddOrchestra([FromForm]AddOrchestraViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
orchestraService.AddOrchestra(model.Title, model.Date, model.Price);
return Redirect(Url.Action("Index", "Orchestras"));
}
[Authorize(Roles = "Administrator")]
[HttpPost]
public IActionResult DeleteOrchestra(int id)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
orchestraService.DeleteOrchestra(id);
return Redirect(Url.Action("Index", "Orchestras"));
}
//Added new
[Authorize(Roles = "User, Administrator")]
[HttpGet]
public IActionResult BookSeat(int id)
{
var buyVm = new BuyTicketViewModel()
{
OrchestraId = id,
SeatNumber = -1
};
return View(buyVm);
}
[Authorize(Roles = "User")]
[HttpPost]
public IActionResult BookSeat([FromForm] BuyTicketViewModel Vm)
{
var userId = userManager.GetUserId(User);
// var personalTrip = historyTripsService.GetPersonalTripByUserId(userId);
if (Vm.SeatNumber != -1)
{
orchestrahistoryService.AddOrchestraInHistory(Vm.OrchestraId, 1, "In Progress", Vm.SeatNumber, 0);
return RedirectToAction("Index", "OrchestraHistories");
}
return RedirectToAction("BookSeat", "Orchestras");
}
}
}
<file_sep># Read first the Documentation.pdf for an overview of the application
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Models
{
public class LeadArtist
{
public int LeadArtistId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public ICollection<Award> Award { get; set; }
public int OrchestraId { get; set; }
public Orchestra Orchestra { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
using OrchestraBookingTicketsApp.Services;
using OrchestraBookingTicketsApp.ViewModels.LeadArtistModel;
namespace OrchestraBookingTicketsApp.Controllers
{
public class LeadArtistsController : Controller
{
private readonly OrchestraContext _context;
private readonly LeadArtistService leadArtistService;
public LeadArtistsController(OrchestraContext context, LeadArtistService leadArtistService)
{
_context = context;
this.leadArtistService = leadArtistService;
}
[HttpGet]
public IActionResult Index(int id)
{
var leadArtist = leadArtistService.GetLeadArtistByOrchestraId(id);
return View(leadArtist);
}
[Authorize(Roles = "Administrator")]
[HttpGet]
public IActionResult AddLeadArtist()
{
return View();
}
[HttpPost]
public IActionResult AddLeadArtist([FromForm]AddLeadArtistViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
leadArtistService.AddLeadArtist(model.Name, model.Age, model.OrchestraId);
return Redirect(Url.Action("Index", "LeadArtists"));
}
}
}
<file_sep>using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Abstractions
{
public interface IInstrumentRepository : IRepository<Instrument>
{
IEnumerable<Instrument> GetInstrumentsByOrchestraId(int orchestraId);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using OrchestraBookingTicketsApp.DataAccess;
using OrchestraBookingTicketsApp.Models;
using OrchestraBookingTicketsApp.Services;
using OrchestraBookingTicketsApp.ViewModels.OrchestraHistoryModel;
namespace OrchestraBookingTicketsApp.Controllers
{
[Authorize(Roles = "User")]
public class OrchestraHistoriesController : Controller
{
private readonly UserManager<IdentityUser> userManager;
private readonly OrchestraHistoryService orchestraHistoryService;
public OrchestraHistoriesController(OrchestraHistoryService orchestraHistoryService, UserManager<IdentityUser> userManager)
{
this.userManager = userManager;
this.orchestraHistoryService = orchestraHistoryService;
}
public ActionResult Index()
{
try
{
var userIdStr = userManager.GetUserId(User);
var orchestraHistory = orchestraHistoryService.GetOrchestrasHistoryByUserId(1);
return View(new OrchestraHistoryViewModel { OrchestraHistories = orchestraHistory });
}
catch (Exception)
{
return BadRequest("Invalid request received");
}
}
[HttpGet]
public IActionResult DeleteOrchestraHistory(OrchestraHistory orchestraHistory)
{
//var historyOrchestra = orchestraHistoryService.GetOrchestraHistoryBy(orchestraHistory.OrchestraHistoryId);
//return View(historyOrchestra);
return View();
}
[HttpGet]
public IActionResult AddOrchestraHistory(int id)
{
AddOrchestraHistoryViewModel vm = new AddOrchestraHistoryViewModel() { OrchestraId = id };
return View(vm);
}
[HttpPost]
public IActionResult AddOrchestraHist([FromForm]AddOrchestraHistoryViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
orchestraHistoryService.AddOrchestraInHistory(model.OrchestraId, 1, model.Status, model.SeatNumber, model.Rating);
return Redirect(Url.Action("Index", "OrchestraHistories"));
}
[HttpPost]
public IActionResult DeleteOrchestraHistory(int id)
{
orchestraHistoryService.DeleteOrchestraHistory(id,1);
return Redirect(Url.Action("Index", "OrchestraHistories"));
}
[HttpPost]
public IActionResult SaveRating([FromForm(Name = "item.OrchestraHistoryId")] int OrchestraId, [FromForm(Name = "item.Rating")] int rating)
{
var userId = userManager.GetUserId(User);
orchestraHistoryService.SaveRating(1, OrchestraId, rating);
return RedirectToAction("Index");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Models
{
public class OrchestraHistory
{
public int OrchestraHistoryId { get; set; }
public string Status { get; set; }
public int SeatNumber { get; set; }
public int Rating { get; set; }
public ICollection<Orchestra> Orchestra { get; set; }
public User User { get; set; }
}
}<file_sep>using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Abstractions
{
public interface ILocationRepository : IRepository<Location>
{
IEnumerable<Location> GetLocationByOrchestraId(int orchestraId);
IEnumerable<Location> GetLocations();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Models
{
public class Award
{
public int AwardId { get; set; }
public string Title { get; set; }
public int Year { get; set; }
public int Amount { get; set; }
public int LeadArtistId { get; set; }
public LeadArtist Artists { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Models
{
public class Orchestra
{
public int OrchestraId { get; set; }
public string Title { get; set; }
public DateTime Date { get; set; }
public int Price { get; set; }
public LeadArtist LeadArtist { get; set; }
public OrchestraHistory OrchestraHistory { get; set; }
public ICollection<Instrument> Instrument { get; set; }
public ICollection<Location> Location { get; set; }
}
}
<file_sep>using OrchestraBookingTicketsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OrchestraBookingTicketsApp.Abstractions
{
public interface IOrchestraRepository : IRepository<Orchestra>
{
IEnumerable<Orchestra> GetOrchestras();
IEnumerable<Orchestra> GetOrchestrasByDate(DateTime dateTime);
Orchestra GetOrchestraById(int orchestraId);
}
}
|
355103f8ed8ba3a3d1e50dc949a763bb14b87cd5
|
[
"Markdown",
"C#"
] | 47 |
C#
|
WAEREWOLF/OrchestraBookingTicketsAppRepo
|
a3326c21e7f8d148754d0ad84979c520dbb74990
|
c1b0c225c05acd822d4f3bdac0c7f552f889f6de
|
refs/heads/master
|
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jbouille <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/11/25 17:13:37 by jbouille #+# #+# */
/* Updated: 2015/11/28 14:33:38 by jbouille ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_separ(char *s, char c)
{
int nword;
int i;
i = 0;
nword = 0;
while (s[i])
{
while (s[i] && s[i] == c)
i++;
if (s[i])
{
nword++;
while (s[i] && s[i] != c)
i++;
}
}
return (nword);
}
static int ft_strlen_separ(char *s, char c)
{
char *tmp;
tmp = s;
while (*s && *s != c)
s++;
return (s - tmp);
}
static char *ft_strcpy_separ(char *s1, char *s2, char c)
{
char *tmp;
tmp = s1;
while (*s2 && *s2 != c)
*s1++ = *s2++;
*s1 = '\0';
return (tmp);
}
char **ft_strsplit(char const *s, char c)
{
int i;
int len;
int nword;
char **str;
if (!s)
return (NULL);
nword = ft_count_separ((char *)s, c);
if (!(str = (char **)malloc((nword + 1) * sizeof(*str))))
return (NULL);
str[nword] = NULL;
i = 0;
while (i < nword)
{
while (*s && *s == c)
s++;
len = ft_strlen_separ((char *)s, c);
if (!(str[i] = (char *)malloc((len + 1) * sizeof(**str))))
return (NULL);
ft_strcpy_separ(str[i], (char *)s, c);
s += len;
i++;
}
return (str);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jbouille <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/11/26 21:52:52 by jbouille #+# #+# */
/* Updated: 2015/12/03 16:25:25 by jbouille ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static unsigned int ft_countnb(unsigned int n)
{
unsigned int i;
i = 0;
while (n)
{
n /= 10;
i++;
}
return (i);
}
static char *ft_strzero(void)
{
char *strzero;
strzero = (char*)ft_strnew(1);
strzero[0] = '0';
return (strzero);
}
static long long ft_abs(int n)
{
if (n >= 0)
return ((long long)n);
return (-(long long)n);
}
char *ft_itoa(int n)
{
int i;
int j;
char *str;
long long nb;
if (n == 0)
return (ft_strzero());
i = 0;
if (n < 0)
i++;
nb = ft_abs(n);
j = i;
i += (int)ft_countnb(nb);
if (!(str = (char*)ft_strnew(i)))
return (NULL);
if (j == 1)
str[0] = '-';
while (j < i)
{
str[j] = nb / ft_power(10, i - j - 1) + '0';
nb = nb - nb / ft_power(10, i - j - 1) * ft_power(10, i - j - 1);
j++;
}
return (str);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jbouille <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/12/08 11:36:22 by jbouille #+# #+# */
/* Updated: 2015/12/10 16:42:41 by jbouille ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef GET_NEXT_LINE_H
# define GET_NEXT_LINE_H
# define BUFF_SIZE 1000000000
# include <sys/types.h>
# include <sys/uio.h>
# include <unistd.h>
# include <fcntl.h>
# include <stdlib.h>
# include "libft.h"
int get_next_line(int const fd, char **line);
typedef struct s_files
{
char *overflow;
int fd;
} t_files;
typedef struct s_static
{
t_files files[1000];
int nb;
char buf[BUFF_SIZE + 1];
} t_static;
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jbouille <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/12/08 11:48:22 by jbouille #+# #+# */
/* Updated: 2015/12/10 16:18:36 by jbouille ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int rtcharin(char *buf)
{
int i;
i = 0;
while (buf[i])
{
if (buf[i] == '\n')
return (i);
i++;
}
return (-1);
}
int intab(int fd, t_static *var)
{
int i;
i = 0;
while (i < var->nb)
{
if (var->files[i].fd == fd)
return (i);
i++;
}
var->nb += 1;
var->files[i].fd = fd;
var->files[i].overflow = ft_strnew(0);
if (!var->files[i].overflow)
return (-1);
return (i);
}
int get_line(int rtchar, int index, t_static *var, char **line)
{
if (!(*line = ft_strnew(rtchar)))
return (-1);
*line = ft_strncpy(*line, var->files[index].overflow, rtchar);
var->files[index].overflow = var->files[index].overflow + rtchar + 1;
return (1);
}
int get_next_line(int const fd, char **line)
{
int ret;
int rtchar;
int i;
static t_static var;
i = intab(fd, &var);
if (fd < 0 || line == NULL || i < 0)
return (-1);
*line = NULL;
if ((rtchar = rtcharin(var.files[i].overflow)) >= 0)
return (get_line(rtchar, i, &var, line));
while (rtchar == -1 && (ret = read(fd, var.buf, BUFF_SIZE)))
{
if (ret == -1)
return (-1);
var.buf[ret] = '\0';
var.files[i].overflow = ft_strjoin(var.files[i].overflow, var.buf);
if ((rtchar = rtcharin(var.files[i].overflow)) >= 0)
return (get_line(rtchar, i, &var, line));
}
if (var.files[i].overflow[0] != '\0' && rtchar == -1 && ret == 0)
return (get_line(ft_strlen(var.files[i].overflow), i, &var, line));
return (0);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstnew.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jbouille <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/11/25 18:31:03 by jbouille #+# #+# */
/* Updated: 2015/11/28 14:15:01 by jbouille ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
t_list *ft_lstnew(void const *content, size_t content_size)
{
t_list *maillon;
if (!(maillon = (t_list *)malloc(sizeof(t_list))))
return (NULL);
if (!content)
{
maillon->content = NULL;
maillon->content_size = 0;
}
else
{
if (!(maillon->content = malloc(content_size)))
return (NULL);
ft_memcpy(maillon->content, content, content_size);
maillon->content_size = content_size;
}
maillon->next = NULL;
return (maillon);
}
<file_sep>.PHONY: all, $(NAME), clean, fclean, re, norme
NAME = libft.a
DIRINCLUDES = includes/
INCLUDE = libft.h
SRC = $(SRC1) $(SRC2) $(SRCBONUS) $(SRCOTHER)
SRC1 = ft_memset.c \
ft_bzero.c \
ft_memcpy.c \
ft_memccpy.c \
ft_memmove.c \
ft_memchr.c \
ft_memcmp.c \
ft_strlen.c \
ft_strdup.c \
ft_strcpy.c \
ft_strncpy.c \
ft_strcat.c \
ft_strncat.c \
ft_strlcat.c \
ft_strchr.c \
ft_strrchr.c \
ft_strstr.c \
ft_strnstr.c \
ft_strcmp.c \
ft_strncmp.c \
ft_atoi.c \
ft_isalpha.c \
ft_isdigit.c \
ft_isalnum.c \
ft_isascii.c \
ft_isprint.c \
ft_toupper.c \
ft_tolower.c
SRC2 = ft_memalloc.c \
ft_memdel.c \
ft_strnew.c \
ft_strdel.c \
ft_strclr.c \
ft_striter.c \
ft_striteri.c \
ft_strmap.c \
ft_strmapi.c \
ft_strequ.c \
ft_strnequ.c \
ft_strsub.c \
ft_strjoin.c \
ft_strtrim.c \
ft_strsplit.c \
ft_itoa.c \
ft_putchar.c \
ft_putstr.c \
ft_putendl.c \
ft_putnbr.c \
ft_putchar_fd.c \
ft_putstr_fd.c \
ft_putendl_fd.c \
ft_putnbr_fd.c
SRCBONUS = ft_lstnew.c \
ft_lstdelone.c \
ft_lstdel.c \
ft_lstadd.c \
ft_lstiter.c \
ft_lstmap.c
SRCOTHER = ft_factorial.c \
ft_power.c \
ft_sqrt.c \
ft_isprime.c \
ft_nextprime.c \
ft_islower.c \
ft_isupper.c
OBJ = $(SRC:.c=.o)
FLAGS = -Wall -Wextra -Werror
all: $(NAME)
$(NAME): $(OBJ)
ar rc $(NAME) $(OBJ)
ranlib $(NAME)
$(OBJ):
gcc -c $(SRC) -I $(DIRINCLUDES) $(FLAGS)
clean:
/bin/rm -f $(OBJ)
fclean: clean
/bin/rm -f $(NAME)
re: fclean all
norme:
norminette $(DIRINCLUDES)$(INCLUDE) $(SRC)
|
555c28b7fa15338764288acbc162f37f1c9c6606
|
[
"C",
"Makefile"
] | 6 |
C
|
jbouille/get_next_line
|
385f1533918b9316e35ee49b0fae975ae83cfc9f
|
da487ff3e048e277f2cd38be048096d3820e8f48
|
refs/heads/main
|
<file_sep>//
// TableRowController.swift
// Table WatchKit Extension
//
// Created by <NAME> on 08.03.2021.
//
import WatchKit
import Foundation
class TableRowController: NSObject {
@IBOutlet weak var itemLabel: WKInterfaceLabel!
}
<file_sep>//
// Model.swift
// Tables WatchKit Extension
//
// Created by <NAME> on 07.03.2021.
//
import Foundation
class Note {
var title: String
var text: String
init (title: String, text: String) {
self.title = title
self.text = text
}
static var notes: [Note] = [
Note(title: "1", text: "111"),
Note(title: "22", text: "222 222"),
Note(title: "333", text: "333 333 333"),
Note(title: "4444", text: "444 444 444 444"),
Note(title: "55555", text: "555 555 555 555 555")
]
}
<file_sep>//
// DetailController.swift
// Table WatchKit Extension
//
// Created by <NAME> on 08.03.2021.
//
import WatchKit
import Foundation
class DetailController: WKInterfaceController {
@IBOutlet weak var titleLabel: WKInterfaceLabel!
@IBOutlet weak var textLabel: WKInterfaceLabel!
var model: Note = Note(title: "", text: "")
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if let model = context as? Note {
titleLabel.setText(model.title)
textLabel.setText(model.text)
}
}
override func contextForSegue(withIdentifier segueIdentifier: String, in table: WKInterfaceTable, rowIndex: Int) -> Any? {
return model
}
}
<file_sep>//
// AddNoteController.swift
// NotesStoryboard WatchKit Extension
//
// Created by <NAME> on 08.03.2021.
//
import WatchKit
import Foundation
class AddNoteController: WKInterfaceController {
@IBOutlet weak var titleEdit: WKInterfaceTextField!
@IBOutlet weak var textEdit: WKInterfaceTextField!
var title: String = ""
var text: String = ""
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if let model = context as? Note {
titleEdit.setText(model.title)
textEdit.setText(model.text)
}
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
@IBAction func changeTitle(_ value: NSString?) {
title = value! as String
}
@IBAction func changeText(_ value: NSString?) {
text = value! as String
}
@IBAction func saveButton() {
Note.notes.append(Note(title: title, text: text))
self.pop()
}
}
<file_sep>//
// InterfaceController.swift
// Table WatchKit Extension
//
// Created by <NAME> on 08.03.2021.
//
import WatchKit
import Foundation
class TableController: WKInterfaceController {
@IBOutlet weak var table: WKInterfaceTable!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
table.setNumberOfRows(Note.notes.count, withRowType: "tableId")
for (index, item) in Note.notes.enumerated() {
let controller = table.rowController(at: index) as! TableRowController
controller.itemLabel.setText(item.title)
}
}
override func contextForSegue(withIdentifier segueIdentifier: String, in table: WKInterfaceTable, rowIndex: Int) -> Any? {
return Note.notes[rowIndex]
}
}
|
f61f1e888d49c058da5e9dc139286652f2924d82
|
[
"Swift"
] | 5 |
Swift
|
mobile-sergey/NotesStoryboard
|
71ee7a92ed9b8132e0bd761d8aea93247c5e0262
|
2d232c118e274cd45379344c821164c2c5de9809
|
refs/heads/master
|
<file_sep># -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://vagrantcloud.com/search.
config.vm.box = "chenhan/lubuntu-desktop-18.04"
# Disable automatic box update checking. If you disable this, then
# boxes will only be checked for updates when the user runs
# `vagrant box outdated`. This is not recommended.
# config.vm.box_check_update = false
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine. In the example below,
# accessing "localhost:8080" will access port 80 on the guest machine.
# NOTE: This will enable public access to the opened port
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.network "forwarded_port", guest: 443, host: 8443
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine and only allow access
# via 127.0.0.1 to disable public access
# config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"
# Create a private network, which allows host-only access to the machine
# using a specific IP.
# config.vm.network "private_network", ip: "192.168.33.10"
# Create a public network, which generally matched to bridged network.
# Bridged networks make the machine appear as another physical device on
# your network.
# config.vm.network "public_network"
# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
# config.vm.synced_folder "../data", "/vagrant_data"
# Provider-specific configuration so you can fine-tune various
# backing providers for Vagrant. These expose provider-specific options.
# Example for VirtualBox:
#
config.vm.provider "virtualbox" do |vb|
# # Display the VirtualBox GUI when booting the machine
vb.gui = true
#
# # Customize the amount of memory on the VM:
vb.cpus = 2
vb.memory = "1024"
vb.customize ["modifyvm", :id, "--vram", "64"]
vb.customize ["modifyvm", :id, "--clipboard", "bidirectional"]
vb.customize ["modifyvm", :id, "--audio", "none"]
end
#
# View the documentation for the provider you are using for more
# information on available options.
# Enable provisioning with a shell script. Additional provisioners such as
# Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
# documentation for more information about their specific syntax and use.
config.vm.provision "shell", inline: <<-SHELL
export DEBIAN_FRONTEND=noninteractive
# export LANGUAGE=en_US.UTF-8
# export LANG=en_US.UTF-8
# export LC_ALL=en_US.UTF-8
# locale-gen en_US.UTF-8
# dpkg-reconfigure locales
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
apt-get update
apt-get install -y mongodb-org ttf-anonymous-pro
systemctl enable mongod
systemctl start mongod
cd /tmp
wget -q https://download-test.robomongo.org/linux/robo3t-1.3.1-linux-x86_64-7419c406.tar.gz
tar xf robo3t-1.3.1-linux-x86_64-7419c406.tar.gz -C /opt/
mv /opt/robo3t-1.3.1-linux-x86_64-7419c406 /opt/robo3t
ln -s /opt/robo3t/bin/robo3t /usr/local/bin/robo3t
cat > /usr/share/applications/robo3t.desktop << EOL
[Desktop Entry]
Name=Robo 3T
Comment=Database shell for MongoDB
Encoding=UTF-8
Exec=robo3t
Icon=gksu-root-terminal
StartupNotify=true
Terminal=false
Type=Application
Categories=Utility;GTK;GNOME;
EOL
mkdir -p /vagrant/samples/dump/Samples
cd /vagrant/samples/dump/Samples
wget -q -nc https://github.com/SouthbankSoftware/dbkoda-data/raw/master/SampleCollections/dump/SampleCollections/samples_pokemon.bson
wget -q -nc https://github.com/SouthbankSoftware/dbkoda-data/raw/master/SampleCollections/dump/SampleCollections/samples_pokemon.metadata.json
cd /vagrant/samples
mongorestore
cat > /usr/share/lxterminal/lxterminal.conf << EOL
[general]
fontname=Anonymous Pro 14
selchars=-A-Za-z0-9,./?%&#:_
scrollback=1000
EOL
mkdir /home/vagrant/.config/lxterminal -p
cat > /home/vagrant/.config/lxterminal/lxterminal.conf << EOL
[general]
fontname=Anonymous Pro 14
selchars=-A-Za-z0-9,./?%&#:_
scrollback=1000
EOL
chown -R vagrant:vagrant /home/vagrant/.config
cat > /etc/lightdm/lightdm.conf.d/10-autologin.conf << EOL
[Seat:*]
autologin-guest = false
autologin-user = vagrant
autologin-user-timeout = 0
[SeatDefaults]
allow-guest = false
EOL
reboot
# wget https://downloads.mongodb.com/compass/mongodb-compass-community_1.17.0_amd64.deb
# dpkg -i mongodb-compass-community_1.17.0_amd64.deb
# git clone https://github.com/SouthbankSoftware/dbkoda-data.git
# cd dbkoda-data/SampleCollections
# mongorestore
# cd ../..
SHELL
end
<file_sep># SiSI - Lab 4
# Laboratorium 4. Baza danych
Do wykonania ćwiczeń z laboratorium potrzebujesz zainstalowanych aplikacji: VirtualBox i Vagrant. Obie aplikacje istnieją w wersjach dla systemów Linux, Windows, Mac.
Po pobraniu repozytorium uruchom maszynę vagranta: vagrant up. Gdy maszyna zakończy proces uruchamiania w wyświetlonym przez VirtualBox okinie maszyny wirtualnej zaloguj się na konto vagrant używając hasła vagrant.
W ramach ćwiczenia zapoznasz się z nierelacyjną bazą danych MongoDB. W maszynie zainstalowana została baza danych MongoDB, testowa baza danych oraz aplikacja Robo3T do zdalnej administracji.
## Łączenie się z bazą danych
1. Uruchom program Robo3T (sekcja Akcesoria).
2. Tylko przy pierwszym uruchomieniu: Zaakceptuj umowę licencyjną, nie musisz podawać swoich danych. Następnie w oknie *MongoDB Connections* utwórz (Create) nowe połączenie z bazą danych: adres serwera: localhost, port: 27017.
3. Po połączeniu z serwerem zobaczysz (pod nazwą połączenia) listę baz danych. Rozwiń bazę danych Samples, a w niej kolekcję samples_pokemon. Obejrzyj zawartość kolekcji w prawym panelu. Przy pomocy ikon w prawym górnym rogu panelu przełącz widok kolekcji na widok: tabeli (Table view), dokumentu (Document view) i drzewo (Tree view).
4. Kliknij na wybranym dokumencie i z menu podręcznego wybierz Edit document. Obejrzyj i zmodyfikuj właściwości wybranego pokemona.
5. W czarnym polu powyżej panelu zmodyfikuj kod w następujący sposób:
```javascript
db.getCollection('samples_pokemon').find({name:"Pikachu"})
```
Naciśnij klawisz F5 i obejrzyj efekt. Zobacz jakie pola ma znaleziony dokument. Zmodyfikuj zapytanie i uruchom je ponownie:
```javascript
db.getCollection('samples_pokemon').find({name:"Pikachu"},{_id:0,name:1,weight:1})
```
6. Kliknij dwukrotnie nazwę kolekcji `samples_pokemon` w lewym panelu aby przywrócić domyślny widok. Kliknij prawym klawiszem dowolny dokument, z menu podręcznego wybierz *Edit document* aby zmodyfikować właściwości pokemona. Przed zapamiętaniem zmian kliknij przycisk *Validate*,
7. Kliknij prawym klawiszem myszy kolekcję `samples_pokemon`, z menu podręcznego wybierz *Insert document*. Wstaw nowy dokument z opisem własnego pokemona.
## Konsola
1. Uruchom terminal: menu / System Tools / LXTerminal
2. Uruchom program `mongo`
3. Wyświetl dostępne bazy danych, wybierz bazę danych Sample i wyświetl kolekcje w bazie danych:
```
show dbs
use Sample
show collections
```
4. Wyświetl wszystkie dokumenty z kolekcji `samples_pokemon` oraz obejrzyj szczegółowe informacje o Pikachu:
```
db.samples_pokemon.find()
db.samples_pokemon.find({name:'Pikachu'})
db.samples_pokemon.find({name:'Pikachu'}).pretty()
```
5. Znajdź pokemony których nazwy zaczynają się od `Ven`
6. Znajdź pokemony które mają nazwy na litery od `A` do `C`
7. Znajdź pokemony których słabością jest `Rock`
8. Wyświetl tylko nazwy (zamiast całych dokumentów) pokemonów z poprzedniego zadania, następnie zmień ich kolejność na odwrotną niż alfabetyczna.
9. Wyświetl trzecią piątkę (od 10 do 15) pokemonów.
10. Znajdź 3 pokemony mające największą wartość `candy_count`.
10. Dodaj do dokumentu opisującego wybranego pokemona pole `color` z dowolną wartością. W polu `img` znajdziesz adres URL obrazka przedstawiającego konkretnego pokemona.
11. Wykorzystaj moduł agregacji, aby policzyć liczbę pokemonów o tym samym wzroście. Wskazówka: do grupowania wykorzystaj jako klucz `_id` pole `height`.
|
8f3143712243d0505f475d4b09faae069c435223
|
[
"Markdown",
"Ruby"
] | 2 |
Ruby
|
pwr-sisi/lab4
|
7070734030b14e0b62cae5caa29d10881b5e5424
|
b62f7198a8c3b8ff0cdced4ec76adb602a200de9
|
refs/heads/proper-3.6.1
|
<file_sep>package liquibase.integration.commandline;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.joran.spi.ConsoleTarget;
import ch.qos.logback.core.spi.FilterReply;
import liquibase.logging.LogType;
import org.slf4j.ILoggerFactory;
import org.slf4j.Marker;
/**
* Customized SLF4j appender which outputs user message and/or SQL to pipe from the log to the console.
*/
public class CommandLineOutputAppender extends ConsoleAppender {
private CommandLineOutputAppender.Mode mode = Mode.STANDARD;
public CommandLineOutputAppender(ILoggerFactory loggerContext, String target) {
setContext((LoggerContext) loggerContext);
setTarget(target);
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setPattern("%msg%n");
encoder.setContext((LoggerContext) loggerContext);
encoder.start();
setEncoder(encoder);
addFilter(new ModeFilter());
}
/**
* Sets the mode this command line logger should execute in.
*/
public void setMode(CommandLineOutputAppender.Mode mode) {
this.mode = mode;
}
protected class ModeFilter extends Filter {
@Override
public FilterReply decide(Object event) {
Marker marker = ((LoggingEvent) event).getMarker();
LogType logType = LogType.valueOf(marker.getName());
if (CommandLineOutputAppender.this.mode == Mode.STANDARD) {
if (logType == LogType.USER_MESSAGE && target.equals(ConsoleTarget.SystemOut)) {
return FilterReply.ACCEPT;
} else {
return FilterReply.DENY;
}
} else if (CommandLineOutputAppender.this.mode == Mode.PIPE_SQL) {
if (logType == LogType.USER_MESSAGE && target == ConsoleTarget.SystemErr) {
return FilterReply.ACCEPT;
} else if (logType == LogType.WRITE_SQL && target == ConsoleTarget.SystemOut) {
return FilterReply.ACCEPT;
} else {
return FilterReply.DENY;
}
}
return FilterReply.DENY;
}
}
public enum Mode {
/**
* "Normal" mode where only user-level messages are printed to stdout.
*/
STANDARD,
/**
* Command line is expecting to be output SQL to stdout that may be piped to a file.
* Any non-sql messages should be sent to stderr.
*/
PIPE_SQL,
/**
* Outputs all log messages to stdout
*/
FULL_LOG,
}
}
<file_sep>package liquibase;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.util.StringUtils;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Encapsulates logic for evaluating if a set of runtime contexts matches a context expression string.
*/
public class ContextExpression {
private HashSet<String> contexts = new HashSet<>();
private String originalString;
public ContextExpression() {
}
public ContextExpression(String... contexts) {
if (contexts.length == 1) {
parseContextString(contexts[0]);
} else {
for (String context : contexts) {
parseContextString(context.toLowerCase());
}
}
}
public ContextExpression(String contexts) {
parseContextString(contexts);
this.originalString = contexts;
}
public ContextExpression(Collection<String> contexts) {
if (contexts != null) {
for (String context : contexts) {
this.contexts.add(context.toLowerCase());
}
}
}
private void parseContextString(String contexts) {
contexts = StringUtils.trimToNull(contexts);
if (contexts == null) {
return;
}
for (String context : StringUtils.splitAndTrim(contexts, ",")) {
this.contexts.add(context.toLowerCase());
}
}
public boolean add(String context) {
return this.contexts.add(context.toLowerCase());
}
public Set<String> getContexts() {
return Collections.unmodifiableSet(contexts);
}
@Override
public String toString() {
if (originalString != null) {
return originalString;
}
return "(" + StringUtils.join(new TreeSet<String>(this.contexts), "), (") + ")";
}
/**
* Returns true if the passed runtime contexts match this context expression
*/
public boolean matches(Contexts runtimeContexts) {
if ((runtimeContexts == null) || runtimeContexts.isEmpty()) {
return true;
}
if (this.contexts.isEmpty()) {
return true;
}
for (String expression : this.contexts) {
if (matches(expression, runtimeContexts)) {
return true;
}
}
return false;
}
private boolean matches(String expression, Contexts runtimeContexts) {
if (runtimeContexts.isEmpty()) {
return true;
}
if (":TRUE".equals(expression.trim())) {
return true;
}
if (":FALSE".equals(expression.trim())) {
return false;
}
while (expression.contains("(")) {
Pattern pattern = Pattern.compile("(.*?)\\((.*?)\\)(.*)");
Matcher matcher = pattern.matcher(expression);
if (!matcher.matches()) {
throw new UnexpectedLiquibaseException("Cannot parse context pattern "+expression);
}
String parenExpression = matcher.group(2);
parenExpression = ":"+String.valueOf(matches(parenExpression, runtimeContexts)).toUpperCase();
expression = matcher.group(1)+" "+parenExpression+" "+matcher.group(3);
}
String[] orSplit = expression.split("\\s+or\\s+");
if (orSplit.length > 1) {
for (String split : orSplit) {
if (matches(split, runtimeContexts)) {
return true;
}
}
return false;
}
String[] andSplit = expression.split("\\s+and\\s+");
if (andSplit.length > 1) {
for (String split : andSplit) {
if (!matches(split, runtimeContexts)) {
return false;
}
}
return true;
}
boolean notExpression = false;
if (expression.startsWith("!")) {
notExpression = true;
expression = expression.substring(1);
}
for (String context : runtimeContexts.getContexts()) {
if (context.equalsIgnoreCase(expression)) {
return !notExpression;
}
}
return notExpression;
}
public boolean isEmpty() {
return (this.contexts == null) || this.contexts.isEmpty();
}
public static boolean matchesAll(Collection<ContextExpression> expressions, Contexts contexts) {
if ((expressions == null) || expressions.isEmpty()) {
return true;
}
if ((contexts == null) || contexts.isEmpty()) {
return true;
}
for (ContextExpression expression : expressions) {
if (!expression.matches(contexts)) {
return false;
}
}
return true;
}
}
<file_sep>package liquibase.integration.ant.logging;
import liquibase.logging.Logger;
import liquibase.logging.LoggerContext;
import liquibase.logging.LoggerFactory;
import liquibase.logging.core.NoOpLoggerContext;
import org.apache.tools.ant.Task;
/**
* An implementation of the Liquibase LogService that logs all messages to the given Ant task. This should only be used
* inside of Ant tasks.
*/
public final class AntTaskLogFactory implements LoggerFactory {
private AntTaskLogger logger;
public AntTaskLogFactory(Task task) {
logger = new AntTaskLogger(task);
}
@Override
public Logger getLog(Class clazz) {
return logger;
}
@Override
public LoggerContext pushContext(String key, Object object) {
return new NoOpLoggerContext();
}
@Override
public void close() {
}
}
<file_sep>package liquibase.change;
public @interface DatabaseChangeNote {
public String database() default "";
public String notes() default "";
}
<file_sep>package liquibase.logging;
/**
* Interface to class that does the actual logging.
* Instances will be created by {@link LoggerFactory} to know the class to log against.
*
* All log methods take a {@link LogType} to describe the type of message being logged.
*
* The hierarchy of log levels is:
* (finest) DEBUG < INFO < WARN < ERROR (coarsest)
*/
public interface Logger {
/**
* Log an error that occurred, using the {@link LogType#LOG} type.
*/
void severe(String message);
/**
* Log an error together with data from an error/exception, using the {@link LogType#LOG} type.
*/
void severe(String message, Throwable e);
/**
* Log an error that occurred.
*/
void severe(LogType target, String message);
/**
* Log an error together with data from an error/exception
*/
void severe(LogType target, String message, Throwable e);
/**
* Log a event the user should be warned about, using the {@link LogType#LOG} type.
*/
void warning(String message);
/**
* Log a event the user should be warned about together with data from an error/exception, using the {@link LogType#LOG} type.
*/
void warning(String message, Throwable e);
/**
* Log a event the user should be warned about
*/
void warning(LogType target, String message);
/**
* Log a event the user should be warned about together with data from an error/exception
*/
void warning(LogType target, String message, Throwable e);
/**
* Logs a general event that might be useful for the user, using the {@link LogType#LOG} type.
*/
void info(String message);
/**
* Logs a general event that might be useful for the user together with data from an error/exception, using the {@link LogType#LOG} type.
*/
void info(String message, Throwable e);
/**
* Logs a general event that might be useful for the user.
*/
void info(LogType logType, String message);
/**
* Logs a general event that might be useful for the user together with data from an error/exception
*/
void info(LogType target, String message, Throwable e);
/**
* Logs a debugging event to aid in troubleshooting, using the {@link LogType#LOG} type.
*/
void debug(String message);
/**
* Logs a debugging event to aid in troubleshooting together with data from an error/exception, using the {@link LogType#LOG} type.
*/
void debug(String message, Throwable e);
/**
* Logs a debugging event to aid in troubleshooting
*/
void debug(LogType target, String message);
/**
* Logs a debugging event to aid in troubleshooting together with data from an error/exception
*/
void debug(LogType target, String message, Throwable e);
}
<file_sep>package liquibase.logging;
/**
* LoggerContexts are used for tracking "nested diagnostic context" as well as tracking progress.
* It is up to the @{link {@link LoggerFactory} implementations to support them as they can.
*
* Implements {@link AutoCloseable} so they can be used nicely in a "try with resources" statement.
*/
public interface LoggerContext extends AutoCloseable {
/**
* Closes this LoggerContext and pops it off the LogFactory's context stack.
*/
@Override
void close();
/**
* Mark that some additional progress has been completed, like by adding a "." to output.
* Most non-UI loggers will not implement this.
*/
void showMoreProgress();
/**
* Mark that some progress within the context is the given percent complete.
* Most non-UI loggers will not implement this.
*/
void showMoreProgress(int percentComplete);
}
<file_sep>package liquibase.change.core;
import liquibase.CatalogAndSchema;
import liquibase.change.*;
import liquibase.changelog.ChangeSet;
import liquibase.database.AbstractJdbcDatabase;
import liquibase.database.Database;
import liquibase.database.core.MSSQLDatabase;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.datatype.DataTypeFactory;
import liquibase.datatype.LiquibaseDataType;
import liquibase.exception.DatabaseException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.exception.Warnings;
import liquibase.executor.ExecutorService;
import liquibase.executor.LoggingExecutor;
import liquibase.io.EmptyLineAndCommentSkippingInputStream;
import liquibase.logging.LogService;
import liquibase.logging.LogType;
import liquibase.logging.Logger;
import liquibase.resource.ResourceAccessor;
import liquibase.resource.UtfBomAwareReader;
import liquibase.snapshot.InvalidExampleException;
import liquibase.snapshot.SnapshotGeneratorFactory;
import liquibase.statement.BatchDmlExecutablePreparedStatement;
import liquibase.statement.ExecutablePreparedStatementBase;
import liquibase.statement.InsertExecutablePreparedStatement;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.InsertOrUpdateStatement;
import liquibase.statement.core.InsertSetStatement;
import liquibase.statement.core.InsertStatement;
import liquibase.structure.core.Column;
import liquibase.structure.core.DataType;
import liquibase.structure.core.Table;
import liquibase.util.BooleanParser;
import liquibase.util.StreamUtil;
import liquibase.util.StringUtils;
import liquibase.util.csv.CSVReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.*;
import static java.util.ResourceBundle.getBundle;
@DatabaseChange(name = "loadData",
description = "Loads data from a CSV file into an existing table. A value of NULL in a cell will be " +
"converted to a database NULL rather than the string 'NULL'.\n" +
"Lines starting with # (hash) sign are treated as comments. You can change comment pattern by " +
"specifying 'commentLineStartsWith' property in loadData tag." +
"To disable comments set 'commentLineStartsWith' to empty value'\n" +
"\n" +
"If the data type for a load column is set to NUMERIC, numbers are parsed in US locale (e.g. 123.45)." +
"\n" +
"Date/Time values included in the CSV file should be in ISO format " +
"http://en.wikipedia.org/wiki/ISO_8601 in order to be parsed correctly by Liquibase. Liquibase will " +
"initially set the date format to be 'yyyy-MM-dd'T'HH:mm:ss' and then it checks for two special " +
"cases which will override the data format string.\n" +
"\n" +
"If the string representing the date/time includes a '.', then the date format is changed to " +
"'yyyy-MM-dd'T'HH:mm:ss.SSS'\n" +
"If the string representing the date/time includes a space, then the date format is changed " +
"to 'yyyy-MM-dd HH:mm:ss'\n" +
"Once the date format string is set, Liquibase will then call the SimpleDateFormat.parse() method " +
"attempting to parse the input string so that it can return a Date/Time. If problems occur, " +
"then a ParseException is thrown and the input string is treated as a String for the INSERT command " +
"to be generated.",
priority = ChangeMetaData.PRIORITY_DEFAULT, appliesTo = "table",
since = "1.7")
public class LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> {
/**
* CSV Lines starting with that sign(s) will be treated as comments by default
*/
public static final String DEFAULT_COMMENT_PATTERN = "#";
private static final Logger LOG = LogService.getLog(LoadDataChange.class);
private static ResourceBundle coreBundle = getBundle("liquibase/i18n/liquibase-core");
private String catalogName;
private String schemaName;
private String tableName;
private String file;
private String commentLineStartsWith = DEFAULT_COMMENT_PATTERN;
private Boolean relativeToChangelogFile;
private String encoding;
private String separator = liquibase.util.csv.CSVReader.DEFAULT_SEPARATOR + "";
private String quotchar = liquibase.util.csv.CSVReader.DEFAULT_QUOTE_CHARACTER + "";
private List<LoadDataColumnConfig> columns = new ArrayList<>();
private Boolean usePreparedStatements;
/**
* Transform a value read from a CSV file into a string to be written into the database if the column type
* is not known.
*
* @param value the value to transform
* @return if the value is empty or the string "NULL" (case-insensitive), return the empty string.
* If not, the value "toString()" representation (trimmed of spaces left and right) is returned.
*/
protected static String getValueToWrite(Object value) {
if ((value == null) || "NULL".equalsIgnoreCase(value.toString())) {
return "";
} else {
return value.toString().trim();
}
}
// TODO: We can currently do this for INSERT operations, but not yet for UPDATE operations, so loadUpdateDataChange
// will overwrite this flag for now.
protected boolean hasPreparedStatementsImplemented() {
return true;
}
@Override
public boolean supports(Database database) {
return true;
}
@Override
public boolean generateRollbackStatementsVolatile(Database database) {
return true;
}
@DatabaseChangeProperty(
since = "3.0",
mustEqualExisting = "table.catalog"
)
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
@DatabaseChangeProperty(mustEqualExisting = "table.schema")
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
@DatabaseChangeProperty(
description = "Name of the table to insert data into",
requiredForDatabase = "all",
mustEqualExisting = "table"
)
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
@DatabaseChangeProperty(
description = "CSV file to load",
exampleValue = "com/example/users.csv",
requiredForDatabase = "all"
)
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public Boolean getUsePreparedStatements() {
return usePreparedStatements;
}
public void setUsePreparedStatements(Boolean usePreparedStatements) {
this.usePreparedStatements = usePreparedStatements;
}
public String getCommentLineStartsWith() {
return commentLineStartsWith;
}
public void setCommentLineStartsWith(String commentLineStartsWith) {
//if the value is null (not provided) we want to use default value
if (commentLineStartsWith == null) {
this.commentLineStartsWith = DEFAULT_COMMENT_PATTERN;
} else if ("".equals(commentLineStartsWith)) {
this.commentLineStartsWith = null;
} else {
this.commentLineStartsWith = commentLineStartsWith;
}
}
public Boolean isRelativeToChangelogFile() {
return relativeToChangelogFile;
}
public void setRelativeToChangelogFile(Boolean relativeToChangelogFile) {
this.relativeToChangelogFile = relativeToChangelogFile;
}
@DatabaseChangeProperty(
description = "Encoding of the CSV file (defaults to UTF-8)",
exampleValue = "UTF-8"
)
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
@DatabaseChangeProperty(exampleValue = ",")
public String getSeparator() {
return separator;
}
public void setSeparator(String separator) {
if ((separator != null) && "\\t".equals(separator)) {
separator = "\t";
}
this.separator = separator;
}
@DatabaseChangeProperty(exampleValue = "'")
public String getQuotchar() {
return quotchar;
}
public void setQuotchar(String quotchar) {
this.quotchar = quotchar;
}
@Override
public void addColumn(LoadDataColumnConfig column) {
columns.add(column);
}
@Override
@DatabaseChangeProperty(description = "Defines how the data should be loaded.", requiredForDatabase = "all")
public List<LoadDataColumnConfig> getColumns() {
return columns;
}
@Override
public void setColumns(List<LoadDataColumnConfig> columns) {
this.columns = columns;
}
@Override
public SqlStatement[] generateStatements(Database database) {
boolean databaseSupportsBatchUpdates = false;
try {
databaseSupportsBatchUpdates = database.supportsBatchUpdates();
} catch (DatabaseException e) {
throw new UnexpectedLiquibaseException(e);
}
CSVReader reader = null;
try {
reader = getCSVReader();
if (reader == null) {
throw new UnexpectedLiquibaseException("Unable to read file " + this.getFile());
}
String[] headers = reader.readNext();
if (headers == null) {
throw new UnexpectedLiquibaseException("Data file " + getFile() + " was empty");
}
// If we do not have a column list yet, take the column list we interpolated from the CSV headers
// earlier.
if (columns.isEmpty()) {
columns.addAll(getColumnsFromHeaders(headers));
}
// If we have an real JDBC connection to the database, ask the database for any missing column types.
try {
retrieveMissingColumnLoadTypes(columns, database);
} catch (DatabaseException e) {
throw new UnexpectedLiquibaseException(e);
}
List<ExecutablePreparedStatementBase> batchedStatements = new ArrayList<>();
boolean anyPreparedStatements = false;
String[] line;
// Start at '1' to take into account the header (already processed):
int lineNumber = 1;
boolean isCommentingEnabled = StringUtils.isNotEmpty(commentLineStartsWith);
List<SqlStatement> statements = new ArrayList<>();
while ((line = reader.readNext()) != null) {
lineNumber++;
if
((line.length == 0) || ((line.length == 1) && (StringUtils.trimToNull(line[0]) == null)) ||
(isCommentingEnabled && isLineCommented(line))
) {
//nothing interesting on this line
continue;
}
// Ensure each line has the same number of columns defined as does the header.
// (Failure could indicate unquoted strings with commas, for example).
if (line.length != headers.length) {
throw new UnexpectedLiquibaseException(
"CSV file " + getFile() + " Line " + lineNumber + " has " + line.length +
" values defined, Header has " + headers.length +
". Numbers MUST be equal (check for unquoted string with embedded commas)"
);
}
boolean needsPreparedStatement = false;
if (usePreparedStatements != null && usePreparedStatements) {
needsPreparedStatement = true;
}
List<ColumnConfig> columnsFromCsv = new ArrayList<>();
for (int i = 0; i < headers.length; i++) {
Object value = line[i];
String columnName = headers[i].trim();
ColumnConfig valueConfig = new ColumnConfig();
ColumnConfig columnConfig = getColumnConfig(i, headers[i].trim());
if (columnConfig != null) {
if ("skip".equalsIgnoreCase(columnConfig.getType())) {
continue;
}
// don't overwrite header name unless there is actually a value to override it with
if (columnConfig.getName() != null) {
columnName = columnConfig.getName();
}
valueConfig.setName(columnName);
if (columnConfig.getType() != null) {
if (columnConfig.getType().equalsIgnoreCase(LOAD_DATA_TYPE.BOOLEAN.toString())) {
if ("NULL".equalsIgnoreCase(value.toString())) {
valueConfig.setValue(null);
} else {
valueConfig.setValueBoolean(
BooleanParser.parseBoolean(value.toString().toLowerCase())
);
}
} else if (columnConfig.getType().equalsIgnoreCase(LOAD_DATA_TYPE.NUMERIC.toString())) {
if ("NULL".equalsIgnoreCase(value.toString())) {
valueConfig.setValue(null);
} else {
valueConfig.setValueNumeric(value.toString());
}
} else if
(
columnConfig.getType().toLowerCase().contains("date")
|| columnConfig.getType().toLowerCase().contains("time")
) {
if ("NULL".equalsIgnoreCase(value.toString())) {
valueConfig.setValue(null);
} else {
valueConfig.setValueDate(value.toString());
}
} else if (columnConfig.getType().equalsIgnoreCase(LOAD_DATA_TYPE.STRING.toString())) {
if ("NULL".equalsIgnoreCase(value.toString())) {
valueConfig.setValue(null);
} else {
valueConfig.setValue(value.toString());
}
} else if (columnConfig.getType().equalsIgnoreCase(LOAD_DATA_TYPE.COMPUTED.toString())) {
if ("NULL".equalsIgnoreCase(value.toString())) {
valueConfig.setValue(null);
} else {
liquibase.statement.DatabaseFunction function =
new liquibase.statement.DatabaseFunction(value.toString());
valueConfig.setValueComputed(function);
}
} else if (columnConfig.getType().equalsIgnoreCase(LOAD_DATA_TYPE.SEQUENCE.toString())) {
String sequenceName;
if ("NULL".equalsIgnoreCase(value.toString())) {
sequenceName = columnConfig.getDefaultValue();
if (sequenceName == null) {
throw new UnexpectedLiquibaseException(
"Must set a sequence name in the loadData column defaultValue attribute"
);
}
} else {
sequenceName = value.toString();
}
liquibase.statement.SequenceNextValueFunction function =
new liquibase.statement.SequenceNextValueFunction(sequenceName);
valueConfig.setValueComputed(function);
} else if (columnConfig.getType().equalsIgnoreCase(LOAD_DATA_TYPE.BLOB.toString())) {
if ("NULL".equalsIgnoreCase(value.toString())) {
valueConfig.setValue(null);
} else {
valueConfig.setValueBlobFile(value.toString());
needsPreparedStatement = true;
}
} else if (columnConfig.getType().equalsIgnoreCase(LOAD_DATA_TYPE.CLOB.toString())) {
if ("NULL".equalsIgnoreCase(value.toString())) {
valueConfig.setValue(null);
} else {
valueConfig.setValueClobFile(value.toString());
needsPreparedStatement = true;
}
} else {
throw new UnexpectedLiquibaseException(
String.format(coreBundle.getString("loaddata.type.is.not.supported"),
columnConfig.getType()
)
);
}
} else {
// columnConfig did not specify a type
valueConfig.setValue(getValueToWrite(value));
}
} else {
// No columnConfig found. Assume header column name to be the table column name.
if (columnName.contains("(") || (columnName.contains(")") && (database instanceof
AbstractJdbcDatabase))) {
columnName = ((AbstractJdbcDatabase) database).quoteObject(columnName, Column.class);
}
valueConfig.setName(columnName);
valueConfig.setValue(getValueToWrite(value));
}
columnsFromCsv.add(valueConfig);
}
// end of: iterate through all the columns of a CSV line
// Try to use prepared statements if any of the two following conditions apply:
// 1. There is no other option than using a prepared statement (e.g. in cases of LOBs)
// 2. The database supports batched statements (for improved performance) AND we are not in an
// "SQL" mode (i.e. we generate an SQL file instead of actually modifying the database).
if
(
(needsPreparedStatement ||
(databaseSupportsBatchUpdates &&
!(ExecutorService.getInstance().getExecutor(database) instanceof LoggingExecutor)
)
)
&& hasPreparedStatementsImplemented()
) {
anyPreparedStatements = true;
ExecutablePreparedStatementBase stmt =
this.createPreparedStatement(
database, getCatalogName(), getSchemaName(), getTableName(), columnsFromCsv,
getChangeSet(), getResourceAccessor()
);
batchedStatements.add(stmt);
} else {
InsertStatement insertStatement =
this.createStatement(getCatalogName(), getSchemaName(), getTableName());
for (ColumnConfig column : columnsFromCsv) {
String columnName = column.getName();
Object value = column.getValueObject();
if (value == null) {
value = "NULL";
}
insertStatement.addColumnValue(columnName, value);
}
statements.add(insertStatement);
}
// end of: will we use a PreparedStatement?
}
// end of: loop for every input line from the CSV file
if (anyPreparedStatements) {
// If we have only prepared statements and the database supports batching, let's roll
if (databaseSupportsBatchUpdates && statements.isEmpty() && (!batchedStatements.isEmpty())) {
return new SqlStatement[] {
new BatchDmlExecutablePreparedStatement(
database, getCatalogName(), getSchemaName(),
getTableName(), columns,
getChangeSet(), getResourceAccessor(),
batchedStatements)
};
} else {
return statements.toArray(new SqlStatement[statements.size()]);
}
} else {
if (statements.isEmpty()) {
// avoid returning unnecessary dummy statement
return new SqlStatement[0];
}
InsertSetStatement statementSet = this.createStatementSet(
getCatalogName(), getSchemaName(), getTableName()
);
for (SqlStatement stmt : statements) {
statementSet.addInsertStatement((InsertStatement) stmt);
}
if ((database instanceof MSSQLDatabase) || (database instanceof MySQLDatabase) || (database
instanceof PostgresDatabase)) {
List<InsertStatement> innerStatements = statementSet.getStatements();
if ((innerStatements != null) && (!innerStatements.isEmpty()) && (innerStatements.get(0)
instanceof InsertOrUpdateStatement)) {
//cannot do insert or update in a single statement
return statementSet.getStatementsArray();
}
// we only return a single "statement" - it's capable of emitting multiple sub-statements,
// should the need arise, on generation.
return new SqlStatement[]{statementSet};
} else {
return statementSet.getStatementsArray();
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (UnexpectedLiquibaseException ule) {
if ((getChangeSet() != null) && (getChangeSet().getFailOnError() != null) && !getChangeSet()
.getFailOnError()) {
LOG.info(LogType.LOG, "Change set " + getChangeSet().toString(false) +
" failed, but failOnError was false. Error: " + ule.getMessage());
return new SqlStatement[0];
} else {
throw ule;
}
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
// Do nothing
}
}
}
}
/**
* Iterate through the List of LoadDataColumnConfig and ask the database for any column types that we have
* no data type of.
* @param columns a list of LoadDataColumnConfigs to process
*/
@SuppressWarnings("CommentedOutCodeLine")
private void retrieveMissingColumnLoadTypes(List<LoadDataColumnConfig> columns, Database database) throws
DatabaseException {
boolean matched = false;
// If no column is missing type information, we are already done.
for (LoadDataColumnConfig c : columns) {
if (c.getType() == null) {
matched = true;
}
}
if (!matched) {
return;
}
/* The above is the JDK7 version of:
if (columns.stream().noneMatch(c -> c.getType() == null)) {
return;
}
*/
// Snapshot the database table
CatalogAndSchema catalogAndSchema = new CatalogAndSchema(getCatalogName(), getSchemaName());
catalogAndSchema = catalogAndSchema.standardize(database);
Table targetTable = new Table(catalogAndSchema.getCatalogName(), catalogAndSchema.getSchemaName(),
database.correctObjectName(getTableName(), Table.class));
Table snapshotOfTable;
try {
snapshotOfTable = SnapshotGeneratorFactory.getInstance().createSnapshot(
targetTable,
database);
} catch (InvalidExampleException e) {
throw new DatabaseException(e);
}
if (snapshotOfTable == null) {
LOG.warning(LogType.LOG, String.format(
coreBundle.getString("could.not.snapshot.table.to.get.the.missing.column.type.information"),
database.escapeTableName(
targetTable.getSchema().getCatalogName(),
targetTable.getSchema().getName(),
targetTable.getName())
));
return;
}
// Save the columns of the database table in a lookup table
Map<String, Column> tableColumns = new HashMap<>();
for (Column c : snapshotOfTable.getColumns()) {
tableColumns.put(c.getName(), c);
}
/* The above is the JDK7 version of:
snapshotOfTable.getColumns().forEach(c -> tableColumns.put(c.getName(), c));
*/
// Normalise the LoadDataColumnConfig column names to the database
Map<String, LoadDataColumnConfig> columnConfigs = new HashMap<>();
for (LoadDataColumnConfig c : columns) {
columnConfigs.put(
database.correctObjectName(c.getName(), Column.class),
c
);
}
/* The above is the JDK7 version of:
columns.forEach(c -> columnConfigs.put(
database.correctObjectName(c.getName(), Column.class),
c
));
*/
for (Map.Entry<String, LoadDataColumnConfig> entry : columnConfigs.entrySet()) {
if (!(entry.getValue().getType() == null)) {
continue;
}
LoadDataColumnConfig columnConfig = entry.getValue();
DataType dataType = tableColumns.get(entry.getKey()).getType();
if (dataType == null) {
LOG.warning(LogType.LOG, String.format(coreBundle.getString("unable.to.find.load.data.type"),
columnConfig.toString(), snapshotOfTable.toString()));
columnConfig.setType(LOAD_DATA_TYPE.STRING.toString());
} else {
LiquibaseDataType liquibaseDataType = DataTypeFactory.getInstance()
.fromDescription(dataType.toString(), database);
if (liquibaseDataType != null) {
columnConfig.setType(liquibaseDataType.getLoadTypeName().toString());
} else {
LOG.warning(LogType.LOG, String.format(coreBundle.getString("unable.to.convert.load.data.type"),
columnConfig.toString(), snapshotOfTable.toString(), liquibaseDataType.toString()));
}
}
}
/* The above is the JDK7 version of:
columnConfigs.entrySet().stream()
.filter(entry -> entry.getValue().getType() == null)
.forEach(entry -> {
LoadDataColumnConfig columnConfig = entry.getValue();
DataType dataType = tableColumns.get(entry.getKey()).getType();
if (dataType == null) {
LOG.warning(String.format(coreBundle.getString("unable.to.find.load.data.type"),
columnConfig.toString(), snapshotOfTable.toString() ));
columnConfig.setType(LOAD_DATA_TYPE.STRING.toString());
} else {
LiquibaseDataType liquibaseDataType = DataTypeFactory.getInstance()
.fromDescription(dataType.toString(), database);
if (liquibaseDataType != null) {
columnConfig.setType(liquibaseDataType.getLoadTypeName().toString());
} else {
LOG.warning(String.format(coreBundle.getString("unable.to.convert.load.data.type"),
columnConfig.toString(), snapshotOfTable.toString(), liquibaseDataType.toString()));
}
}
}
);
*/
}
/**
* If no columns (and their data types) are specified in the loadData change, we interpolate their names from
* the header columns of the CSV file.
* @param headers the headers of the CSV file
* @return a List of LoadDataColumnConfigs
*/
private List<LoadDataColumnConfig> getColumnsFromHeaders(String[] headers) {
ArrayList<LoadDataColumnConfig> result = new ArrayList<>();
int i=0;
for (String columnNameFromHeader : headers) {
LoadDataColumnConfig loadDataColumnConfig = new LoadDataColumnConfig();
loadDataColumnConfig.setIndex(i);
loadDataColumnConfig.setHeader(columnNameFromHeader);
loadDataColumnConfig.setName(columnNameFromHeader);
result.add(loadDataColumnConfig);
i++;
}
return result;
}
private boolean isLineCommented(String[] line) {
return StringUtils.startsWith(line[0], commentLineStartsWith);
}
@Override
public boolean generateStatementsVolatile(Database database) {
return true;
}
public CSVReader getCSVReader() throws IOException {
ResourceAccessor resourceAccessor = getResourceAccessor();
if (resourceAccessor == null) {
throw new UnexpectedLiquibaseException("No file resourceAccessor specified for " + getFile());
}
InputStream stream = StreamUtil.openStream(file, isRelativeToChangelogFile(), getChangeSet(), resourceAccessor);
if (stream == null) {
return null;
}
Reader streamReader;
if (getEncoding() == null) {
streamReader = new UtfBomAwareReader(stream);
} else {
streamReader = new UtfBomAwareReader(stream, getEncoding());
}
char quotchar;
if (StringUtils.trimToEmpty(this.quotchar).isEmpty()) {
// hope this is impossible to have a field surrounded with non ascii char 0x01
quotchar = '\1';
} else {
quotchar = this.quotchar.charAt(0);
}
if (separator == null) {
separator = liquibase.util.csv.CSVReader.DEFAULT_SEPARATOR + "";
}
return new CSVReader(streamReader, separator.charAt(0), quotchar);
}
protected ExecutablePreparedStatementBase createPreparedStatement(
Database database, String catalogName, String schemaName, String tableName,
List<ColumnConfig> columns, ChangeSet changeSet, ResourceAccessor resourceAccessor) {
return new InsertExecutablePreparedStatement(database, catalogName, schemaName, tableName, columns,
changeSet, resourceAccessor);
}
protected InsertStatement createStatement(String catalogName, String schemaName, String tableName) {
return new InsertStatement(catalogName, schemaName, tableName);
}
protected InsertSetStatement createStatementSet(String catalogName, String schemaName, String tableName) {
return new InsertSetStatement(catalogName, schemaName, tableName);
}
protected ColumnConfig getColumnConfig(int index, String header) {
for (LoadDataColumnConfig config : columns) {
if ((config.getIndex() != null) && config.getIndex().equals(index)) {
return config;
}
if ((config.getHeader() != null) && config.getHeader().equalsIgnoreCase(header)) {
return config;
}
if ((config.getName() != null) && config.getName().equalsIgnoreCase(header)) {
return config;
}
}
return null;
}
@Override
public ChangeStatus checkStatus(Database database) {
return new ChangeStatus().unknown("Cannot check loadData status");
}
@Override
public String getConfirmationMessage() {
return "Data loaded from " + getFile() + " into " + getTableName();
}
@Override
public CheckSum generateCheckSum() {
InputStream stream = null;
try {
stream = StreamUtil.openStream(file, isRelativeToChangelogFile(), getChangeSet(), getResourceAccessor());
if (stream == null) {
throw new UnexpectedLiquibaseException(getFile() + " could not be found");
}
stream = new EmptyLineAndCommentSkippingInputStream(stream, commentLineStartsWith);
return CheckSum.compute(getTableName() + ":" + CheckSum.compute(stream, /*standardizeLineEndings*/ true));
} catch (IOException e) {
throw new UnexpectedLiquibaseException(e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException ignore) {
// Do nothing
}
}
}
}
@Override
public Warnings warn(Database database) {
return null;
}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@SuppressWarnings("HardCodedStringLiteral")
public enum LOAD_DATA_TYPE {
BOOLEAN, NUMERIC, DATE, STRING, COMPUTED, SEQUENCE, BLOB, CLOB, SKIP
}
}
<file_sep>package liquibase.dbtest.oracle;
import liquibase.Liquibase;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.dbtest.AbstractIntegrationTest;
import liquibase.exception.LiquibaseException;
import liquibase.exception.ValidationFailedException;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeNotNull;
/**
* Integration test for Oracle Database, Version 11gR2 and above.
*/
public class OracleIntegrationTest extends AbstractIntegrationTest {
String indexOnSchemaChangeLog;
String viewOnSchemaChangeLog;
public OracleIntegrationTest() throws Exception {
super("oracle", DatabaseFactory.getInstance().getDatabase("oracle"));
indexOnSchemaChangeLog = "changelogs/oracle/complete/indexOnSchema.xml";
viewOnSchemaChangeLog = "changelogs/oracle/complete/viewOnSchema.xml";
// Respect a user-defined location for sqlnet.ora, tnsnames.ora etc. stored in the environment
// variable TNS_ADMIN. This allowes the use of TNSNAMES.
if (System.getenv("TNS_ADMIN") != null)
System.setProperty("oracle.net.tns_admin",System.getenv("TNS_ADMIN"));
}
@Override
protected boolean isDatabaseProvidedByTravisCI() {
// Seems unlikely to ever be provided by Travis, as it's not free
return false;
}
@Override
@Test
public void testRunChangeLog() throws Exception {
super.testRunChangeLog(); //To change body of overridden methods use File | Settings | File Templates.
}
@Test
public void indexCreatedOnCorrectSchema() throws Exception {
assumeNotNull(this.getDatabase());
Liquibase liquibase = createLiquibase(this.indexOnSchemaChangeLog);
clearDatabase();
try {
liquibase.update(this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
Statement queryIndex = ((JdbcConnection) this.getDatabase().getConnection()).getUnderlyingConnection().createStatement();
ResultSet indexOwner = queryIndex.executeQuery("SELECT owner FROM ALL_INDEXES WHERE index_name = 'IDX_BOOK_ID'");
assertTrue(indexOwner.next());
String owner = indexOwner.getString("owner");
assertEquals("LBCAT2", owner);
// check that the automatically rollback now works too
try {
liquibase.rollback( new Date(0),this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
}
@Test
public void viewCreatedOnCorrectSchema() throws Exception {
assumeNotNull(this.getDatabase());
Liquibase liquibase = createLiquibase(this.viewOnSchemaChangeLog);
clearDatabase();
try {
liquibase.update(this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
Statement queryIndex = ((JdbcConnection) this.getDatabase().getConnection()).getUnderlyingConnection().createStatement();
ResultSet indexOwner = queryIndex.executeQuery("SELECT owner FROM ALL_VIEWS WHERE view_name = 'V_BOOK2'");
assertTrue(indexOwner.next());
String owner = indexOwner.getString("owner");
assertEquals("LBCAT2", owner);
// check that the automatically rollback now works too
try {
liquibase.rollback( new Date(0),this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
}
@Test
public void smartDataLoad() throws Exception {
assumeNotNull(this.getDatabase());
Liquibase liquibase = createLiquibase("changelogs/common/smartDataLoad.changelog.xml");
clearDatabase();
try {
liquibase.update(this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
// check that the automatically rollback now works too
try {
liquibase.rollback( new Date(0),this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
}
@Override
@Test
public void testDiffExternalForeignKeys() throws Exception {
//cross-schema security for oracle is a bother, ignoring test for now
}
}<file_sep>package liquibase.sqlgenerator.core;
import liquibase.change.ColumnConfig;
import liquibase.change.ConstraintsConfig;
import liquibase.database.Database;
import liquibase.database.core.SQLiteDatabase;
import liquibase.exception.ValidationErrors;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.statement.core.AddColumnStatement;
import liquibase.structure.core.Index;
import java.util.Set;
/**
* Workaround for adding column on existing table for SQLite.
*
*/
public class AddColumnGeneratorSQLite extends AddColumnGenerator {
@Override
public ValidationErrors validate(AddColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
ValidationErrors validationErrors = super.validate(statement, database, sqlGeneratorChain);
validationErrors.checkRequiredField("tableName", statement);
validationErrors.checkRequiredField("columnName", statement);
return validationErrors;
}
@Override
public boolean generateStatementsIsVolatile(Database database) {
// need metadata for copying the table
return true;
}
@Override
public boolean supports(AddColumnStatement statement, Database database) {
return database instanceof SQLiteDatabase;
}
@Override
public Sql[] generateSql(final AddColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
// Workaround implemented by replacing a table with a new one (duplicate)
// with a new column added
Sql[] generatedSqls;
SQLiteDatabase.AlterTableVisitor alterTableVisitor = new SQLiteDatabase.AlterTableVisitor() {
@Override
public ColumnConfig[] getColumnsToAdd() {
ColumnConfig[] columnConfigs = new ColumnConfig[1];
ColumnConfig newColumn = new ColumnConfig();
newColumn.setName(statement.getColumnName());
newColumn.setType(statement.getColumnType());
newColumn.setAutoIncrement(statement.isAutoIncrement());
ConstraintsConfig constraintsConfig = new ConstraintsConfig();
if (statement.isPrimaryKey()) {
constraintsConfig.setPrimaryKey(true);
}
if (statement.isNullable()) {
constraintsConfig.setNullable(true);
}
if (statement.isUnique()) {
constraintsConfig.setUnique(true);
}
newColumn.setConstraints(constraintsConfig);
columnConfigs[0] = newColumn;
return columnConfigs;
}
@Override
public boolean copyThisColumn(ColumnConfig column) {
return !column.getName().equals(statement.getColumnName());
}
@Override
public boolean createThisColumn(ColumnConfig column) {
return true;
}
@Override
public boolean createThisIndex(Index index) {
return true;
}
};
generatedSqls = SQLiteDatabase.getAlterTableSqls(database, alterTableVisitor, statement.getCatalogName(),
statement.getSchemaName(), statement.getTableName());
return generatedSqls;
}
@Override
public int getPriority() {
return PRIORITY_DATABASE;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.proper.enterprise.platform</groupId>
<artifactId>liquibase-parent</artifactId>
<version>3.6.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Liquibase Parent Configuration</name>
<description>Liquibase is a tool for managing and executing database changes.</description>
<url>http://www.liquibase.org</url>
<organization>
<name>Liquibase.org</name>
<url>http://www.liquibase.org</url>
</organization>
<licenses>
<license>
<url>http://www.apache.org/licenses/LICENSE-2.0</url>
<name>Apache License, Version 2.0</name>
</license>
</licenses>
<developers>
<developer>
<id>nvoxland</id>
<name><NAME></name>
<email><EMAIL></email>
<url>http://nathan.voxland.net</url>
<organizationUrl>http://nathan.voxland.net/</organizationUrl>
<roles>
<role>architect</role>
<role>developer</role>
</roles>
<timezone>-6</timezone>
</developer>
</developers>
<modules>
<module>liquibase-core</module>
<module>liquibase-maven-plugin</module>
<module>liquibase-cdi</module>
<module>liquibase-integration-tests</module>
</modules>
<scm>
<connection>scm:git:<EMAIL>:liquibase/liquibase.git</connection>
<url>scm:git:<EMAIL>:liquibase/liquibase.git</url>
<developerConnection>scm:git:git@github.com:liquibase/liquibase.git</developerConnection>
<tag>HEAD</tag>
</scm>
<issueManagement>
<url>http://liquibase.jira.com/browse/CORE</url>
</issueManagement>
<ciManagement>
<system>CircleCI</system>
<url>https://circleci.com/gh/liquibase/liquibase/tree/master</url>
</ciManagement>
<distributionManagement>
<repository>
<id>nexus-releases</id>
<name>Nexus Release Repository</name>
<url>http://nexus.propersoft.cn:8081/repository/maven-releases/</url>
</repository>
<snapshotRepository>
<id>nexus-snapshots</id>
<name>Nexus Snapshot Repository</name>
<url>http://nexus.propersoft.cn:8081/repository/maven-snapshots/</url>
</snapshotRepository>
</distributionManagement>
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<jdk.version>1.7</jdk.version>
<maven.build.timestamp.format>E MMM dd hh:mm:ss zzz yyyy</maven.build.timestamp.format>
<build.timestamp>${maven.build.timestamp}</build.timestamp>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- To skip all tests, pass -Dmaven.test.skip=true on the command line. Alternatively, pass
-DskipITs=true to skip only the integration tests, or -DskipUTs=true to only skip the
unit tests. -->
<skipTests>false</skipTests>
<skipITs>${skipTests}</skipITs>
<skipUTs>${skipTests}</skipUTs>
<!-- Liquibase core dependencies and required jars versions -->
<org.springframework.version>4.3.8.RELEASE</org.springframework.version>
<snakeyaml.version>1.18</snakeyaml.version>
<!-- Liquibase SDK sdk/lib-sdk required libraries versions -->
<commons-cli.version>1.4</commons-cli.version>
<hamcrest-core.version>1.3</hamcrest-core.version>
<javax.servlet.version>3.0.0.v201112011016</javax.servlet.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<powermock.version>1.6.6</powermock.version>
<slf4j.version>1.7.25</slf4j.version>
<logback.version>1.2.3</logback.version>
<maven-surefire-plugin.version>2.20</maven-surefire-plugin.version>
<maven-failsafe-plugin.version>2.20</maven-failsafe-plugin.version>
<maven-enforcer-plugin.version>1.4.1</maven-enforcer-plugin.version>
<maven-assembly-plugin.version>3.1.0</maven-assembly-plugin.version>
<org.codehaus.groovy.version>2.4.11</org.codehaus.groovy.version>
<org.spockframework.version>1.1-groovy-2.4</org.spockframework.version>
<system-rules.version>1.16.0</system-rules.version>
<!-- Code coverage settings for the combination JaCoCo (offline instrumentation) and SONAR (cloud) -->
<jacoco.version>0.7.9</jacoco.version>
<jacoco.ut.execution.data.file>${project.basedir}/../target/coverage.exec</jacoco.ut.execution.data.file>
<jacoco.it.execution.data.file>${project.basedir}/../target/coverage-it.exec</jacoco.it.execution.data.file>
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
<sonar.organization>liquibase-core</sonar.organization>
<sonar.jacoco.reportPaths>../target/coverage.exec,../target/coverage-it.exec</sonar.jacoco.reportPaths>
<!-- JDBC driver versions -->
<derby.version>10.12.1.1</derby.version>
<mariadb-java-client.version>1.7.1</mariadb-java-client.version>
<mssql-jdbc.version>6.2.2.jre7</mssql-jdbc.version>
<hsqldb.version>2.3.5</hsqldb.version>
<mysql-connector-java.version>5.1.45</mysql-connector-java.version>
<jaybird.version>3.0.1</jaybird.version>
<postgresql.version>42.1.1.jre7</postgresql.version>
<com.h2database.version>1.4.196</com.h2database.version>
<sqlite-jdbc.version>3.19.3</sqlite-jdbc.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<!-- Apache Maven Plugins -->
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-plugin-testing-harness</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
<!-- JUnit & JUnit logging -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-rules</artifactId>
<version>${system-rules.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>1.1.8.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.7.1</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.1-b04</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.0-SP4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-verifier</artifactId>
<version>1.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${org.codehaus.groovy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>${org.spockframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-antunit</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>${commons-cli.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>${mockito.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${com.h2database.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<version>1.4.5</version>
</dependency>
<!-- JDBC drivers -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>${mariadb-java-client.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>${derby.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.firebirdsql.jdbc</groupId>
<artifactId>jaybird-jdk17</artifactId>
<version>${jaybird.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>${mssql-jdbc.version}</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>${sqlite-jdbc.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
<optimize>true</optimize>
<debug>true</debug>
<encoding>${project.build.sourceEncoding}</encoding>
<!-- <compilerArgument>-Xlint:deprecation</compilerArgument> -->
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<redirectTestOutputToFile>true</redirectTestOutputToFile>
<reportFormat>plain</reportFormat>
<printSummary>false</printSummary>
<skipTests>${skipUTs}</skipTests>
<systemPropertyVariables>
<jacoco-agent.destfile>${jacoco.ut.execution.data.file}</jacoco-agent.destfile>
</systemPropertyVariables>
<systemProperties>
<property>
<name>liquibase.defaultlogger.level</name>
<value>severe</value>
</property>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>${maven-enforcer-plugin.version}</version>
<executions>
<execution>
<id>enforce-java</id>
<phase>compile</phase>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireJavaVersion>
<version>${jdk.version}</version>
</requireJavaVersion>
<requireMavenVersion>
<version>3.0</version>
</requireMavenVersion>
<!-- Avoid the M.A.D. Gadget vulnerability in certain Apache commons-collections versions -->
<bannedDependencies>
<excludes>
<exclude>commons-collections:commons-collections:[3.0,3.2.1]</exclude>
<exclude>commons-collections:commons-collections:4.0</exclude>
</excludes>
</bannedDependencies>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.9.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.2</version>
<configuration>
<stagingRepository>/tmp/maven-snapshot</stagingRepository>
<mavenExecutorId>forked-path</mavenExecutorId>
</configuration>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
<configuration>
<skip>false</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>1.4</version>
<configuration>
<providerSelection>2.0</providerSelection>
<source />
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.codehaus.gmaven.runtime</groupId>
<artifactId>gmaven-runtime-2.0</artifactId>
<version>1.4</version>
<exclusions>
<exclusion>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.3.10</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>javacc-maven-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.3.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<version>2.6</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<profile>
<id>release-sign-artifacts</id>
<activation>
<property>
<name>performRelease</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<configuration>
<keyname>${liquibase.gpg.keyname}</keyname>
<passphraseServerId>${liquibase.gpg.keyname}</passphraseServerId>
</configuration>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>debian</id>
<activation>
<os>
<family>linux</family>
</os>
</activation>
<modules>
<module>liquibase-debian</module>
</modules>
</profile>
<profile>
<id>rpm</id>
<activation>
<os>
<family>linux</family>
</os>
</activation>
<modules>
<module>liquibase-rpm</module>
</modules>
</profile>
<profile>
<id>doclint-java8-disable</id>
<activation>
<jdk>[1.8,)</jdk>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
<quiet>true</quiet>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>pre-release-activities</id>
<build>
<plugins>
<!-- Search for and report dependencies that have known security vulnerabilities.
This is a must-have execution before every release! It is not included in every build
because the first execution can easily take 20 minutes. -->
<plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<version>1.4.5</version>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>sonar</id>
<!-- This is the JaCoCo setup offline instrumentation for all production classes. -->
<dependencies>
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>org.jacoco.agent</artifactId>
<classifier>runtime</classifier>
<version>${jacoco.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<executions>
<execution>
<id>unit-test-instrument</id>
<phase>process-classes</phase>
<goals>
<goal>instrument</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<id>mkdir-target</id>
<inherited>false</inherited>
<phase>generate-resources</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<!-- Safety -->
<mkdir dir="${project.build.directory}" />
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>liquibase-parent</artifactId>
<groupId>com.proper.enterprise.platform</groupId>
<version>3.6.1-SNAPSHOT</version>
</parent>
<artifactId>liquibase-integration-tests</artifactId>
<name>Liquibase Integration Tests</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-verifier</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-antunit</artifactId>
<scope>test</scope>
</dependency>
<!-- Main artifacts to be tested -->
<dependency>
<groupId>com.proper.enterprise.platform</groupId>
<artifactId>liquibase-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.proper.enterprise.platform</groupId>
<artifactId>liquibase-core</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<!-- JDBC drivers -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.firebirdsql.jdbc</groupId>
<artifactId>jaybird-jdk17</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemProperties>
<property>
<name>liquibase.defaultlogger.level</name>
<value>WARNING</value>
</property>
</systemProperties>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<configuration>
<skipTests>${skipTests}</skipTests>
<skipITs>${skipITs}</skipITs>
<redirectTestOutputToFile>true</redirectTestOutputToFile>
<systemPropertyVariables>
<jacoco-agent.destfile>${jacoco.it.execution.data.file}</jacoco-agent.destfile>
</systemPropertyVariables>
<systemProperties>
<property>
<name>liquibase.defaultlogger.level</name>
<value>WARNING</value>
</property>
</systemProperties>
<includes>
<include>**/*Test.java</include>
<include>**/*IntegrationTest.java</include>
<include>**/*Tests.java</include>
<include>**/IT*.java</include>
<include>**/*IT.java</include>
<include>**/*ITCase.java</include>
</includes>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>false</filtering>
</testResource>
<testResource>
<directory>src/test/filtered-resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
</build>
<profiles>
<profile>
<!-- The Oracle RDBMS JDBC driver is only available under a proprietary license from the Oracle
Maven repository. You have to register and accept a license agreement to gain access. The procedure
is described at
http://docs.oracle.com/middleware/1213/core/MAVEN/config_maven_repo.htm#MAVEN9012
-->
<id>oracle</id>
<dependencies>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>172.16.58.3</version>
</dependency>
</dependencies>
</profile>
<profile>
<!-- IBM DB2 drivers are not available at all in Maven repositories (due to their proprietary nature
and IBM not having a Maven repository that would contain these artifacts. The only way to get
these drivers is to extract the file db2jcc4.jar from a licensed software installation and
manually install them in your local (per-user) maven repository like this (you will need to replace
the path to the JAR and the actual version number of the JDBC driver!):
mvn install:install-file -DlocalRepositoryPath=lib -DcreateChecksum=true -Dpackaging=jar \
-Dfile=d:\IBM\SQLLIB\java\db2jcc4.jar -DgroupId=com.ibm.db2.jcc -DartifactId=db2jcc4 \
-Dversion=4.22.29
After that, adjust the driver version number in the following <dependency> tag.
-->
<id>db2</id>
<dependencies>
<dependency>
<groupId>com.ibm.db2.jcc</groupId>
<artifactId>db2jcc4</artifactId>
<version>4.22.29</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<!-- SAP (formerly: Sybase) j/Connect drivers are not available at all in Maven repositories (due to their
proprietary nature
and IBM not having a Maven repository that would contain these artifacts. The only way to get
these drivers is to extract the file jconn4.jar from a licensed software installation and
manually install them in your local (per-user) maven repository like this (you will need to replace
the path to the JAR and the actual version number of the JDBC driver!):
mvn install:install-file -DlocalRepositoryPath=lib -DcreateChecksum=true -Dpackaging=jar \
-Dfile=D:\sap\jConnect-16_0\classes\jconn4.jar -DgroupId=com.sybase.jdbc4.utils \
-DartifactId=jconnect -Dversion=16.0.SP02.PL05
One possible download source is the "SAP Store" at https://store.sap.com where you can search for the
term "SCN ADAPTIVE SERVER ENTERPRISE SDK" and "buy" it as "trial" software for € 0.00.
After that, adjust the driver version number in the following <dependency> tag.
-->
<id>sap-jconnect</id>
<dependencies>
<dependency>
<groupId>com.sybase.jdbc4.utils</groupId>
<artifactId>jconnect</artifactId>
<version>16.0.SP02.PL05</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
</profiles>
</project>
<file_sep>package liquibase.util;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.statement.DatabaseFunction;
import liquibase.statement.SequenceCurrentValueFunction;
import liquibase.statement.SequenceNextValueFunction;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* Various methods that make it easier to read and write object properties using the propertyName, instead of having
* to look up the correct reader/writer methods manually first. All methods in this class are static by nature.
*/
public class ObjectUtil {
/**
* Cache for the methods of classes that we have been queried about so far.
*/
private static Map<Class<?>, Method[]> methodCache = new HashMap<>();
/**
* For a given object, try to find the appropriate reader method and return the value, if set
* for the object. If the property is currently not set for the object, an
* {@link UnexpectedLiquibaseException} run-time exception occurs.
*
* @param object the object to examine
* @param propertyName the property name for which the value should be read
* @return the stored value
*/
public static Object getProperty(Object object, String propertyName)
throws UnexpectedLiquibaseException {
Method readMethod = getReadMethod(object, propertyName);
if (readMethod == null) {
throw new UnexpectedLiquibaseException(
String.format("Property [%s] was not found for object type [%s]", propertyName,
object.getClass().getName()
));
}
try {
return readMethod.invoke(object);
} catch (IllegalAccessException|InvocationTargetException e) {
throw new UnexpectedLiquibaseException(e);
}
}
/**
* Tried to determine the appropriate reader method for a given propertyName of a given object and, if found,
* returns the class of its return type.
* @param object the object to examine
* @param propertyName the property name whose reading method should be searched
* @return the class name of the return type if the reading method is found, null if it is not found.
*/
public static Class getPropertyType(Object object, String propertyName) {
Method readMethod = getReadMethod(object, propertyName);
if (readMethod == null) {
return null;
}
return readMethod.getReturnType();
}
/**
* Examines the given object's class and returns true if reader and writer methods both exist for the
* given property name.
* @param object the object for which the class should be examined
* @param propertyName the property name to search
* @return true if both reader and writer methods exist
*/
public static boolean hasProperty(Object object, String propertyName) {
return hasReadProperty(object, propertyName) && hasWriteProperty(object, propertyName);
}
/**
* Examines the given object's class and returns true if a reader method exists for the
* given property name.
* @param object the object for which the class should be examined
* @param propertyName the property name to search
* @return true if a reader method exists
*/
public static boolean hasReadProperty(Object object, String propertyName) {
return getReadMethod(object, propertyName) != null;
}
/**
* Examines the given object's class and returns true if a writer method exists for the
* given property name.
* @param object the object for which the class should be examined
* @param propertyName the property name to search
* @return true if a writer method exists
*/
public static boolean hasWriteProperty(Object object, String propertyName) {
return getWriteMethod(object, propertyName) != null;
}
/**
* Tries to guess the "real" data type of propertyValue by the given propertyName, then sets the
* selected property of the given object to that value.
* @param object the object whose property should be set
* @param propertyName name of the property to set
* @param propertyValue new value of the property, as String
*/
public static void setProperty(Object object, String propertyName, String propertyValue) {
Method method = getWriteMethod(object, propertyName);
if (method == null) {
throw new UnexpectedLiquibaseException (
String.format("Property [%s] was not found for object type [%s]", propertyName,
object.getClass().getName()
));
}
Class<?> parameterType = method.getParameterTypes()[0];
Object finalValue = propertyValue;
if (parameterType.equals(Boolean.class) || parameterType.equals(boolean.class)) {
finalValue = Boolean.valueOf(propertyValue);
} else if (parameterType.equals(Integer.class)) {
finalValue = Integer.valueOf(propertyValue);
} else if (parameterType.equals(Long.class)) {
finalValue = Long.valueOf(propertyValue);
} else if (parameterType.equals(BigInteger.class)) {
finalValue = new BigInteger(propertyValue);
} else if (parameterType.equals(BigDecimal.class)) {
finalValue = new BigDecimal(propertyValue);
} else if (parameterType.equals(DatabaseFunction.class)) {
finalValue = new DatabaseFunction(propertyValue);
} else if (parameterType.equals(SequenceNextValueFunction.class)) {
finalValue = new SequenceNextValueFunction(propertyValue);
} else if (parameterType.equals(SequenceCurrentValueFunction.class)) {
finalValue = new SequenceCurrentValueFunction(propertyValue);
} else if (Enum.class.isAssignableFrom(parameterType)) {
finalValue = Enum.valueOf((Class<Enum>) parameterType, propertyValue);
}
try {
method.invoke(object, finalValue);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new UnexpectedLiquibaseException(e);
} catch (IllegalArgumentException e) {
throw new UnexpectedLiquibaseException("Cannot call " + method.toString()
+ " with value of type " + finalValue.getClass().getName());
}
}
/**
* Sets the selected property of the given object to propertyValue. A run-time exception will occur if the
* type of value is incompatible with the reader/writer method signatures of the given propertyName.
* @param object the object whose property should be set
* @param propertyName name of the property to set
* @param propertyValue new value of the property
*/
public static void setProperty(Object object, String propertyName, Object propertyValue) {
Method method = getWriteMethod(object, propertyName);
if (method == null) {
throw new UnexpectedLiquibaseException (
String.format("Property [%s] was not found for object type [%s]", propertyName,
object.getClass().getName()
));
}
try {
if (propertyValue == null) {
setProperty(object, propertyName, null);
return;
}
if (!method.getParameterTypes()[0].isAssignableFrom(propertyValue.getClass())) {
setProperty(object, propertyName, propertyValue.toString());
return;
}
method.invoke(object, propertyValue);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new UnexpectedLiquibaseException(e);
} catch (IllegalArgumentException e) {
throw new UnexpectedLiquibaseException("Cannot call " + method.toString() + " with value of type "
+ (propertyValue == null ? "null" : propertyValue.getClass().getName()));
}
}
/**
* Tries to find the Java method to read a given propertyName for the given object.
* @param object the object whose class will be examined
* @param propertyName the property name for which the read method should be searched
* @return the {@link Method} if found, null in all other cases.
*/
private static Method getReadMethod(Object object, String propertyName) {
String getMethodName = "get" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH)
+ propertyName.substring(1);
String isMethodName = "is" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH)
+ propertyName.substring(1);
Method[] methods = getMethods(object);
for (Method method : methods) {
if ((method.getName().equals(getMethodName) || method.getName().equals(isMethodName)) && (method
.getParameterTypes().length == 0)) {
return method;
}
}
return null;
}
/**
* Tries to find the Java method to write a new value for a given propertyName to the given object.
* @param object the object whose class will be examined
* @param propertyName the property name for which the write method is to be searched
* @return the {@link Method} if found, null in all other cases.
*/
private static Method getWriteMethod(Object object, String propertyName) {
String methodName = "set"
+ propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1);
Method[] methods = getMethods(object);
for (Method method : methods) {
if (method.getName().equals(methodName) && (method.getParameterTypes().length == 1)) {
return method;
}
}
return null;
}
/**
* Determines the class of a given object and returns an array of that class's methods. The information might come
* from a cache.
* @param object the object to examine
* @return a list of methods belonging to the class of the object
*/
private static Method[] getMethods(Object object) {
Method[] methods = methodCache.get(object.getClass());
if (methods == null) {
methods = object.getClass().getMethods();
methodCache.put(object.getClass(), methods);
}
return methods;
}
}
<file_sep>package liquibase.integration.ant.logging;
import liquibase.logging.LogLevel;
import liquibase.logging.LogType;
import liquibase.logging.core.AbstractLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
/**
* An implementation of the Liquibase logger that logs to the given Ant task.
*/
public final class AntTaskLogger extends AbstractLogger {
private final Task task;
public AntTaskLogger(Task task) {
this.task = task;
}
@Override
public void severe(LogType target, String message) {
task.log(message, Project.MSG_ERR);
}
@Override
public void severe(LogType target, String message, Throwable e) {
task.log(message, e, Project.MSG_ERR);
}
@Override
public void warning(LogType target, String message) {
task.log(message, Project.MSG_WARN);
}
@Override
public void warning(LogType target, String message, Throwable e) {
task.log(message, e, Project.MSG_WARN);
}
@Override
public void info(LogType logType, String message) {
task.log(message, Project.MSG_INFO);
}
@Override
public void info(LogType target, String message, Throwable e) {
task.log(message, e, Project.MSG_INFO);
}
@Override
public void debug(LogType target, String message) {
task.log(message, Project.MSG_DEBUG);
}
@Override
public void debug(LogType target, String message, Throwable e) {
task.log(message, e, Project.MSG_DEBUG);
}
}
<file_sep>package liquibase.parser.core.xml;
import liquibase.logging.LogService;
import liquibase.logging.LogType;
import liquibase.logging.Logger;
import java.io.InputStream;
public class ContextClassLoaderXsdStreamResolver extends XsdStreamResolver {
private static final Logger LOGGER = LogService.getLog(ContextClassLoaderXsdStreamResolver.class);
@Override
public InputStream getResourceAsStream(String xsdFile) {
LOGGER.debug(LogType.LOG, "Trying to load resource from context classloader");
if (Thread.currentThread().getContextClassLoader() == null) {
LOGGER.debug(LogType.LOG, "Failed to load resource from context classloader");
return getSuccessorValue(xsdFile);
}
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdFile);
if(resourceAsStream == null){
LOGGER.debug(LogType.LOG, "Failed to load resource from context classloader");
return getSuccessorValue(xsdFile);
}
return resourceAsStream;
}
}
<file_sep>package liquibase.util;
public class SpringBootFatJar {
public static String getPathForResource(String path) {
String[] components = path.split("!");
if (components.length == 3) {
return String.format("%s%s", components[1].substring(1), components[2]);
} else {
return path;
}
}
}<file_sep>Liquibase
=========
@propersoft-cn customized version.
Now this branch has merged [liquibase-parent-3.6.1](https://github.com/liquibase/liquibase/tree/liquibase-parent-3.6.1) tag, and you can find diff [here](https://github.com/liquibase/liquibase/compare/liquibase-parent-3.6.1...propersoft-cn:proper-3.6.1).
How to build
------------
```
$ mvn -DskipTests clean package deploy
```
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package liquibase.util;
/**
*
* @author asales
*/
public class BooleanParser {
public static boolean parseBoolean(String s){
// test if we have a integer : if it's = 0 then return true, else return false
if(s == null){
return false;
}
try{
int tmp = Integer.parseInt(s.trim());
// it's an int !
if(tmp <= 0){
return false;
}
else{
return true;
}
}
catch(NumberFormatException ex){
// it's not a number
// cast it as a String
String test = s.trim().toLowerCase();
if("true".equalsIgnoreCase(test)){
return true;
}
else if("t".equalsIgnoreCase(test)){
return true;
}
else if("yes".equalsIgnoreCase(test)){
return true;
}
else if("y".equalsIgnoreCase(test)){
return true;
}
else if("false".equalsIgnoreCase(test)){
return false;
}
else if("f".equalsIgnoreCase(test)){
return false;
}
else if("no".equalsIgnoreCase(test)){
return false;
}
else if("n".equalsIgnoreCase(test)){
return false;
}
else{
return false;
}
}
}
}
<file_sep>package liquibase.logging.core;
import liquibase.configuration.AbstractConfigurationContainer;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.logging.LogLevel;
/**
* Configuration container for {@link liquibase.logging.LogService} properties
*/
public class DefaultLoggerConfiguration extends AbstractConfigurationContainer {
public static final String LOG_LEVEL = "level";
public DefaultLoggerConfiguration() {
super("liquibase.defaultlogger");
getContainer().addProperty(LOG_LEVEL, String.class)
.setDescription("Logging level")
.setDefaultValue("INFO");
}
public String getLogLevelName() {
return getContainer().getValue(LOG_LEVEL, String.class);
}
/**
* Transforms the strings DEBUG, INFO, WARNING, ERROR and OFF (case-insensitive) into the appropriate LogLevel.
* @return a value from the LogLevel enum
*/
public LogLevel getLogLevel() {
String logLevel = getLogLevelName();
if ("debug".equalsIgnoreCase(logLevel)) {
return LogLevel.DEBUG;
} else if ("info".equalsIgnoreCase(logLevel)) {
return LogLevel.INFO;
} else if ("warning".equalsIgnoreCase(logLevel)) {
return LogLevel.WARNING;
} else if ("error".equalsIgnoreCase(logLevel) || "severe".equalsIgnoreCase(logLevel)) {
return LogLevel.SEVERE;
} else if ("off".equalsIgnoreCase(logLevel)) {
return LogLevel.OFF;
} else {
throw new UnexpectedLiquibaseException("Unknown log level: " + logLevel+". Valid levels are: debug, info, warning, error, off");
}
}
public DefaultLoggerConfiguration setLogLevel(String name) {
getContainer().setValue(LOG_LEVEL, name);
return this;
}
}
<file_sep>package liquibase.dbtest.pgsql;
import liquibase.database.DatabaseFactory;
import liquibase.dbtest.AbstractIntegrationTest;
public class PostgreSQLIntegrationTest extends AbstractIntegrationTest {
public PostgreSQLIntegrationTest() throws Exception {
super("pgsql", DatabaseFactory.getInstance().getDatabase("postgresql"));
}
@Override
protected boolean isDatabaseProvidedByTravisCI() {
return true;
}
}
<file_sep>package liquibase.logging.core;
import liquibase.logging.LoggerContext;
import org.slf4j.MDC;
public class Slf4jLoggerContext implements LoggerContext {
private final String key;
public Slf4jLoggerContext(String key, Object value) {
MDC.put(key, String.valueOf(value));
this.key = key;
}
@Override
public void showMoreProgress() {
}
@Override
public void showMoreProgress(int percentComplete) {
}
@Override
public void close() {
MDC.remove(key);
}
}
<file_sep>CREATE user lbuser@localhost identified by 'lbuser';
CREATE DATABASE lbcat;
GRANT ALL PRIVILEGES ON lbcat.* TO 'lbuser'@'localhost';
CREATE DATABASE lbcat2;
GRANT ALL PRIVILEGES ON lbcat2.* TO 'lbuser'@'localhost';
FLUSH privileges;
<file_sep>-- Database: derby
-- Change Parameter: existingColumnName=state
-- Change Parameter: existingTableName=address
-- Change Parameter: newColumnName=abbreviation
-- Change Parameter: newTableName=state
CREATE TABLE "state" AS SELECT DISTINCT "state" AS abbreviation FROM address WHERE "state" IS NOT NULL;
ALTER TABLE "state" ALTER COLUMN abbreviation NOT NULL;
ALTER TABLE "state" ADD PRIMARY KEY (abbreviation);
ALTER TABLE address ADD CONSTRAINT FK_ADDRESS_STATE FOREIGN KEY ("state") REFERENCES "state" (abbreviation);
<file_sep>-- Database: sybase
-- Change Parameter: columnName=id
-- Change Parameter: tableName=person
ALTER TABLE [person] REPLACE [id] DEFAULT NULL;
<file_sep>package liquibase.sqlgenerator.core;
import liquibase.ContextExpression;
import liquibase.changelog.ChangeSet;
import liquibase.changelog.DatabaseChangeLog;
import liquibase.sdk.database.MockDatabase;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.AbstractSqlGeneratorTest;
import liquibase.sqlgenerator.MockSqlGeneratorChain;
import liquibase.statement.core.MarkChangeSetRanStatement;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class MarkChangeSetRanGeneratorTest extends AbstractSqlGeneratorTest<MarkChangeSetRanStatement> {
public MarkChangeSetRanGeneratorTest() throws Exception {
super(new MarkChangeSetRanGenerator());
}
@Override
protected MarkChangeSetRanStatement createSampleSqlStatement() {
return new MarkChangeSetRanStatement(new ChangeSet("1", "a", false, false, "c", null, null, null), ChangeSet.ExecType.EXECUTED);
}
@Test
public void generateSql_markRan() {
Sql[] sqls = new MarkChangeSetRanGenerator().generateSql(new MarkChangeSetRanStatement(new ChangeSet("1", "a", false, false, "c", null, null, null), ChangeSet.ExecType.MARK_RAN), new MockDatabase(), new MockSqlGeneratorChain());
assertEquals(1, sqls.length);
assertTrue(sqls[0].toSql(), sqls[0].toSql().contains("MARK_RAN"));
}
@Test
public void generateSqlWithComplexContext() {
String changeSetContextExpression = "changeSetContext1 AND changeSetContext2";
DatabaseChangeLog rootChangeLog = new DatabaseChangeLog();
rootChangeLog.setContexts(new ContextExpression("rootContext1 OR (rootContext2) AND (rootContext3)"));
DatabaseChangeLog childChangeLog = new DatabaseChangeLog();
childChangeLog.setContexts(new ContextExpression("childChangeLogContext1, childChangeLogContext2 AND childChangeLogContext3"));
childChangeLog.setIncludeContexts(new ContextExpression("includeContext1, includeContext2 AND includeContext3"));
childChangeLog.setParentChangeLog(rootChangeLog);
ChangeSet changeSet = new ChangeSet("1", "a", false, false, "c", changeSetContextExpression, null, childChangeLog);
Sql[] sqls = new MarkChangeSetRanGenerator().generateSql(new MarkChangeSetRanStatement(changeSet, ChangeSet.ExecType.EXECUTED), new MockDatabase(), new MockSqlGeneratorChain());
assertTrue(sqls[0].toSql(), sqls[0].toSql().contains("(childChangeLogContext1, childChangeLogContext2 AND childChangeLogContext3) AND " +
"(includeContext1, includeContext2 AND includeContext3) AND " +
"(rootContext1 OR (rootContext2) AND (rootContext3)) AND " +
"(changeSetContext1 AND changeSetContext2)"));
}
}
<file_sep>package liquibase.logging.core;
import liquibase.logging.LogLevel;
import liquibase.logging.LogType;
import org.slf4j.Logger;
import org.slf4j.MarkerFactory;
/**
* The default logger for Liquibase. Routes messages through SLF4j.
* The command line app uses logback, but this logger can use any slf4j binding.
*/
public class Slf4jLogger extends AbstractLogger {
private org.slf4j.Logger logger;
public Slf4jLogger(Logger logger) {
this.logger = logger;
}
@Override
public void severe(LogType target, String message) {
logger.error(MarkerFactory.getMarker(target.name()), message);
}
@Override
public void severe(LogType target, String message, Throwable e) {
logger.error(MarkerFactory.getMarker(target.name()), message, e);
}
@Override
public void warning(LogType target, String message) {
logger.warn(MarkerFactory.getMarker(target.name()), message);
}
@Override
public void warning(LogType target, String message, Throwable e) {
logger.warn(MarkerFactory.getMarker(target.name()), message, e);
}
@Override
public void info(LogType target, String message) {
logger.info(MarkerFactory.getMarker(target.name()), message);
}
@Override
public void info(LogType target, String message, Throwable e) {
logger.info(MarkerFactory.getMarker(target.name()), message, e);
}
@Override
public void debug(LogType target, String message) {
logger.debug(MarkerFactory.getMarker(target.name()), message);
}
@Override
public void debug(LogType target, String message, Throwable e) {
logger.debug(MarkerFactory.getMarker(target.name()), message, e);
}
}
<file_sep>package liquibase.logging;
/**
* Primary front-end for various Logging implementations by constructing the correct {@link Logger} version.
*
* This interface is also the front-end for managing Nested Diagnostic Contexts.
*/
public interface LoggerFactory {
/**
* Creates a logger for logging from the given class.
* Unlike most logging systems, there is no exposed getLog(String) method in order to provide more consistency in how logs are named.
*/
Logger getLog(Class clazz);
/**
* Creates a new {@link LoggerContext} and pushes it onto the stack.
* LoggerContexts are removed from the stack via the {@link LoggerContext#close()} method.
*/
LoggerContext pushContext(String key, Object object);
/**
* Closes the current log output file(s) or any other resources used by this LoggerFactory and its Loggers.
*/
void close();
}
<file_sep>package liquibase.logging.core;
import liquibase.logging.LoggerContext;
/**
* "Blank" context to use for {@link liquibase.logging.LoggerFactory} implementations that do not support nested contexts.
*/
public class NoOpLoggerContext implements LoggerContext {
@Override
public void close() {
}
@Override
public void showMoreProgress() {
}
@Override
public void showMoreProgress(int percentComplete) {
}
}
<file_sep>package liquibase.logging;
import liquibase.Liquibase;
/**
* @deprecated use {@link LogService} now.
* This class is kept for compatibility with Liquibase 3.5 and prior.
*/
public class LogFactory {
private static LogFactory instance;
public static synchronized void reset() {
instance = new LogFactory();
}
public static synchronized LogFactory getInstance() {
if (instance == null) {
instance = new LogFactory();
}
return instance;
}
/**
* Set the instance used by this singleton. Used primarily for testing.
*/
public static void setInstance(LogFactory instance) {
LogFactory.instance = instance;
}
public static Logger getLogger(String name) {
return getInstance().getLog(name);
}
public Logger getLog(String name) {
Class clazz;
try {
clazz = Class.forName(name);
} catch (ClassNotFoundException e) {
clazz = Liquibase.class;
}
return LogService.getLog(clazz);
}
public static Logger getLogger() {
return getInstance().getLog();
}
public Logger getLog() {
return LogService.getLog(Liquibase.class);
}
public void setDefaultLoggingLevel(String defaultLoggingLevel) {
LogService.getLog(getClass()).warning(LogType.LOG, "LogFactory.setDefaultLoggingLevel() is now a no-op.");
}
public void setDefaultLoggingLevel(LogLevel defaultLoggingLevel) {
LogService.getLog(getClass()).warning(LogType.LOG, "LogFactory.setDefaultLoggingLevel() is now a no-op.");
}
public static void setLoggingLevel(String defaultLoggingLevel) {
LogService.getLog(LogFactory.class).warning(LogType.LOG, "LogFactory.setLoggingLevel() is now a no-op.");
}
}
|
7e97bd64199d987913fa5a700eb74c3e49256d6c
|
[
"Markdown",
"Java",
"Maven POM",
"SQL"
] | 28 |
Java
|
propersoft-cn/liquibase
|
8054ac3fc00d4b81520685b9264d98fb04f261f1
|
59ca79d50b26760894d108aca05e28ee5b5eb055
|
refs/heads/master
|
<file_sep>SciPy Tutorial Code
===================
Introduction
-------------------
A collection of codes from SciPy Reference Guide Release 0.17.0<file_sep>"""
02_basic_functions/interaction_with_numpy.py
SciPy Reference Guide Release 0.17.0
- Basics functions
- Interaction with Nunpy
- Index Tricks
- Shape manipulation
- Polynomials
- Vectorizing functions (vectorize)
- Type handling
- Other useful functions
Creation time: 2016-04-13
Last modified: 2016-04-16
Email address: <EMAIL>
Platform: ubuntu 14.01 LTS, Python 3.4
"""
import numpy as np
from numpy import poly1d
# ===== Index Tricks =====
# np.mgrid, np.ogrid, np.r_, np.c_
a = np.concatenate(([3], [0]*5, np.arange(-1, 1.002, 2/9.0)))
print(a)
# The following method is recommended
a = np.r_[3, [0]*5, -1:1:10j]
print(a)
print(np.mgrid[0:5,0:5])
print(np.mgrid[0:5:4j,0:5:4j])
# ===== Shape manipulation =====
# ===== Polynomials =====
p = poly1d([3,4,5])
print(p)
print(p*p)
# integ(k) returns the indefinate integral of p with C = k
print(p.integ(k=6))
# deriv() returns the derivative of p
print(p.deriv())
print(p([4, 5]))
# ===== Vectorizing functions =====
def func(a, b):
if a > b:
return a - b
else:
return a + b
func_vec = np.vectorize(func)
# the vectorized function can be applied to lists
print(func_vec([0,3,6,9],[1,3,5,7]))
# ===== Type handling =====
print(np.cast['f'](np.pi))
# ===== Other useful functions =====
# angle unwrap linspace logspace factorial comb lena derivative
# select(condlist, choicelist, default=0)
x = np.r_[-2:3]
print(x)
print(np.select([x > 3, x >= 0], [0, x + 2]))
"""
Output:
$ python3 interaction_with_numpy.py
[ 3. 0. 0. 0. 0. 0. -1.
-0.77777778 -0.55555556 -0.33333333 -0.11111111 0.11111111 0.33333333
0.55555556 0.77777778 1. ]
[ 3. 0. 0. 0. 0. 0. -1.
-0.77777778 -0.55555556 -0.33333333 -0.11111111 0.11111111 0.33333333
0.55555556 0.77777778 1. ]
[[[0 0 0 0 0]
[1 1 1 1 1]
[2 2 2 2 2]
[3 3 3 3 3]
[4 4 4 4 4]]
[[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]]]
[[[ 0. 0. 0. 0. ]
[ 1.66666667 1.66666667 1.66666667 1.66666667]
[ 3.33333333 3.33333333 3.33333333 3.33333333]
[ 5. 5. 5. 5. ]]
[[ 0. 1.66666667 3.33333333 5. ]
[ 0. 1.66666667 3.33333333 5. ]
[ 0. 1.66666667 3.33333333 5. ]
[ 0. 1.66666667 3.33333333 5. ]]]
2
3 x + 4 x + 5
4 3 2
9 x + 24 x + 46 x + 40 x + 25
3 2
1 x + 2 x + 5 x + 6
6 x + 4
[ 69 100]
[1 6 1 2]
3.1415927410125732
[-2 -1 0 1 2]
[0 0 2 3 4]
"""<file_sep>"""
01_introduction/organization_and_documentation.py
SciPy Reference Guide Release 0.17.0
Introduction
Creation time: 2016-04-13
Last modified: 2016-04-13
Email address: <EMAIL>
Platform: ubuntu 14.01 LTS, Python 3.4
"""
# Heghly recommended conventions
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
"""
subpackages: cluster, constants, fftpack, integrate,
interpolate, io, linalg, ndimage, odr,
optimize, signal, sparse, spatial, special,
stats, weave
"""
from scipy import linalg, optimize
# np.info() -- numpy/scipy-specific help system
print(np.info(optimize.fmin))<file_sep>"""
03_special_functions/scipy_special.py
SciPy Reference Guide Release 0.17.0
- Special functions
- Bessel functions of real order
Creation time: 2016-04-16
Last modified: 2016-04-16
Email address: <EMAIL>
Platform: ubuntu 14.01 LTS, Python 3.4
"""
"""
scipy.special
airy, elliptic, bessel, gamma, beta, hypergeometric,
parabolic cylinder, mathieu, spheroidal wave, struve, kelvin
"""
# ===== Bessel functions of real order =====
# x^2 \frac{d^2y}{dx^2} + x \frac{dy}{dx} + (x^2 - \alpha^2) y = 0
import numpy as np
from scipy import special
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
def drumhead_height(n, k, distance, angle, t):
kth_zero = special.jn_zeros(n, k)[-1]
return np.cos(t) * np.cos(n*angle) * special.jn(n, distance*kth_zero)
theta = np.r_[0:2*np.pi:50j]
radius = np.r_[0:1:50j]
x = np.array([r * np.cos(theta) for r in radius])
y = np.array([r * np.sin(theta) for r in radius])
z = np.array([drumhead_height(1, 1, r, theta, 0.5) for r in radius])
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.jet)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
|
b253dec8edad05047d9cf3c60b0c8893ea59a1b2
|
[
"Markdown",
"Python"
] | 4 |
Markdown
|
WaizungTaam/SciPy-Tutorial-Code
|
c320646772976963f79b56771ba4476a84a2ab87
|
31024a6243821956c506f3f320d8abd9e5338652
|
refs/heads/main
|
<repo_name>Michaelllllll25/Python-Learn<file_sep>/Strings.py
message = "Hello" # String
message2 = 2 # Not a string
print("Hello world")
print(message)
print("#########################")
a = """Bobby and the people
went into the shop to buy a
pair of Jordan 1 Low's"""
print(a)
print("#########################")
b = "Hello World"
print(len(b)) # Counts length of words
print(b[0]) # Prints first character (H)
print(b[1]) # Prints second character (e)
print(b[0:5]) # Prints first charcter up to but not including the fith (Hello)
print(b[6:]) # Prints "World"
# ^^^^^^^Slicing
print("#########################")
c = "Hello World"
print(c.lower()) # Prnts string in lower case
print(c.upper()) # Prnts string in upper case
print(c.count('o')) # Counts number of characters in the string
print(c.find('World')) # Finds the word in the string, will return the index where the character can be found (worlds starts at 6th character)
print("#########################")
d = "Hello World"
new_d = d.replace('World', 'Universe') # Used to replace
print(new_d)
print("#########################")
greeting = "Hello"
name = "Michael"
e = greeting + ', ' + name + '. Welcome!' # Concatination
print(e)
print("#########################")
greeting1 = "Hello"
name1 = "Michael"
f = '{}, {}. Welcome!'.format(greeting1, name) # Format words into same sentence
print(f)
g = f'{greeting}, {name.upper()}. Welcome!' # Formating using f-string
print(g)
print("#########################")
<file_sep>/Loops.py
# 4.1. Loop with a counter variable
i = 0
while i < 5:
print("hello") # will priont hi 5 times
i += 1
# --------------
# 4.2. Loop with an accumulator variable
total = 0 # accumulator
i = 1 # counter
while i <= 10:
total += i # add to the accumulator
i += 1 # increase the counter
# --------------
# 4.3. break
i = 0
while i <= 10:
print(i)
if i == 5:
break
i += 1
# --------------
#4.4. continue
i = 0
while i <= 10:
if i == 5 or i == 7:
i += 1
continue
print(i)
i += 1
# --------------
# 4.5. Get user input in a loop
i = 0 # counter
total = 0 # accumulator
while i < 5: # set to loop 5 times
num = int(input("Enter number: "))
total += num
i += 1
print(total)
# --------------
# 4.6. Quit loop with sentinel value
total = 0
while True:
num = int(input("Enter number, -1 to stop: "))
if num == -1:
break
total += num
print(total)
# --------------
# 4.7. Loop through a string (while)
name = "Mr. Gallo"
i = 0
while i < len(name):
print(i, name[i])
i += 1
# --------------
# 4.8. Loop through a list (while)
friends = ["Frank", "Sally", "Jimbo"]
i = 0
while i < len(friends):
print(i, friends[i])
i += 1
# --------------
# 4.9. Loop through a string (for)
name = "Mr. Gallo"
for character in name:
print(character)
# --------------
# 4.10. Loop through a list (for)
friend_list = ["Frank", "Sally", "Jimbo"]
# For every friend in my friend list
# print the friend
for friend in friend_list:
print(friend)
# --------------
# 4.11. Loop using range
# while loop print 50-100
i = 50
while i <= 100:
print(i)
i += 1
# range(start, end)... Goes up to, but, doesn't include the end
for num in range(50, 101):
print(num)
# while loop print 1-25 by 5
i = 0
while i <= 25:
print(i)
i += 5
# range(start, end, step)
for num in range(0, 26, 5):
print(num)
# --------------
# 4.12. Loop using enumerate
name = "Mr. Gallo"
for i, character in enumerate(name):
print(i, character)
# --------------
# 4.13. String building and filtering
my_string = ""
for n in range(65, 70):
my_string += str(n) + " "
print(my_string) # "65 66 67 68 69 "
# --------------
nums = [1, 6, -4, 1, -5, 1]
only_ones = []
for n in nums:
if n == 1:
only_ones.append(n)
print(only_ones) # [1, 1, 1]
<file_sep>/functions.py
def hello_func():
print("Hello Function!")
hello_func() # need this line to run the code
# --------------
def hello(greeting, name):
return f"{greeting} {name} "
print(hello('greeting', name = 'mike'))
# --------------
name = input("Name: ")
age = input("Age: ")
def name_age(name: str, age: int) -> str:
return name + age
print(name_age(name, age))
# or
result = name_age(name, age)
print(result)
# --------------
num_1 = int(input("Num1: "))
num_2 = int(input("Num2: "))
def average(num_1: int, num_2: int) -> float:
return (num_1 + num_2) / 2
print(average(num_1, num_2))
# --------------
num_1 = int(input("Num 1: "))
num_2 = int(input("Num 2: "))
num_3 = int(input("Num 3: "))
def largest(num_1, num_2, num_3):
if (num_1 > num_2) and (num_1 > num_3):
largest_num = num_1
elif (num_2 > num_1) and (num_2 > num_3):
largest_num = num_1
else:
largest_num = num_3
print("The largest number is ", num_1)
largest(num_1, num_2, num_3)
<file_sep>/Lists.py
######################################### 5.1. Creating a list
empty_list = []
empty_list
#[]
another_empty_list = list()
another_empty_list
#[]
odd_nums = [1, 3, 5, 7, 9]
odd_nums
#[1, 3, 5, 7, 9]
my_friends = ["Jim", "Joe", "Sally"]
my_friends
#['Jim', 'Joe', 'Sally']
vowels = ['a', 'e', 'i', 'o', 'u']
vowels
#['a', 'e', 'i', 'o', 'u']
vowels = list("aeiou")
vowels
#['a', 'e', 'i', 'o', 'u']
letters = list("hello")
letters
#['h', 'e', 'l', 'l', 'o']
friends = "<NAME>".split(" ")
friends
#['Jim', 'Sally', 'Joe']
friends = "Jim, Sally, Joe".split(", ")
friends
#['Jim', 'Sally', 'Joe']
######################################### 5.2. Accessing list elements
marks = [6, 2, 8, 5, 0, 4, 1] # Initalizing a list
marks[0] # Access single element by index
#6
marks[3]
#5
######################################### 5.3. Slicing a list
marks = [6, 2, 8, 5, 0, 4, 1]
marks[3:5] # Slice list from index 3 up to (not including) 5
#[5, 0]
marks[:5] # Slice list from beginning up to (not including) 5
#[6, 2, 8, 5, 0]
marks[3:] # Slice list from 3 to the end
#[5, 0, 4, 1]
marks[:-1] # Slice list from beginning to (not including) the last element
#[6, 2, 8, 5, 0, 4]
marks[:] # Slice from beginning to the end (copy whole list)
#[6, 2, 8, 5, 0, 4, 1]
marks[::2] # Slice from beginning to the end stepping by 2
#[6, 8, 0, 1]
marks[::-1] # Slice from beginning to the end backwards
#[1, 4, 0, 5, 8, 2, 6]
######################################### 5.4. Appending elements to a list
friends = ['Jim', 'Sally', 'Lucy']
friends.append("ABC")
friends
#['Jim', 'Sally', 'Lucy', 'ABC']
friends.append("Bob")
friends
#['Jim', 'Sally', 'Lucy', 'ABC', 'Bob']
######################################### 5.5. Reassign element at list index
friends = ['Jim', 'Sally', 'Lucy', 'ABC', 'Bob']
friends[2] = "Abigail"
friends
#['Jim', 'Sally', 'Abigail', 'ABC', 'Bob']
######################################### 5.6. Remove list element using .remove
friends = ['Jim', 'Sally', 'Lucy', 'ABC', 'Bob']
friends.remove("Lucy")
friends
#['Jim', 'Sally', 'ABC', 'Bob']
######################################### 5.7. Remove list element at index using del
friends = ['Jim', 'Sally', 'ABC', 'Bob']
del friends[2]
friends
#['Jim', 'Sally', 'Bob']
|
d75761932a3124e208bce24ce5ad08d04301013a
|
[
"Python"
] | 4 |
Python
|
Michaelllllll25/Python-Learn
|
1d03b301a4b6d39c1ffcac3a3d75887c04463cfe
|
88cd532363f18760bb2679bf0d1c19f3524edcc5
|
refs/heads/master
|
<repo_name>KiarashE/fibonaccis<file_sep>/Main.java
import java.math.BigInteger;
import java.util.HashMap;
public class Main {
private static HashMap<BigInteger, BigInteger> stash = new HashMap<>();
private static BigInteger ZERO = BigInteger.ZERO;
private static BigInteger ONE = BigInteger.ONE;
public static void main(String[] args) {
/**
* Either assign value as parameter to the main method "java Main x y z..." for
* list of results or assign variable n in the code for single result
*/
int n = 6;
if(args.length > 0){
for(int i = 0; i < args.length; i++){
System.out.println(args[i] + " - " + getValue(Integer.parseInt(args[i])));
}
} else {
System.out.println(getValue(n));
}
}
public static BigInteger getValue(int n){
return getBigValue(BigInteger.valueOf(n));
}
public static BigInteger getBigValue(BigInteger n) {
if (n.equals(ZERO))
return ZERO;
if (n.equals(ONE))
return ONE;
if (stash.containsKey(n))
return stash.get(n);
BigInteger n2 = n.shiftRight(1);
BigInteger n2Value = getBigValue(n2);
if (n.testBit(0)) {
BigInteger n2PlusOne = n2.add(ONE);
BigInteger n3Value = getBigValue(n2PlusOne);
BigInteger n2Square = n2Value.pow(2);
BigInteger n3Square = n3Value.pow(2);
BigInteger outcome = n2Square.add(n3Square);
stash.put(n, outcome);
return outcome;
}
else {
BigInteger n2MinusOne = n2.subtract(ONE);
BigInteger n3Value = getBigValue(n2MinusOne);
BigInteger n3Multiplied2 = n3Value.add(n3Value);
BigInteger n2PlusN3 = n2Value.add(n3Multiplied2);
BigInteger outcome = n2Value.multiply(n2PlusN3);
stash.put(n, outcome);
return outcome;
}
}
}
|
715daa00ef82c44c4b41201c6614917787c8ddac
|
[
"Java"
] | 1 |
Java
|
KiarashE/fibonaccis
|
636eb6894ccd7e3d215eb64715eae2d9e59fa423
|
912120320a56be1efaccb352ea94f3485a297c5a
|
refs/heads/master
|
<repo_name>keefmarshall/camunda-demo<file_sep>/src/main/java/org/hmcts/camunda/api/FeignClientConfig.java
package org.hmcts.camunda.api;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import feign.Logger;
import feign.codec.Decoder;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignFormatterRegistrar;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Configuration
@EnableFeignClients
public class FeignClientConfig {
public final static String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
/**
* Custom decoder using the ObjectMapper (from below)
*/
@Bean
public Decoder feignDecoder() {
MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(objectMapper());
return new ResponseEntityDecoder(new SpringDecoder(() ->
new HttpMessageConverters(jacksonConverter)
));
}
/**
* Object mapper with Java Time support
*/
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
// For some reason the ISO format used by Camunda is not translated automatically - not sure why
// as it looks like valid ISO8601 to me. However, we can fix it using a custom Deserializer - just
// be aware this will apply to all Feign clients in this application unless more work is done.
JavaTimeModule timeModule = new JavaTimeModule();
timeModule.addDeserializer(LocalDateTime.class, localDateTimeDeserializer());
timeModule.addSerializer(LocalDateTime.class, localDateTimeSerializer());
mapper.registerModule(timeModule);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper;
}
private LocalDateTimeDeserializer localDateTimeDeserializer() {
return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_PATTERN));
}
private LocalDateTimeSerializer localDateTimeSerializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_PATTERN));
}
/**
* Attempting to get dates formatted correctly in GET parameters attached to Feign requests
* see: https://github.com/spring-cloud/spring-cloud-openfeign/issues/104#issuecomment-232330995
*
* NB Feign request URLs use this for formatting, NOT the above ones which are used for JSON ser/deser
* (e.g. creating an application/json POST body of a request, or parsing a JSON response)
*
* @return
*/
@Bean
public FeignFormatterRegistrar localDateFeignFormatterRegistrar() {
// NB Java 8 lambda syntactic sugar for anonymous classes with only one method
return formatterRegistry -> {
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.setDateTimeFormatter(DateTimeFormatter.ofPattern(DATE_PATTERN));
registrar.registerFormatters(formatterRegistry);
};
}
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.BASIC;
}
}
<file_sep>/src/main/java/org/hmcts/camunda/api/HistoryService.java
package org.hmcts.camunda.api;
import org.hmcts.camunda.api.model.Activity;
import org.hmcts.camunda.api.model.Process;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.time.ZonedDateTime;
import java.util.List;
@FeignClient("camunda")
public interface HistoryService {
@RequestMapping("/engine-rest/history/process-instance")
List<Process> getProcessHistory();
@RequestMapping("/engine-rest/history/process-instance")
List<Process> getProcessHistoryByKey(
@RequestParam String processDefinitionKey
);
@RequestMapping("/engine-rest/history/process-instance")
List<Process> getProcessHistoryByKeySinceDate(
@RequestParam String processDefinitionKey,
@RequestParam ZonedDateTime startedAfter
);
/**
* Get all activities associated with a single process instance
* @param processInstanceId
* @return
*/
@RequestMapping("/engine-rest/history/activity-instance")
List<Activity> getProcessInstanceActivities(
@RequestParam String processInstanceId
);
/**
* Get all finished activities associated with a single process instance
* @param processInstanceId
* @return
*/
@RequestMapping("/engine-rest/history/activity-instance?finished=true")
List<Activity> getProcessInstanceFinishedActivities(
@RequestParam String processInstanceId
);
/**
* Get finished, completeScope activity/activities associated with a single process instance
* Should ideally return just a single Activity representing the end state but there might
* be edge cases with more than one completeScope activity depending on the flow definition
*
* @param processInstanceId
* @return
*/
@RequestMapping("/engine-rest/history/activity-instance?finished=true&completeScope=true")
List<Activity> getProcessInstanceCompleteActivities(
@RequestParam String processInstanceId
);
}
<file_sep>/src/main/java/org/hmcts/camunda/api/model/Activity.java
package org.hmcts.camunda.api.model;
import java.time.LocalDateTime;
/**
* Data object, deliberately haven't implemented setters/getters - use Lombok
* (or better, Kotlin!) if required.
*/
public class Activity {
public String id;
public String activityId;
public String activityName;
public String activityType;
public boolean canceled;
public boolean completeScope;
public String processInstanceId;
public LocalDateTime startTime;
public LocalDateTime endTime;
public int duration;
@Override
public String toString() {
return String.format("%s : %s - %s %s", activityType, startTime, endTime, completeScope);
}
}
<file_sep>/README.md
Camunda demo
============
Some unstructured code for playing with various aspects of Camunda. This
is unlikely to make any sense without a walkthrough from me, as it's just
stuff I was playing with at the time.
There are some sample actions, which tie into the Camunda BPMN documents
you'll find in the main/resources folder.
This was all written in Spring 2019 (Feb/Mar/April), so may be out of date by now.
TestAction
----------
Just an implementation of the Camunda documented example.
poc
---
A start at a practical attempt to implement something that might be useful within the
context of the project I was working on at the time.
api
---
An exploratory attempt to use the Camunda history API to find
out about processes that are/have run, in the api package folder.
Running Notes
-------------
All the code assumes you have a local instance of Camunda running -
I used the Docker image (and corresponding Docker PostgreSQL)
<file_sep>/src/main/java/org/hmcts/camunda/api/model/Process.java
package org.hmcts.camunda.api.model;
import java.time.LocalDateTime;
public class Process {
public String id;
public String processDefinitionKey;
public String processDefinitionName;
public LocalDateTime startTime;
public LocalDateTime endTime;
public Long durationInMillis;
public String state;
@Override
public String toString() {
return String.format("%s : %s - %s %s", processDefinitionKey, startTime, endTime, state);
}
}
|
d8b8095eb85bb09a7e7c2ef5c99758360ca67ca9
|
[
"Markdown",
"Java"
] | 5 |
Java
|
keefmarshall/camunda-demo
|
27e2778d77093d33656de41250bcda38e4cdcca1
|
4e0e80f6f73d003d795d146fceb0316fe58ed321
|
refs/heads/master
|
<repo_name>corsoa/pmon<file_sep>/notes.txt
Note: still need to have a grep by "real" process, ie search that node-inspector is bound to a port by its name, rather than ss just saying node is running on that port
cd /proc
find . -maxdepth 1 -type d | cut -d '/' -f2- | grep -vP '\D'
There are some processes that don't contain enough information -ie. you start "node app.js" but you don't have context - /proc/ also stores a symbolic link to the startup directory:
readlink -e /proc/PID/cwd
This should also be a greppable field.
<file_sep>/README.md
Searches for any processes bound to ports and formats everything in a nice table.
You can get better information on processes that may have been started with specific arguments you'd be more familiar with.
ie. you start 'node app.js' in a specific directory and you want to search for that
ie. you start a node process using pm2 and you want to search for that.
ie. you start a node package like node-inspector and want to search for that.
<file_sep>/pmon
#!/usr/bin/env node
'use strict';
var Promise = require('bluebird');
var exec = require('child_process').exec;
var Table = require('cli-table2');
var fs = Promise.promisifyAll(require('fs'));
var yargs = require('yargs').argv;
var _ = require('lodash');
if (yargs.help || yargs.h) {
process.stdout.write(`Usage:
pmon node -> Shows all procsses matching the argument and their associated bound ports (if any)
pmon -b node -> Shows only matching processes bound to a port.`);
process.exit();
}
var grepArg;
var numArgs = Object.keys(yargs).length;
if (process.argv.length === numArgs) {
process.stderr.write('Must supply a search term (PID, process name)'); process.exit();
}
else {
grepArg = process.argv[numArgs];
}
function stripNullChars(stdout) {
//proc cmdline has null characters for spaces, but only non-trailing should be converted
//otherwise it causes formatting issues with cli-table2
stdout = stdout.replace(/\0+$/,'');
stdout = stdout.replace(/\0/g,' ');
return stdout;
}
function populateName(pid) {
return new Promise((resolve, reject) => {
exec("cat /proc/" + pid + "/cmdline", (error, stdout, stderr) => {
if (error || stderr) {
reject(error || stderr);
}
stdout = stripNullChars(stdout);
resolve(stdout);
});
});
}
function readProcFile(fileName, pid) {
//always resolve because this function is being used to resolve a Promise.all
return new Promise((resolve, reject) => {
var fullFile = `/proc/${pid}/${fileName}`;
if (fileName !== 'cwd') {
//reads a proc file - if fileName is cwd, it returns the symbolic link location.
fs.readFileAsync(fullFile).then((fileResult) => {
//strip null chars / check for empty
var fileBody = stripNullChars(fileResult.toString());
if (fileBody.length) {
resolve({result: fileBody, error: false, pid: pid, fileName: fileName});
}
else {
resolve({result: '', error: true, pid: pid, fileName: fileName});
}
}).catch((err) => {
resolve({result: err, error: true, pid: pid, fileName: fileName});
});
}
else {
fs.readlinkAsync(fullFile).then((fileResult) => {
resolve({result: fileResult, error: false, pid: pid, fileName: fileName});
}).catch((err) => {
resolve({result: err, error: true, pid: pid, fileName: fileName});
});
}
});
}
function doAlphaSearch(grepArg) {
return new Promise((resolve, reject) => {
buildPidHash().then((pidHash) => {
//search through the properties of the hash for something matching the grepArg.
var matchedData = {};
var pids = Object.keys(pidHash);
pids.forEach((pid) => {
var procKeys = Object.keys(pidHash[pid]);
procKeys.forEach((procKey, procKeyIndex) => {
if (pidHash[pid][procKey].indexOf(grepArg) !== -1 && pidHash[pid][procKey].indexOf('pmon') === -1) {
if (!matchedData[pid]) {
matchedData[pid] = {};
}
matchedData[pid][procKeys[procKeyIndex]] = pidHash[pid][procKey];
}
});
});
resolve(matchedData);
});
});
}
function buildPidHash() {
return new Promise((resolve, reject) => {
exec("find /proc/ -maxdepth 1 -type d | cut -d '/' -f3-", (error, stdout, stderr) => {
var filesToRead = [];
var pidHash = {};
if (error || stderr) {
reject(error || stderr);
}
if (stdout) {
var pids = stdout.split('\n');
pids.forEach((pid, pidIndex) => {
//filter out any non-digit dirs is /proc here - grep with extended or PCRL is only
//consistent on GNU Grep.
if (pid.match(/\D/) === null) {
filesToRead.push(readProcFile('cwd', pid));
filesToRead.push(readProcFile('cmdline', pid));
}
});
Promise.all(filesToRead).then((fileArr) => {
fileArr.forEach((promiseResult) => {
if (!promiseResult.error) {
if (!pidHash[promiseResult.pid]) {
pidHash[promiseResult.pid] = {};
}
var fileNameEval = promiseResult.fileName;
pidHash[promiseResult.pid][fileNameEval] = promiseResult.result;
}
});
resolve(pidHash);
});
}
});
});
}
function buildListeningPortHash() {
return new Promise((resolve, reject) => {
exec("ss -nlp | grep " + grepArg + " | tr -d [:blank:] | cut -d ':' -f2- | sed 's/^\:://g' | sort", (error, stdout, stderr) => {
if (stderr) {
process.stderr.write(stderr);
process.exit();
}
var lines = stdout.split('\n');
lines.pop();
var line;
var processHash = {};
var numPopulated = 0;
if (!lines.length) {
resolve(processHash);
}
lines.forEach((line, key) => {
var port;
var pid;
var endPortPos = line.search(/\D/);
if (endPortPos !== -1) {
port = line.substring(0, endPortPos);
}
var parenIndex = line.indexOf('((');
var endParenIndex = line.indexOf('))');
pid = line.substring(parenIndex, endParenIndex);
var firstCommaPos = pid.indexOf(',');
var secondCommaPos = firstCommaPos + pid.substring(firstCommaPos+1).indexOf(',');
pid = pid.substring(firstCommaPos+1, secondCommaPos + 1);
// on some systems, the pid is prefixed by the literal 'pid='
let literalPidPos = pid.indexOf('pid=');
if (literalPidPos !== -1) {
pid = pid.substring(literalPidPos + 4);
}
processHash[pid] = {port: port};
populateName(pid).then((name) => {
processHash[pid].desc = name;
numPopulated += 1;
if (numPopulated === lines.length) {
resolve(processHash);
}
}).catch((err) => {
reject(err);
});
});
});
});
}
function buildCombinedHash(alphaHash, portHash) {
_.merge(alphaHash, portHash);
return alphaHash;
}
function doMain() {
return new Promise((resolve, reject) => {
var isAlphaSearch = false;
if (grepArg.match(/\D/) !== null) {
isAlphaSearch = true;
}
//by default, list processes bound to a port first, then other processes.
//If there is a 'b' flag, do not do an alpha search on processes not known to be bound to a port.
if (yargs.b) {
buildListeningPortHash().then((portHash) => {
resolve(portHash);
}).catch((err) => {
reject(err);
});
}
else {
doAlphaSearch(grepArg).then((alphaResult) => {
buildListeningPortHash().then((portResult) => {
var combinedHash = buildCombinedHash(alphaResult, portResult);
resolve(combinedHash);
}).catch((err) => {
reject(err);
});
}).catch((err) => {
reject(err);
});
}
});
}
doMain().then((processHash) => {
var hashKeys = Object.keys(processHash);
if (!hashKeys.length) {
process.stdout.write('Nothing matched.');
process.exit();
}
var table = new Table({
head: ['PID', 'Port', 'Description'],
colWidths: [8, 8, 70],
style: {
head: [],
border: []
}
});
for (var i = 0; i < hashKeys.length; i++) {
var desc = (processHash[hashKeys[i]].desc || processHash[hashKeys[i]].cmdline);
table.push([hashKeys[i], processHash[hashKeys[i]].port, desc]);
}
process.stdout.write(table.toString());
}).catch((err) => {
process.stderr.write(err);
});
|
065645b92bbaa69cd0dd6027c3102d970b590535
|
[
"Markdown",
"JavaScript",
"Text"
] | 3 |
Text
|
corsoa/pmon
|
d9d85f49db35ba7c963c3d260712c011c02b3007
|
9c933d2069af1194c8f8fab48fced99ed99889a6
|
refs/heads/master
|
<file_sep>package 프로젝트;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
public class join extends JFrame {
private JPanel contentPane;
private JTextField 아이디;
private JTextField 이름;
private JTextField 비밀번호;
private JTextField 휴대전화;
private JTextField 생년;
private JTextField 일;
private JTextField 이메일;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
join frame = new join();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public join() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 480, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 464, 561);
contentPane.add(panel);
panel.setLayout(null);
JLabel laJoin = new JLabel("\uD68C\uC6D0 \uAC00\uC785 \uD398\uC774\uC9C0");
laJoin.setBounds(12, 10, 444, 47);
laJoin.setFont(new Font("맑은 고딕", Font.BOLD, 25));
laJoin.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(laJoin);
JLabel la1 = new JLabel("\uC544\uC774\uB514");
la1.setBounds(46, 100, 75, 33);
la1.setHorizontalAlignment(SwingConstants.CENTER);
la1.setFont(new Font("맑은 고딕", Font.BOLD, 18));
panel.add(la1);
JLabel la2 = new JLabel("\uBE44\uBC00\uBC88\uD638");
la2.setBounds(46, 150, 75, 33);
la2.setHorizontalAlignment(SwingConstants.CENTER);
la2.setFont(new Font("맑은 고딕", Font.BOLD, 18));
panel.add(la2);
JLabel la3 = new JLabel("\uC774\uB984");
la3.setBounds(46, 200, 75, 33);
la3.setHorizontalAlignment(SwingConstants.CENTER);
la3.setFont(new Font("맑은 고딕", Font.BOLD, 18));
panel.add(la3);
JLabel la4 = new JLabel("\uC0DD\uB144\uC6D4\uC77C");
la4.setBounds(46, 250, 75, 33);
la4.setHorizontalAlignment(SwingConstants.CENTER);
la4.setFont(new Font("맑은 고딕", Font.BOLD, 18));
panel.add(la4);
JLabel la5 = new JLabel("\uC131\uBCC4");
la5.setBounds(46, 300, 75, 33);
la5.setHorizontalAlignment(SwingConstants.CENTER);
la5.setFont(new Font("맑은 고딕", Font.BOLD, 18));
panel.add(la5);
JLabel la6 = new JLabel("\uD734\uB300\uC804\uD654");
la6.setBounds(46, 350, 75, 33);
la6.setHorizontalAlignment(SwingConstants.CENTER);
la6.setFont(new Font("맑은 고딕", Font.BOLD, 18));
panel.add(la6);
JLabel la7 = new JLabel("\uC774\uBA54\uC77C");
la7.setBounds(46, 400, 75, 33);
la7.setHorizontalAlignment(SwingConstants.CENTER);
la7.setFont(new Font("맑은 고딕", Font.BOLD, 18));
panel.add(la7);
아이디 = new JTextField();
아이디.setBounds(129, 100, 231, 33);
아이디.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
panel.add(아이디);
아이디.setColumns(10);
이름 = new JTextField();
이름.setBounds(129, 150, 231, 33);
이름.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
이름.setColumns(10);
panel.add(이름);
비밀번호 = new JTextField();
비밀번호.setBounds(129, 200, 231, 33);
비밀번호.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
비밀번호.setColumns(10);
panel.add(비밀번호);
생년 = new JTextField();
생년.setBounds(129, 250, 66, 33);
생년.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
생년.setColumns(10);
panel.add(생년);
일 = new JTextField("일");
일.setBounds(294, 250, 66, 33);
일.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
일.setColumns(10);
panel.add(일);
휴대전화 = new JTextField();
휴대전화.setBounds(129, 350, 231, 33);
휴대전화.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
휴대전화.setColumns(10);
panel.add(휴대전화);
이메일 = new JTextField();
이메일.setBounds(129, 400, 231, 33);
이메일.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
이메일.setColumns(10);
panel.add(이메일);
JComboBox 월 = new JComboBox(new Object[]{"월",1,2,3,4,5,6,7,8,9,10,11,12});
월.setBounds(207, 250, 75, 33);
월.setFont(new Font("맑은 고딕", Font.BOLD, 18));
panel.add(월);
String[] combo = {"성별" , "남자" , "여자" };
JComboBox gender = new JComboBox(combo);
gender.setBounds(129, 300, 231, 33);
gender.setFont(new Font("맑은 고딕", Font.BOLD, 18));
panel.add(gender);
JButton btnJoin = new JButton("\uAC00\uC785\uD558\uAE30");
btnJoin.setBounds(129, 480, 231, 50);
btnJoin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnJoin.setForeground(Color.WHITE);
btnJoin.setFont(new Font("맑은 고딕", Font.BOLD, 17));
btnJoin.setBackground(new Color(51, 153, 204));
panel.add(btnJoin);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setIcon(new ImageIcon("C:\\Users\\admin\\Desktop\\image\\112.jpg"));
lblNewLabel.setBounds(0, 0, 464, 561);
panel.add(lblNewLabel);
}
}
<file_sep>import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
private Image img;
public ImagePanel(Image img) {
this.img = img;
setSize( new Dimension(img.getWidth(null), img.getHeight(null)));
setPreferredSize(new Dimension(img.getWidth(null), img.getHeight(null)));
setLayout(null);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Panel Picture");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
ImagePanel panel = new ImagePanel(new ImageIcon("C:\\Users\\admin\\Desktop\\image\\aerial2.jpg").getImage());
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
<file_sep>package 프로젝트;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class customer {
public static void main(String[] args) {
//getCustomers();
}
public static void login(String id, String pw) {
try {
Connection conn = getConnection();
PreparedStatement statement = conn.prepareStatement(
"SELECT * FROM customer WHERE id=? AND pw=?");
statement.setString(1, id);
statement.setString(2, pw);
ResultSet results = statement.executeQuery();
if(results.next()) { //
JOptionPane.showMessageDialog(null, "로그인 성공!");
} else {
JOptionPane.showMessageDialog(null, "아이디나 패스워드가 틀립니다");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String[][] getlogin() {
try {
Connection conn = getConnection();
PreparedStatement statement = conn.prepareStatement(
"SELECT * FROM login");
ResultSet results = statement.executeQuery();
ArrayList<String[]> list = new ArrayList<String[]>();
while(results.next()) {
list.add(new String[] {
results.getString("id"),
results.getString("pw"),
results.getString("name"),
results.getString("year"),
results.getString("month"),
results.getString("day"),
results.getString("gender"),
results.getString("phone"),
results.getString("email")
});
}
System.out.println("검색되었습니다.");
String [][] arr = new String[list.size()][5];
return list.toArray(arr);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void createCustomer(String id, String pw, String name, int year, int month, int day, String gender, String phone, String email) {
try {
Connection conn = getConnection();
PreparedStatement insert = conn.prepareStatement(
"INSERT INTO login(id, pw, name, year, month, day, gender, phone, email) "
+ "VALUES ('"+id+"','"+pw+"','"+name+"','"+year+"','"+month+"','"+day+"','"+gender+"','"+phone+"','"+email+"')");
insert.execute();
System.out.println("손님이 저장됬습니다.");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void createTable() {
try {
Connection conn = getConnection();
PreparedStatement create = conn.prepareStatement(
"CREATE TABLE IF NOT EXISTS "
+"customer(customer_id int NOT NULL AUTO_INCREMENT,"
+"id varChar(255),"
+"pw varChar(45),"
+"name varChar(45),"
+"year int,"
+"month int,"
+"day int,"
+"gender varChar(45),"
+"phone varChar(45),"
+"email varChar(45),"
+"PRIMARY KEY(customer_id))");
create.execute();
System.out.println("테이블을 만들었습니다.");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/login?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false";
String user = "root";
String pass = "<PASSWORD>";
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,user,pass);
System.out.println("DB 연결 완료!");
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
<file_sep>#Cached timestamps
#Tue Feb 18 14:50:35 KST 2020
<file_sep>#Tue Feb 18 14:50:00 KST 2020
org.eclipse.core.runtime=2
org.eclipse.platform=4.14.0.v20191210-0610
|
6ec22808f8097c6a3a61597a2326a8a0fd507c35
|
[
"Java",
"INI"
] | 5 |
Java
|
kkroki/java
|
5e6744789a2d1ab1032094b560e16f9f10e08574
|
c745c8450c87f8e05f05383f12338677aae2d760
|
refs/heads/master
|
<file_sep>import json
import urllib
import urllib2
def main():
url = "https://en.wikipedia.org/w/api.php"
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'action' : 'query',
'list' : 'recentchanges',
'format' : 'json',
'rcprop' : 'user|flags|title|ids|sizes|timestamp',
'rclimit' : 500
}
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
parsed_json = json.loads(the_page)
recent_changes = parsed_json['query']['recentchanges']
print recent_changes
for change in recent_changes:
print 'time: {}, user: {}, title: {}\n'.format(change['timestamp'].encode('utf8'), change['user'].encode('utf8'), change['title'].encode('utf8'))
if __name__ == '__main__':
main()
<file_sep>import re, collections
def words(test):
return re.findall('[a-z]+',text.lower())
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f]+=1
return model
def ingest_from_file(fileName):
model = collections.defaultdict(lambda: 1)
with open(fileName, 'r') as f:
for line in f:
(k, v) = line.strip().split(None, 1)
model[k.lower()]=v
return model
# NWORDS = train(words(file('big.txt').read()))
NWORDS = ingest_from_file('google-books-common-words.txt')
alphabet = "abcdefghijklmnopqrstuvwxyz"
def edits1(word):
n = len(word)
return set([word[0:i]+word[i+1:] for i in range(n)] +
[word[0:i]+word[i+1]+word[i]+word[i+2:] for i in range(n-1)] +
[word[0:i]+c+word[i+1:] for i in range(n) for c in alphabet] +
[word[0:i]+c+word[i:] for i in range(n+1) for c in alphabet])
def known_edits2(word):
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
def known(words):
return set(w for w in words if w in NWORDS)
def correct(word):
candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
return max(candidates, key=lambda w : NWORDS[w])
<file_sep>from django.shortcuts import render
from django.views import generic
from .models import Item
# Create your views here.
class IndexView(generic.ListView):
template_name = "mama/index.html"
context_object_name = "latest_item_list"
def get_queryset(self):
return Item.objects.order_by('-pub_date')[:50]
<file_sep>from urllib import request
from sys import argv
from bs4 import BeautifulSoup
def main(url):
html_doc = request.urlopen(url).read()
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.find_all('a'))
if __name__ == "__main__":
main(argv[1])
<file_sep># Token types
#
# EOF (end-of-file) token is used to indicate that
# there is no more input left for lexical analysis
INTEGER, PLUS, EOF, MINUS, MULTIPLY, DIVIDE = 'INTEGER', 'PLUS', 'EOF', 'MINUS', 'MULTIPLY', 'DIVIDE'
class Token(object):
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
return 'Token({type}, {value})'.format(
type=self.type,
value=repr(self.value)
)
def __repr__(self):
return self.__str__()
class Intepreter(object):
def __init__(self, text):
self.text = text
self.pos = 0
self.current_token = None
self.current_char = self.text[self.pos]
def error(self):
raise Exception('Error parsing input')
def advance(self):
self.pos += 1
if self.pos >= len(self.text):
self.current_char = None
else:
self.current_char = self.text[self.pos]
def skip_ws(self):
while self.current_char is not None and self.current_char.isspace():
self.advance()
def integer(self):
current_str = ''
while self.current_char is not None and self.current_char.isdigit():
current_str += self.current_char
self.advance()
return int(current_str)
def get_next_token(self):
while self.current_char is not None:
if self.current_char.isdigit():
return Token(INTEGER, self.integer())
if self.current_char.isspace():
self.skip_ws()
continue;
if self.current_char == '+':
self.advance()
return Token(PLUS, '+')
if self.current_char == '-':
self.advance()
return Token(MINUS, '-')
if self.current_char == '*':
self.advance()
return Token(MULTIPLY, '-')
if self.current_char == '/':
self.advance()
return Token(DIVIDE, '/')
self.error()
return Token(EOF, None)
def eat(self, token_type):
if self.current_token.type == token_type:
self.current_token = self.get_next_token()
else:
self.error()
def expr(self):
result = None
self.current_token = self.get_next_token()
while self.current_token.type != EOF:
if result is None:
result = self.current_token.value
self.eat(INTEGER)
else:
op = self.current_token
if op.type == PLUS:
self.eat(PLUS)
right = self.current_token
self.eat(INTEGER)
result += right.value
elif op.type == MINUS:
self.eat(MINUS)
right = self.current_token
self.eat(INTEGER)
result -= right.value
elif op.type == MULTIPLY:
self.eat(MULTIPLY)
right = self.current_token
self.eat(INTEGER)
result *= right.value
elif op.type == DIVIDE:
self.eat(DIVIDE)
right = self.current_token
self.eat(INTEGER)
result /= right.value
return result
def main():
while True:
try:
text = input('calc> ')
except EOFError:
break
if not text:
continue
intepreter = Intepreter(text)
result = intepreter.expr()
print(result)
if __name__ == '__main__':
main()
<file_sep>### REPO FOR PLAYING WITH python
|
e0a50da6883f42f6cda125e069e591c058035c40
|
[
"Markdown",
"Python"
] | 6 |
Python
|
jshencode/python-play
|
2f16a066cd9bc3a4eb629a2b05837a432707f4ec
|
cea2208e7b645a88edfe8500ff998d6ee413693f
|
refs/heads/master
|
<file_sep>class Account < ActiveRecord::Base
attr_accessible :address, :payment_method
end
<file_sep>module ApplicationHelper
def number_to_euro(price)
number_to_currency(price, :unit => '€')
end
private
def current_cart
cart = Cart.find_by_id(session[:cart_id])
if cart.nil?
cart = Cart.create
session[:cart_id] = cart_id
end
cart
end
def show_field_error(model, field)
s=""
if !model.errors[field].empty?
s =
<<-EOHTML
<div id="error_message">
#{model.errors[field][0]}
</div>
EOHTML
end
s.html_safe
end
end
<file_sep>class Lineitem < ActiveRecord::Base
attr_accessible :book_id, :cart_id, :order_id, :quantity
belongs_to :cart
belongs_to :order
belongs_to :book
end
<file_sep>class Book < ActiveRecord::Base
attr_accessible :author, :category, :picture, :price, :title
has_many :lineitems
has_many :orders, :through => :lineitems
def self.search(search)
search_condition = "%" + search + "%"
find(:all, :conditions => ['title LIKE ?', search_condition])
end
end
<file_sep>require 'singleton'
class Cart < ActiveRecord::Base
attr_accessible :title, :body
has_many :lineitems, dependent: :destroy
def add_book(book_id)
current_item = lineitems.find_by_book_id(book_id)
if current_item
current_item.quantity += 1
else
current_item = lineitems.build(book_id: book_id)
current_item.quantity = 1
end
current_item
end
end
<file_sep>class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
def current_user
@current_user ||= User.find_by_id(session[:user_id]) if session[:user_id]
end
private
def current_cart
cart = Cart.find_by_id(session[:cart_id])
if cart.nil?
cart = Cart.create
session[:cart_id] = cart.id
end
cart
end
end
|
ee59da8d6e65e1a113f6ec77f1f903dda741f05e
|
[
"Ruby"
] | 6 |
Ruby
|
matthewryan1986/Bookstore
|
fd934d24d5929629290dcaf1000a3304e75d6f85
|
065a8783fca04ad7c326f1c7ff83a6e1290ba072
|
refs/heads/master
|
<file_sep>local VRC = {}
VRC["updaterate"] = 1 / 25
function GVR.GetConfig(id)
return VRC[id]
end
<file_sep># gmVR
#### Garrysmod Virtual Reality
###### <NAME>
Uses a C++ module to connect OpenVR methods with Gmod lua.
## Features
### complete
* __(C++)__ Connect with SteamVR and tell if a headset is present
### In Progress
* __(C++)__ Get the position/angle of the HMD
### Todo
* __(C++)__ Get the position/angle of the controllers
* __(C++)__ Get the trigger/input state on the controllers
* __(GLUA/ C++)__ Represent the player in VR by using the SteamVR supplied variables and animating them as such
* __(GLUA)__ Picking up props
* __(GLUA)__ Simple SWEP usage
* __(GLUA / C++)__ Rendering in VR without relying on VorpX/Virtual Desktop
## Requirements for usage
* Latest [openvr_api.dll](https://github.com/ValveSoftware/openvr/raw/master/bin/win32/openvr_api.dll)
* [SteamVR](http://store.steampowered.com/steamvr) on steam
## Usage
##### Gmod Root
Throughout this readme, a directory known as the "Garrysmod Root" or "gmod root" will be referenced for installation and usage, to find this directory, Right click on Garrysmod in steam, click "properties" select the "Local Files" Tabs and click "Browse Local Files". This will take you to the Garrysmod root.
Download the latest `openvr_api.dll` and place it directly in your gmod root, the same directory that has `hl2.exe` in it.
## Requirements for source Editing
* Windows (Tested with Windows 10)
* [Visual Studio](https://www.visualstudio.com) With Windows SDK v8.1 or higher (Tested with version 2017)
* [Valve OpenVR SDK](https://github.com/ValveSoftware/openvr) (read instructions before cloning)
* [Premake 5.0+](https://github.com/premake/premake-core/releases) extracted to your _C:\Windows_ folder, or the project directory (it will be gitignored)
## Installation for Source Editing
1. Clone Repo with a [git CLI](https://git-scm.com/downloads)
```bash
$ git clone https://github.com/bizzclaw/gmVR.git
```
2. Clone the Valve OpenVR sdk to a folder and take note of that folder's location.
3. Create a new file called `"buildconfig.lua"` in the project's main directory with your favorite text editor, fill it with the following:
*NOTE:* you cannot use backslashes for the path! You'll have to replace any "\"s with "/"s
```LUA
sdkPaths = "Set this as the path to the folder that contains your cloned OpenVR SDK"
```
4. now, simply run buildprojects.bat, the batch file will generate a project folder with a visual studio project that can be loaded.
## Compiling and Testing
* When you're ready to compile, build from visual studio and move the compiled gmcl_gvr_win32.dll from the `build` folder into your `steam/steamapps/common/garrysmod/garrysmod/lua/bin` folder
___
###### This README is a work in progress, I need to test with another computer to make sure everything works as it should when followed.
## Credits
__Datamats__ - Created the original [gmcl_openvr](https://github.com/Datamats/gmcl_openvr) that this is largely based off of and used as reference.
__Joseph (<NAME>__ - Lua scripting, Stringing C++ components together and finding out how to get it to work on windows.
<file_sep>GVR = GVR or {}
GVR.__index = GVR
DEVICETYPE_HMD = 1
DEVICETYPE_LHAND = 2
DEVICETYPE_RHAND = 3
if SERVER then
AddCSLuaFile("gvr/sh_tracking.lua")
AddCSLuaFile("gvr/cl_tracking.lua")
AddCSLuaFile("gvr/cl_render.lua")
include("gvr/sv_config.lua")
include("gvr/sv_tracking.lua")
else
GVR.Set = function(enable)
if enable then
OpenVR.InitVR()
end
end
include("gvr/cl_tracking.lua")
include("gvr/cl_render.lua")
end
include("gvr/sh_tracking.lua")
<file_sep>#include <stdio.h>
#include <math.h>
#include <float.h>
#include "GarrysMod/Lua/Interface.h"
#include "openvr.h"
int version = 1; //every release this will be incremented, in lua, the user will be warned to update the dll if they have a lua version ahead of the module.
using namespace GarrysMod::Lua;
using namespace vr;
IVRSystem *vr_pointer;
LUA_FUNCTION( GetVersion )
{
LUA->PushNumber(version);
return 1;
}
LUA_FUNCTION(IsHmdPresent)
{
LUA->PushBool(VR_IsHmdPresent());
return 1;
}
LUA_FUNCTION(InitVR)
{
EVRInitError eError = VRInitError_None;
vr_pointer = VR_Init(&eError, VRApplication_Background);
if (eError != VRInitError_None)
{
LUA->PushBool(false);
return 1;
}
LUA->PushBool(true);
return 1;
}
LUA_FUNCTION(CountDevices)
{
LUA->PushNumber(vr::k_unMaxTrackedDeviceCount);
return 1;
}
int ResolveDeviceType( int deviceId ){
if (!vr_pointer) {
return -1;
}
ETrackedDeviceClass deviceClass = VRSystem()->GetTrackedDeviceClass(deviceId);
return static_cast<int>(deviceClass);
}
int ResolveDeviceRole(int deviceId) {
if (!vr_pointer) {
return -1;
}
int deviceRole = VRSystem()->GetInt32TrackedDeviceProperty(deviceId, ETrackedDeviceProperty::Prop_ControllerRoleHint_Int32);
return static_cast<int>(deviceRole);
}
LUA_FUNCTION(GetDevicePose)
{
(LUA->CheckType(1, Type::NUMBER));
int deviceId = static_cast<int>(LUA->GetNumber(1));
LUA->PushBool(false);
return 1;
}
LUA_FUNCTION(GetDeviceClass)
{
(LUA->CheckType(1, Type::NUMBER));
int deviceId = static_cast<int>(LUA->GetNumber(1));
int type = ResolveDeviceType(deviceId);
LUA->PushNumber(type);
return 1;
}
LUA_FUNCTION(GetDeviceRole)
{
(LUA->CheckType(1, Type::NUMBER));
int deviceId = static_cast<int>(LUA->GetNumber(1));
int type = ResolveDeviceRole(deviceId);
LUA->PushNumber(type);
return 1;
}
GMOD_MODULE_OPEN()
{
LUA->PushSpecial(GarrysMod::Lua::SPECIAL_GLOB);
LUA->CreateTable();
LUA->PushCFunction(GetVersion); LUA->SetField(-2, "GetVersion");
LUA->PushCFunction(IsHmdPresent); LUA->SetField(-2, "IsHmdPresent");
LUA->PushCFunction(InitVR); LUA->SetField(-2, "InitVR");
LUA->PushCFunction(CountDevices); LUA->SetField(-2, "CountDevices");
LUA->PushCFunction(GetDeviceClass); LUA->SetField(-2, "GetDeviceClass");
LUA->PushCFunction(GetDeviceRole); LUA->SetField(-2, "GetDeviceRole");
LUA->SetField(-2, "gvr");
LUA->Pop();
return 0;
}
GMOD_MODULE_CLOSE()
{
return 0;
}
void Shutdown()
{
if (vr_pointer != NULL)
{
VR_Shutdown();
vr_pointer = NULL;
}
}<file_sep>GVR.Device = GVR.Device or {
List = {}
}
GVR.Device.__index = GVR.Device
GVR.Device.new = function(id, deviceType)
local newDevice = {
Id = id,
DeviceType = deviceType,
}
setmetatable(newDevice, GVR.Device)
table.insert(GVR.Device.List, newDevice)
end
function GVR.Device:getType()
end
function GVR.Device:updatePose()
end
require("gvr")
TrackedDeviceClass_HMD = 1
TrackedDeviceClass_Controller = 2
local function attemptInit()
table.Empty(GVR.Device.List)
if not gvr.IsHmdPresent() then
return false
end
if not gvr.InitVR() then
return false
end
for i = 0, gvr.CountDevices() do
local class = gvr.GetDeviceClass(i)
if class != 0 then
local role = gvr.GetDeviceRole(i)
local deviceType
if class == 1 then
deviceType = DEVICETYPE_HMD
elseif role == 1 then
deviceType = DEVICETYPE_LHAND
elseif role == 2 then
deviceType = DEVICETYPE_RHAND
else
continue
end
GVR.Device.new(i, deviceType)
end
end
return true
end
GVR.isReady = attemptInit()
PrintTable(GVR.Device.List)
<file_sep>-- Directory where you've installed OVR and Source SDK Base 2013
include("buildconfig.lua")
workspace "gmcl_gvr"
configurations { "Debug", "Release" }
location ( "projects/" .. os.target() )
project "gmcl_gvr"
kind "SharedLib"
architecture "x86"
language "C++"
links {
sdkPaths.."/openvr/lib/win32/openvr_api.lib"
}
includedirs {
"include/",
sdkPaths.."/openvr/headers",
}
targetdir "build"
symbols "On"
if os.istarget( "windows" ) then targetsuffix "_win32" end
if os.istarget( "macosx" ) then targetsuffix "_osx" end
if os.istarget( "linux" ) then targetsuffix "_linux" end
configuration "Debug"
optimize "Debug"
configuration "Release"
optimize "Speed"
flags "StaticRuntime"
files
{
"src/**.*",
"include/**.*"
}
<file_sep>local RECIEVE_ALL = 1 -- player vr fully recieved
local RECIEVE_PARTIAL = 2 -- only recieve the position of the player's head and hands, no gestures.
local RECIEVE_LOWFPS = 3 -- partial at a lower framerate
local RECIEVE_NONE = 4 -- just appear as a regular (Non VR) player
function GVR.GetFilter(plyInVR, ply)
if plyInVR == ply then return false end
local plyInVRPos = plyInVR:GetPos()
local dist = plyInVRPos:Distance(ply)
if (SERVER and not ply:TestPVS(plyInVRPos)) or dist > 2048 then
return RECIEVE_NONE
elseif dist >= 1024 then
return RECIEVE_LOWFPS
elseif dist >= 512 then
return RECIEVE_PARTIAL
else
return RECIEVE_ALL
end
end
function GVR.UpdatePose(ply)
if SERVER or ply != LocalPlayer() then return false end
ply.VRPose = {}
for id, device in pairs(GVR.Device.List) do
local index = device.deviceType
ply.VRPose[index] = device.updatePose()
end
net.Start("GVR_UpdatePose")
net.WriteTable(ply.VRPose)
net.SendToServer()
return true
end
function GVR.GetVRPose(ply)
return ply.VRPose or false
end
function GVR.StartCommand(ply, cmd)
if ply.InVR then
GVR.UpdatePose()
if ply.VRPose then
end
end
end
hook.Add("StartCommand", "GVR_ProcessTracking", GVR.StartCommand)
<file_sep>util.AddNetworkString("GVR_UpdatePose")
net.Receive("GVR_UpdateTracking", function(len, ply)
local updateRate = GVR.GetConfig("updaterate")
local lastUpdate = ply.VRLastUpdate or 0
if CurTime() < lastUpdate + updateRate then return false end
for k, v in pairs(player.GetAll()) do
local filter = GVR.GetFilter()
if filter == RECIEVE_NONE then continue end
end
ply.VRLastUpdate = CurTime()
end)
|
7e8a282115c524f3bb8cff72f5f610f58c85c96c
|
[
"Markdown",
"C++",
"Lua"
] | 8 |
Lua
|
bizzclaw/gmVR
|
bc06a1659f4fe64b906c897a97fe05615a0c013f
|
b9b1f7378e24cfe5514628b500b409a7df0458f2
|
refs/heads/master
|
<file_sep># tseipii1989.github.io<file_sep>var myHeading = document.querySelector('h2');
myHeading.textContent = 'Hello world!';
function multiply(num1,num2) {
var result = num1 * num2;
return result;
}
multiply(4,7);
multiply(20,20);
multiply(0.5,3);
alert(multiply(0.5,3));
|
6e1d9a536608ad7b8bf065fe033cf9b753ce9eb6
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
tseipii1989/tseipii1989.github.io
|
84e9b531a349858515602c68b94431ee11cce045
|
69b2b3fe652f3398bc9c98ec0494775cc7ccd706
|
refs/heads/master
|
<repo_name>logicgupta/MyOutpass<file_sep>/app/src/main/java/com/example/android/myoutpass/service/MyFirebaseInstanceId.java
package com.example.android.myoutpass.service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.android.myoutpass.app.Config;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import java.util.HashMap;
import java.util.Map;
public class MyFirebaseInstanceId extends FirebaseInstanceIdService {
public static String TAG = MyFirebaseInstanceId.class.getSimpleName();
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
String referenedToken = FirebaseInstanceId.getInstance().getToken();
// saving reg id to shared preferences
SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("regId", referenedToken);
editor.commit();
Log.e(TAG, "Token ::" + referenedToken);
//sending reg id to your server
sendRegistrationToServer(referenedToken);
// Notify UI that registration has completed , so progress indicator can be hidden
Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
registrationComplete.putExtra("token", referenedToken);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
public void sendRegistrationToServer(final String token) {
//sending to gcm token to server
Log.e(TAG, "sendRegistration To Server" + token);
}
}<file_sep>/app/src/main/java/com/example/android/myoutpass/Denied/Denied_Adapter.java
package com.example.android.myoutpass.Denied;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.android.myoutpass.Model.Listdata;
import com.example.android.myoutpass.R;
import java.util.ArrayList;
import java.util.List;
public class Denied_Adapter extends RecyclerView.Adapter<Denied_Adapter.ViewHolder> {
public interface OnItemClickListener{
void onItemClick(String abc, int position, String key, String studenttoken, String superintendenttoken, String femailid, String imageUrl);
}
RecyclerView recyclerView;
Context mContext;
List<Listdata> arrayList=new ArrayList<Listdata>();
public OnItemClickListener listener;
public Denied_Adapter(RecyclerView recyclerView, Context mContext, List<Listdata> arrayList, OnItemClickListener listener) {
this.recyclerView = recyclerView;
this.mContext = mContext;
this.arrayList = arrayList;
this.listener=listener;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_recyclerview1,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
Listdata listdata=arrayList.get(position);
holder.textView.setText(listdata.getEnroll());
holder.name_textView.setText(listdata.getName());
holder.departDate_textView.setText(listdata.getD_date());
Glide.with(mContext)
.load(listdata.getPhoto())
.into(holder.imageView);
}
@Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView textView,name_textView,departDate_textView;
ImageView imageView;
public ViewHolder(final View itemView) {
super(itemView);
textView=itemView.findViewById(R.id.showEnroll_textView);
name_textView=itemView.findViewById(R.id.showName_textView);
departDate_textView=itemView.findViewById(R.id.show_date);
imageView=itemView.findViewById(R.id.userimage);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position=recyclerView.getChildLayoutPosition(itemView);
String enroll = textView.getText().toString();
Listdata listdata=arrayList.get(position);
String key=listdata.getKey();
String studenttoken=listdata.getSregid();
String imageUrl=listdata.getPhoto();
String superintendenttoken=listdata.getWregid();
listener.onItemClick(enroll,position,key,studenttoken
,superintendenttoken,listdata.getFemailid(),imageUrl);
}
});
}
}
}
<file_sep>/app/src/main/java/com/example/android/myoutpass/RegisterActivity.java
package com.example.android.myoutpass;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.nfc.Tag;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
public class RegisterActivity extends AppCompatActivity {
EditText useredit,emailedit,passedit,confirmedit;
Button continueButton;
CircleImageView imageButton;
ImageView imageView;
Uri uri;
private StorageReference mStorageRef;
private FirebaseAuth mAuth;
private FirebaseFirestore mFirestore;
CollectionReference collectionReference;
@Override
protected void onStart() {
FirebaseUser currentUser=mAuth.getCurrentUser();
super.onStart();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth=FirebaseAuth.getInstance();
mFirestore=FirebaseFirestore.getInstance();
useredit=findViewById(R.id.editText2);
imageView=findViewById(R.id.imageView3);
emailedit=findViewById(R.id.editText4);
passedit=findViewById(R.id.editText6);
confirmedit=findViewById(R.id.editText7);
continueButton=findViewById(R.id.button4);
imageButton=findViewById(R.id.getuserimage);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 114);
}
});
continueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String username=useredit.getText().toString();
final String email=emailedit.getText().toString();
final String password=<PASSWORD>().toString();
final String confpass=confirmedit.getText().toString();
if(username.equals("")&&email.equals("")&&!checkEmail(email)&&password.equals("")&&confpass.equals("")){
useredit.setError("enter the username");
emailedit.setError("enter the email");
passedit.setError("enter the password");
confirmedit.setError("enter confirm password");
}
else if(username.equals("")){
useredit.setError("enter the username");
}
else if(email.equals("")&&!checkEmail(email)){
emailedit.setError("enter the email");
}
else if(password.equals("")){
passedit.setError("enter the password");
}
else if(confpass.equals("")){
confirmedit.setError("enter confirm password");
}
else if(!password.equals(confpass)){
Toast.makeText(RegisterActivity.this, "Enter the correct password", Toast.LENGTH_SHORT).show();
}
else if (uri==null){
Toast.makeText(RegisterActivity.this, "Please Select Image", Toast.LENGTH_SHORT).show();
}
else{
onContinueTapped();
}
}
});
}
public void onContinueTapped(){
final String user_name=useredit.getText().toString();
String email=emailedit.getText().toString();
String password=passedit.getText().toString();
String []sup_email=email.split("[.@,]+");
StringBuilder builder=new StringBuilder("");
for (String ans_wemail:sup_email){
builder.append(ans_wemail);
}
final String final_wemail=builder.toString();
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// SharedPreferences preferences=getApplicationContext()
// .getSharedPreferences("uimage",0);
// SharedPreferences.Editor editor=preferences.edit();
// editor.putString("uimages",uri.toString());
// editor.commit();
final String user_ID=mAuth.getCurrentUser().getUid();
mStorageRef = FirebaseStorage.getInstance().getReference().child("images");
StorageReference user_profile=mStorageRef.child(user_ID + ".jpg");
user_profile.putFile(uri).
addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String download_uri=taskSnapshot.getDownloadUrl().toString();
Map<String,Object> UserMap=new HashMap<>();
UserMap.put("name",user_name);
UserMap.put("image",download_uri);
Toast.makeText(RegisterActivity.this, "kcvkk", Toast.LENGTH_SHORT).show();
mFirestore.collection("Users").document(user_ID).set(UserMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
mAuth.signOut();
Intent i=new Intent(RegisterActivity.this,Login_Activity.class);
startActivity(i);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(RegisterActivity.this, "Failure ....", Toast.LENGTH_SHORT).show();
}
});
}
});
Log.i("TAG", "createUserWithEmail:success");
Toast.makeText(RegisterActivity.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
} else {
// If sign in fails, display a message to the user.
if (mAuth.getCurrentUser()!=null){
mAuth.signOut();
Intent i=new Intent(RegisterActivity.this,Login_Activity.class);
startActivity(i);
}
else {
Toast.makeText(RegisterActivity.this, "failure", Toast.LENGTH_SHORT).show();
}
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==114 && resultCode==RESULT_OK && data!=null){
uri = data.getData();
imageButton.setImageURI(uri);
}
}
private boolean checkEmail(String email){
return email.contains("@");
}
public void onSignInTapped(View view){
Intent intent=new Intent(RegisterActivity.this,Main_Activity.class);
startActivity(intent);
}
}
<file_sep>/app/src/main/java/Website/LoginStatus.java
package Website;
import android.content.Context;
import com.example.android.myoutpass.R;
public class LoginStatus {
public static final int LOGIN_DONE=1;
public static final int CONN_ERROR=2;
public static final int INVALID_PASS=3;
public static final int INVALID_ENROLL=4;
public static final int ACCOUNT_LOCKED=5;
public static final int UNKNOWN_ERROR=6;
public static String responseToString(Context context, int response){
switch (response){
case INVALID_PASS:
return context.getString(R.string.invalid_pass);
case INVALID_ENROLL:
return context.getString(R.string.invalid_enroll);
case CONN_ERROR:
return context.getString(R.string.con_error);
case ACCOUNT_LOCKED :
return context.getString(R.string.employeeid_error);
case UNKNOWN_ERROR:
return context.getString(R.string.unknown_error);
default:
return null;
}
}
}
<file_sep>/app/src/main/java/com/example/android/myoutpass/User_Profile/MyAccount.java
package com.example.android.myoutpass.User_Profile;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android.myoutpass.R;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.bumptech.glide.Glide;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.concurrent.ExecutionException;
public class MyAccount extends AppCompatActivity {
TextView enroll,course,fathername,fathermobile,fatheremail,username;
ImageView userphoto;
Bitmap bitmap_userphoto;
FirebaseAuth mAuth;
FirebaseFirestore mFirestore;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_info);
mAuth=FirebaseAuth.getInstance();
mFirestore=FirebaseFirestore.getInstance();
String user_ID=mAuth.getCurrentUser().getUid();
SharedPreferences preferences=getApplicationContext().getSharedPreferences("UserData",MODE_PRIVATE);
String sname=preferences.getString("Name11",null);
String enroll1=preferences.getString("Enroll",null);
String course1=preferences.getString("Course",null);
String fname=preferences.getString("Father's Name",null);
String fmobile=preferences.getString("Father's Mobile Number",null);
String femail=preferences.getString("Father's Email",null);
String paddress=preferences.getString("Address",null);
String pdistrict=preferences.getString("District",null);
String pin=preferences.getString("Pin",null);
String pstate=preferences.getString("State",null);
enroll=findViewById(R.id.textView);
course=findViewById(R.id.textView4);
userphoto=findViewById(R.id.imageView3);
fathername=findViewById(R.id.textView5);
fatheremail=findViewById(R.id.textView6);
fathermobile=findViewById(R.id.textView7);
username=findViewById(R.id.nametext);
Log.e("My Profile","++++"+user_ID);
enroll.setText(enroll1);
course.setText(course1);
fathername.setText(fname);
fathermobile.setText(fmobile);
fatheremail.setText(paddress);
username.setText(sname);
// Retreive image
if (getPhotoFromFirebase()!=null){
Glide.with(getApplicationContext()).load(getPhotoFromFirebase()).into(userphoto);
}
else {
mFirestore.collection("Users").document(user_ID).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String username=documentSnapshot.getString("name");
final String userimage=documentSnapshot.getString("image");
Glide.with(getApplicationContext()).load(userimage).into(userphoto);
}
});
}
}
public String getEmailFromFirebase(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
//String name = user.getDisplayName();
String email = user.getEmail();
//String uid = user.getUid(); // The user's ID, unique to the Firebase project.
return email;
} else {
// No user is signed in.
return " ";
}
}
public Uri getPhotoFromFirebase(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
//String name = user.getDisplayName();
Uri photoUrl = user.getPhotoUrl();
//String uid = user.getUid(); // The user's ID, unique to the Firebase project.
return photoUrl;
} else {
// No user is signed in.
return null;
}
}
}
<file_sep>/app/src/main/java/com/example/android/myoutpass/AboutUs.java
package com.example.android.myoutpass;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
public class AboutUs extends AppCompatActivity {
TextView fblink,fblink1;
WebView webView;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_us);
imageView=findViewById(R.id.imageButton);
fblink=findViewById(R.id.textView22);
fblink1=findViewById(R.id.textView21);
fblink1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent facebookIntent = getOpenFacebookIntent1(AboutUs.this);
startActivity(facebookIntent);
}
});
fblink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent facebookIntent = getOpenFacebookIntent2(AboutUs.this);
startActivity(facebookIntent);
}
});
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent facebookIntent = getOpenFacebookIntent3(AboutUs.this);
startActivity(facebookIntent);
}
});
}
public static Intent getOpenFacebookIntent3(Context context) {
try {
context.getPackageManager()
.getPackageInfo("com.facebook.katana", 0); //Checks if FB is even installed.
return new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.facebook.com/Outpass-1018485261665536/")); //Trys to make intent with FB's URI
} catch (Exception e) {
return new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.facebook.com/arkverse")); //catches and opens a url to the desired page
}
}
public static Intent getOpenFacebookIntent1(Context context) {
try {
context.getPackageManager()
.getPackageInfo("com.facebook.katana", 0); //Checks if FB is even installed.
return new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.facebook.com/logic.gupta")); //Trys to make intent with FB's URI
} catch (Exception e) {
return new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.facebook.com/arkverse")); //catches and opens a url to the desired page
}
}
public static Intent getOpenFacebookIntent2(Context context) {
try {
context.getPackageManager()
.getPackageInfo("com.facebook.katana", 0); //Checks if FB is even installed.
return new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.facebook.com/lokesh.gidwani.18")); //Trys to make intent with FB's URI
} catch (Exception e) {
return new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.facebook.com/arkverse")); //catches and opens a url to the desired page
}
}
}
<file_sep>/app/src/main/java/com/example/android/myoutpass/app/Config.java
package com.example.android.myoutpass.app;
public class Config {
// global topic to receive app wide push notification
public static final String TOPIC_GLOBAL="global";
// broadcast receiver intent filters
public static final String REGISTRATION_COMPLETE="registrationcomplete";
public static final String PUSH_NOTIFICATION="pushnotification";
// id to handle the notification in the notification tray
public static final int NOTIFICATION_ID=170;
public static final int NOTIFICATION_ID_BIG_IMAGE=180;
public static final String SHARED_PREF="ah_firebase";
}
<file_sep>/app/src/main/java/com/example/android/myoutpass/GoogleSigninActivity.java
package com.example.android.myoutpass;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.android.myoutpass.webView.JuetWebView;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
public class GoogleSigninActivity extends AppCompatActivity {
Button loginbutton,Registerbutton;
EditText Emailedit,passwordedit;
SignInButton button;
FirebaseAuth mAuth;
private final static int RC_SIGN_IN=1;
GoogleApiClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListener;
// @Override
// protected void onStart() {
// super.onStart();
// mAuth.addAuthStateListener(mAuthListener);
// }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//removing toolbar
getSupportActionBar().hide();
//this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_google_signin);
Registerbutton=findViewById(R.id.button2);
Emailedit=findViewById(R.id.editText);
passwordedit=findViewById(R.id.editText5);
loginbutton=findViewById(R.id.button);
button=findViewById(R.id.googlebtn);
mAuth = FirebaseAuth.getInstance();
loginbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email=Emailedit.getText().toString();
String password=<PASSWORD>();
// Storing that the user is warden or superintendent
if(email.equals("")&&password.equals("")){
Emailedit.setError("enter the email");
passwordedit.setError("enter the password");
}
else if(email.equals("")){
Emailedit.setError("enter the email");
}
else if(password.equals("")){
pass<PASSWORD>.setError("enter the password");
}
else{
onLogin();
}
}
});
Registerbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(GoogleSigninActivity.this,RegisterActivity.class);
startActivity(i);
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
// mAuthListener=new FirebaseAuth.AuthStateListener() {
// @Override
// public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
// if(firebaseAuth.getCurrentUser()!=null)
// {
// startActivity(new Intent(GoogleSigninActivity.this,Main_Activity.class));
// finish();
//
// }
// }
// };
GoogleSignInOptions gso=new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient =new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(GoogleSigninActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API,gso)
.build();
}
//.build();
public void onLogin()
{
final String email=Emailedit.getText().toString();
final String password=<PASSWORD>().<PASSWORD>();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.i("TAG", "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
String userID=user.getUid().toString();
Toast.makeText(GoogleSigninActivity.this, "Auth success", Toast.LENGTH_SHORT).show();
Log.i("USER","USER"+user.toString());
Log.i("USER","USER"+userID);
Intent intent=new Intent(GoogleSigninActivity.this,Main_Activity.class);
startActivity(intent);
passwordedit.setText("");
Emailedit.setText("");
} else {
// If sign in fails, display a message to the user.
Log.i("TAG", "signInWithEmail:failure", task.getException());
Toast.makeText(GoogleSigninActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
private void signIn() {
Intent signInIntent=Auth.GoogleSignInApi.getSignInIntent(mGoogleSignInClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result= Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if(result.isSuccess())
{
GoogleSignInAccount account=result.getSignInAccount();
firebaseAuthWithGoogle(account);
}
else
{
Toast.makeText(
this, "Auth Went Wrong", Toast.LENGTH_SHORT).show();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("TAG", "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInWithCredential:failure", task.getException());
updateUI(null);
}
// ...
}
});
}
public void updateUI(FirebaseUser user){
if (user!=null){
Log.e("Google login","Sucess ");
Toast.makeText(this, "Successfull", Toast.LENGTH_SHORT).show();
startActivity(new Intent(GoogleSigninActivity.this, JuetWebView.class));
finish();
}
else{
Toast.makeText(this, "Please Try Again!", Toast.LENGTH_SHORT).show();
}
}
}
<file_sep>/app/src/main/java/com/example/android/myoutpass/Outpass_Details/Generate_Outpass.java
package com.example.android.myoutpass.Outpass_Details;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.android.myoutpass.Model.FetchFacultyEmail;
import com.example.android.myoutpass.Model.FetchFirebaseKeydata;
import com.example.android.myoutpass.Model.studentDetails;
import com.example.android.myoutpass.R;
import com.example.android.myoutpass.app.Config;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.msg91.sendotp.library.SendOtpVerification;
import com.msg91.sendotp.library.Verification;
import com.msg91.sendotp.library.VerificationListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import cn.iwgang.countdownview.CountdownView;
public class Generate_Outpass extends AppCompatActivity implements VerificationListener {
public static final String TAG=Generate_Outpass.class.getSimpleName();
Verification mVerification;
EditText editTextotp;
ProgressDialog progressDialog;
ProgressDialog otpprogressDialog;
Button continue_button;
Spinner spinner ,spinner_superintendent;
EditText enroll_edittext,name_edittext,course_edittext,departure_date_edittext;
EditText arival_date_editext,days_edittext,location_edittext,smobile_edittext;
EditText room_edittext,hostel_edittext,mobile_editText,reason_EditText,year_editText,semester_editText;
String faculty_warden[];
int day,yr,mth;
String a[]=null;
String myname;
String enroll;
String course;
String fmobile;
String smobile;
String date_departure,date_arrival,location,hostel_number,room_number,reason,year,semester;
String pmobile,faculty;
String faculty_email;
String faculty_token;
String faculty_mobile;
String superintendent_token;
String superintendent_mobile;
String faculty_usertype;
ImageButton date_pick_departure,date_pick_arrival;
List<String> faculty_emailList =new ArrayList<String>();
List<String> superintendent_emailList =new ArrayList<String>();
List<String> faculty_tokenList =new ArrayList<String>();
List<String> faculty_mobileList =new ArrayList<String>();
List<String> superintendent_tokenList=new ArrayList<String>();
List<String> superintendent_mobileList=new ArrayList<String>();
List<String> usertypeList=new ArrayList<String>();
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
String secondString;
TextView textViewtimer;
int warden_position_sp;
int superintendent_position_sp;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generate__outpass);
ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState()== NetworkInfo.State.CONNECTED
|| connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState()== NetworkInfo.State.CONNECTED) {
faculty_emailList.add("Select Warden Email Id");
faculty_data();
superintendent_emailList.add("Select Superintendent Email Id");
name_edittext = findViewById(R.id.name_EditText);
enroll_edittext = findViewById(R.id.enroll_EditText);
year_editText = findViewById(R.id.year_EditText);
semester_editText = findViewById(R.id.semester_EditText);
course_edittext = findViewById(R.id.course_EditText);
departure_date_edittext = findViewById(R.id.date_departure_EditText);
arival_date_editext = findViewById(R.id.date_arrival_EditText);
location_edittext = findViewById(R.id.location_EditText);
room_edittext = findViewById(R.id.room_EditText);
hostel_edittext = findViewById(R.id.hostel_EditText);
mobile_editText = findViewById(R.id.mobile_EditText);
smobile_edittext = findViewById(R.id.smobile_EditText);
reason_EditText = findViewById(R.id.reason_EditText);
spinner = findViewById(R.id.warden_spinner);
spinner_superintendent = findViewById(R.id.superintendent_spinner);
date_pick_departure = findViewById(R.id.date_picker_imagebutton);
date_pick_arrival = findViewById(R.id.date_picker_arrival_imagebutton);
faculty_warden = getResources().getStringArray(R.array.hostel_warden);
continue_button = findViewById(R.id.continue_button);
//continue_button.setEnabled(false);
// Warden faculty spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Generate_Outpass.this
, android.R.layout.simple_spinner_item, faculty_emailList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.notifyDataSetChanged();
spinner.setAdapter(adapter);
Toast.makeText(this, ""+faculty_emailList, Toast.LENGTH_SHORT).show();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position != 0) {
warden_position_sp=position;
// faculty_token = faculty_tokenList.get(position - 1);
//faculty_mobile=faculty_mobileList.get(position-1);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Superintendent Spinner ......
ArrayAdapter<String> adapter_super = new ArrayAdapter<String>(Generate_Outpass.this, android.R.layout.simple_spinner_item, superintendent_emailList);
adapter_super.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter_super.notifyDataSetChanged();
spinner_superintendent.setAdapter(adapter_super);
spinner_superintendent.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position != 0) {
superintendent_position_sp=position;
//superintendent_token = superintendent_tokenList.get(position - 1);
//superintendent_mobile=superintendent_mobileList.get(position-1);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SharedPreferences preferences = getApplicationContext().getSharedPreferences("UserData", MODE_PRIVATE);
enroll = preferences.getString("Enroll", null);
myname = preferences.getString("Name11", null);
course = preferences.getString("Course", null);
String fname = preferences.getString("Father's Name", null);
fmobile = preferences.getString("Father's Mobile Number", null);
String femail = preferences.getString("Father's Email", null);
course_edittext.setText(course);
if (fmobile.contains(",")) {
a = fmobile.split(",");
name_edittext.setText(myname);
course_edittext.setText(course);
fmobile = fmobile.substring(0, 10);
Spinner mobilesp = findViewById(R.id.mobile_spinner);
mobilesp.setVisibility(View.VISIBLE);
ArrayAdapter<String> mobileadapter = new ArrayAdapter<String>(Generate_Outpass.this, android.R.layout.simple_list_item_1, a);
mobilesp.setAdapter(mobileadapter);
} else {
mobile_editText.setVisibility(View.VISIBLE);
mobile_editText.setText(fmobile);
}
enroll_edittext.setText(enroll);
name_edittext.setText(myname);
Calendar calendar = Calendar.getInstance();
yr = calendar.get(Calendar.YEAR);
mth = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
date_pick_departure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DatePickerDialog(Generate_Outpass.this, date1, yr, mth, day).show();
}
});
date_pick_arrival.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DatePickerDialog(Generate_Outpass.this, date2, yr, mth, day).show();
}
});
/**
* continue_button is used to play the further progress of outpass generation ...
*/
continue_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
faculty = spinner.getSelectedItem().toString();
/**
* Getting the value from the Edit Text .......
*/
date_departure = departure_date_edittext.getText().toString();
date_arrival = arival_date_editext.getText().toString();
location = location_edittext.getText().toString();
hostel_number = hostel_edittext.getText().toString();
room_number = room_edittext.getText().toString();
reason = reason_EditText.getText().toString();
smobile = smobile_edittext.getText().toString();
year=year_editText.getText().toString();
semester=semester_editText.getText().toString();
Log.e(TAG, "smobile" + smobile);
if (name_edittext.getText().toString().equals("") && departure_date_edittext.getText().toString().equals("")
&& arival_date_editext.getText().toString().equals("")
&& room_edittext.getText().toString().equals("")
&& hostel_edittext.getText().toString().equals("") && faculty.equals("")) {
Toast.makeText(Generate_Outpass.this, " Please Fill All Fields!", Toast.LENGTH_SHORT).show();
} else if (name_edittext.getText().toString().equals("")) {
name_edittext.setError("Please Enter Name");
} else if (departure_date_edittext.getText().toString().equals("")) {
Toast.makeText(Generate_Outpass.this, " Please Fill Departure Date!", Toast.LENGTH_SHORT).show();
} else if (arival_date_editext.getText().toString().equals("")) {
Toast.makeText(Generate_Outpass.this, " Please Fill Arival Date!", Toast.LENGTH_SHORT).show();
} else if (room_edittext.getText().toString().equals("")) {
room_edittext.setError("Please Enter Room Number !");
} else if (hostel_edittext.getText().toString().equals("")) {
Toast.makeText(Generate_Outpass.this, " Please Fill Hostel Number!", Toast.LENGTH_SHORT).show();
} else if (faculty.equalsIgnoreCase("Select Warden Email id")) {
Toast.makeText(Generate_Outpass.this, " Please Select Faculty", Toast.LENGTH_SHORT).show();
} else if (smobile_edittext.getText().toString().equals("")) {
smobile_edittext.setError("Please Enter Mobile Number !");
} else {
faculty_token=faculty_tokenList.get(warden_position_sp-1);
faculty_mobile=faculty_mobileList.get(warden_position_sp-1);
superintendent_token=superintendent_tokenList.get(superintendent_position_sp-1);
superintendent_mobile=superintendent_mobileList.get(superintendent_position_sp-1);
Log.e("ftoekn",""+faculty_token);
Log.e("faculty MObile",""+faculty_mobile);
Log.e("Sup Token",""+faculty_mobile);
Log.e("Sup Token",""+faculty_mobile);
SharedPreferences sharedPreferences=getApplicationContext()
.getSharedPreferences("firebaseReference",0);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("femail",spinner.getSelectedItem().toString());
editor.putString("enroll",enroll);
editor.commit();
continue_button.setEnabled(true);
progressDialog = new ProgressDialog(Generate_Outpass.this);
progressDialog.setMessage("Sending OTP ...");
progressDialog.setCancelable(false);
progressDialog.show();
//otpgenerate(fmobile); // fmobile is fathers Mobile Number Student Selected !
otpgenerate(superintendent_mobile); // Superientendent OTP IS send Student Selected !
mVerification.initiate();
}
}
});
}
else {
Toast.makeText(this, "Please Connect To Internet", Toast.LENGTH_SHORT).show();
setContentView(R.layout.no_internet);
}
}
DatePickerDialog.OnDateSetListener date1=new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
departure_date_edittext.setText(" "+dayOfMonth + " /" + (month+1)+"/"+year);
day=dayOfMonth;
yr=year;
mth=month;
}
};
DatePickerDialog.OnDateSetListener date2=new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
arival_date_editext.setText(" "+dayOfMonth + " /" + (month+1)+"/"+year);
day=dayOfMonth;
yr=year;
mth=month;
}
};
// Getting all the data from APP Server ... Firebase Realtime Database
public void faculty_data ()
{
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference().child("JUET").child("FGET");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String key=dataSnapshot1.getKey();
Log.e(TAG,""+key);
databaseReference.child(key).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG,""+dataSnapshot.getValue());
String post=null;
String email = null;
String freg = null;
String mobile;
JSONObject jsonObject= null;
try {
jsonObject = new JSONObject(dataSnapshot.getValue().toString());
email=jsonObject.getString("femail");
freg=jsonObject.getString(" Rgid");
Log.e(TAG,"email"+email+"freg"+freg);
} catch (JSONException e) {
e.printStackTrace();
}
FetchFacultyEmail fetchData=dataSnapshot.getValue(FetchFacultyEmail.class);
email=fetchData.femail;
String x=fetchData.post;
post=fetchData.getPost();
mobile=fetchData.getMobileNumber();
Log.e(TAG,"+post"+post+email+"*-*-*-*-"+x);
if (post.equalsIgnoreCase("Hostel Superintendent")&& email!=null){
superintendent_emailList.add(email);
superintendent_tokenList.add(freg);
superintendent_mobileList.add(mobile);
Log.e(TAG,"Called 1");
}
else {
if (email!=null){
faculty_emailList.add(fetchData.getEmail());
faculty_tokenList.add(fetchData.getFregid());
faculty_mobileList.add(fetchData.getMobileNumber());
}
Log.e(TAG,"Called 2");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void otpgenerate(String number){
Log.e("Superientendent",""+number);
Random random=new Random();
int n= random.nextInt(5982)+1;
String otp_code=String.valueOf(n);
mVerification= SendOtpVerification.createSmsVerification(
SendOtpVerification.config("+91"+number)
// .message("For Insuing Outpass Your Ward "+name+" Requested Outpass.THis is verifaction code "+otp_code)
// .httpsConnection(false)
// .expiry("1000")
// .senderId("OTBS")
// .otp(otp_code)
// .otplength("4")
.context(Generate_Outpass.this)
.autoVerification(true)
.build(),
Generate_Outpass.this);
}
@Override
public void onInitiated(String response) {
progressDialog.dismiss();
Log.d(TAG, "Initialized!" + response);
//OTP successfully resent/sent.
Dialog dialog=new Dialog(Generate_Outpass.this);
setContentView(R.layout.verify_otp);
editTextotp=findViewById(R.id.verify_otp);
textViewtimer=findViewById(R.id.countdown);
CountDownTimer countDownTimer=new CountDownTimer(300000,1000) {
@Override public void onTick(long millisUntilFinished) {
UpdateTimer((int)millisUntilFinished/1000);
}
@Override
public void onFinish() {
}
}.start();
Button button=findViewById(R.id.validate_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
otpprogressDialog=new ProgressDialog(Generate_Outpass.this);
otpprogressDialog.setMessage(" Verifying OTP ...");
otpprogressDialog.setCancelable(false);
otpprogressDialog.show();
String otp_code=editTextotp.getText().toString();
if(otp_code.equals("")){
otpprogressDialog.dismiss();
Toast.makeText(Generate_Outpass.this, "Please Enter THe OTP !", Toast.LENGTH_SHORT).show();
}
else {
mVerification.verify(otp_code);
}
}
});
}
@Override
public void onInitiationFailed(Exception paramException) {
otpprogressDialog.dismiss();
// progressDialog.dismiss();
Toast.makeText(this, "Please Try Again!", Toast.LENGTH_SHORT).show();
Log.d(TAG,"Verification Inititated Failed");
}
@Override
public void onVerified(String response) {
otpprogressDialog.dismiss();
//progressDialog.dismiss();
Log.d(TAG,"Verified Response"+response);
sendData();
}
@Override
public void onVerificationFailed(Exception paramException) {
otpprogressDialog.dismiss();
//progressDialog.dismiss();
Toast.makeText(this, " Invalid OTP !", Toast.LENGTH_SHORT).show();
Log.d(TAG,"Verification Failed");
}
public void UpdateTimer(int leftSeconds){
int minutes=leftSeconds/60;
int seconds=leftSeconds-(minutes*60);
if (seconds<=9){
secondString="0"+seconds;
textViewtimer.setText(Integer.toString(minutes)+":"+secondString);
}
else {
textViewtimer.setText(Integer.toString(minutes)+":"+seconds);
}
}
public void sendData(){
Intent intent=new Intent(Generate_Outpass.this, Otp_Generate.class);
intent.putExtra("enroll",enroll_edittext.getText().toString());
intent.putExtra("name",name_edittext.getText().toString());
intent.putExtra("course",course_edittext.getText().toString());
intent.putExtra("date_departure",date_departure);
intent.putExtra("date_arrival",date_arrival);
intent.putExtra("smobile",smobile);
intent.putExtra("fmobile",fmobile);
intent.putExtra("location",location);
intent.putExtra("hostel",hostel_number);
intent.putExtra("room",room_number);
intent.putExtra("purpose",reason);
intent.putExtra("femail",spinner.getSelectedItem().toString());
intent.putExtra("wemail",spinner_superintendent.getSelectedItem().toString());
intent.putExtra("ftoken",faculty_token);
intent.putExtra("wtoken",superintendent_token);
intent.putExtra("year",year_editText.getText().toString());
intent.putExtra("semester",semester_editText.getText().toString());
startActivity(intent);
}
// *******************************************************************************************************************
/*
public void SendNotification(){
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Sending your Outpass ....");
progressDialog.show();
SharedPreferences sharedPreferences=getApplicationContext().getSharedPreferences(Config.SHARED_PREF,0);
final String regId=sharedPreferences.getString("regId",null);
String firebaseRegId=regId;
final String title="OUTPASS";
final String message=" "+name_edittext.getText().toString()+" ("+enroll_edittext.getText().toString()+") "+" is requesting for outpass .";
Log.e(TAG,"F reg"+faculty_token);
StringRequest stringRequest=new StringRequest(Request.Method.POST,
"https://juetoutpass.000webhostapp.com/firebase/index.php?regId="+faculty_token+"&title="+title.trim().replace(' ','_')+"&team="+regId+"&score="+superintendent_token+"&message="+message.trim().replace(' ','_')+"&push_type=individual&team=logic&score=123"
,new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e(TAG,"Response is"+response);
Document document= Jsoup.parse(response);
Element div1=document.select("div").get(0);
Element pre=div1.select("pre").get(0);
Log.e(TAG,"Html Parser "+pre.text());
try {
JSONObject jsonObject1=new JSONObject(pre.text());
JSONObject jsonObject11=jsonObject1.getJSONObject("data");
String title1=jsonObject11.getString("title");
String message=jsonObject11.getString("message");
Log.e(TAG,"Title :"+title1);
Log.e(TAG,"Message : "+message);
if (title1.equals(title)) {
Log.e(TAG,"enroll"+enroll_edittext.getText().toString()
+" name "+name_edittext.getText().toString());
Intent intent=new Intent(Generate_Outpass.this, Sucess_Outpass_Activity.class);
intent.putExtra("enroll",enroll_edittext.getText().toString());
intent.putExtra("name",name_edittext.getText().toString());
intent.putExtra("course",course_edittext.getText().toString());
intent.putExtra("date_departure",date_departure);
intent.putExtra("date_arrival",date_arrival);
intent.putExtra("smobile",smobile);
intent.putExtra("fmobile",fmobile);
intent.putExtra("location",location);
intent.putExtra("hostel",hostel_number);
intent.putExtra("room",room_number);
intent.putExtra("purpose",reason);
intent.putExtra("femail",spinner.getSelectedItem().toString());
intent.putExtra("wemail",spinner_superintendent.getSelectedItem().toString());
intent.putExtra("ftoken",faculty_token);
intent.putExtra("wtoken",superintendent_token);
intent.putExtra("year",year_editText.getText().toString());
intent.putExtra("semester",semester_editText.getText().toString());
Log.e(TAG,"femail"+spinner.getSelectedItem().toString()
+" wemail "+spinner_superintendent.getSelectedItem().toString());
firebaseDatabase= FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference().child("JUET").child("Faculty");
FetchFirebaseKeydata fetchFirebaseKeydata=new FetchFirebaseKeydata(name_edittext.getText().toString()
,enroll,spinner.getSelectedItem().toString()
,spinner_superintendent.getSelectedItem().toString());
databaseReference.child(enroll).setValue(fetchFirebaseKeydata);
progressDialog.dismiss();
startActivity(intent);
finish();
}
else {
Toast.makeText(Generate_Outpass.this, "Please Try Again !", Toast.LENGTH_SHORT).show();
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG,"Error in connection"+error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}*/
}
<file_sep>/README.md
# MyOutpass
Android Application for generating Outpass for JUET college students
# Online College Outpass Android Application . Fast way to get approval of Outpass After 2 - step Verification to ensure that no fake outpass generated.
Link to Application is : - https://drive.google.com/open?id=1Hgt8H7nTCIKukLViMbZS1MsLbNMfLRN0
<img width=" 250px" height="450px" src="https://github.com/logicgupta/JuetOutpass/blob/master/Images/Screenshot_2019-09-01-20-52-12-457_com.example.android.myoutpass.png"/>
<img width=" 250px" height="450px" src="https://github.com/logicgupta/JuetOutpass/blob/master/Images/Screenshot_2019-09-01-20-50-14-633_com.example.android.myoutpass.png">
<img width=" 250px" height="450px" src="https://github.com/logicgupta/JuetOutpass/blob/master/Images/Screenshot_2019-09-01-20-50-21-370_com.example.android.myoutpass.png">
<file_sep>/app/src/main/java/Website/StudentWebkoishdata.java
package Website;
import android.content.Context;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class StudentWebkoishdata {
private HttpClient httpClient_get = null;
HttpContext localContext = new BasicHttpContext();
InputStream inputStream = null;
String json;
public void getResponse(String colg,String enroll, String pass,String captcha, Context context) throws IOException {
WebsiteLogin ab = new WebsiteLogin();
HttpPost httppost = new HttpPost(WebkoiskWebsite.getLoginUrl(colg));
BufferedReader reader = null;
BufferedReader personal_reader = null;
Integer status = null;
localContext = ab.getLocalContext();
HttpGet httpGet = new HttpGet(WebkoiskWebsite.getPersonalInfo(colg));
HttpResponse personal_response = httpClient_get.execute(httpGet, localContext);
HttpEntity httpEntity = personal_response.getEntity();
inputStream = httpEntity.getContent();
status=ab.login(colg,enroll,pass,captcha,context);
try {
if (status == 1) {
BufferedReader reader2 = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader2.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
json = sb.toString();
Document document = Jsoup.parse(json);
Log.d("Website Login ", " Personal " + document);
Element table1 = document.select("table").get(1);
Elements rows = table1.select("tr");
for (int i = 0; i < rows.size(); i++) {
Element row = rows.get(i);
Elements cols = row.select("td");
if (cols.get(0).text().equals("Name")) {
String name1 = cols.get(1).text();
Log.d("Username ", "My NAME IS " + name1);
}
}
}
}
catch (IOException e) {
status = LoginStatus.UNKNOWN_ERROR;
httppost.abort();
e.printStackTrace();
}
}
}
<file_sep>/app/src/main/java/com/example/android/myoutpass/Outpass_Details/Otp_Generate.java
package com.example.android.myoutpass.Outpass_Details;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.android.myoutpass.Model.FetchFirebaseKeydata;
import com.example.android.myoutpass.R;
import com.example.android.myoutpass.app.Config;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.msg91.sendotp.library.SendOtpVerification;
import com.msg91.sendotp.library.Verification;
import com.msg91.sendotp.library.VerificationListener;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.util.Random;
import cn.iwgang.countdownview.CountdownView;
public class Otp_Generate extends AppCompatActivity implements VerificationListener{
Spinner mobile_number_spinner;
Button otp_button;
EditText editText;
String a[];
public static final String TAG=Otp_Generate.class.getSimpleName();
Verification mVerification;
ProgressDialog progressDialog;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
public String enroll;
public String name;
public String course;
public String date_depature;
public String date_arrival;
public String smobile;
public String hostel;
public String room;
public String location;
public String purpose;
public String pmobile;
Bundle bundle;
String femail;
String wemail;
String ftoken;
String wtoken;
String year;
String semester;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.otp_generate);
// Getting the Intent data
bundle=getIntent().getExtras();
enroll=bundle.getString("enroll");
name=bundle.getString("name");
course=bundle.getString("course");
date_depature=bundle.getString("date_departure");
date_arrival=bundle.getString("date_arrival");
smobile=bundle.getString("smobile");
pmobile=bundle.getString("fmobile"); // Parents Mobile Number
location=bundle.getString("location");
hostel=bundle.getString("hostel");
room=bundle.getString("room");
purpose=bundle.getString("purpose");
year=bundle.getString("year");
semester=bundle.getString("semester");
femail=bundle.getString("femail");
wemail=bundle.getString("wemail");
ftoken=bundle.getString("ftoken"); // Warden Token
wtoken=bundle.getString("wtoken"); // Superintendent Token
SharedPreferences preferences=getApplicationContext().getSharedPreferences("UserData",MODE_PRIVATE);
String fmobile=preferences.getString("Father's Mobile Number",null);
a=fmobile.split(",",9);
mobile_number_spinner=findViewById(R.id.spinner);
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<>(Otp_Generate.this,android.R.layout.simple_list_item_1,a);
mobile_number_spinner.setAdapter(arrayAdapter);
otp_button=findViewById(R.id.otp_generate_button);
otp_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mobile=mobile_number_spinner.getSelectedItem().toString();
if(mobile.equals("")){
Toast.makeText(Otp_Generate.this, "Please Select Valid Number", Toast.LENGTH_SHORT).show();
}
else {
progressDialog=new ProgressDialog(Otp_Generate.this);
progressDialog.setMessage("Sending OTP ...");
progressDialog.setCancelable(false);
progressDialog.show();
otpgenerate(mobile);
mVerification.initiate();
}
}
});
}
public void otpgenerate(String number){
Random random=new Random();
int n= random.nextInt(5982)+1;
String otp_code=String.valueOf(n);
mVerification= SendOtpVerification.createSmsVerification(
SendOtpVerification.config("+91"+"8963970412")
// .message("For Insuing Outpass Your Ward "+name+" Requested Outpass.THis is verifaction code "+otp_code)
// .httpsConnection(false)
// .expiry("1000")
// .senderId("OTBS")
// .otp(otp_code)
// .otplength("4")
.context(Otp_Generate.this)
.autoVerification(true)
.build(),
Otp_Generate.this
);
}
@Override
public void onInitiated(String response) {
progressDialog.dismiss();
Log.d(TAG, "Initialized!" + response);
//OTP successfully resent/sent.
Dialog dialog=new Dialog(Otp_Generate.this);
setContentView(R.layout.parent_verify_otp);
editText=findViewById(R.id.verify_otp);
Button button=findViewById(R.id.validate_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String otp_code=editText.getText().toString();
if(otp_code.equals("")){
Toast.makeText(Otp_Generate.this, "Please Enter THe OTP !", Toast.LENGTH_SHORT).show();
}
else {
mVerification.verify(otp_code);
}
}
});
}
@Override
public void onInitiationFailed(Exception paramException) {
progressDialog.dismiss();
Toast.makeText(this, "Please Try Again!", Toast.LENGTH_SHORT).show();
Log.d(TAG,"Verification Inititated Failed");
}
@Override
public void onVerified(String response) {
progressDialog.dismiss();
Log.d(TAG,"Verified Response"+response);
sendNotification();
}
@Override
public void onVerificationFailed(Exception paramException) {
progressDialog.dismiss();
Toast.makeText(this, " Invalid OTP !", Toast.LENGTH_SHORT).show();
Log.d(TAG,"Verification Failed");
}
public void sendNotification(){
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Sending your Outpass ....");
progressDialog.show();
SharedPreferences sharedPreferences=getApplicationContext().getSharedPreferences(Config.SHARED_PREF,0);
final String regId=sharedPreferences.getString("regId",null);
String firebaseRegId=regId;
final String title="OUTPASS";
final String message=" "+name+" ("+enroll+") "+" is requesting for outpass .";
Log.e(TAG,"F reg"+ftoken);
StringRequest stringRequest=new StringRequest(Request.Method.POST,
"https://juetoutpass.000webhostapp.com/firebase/index.php?regId="+ftoken+"&title="+title.trim().replace(' ','_')+"&team="+regId+"&score="+wtoken+"&message="+message.trim().replace(' ','_')+"&push_type=individual&team=logic&score=123"
,new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e(TAG,"Response is"+response);
Document document= Jsoup.parse(response);
Element div1=document.select("div").get(0);
Element pre=div1.select("pre").get(0);
Log.e(TAG,"Html Parser "+pre.text());
try {
JSONObject jsonObject1=new JSONObject(pre.text());
JSONObject jsonObject11=jsonObject1.getJSONObject("data");
String title1=jsonObject11.getString("title");
String message=jsonObject11.getString("message");
Log.e(TAG,"Title :"+title1);
Log.e(TAG,"Message : "+message);
if (title1.equals(title)) {
Intent intent=new Intent(Otp_Generate.this, Sucess_Outpass_Activity.class);
intent.putExtra("enroll",enroll);
intent.putExtra("name",name);
intent.putExtra("course",course);
intent.putExtra("date_departure",date_depature);
intent.putExtra("date_arrival",date_arrival);
intent.putExtra("smobile",smobile);
intent.putExtra("fmobile",pmobile);
intent.putExtra("location",location);
intent.putExtra("hostel",hostel);
intent.putExtra("room",room);
intent.putExtra("purpose",purpose);
intent.putExtra("femail",femail);
intent.putExtra("wemail",wemail);
intent.putExtra("ftoken",ftoken);
intent.putExtra("wtoken",wtoken);
intent.putExtra("year",year);
intent.putExtra("semester",semester);
Log.e(TAG," Warden Email :femail"+femail
+" *** Superientendent Email wemail "+ wemail);
firebaseDatabase= FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference().child("JUET").child("Faculty");
FetchFirebaseKeydata fetchFirebaseKeydata=new FetchFirebaseKeydata(name
,enroll,femail
,wemail);
databaseReference.child(enroll).setValue(fetchFirebaseKeydata);
progressDialog.dismiss();
startActivity(intent);
finish();
}
else {
Toast.makeText(Otp_Generate.this, "Please Try Again !", Toast.LENGTH_SHORT).show();
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG,"Error in connection"+error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
<file_sep>/app/src/main/java/com/example/android/myoutpass/Denied/Details_Denied_Outpass.java
package com.example.android.myoutpass.Denied;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.android.myoutpass.Accept.Details_Accept_Outpass;
import com.example.android.myoutpass.Model.Listdata;
import com.example.android.myoutpass.Model.studentDetails;
import com.example.android.myoutpass.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class Details_Denied_Outpass extends AppCompatActivity {
private static final String TAG = Details_Accept_Outpass.class.getSimpleName();
TextView textView,nameTextView;
String femail1;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
Bundle bundle;
String enroll;
String key;
String studenttoken;
String superintendenttoken;
List<Listdata> list=new ArrayList<Listdata>();
ImageView imageView;
String imageUrl;
CircleImageView circleImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details__denied__outpass);
bundle=getIntent().getExtras();
//getUserEmailId();
enroll=bundle.getString("detail",null);
key=bundle.getString("key",null);
femail1=bundle.getString("femail12",null);
imageUrl=bundle.getString("imageUrl",null);
Log.e(TAG,"enroll "+enroll+"femail:"+femail1);
circleImageView=findViewById(R.id.imageView4);
Glide.with(this).load(imageUrl)
.into(circleImageView);
textView=findViewById(R.id.detailed_textView);
imageView=findViewById(R.id.grcode);
nameTextView=findViewById(R.id.nameview);
SharedPreferences preferences=getApplicationContext()
.getSharedPreferences("UserData",MODE_PRIVATE);
String sname=preferences.getString("Name11",null);
nameTextView.setText(sname);
firebaseDatabase=FirebaseDatabase.getInstance();
String [] args=femail1.split("[@,.]+");
StringBuilder stringBuilder=new StringBuilder("");
for (String ans_femail:args){
stringBuilder.append(ans_femail);
}
String final_femail=stringBuilder.toString();
databaseReference=firebaseDatabase.getReference()
.child("JUET")
.child("Faculty")
.child(final_femail)
.child(enroll);
getFirebaseData();
}
public void getFirebaseData(){
databaseReference.child(key).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG," "+dataSnapshot);
studentDetails details=dataSnapshot.getValue(studentDetails.class);
Listdata listdata=new Listdata();
String name=details.getName();
String enroll=details.getEnroll();
String message=details.getMessage();
String qrcode=details.getQrcode();
try {
Bitmap imageBitmap = decodeFromFirebaseBase64(qrcode);
imageView.setImageBitmap(imageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
textView.setText(message);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public static Bitmap decodeFromFirebaseBase64(String image) throws IOException {
byte[] decodedByteArray = android.util.Base64.decode(image, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(decodedByteArray, 0, decodedByteArray.length);
}
}
|
f8d507174fb11b24cb0b9c0c773e334ccb233bf8
|
[
"Markdown",
"Java"
] | 13 |
Java
|
logicgupta/MyOutpass
|
b6dde6de2e2d3efc6f733bc7c9ccbd1923352584
|
336bcc64eb775663bd6db6b8df27b5ffa0082c48
|
refs/heads/master
|
<repo_name>ortsed/django-wordiff<file_sep>/README.md
django-wordiff
==============
Uses an n-gram search to find similar files<file_sep>/wordiff/tasks.py
from wordiff.models import ObjectGram, IgnoredGram, GramRankings
from wordiff.n_gram_splitter import lang_model
from django.conf import settings
from HTMLParser import HTMLParser
from django.db import connection, IntegrityError
from datetime import datetime
NGRAM_LENGTH = 8
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
if hasattr(settings, "WORDIFF_NGRAM_LENGTH"):
NGRAM_LENGTH = settings.WORDIFF_NGRAM_LENGTH
def gram_parse_object_text(object, object_text):
"""
Parses out an object into its N-grams and saves them
Can be included as a task, celery task, a post-save signal,
or part of the save method
but may need to be modified accordingly
"""
parsed = lang_model(strip_tags(object_text))
for gram in parsed.gram(NGRAM_LENGTH):
object_gram = ObjectGram()
object_gram.gram = gram
object_gram.state = object.bill.bill_details["state"]
object_gram.object = object
object_gram.save()
def update_gram_rankings():
cursor = connection.cursor()
cursor.execute("""
DELETE FROM wordiff_objectgramrank;
DELETE FROM wordiff_objectgram_unique;
INSERT INTO wordiff_objectgram_unique (`gram`, `state`) SELECT DISTINCT gram, state FROM wordiff_objectgram;
INSERT INTO
wordiff_objectgramrank
(`gram`, `rank`)
SELECT gram, count(id) FROM wordiff_objectgram_unique
GROUP BY gram;
UPDATE wordiff_objectgram
LEFT JOIN wordiff_objectgramrank
ON wordiff_objectgram.gram = wordiff_objectgramrank.gram
SET wordiff_objectgram.rank = wordiff_objectgramrank.rank
""")
def remove_ignored_grams():
ignored_grams = IgnoredGram.objects.all()
for gram in ignored_grams:
ObjectGram.objects.filter(gram=gram).delete()
def add_common_grams_to_ignored():
common_grams = ObjectGram.objects.filter(rank__gt=15)
for gram in common_grams:
try:
ignored_gram = IgnoredGram()
ignored_gram.gram = gram.gram
ignored_gram.date_published = datetime.today()
ignored_gram.save()
except IntegrityError:
pass
# cursor = connection.cursor()
# cursor.execute("INSERT INTO wordiff_ignoredgram (`gram`, `date_created`) SELECT gram, NOW() FROM wordiff_objectgram WHERE rank > 25")
<file_sep>/wordiff/models.py
from django.db import models
from lawdiff.models import Bill_File
class ObjectGramManager(models.Manager):
pass
class ObjectGram(models.Model):
objects = ObjectGramManager()
state = models.CharField(max_length=10, null=False, blank=False)
object = models.ForeignKey(Bill_File, null=False, blank=False)
gram = models.CharField(max_length=1000, null=False, blank=False)
rank = models.PositiveIntegerField(null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
@property
def similar_objects(self):
qs = ObjectGram.objects.filter(gram=self.gram).order_by("object")
qs.group_by = ['object']
return qs
def __unicode__(self, *args, **kwargs):
return self.gram
class GramRankings(models.Model):
gram = models.CharField(max_length=1000, null=False, blank=False)
rank = models.PositiveIntegerField(null=False, blank=False)
class GramUnique(models.Model):
gram = models.CharField(max_length=1000, null=False, blank=False)
state = models.CharField(max_length=10, null=False, blank=False)
class IgnoredGram(models.Model):
gram = models.CharField(max_length=255L, unique=True)
date_created = models.DateTimeField(auto_now_add=True)
<file_sep>/wordiff/n_gram_splitter.py
# n-gram-splitter
""" Has a class called langmodel that takes a text and creates an NLTK FreqDist object
that has counts of unigrams, bigrams, and trigrams.
Example Usage:
s = "This is a test string. This is a test string. This is a test string. This is a test string. This is a test string. This is a test string. This is a test string. This is a test string."
test_lang_model = lang_model(s)
To access word counts of a specific n-gram:
- e.g. for unigrams
test_lang_model.uni_fd.count(<<WORD>>)
List of Strings
test_lang_model.uni_fd.keys()
List of Tuples with (STRING, COUNT)
test_lang_model.uni_fd.items()
"""
from nltk.corpus import stopwords
from nltk import FreqDist, wordpunct_tokenize, cluster, ingrams
from django.conf import settings
stopwords_new = stopwords.words('english')
# If defined in settings, ADDITIONAL_STOPWORDS is a list of words to be added to the stopwords list
if hasattr(settings, "WORDIFF_ADDITIONAL_STOPWORDS"):
stopwords_new.append(settings.ADDITIONAL_STOPWORDS)
def _sliding_window(l, n):
return [tuple(l[i:i + n]) for i in range(len(l) - n + 1)]
def _remove_stopwords_lowercase(words):
"""
Remove stopwords, convert all words to lowercase, exclude numbers
"""
return [w.lower() for w in words if not w.lower()
in stopwords_new and w.isalpha()]
def make_ngram_tuples(l, n):
l = _remove_stopwords_lowercase(l)
t = _sliding_window(l, n)
phrase_list = []
if n == 1:
phrase_list = [s for (s,) in t]
else:
list_of_tuples = [(tuple(s[:-1]), s[-1]) for s in t]
for phrase in list_of_tuples:
#print phrase
if n == 2:
phrase_list.append("%s %s" % (phrase[0][0], phrase[1]))
if n == 3:
phrase_list.append("%s %s %s" % (phrase[0][0], phrase[0][1], phrase[1]))
return phrase_list
def ngrams(l, n):
l = _remove_stopwords_lowercase(l)
phrase_list = []
for n_grams in ingrams(l, n):
phrase_list.append(' '.join(n_grams))
return phrase_list
class lang_model():
"""Creates a language model of given text"""
def __init__(self, text):
self.tokens = wordpunct_tokenize(text)
# self.unigram = make_ngram_tuples(tokens, 1)
# self.bigram = make_ngram_tuples(tokens, 2)
# self.trigram = make_ngram_tuples(tokens, 3)
# self.uni_fd = FreqDist(self.unigram)
# self.bi_fd = FreqDist(self.bigram)
# self.tri_fd = FreqDist(self.trigram)
#self.big_gram = make_ngram_tuples(tokens, 8)
self.big_gram = ngrams(self.tokens,8)
self.big_fd = FreqDist(self.big_gram)
def gram(self, size):
return ngrams(self.tokens, size)
if __name__ == '__main__':
s = "This is a test string. This is a test string. This is a test string. This is a test string. This is a test string. This is a test string. This is a test string. This is a test string."
test_lang_model = lang_model(s)
print test_lang_model.uni_fd.items()
|
86bc1304067adc394cb93320b36ea96e1a9ffd40
|
[
"Markdown",
"Python"
] | 4 |
Markdown
|
ortsed/django-wordiff
|
503bcb63dbdf1ac4eff8cfb188b9720d9511c343
|
faf78d74cde94d98576f7a5beac8f50b89630b6f
|
refs/heads/master
|
<repo_name>hainguyenvan6799/hocGit<file_sep>/index.php
<?php
"echo XIn chao";
"da co them 1 ng fork";
"alo";
"tu ben klhac";
"abc";
?>
|
34b0670353583d867e669428bc35809105207c52
|
[
"PHP"
] | 1 |
PHP
|
hainguyenvan6799/hocGit
|
534b47bb9a38873d1cef8d247e826600a1cb17d3
|
39b7be8b2ff6b0f9e595438bf43b0110e7614b02
|
refs/heads/master
|
<file_sep>import { Injectable } from '@angular/core';
import { UtilityProvider } from '../utility/utility';
@Injectable()
export class ApiProvider {
domain: string;
constructor(private utils: UtilityProvider) {
this.domain = "https://vast-shore-74260.herokuapp.com/";
}
getBanks(city, requestHeaders) {
return new Promise((resolve, reject) => {
let endPoint = this.domain + "banks?city=" + city;
this.utils.makeGetRequest(endPoint, requestHeaders)
.then((resp: any) => {
resolve(resp);
})
.catch((err) => {
reject(err);
})
})
}
}
<file_sep>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'bankFilter',
})
export class BankFilterPipe implements PipeTransform {
transform(banks: any, nameFilter: any, branchFilter: any, ifscFilter: any): any {
if (nameFilter == null && branchFilter == null && ifscFilter == null) return banks;
let filteredBanks = banks;
if (nameFilter != "") {
filteredBanks = filteredBanks.filter(bank => {
return (bank.bank_name.toLowerCase().indexOf(nameFilter.toLowerCase()) > -1)
})
}
if (branchFilter != "") {
filteredBanks = filteredBanks.filter(bank => {
return (bank.branch.toLowerCase().indexOf(branchFilter.toLowerCase()) > -1)
})
}
let ifscFilteredBanks;
if (ifscFilter.length > 0) {
ifscFilter.forEach(ifsc => {
let banks = filteredBanks.filter(bank => {
return (bank.ifsc.toLowerCase().indexOf(ifsc.toLowerCase()) > -1)
})
if(ifscFilteredBanks){
banks.forEach(e=>{
ifscFilteredBanks.push(e);
});
}
else{
ifscFilteredBanks = banks;
}
})
return ifscFilteredBanks;
}
return filteredBanks;
}
}
<file_sep>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController } from 'ionic-angular';
import { UtilityProvider } from '../../providers/utility/utility';
import { ApiProvider } from '../../providers/api/api';
@IonicPage()
@Component({
selector: 'page-home',
templateUrl: 'home.html',
})
export class HomePage {
banks: any = [];
city: any = "MUMBAI";
cities: any = [];
nameFilter: any = "";
branchFilter: any = "";
ifscFilter: any = "";
filters;
constructor(public navCtrl: NavController,
public api: ApiProvider,
public utils: UtilityProvider,
public navParams: NavParams,
public modalCtrl: ModalController) {
this.cities = [
"BANGALORE",
"CHENNAI",
"DELHI",
"KOLKATA",
"MUMBAI",
"PUNE"
];
}
ionViewDidLoad() {
this.getBanks();
}
onCityChange() {
this.getBanks();
this.nameFilter = "";
this.branchFilter = "";
this.ifscFilter = [];
}
getBanks() {
let requestHeaders: any = {};
this.utils.showLoading();
this.api.getBanks(this.city, requestHeaders).then((res: any) => {
this.banks = res;
this.utils.hideLoading();
}).catch(err => {
console.log(err);
this.utils.hideLoading();
})
}
openFilters() {
let modal = this.modalCtrl.create('FiltersPage', {filters: this.filters}, {
showBackdrop: true,
enableBackdropDismiss: true
});
modal.onDidDismiss(data => {
if (data && data.params) {
this.nameFilter = data.params.name;
this.branchFilter = data.params.branch;
this.ifscFilter = data.params.ifscList.length > 0 ? data.params.ifscList : "";
this.filters = data.params;
}
});
modal.present();
}
// onSearch(event) {
// this.searchText = event;
// }
}
<file_sep>import { Injectable } from '@angular/core';
import { Headers, RequestOptions, Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import { AlertController, ToastController, LoadingController, App } from 'ionic-angular';
@Injectable()
export class UtilityProvider {
loader;
constructor(private http: Http,
public alertCtrl: AlertController,
public toastCtrl: ToastController,
public loadingCtrl: LoadingController,
public app: App) {
}
showAlert(title: string, subTitle: string): void {
let alert = this.alertCtrl.create({
title: title,
subTitle: subTitle,
buttons: ['OK']
});
alert.present();
}
showLoading(message?: string) {
if (!message) {
message = "Please Wait...";
}
this.loader = this.loadingCtrl.create({
content: message,
});
this.loader.present();
}
hideLoading() {
this.loader.dismiss();
}
makeGetRequest(url, requestHeaders?) {
return new Promise((resolve, reject) => {
let headers: any = new Headers();
if (requestHeaders.token) {
headers.append('Authorization', 'Token ' + requestHeaders.token);
}
let requestOptions = (headers == undefined) ? undefined : new RequestOptions({ headers: headers });
this.http.get(url, requestOptions)
.subscribe((res: Response) => {
if (res.status === 200 || res.status === 201) {
resolve(res.json());
}
}, error => {
if (error.status == 400) {
resolve(error.json());
} else {
reject(error);
}
});
})
}
makePostRequest(url, params?, requestHeaders?, isMultipart?) {
return new Promise((resolve, reject) => {
let headers: any = new Headers();
if (requestHeaders.msisdn) {
headers.append('msisdn', requestHeaders.msisdn);
} else if (requestHeaders.token) {
headers.append('Authorization', 'Token ' + requestHeaders.token);
}
if (!isMultipart) {
headers.append('Content-Type', 'application/json; charset=utf-8');
}
let requestOptions = (headers == undefined) ? undefined : new RequestOptions({ headers: headers });
this.http.post(url, params, requestOptions)
.subscribe((res: Response) => {
if (res.status === 200 || res.status === 201) {
resolve(res.json());
}
}, error => {
if (error.status == 400) {
resolve(error.json());
} else {
reject(error);
}
});
})
}
makePutRequest(url, params?, requestHeaders?, isMultipart?) {
return new Promise((resolve, reject) => {
let headers: any = new Headers();
if (requestHeaders.msisdn) {
headers.append('msisdn', requestHeaders.msisdn);
} else {
headers.append('Authorization', 'Token ' + requestHeaders.token);
}
if (!isMultipart) {
headers.append('Content-Type', 'application/json; charset=utf-8');
}
let requestOptions = (headers == undefined) ? undefined : new RequestOptions({ headers: headers });
this.http.put(url, params, requestOptions)
.subscribe((res: Response) => {
if (res.status === 200 || res.status === 201) {
resolve(res.json());
}
}, error => {
if (error.status == 400) {
resolve(error.json());
} else {
reject(error);
}
});
})
}
makeDeleteRequest(url, requestHeaders?) {
return new Promise((resolve, reject) => {
let headers: any = new Headers();
if (requestHeaders.msisdn) {
headers.append('msisdn', requestHeaders.msisdn);
} else {
headers.append('Authorization', 'Token ' + requestHeaders.token);
}
headers.append('content-type', 'application/json; charset=utf-8');
let requestOptions = (headers == undefined) ? undefined : new RequestOptions({ headers: headers });
this.http.delete(url, requestOptions)
.subscribe((res: Response) => {
if (res.status === 200 || res.status === 201) {
resolve(res.json());
}
}, error => {
if (error.status == 400) {
resolve(error.json());
} else {
reject(error);
}
});
})
}
}
<file_sep>import { NgModule } from '@angular/core';
import { InitialsPipe } from './initials/initials';
import { BankFilterPipe } from './bank-filter/bank-filter';
@NgModule({
declarations: [InitialsPipe,
BankFilterPipe],
imports: [],
exports: [InitialsPipe,
BankFilterPipe]
})
export class PipesModule {}
<file_sep>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';
import { FormGroup, FormBuilder } from '@angular/forms';
@IonicPage()
@Component({
selector: 'page-filters',
templateUrl: 'filters.html',
})
export class FiltersPage {
filterForm: FormGroup;
ifscList: any;
constructor(public navCtrl: NavController,
public navParams: NavParams,
public viewCtrl: ViewController,
public formBuilder: FormBuilder) {
let filters = navParams.get("filters")
if (filters) {
this.filterForm = formBuilder.group({
name: [filters.name],
branch: [filters.branch]
});
this.ifscList = filters.ifscList;
}
else {
this.filterForm = formBuilder.group({
name: [''],
branch: ['']
})
this.ifscList = [];
}
}
apply() {
let filterParams: any = {};
filterParams = this.filterForm.value;
filterParams.ifscList = this.ifscList;
this.dismiss(filterParams);
}
dismiss(params?) {
this.viewCtrl.dismiss({ params: params });
}
}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { FiltersPage } from './filters';
import {IonTagsInputModule} from "ionic-tags-input";
@NgModule({
declarations: [
FiltersPage,
],
imports: [
IonicPageModule.forChild(FiltersPage),
IonTagsInputModule
],
})
export class FiltersPageModule {}
|
5ca3ecc24176020acebb3c7e65a628522d0b610c
|
[
"TypeScript"
] | 7 |
TypeScript
|
piyushpandey14/bank-app
|
58fe5c1205360a2e304a1a694a3543a2604d29b9
|
ee65afd892ee4e79c1eb68fd0768fef933a4ac62
|
refs/heads/master
|
<repo_name>pozag/wikistack<file_sep>/app.js
const express = require('express');
const morgan = require('morgan');
const app = express();
const mainPage = require('./views/main');
const { db, models } = require('./models');
const Sequelize = require('sequelize');
const wikiRouter = require('./routes/wiki.js');
const userRouter = require('./routes/user.js');
app.use(morgan("dev"));
app.use(express.static(__dirname + "/public"));
app.use(express.urlencoded({extended: false}));
app.use('/wiki', wikiRouter);
app.use('/user', userRouter);
const init = async () => {
await db.authenticate();
console.log('Connected to the database...');
await db.sync({ force: true });
console.log('Synced to database...')
app.listen(3000, () => {
console.log("Listening...");
})
}
init();
app.get('/', (req, res) =>{
res.redirect('/wiki');
})
<file_sep>/routes/.#wiki.js
pozag@pozag-XPS-13-9360.10759:1573099708<file_sep>/routes/wiki.js
const express = require('express');
const router = express.Router();
const allPages = require('../views/main');
const addPage = require('../views/addPage');
const wikiPage = require('../views/wikipage');
const { models } = require("../models/index");
const Page = models.Page;
router.get('/', (req, res) => {
res.send(allPages(''));
});
router.post('/', async (req, res, next) => {
const page = new Page({
title: req.body.title,
content: req.body.content,
});
try {
await page.save();
res.redirect('/');
} catch (error) { next(error) }
});
router.get('/add', (req, res) => {
res.send(addPage());
});
router.get('/:slug', async (req, res) => {
const allPages = await Page.findAll();
console.log("allpages", allPages);
console.log("slug", req.params.slug);
const foundPage = await Page.findOne({
where: { slug: req.params.slug }
});
console.log("found Page", foundPage);
res.send(wikiPage(foundPage.title, foundPage.author));
});
module.exports = router;
|
b1d08a27715a41a1119dd12f49c8eadd6ec6224b
|
[
"JavaScript"
] | 3 |
JavaScript
|
pozag/wikistack
|
d54bfd6b3d9a3a0cb0614af7142176af56501fc2
|
2c6983f098699306bbea2c99c06dfadab7338207
|
refs/heads/master
|
<repo_name>liulaojian/ScreenToGif<file_sep>/ScreenToGif/Windows/Other/Localization.xaml.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.Win32;
using ScreenToGif.Controls;
using ScreenToGif.Util;
namespace ScreenToGif.Windows.Other
{
public partial class Localization : Window
{
public Localization()
{
InitializeComponent();
}
#region Events
private void Localization_OnLoaded(object sender, RoutedEventArgs e)
{
foreach (var resourceDictionary in Application.Current.Resources.MergedDictionaries)
{
var imageItem = new ImageListBoxItem
{
Tag = resourceDictionary.Source?.OriginalString ?? "Settings",
Content = resourceDictionary.Source?.OriginalString ?? "Settings"
};
if (resourceDictionary.Source == null)
{
imageItem.IsEnabled = false;
imageItem.Image = FindResource("Vector.No") as Canvas;
imageItem.Author = "This is a settings dictionary.";
}
else if (resourceDictionary.Source.OriginalString.Contains("StringResources"))
{
imageItem.Image = FindResource("Vector.Translate") as Canvas;
#region Name
var subs = resourceDictionary.Source.OriginalString.Substring(resourceDictionary.Source.OriginalString.IndexOf("StringResources"));
var pieces = subs.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries);
if (pieces.Length == 3)
{
imageItem.Author = "Recognized as " + pieces[1];
}
else
{
imageItem.Author = "Not recognized";
}
#endregion
}
else
{
imageItem.IsEnabled = false;
imageItem.Image = FindResource("Vector.No") as Canvas;
imageItem.Author = "This is a style dictionary.";
}
ResourceListBox.Items.Add(imageItem);
}
ResourceListBox.SelectedIndex = ResourceListBox.Items.Count - 1;
ResourceListBox.ScrollIntoView(ResourceListBox.SelectedItem);
CommandManager.InvalidateRequerySuggested();
}
private void MoveUp_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = ResourceListBox.SelectedIndex > 0;
}
private void MoveDown_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = ResourceListBox.SelectedIndex < ResourceListBox.Items.Count - 1;
}
private void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = ResourceListBox.SelectedIndex != -1;
}
private void Remove_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = ResourceListBox.SelectedIndex != -1;
}
private void Add_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void MoveUp_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (LocalizationHelper.Move(ResourceListBox.SelectedIndex))
{
var selectedIndex = ResourceListBox.SelectedIndex;
var selected = ResourceListBox.Items[selectedIndex];
ResourceListBox.Items.RemoveAt(selectedIndex);
ResourceListBox.Items.Insert(selectedIndex - 1, selected);
ResourceListBox.SelectedItem = selected;
}
CommandManager.InvalidateRequerySuggested();
}
private void MoveDown_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (LocalizationHelper.Move(ResourceListBox.SelectedIndex, false))
{
var selectedIndex = ResourceListBox.SelectedIndex;
var selected = ResourceListBox.Items[selectedIndex];
ResourceListBox.Items.RemoveAt(selectedIndex);
ResourceListBox.Items.Insert(selectedIndex + 1, selected);
ResourceListBox.SelectedItem = selected;
}
CommandManager.InvalidateRequerySuggested();
}
private void Save_Executed(object sender, ExecutedRoutedEventArgs e)
{
var sfd = new SaveFileDialog
{
AddExtension = true,
Filter = "Resource Dictionary (*.xaml)|*.xaml",
Title = "Save Resource Dictionary"
};
var source = ((ImageListBoxItem)ResourceListBox.SelectedItem).Content.ToString();
var subs = source.Substring(source.IndexOf("StringResources"));
sfd.FileName = subs;
var result = sfd.ShowDialog();
if (result.HasValue && result.Value)
LocalizationHelper.SaveSelected(ResourceListBox.SelectedIndex, sfd.FileName);
CommandManager.InvalidateRequerySuggested();
}
private void Remove_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (LocalizationHelper.Remove(ResourceListBox.SelectedIndex))
ResourceListBox.Items.RemoveAt(ResourceListBox.SelectedIndex);
CommandManager.InvalidateRequerySuggested();
}
private async void Add_Executed(object sender, ExecutedRoutedEventArgs e)
{
var ofd = new OpenFileDialog
{
AddExtension = true,
CheckFileExists = true,
Title = "Open a Resource Dictionary",
Filter = "Resource Dictionay (*.xaml)|*.xaml;"
};
var result = ofd.ShowDialog();
if (!result.HasValue || !result.Value) return;
#region Validation
if (!ofd.FileName.Contains("StringResources"))
{
Dispatcher.Invoke(() => Dialog.Ok("Action Denied", "The name of file does not follow a valid pattern.",
"Try renaming like (without the []): StringResources.[Language Code].xaml"));
return;
}
var subs = ofd.FileName.Substring(ofd.FileName.IndexOf("StringResources"));
if (Application.Current.Resources.MergedDictionaries.Any(x => x.Source != null && x.Source.OriginalString.Contains(subs)))
{
Dispatcher.Invoke(() => Dialog.Ok("Action Denied", "You can't add a resource with the same name.",
"Try renaming like: StringResources.[Language Code].xaml"));
return;
}
var pieces = subs.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if (pieces.Length != 3)
{
Dispatcher.Invoke(() => Dialog.Ok("Action Denied", "Filename with wrong format.",
"Try renaming like: StringResources.[Language Code].xaml"));
return;
}
var culture = new CultureInfo(pieces[1]);
if (culture.EnglishName.Contains("Unknown"))
{
Dispatcher.Invoke(() => Dialog.Ok("Action Denied", "Unknown Language.", $"The \"{pieces[1]}\" was not recognized as a valid language code."));
return;
}
var properCulture = await CheckSupportedCultureAsync(culture);
if(properCulture == null)
{
Dispatcher.Invoke(() => Dialog.Ok("Action Denied", "Unknown Language.", $"The \"{pieces[1]}\" and its family were not recognized as a valid language codes."));
return;
}
if(properCulture != culture)
{
Dispatcher.Invoke(() => Dialog.Ok("Action Denied", "Redundant Language Code.", $"The \"{pieces[1]}\" code is redundant. Try using \'{properCulture.Name}\" instead"));
return;
}
#endregion
try
{
await Task.Factory.StartNew(() => LocalizationHelper.ImportStringResource(ofd.FileName));
}
catch(Exception ex)
{
Dispatcher.Invoke(() => Dialog.Ok("Localization", "Localization - Importing Xaml Resource", ex.Message));
GC.Collect();
return;
}
var resourceDictionary = Application.Current.Resources.MergedDictionaries.LastOrDefault();
var imageItem = new ImageListBoxItem
{
Tag = resourceDictionary?.Source.OriginalString ?? "Unknown",
Content = resourceDictionary?.Source.OriginalString ?? "Unknown",
Image = FindResource("Vector.Translate") as Canvas,
Author = "Recognized as " + pieces[1]
};
ResourceListBox.Items.Add(imageItem);
ResourceListBox.ScrollIntoView(imageItem);
CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Methods
private async Task<CultureInfo> CheckSupportedCultureAsync(CultureInfo culture)
{
IEnumerable<CultureInfo> supportedCultures = await GetProperCulturesAsync();
if (supportedCultures.Contains(culture))
return culture;
CultureInfo t = culture;
while(t != CultureInfo.InvariantCulture)
{
if (supportedCultures.Contains(t))
return t;
t = t.Parent;
}
return null;
}
private async Task<IEnumerable<CultureInfo>> GetProperCulturesAsync()
{
IEnumerable<CultureInfo> allCodes = CultureInfo.GetCultures(CultureTypes.AllCultures).Where(x => !string.IsNullOrEmpty(x.Name));
try
{
IEnumerable<string> properCodes = await GetLanguageCodesAsync();
IEnumerable<CultureInfo> properCultures = allCodes.Where(x => properCodes.Contains(x.Name));
if (properCultures == null)
return allCodes;
return properCultures;
}
catch (Exception ex)
{
Dispatcher.Invoke(() => Dialog.Ok("Translator", "Translator - Getting Language Codes", ex.Message +
Environment.NewLine + "Loading all local language codes."));
}
GC.Collect();
return allCodes;
}
private async Task<IEnumerable<string>> GetLanguageCodesAsync()
{
var path = await GetLanguageCodesPathAsync();
if (string.IsNullOrEmpty(path))
throw new WebException("Can't get language codes. Path to language codes is null");
var request = (HttpWebRequest)WebRequest.Create(path);
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393";
var response = (HttpWebResponse)await request.GetResponseAsync();
using (var resultStream = response.GetResponseStream())
{
if (resultStream == null)
throw new WebException("Empty response from server when getting language codes");
using (var reader = new StreamReader(resultStream))
{
var result = reader.ReadToEnd();
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(result),
new System.Xml.XmlDictionaryReaderQuotas());
var json = await Task<XElement>.Factory.StartNew(() => XElement.Load(jsonReader));
var languages = json.Elements();
return languages.Where(x => x.XPathSelectElement("defs").Value != "0").Select(x => x.XPathSelectElement("lang").Value);
}
}
}
private async Task<string> GetLanguageCodesPathAsync()
{
var request = (HttpWebRequest)WebRequest.Create("https://datahub.io/core/language-codes/datapackage.json");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393";
var response = (HttpWebResponse)await request.GetResponseAsync();
using (var resultStream = response.GetResponseStream())
{
if (resultStream == null)
throw new WebException("Empty response from server when getting language codes path");
using (var reader = new StreamReader(resultStream))
{
var result = reader.ReadToEnd();
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(result),
new System.Xml.XmlDictionaryReaderQuotas());
var json = await Task<XElement>.Factory.StartNew(() => XElement.Load(jsonReader));
return json.XPathSelectElement("resources").Elements().Where(x => x.XPathSelectElement("name").Value == "ietf-language-tags_json").First().XPathSelectElement("path").Value;
}
}
}
#endregion
}
}
<file_sep>/ScreenToGif/Util/Model/StartupViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace ScreenToGif.Util.Model
{
internal class StartupViewModel : ApplicationViewModel
{
}
}
|
95efdd7c0ae2461bc9cf03d5d8a84a53b9831d02
|
[
"C#"
] | 2 |
C#
|
liulaojian/ScreenToGif
|
a5b50cea9d69981bd4a84ea0889a17c4e952b184
|
677eaee1b846fb2bb0bbc05c5229578afd379c08
|
refs/heads/main
|
<file_sep># charts
helm chart public repo
<file_sep>#!/bin/bash
set -x
set -e
find . -maxdepth 1 -mindepth 1 -not -path '*/\.*' -type d -exec helm package {} \;
helm repo index --url https://fallenangelblog.github.io/charts/ .
git add . && git commit -m 'rebuild' && git push
<file_sep># RocketMQ Helm
## 部署
``` shell
# git clone
# cd rocketmq-helm
kubectl create namespace rocketmq
# 部署测试集群, 单 Master
helm -n rocketmq install rocketmq -f examples/test.yml ./
# 部署生产集群, 多 Master 多 Slave
helm -n rocketmq install rocketmq -f examples/production.yaml ./
```
## Broker 集群架构
### 单 Master 模式
``` yaml
broker:
size:
master: 1
replica: 0
```
### 多 Master 模式
一个集群无Slave,全是Master,例如2个Master或者3个Master,这种模式的优缺点如下:
- 优点:配置简单,单个Master宕机或重启维护对应用无影响,性能最高;
- 缺点:单台机器宕机期间,这台机器上未被消费的消息在机器恢复之前不可订阅,消息实时性会受到影响。
``` yaml
broker:
size:
master: 3
replica: 0
```
### 多 Master 多 Slave 模式
每个Master配置一个Slave,有多对Master-Slave,HA采用异步复制方式,主备有短暂消息延迟(毫秒级),这种模式的优缺点如下:
- 优点:Master宕机后,消费者仍然可以从Slave消费,而且此过程对应用透明,不需要人工干预,性能同多Master模式几乎一样;
- 缺点:Master宕机,磁盘损坏情况下会丢失少量消息 (已经同步到 Slave 的数据不受影响)
``` yaml
broker:
size:
master: 3
replica: 1
# 3个 master 节点,每个 master 具有1个副节点,共6个 broker 节点
```
## 配置
``` yaml
# 集群名
clusterName: "cluster-production"
broker:
# 3个 master 节点,每个 master 具有1个副节点,共6个 broker 节点
size:
master: 3
replica: 1
# 修改 broker 容器镜像地址和版本
#image:
# repository: "apacherocketmq/rocketmq-broker"
# tag: "4.5.0-alpine-operator-0.3.0"
persistence:
enabled: true
size: 8Gi
#storageClass: gp2
# 主节点资源分配
master:
brokerRole: ASYNC_MASTER
jvmMemory: " -Xms4g -Xmx4g -Xmn1g "
resources:
limits:
cpu: 4
memory: 12Gi
requests:
cpu: 200m
memory: 6Gi
# 副节点资源分配
replica:
jvmMemory: " -Xms1g -Xmx1g -Xmn256m "
resources:
limits:
cpu: 4
memory: 8Gi
requests:
cpu: 50m
memory: 2Gi
nameserver:
replicaCount: 3
# 修改 nameserver 容器镜像地址和版本
#image:
# repository: "apacherocketmq/rocketmq-nameserver"
# tag: "4.5.0-alpine-operator-0.3.0"
resources:
limits:
cpu: 4
memory: 8Gi
requests:
cpu: 50m
memory: 1Gi
persistence:
enabled: true
size: 8Gi
#storageClass: gp2
dashboard:
enabled: true
replicaCount: 1
ingress:
enabled: true
className: "nginx"
hosts:
- host: rocketmq.example.com
paths:
- path: /
pathType: ImplementationSpecific
#tls:
# - secretName: example-com-tls
# hosts:
# - rocketmq.example.com
```
<file_sep># Introduction
This chart bootstraps an [EMQX](https://www.emqx.io/) deployment on a [Kubernetes](https://kubernetes.io/) (K8s) cluster using the [Helm](https://helm.sh/) package manager.
# Prerequisites
+ [Kubernetes](https://kubernetes.io/) 1.6+
+ [Helm](https://helm.sh/)
# Installing the Chart
To install the chart with the release name `my-emqx`:
+ From github
```
$ git clone https://github.com/emqx/emqx.git
$ cd emqx/deploy/charts/emqx
$ helm install my-emqx .
```
+ From chart repos
```
helm repo add emqx https://repos.emqx.io/charts
helm install my-emqx emqx/emqx
```
> If you want to install an unstable version, you need to add `--devel` when you execute the `helm install` command.
# Uninstalling the Chart
To uninstall/delete the `my-emqx` deployment:
```
$ helm del my-emqx
```
# Configuration
The following sections describe the configurable parameters of the chart and their default values.
## [K8s]((https://kubernetes.io/)) specific settings
The following table lists the configurable K8s parameters of the [EMQX](https://www.emqx.io/) chart and their default values.
Parameter | Description | Default Value
--- | --- | ---
`replicaCount` | It is recommended to have odd number of nodes in a cluster, otherwise the emqx cluster cannot be automatically healed in case of net-split. | `3`
`image.tag` | EMQX Image tag (defaults to `.Chart.AppVersion`) | `nil`
`image.repository` | EMQX Image repository | `emqx/emqx`
`image.pullPolicy` | The image pull policy | `IfNotPresent`
`image.pullSecrets ` | The image pull secrets (does not add image pull secrets to deployed pods) |``[]``
`recreatePods` | Forces the recreation of pods during upgrades, which can be useful to always apply the most recent configuration. | `false`
`persistence.enabled` | Enable EMQX persistence using PVC | `false`
`persistence.storageClass` | Storage class of backing PVC (uses alpha storage class annotation) | `nil`
`persistence.existingClaim` | EMQX data Persistent Volume existing claim name, evaluated as a template | `""`
`persistence.accessMode` | PVC Access Mode for EMQX volume | `ReadWriteOnce`
`persistence.size` | PVC Storage Request for EMQX volume | `20Mi`
`initContainers` | Containers that run before the creation of EMQX containers. They can contain utilities or setup scripts. |`{}`
`resources` | CPU/Memory resource requests/limits |`{}`
`nodeSelector` | Node labels for pod assignment |`{}`
`tolerations` | Toleration labels for pod assignment |``[]``
`affinity` | Map of node/pod affinities |`{}`
`service.type` | Kubernetes Service type. | `ClusterIP`
`service.mqtt` | Port for MQTT. | `1883`
`service.mqttssl` | Port for MQTT(SSL). | `8883`
`service.mgmt` | Port for mgmt API. | `8081`
`service.ws` | Port for WebSocket/HTTP. | `8083`
`service.wss` | Port for WSS/HTTPS. | `8084`
`service.dashboard` | Port for dashboard. | `18083`
`service.nodePorts.mqtt` | Kubernetes node port for MQTT. | `nil`
`service.nodePorts.mqttssl` | Kubernetes node port for MQTT(SSL). | `nil`
`service.nodePorts.mgmt` | Kubernetes node port for mgmt API. | `nil`
`service.nodePorts.ws` | Kubernetes node port for WebSocket/HTTP. | `nil`
`service.nodePorts.wss` | Kubernetes node port for WSS/HTTPS. | `nil`
`service.nodePorts.dashboard` | Kubernetes node port for dashboard. | `nil`
`service.loadBalancerIP` | loadBalancerIP for Service | `nil`
`service.loadBalancerSourceRanges` | Address(es) that are allowed when service is LoadBalancer | `[]`
`service.externalIPs` | ExternalIPs for the service | `[]`
`service.annotations` | Service annotations (evaluated as a template) | `{}`
`ingress.dashboard.enabled` | Enable ingress for EMQX Dashboard | false
`ingress.dashboard.ingressClassName` | Set the ingress class for EMQX Dashboard
`ingress.dashboard.path` | Ingress path for EMQX Dashboard | `/`
`ingress.dashboard.pathType` | Ingress pathType for EMQX Dashboard | `ImplementationSpecific`
`ingress.dashboard.hosts` | Ingress hosts for EMQX Mgmt API | dashboard.emqx.local
`ingress.dashboard.tls` | Ingress tls for EMQX Mgmt API | `[]`
`ingress.dashboard.annotations` | Ingress annotations for EMQX Mgmt API | `{}`
`ingress.mgmt.enabled` | Enable ingress for EMQX Mgmt API | `false`
`ingress.mqtt.ingressClassName` | Set the ingress class for EMQX Mgmt API | `nil`
`ingress.mgmt.path` | Ingress path for EMQX Mgmt API | `/`
`ingress.mgmt.pathType` | Ingress pathType for EMQX Mgmt API | `ImplementationSpecific`
`ingress.mgmt.hosts` | Ingress hosts for EMQX Mgmt API | `api.emqx.local`
`ingress.mgmt.tls` | Ingress tls for EMQX Mgmt API | `[]`
`ingress.mgmt.annotations` | Ingress annotations for EMQX Mgmt API | `{}`
`ingress.wss.enabled` | Enable ingress for EMQX Mgmt API | `false`
`ingress.wss.ingressClassName` | Set the ingress class for EMQX Mgmt API | `nil`
`ingress.wss.path` | Ingress path for EMQX WSS | `/`
`ingress.wss.pathType` | Ingress pathType for EMQX WSS | `ImplementationSpecific`
`ingress.wss.hosts` | Ingress hosts for EMQX WSS | `wss.emqx.local`
`ingress.wss.tls` | Ingress tls for EMQX WSS | `[]`
`ingress.wss.annotations` | Ingress annotations for EMQX WSS | `{}`
| `metrics.enable` | If set to true, [prometheus-operator](https://github.com/prometheus-operator/prometheus-operator) needs to be installed, and [emqx_prometheus](https://github.com/emqx/emqx/tree/main-v4.4/apps/emqx_prometheus) needs to enable | false |
| `metrics.type` | Now we only supported "prometheus" | "prometheus" |
`extraEnv` | Aditional container env vars | `[]`
`extraEnvFrom` | Aditional container env from vars (eg. [config map](https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/), [secrets](https://kubernetes.io/docs/concepts/configuration/secret/) | `[]`
`extraArgs` | Additional container executable arguments | `[]`
`extraVolumes` | Additional container volumes (eg. for mounting certs from secrets) | `[]`
`extraVolumeMounts` | Additional container volume mounts (eg. for mounting certs from secrets) | `[]`
## EMQX specific settings
The following table lists the configurable [EMQX](https://www.emqx.io/)-specific parameters of the chart and their default values.
Parameter | Description | Default Value
--- | --- | ---
`emqxConfig` | Map of [configuration](https://www.emqx.io/docs/en/latest/configuration/configuration.html) items expressed as [environment variables](https://www.emqx.io/docs/en/v4.3/configuration/environment-variable.html) (prefix can be omitted) or using the configuration files [namespaced dotted notation](https://www.emqx.io/docs/en/latest/configuration/configuration.html) | `nil`
`emqxLicenseSecretName` | Name of the secret that holds the license information | `nil`
`emqxAclConfig` | [ACL](https://docs.emqx.io/broker/latest/en/advanced/acl-file.html) configuration | `{allow, {user, "dashboard"}, subscribe, ["$SYS/#"]}. {allow, {ipaddr, "127.0.0.1"}, pubsub, ["$SYS/#", "#"]}. {deny, all, subscribe, ["$SYS/#", {eq, "#"}]}. {allow, all}.`
`emqxLoadedModules` | Modules to load on startup | `{emqx_mod_acl_internal, true}. {emqx_mod_presence, true}. {emqx_mod_delayed, false}. {emqx_mod_rewrite, false}. {emqx_mod_subscription, false}. {emqx_mod_topic_metrics, false}.`
`emqxLoadedPlugins` | Plugins to load on startup | `{emqx_management, true}. {emqx_recon, true}. {emqx_retainer, true}. {emqx_dashboard, true}. {emqx_telemetry, true}. {emqx_rule_engine, true}. {emqx_bridge_mqtt, false}.`
# Examples
This section provides some examples for the configuration of common scenarios.
## Enable Websockets SSL via [nginx-ingress community controller](https://kubernetes.github.io/ingress-nginx/)
The following settings describe a working scenario for acessing [EMQX](https://www.emqx.io/) Websockets with SSL termination at the [nginx-ingress community controller](https://kubernetes.github.io/ingress-nginx/).
```yaml
ingress:
wss:
enabled: true
# ingressClassName: nginx
annotations:
nginx.ingress.kubernetes.io/backend-protocol: "http"
nginx.ingress.kubernetes.io/use-forwarded-headers: "true"
nginx.ingress.kubernetes.io/enable-real-ip: "true"
nginx.ingress.kubernetes.io/proxy-request-buffering: "off"
nginx.ingress.kubernetes.io/proxy-connect-timeout: "120"
nginx.ingress.kubernetes.io/proxy-http-version: "1.1"
nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
nginx.ingress.kubernetes.io/use-proxy-protocol: "false"
nginx.ingress.kubernetes.io/proxy-protocol-header-timeout: "5s"
path: /mqtt
pathType: ImplementationSpecific
hosts:
- myhost.example.com
tls:
- hosts:
- myhost.example.com
secretName: myhost-example-com-tls # Name of the secret that holds the certificates for the domain
```
<file_sep>1. Get the application URL by running these commands:
{{- if .Values.dashboard.ingress.enabled }}
{{- range $host := .Values.dashboard.ingress.hosts }}
{{- range .paths }}
http{{ if $.Values.dashboard.ingress.tls }}s{{ end }}://{{ $host.host }}{{ .path }}
{{- end }}
{{- end }}
{{- end }}<file_sep>#### install
```
helm install tianrang/redis-ui --version lastet --name-template redis-ui \
--set image.name="",image.tag=""
```
|
08b95c594d4a427f4b135c4d1199a934f3df7fcc
|
[
"Markdown",
"Text",
"Shell"
] | 6 |
Markdown
|
fallenangelblog/charts
|
9801bc3f100a264979ccfb2611c6f2ff55259b0e
|
697c4776ee796e5f54dc4efb5b34393b98f7b820
|
refs/heads/master
|
<file_sep>from sense_hat import SenseHat
from time import sleep
from random import randint
#init
sense = SenseHat()
sense.set_imu_config(False, False, False)
# Generate a random colour
def pick_random_colour():
random_red = randint(0, 255)
random_green = randint(0, 255)
random_blue = randint(0, 255)
return (random_red, random_green, random_blue)
def main():
while True:
print(pick_random_colour())
sense.show_letter("N", text_colour=pick_random_colour())
sleep(1)
sense.show_letter("M", text_colour=pick_random_colour())
sleep(1)
sense.show_letter("D", text_colour=pick_random_colour())
print('test')
sleep(1)
try:
main()
except (KeyboardInterrupt, SystemExit):
print('Programma sluiten')
sense.clear()<file_sep>from sense_hat import SenseHat
#import turtle
from time import sleep
from random import randint
screen = turtle.Screen()
#init
sense = SenseHat()
sense.set_imu_config(False, False, False)
# Or, set the shape of a turtle
screen.addshape("rocketship.gif")
tina = turtle.Turtle()
tina.shape("filename.png")
#sense.display_image('mario')
<file_sep>from sense_hat import SenseHat
from time import sleep
from random import randint
#Init
sense = SenseHat()
sense.set_imu_config(False, False, False)
# Generate a random colour
def pick_random_colour():
random_red = randint(0, 255)
random_green = randint(0, 255)
random_blue = randint(0, 255)
return (random_red, random_green, random_blue)
# Display Msg
def main():
while True:
sense.show_message("Hello!", text_colour=pick_random_colour(), back_colour=pick_random_colour())
try:
main()
except (KeyboardInterrupt, SystemExit):
print('Programma sluiten')
sense.clear()
|
ee8e707ba58c3475cc9ca6eae4d1c23414f47e3c
|
[
"Python"
] | 3 |
Python
|
gdmgent-IoT-1920/labo-2-sensehat-arilybaert
|
b86311252beb13d625b577707c006373d3690abf
|
9180606ac6c4a99a5f8f52dc10c450be0703d1c6
|
refs/heads/master
|
<repo_name>bao1018/SopranoUtil<file_sep>/src_test/com/pwc/soprano/util/WordErrorRateTest.java
package com.pwc.soprano.util;
import com.pwc.soprano.util.WordSequenceAligner.Alignment;
public class WordErrorRateTest {
public static void main(String[] args) {
String str1 = "the quick brown cow jumped over the moon";
String str2 = "quick brown cows jumped way over the moon dude";
try {
System.out.println("WER: "+WordErrRate.compare(str1, str2));
System.out.println("---------------------------");
WordSequenceAligner wsa = new WordSequenceAligner();
Alignment alignment = wsa.align(str1.split(" "), str2.split(" "));
System.out.println("WordSequenceAligner: "+ alignment.getWER());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
efdd20d44ece3b274df3b339632bc409ea0e551b
|
[
"Java"
] | 1 |
Java
|
bao1018/SopranoUtil
|
b078c18a77e60b2833746f9880a8572d5d883c76
|
9d6672b63875404192effa9fecfa1ae27a3706fa
|
refs/heads/master
|
<file_sep>'use strict';
// Declare app level module which depends on views, and components
var app = angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version',
'UserApp'
]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
$routeProvider.when('/login', {templateUrl: 'login/login.html', login: true});
$routeProvider.when('/signup', {templateUrl: 'signup/signup.html', public: true});
}]);
app.run(function(user){
user.init({ appId: '54d6e87bd2b52'});
});
<file_sep># Demo of UserApp
This project is an application to demo the UserApp tool/API for CSE 112
|
306cef57fee1648a70dec53df9f3e58152d62ed9
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
jwlai/loginAngular
|
486eb976f1ee69392eddd902852143e451b48b86
|
14c4275f0f5bec635e68644ac5a33d92d83a0e78
|
refs/heads/master
|
<repo_name>honzajavorek/map<file_sep>/sample/__init__.py
import os
import json
import gspread
import geocoder
from slugify import slugify
from flask import Flask, render_template, jsonify
from oauth2client.service_account import ServiceAccountCredentials
app = Flask('sample')
app.config['JSON_AS_ASCII'] = False
app.config['SHEET_URL'] = os.environ.get('SHEET_URL')
app.config['SHEETS_API_KEY'] = json.loads(os.environ.get('SHEETS_API_KEY'))
app.config['GEOCODING_API_KEY'] = os.environ.get('GEOCODING_API_KEY')
data = {
'type': 'FeatureCollection',
'features': [],
}
@app.before_first_request
def before_first_request():
for row in get_sheet(app.config['SHEETS_API_KEY'], app.config['SHEET_URL']):
location = row['Location'] + ', Czech Republic'
g = geocoder.google(location, key=app.config['GEOCODING_API_KEY'])
coords = g.latlng
properties = dict((slugify(item[0]), item[1]) for item in row.items())
data['features'].append({
'type': 'Feature',
'properties': properties,
'geometry': {
'type': 'Point',
'coordinates': [coords[1], coords[0]]
}
})
@app.route('/')
def index():
return render_template('index.html')
# See https://github.com/pyvec/elsa/issues/58 to see why this route is crippled
@app.route('/api.json')
def api():
response = jsonify(data)
# response.mimetype = 'application/geo+json'
return response
def get_sheet(api_key, sheet_url):
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_dict(api_key, scope)
sheets = gspread.authorize(credentials)
worksheet = sheets.open_by_url(sheet_url).get_worksheet(0)
cells = worksheet.get_all_values()
header = cells[0]
rows = cells[1:]
return (dict(zip(header, row)) for row in rows)
<file_sep>/README.md
# Map
A prototype of a static website hosted on [GitHub Pages](https://pages.github.com), which contains an [OpenStreetMap](https://www.openstreetmap.org/) map rendered by [Leaflet](http://leafletjs.com/) from a [GeoJSON](http://geojson.org/) file [cron-generated](https://docs.travis-ci.com/user/cron-jobs/) by [Travis CI](http://travis-ci.org/) from data in [Google Sheets](https://docs.google.com/spreadsheets/).
## Installation and Usage
1. Have a Google Spreadsheet like [this](https://docs.google.com/spreadsheets/d/1wvEgQtTtXVbkcq2sCis3T6P3AHMJXOzylkshH8sC2s0/edit?usp=sharing):
| Name | Location | Web |
|---------------|----------------------|---------------------------|
| FÆNCY FRIES | Přívozská 9, Ostrava | https://faencyfries.cz/ |
| Garage | Křižíkova 58, Praha | http://poutine.cz/ |
Set its URL as an environment variable:
```shell
export SHEET_URL='https://docs.google.com/spreadsheets/d/1wvEgQtTtXVbkcq2sCis3T6P3AHMJXOzylkshH8sC2s0/edit?ouid=107119873943551212790&usp=sheets_home&ths=true'
```
1. Head to [Google Developers Console](https://console.developers.google.com/project) and create a new project.
1. In the navigation menu (top left corner) go to <kbd>APIs & Services</kbd> and <kbd>Library</kbd>.
1. Find **Google Sheets API**, enable it.
1. Find **Geocoding API**, enable it.
1. In the navigation menu (top left corner) go to <kbd>APIs & Services</kbd> and <kbd>Credentials</kbd>.
1. Click <kbd>New Credentials</kbd> and choose <kbd>API key</kbd>.
1. Edit the key. Name it (e.g. _Geocoding_)
1. Restrict the key only to the Geocoding API: <kbd>Key restrictions</kbd> » <kbd>API restrictions</kbd>
1. Set the key as an environment variable:
```shell
export GEOCODING_API_KEY=aBcdE...
```
1. Click <kbd>New Credentials</kbd> and choose <kbd>Service account key</kbd>.
1. Service account: <kbd>New service account<kbd>
1. Service account name: e.g. _Sheets Reader_
1. Role: <kbd>Project</kbd> » <kbd>Viewer</kbd>
1. Download it as JSON.
1. Set the contents of the JSON file as an environment variable:
```shell
export SHEETS_API_KEY=$(cat map-sample-12345678900a.json)
```
1. Go to your Google Spreadsheet and invite the email from the JSON file's `client_email` field to be able to view the document.
1. Have **Python 3.7** and [pipenv](https://pipenv.readthedocs.io/). Clone the project and install dependencies:
```shell
$ pipenv install --dev
```
Now you can use following to develop the website locally and to preview it in your browser:
```shell
$ pipenv run serve
```
1. Go to [your GitHub settings](https://github.com/settings/tokens) and generate a new token with the `public_repo` scope. Save the token, you'll need it in the next step.
1. See the `.travis.yml` file. Go to [Travis CI](http://travis-ci.org/), sign in with GitHub and add a new project with this repository. Go to settings page for the repository (for admins of `honzajavorek/map` it's [here](https://travis-ci.org/honzajavorek/map/settings).
1. In the <kbd>Environment Variables</kbd> section add all the environment variables from above: `SHEET_URL`, `SHEETS_API_KEY`, `GEOCODING_API_KEY`. Be sure to set the `SHEETS_API_KEY` quoted with apostrophes `'{ ... }'`.
1. Add the GitHub token from previous step as a `GITHUB_TOKEN` environment variable.
1. [Set a cron job](https://docs.travis-ci.com/user/cron-jobs/) to build the website daily.
1. Once the build is passing on the `master` branch, go to the project GitHub Pages, e.g. https://honzajavorek.github.io/map/, and see the result.
<file_sep>/sample/__main__.py
from elsa import cli
from sample import app
cli(app, base_url='https://honzajavorek.github.io/map')
<file_sep>/Pipfile
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[dev-packages]
pylama = "*"
[packages]
gspread = "*"
elsa = "*"
pyopenssl = "*"
"oauth2client" = "*"
geocoder = "*"
python-slugify = "*"
[requires]
python_version = "3.7"
[scripts]
freeze = "pipenv run python sample freeze"
serve = "pipenv run python sample serve"
deploy = "pipenv run python sample deploy --push"
|
d16c07bc3a47a14bcc300e269dde911910401048
|
[
"Markdown",
"TOML",
"Python"
] | 4 |
Python
|
honzajavorek/map
|
2952a17c44c3dcd0be831d066e94547da8409850
|
d0d54729211f7a048b9c906df6bdeafe3e6e7117
|
refs/heads/master
|
<repo_name>xuelingxiao/java-knowledge-structure<file_sep>/design-patterns/src/main/java/com/xlx/pattern/proxy/cglib/HongQiCar.java
package com.xlx.pattern.proxy.cglib;
public class HongQiCar {
public void sale() {
System.out.println("卖了一辆红旗");
}
}
<file_sep>/rest/src/main/java/com/xlx/rest/webflux/WebfluxConfiguration.java
package com.xlx.rest.webflux;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.*;
@Configuration
public class WebfluxConfiguration {
@Bean
public RouterFunction<ServerResponse> saveUser(UserHandler userHandler){
return RouterFunctions.route(RequestPredicates. POST("/flux/user/save"),userHandler::save);
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xlx</groupId>
<artifactId>java-knowledge-structure</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>design-patterns</module>
<module>engineering</module>
<module>corejava</module>
<module>threads</module>
<module>distribute-all</module>
<module>mvc-stuff</module>
</modules>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!--静态代码bug扫描-->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<threshold>High</threshold>
<effort>Default</effort>
<findbugsXmlOutput>true</findbugsXmlOutput>
<findbugsXmlOutputDirectory>target/site</findbugsXmlOutputDirectory>
</configuration>
</plugin>
<!--版本号管理-->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.3</version>
</plugin>
<!--打包源代码-->
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>install</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<!--这个有点晕,生成可执行jar包什么的-->
<!--<plugin>-->
<!--<artifactId>maven-assembly-plugin</artifactId>-->
<!--<version>3.0.0</version>-->
<!--<configuration>-->
<!--<archieve>-->
<!--<manifest>-->
<!--<mainClass>com.xlx.Test</mainClass>-->
<!--</manifest>-->
<!--</archieve>-->
<!--<descriptorRefs>-->
<!--<descriptorRef>jar-with-dependencies</descriptorRef>-->
<!--</descriptorRefs>-->
<!--</configuration>-->
<!--</plugin>-->
<!--tomcat插件-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/mvc-stuff/src/main/java/com/xlx/mvc/web/controller/HomeController.java
package com.xlx.mvc.web.controller;
import org.springframework.http.HttpStatus;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
@ManagedResource(objectName = "mvc:name=HomeController")
public class HomeController {
@GetMapping("/npe1")
@ResponseBody
public String npe1() throws NullPointerException {
throw new NullPointerException();
}
@GetMapping("/npe2")
@ResponseBody
@ManagedOperation
public String npe2() throws NullPointerException {
throw new NullPointerException();
}
@ExceptionHandler(value = {NullPointerException.class})
@ResponseBody
public String npehandler(){
return "test npe handler";
}
@GetMapping("/")
@ResponseBody
@ManagedOperation
public String hello() throws BindException {
throw new BindException(new Object(),"test");
}
@GetMapping("/responseStatus")
@ResponseBody
public String responseStatus() throws MyException {
throw new MyException();
}
@ResponseStatus(code = HttpStatus.BAD_GATEWAY)
public class MyException extends Exception{}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/prototype/CarProperty.java
package com.xlx.pattern.prototype;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
@Data
@AllArgsConstructor
public class CarProperty implements Cloneable, Serializable {
public final String test ="test";
private String power;
private double maxSpeed;
private double oilPerKm;
public Object clone(){
Object obj = null;
try {
obj = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return obj;
}
}
<file_sep>/distribute-all/src/main/java/com/xlx/ws/BMWCar.java
package com.xlx.ws;
import javax.jws.WebService;
@WebService
public class BMWCar implements ICar {
@Override
public String getCarName() {
return "宝马汽车...";
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/factorymethod/Client.java
package com.xlx.pattern.factorymethod;
/**
* 调用方角色
*/
public class Client {
/**
* 调用演示
*/
public void drive(){
CarFactory bmwFactory = new BMWFactory();
Car bmwCar = bmwFactory.getCar();
bmwCar.run();
CarFactory qqFactory = new QQFactory();
Car qqCar = qqFactory.getCar();
qqCar.run();
Car car = getCarByType(1);
if (car!=null){
car.run();
}
car = getCarByType(2);
if (car!=null){
car.run();
}
}
/**
* 简单工厂实现, 通过传入的参数返回具体的汽车
* @param carType
* @return
*/
public Car getCarByType(int carType){
Car car = null;
switch (carType){
case 1:
CarFactory bmwFactory = new BMWFactory();
Car bmwCar = bmwFactory.getCar();
car = bmwCar;
break;
case 2:
CarFactory qqFactory = new QQFactory();
Car qqCar = qqFactory.getCar();
car = qqCar;
break;
}
return car;
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/abstractfactory/MacRAMFactory.java
package com.xlx.pattern.abstractfactory;
public class MacRAMFactory implements RAMFactory {
public RAM createRAM() {
return new MacRAM();
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/abstractfactory/WindowsRAMFactory.java
package com.xlx.pattern.abstractfactory;
public class WindowsRAMFactory implements RAMFactory {
public RAM createRAM() {
return new WindowsRAM();
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/observer/UncleObserver.java
package com.xlx.pattern.observer;
public class UncleObserver implements MyObserver {
public void update(Subject subject) {
ConcreteSubject concreteSubject = (ConcreteSubject)subject;
System.out.println("UncleObserver 知道了: "+concreteSubject.getName());
}
}
<file_sep>/distribute-all/src/main/java/com/xlx/rmi/TestServer.java
package com.xlx.rmi;
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
public class TestServer {
public static void main(String[] args) throws RemoteException, AlreadyBoundException, MalformedURLException {
IRmiTest rmiTest = new RmiTest();
LocateRegistry.createRegistry(8888);
Naming.bind("rmi://localhost:8888/hello",rmiTest);
System.out.println("server started");
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/delegate/TaskTest.java
package com.xlx.pattern.delegate;
public class TaskTest {
public static void main(String[] args) {
new TaskDelegate().doTask();
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/singleton/DoubleCheckSingleton4.java
package com.xlx.pattern.singleton;
/**
* 双重校验
* 特点: 线程安全,延迟加载,基本不会发生阻塞
*/
public class DoubleCheckSingleton4 {
private volatile DoubleCheckSingleton4 onlyOneInstance;
private DoubleCheckSingleton4(){}
public DoubleCheckSingleton4 getOnlyOneInstance(){
if (onlyOneInstance==null){
synchronized (DoubleCheckSingleton4.class){
if (onlyOneInstance==null){
onlyOneInstance = new DoubleCheckSingleton4();
}
}
}
return onlyOneInstance;
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/factorymethod/BMWFactory.java
package com.xlx.pattern.factorymethod;
/**
* BMW 汽车工厂实现
*/
public class BMWFactory implements CarFactory {
public Car getCar() {
return new BMWCar();
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/builder/QQCarBuilder.java
package com.xlx.pattern.builder;
public class QQCarBuilder extends AbstractCarBuilder {
public AbstractCarBuilder setEngine() {
Car car = this.getCar();
car.setEngine("QQ setEngine");
return this;
}
public AbstractCarBuilder setChassis() {
Car car = this.getCar();
car.setChassis("QQ setChassis");
return this;
}
public AbstractCarBuilder setBody() {
Car car = this.getCar();
car.setBody("QQ setBody");
return this;
}
public AbstractCarBuilder setWheels() {
Car car = this.getCar();
car.setWheels("QQ setWheels");
return this;
}
public AbstractCarBuilder setEquipment() {
return this;
}
public AbstractCarBuilder setRadar() {
return this;
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/abstractfactory/MacFactory.java
package com.xlx.pattern.abstractfactory;
/**
* Mac的工厂实现
*/
public class MacFactory implements PCAbstractFactory{
public CPU createCPU() {
return new MacCPUFactory().createCPU();
}
public RAM createRAM() {
return new MacRAMFactory().createRAM();
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/abstractfactory/RAM.java
package com.xlx.pattern.abstractfactory;
public interface RAM {
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/prototype/Car.java
package com.xlx.pattern.prototype;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Car implements Cloneable {
private String brand;
private double price;
private CarProperty carProperty;
/**
* 深拷贝在此实现,对于复杂的应用类型, 这里的代码可能会相当复杂,如果类有修改(新增成员变量等),这里也需要相应修改
* @return
*/
public Object clone(){
Object car = null;
try {
car = super.clone();
CarProperty carPropertyClone = (CarProperty)this.getCarProperty().clone();
((Car)car).setCarProperty(carPropertyClone);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return car;
}
public static void main(String[] args) {
CarProperty carProperty = new CarProperty("8匹",250,30);
Car car= new Car("BMW",200,carProperty);
Car copy = (Car) car.clone();
System.out.println("copy最大速度为: "+copy.getCarProperty().getMaxSpeed());
System.out.println("原型最大速度为: "+car.getCarProperty().getMaxSpeed());
car.getCarProperty().setMaxSpeed(360);
System.out.println("copy最大速度为: "+copy.getCarProperty().getMaxSpeed());
System.out.println("原型最大速度为: "+car.getCarProperty().getMaxSpeed());
}
}
<file_sep>/distribute-all/src/main/java/com/xlx/zk/curator/CuratorSession.java
package com.xlx.zk.curator;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.transaction.CuratorOp;
import org.apache.curator.framework.api.transaction.CuratorTransactionResult;
import org.apache.curator.framework.api.transaction.TypeAndPath;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Op;
import org.apache.zookeeper.data.Stat;
import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CuratorSession {
private static final String CONN = "localhost:2181";
public static void main(String[] args) throws Exception {
// 创建
CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(CONN, 2000, 5000, new ExponentialBackoffRetry(1000,3));
curatorFramework.start();
System.out.println(curatorFramework.getState());
//另一种方式
//curatorFramework = CuratorFrameworkFactory.builder().build();
// 新增节点
curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/curator/chd/dd","dfadfe".getBytes());
//读取
byte[] data = curatorFramework.getData().forPath("/curator/chd/dd");
java.lang.String string = new java.lang.String(data);
System.out.println(string);
// 修改
Stat stat = curatorFramework.setData().forPath("/curator/chd/dd","fdaefv".getBytes());
System.out.println(stat);
curatorFramework.setData().inBackground(new BackgroundCallback() {
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
System.out.println(event);
}
}).forPath("/curator/chd/dd","fafdae".getBytes());
//删除
curatorFramework.delete().guaranteed().deletingChildrenIfNeeded().forPath("/curator/chd");
//异步
ExecutorService executorService = Executors.newSingleThreadExecutor();
curatorFramework.setData().inBackground(new BackgroundCallback() {
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
System.out.println(event.getData());
}
},executorService).forPath("/curator/chd/dd","fafdae".getBytes());
//事务
// this example shows how to use ZooKeeper's transactions
CuratorOp createOp = curatorFramework.transactionOp().create().forPath("/a/path", "some data".getBytes());
CuratorOp setDataOp = curatorFramework.transactionOp().setData().forPath("/another/path", "other data".getBytes());
CuratorOp deleteOp = curatorFramework.transactionOp().delete().forPath("/yet/another/path");
Collection<CuratorTransactionResult> results = curatorFramework.transaction().forOperations(createOp, setDataOp, deleteOp);
for ( CuratorTransactionResult result : results )
{
System.out.println(result.getForPath() + " - " + result.getType());
}
//
Thread.sleep(2000);
}
}
<file_sep>/distribute-all/src/main/java/com/xlx/zk/javaapi/MyWatcher.java
package com.xlx.zk.javaapi;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
/**
* 定义Watcher
*/
public class MyWatcher implements Watcher {
@Override
public void process(WatchedEvent event) {
if(event.getState()== Event.KeeperState.SyncConnected){
System.out.println("---->>>>>"+event.getType());
System.out.println("---->>>>>"+event.getPath());
}
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/abstractfactory/MacRAM.java
package com.xlx.pattern.abstractfactory;
public class MacRAM implements RAM {
}
<file_sep>/mvc-stuff/src/main/java/com/xlx/mvc/service/MyThing.java
package com.xlx.mvc.service;
public class MyThing {
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
private int count;
@Override
public String toString() {
return "class MyThing[count="+this.getCount()+"]";
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/proxy/jdk/Agent.java
package com.xlx.pattern.proxy.jdk;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 经纪公司,或者经销商
*/
public class Agent implements InvocationHandler {
private Car car ;
/**
* 返回代理对象,接收被代理对象
* @param car
* @return
* @throws Exception
*/
public Object getInstance(Car car) throws Exception {
this.car=car;
Class clazz = car.getClass();
System.out.println("代理前对象的类型"+car.getClass().getName());
Object obj = Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
System.out.println("代理后对象类型变为"+obj.getClass().getName());
return obj;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Agent find some costumers");
//this.car.sale();
method.invoke(this.car, args);
System.out.println("Agent saled the car");
return null;
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/strategy/WinStrategy.java
package com.xlx.pattern.strategy;
/**
* 赢得吃鸡的策略接口
*/
public interface WinStrategy {
void win();
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/strategy/AlwaysHideWinStrategy.java
package com.xlx.pattern.strategy;
/**
* 采用LYB的模式
*/
public class AlwaysHideWinStrategy implements WinStrategy {
public void win() {
System.out.println("总是很苟,活得长久; 天气: ");
}
}
<file_sep>/distribute-all/src/main/java/com/xlx/socket/MultcastClient.java
package com.xlx.socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
public class MultcastClient {
public static void main(String[] args) throws IOException, InterruptedException {
// 多播必须是224网段
InetAddress group = InetAddress.getByName("172.16.17.32");
MulticastSocket socket = new MulticastSocket(8888);
socket.joinGroup(group);
byte[] buf = new byte[32];
while (true){
DatagramPacket packet = new DatagramPacket(buf,buf.length);
socket.receive(packet);
String reveived = new String(packet.getData());
System.out.println("received:"+reveived);
}
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/abstractfactory/WindowsFactory.java
package com.xlx.pattern.abstractfactory;
/**
* Windows的工厂实现
*/
public class WindowsFactory implements PCAbstractFactory{
public CPU createCPU() {
return new WindowsCPUFactory().createCPU();
}
public RAM createRAM() {
return new WindowsRAMFactory().createRAM();
}
}
<file_sep>/distribute-all/src/main/java/com/xlx/zk/javaapi/DistributeLock.java
package com.xlx.zk.javaapi;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class DistributeLock {
private static final String ROOT_LOCKS="/LOCK";
private ZooKeeper zooKeeper;
private int sessionTimeout;
private String lockID;
private final static byte[] date={1,2};
private CountDownLatch countDownLatch = new CountDownLatch(1);
public DistributeLock() throws IOException, InterruptedException {
this.zooKeeper = ZookeeperClient.getZookeeperClient();
this.sessionTimeout = ZookeeperClient.SESSIONTIMEOUT;
}
public boolean lock(){
try{
lockID = zooKeeper.create(ROOT_LOCKS+"/",date, ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(Thread.currentThread().getName()+"->成功创建了lock节点["+lockID+"], 开始去竞争锁");
List<String> childrenNodes = zooKeeper.getChildren(ROOT_LOCKS,true);
SortedSet<String> sortedSet = new TreeSet<>();
for(String children:childrenNodes){
sortedSet.add(ROOT_LOCKS+"/"+children);
}
String first = sortedSet.first();
if (first.equals(lockID)){
System.out.println(Thread.currentThread().getName()+"->成功获得锁,lock节点为:["+lockID+"]");
return true;
}
SortedSet<String> lessThanLockId = ((TreeSet<String>) sortedSet).headSet(lockID);
if (!lessThanLockId.isEmpty()){
String prevLockID = lessThanLockId.last();
zooKeeper.exists(prevLockID,new LockWatcher(countDownLatch));
countDownLatch.await(sessionTimeout,TimeUnit.MILLISECONDS);
System.out.println(Thread.currentThread().getName()+" 成功获取锁:["+lockID+"]");
}
}catch (Exception e){e.printStackTrace();}
return false;
}
public boolean unlock(){
System.out.println(Thread.currentThread().getName()+"->开始释放锁:["+lockID+"]");
try {
zooKeeper.delete(lockID,-1);
System.out.println("节点["+lockID+"]成功被删除");
return true;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
final CountDownLatch latch=new CountDownLatch(10);
Random random=new Random();
for(int i=0;i<10;i++){
new Thread(()->{
DistributeLock lock=null;
try {
lock=new DistributeLock();
latch.countDown();
latch.await();
lock.lock();
Thread.sleep(random.nextInt(500));
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
if(lock!=null){
lock.unlock();
}
}
}).start();
}
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/abstractfactory/CPU.java
package com.xlx.pattern.abstractfactory;
public interface CPU {
}
<file_sep>/rest/src/main/java/com/xlx/rest/webflux/UserHandler.java
package com.xlx.rest.webflux;
import com.xlx.rest.entity.User;
import com.xlx.rest.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Component
public class UserHandler {
private final UserRepository userRepository;
@Autowired
public UserHandler(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Mono<ServerResponse> save(ServerRequest request){
Mono<User> userMono = request.bodyToMono(User.class);
Mono<Boolean> booleanMono = userMono.map(userRepository::save);
return ServerResponse.ok().body(booleanMono,Boolean.class);
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/abstractfactory/PCAbstractFactory.java
package com.xlx.pattern.abstractfactory;
/**
* 抽象工厂接口
*/
public interface PCAbstractFactory {
CPU createCPU();
RAM createRAM();
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/factorymethod/QQCar.java
package com.xlx.pattern.factorymethod;
/**
* QQ 汽车实现类
*/
public class QQCar implements Car {
public void run() {
System.out.println("QQ run...");
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/proxy/my/MyProxy.java
package com.xlx.pattern.proxy.my;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* 生成代理对象的代码, Proxy的具体原理在这里体现
*/
public class MyProxy {
private static final String ln = "\r\n";
public static Object newProxyInstance(MyClassLoader loader, Class<?>[] interfaces, MyInvocationHandler h) {
File f = null;
try {
// 第一步: 生成源代码
String src = generateSrc(interfaces[0]);
// 第二步: 保存生成的源码文件
String filePath = MyProxy.class.getResource("").getPath();
f = new File(filePath + "/$Proxy0.java");
FileWriter writer = new FileWriter(f);
writer.write(src);
writer.flush();
writer.close();
// 第三步: 编译生成.class文件
JavaCompiler compliler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager manager = compliler.getStandardFileManager(null, null, null);
Iterable iterable = manager.getJavaFileObjects(f);
JavaCompiler.CompilationTask task = compliler.getTask(null, manager, null, null, null, iterable);
((JavaCompiler.CompilationTask) task).call();
manager.close();
// 第四步: 加载class字节码到内存(MyClassLoader类实现)
Class proxyClass = loader.findClass("$Proxy0");
// 第五步: 返回代理对象
Constructor constructor = proxyClass.getConstructor(MyInvocationHandler.class);
return constructor.newInstance(h);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != f) {
f.delete();
}
}
return null;
}
/**
* 生成源码的方法
*
* @param interfaces 为了演示,按一个接口处理
* @return
*/
private static String generateSrc(Class<?> interfaces) {
StringBuffer src = new StringBuffer();
src.append("package com.xlx.pattern.proxy.my;" + ln);
src.append("import java.lang.reflect.Method;" + ln);
src.append("public class $Proxy0 extends MyProxy implements " + interfaces.getName() + "{" + ln);
src.append("MyInvocationHandler h;" + ln);
src.append("public $Proxy0(MyInvocationHandler h){" + ln);
src.append("this.h=h;" + ln);
src.append("}" + ln);
// 循环定义方法,与被代理类的方法同名
for (Method m : interfaces.getMethods()) {
src.append("public " + m.getReturnType().getName() + " " + m.getName() + "(){" + ln);
src.append("try{" + ln);
src.append("Method m =" + interfaces.getName() + ".class.getMethod(\"" + m.getName() + "\",new Class[]{});" + ln);
src.append("this.h.invoke(this,m,null);" + ln);
src.append("}catch(Throwable e){e.printStackTrace();}" + ln);
src.append("}" + ln);
}
src.append("}" + ln);
return src.toString();
}
}
<file_sep>/README.md
"# java-knowledge-structure"
<file_sep>/threads/src/main/java/com/xlx/threads/threads01/DirtyRead.java
package com.xlx.threads.threads01;
public class DirtyRead {
private String username="xlx";
private String password="<PASSWORD>";
public synchronized void setValue(String username,String password){
this.username=username;
try {
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}
this.password=<PASSWORD>;
System.out.println("setValue的最终结果: username="+this.username+",password="+this.password);
}
// synchronized
public synchronized void getValue(){
System.out.println("getValue方法得到:username="+this.username+",password="+this.password);
}
public static void main(String[] args) throws Exception {
final DirtyRead dr = new DirtyRead();
Thread t1 = new Thread(new Runnable() {
public void run() {
dr.setValue("yxj","789");
}
});
t1.start();
Thread.sleep(1000);
dr.getValue();
}
}
<file_sep>/engineering/src/main/java/com/xlx/mvn/plugin/Test.java
package com.xlx.mvn.plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import java.util.List;
@Mojo(name="xlxTest",defaultPhase = LifecyclePhase.PACKAGE)
public class Test extends AbstractMojo {
/**
* 接收的参数
*/
@Parameter
private String message;
/**
* 接收多个值的参数
*/
@Parameter
private List<String> options;
/**
* 命令行中接收,注意必须有property mvn:package -Dargs=this is from cmd
*/
@Parameter(property = "args")
private String args;
public void execute() throws MojoExecutionException, MojoFailureException {
System.out.println("my first maven plugin message is : " + message);
System.out.println("my first maven plugin options is : " + options);
System.out.println("my first maven plugin args from evm is : " + args);
}
}
<file_sep>/distribute-all/src/main/java/com/xlx/ws/client/BMWCarService.java
package com.xlx.ws.client;
import com.xlx.ws.BMWCar;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.9-b130926.1035
* Generated source version: 2.2
*
*/
@WebServiceClient(name = "BMWCarService", targetNamespace = "http://ws.xlx.com/", wsdlLocation = "http://localhost:8090/car?wsdl")
public class BMWCarService
extends Service
{
private final static URL BMWCARSERVICE_WSDL_LOCATION;
private final static WebServiceException BMWCARSERVICE_EXCEPTION;
private final static QName BMWCARSERVICE_QNAME = new QName("http://ws.xlx.com/", "BMWCarService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://localhost:8090/car?wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
BMWCARSERVICE_WSDL_LOCATION = url;
BMWCARSERVICE_EXCEPTION = e;
}
public BMWCarService() {
super(__getWsdlLocation(), BMWCARSERVICE_QNAME);
}
public BMWCarService(WebServiceFeature... features) {
super(__getWsdlLocation(), BMWCARSERVICE_QNAME, features);
}
public BMWCarService(URL wsdlLocation) {
super(wsdlLocation, BMWCARSERVICE_QNAME);
}
public BMWCarService(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, BMWCARSERVICE_QNAME, features);
}
public BMWCarService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public BMWCarService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns BMWCar
*/
@WebEndpoint(name = "BMWCarPort")
public com.xlx.ws.client.BMWCar getBMWCarPort() {
return super.getPort(new QName("http://ws.xlx.com/", "BMWCarPort"), com.xlx.ws.client.BMWCar.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns BMWCar
*/
@WebEndpoint(name = "BMWCarPort")
public com.xlx.ws.BMWCar getBMWCarPort(WebServiceFeature... features) {
return super.getPort(new QName("http://ws.xlx.com/", "BMWCarPort"), BMWCar.class, features);
}
private static URL __getWsdlLocation() {
if (BMWCARSERVICE_EXCEPTION!= null) {
throw BMWCARSERVICE_EXCEPTION;
}
return BMWCARSERVICE_WSDL_LOCATION;
}
}
<file_sep>/mvc-stuff/src/main/java/com/xlx/mvc/web/controller/SecondController.java
package com.xlx.mvc.web.controller;
import com.xlx.mvc.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
@Controller
@RequestMapping("/v2")
public class SecondController {
@GetMapping("/npe")
@ResponseBody
public String npe2() throws NullPointerException {
throw new NullPointerException();
}
@Autowired
WebApplicationContext context;
@Autowired
@GetMapping("/getMyService")
@ResponseBody
public String getMyService() {
return context.getBean("myService").toString();
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/factorymethod/CarFactory.java
package com.xlx.pattern.factorymethod;
/**
* 汽车工厂接口
*/
public interface CarFactory {
/**
* 生产汽车
* @return 实现Car接口的类实例
*/
Car getCar();
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/prototype/MyCar.java
package com.xlx.pattern.prototype;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
@Data
@AllArgsConstructor
public class MyCar extends DeepCloneBase implements Serializable {
private String brand;
private double price;
private CarProperty carProperty;
public static void main(String[] args) throws Exception{
CarProperty carProperty = new CarProperty("8匹",250,30);
MyCar car= new MyCar("BMW",200,carProperty);
MyCar copy = (MyCar)car.deepClone();
if (copy!=null){
System.out.println("copy最大速度为: "+copy.getCarProperty().getMaxSpeed());
System.out.println("原型最大速度为: "+car.getCarProperty().getMaxSpeed());
car.getCarProperty().setMaxSpeed(360);
System.out.println("copy最大速度为: "+copy.getCarProperty().getMaxSpeed());
System.out.println("原型最大速度为: "+car.getCarProperty().getMaxSpeed());
}else{
System.out.println("对象没拷贝成功....");
}
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/abstractfactory/RAMFactory.java
package com.xlx.pattern.abstractfactory;
public interface RAMFactory {
RAM createRAM();
}
<file_sep>/distribute-all/src/main/java/com/xlx/serialization/QQ.java
package com.xlx.serialization;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class QQ extends Car{
private String area;
@Override
public String toString(){
return "{name:"+this.getName()+";wheels:"+this.getWheels()+"desc:"+this.getDesc()+";area:"+this.getArea()+"}";
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
serializeCar();
QQ car = deSerializeCar();
System.out.println(car.toString());
}
private static void serializeCar() throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("car")));
QQ car = new QQ();
car.setArea("china");
car.setDesc("qq is great");
car.setName("qq");
car.setWheels(4);
objectOutputStream.writeObject(car);
objectOutputStream.close();
}
private static QQ deSerializeCar() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream;
objectInputStream = new ObjectInputStream(new FileInputStream(new File("car")));
QQ car = (QQ) objectInputStream.readObject();
return car;
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/templatemethod/WheatMill.java
package com.xlx.pattern.templatemethod;
/**
* 小麦磨坊
*/
public class WheatMill extends MillTemplate {
protected void prepare() {
System.out.println("准备好小麦");
}
protected void transport() {
System.out.println("船运");
}
@Override
protected boolean needRecheck(){
return false;
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/singleton/SimpleSingleton3.java
package com.xlx.pattern.singleton;
/**
* 简单实现
* 特点: 延迟加载, 线程不安全,但容易阻塞
*/
public class SimpleSingleton3 {
private static SimpleSingleton3 onlyOneInstance;
private SimpleSingleton3(){}
public static synchronized SimpleSingleton3 getOnlyOneInstance(){
if (onlyOneInstance==null){
onlyOneInstance = new SimpleSingleton3();
}
return onlyOneInstance;
}
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/builder/Car.java
package com.xlx.pattern.builder;
import lombok.Data;
/**
* Car 有很多成员变量, 当然成员可能是一些复杂类型, 这里简化只定义一些基本类型
*/
@Data
public class Car {
private String engine; //发动机
private String chassis; // 底盘
private String body; //车身
private String wheels; //轮子
private String equipment; //构件, 可选
private String radar;// 雷达, 可选
}
<file_sep>/design-patterns/src/main/java/com/xlx/pattern/abstractfactory/WindowsCPUFactory.java
package com.xlx.pattern.abstractfactory;
public class WindowsCPUFactory implements CPUFactory {
public CPU createCPU() {
return new WindowsCPU();
}
}
<file_sep>/distribute-all/src/main/java/com/xlx/zk/javaapi/ZookeeperClient.java
package com.xlx.zk.javaapi;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class ZookeeperClient {
private static final String CONN = "localhost:2181";
public static final int SESSIONTIMEOUT = 5000;
public static ZooKeeper getZookeeperClient() throws IOException, InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
ZooKeeper zooKeeper = new ZooKeeper(CONN, SESSIONTIMEOUT, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState()== Event.KeeperState.SyncConnected){
System.out.println("--连接成功...");
latch.countDown();
}
}
});
System.out.println("--等待连接....");
latch.await();
System.out.println("--返回连接实例....");
return zooKeeper;
}
}
|
426794720f48dc8a5b0833895995418e5f182356
|
[
"Markdown",
"Java",
"Maven POM"
] | 47 |
Java
|
xuelingxiao/java-knowledge-structure
|
24f582a5070f0ba0b207f440dee29537af017fd5
|
053ba4d89e0c734f20805a3675193a12e26984b0
|
refs/heads/master
|
<file_sep>import React, { useState } from 'react';
import ChartWrapper from '../components/ColumnRangeChart/ChartWrapper';
import Select from 'react-select';
function ColumnRangeChartPage() {
const [year, yearSelected] = useState('')
const options = [
{ value: 'first', label: 'First Year of Business' },
{ value: 'second', label: 'Second Year of Business' },
{ value: 'third', label: 'Third Year of Business' },
];
return (
<div className="App">
<h2>Column Range Chart Wrapper</h2>
<div className='select-wrapper'>
<span>Select a data set: </span>
<div className='select-container'>
<Select
options={options}
defaultValue={options[0]}
onChange={(options) => yearSelected(options.value) }
/>
</div>
</div>
<ChartWrapper year={year} />
</div>
);
}
export default ColumnRangeChartPage;<file_sep>import React, { useState } from 'react';
import ChartWrapper from '../components/StaticBarChart/ChartWrapper';
import Select from 'react-select';
function StaticBarChartPage() {
const [gender, genderSelected] = useState('')
const options = [
{ value: 'men', label: 'Men' },
{ value: 'women', label: 'Women' },
];
return (
<div className="App">
<h2>Updating Bar Chart Wrapper</h2>
<div className='select-wrapper'>
<span>Select a data set: </span>
<div className='select-container'>
<Select
options={options}
defaultValue={options[0]}
onChange={(options) => genderSelected(options.value) }
/>
</div>
</div>
<ChartWrapper gender={gender} />
</div>
);
}
export default StaticBarChartPage;<file_sep>import React from 'react';
function FileInputPage() {
const handleChangeFile = (file) => {
const fileData = new FileReader();
fileData.onloadend = r => {
console.log(r.target.result);
};;
fileData.readAsText(file);
}
const fileInput = () => {
return(
<div className='file-uploader'>
<input
className='file-uploader__input'
type="file"
accept=".csv"
onChange={e => handleChangeFile(e.target.files[0])}
/>
</div>
)
}
return (
<div className="App">
<h2>File Input Example</h2>
{fileInput()}
</div>
);
}
export default FileInputPage;<file_sep># ReactD3Wrapper
An experiment in creating a wrapper in React for implementing D3, using methods from <NAME>'s [Udemy Course](http://www.udemy.com/course/d3-react) as a starting point.
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
<img width="1431" alt="Screenshot 2020-01-09 at 10 18 11" src="https://user-images.githubusercontent.com/25869284/72059154-61de5f00-32c9-11ea-8bb3-539d00f4ae45.png">
A customised Column Range Chart with hover events, transition animations, multiple datasets and custom tooltip.<file_sep>import * as d3 from 'd3';
const margin = { top: 10, bottom: 90, left: 90, right: 90 }
const width = 950 - margin.left - margin.right;
const height = 750 - margin.top - margin.bottom;
const map = 'https://raw.githubusercontent.com/ahebwa49/geo_mapping/master/src/world_countries.json';
export default class D3Chart {
constructor(element, cupData) {
const vis = this;
// data = data;
console.log('data', cupData);
vis.g = d3.select(element)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`)
d3.json(map, cupData).then(dataSets => {
vis.projection = d3.geoMercator()
.scale(130)
.translate([width / 2, height / 1.4]);
const path = d3.geoPath().projection(vis.projection);
const map = vis.g.selectAll("path")
.data(dataSets.features)
map.enter()
.append("path")
.attr("d", path)
.style("fill", "rgb(9, 157, 217)")
.style("stroke", "black")
.style("stroke-width", 0.5);
console.log('GEODATA', cupData)
const tooltip = d3
.select('body')
.append('div')
.attr('class', 'tooltip')
.style('opacity', 0);
vis.nested = d3
.nest()
.key(d => d.year)
.rollup(leaves => {
vis.total = d3.sum(leaves, d => d.attendance);
vis.coords = leaves.map(d => vis.projection([+d.long, +d.lat]));
vis.center_x = d3.mean(vis.coords, d => d[0]);
vis.center_y = d3.mean(vis.coords, d => d[1]);
vis.year = leaves.map(d => d.year);
vis.home = leaves.map(d => d.home);
return {
attendance: vis.total,
home: vis.home[0],
year: vis.year[0],
x: vis.center_x,
y: vis.center_y
};
})
.entries(cupData);
vis.attendance_extent = d3.extent(vis.nested, d => d.value["attendance"]);
function handleMouseOver(d) {
tooltip
.transition()
.duration(200)
.style('opacity', 1);
tooltip
.html((`
<h3 style="text-align:center">${d.value["home"]}</h3>
<br />
<strong>First Hosting Year:</strong> ${d.value["year"]}
<br />
<strong>Total Attendance:</strong> ${d.value["attendance"]}
`))
.style('left', d3.event.pageX + 'px')
.style('top', d3.event.pageY - 28 + 'px')
}
function handleMouseOut() {
tooltip
.transition()
.duration(200)
.style('opacity', 0);
}
vis.rScale = d3
.scaleSqrt()
.domain(vis.attendance_extent)
.range([0, 8]);
vis.g
.append("g")
.attr("class", "bubble")
.selectAll("circle")
.data(vis.nested.sort(function(a, b) {
return b.value["attendance"] - a.value["attendance"];
})
)
.enter()
.append("circle")
.attr("fill", "rgb(247, 148, 42)")
.attr("cx", d => d.value["x"])
.attr("cy", d => d.value["y"])
.attr("r", d => vis.rScale(d.value["attendance"]))
.attr("stroke", "black")
.attr("stroke-width", 0.7)
.attr("opacity", 0.7)
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut);
})
}
}<file_sep>import React, { useState, useEffect } from 'react';
import ChartWrapper from '../components/ScatterGraph/ChartWrapper';
import Table from '../components/ScatterGraph/Table';
import { json } from 'd3';
function ScatterGraphPage() {
const [scatterData, dataLoader] = useState({ data: [] });
const [activeName, activeNameSelector] = useState('');
useEffect(() => {
json('https://udemy-react-d3.firebaseio.com/children.json')
.then(data => dataLoader({ data }))
.catch(error => console.log(error))
}, []);
const updateName = (activeName) => {
activeNameSelector({ activeName })
}
const updateData = (data) => {
dataLoader({ data })
}
const renderChart = () => {
if(scatterData.length === 0) {
return 'No Data Yet'
}
return (
<div className='graph-container'>
<ChartWrapper data={scatterData.data} updateName={updateName} />
<Table data={scatterData.data} updateData={updateData} activeName={activeName.activeName} />
</div>
)
};
return (
<div className="App">
<h2>Scatter Graph Wrapper</h2>
{renderChart()}
</div>
);
}
export default ScatterGraphPage;<file_sep>import React, { Component } from 'react';
import D3Chart from './D3Chart/D3Chart';
import './ChartWrapper.scss';
class ChartWrapper extends Component {
componentDidMount(){
this.setState({
chart: new D3Chart(this.refs.chart, this.props.cupData)
})
console.log('PROPS', this.props.cupData);
}
shouldComponentUpdate() {
return false
}
render() {
return (
<div className="chart-area" ref="chart"></div>
)
}
}
export default ChartWrapper;<file_sep>import React, { useEffect, useRef } from "react";
import * as d3 from "d3";
const CircleOutDemo = props => {
const ref = useRef(null);
const cache = useRef(props.data);
const createPie = d3
.pie()
.value(d => d.price)
.sort(null);
const createArc = d3
.arc()
.innerRadius(props.innerRadius)
.outerRadius(props.outerRadius)
.padAngle(.02);
const colors = d3.scaleOrdinal(d3.schemeSet1);
const format = d3.format(".2f");
useEffect(
() => {
const data = createPie(props.data);
const prevData = createPie(cache.current);
const group = d3.select(ref.current);
const groupWithData = group.selectAll("g.arc").data(data);
groupWithData.exit().remove();
const groupWithUpdate = groupWithData
.enter()
.append("g")
.attr("class", "pie-arc")
.attr("transform", `translate(310, 50)`)
// const path = groupWithUpdate
// .append("path")
.merge(groupWithData.select("path.pie-arc"))
.on("mouseover", function(d) {
let g = d3.select(this)
.style("cursor", "pointer")
.append("g")
.attr("class", "text-group")
g.append("text")
.attr("class", "name-text")
.text(`${d.data.company}`)
.attr('text-anchor', 'middle')
.attr('dy', '-1.2em');
g.append("text")
.attr("class", "value-text")
.text(`$${d.data.price}`)
.attr('text-anchor', 'middle')
.attr('dy', '.6em');
g.append("svg:circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", props.outerRadius -60)
.attr("class", "pie-centre")
.attr('fill', colors)
.append("g")
})
.on("mouseout", function(d) {
d3.select(this)
.style("cursor", "none")
.select(".text-group").remove()
})
.append('path')
.attr('d', createArc)
.attr('class', 'pie-arc')
.attr('fill', (d,i) => colors(i))
.each(function(d) { d.outerRadius = props.outerRadius - 20; })
.each(function(d, i) { this._current = i; })
const arcTween = (d, i) => {
const interpolator = d3.interpolate(prevData[i], d);
return t => createArc(interpolator(t));
};
groupWithUpdate
.attr("class", "arc")
.attr("fill", (d, i) => colors(i))
.transition()
.attrTween("d", arcTween);
},
[props.data, colors, createArc, createPie, format, props.innerRadius, props.outerRadius]
);
return (
<svg width={props.width} height={props.height}>
<g
ref={ref}
transform={`translate(${props.outerRadius} ${props.outerRadius})`}
/>
</svg>
);
};
export default CircleOutDemo;<file_sep>import React, { Component } from 'react';
import './Table.scss';
class Table extends Component {
state = {
name: '',
height: '',
age: ''
}
handleSubmit = () => {
this.props.updateData([...this.props.data, this.state])
this.setState({
name: '',
height: '',
age: ''
})
}
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value })
}
handleRemove = (event) => {
const newData = this.props.data.filter(d => {
return d.name !== event.target.name;
});
this.props.updateData(newData);
}
renderRows(){
return (
this.props.data.map(student => {
const background = (student.name === this.props.activeName) ? 'grey' : 'white'
return (
<tr key={student.name} className={`table-form__row__${background}`}>
<td className='table-form__table-data'>{student.name}</td>
<td className='table-form__table-data'>{student.height}</td>
<td className='table-form__table-data'>{student.age}</td>
<td>
<button
className='table-form__table-data__button'
name={student.name}
onClick={this.handleRemove}
type='button'
>
Remove
</button>
</td>
</tr>
)
})
)
}
render(){
return (
<div className='table-form'>
<form className='table-form__row'>
<input
className='table-form__row__input'
placeholder="Name"
name={'name'}
value={this.state.name}
onChange={this.handleChange}
/>
<input
className='table-form__row__input'
placeholder="Height"
name={'height'}
value={this.state.height}
onChange={this.handleChange}
/>
<input
className='table-form__row__input'
placeholder="Age"
name={'age'}
value={this.state.age}
onChange={this.handleChange}
/>
<button
className='table-form__row__button'
type='button'
onClick={this.handleSubmit}
>
Add
</button>
<table className='table-form__table'>
<tbody>
{this.renderRows()}
</tbody>
</table>
</form>
</div>
)
}
}
export default Table;
|
73d8bdc5f18bfaf6767ad2e2c341b5a32febe26d
|
[
"JavaScript",
"Markdown"
] | 9 |
JavaScript
|
sleeplesseditor/ReactD3Wrapper
|
420b71e10bf144a7cefcd7c3dcaebc73b9dd4a51
|
21ae0211d6e0a8406895264b2baeddef1d271f3a
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FireController : InteractableObject {
public GameObject Light;
public float Fuel = 100;
public float burnRate = 2f;
public float MaxRange;
private float fireScale;
// Use this for initialization
void Start () {
// StartCoroutine("oneSecPrint");
}
IEnumerator oneSecPrint () {
while (true) {
yield return new WaitForSeconds (1f);
OutputFuel ();
}
}
// Update is called once per frame
void Update () {
burnFuel ();
}
public override void Interact () {
if (GameManager.Instance.numSticks > 0)
putFuelInFire ();
else
takeFuelFromFire ();
}
void burnFuel () {
if (Fuel > 0) {
Fuel -= burnRate * Time.deltaTime;
fireScale = Mathf.Clamp (Fuel, 0, MaxRange);
Light.transform.localScale = new Vector3 (fireScale / 2, fireScale / 2, fireScale / 2);
}
}
/// <summary>
/// Take fuel out of the campfire
/// </summary>
private void takeFuelFromFire () {
Debug.Log ("Just took 10 fuel");
int amount = 10;
if (Fuel > amount) {
Fuel -= amount;
GameManager.Instance.torch.torchFuel += amount;
} else {
Debug.Log ("Not Enough Fuel!!");
}
}
/// <summary>
/// Put all currently held fuel into the campfire
/// </summary>
private void putFuelInFire () {
Debug.Log ("Added " + (GameManager.Instance.numSticks) + " to Fire");
Fuel += GameManager.Instance.numSticks;
GameManager.Instance.numSticks = 0;
}
//for testing purposes only
void OutputFuel () {
Debug.Log ("CAMPFIRE :: Remaining Fuel: " + Fuel);
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
//global variables
public int numSticks = 0;
public int numKeys = 0;
// public references
public Torch torch;
public FireController campfire;
public PlayerController player;
// implementing singleton pattern
private static GameManager _instance;
public static GameManager Instance { get { return _instance; } }
private void Awake () {
if (_instance != null && _instance != this) {
Destroy (this.gameObject);
} else {
_instance = this;
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpotlightController : InteractableObject {
public float rotationAmount = 45;
public override void Interact () {
Vector3 newRot = transform.rotation.eulerAngles;
newRot.y += rotationAmount;
transform.rotation = Quaternion.Euler(newRot);
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Stick : MonoBehaviour {
public GameObject Player;
public int stickValue = 20;
private void OnCollisionEnter (Collision collision) {
if (collision.gameObject.name == "Player") {
Debug.Log ("You picked up a stick!");
GameManager.Instance.numSticks += stickValue;
Destroy (gameObject);
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Door : InteractableObject {
public override void Interact () {
if (GameManager.Instance.numKeys > 0) {
Debug.Log ("Opening door");
GameManager.Instance.numKeys--;
Destroy (gameObject);
} else {
Debug.Log ("No key!");
}
}
}<file_sep># Campfire
Unity version 2019.2.0f1
https://sundy.itch.io/campfire
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour {
//movement variables
public float movementSpeed = 20f;
public float rotationSpeed = 20f;
private float tempRotationSpeed;
private float horizAxis = 0f;
private float vertAxis = 0f;
// GameObject references
public GameObject Torch;
private Torch torchComponent;
public GameObject CampFire;
private FireController campfireComponent;
// editor variables
public bool canDropTorch = true;
// animation and audio
private Animator anim;
private AudioSource audio;
// component references
private Rigidbody rb;
public GameObject pickupPos;
// collision checking
private GameObject touchingSconce = null;
private GameObject currentPickup = null; // whether we currently have something in our hand
private GameObject pickupObj = null; // potential nearby object to be picked up
private InteractableObject touchingInteractable = null; // if touching an interactable object
public InputActionAsset inputBindings;
private InputAction move;
private InputAction interact;
public bool gamePad = false;
private void Awake () {
rb = GetComponent<Rigidbody> ();
campfireComponent = CampFire.GetComponent<FireController> ();
torchComponent = Torch.GetComponent<Torch> ();
anim = GetComponent<Animator> ();
audio = GetComponent<AudioSource> ();
tempRotationSpeed = rotationSpeed;
inputBindings.Enable ();
move = inputBindings.FindAction ("Move");
interact = inputBindings.FindAction ("Interact");
}
private void FixedUpdate () {
// rotate player to face mouse position
if (gamePad) {
// rotate player to face gamepad right stick position
Vector2 rightStick = Gamepad.current.rightStick.ReadValue ();
Vector3 rotation = new Vector3 (rightStick.x, 0f, rightStick.y);
rb.rotation = Quaternion.LookRotation (rotation);
} else {
Ray ray = Camera.main.ScreenPointToRay (Mouse.current.position.ReadValue ());
RaycastHit hit = new RaycastHit ();
if (Physics.Raycast (ray.origin, ray.direction, out hit)) {
Vector3 target = hit.point - rb.position;
target.y = 0.0f;
rb.rotation = Quaternion.Slerp (rb.rotation, Quaternion.LookRotation (target), tempRotationSpeed * Time.deltaTime);
}
}
// player movment
Vector3 movement = new Vector3 (movementSpeed * Time.deltaTime * horizAxis, rb.velocity.y, movementSpeed * Time.deltaTime * vertAxis);
rb.velocity = movement;
}
private void Update () {
var moveVal = move.ReadValue<Vector2> ();
horizAxis = moveVal.x;
vertAxis = moveVal.y;
if (interact.triggered) {
if (touchingInteractable) {
touchingInteractable.Interact ();
}
checkPickup ();
}
}
/// <summary>
/// Check if object should be picked up or put down
/// </summary>
private void checkPickup () {
// if next to a sconce and currently holding something, put it in the sconce
if (touchingSconce && currentPickup) {
currentPickup.transform.parent = touchingSconce.transform;
currentPickup.transform.localPosition = new Vector3 (0, 0, 0);
currentPickup = null;
Debug.Log ("this is colliding");
}
// drop object if one is currently picked up, pick up if one is nearby
if (currentPickup) {
if (currentPickup.name != "Torch") {
dropObject ();
} else if (canDropTorch) {
dropObject ();
}
} else if (pickupObj) { // if there is an object nearby that can be picked up
pickupObject ();
}
}
/// <summary>
/// Called to pick up an object and parent it to the player
/// </summary>
private void pickupObject () {
currentPickup = pickupObj;
currentPickup.GetComponent<Rigidbody> ().isKinematic = true;
currentPickup.transform.parent = pickupPos.transform;
if (pickupObj.tag == "Drag") {
tempRotationSpeed = rotationSpeed / 4;
} else {
currentPickup.GetComponent<Collider> ().enabled = false;
// set position and rotation
currentPickup.transform.localPosition = new Vector3 (0, 0, 0);
currentPickup.transform.localEulerAngles = new Vector3 (0, 0, 0);
}
}
/// <summary>
/// Called to drop object and unparent it from player
/// </summary>
private void dropObject () {
tempRotationSpeed = rotationSpeed;
// unparent currently picked up object
currentPickup.transform.parent = null;
// set non kinematic and enable collider
currentPickup.GetComponent<Rigidbody> ().isKinematic = false;
currentPickup.GetComponent<Collider> ().enabled = true;
currentPickup = null;
}
// Collision checking functions
private void OnCollisionEnter (Collision other) {
// checking collisions with interactable objects
touchingInteractable = (other.gameObject.GetComponent<InteractableObject> () != null) ? other.gameObject.GetComponent<InteractableObject> () : null;
}
private void OnCollisionExit (Collision other) {
touchingInteractable = null;
}
private void OnTriggerEnter (Collider other) {
pickupObj = (other.gameObject.tag == "Pickup" || other.gameObject.tag == "Drag") ? other.gameObject : null;
Debug.Log (pickupObj);
touchingSconce = (other.gameObject.name == "Sconce") ? other.gameObject : null;
}
private void OnTriggerExit (Collider other) {
pickupObj = null;
touchingSconce = null;
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Key : MonoBehaviour {
private void OnCollisionEnter (Collision collision) {
if (collision.gameObject.name == "Player") {
Debug.Log ("You picked up a key!");
GameManager.Instance.numKeys++;
Destroy (gameObject);
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Torch : MonoBehaviour
{
public GameObject CampFire;
public Light Light;
private GameObject[] Enemies;
private float MaxRange;
public float torchFuel = 100f;
private float torchScale;
public float torchBurnRate = 10f;
private float Range;
public float rangeScale;
void Start()
{
//here, the torch should get set to 0 so it is unlit at the beginning of the game,
//but not for now cuz of testing and whatnot
// StartCoroutine("oneSecPrint");
// Enemies = GameObject.FindGameObjectsWithTag("Enemies");
MaxRange = Light.range;
}
void Update()
{
if(torchFuel > 0)
{
burnFuel();
}
}
IEnumerator oneSecPrint()
{
while (true)
{
yield return new WaitForSeconds(1f);
OutputFuel();
}
}
void burnFuel()
{
torchFuel -= torchBurnRate * Time.deltaTime;
// float closestEnemy = 100;
// for(int i=0; i<Enemies.Length; i++)
// {
// float dist = Vector3.Distance(this.transform.position, Enemies[i].transform.position);
// if(dist < closestEnemy)
// {
// closestEnemy = dist;
// }
// }
// if(closestEnemy*rangeScale < MaxRange)
// {
// torchScale = Mathf.Clamp(torchFuel, 0, closestEnemy*rangeScale);
// }
// else
// {
// torchScale = Mathf.Clamp(torchFuel, 0, MaxRange);
// }
// Light.transform.localScale = new Vector3(torchScale, torchScale, torchScale);
torchScale = Mathf.Clamp(torchFuel, 0, MaxRange);
Light.range = torchScale;
}
//for testing purposes only
void OutputFuel()
{
Debug.Log("TORCH :: Remaining Torch Fuel: " + torchFuel);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LightCheck : MonoBehaviour {
// light detection variables
public bool printLightLevel;
public float minLightValue;
public float maxDarknessTime;
private float darknessTimer = 0f;
public RenderTexture lightCheckTexture;
public float LightLevel = 1000000000f;
// Update is called once per frame
void Update () {
// copy rendertexture into temporary rendertexture for this frame
RenderTexture tmpTexture = RenderTexture.GetTemporary (lightCheckTexture.width, lightCheckTexture.height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear);
Graphics.Blit (lightCheckTexture, tmpTexture);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = tmpTexture;
// copy rendertexture values into texture2D
Texture2D tmp2DTexture = new Texture2D (lightCheckTexture.width, lightCheckTexture.height);
tmp2DTexture.ReadPixels (new Rect (0, 0, tmpTexture.width, tmpTexture.height), 0, 0);
tmp2DTexture.Apply ();
// release temporary rendertexture
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary (tmpTexture);
// get pixel values out of texture
Color32[] colors = tmp2DTexture.GetPixels32 ();
Destroy (tmp2DTexture);
// calculate light level by adding up all pixel values
LightLevel = 0;
for (int i = 0; i < colors.Length; i++) {
// formula to calculate light level from rgb values
LightLevel += ((0.2126f * colors[i].r) + (0.7152f * colors[i].g) + (0.0722f * colors[i].b));
}
if (printLightLevel) {
Debug.Log ("Light Level: " + LightLevel);
}
if (LightLevel <= minLightValue) {
// Debug.Log("In Darkness: " + lightChecker.LightLevel);
if (darknessTimer == 0f) {
darknessTimer = Time.time;
}
if ((Time.time - darknessTimer) > maxDarknessTime) {
SceneManager.LoadScene (SceneManager.GetActiveScene ().name);
}
} else {
darknessTimer = 0f;
}
}
}
|
88411ae436a457c8af22276ca29502f900136d41
|
[
"Markdown",
"C#"
] | 10 |
C#
|
nicksundermeyer/Campfire
|
a94cb3149014787b6a7164e077f6207382bff329
|
1f6e3e6e0f3564f90880bbe1f92d348921d16da4
|
refs/heads/master
|
<repo_name>darwintk/eyebrow_length<file_sep>/dlib_face_68.md
# Dlib面部识别以及68个特征点
> 在处理图像上,opencv比较常用,因此除了人脸识别使用了dlib库,其他地方都使用了opencv来进行处理
本代码参考[vipstone/faceai](https://github.com/vipstone/faceai)
## Dlib面部识别
使用dlib中的get_frontal_face_detector()来查找图片中的人脸,代码如下:
``` python
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转灰度图
detector = dlib.get_frontal_face_detector() # 人脸分类器
dets = detector(gray, 1) # 使用人脸分类器找到图中的人脸
for face in dets:
# 找到人脸矩形框的四个角点
left = face.left()
top = face.top()sss
right = face.right()
bottom = face.bottom()
# 在图片中标注人脸,并显示
cv2.rectangle(img, (left, top), (right, bottom), (255 ,0, 0), 2)
cv2.imshow("image", img)
cv2.waitKey(0)
```
完整代码:[facesDetection](./facesDetection.py)
识别的结果如下图所示:

## Dlib面部识别的68个特征点
除了识别图像中的人脸外,dlib还能找到人脸上的68个特征点
- 面部轮廓 1~17
- 眉毛
- 左眉毛 18~22
- 右眉毛 23~27
- 鼻梁 28~31
- 鼻子下沿 32~36
- 眼睛
- 左眼 37~42
- 右眼 43~48
- 嘴巴外轮廓49~60
- 嘴巴内轮廓 61~68
如图所示:

代码如下:
``` python
# 获取人脸检测器
predictor = dlib.shape_predictor(
"./shape_predictor_68_face_landmarks.dat")
dets = detector(gray, 1)
for face in dets:
# 在图片中标注人脸,并显示
left = face.left()
top = face.top()
right = face.right()
bottom = face.bottom()
cv2.rectangle(img, (left, top), (right, bottom), (255 ,0, 0), 2)
cv2.imshow("image", img)
cv2.waitKey(0)
shape = predictor(img, face) # 寻找人脸的68个标定点
i = 1
# 遍历所有点,打印出其坐标,并圈出来
for pt in shape.parts():
pt_pos = (pt.x, pt.y)
cv2.circle(img, pt_pos, 1, ( 0,255, 0), 2)
# 打印点的标号
cv2.putText(img, str(i),pt_pos,cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1, cv2.LINE_AA)
i+=1
cv2.imshow("image", img)
# 裁剪出人脸部分进行保存
imgsmall = img[ (top-50):(bottom+50),(left-50):(right+50),:]
cv2.imshow("image_small", imgsmall)
cv2.waitKey(0)
cv2.imwrite("Ronald68.jpg",imgsmall)
cv2.destroyAllWindows()
```
完整代码:[detectionDlib](./detectionDlib.py)
<file_sep>/facesDetection.py
#coding=utf-8
# faces detect
import cv2 as cv
import dlib
path = "./ori_img/chelsea1.jpg"
img = cv.imread(path)
cv.imshow("image", img)
cv.waitKey(0)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
detector = dlib.get_frontal_face_detector()
dets = detector(gray,1)
for face in dets:
# 在图片中标注人脸,并显示
left = face.left()
top = face.top()
right = face.right()
bottom = face.bottom()
cv.rectangle(img, (left, top), (right, bottom), (0 ,0, 255), 2)
cv.imshow("image", img)
cv.waitKey(0)
cv.imshow("image", img)
cv.waitKey(0)
cv.imwrite("./out_img/chelsea1_faces.jpg",img)
cv.destroyAllWindows()<file_sep>/detectionDlib.py
#coding=utf-8
#图片检测 - Dlib版本
import cv2
import dlib
path = "./ori_img/Ronald1.jpg"
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#人脸分类器
detector = dlib.get_frontal_face_detector()
# 获取人脸检测器
predictor = dlib.shape_predictor(
"./shape_predictor_68_face_landmarks.dat")
dets = detector(gray, 1)
for face in dets:
# 在图片中标注人脸,并显示
left = face.left()
top = face.top()
right = face.right()
bottom = face.bottom()
cv2.rectangle(img, (left, top), (right, bottom), (255 ,0, 0), 2)
cv2.imshow("image", img)
cv2.waitKey(0)
shape = predictor(img, face) # 寻找人脸的68个标定点
i = 1
# 遍历所有点,打印出其坐标,并圈出来
for pt in shape.parts():
pt_pos = (pt.x, pt.y)
cv2.circle(img, pt_pos, 1, ( 0,255, 0), 2)
cv2.putText(img, str(i),pt_pos,cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1, cv2.LINE_AA)
i+=1
# cv2.waitKey(0)
cv2.imshow("image", img)
imgsmall = img[ (top-50):(bottom+50),(left-50):(right+50),:]
cv2.imshow("image_small", imgsmall)
cv2.waitKey(0)
cv2.imwrite("./out_img/Ronald1_68points.jpg",imgsmall)
cv2.destroyAllWindows()
<file_sep>/out_img/images.md
# 关于md文件中的图片上传问题
在一开始使用git push,发现不论是打开md文件还是直接打开上传的图片,都无法显示(裂开状态),后来*工具人小然哥*表示:可能是没有**上传成功**。
于是我删去了本地的out_img,在GitHub的页面上直接新建文件夹上传,之后图片成功显示。
最后再`git pull origin master`,将本地和线上的项目同步一波。
|
1567afa471f5fe72d042830931b99808e81b35c1
|
[
"Markdown",
"Python"
] | 4 |
Markdown
|
darwintk/eyebrow_length
|
0ff90063037c7e2d761b643cd57b72a0cc6857eb
|
ff3505dd513e5564470286370fdbb718811dd942
|
refs/heads/master
|
<file_sep>var sys = require('sys');
var exec = require('child_process').exec;
var child;
var fs = require('fs');
var traverseFileSystem = function (currentPath) {
var files = fs.readdirSync(currentPath);
for (var i in files) {
var currentFile = currentPath + '/' + files[i];
var stats = fs.statSync(currentFile);
if (stats.isDirectory()) {
var src = currentFile + '/';
dest = currentFile.replace(/^dist/, 'b2b') + '/';
(function(method, src, dest) {
var command = [
"s3cmd/s3cmd",
"-r",
method,
src,
"s3://mydriverstatic/" + dest
].join(" ");
child = exec(command, function (error, stdout, stderr) {
sys.print(stdout);
sys.print(stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
})("put", src, dest);
// traverseFileSystem(currentFile);
}
}
};
traverseFileSystem('dist');
|
b8fc8b3e0ab2ff53607fc9ed8b3faa38b7dc81ef
|
[
"JavaScript"
] | 1 |
JavaScript
|
mrhanti/node-s3
|
33430fdaca35abbfddc78f88e1b868b6e99def4e
|
6021543ec679a272d546dad8e402fc2f59f2ed0d
|
refs/heads/master
|
<repo_name>una-eif506-18G01/examen-parcial-1-JordyRG21<file_sep>/examen1/src/Components/Menu.js
import React, { Component } from 'react';
class Menu extends Component {
render() {
return (
<div className="container-fluid">
<div className="row">
<div className="nav nav-pills">
<ul>
<li><a href="/about">About</a></li>
<li><a href="/"> Home</a></li>
</ul>
</div>
</div>
</div>
);
}
}
export default Menu;
<file_sep>/examen1/src/Components/Aside.js
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Aside extends Component {
render() {
return (
<aside className="col-md-2">
<h2>{this.props.heading}</h2>
<article>
<p>{this.props.asideContent}</p>
</article>
</aside>
);
}
}
export default Aside;<file_sep>/examen1/src/Components/ViewContent.js
import React, { Component } from 'react';
import DocumentMeta from 'react-document-meta';
import Menu from './Menu';
import Header from './Header';
import Aside from './Aside';
import Footer from './Footer';
import 'bootstrap/dist/css/bootstrap.css';
class ViewContent extends Component {
render() {
const content = this.props.pageContent;
const meta = {
title: content.name,
meta: {
charset: 'utf-8',
name: {
keywords: content.keywords
}
}
};
return (
<React.Fragment>
<DocumentMeta {...meta} />
<Header />
<Menu />
<main>
<div className="container-fluid">
<div className="row">
<div className="col-md-2"><img className="img-responsive" src={content.main_logo} alt="Main Logo"></img></div>
<article className="col-md-8">
<h1>{content.heading_1}</h1>
<p>{content.main_content}</p>
<img className="img-responsive" src={content.main_img} alt="Main Image"></img>
</article>
{content.aside_content &&
<Aside asideContent ={content.aside_content} heading = {content.heading_2} />
}
</div>
</div>
</main>
<Footer copyright={content.copyright}/>
</React.Fragment>
);
}
}
export default ViewContent;<file_sep>/examen1/src/Components/Content.js
import React, { Component } from 'react';
import { BrowserRouter as Router } from "react-router-dom";
import {PropsRoute} from 'react-router-with-props';
import Switch from 'react-router-dom/Switch';
import ViewContent from './ViewContent';
class Content extends Component {
render() {
return (
<React.Fragment>
<Router>
<React.Fragment>
{ this.props.data.length > 0 &&
<Switch>
<PropsRoute exact path="/" component={ViewContent} pageContent ={this.props.data[0]}/>
<PropsRoute path="/about" component={ViewContent} pageContent ={this.props.data[1]}/>
</Switch>
}
</React.Fragment>
</Router>
</React.Fragment>
);
}
}
export default Content;
|
c80e016e5b8ea161882e37a87f16c1c0764b8483
|
[
"JavaScript"
] | 4 |
JavaScript
|
una-eif506-18G01/examen-parcial-1-JordyRG21
|
c938635ed0a554d26220c9848482beeace388f3a
|
6dca1f6ae553ef1a40f5760c952a77a85e69ed5f
|
refs/heads/master
|
<repo_name>williamsbs/Piscine-PHP<file_sep>/day05/ex00/ex00.sql
CREATE DATABASE db_wsabates CHARACTER SET 'utf8';
<file_sep>/rush00/srcs/admin/modif_categorie.php
<?PHP
session_start();
include ("header_admin.php");
if ((isset($_POST['ancienne']) && $_POST['ancienne'] != NULL)&&
(isset($_POST['nouvelle']) && $_POST['nouvelle'] != NULL)&&
(isset($_POST['submit']) && $_POST['submit'] === "valider"))
{
$ok = 0;
$content = unserialize(file_get_contents("../../private/categorie"));
foreach ($content as $cat=>$value)
{
$i = 0;
foreach($value as $elem)
{
if ($elem == $_POST['ancienne']){
$content[$cat][$_POST['nouvelle']] = $_POST['nouvelle'];
unset($content[$cat][$_POST['ancienne']]);
$ok = 1;
}
$i++;
}
}
}
else
{
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
exit();
}
echo $ok;
if ($ok == 0)
{
$_SESSION['modif_cat'] = 0;
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
exit();
}
else if ($ok == 1)
{
$serialized = serialize($content);
file_put_contents("../../private/categorie", $serialized);
$_SESSION['modif_cat'] = 1;
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
exit();
}
?>
<file_sep>/rush00/ancien/ancien_fruit.php
<?php
include ('index.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Boutique</title>
<link rel="stylesheet" href="selection.css">
</head>
<body>
<div class="responsive">
<div class="gallery">
<img title="Babane" src="https://www.ok-salute.it/wp-content/uploads/2017/05/banane-696x392.jpg" alt="Image Banane">
<div class="desc">La banane est le fruit ou la baie dérivant de l’inflorescence du bananier. Les bananes sont des fruits très généralement stériles issus de variétés domestiquées.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="responsive">
<div class="gallery">
<img title="Fraise" src="https://www.lanutrition.fr/sites/default/files/styles/article_large/public/ressources/fraises_3.jpg?itok=xKYGdJIk" alt="Image Fraise">
<div class="desc">La fraise est le fruit des fraisiers, espèces de plantes herbacées appartenant au genre Fragaria, dont plusieurs sont cultivées.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="responsive">
<div class="gallery">
<img title="Pomme" src="https://www.lejournaldejoliette.ca/upload/11/evenements/2015/1/207453/rappel-de-pommes-620x348.jpg" alt="Image Pomme">
<div class="desc">La pomme est un fruit comestible à pépins d'un goût sucré et acidulé et à la propriété plus ou moins astringente selon les variétés.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="responsive">
<div class="gallery">
<img title="Orange" src="https://www.rd.com/wp-content/uploads/2017/12/01_oranges_Finally%E2%80%94Here%E2%80%99s-Which-%E2%80%9COrange%E2%80%9D-Came-First-the-Color-or-the-Fruit_691064353_Lucky-Business-1024x683.jpg" alt="Image Orange">
<div class="desc">L’orange est un agrume, fruit des orangers, des arbres de différentes espèces de la famille des Rutacées ou d'hybrides de ceux-ci.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="clearfix"></div>
</body>
</html>
<file_sep>/rush00/srcs/connection/auth.php
<?php
function auth($login, $passwd)
{
$mdp = hash(sha512, $passwd);
$content = unserialize(file_get_contents("../../private/passwd"));
$is_logged = FALSE;
foreach($content as $elem)
{
if ($elem["login"] == $login && $elem["passwd"] == $mdp)
{
$is_logged = TRUE;
}
}
if ($is_logged == TRUE)
{
return (TRUE);
}
else
{
return (FALSE);
}
}
?>
<file_sep>/rush00/srcs/admin/sup_product.php
<?php
session_start();
$content = unserialize(file_get_contents("../../private/data"));
if (count($content) > 0)
{
foreach ($content as $elem=>$value)
{
if ($value[0] == $_POST['id'])
{
unset($content[$elem]);
$flag = 1;
}
}
}
else {
$_SESSION['supp'] = 0;
header('Location: products.php');
exit();
}
if ($flag == 1)
{
$i = 0;
$content = array_values($content);
foreach ($content as $product=>$value)
{
$content[$product][0] = ($i + 1);
$i++;
}
$serialized = serialize($content);
file_put_contents("../../private/data", $serialized);
$_SESSION['supp'] = "1";
echo "<meta http-equiv='refresh' content='0,url=products.php'>";
exit();
}
else {
$_SESSION['supp'] = "0";
echo "<meta http-equiv='refresh' content='0,url=products.php'>";
exit();
}
?>
<file_sep>/rush00/srcs/admin/header_admin.php
<?php
session_start();
$data = unserialize(file_get_contents("../../private/data"));
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Boutique</title>
<link rel="stylesheet" href="../css/selection.css">
</head>
<body>
<nav>
<label for="menu-deroulant" class="menu-deroulant">Menu</label>
<input type="checkbox" id="menu-deroulant" role="button">
<ul>
<li class='home'><a href='../selection.php'>Boutique</a></li>
<?php
$i=0;
$j=0;
$content = unserialize(file_get_contents("../../private/categorie"));
$cat1 = $content[cat1];
$cat2 = $content[cat2];
$cat3 = $content[cat3];
$cat4 = $content[cat4];
foreach($cat1 as $elem1){}
foreach($cat2 as $elem2){}
foreach($cat3 as $elem3){}
foreach($cat4 as $elem4){}
// ------------------------------------LEGUME-----------------------------------------------
echo "<li class='menu-legume'><a href='../Articles.php?id=".$i."&categorie=".$elem1."'>".$elem1."</a>";
echo "<ul class='sous-menu'>";
while($data[$j++][2] == "Legume")
{
echo"<li><a href='../detail.php?produit=".($i+1)."'>".$data[$i++][1]."</a></li>";
}
echo "</ul></li>";
// ---------------------------------------FRUIT--------------------------------------------
echo "<li class='menu-fruit'><a href='../Articles.php?id=".$i."&categorie=".$elem2."'>".$elem2."</a>";
echo "<ul class='sous-menu'>";
$j--;
while($data[$j++][2] == "Fruit"){
echo"<li><a href='../detail.php?produit=".($i+1)."'>".$data[$i++][1]."</a></li>";}
echo "</ul></li>";
// ---------------------------------------VIANDE--------------------------------------------
echo "<li class='menu-viande'><a href='../Articles.php?id=".$i."&categorie=".$elem3."'>".$elem3."</a>";
echo "<ul class='sous-menu'>";
$j--;
while($data[$j++][2] == "Viande"){
echo"<li><a href='../detail.php?produit=".($i+1)."'>".$data[$i++][1]."</a></li>";}
echo "</ul></li>";
// --------------------------------------LAIT---------------------------------------------
echo "<li class='menu-lait'><a href='../Articles.php?id=".$i."&categorie=".$elem4."'>".$elem4."</a>";
echo "<ul class='sous-menu'>";
$j--;
while($data[$j++][2] == "Produits laitier"){
echo"<li><a href='../detail.php?produit=".($i+1)."'>".$data[$i++][1]."</a></li>";}
echo "</ul></li>";
// -----------------------------------------------------------------------------------?>
<li class="compte"><a href="#">Compte</a>
<ul class="sous-menu">
<li><a href="../connection/login.php">Se connecter</a></li>
<li><a href="../connection/create.php">Cree un compte</a></li>
<li><a href="../connection/modif.php">Modifier son compte</a></li>
<li><a href="../connection/supprimer.php">Supprimer son compte</a></li>
<li><a href="../connection/logout.php">Deconnection</a></li>
</ul></li>
<li class="panier"><a href="../panier.php">Panier</a>
<ul class="sous-menu">
<li><a href="../panier.php">Visualiser le panier</a></li>
<li><a href="../vide_panier.php">supprimer le panier</a></li>
</ul></li>
<?php
if ($_SESSION["loggued_on_user"] == "admin")
{
echo "<li class='admin'><a href='admin.php'>Admin</a>";
echo "<ul class='sous-menu'>";
echo "<li><a href='add_user.php'>Ajouter un utilisateur</a></li>";
echo "<li><a href='modif_user.php'>Modifier un utilisateur</a></li>";
echo "<li><a href='sup_user.php'>Supprimer un utilisateur</a></li>";
echo "<li><a href='products.php'>Ajouter/Modifier/Supprimer un produit</a></li>";
echo "<li><a href='categories.php'>Ajouter/Modifer/Supprimer une categorie</a></li>";
echo "<li><a href='historique_commande.php'>Historique des commandes</a></li>";
echo "</ul></li>";
}
?>
</ul>
</nav>
</body>
</html>
<file_sep>/rush00/srcs/Articles.php
<?php
include ("header.php"); ?>
<!DOCTYPE html>
<html>
<body>
<?php
$data = unserialize(file_get_contents("../private/data"));
$j=0;
foreach ($data as $elem)
{
while($data[$j++][2] === $_GET[categorie])
{
echo "<div class='responsive'>";
echo "<div class='aff_prod'>";
echo "<tr><td>".$data[$_GET[id]][1]."</td></tr>";
echo "<tr><td><img src='".$data[$_GET[id]][6]."'></td><tr/>";
echo "<tr><td ><a class='voir_articles' href='detail.php?produit=".$data[$_GET[id]][0]."'>Voir les ".$data[$_GET[id]][1]."s !</a></td></tr>";
echo "</div>";
echo "</div>";
$_GET[id]++;
}
}
?>
</body>
</html>
<file_sep>/rush00/srcs/admin/add_product.php
<?php
session_start();
function get_data($content)
{
$i = 0;
if((isset($_POST['type']) && $_POST['type'] != NULL) &&
(isset($_POST['categorie']) && $_POST['categorie'] != NULL) &&
($_POST['categorie'] == "Fruit" || $_POST['categorie'] == "Legume" ||
$_POST['categorie'] == 'Viande' || $_POST['categorie'] == "Produits laitier") &&
(isset($_POST['quantite']) && $_POST['quantite'] != NULL) &&
(isset($_POST['poids']) && $_POST['poids'] != NULL) &&
(isset($_POST['prix']) && $_POST['prix'] != NULL) &&
(isset($_POST['image']) && $_POST['image'] != NULL) &&
(isset($_POST['submit']) && $_POST['submit'] == "valider"))
{
$tab[0] = $id+1;
$tab[1] = $_POST['type'];
$tab[2] = $_POST['categorie'];
$tab[3] = $_POST['quantite'];
$tab[4] = $_POST['poids'];
$tab[5] = $_POST['prix'];
$tab[6] = $_POST['image'];
}
else
{
$_SESSION["ajouter"] = 1;
header('Location: products.php');
exit();
}
return($tab);
}
$content = unserialize(file_get_contents("../../private/data"));
$data = get_data($content);
$data[0] = count($content) + 1;
$content[] = $data;
$serialized = serialize($content);
file_put_contents("../../private/data", $serialized);
$_SESSION["ajouter"] = 2;
echo "<meta http-equiv='refresh' content='0,url=products.php'>";
exit();
?>
<file_sep>/rush00/srcs/detail.php
<?php
session_start();
include ("header.php"); ?>
<!DOCTYPE html>
<html>
<body>
<?php
$data = unserialize(file_get_contents("../private/data"));
$flag = 0;
$content = unserialize(file_get_contents("../private/categorie"));
$cat1 = $content[cat1];
$cat2 = $content[cat2];
$cat3 = $content[cat3];
$cat4 = $content[cat4];
foreach($cat1 as $elem1){}
foreach($cat2 as $elem2){}
foreach($cat3 as $elem3){}
foreach($cat4 as $elem4){}
$tab[0] = $elem1;
$tab[1] = $elem2;
$tab[2] = $elem3;
$tab[3] = $elem4;
$id = $_GET[produit] - 1;
foreach ($data as $elem)
{
if ($elem[0] == $_GET[produit])
$flag = 1;
}
?>
<h1><?php echo $data[$id][1];?>:</h1>
<?php
if (isset($_GET[produit]) && $_GET[produit] != NULL &&
$_GET[produit] >= 0 && is_numeric($_GET[produit]) && $flag == 1)
{
echo "<a class='admin-users' href='Articles.php?id=".$id."&categorie=".$data[$id][2]."'>← Revenir à la liste</a><br/><br/>";
echo "<div class='responsive'>";
echo "<div class='aff_prod'>";
echo "<table>";
echo "<tr><td class='produit'>".$data[$id][1]."</td><tr/>";
echo "<tr><td><img src='".$data[$id][6]."'></td><tr/>";
if ($data[$id][2] == "Legume")
echo "<tr><td>Categorie : ".$tab[0]."</td><tr/>";
if ($data[$id][2] == "Fruit")
echo "<tr><td>Categorie : ".$tab[1]."</td><tr/>";
if ($data[$id][2] == "Viande")
echo "<tr><td>Categorie : ".$tab[2]."</td><tr/>";
if ($data[$id][2] == "Produits laitier")
echo "<tr><td>Categorie : ".$tab[3]."</td><tr/>";
echo "<tr><td>Poids : ".$data[$id][4]."</td><tr/>";
echo "<tr><td>Prix : ".$data[$id][5]."</td><tr/>";
echo "<tr><td>Quantité : ".$data[$id][3]."</td><tr/>";
echo "<tr><td><a class='voir_articles' href='add_panier.php?produit=".$data[$id][0]."'>Ajouter au panier</a></td><tr/>";
echo "</table>";
echo "</div>";
echo "</div>";
}
?>
</body>
<footer>
</footer>
</html>
<file_sep>/day01/ex11/do_op2.php
#!/usr/bin/php
<?php
// $chiffre1 = trim ($argv[1]);
// $operateur = trim ($argv[2]);
// $chiffre3 = trim ($argv[3]);
if ($argc != 2)
{
echo "Incorrect Parameters\n";
}
// $op = explode(";", "+;-;*;/;%");
$cal = sscanf($argv[1], "%d %c %d");
if ($cal[0] && $cal[1] && $cal[2])
{
if ($cal[1] == "+")
echo $cal[0] + $cal[2];
if ($cal[1] == "-")
echo $cal[0] - $cal[2];
if ($cal[1] == "/")
echo $cal[0] / $cal[2];
if ($cal[1] == "*")
echo $cal[0] * $cal[2];
if ($cal[1] == "%")
echo $cal[0] % $cal[2];
}
else
echo "tu fais n'importe quoi";
?>
<file_sep>/day04/ex03/modif.php
<?php
if ($_POST["submit"] == "OK" && $_POST["newpw"] != NULL && $_POST["login"] != NULL)
{
$oldpw = hash(sha512, $_POST["oldpw"]);
$newpw = hash(sha512, $_POST["newpw"]);
$content = unserialize(file_get_contents("../private/passwd"));
$i = 0;
foreach($content as $elem)
{
if ($elem["login"] == $_POST["login"] && $elem["passwd"] == $oldpw)
{
$content[$i]["passwd"] = $newpw;
$changed = 1;
}
if ($elem["passwd"] != $oldpw)
{
echo "ERROR\n";
}
$i++;
}
if ($changed == 1)
{
$serialised = serialize($content);
file_put_contents("../private/passwd", $serialised);
echo "OK\n";
}
}
else
{
echo "ERROR\n";
}
?>
<file_sep>/day05/ex02/ex02.sql
insert into ft_table value(1,'loki','staff','2013-05-01');
insert into ft_table value(2,'scadoux','student','2014-01-01');
insert into ft_table value(3,'chap','staff','2011-04-27');
insert into ft_table value(4,'bambou','staff','2014-03-01');
insert into ft_table value(5,'fantomet','staff','2010-04-03');
<file_sep>/day02/ex00/another_world.php
#!/usr/bin/php
<?php
$trimed = trim($argv[1]);
$replaced = preg_replace('/[ \t]{2,}/', ' ', $trimed);
echo $replaced;
echo "\n";
?>
<file_sep>/rush00/srcs/admin/modif_user.php
<?php
include ('header_admin.php');
if ($_POST["submit"] == "OK" && $_POST["newpw"] != NULL && $_POST["login"] != NULL)
{
$oldpw = hash(sha512, $_POST["oldpw"]);
$newpw = hash(sha512, $_POST["newpw"]);
$content = unserialize(file_get_contents("../../private/passwd"));
$i = 0;
$changed = 0;
foreach($content as $elem)
{
if ($elem["login"] == $_POST["login"] && $elem["passwd"] == $oldpw)
{
$content[$i]["passwd"] = $newpw;
$changed = 1;
}
$i++;
}
if ($changed == 1)
{
$serialised = serialize($content);
file_put_contents("../../private/passwd", $serialised);
?>
<h1>Mot de passe modifié</h1>
<?php
}
elseif ($changed == 0)
{
?>
<h1>Le compte existe pas</h1>
<?php
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Modifier un compte</title>
</head>
<body>
<h1>Modifier un compte:</h1>
<div class="connection">
<form method="POST" action="modif_user.php">
Identifiant: <input type="text" name="login" value="">
</br>
Ancien mot de passe: <input type="<PASSWORD>" name="oldpw" value="">
</br>
Nouveau mot de passe: <input type="<PASSWORD>" name="<PASSWORD>" value="">
<input type="submit" name="submit" value="OK">
</form>
</div>
</body>
</html>
<file_sep>/day05/ex03/ex03.sql
INSERT INTO ft_table (login, groupe, date_de_creation)
SELECT nom, 'other', date_naissance FROM fiche_personne WHERE LENGHT(nom) < 9 AND LIKE '%a%' ORDER BY ASC LIMIT 10;
<file_sep>/rush00/ancien/selection2.php
<?php include ("index.php"); ?>
<!DOCTYPE html>
<html>
<body>
<?PHP
$data = unserialize(file_get_contents("../private/categorie"));
echo "<table id='boutique'>";
foreach ($data as $elem)
{
echo "<tr><td class='type'>".$elem[legume]."</td></tr>";
// print_r ($elem);
echo "<tr><td><img src='".$elem[7]."'/ style='width:20%;'></td><tr/>";
echo "<tr><td class='acheter_articles'><a href='detail.php?produit=".$elem[legume]."'>Voir les produits !</a></td></tr>";
}
echo "</table>";
?>
</body>
<footer>
</footer>
</html>
<file_sep>/rush00/srcs/admin/categories.php
<?php
session_start();
include ("header_admin.php");
$content = unserialize(file_get_contents("../../private/categorie"));
$cat1 = $content[cat1];
$cat2 = $content[cat2];
$cat3 = $content[cat3];
$cat4 = $content[cat4];
$cat5 = $content[cat5];
echo "<table class='products'>";
echo "<tr>
<th>Catégorie :</th>
</tr>";
foreach ($cat1 as $cat1_elem)
{
echo "<tr>
<td>".$cat1_elem."</td></tr>";
}
foreach ($cat2 as $cat2_elem)
{
echo "<td>".$cat2_elem."</td></tr>";
}
foreach ($cat3 as $cat3_elem)
{
echo "<td>".$cat3_elem."</td></tr>";
}
foreach ($cat4 as $cat4_elem)
{
echo "<td>".$cat4_elem."</td></tr>";
}
if ($cat5 != "")
{
foreach ($cat5 as $cat5_elem)
{
echo "<td>".$cat5_elem."</td></tr>";
}
}
echo "</table>";
?>
<h1>Ajouter une categorie</h1>
<div class='connection'>
<form method="POST" action="add_categorie.php">
Catégorie 1:<input type="text" name='categorie'></br>
<input type="submit" name="submit" value="valider">
</form>
</div>
<h1>Modifier une catégorie</h1>
<div class='connection'>
<form method="POST" action="modif_categorie.php">
Catégorie a modifier:<input type="text" name='ancienne'></br>
Nouvelle catégorie :<input type="text" name='nouvelle'></br>
<input type="submit" name="submit" value="valider">
</form>
</div>
<h1>supprimer une catégorie</h1>
<div class='connection'>
<form method="POST" action="supp_categorie.php">
Catégorie :<input type="text" name='categorie'></br>
<input type="submit" name="submit" value="valider">
</form>
</div>
<file_sep>/day01/ex09/rostring.php
#!/usr/bin/php
<?php
function ft_destroy_espace($tab)
{
$elem = trim($tab);
while (strstr($elem, " "))
{
$elem = str_ireplace(" ", " ", $elem);
}
return($elem);
}
$tab = ft_destroy_espace($argv[1]);
$tab1 = explode(" ", $tab);
$count = count($tab1) - 1 ;
$tmp = $tab1[0];
$tab1[0] = $tab1[$count];
$tab1[$count] = $tmp;
echo(implode(" ", $tab1));
?>
<file_sep>/rush00/srcs/admin/products.php
<?php
session_start();
include ("header_admin.php");
$content = unserialize(file_get_contents("../../private/data"));
echo "<table class='products'>";
echo "<tr>
<th>Id</th>
<th>Type</th>
<th>Catégorie</th>
<th>Quantite</th>
<th>Poids</th>
<th>Prix</th>
<th>Image</th>
</tr>";
foreach ($content as $elem)
{
echo "<tr>
<td>".$elem[0]."</td>
<td>".$elem[1]."</td>
<td>".$elem[2]."</td>
<td>".$elem[3]."</td>
<td>".$elem[4]."</td>
<td>".$elem[5]."</td>
<td>".$elem[6]."</td>
</tr>";
}
echo "</table>";
?>
<?php
if( $_SESSION["ajouter"] == 1)
{
echo "<h1>Il faut remplire tous les champs</h1>";
}
?>
<h1>Ajouter un produit</h1>
<div class='connection'>
<form method="POST" action="add_product.php">
Type :<input type="text" name='type'></br>
Categorie :<input type="text" name='categorie'></br>
Quantite :<input type="text" name='quantite'></br>
Poids :<input type="text" name='poids'></br>
Prix :<input type="text" name='prix'></br>
Image :<input type="file" name='image'></br></br>
<input type="submit" name="submit" value="valider">
</form>
</div>
<h1>Modifier un produit</h1>
<div class='connection'>
<form method="POST" action="modif_product.php">
Id :<input type="text" name='id'></br>
Type :<input type="text" name='type'></br>
Categorie :<input type="text" name='categorie'></br>
Quantite :<input type="text" name='quantite'></br>
Poids :<input type="text" name='poids'></br>
Prix :<input type="text" name='prix'></br>
Image :<input type="file" name='image'></br></br>
<input type="submit" name="submit" value="valider">
</form>
</div>
<h1>supprimer un produit</h1>
<div class='connection'>
<form method="POST" action="sup_product.php">
Id :<input type="text" name='id'></br>
<input type="submit" name="submit" value="valider">
</form>
</div>
<file_sep>/day01/ex09/ft_is_sort.php
#!/usr/bin/php
<?php
function ft_is_sort($tab)
{
$str = $tab;
sort($tab);
if(implode(" ", $tab) == implode(" ", $str))
return TRUE;
return FALSE;
}
?>
<file_sep>/day04/ex05/speak.php
<?php
session_start();
if ($_SESSION["loggued_on_user"] != "")
{
if ($_POST["submit"] == "send")
{
if(file_exists("../private") == FALSE)
{
mkdir("../private", 0777, TRUE);
}
if(file_exists("../private/chat") == FALSE)
{
$tab = array(array("time" => time(),"login" => $_SESSION["loggued_on_user"], "msg" => $_POST["msg"]));
$serialised = serialize($tab);
file_put_contents("../private/chat", $serialised);
}
else
{
$file = fopen("../private/chat", "c+");
flock($file, LOCK_EX);
$content = unserialize(file_get_contents("../private/chat"));
$content[] = array("time" => time(),"login" => $_SESSION["loggued_on_user"], "msg" => $_POST["msg"]);
$serialised = serialize($content);
file_put_contents("../private/chat", $serialised);
fclose($file);
}
}
?>
<html>
<head>
<script langage="javascript">top.frames['chat'].location = 'chat.php';</script>
</head>
<body>
<form action="speak.php" method="POST">
<input type="text" name="msg" value="" />
<input type="submit" name="submit" value="send"/>
</form>
</body>
</html>
<?php
}
else
{
echo "ERROR\n";
}
?>
<file_sep>/rush00/srcs/admin/add_categorie.php
<?php
session_start();
$ok = 1;
if ((isset($_POST['categorie']) && $_POST['categorie'] != NULL) &&
(isset($_POST['submit']) && $_POST['submit'] === "valider"))
{
$content = unserialize(file_get_contents("../../private/categorie"));
foreach($content as $product=>$value)
{
if($value[0] = $_POST["categorie"])
{
$_SESSION['add_categorie'] = 0;
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
}
}
}
else
{
header("Location: categorie.php");
exit();
}
if ($ok == 1)
{
if (!array_search("Legume", $content[cat1]) && $_POST['categorie'] == "Legume")
{
$content[cat1][$_POST["categorie"]] = $_POST["categorie"];
$serialized = serialize($content);
file_put_contents("../../private/categorie", $serialized);
$_SESSION['add_categorie'] = 1;
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
exit();
}
if (!array_search("Fruit", $content[cat2]) && $_POST['categorie'] == "Fruit")
{
$content[cat2][$_POST["categorie"]] = $_POST["categorie"];
$serialized = serialize($content);
file_put_contents("../../private/categorie", $serialized);
$_SESSION['add_categorie'] = 1;
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
exit();
}
if (!array_search("Viande", $content[cat3]) && $_POST['categorie'] == "Viande")
{
$content[cat3][$_POST["categorie"]] = $_POST["categorie"];
$serialized = serialize($content);
file_put_contents("../../private/categorie", $serialized);
$_SESSION['add_categorie'] = 1;
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
exit();
}
if (!array_search("Produits laitier", $content[cat4]) && $_POST['categorie'] == "Produits laitier")
{
$content[cat4][$_POST["categorie"]] = $_POST["categorie"];
$serialized = serialize($content);
file_put_contents("../../private/categorie", $serialized);
$_SESSION['add_categorie'] = 1;
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
exit();
}
else
{
$content[cat5][$_POST["categorie"]]= $_POST["categorie"];
$serialized = serialize($content);
file_put_contents("../../private/categorie", $serialized);
$_SESSION['add_categorie'] = 1;
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
exit();
}
}
?>
<file_sep>/rush00/srcs/vide_panier.php
<?php
session_start();
unset($_SESSION['panier']);
include ("panier.php");
?>
<file_sep>/day01/ex09/aff_param.php
#!/usr/bin/php
<?php
$elem = count($argv);
$i = 1;
while ($i < $elem)
{
echo $argv[$i];
echo "\n";
$i++;
}
?>
<file_sep>/rush00/srcs/admin/admin.php
<?php
include ('header_admin.php');
echo "<div>";
echo "<ul>";
echo "<li><a class='admin-users1' href='add_user.php'>Ajouter un utilisateur</a></li></br>";
echo "<li><a class='admin-users1' href='modif_user.php'>Modifier un utilisateur</a></li></br>";
echo "<li><a class='admin-users1' href='sup_user.php'>Supprimer un utilisateur</a></li></br>";
echo "<li><a class='admin-users1' href='products.php'>Ajouter/Modifier/Supprimer un produit</a></li></br>";
echo "<li><a class='admin-users1' href='categories.php'>Ajouter/Modifer/Supprimer une categorie</a></li></br>";
echo "<li><a class='admin-users1' href='historique_commande.php'>Historique des commandes</a></li></br>";
echo "</ul>";
echo "</div>";
?>
<file_sep>/rush00/ancien/lait.php
<?php
include ('index.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Boutique</title>
<link rel="stylesheet" href="selection.css">
</head>
<body>
<div class="responsive">
<div class="gallery">
<img class="Lait" title="Lait" src="https://www.acupuncture-paysbasque.com/uploads/6/9/9/1/69918189/2213327-inline_orig.jpg" alt="image Lait" >
<div class="desc">Le lait est un liquide biologique comestible généralement de couleur blanchâtre produit par les glandes mammaires des mammifères femelles.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="responsive">
<div class="gallery">
<img class="fromage" title="fromage" src="http://resize3-doctissimo.ladmedia.fr/r/1010,,forcex/img/var/doctissimo/storage/images/fr/www/nutrition/diaporamas/fromages-moins-caloriques/3227540-1-fre-FR/Les-10-fromages-les-moins-caloriques.jpg" alt="image de fromage" >
<div class="desc">Le fromage est un aliment obtenu à partir de lait coagulé ou de produits laitiers, comme la crème, puis d'un égouttage suivi ou non de fermentation et éventuellement d'affinage.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="responsive">
<div class="gallery">
<img class="Yaourt" title="Yaourt" src="https://image.afcdn.com/recipe/20160628/44392_w420h344c1cx1424cy2144.jpg" alt="image de Yaourt" >
<div class="desc">Le yaourt, yahourt, yogourt ou yoghourt, est un lait fermenté par le développement des seules bactéries lactiques thermophiles Lactobacillus delbrueckii subsp.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="clearfix"></div>
</body>
</html>
<file_sep>/README.md
# Piscine-PHP
Piscine de préparation aux langages PHP/HTML/CSS/JS
<file_sep>/day05/ex01/ex01.sql
-- use db_wsabates
CREATE TABLE ft_table (
id INT NOT NULL AUTO_INCREMENT,
login VARCHAR(11) DEFAULT 'toto' NOT NULL,
groupe ENUM('staff', 'student', 'other') NOT NULL,
date_de_creation DATE NOT NULL,
PRIMARY KEY (id)
);
<file_sep>/rush00/srcs/admin/sup_user.php
<?php
session_start();
include ('header_admin.php');
$passwd = <PASSWORD>(sha512, $_POST["passwd"]);
$content = unserialize(file_get_contents("../../private/passwd"));
$i = 0;
foreach($content as $elem)
{
if ($elem["login"] == $_POST["login"] && $passwd == $elem["passwd"])
{
$content[$i]["login"] = "";
$_content[$i]["passwd"] = "";
unset($content[$i]);
$serialised = serialize($content);
file_put_contents("../../private/passwd", $serialised);
?>
<h1>Le compte a ete supprimer</h1>
<?php
}
$i++;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Suppimer un compte:</h1>
<div class="connection">
<form method="POST" action="sup_user.php">
Identifiant:<input type="text" name="login" value="" />
</br>
Mot de passe: <input type="<PASSWORD>" name="<PASSWORD>" value="" />
</br>
<input type="submit" name="submit" value="OK" />
</form>
</div>
</body>
</html>
<file_sep>/rush00/ancien/ancien_legume.php
<?php
include ('index.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Boutique</title>
<link rel="stylesheet" href="selection.css">
</head>
<body>
<div class="responsive">
<div class="gallery">
<img class="salade" title="salade" src="https://jardinage.lemonde.fr/images/dossiers/2017-07/batavia-153406.jpg" alt="image_salade" >
<div class="desc">La laitue, laitue cultivée ou salade est une plante herbacée appartenant au genre Lactuca, de la famille des Astéracées, largement cultivée pour ses feuilles tendres consommées comme légume, généralement crues en salade.
<?php echo "<a href='detail.php?produit=".$elem[0]."'>Voir les produits !</a>"; ?>
</div>
</div>
</div>
<div class="responsive">
<div class="gallery">
<img class="courgette" title="courgette" src="https://www.marshalls-seeds.co.uk/images/products/product_2323_large.jpg" alt="image_courgette" >
<div class="desc">La courgette est une plante herbacée de la famille des Cucurbitaceae, c'est aussi le fruit comestible de cette plante. La courgette est un légume courant en été, la fleur de courgette est aussi utilisée en cuisine.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="responsive">
<div class="gallery">
<img class="patate" title="patate" src="http://lavieagricole.ca/media/image_article/patates.jpg" alt="image_patate" >
<div class="desc">La pomme de terre, ou patate, est un tubercule comestible produit par l’espèce Solanum tuberosum, appartenant à la famille des solanacées.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="responsive">
<div class="gallery">
<img class="mais" title="mais" src="https://fr.cdn.v5.futura-sciences.com/buildsv6/images/largeoriginal/2/c/e/2ce0f12e9f_91255_mais.jpg" alt="image_mais" >
<div class="desc">Le maïs, appelé blé d’Inde au Canada, est une plante herbacée tropicale annuelle de la famille des Poacées, largement cultivée comme céréale pour ses grains riches en amidon, mais aussi comme plante fourragère.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="clearfix"></div>
</body>
</html>
<file_sep>/day01/ex09/epur_str.php
#!/usr/bin/php
<?php
if ($argc == 2)
{
$elem = trim($argv[1]);
// $tab = str_ireplace(" ", " ",$elem);
while (strstr($elem, " "))
{
$elem = str_ireplace(" ", " ", $elem);
}
echo $elem;
}
?>
<file_sep>/day04/ex02/create.php
<?php
if ($_POST["login"] != "" && $_POST["passwd"] != "" && $_POST["submit"] == "OK")
{
$passwd = hash(sha512,$_POST["passwd"]);
if (file_exists("../private") == FALSE)
{
mkdir ("../private", 0777, TRUE);
}
if (file_exists("../private/passwd") == FALSE)
{
$tab = array(array("login" => $_POST["login"], "passwd" => <PASSWORD>));
$serialised = serialize($tab);
file_put_contents("../private/passwd", $serialised);
echo "OK";
}
else
{
$content = FALSE;
$unserialised = unserialize(file_get_contents("../private/passwd"));
foreach($unserialised as $elem)
{
if($elem["login"] == $_POST["login"])
{
$content = TRUE;
}
}
if ($content == FALSE)
{
$unserialised[] = array("login" => $_POST["login"], "passwd" => <PASSWORD>);
$new_serialized = serialize($unserialised);
file_put_contents("../private/passwd", $new_serialized);
echo "OK";
}
else
{
echo "ERROR\n";
}
}
}
else
{
echo "ERROR\n";
}
?>
<file_sep>/rush00/srcs/admin/historique_commande.php
<?PHP session_start(); ?>
<?PHP include ("header_admin.php"); ?>
<!DOCTYPE html>
<html>
<body>
<h1> Dernier commande effectuées:</h1>
<h2>Commandes de <?php echo $_SESSION['old_loggued_on_user'] ?>:</h2>
<?PHP
if ($_POST['compte'] == "Acheter" || ((count($_SESSION['historique'])) != 0))
{
$unserialized = unserialize(file_get_contents("../../private/data"));
$_SESSION['nb_articles'] = count($_SESSION['historique']);
if ($_SESSION['nb_articles'] != 0)
{
$total = 0;
echo "<table class='recap_panier'>";
echo "<tr><th>Articles</th><th>Quantite</th><th>Prix</th><tr/>";
foreach ($_SESSION['historique'] as $elem)
{
$id = $elem - 1;
echo "<tr><td>".$unserialized[$id][1]."</td><td>1</td><td>".$unserialized[$id][5]."</td><tr/>";
$total += $unserialized[$id][5];
}
echo "<tr><td></td><td>Total</td><td>".$total."</td><tr/>";
echo "</table>";
$_SESSION['nb_articles'] = 0;
}
else
{
echo "<p>Votre panier est vide</p>";
}
}
else
{
echo"<p>Auncune commande</p>";
}
unset($_SESSION['panier']);
?>
</body>
</html>
<file_sep>/day01/ex09/oddeven.php
#!/usr/bin/php
<?php
while(42)
{
echo "Entrez un nombre: ";
$input = trim(fgets(STDIN));
if (feof(STDIN) == TRUE)
exit();
if (!is_numeric($input))
{
echo "'$input' n'est pas un chiffre\n";
}
else
{
echo "Le chiffre $input est ";
if (substr($input, - 1) % 2 == 0)
{
echo "Pair\n";
}
else {
echo "Impair\n";
}
}
}
?>
<file_sep>/day01/ex09/ssap.php
#!/usr/bin/php
<?php
function ft_split($s1)
{
$tab = explode (" ", $s1);
sort($tab);
return ($tab);
}
foreach ($argv as $elem)
{
if ($elem != $argv[0])
{
$tab = ft_split($elem);
}
}
sort($tab);
foreach ($tab as $ele)
{
echo $ele;
echo "\n";
}
?>
<file_sep>/rush00/srcs/selection.php
<?php
include ("header.php"); ?>
<!DOCTYPE html>
<html>
<body>
<?php
$data = unserialize(file_get_contents("../private/data"));
foreach ($data as $elem)
{
echo "<div class='responsive'>";
echo "<div class='aff_prod'>";
echo "<tr><td>".$elem[1]."</td></tr>";
echo "<tr><td><img src='".$elem[6]."'></td><tr/>";
echo "<tr><td><a class='voir_articles' href='detail.php?produit=".$elem[0]."'>Voir les ".$elem[1]."s !</a></td></tr>";
echo "</div>";
echo "</div>";
}
?>
</body>
</html>
<file_sep>/rush00/srcs/add_panier.php
<?php
session_start();
$_SESSION['nb_articles']++;
$_SESSION['panier'][] = $_GET['produit'];
echo "<meta http-equiv='refresh' content='0,url=panier.php'>";
?>
<file_sep>/rush00/srcs/get_data.php
<?php
$data = file("csv/database.csv");
unset($data[0]);
foreach($data as $elem)
{
$info = explode(",", $elem);
$tab_info[] = $info;
}
$serialised = serialize($tab_info);
file_put_contents("private/data", $serialised);
?>
<file_sep>/day02/ex03/who.php
#!/usr/bin/php
<?php
$user = get_current_user();
$user = $user . " ";
$file = file_get_contents("/var/run/utmpx");
$sub = substr($file, 1256);
$tab_data = 'a256user/a4id/a32line/ipid/itype/I2time/a256host/i16pad';
while($sub != NULL)
{
$array = unpack($tab_data, $sub);
$date = date("M j H:i", $array["time1"]);
$line = $array[line];
$line = $line . " ";
$tab = array($user, $line, $date);
$who = implode($tab);
echo "$who\n";
$sub = substr($sub, 628);
}
?>
<file_sep>/day03/ex03/cookie_crisp.php
<?php
if(isset($_GET["name"]) && isset($_GET["action"]))
{
if($_GET["action"] == "del")
{
setcookie($_GET["name"], NULL, -1);
}
if($_GET["action"] == "set")
{
setcookie($_GET["name"], $_GET["value"], time() + (1 * 1 * 1 * 60));
}
if($_GET["action"] == "get")
{
if(isset($_COOKIE[$_GET["name"]]))
{
echo $_COOKIE[$_GET["name"]];
echo "\n";
}
}
}
?>
<file_sep>/rush00/ancien/index_test.php
<?php
include ("install.php");
$data = unserialize(file_get_contents("../private/data"));
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Boutique</title>
<link rel="stylesheet" href="selection.css">
</head>
<body>
<nav>
<label for="menu-deroulant" class="menu-deroulant">Menu</label>
<input type="checkbox" id="menu-deroulant" role="button">
<ul>
<?php
$i=0;
foreach($data as $elem){
echo "<li class='home'><a href='selection.php'>".$data[1][2]."</a></li>";}?>
<li class="menu-legume"><a href="legume.php">Legume</a>
<ul class="sous-menu">
<li><a href="legume.php">Courgette</a></li>
<li><a href="legume.php">Salade</a></li>
<li><a href="legume.php">Pomme de terre</a></li>
<li><a href="legume.php">Maïs</a></li>
</ul></li>
<li class="menu-fruit"><a href="fruit.php">Fruit</a>
<ul class="sous-menu">
<li><a href="fruit.php">Banane</a></li>
<li><a href="fruit.php">Fraise</a></li>
<li><a href="fruit.php">Pomme</a></li>
<li><a href="fruit.php">Orange</a></li>
</ul></li>
<li class="menu-viande"><a href="viande.php">Viande</a>
<ul class="sous-menu">
<li><a href="viande.php">Boeuf</a></li>
<li><a href="viande.php">Poulet</a></li>
<li><a href="viande.php">Poisson</a></li>
</ul></li>
<li class="menu-lait"><a href="lait.php">Produit laitier</a>
<ul class="sous-menu">
<li><a href="lait.php">Lait</a></li>
<li><a href="lait.php">Fromage</a></li>
<li><a href="lait.php">Yaourt</a></li>
</ul></li>
<li class="compte"><a href="#">Compte</a>
<ul class="sous-menu">
<li><a href="login.php">Se connecter</a></li>
<li><a href="create.php">Cree un compte</a></li>
<li><a href="modif.php">Modifier son compte</a></li>
<li><a href="supprimer.php">Supprimer son compte</a></li>
<li><a href="logout.php">Deconnection</a></li>
</ul></li>
<li class="panier"><a href="panier.php">Panier</a>
<ul class="sous-menu">
<li><a href="#">Visualiser le panier</a></li>
<li><a href="#">passer la commande</a></li>
<li><a href="#">supprimer le panier</a></li>
</ul></li>
</ul>
</nav>
</body>
</html>
<file_sep>/rush00/srcs/admin/add_user.php
<?php
session_start();
include ('header_admin.php');
if($_SESSION['loggued_on_user'] == "admin")
{
if ($_POST["login"] != "" && $_POST["passwd"] != "" && $_POST["submit"] == "OK")
{
$passwd = hash(sha512,$_POST["passwd"]);
$content = FALSE;
$unserialised = unserialize(file_get_contents("../../private/passwd"));
foreach($unserialised as $elem)
{
if($elem["login"] == $_POST["login"])
{
$content = TRUE;
}
}
if ($content == FALSE)
{
$unserialised[] = array("login" => $_POST["login"], "passwd" => $passwd);
$new_serialized = serialize($unserialised);
file_put_contents("../../private/passwd", $new_serialized);
?>
<h1>L'utilisateur ete ajouté</h1>
<?php
}
else
{
?>
<h1>Le compte existe deja</h1>
<?php
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Ajouter un utilisateur:</h1>
<div class="connection">
<form method="POST" action="add_user.php">
Identifiant: <input type="text" name="login" value="">
</br>
Mot de passe: <input type="<PASSWORD>" name="passwd" value="">
</br>
<input type="submit" name="submit" value="OK">
</form>
</div>
</body>
</html>
<file_sep>/rush00/srcs/panier.php
<?php
session_start();
include ("header.php");
?>
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<body>
<?PHP
$data = "../private/data";
$content = unserialize(file_get_contents($data));
$_SESSION['nb_articles'] = count($_SESSION['panier']);
if ($_SESSION['nb_articles'] != 0)
{
$total = 0;
echo "<table class='recap_panier'>";
echo "<tr><th>Articles: </th><th>Quantite: </th><th>Prix: </th><tr/>";
foreach ($_SESSION['panier'] as $elem)
{
$id = $elem - 1;
echo "<tr><td>".$content[$id][1].":</td><td>1</td><td>".$content[$id][5]."</td><tr/>";
$total += $content[$id][5];
}
echo "<tr><td></td><td>Total:</td><td>".$total."€</td><tr/>";
echo "</table>";
if ($_SESSION['loggued_on_user'] != "")
{
$_SESSION['historique'] = $_SESSION['panier'];
// unset($_SESSION['panier']);
$_SESSION['nb_articles'] = 0;
echo "<form action='commande.php' method='post'>";
echo "<input type='submit' name='compte' value='Acheter' />";
echo "</form>";
}
else if ($_SESSION['loggued_on_user'] == "")
{
echo "<form action='connection/login.php' method='post'>";
echo "<input type='submit' name='pas-compte' value='Vous êtes pas connecté' />";
echo "</form>";
}
?>
<a class='admin-users' href="vide_panier.php">Vider le panier </a>
</body>
</html>
<?php
}
else
{
echo "<h1>Votre panier est vide</h1>";
}
?>
<file_sep>/rush00/ancien/viande.php
<?php
include ('index.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Boutique</title>
<link rel="stylesheet" href="selection.css">
</head>
<body>
<div class="responsive">
<div class="gallery">
<img class="Boeuf" title="Boeuf" src="https://docteurbonnebouffe.com/wp-content/uploads/2014/06/viande-rouge-bienfaits-et-risques-pour-la-sant%C3%A9-660x400.jpg" alt="image_viande de boeuf" >
<div class="desc">La viande bovine est la viande issue des animaux de l'espèce Bos taurus, qu'il s'agisse de vache, taureau, veau, broutard, taurillon, génisse ou bœuf.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="responsive">
<div class="gallery">
<img class="poulet" title="poulet" src="http://www.canalvie.com/polopoly_fs/1.780710.1344275961!/image/1947_le_poulet_viande_blanche_ou_viande_brune_670.jpg_gen/derivatives/cvlandscape_670_377/1947_le_poulet_viande_blanche_ou_viande_brune_670.jpg" alt="image de viande poulet" >
<div class="desc">Un poulet est une jeune volaille, mâle ou femelle, de la sous-espèce Gallus gallus domesticus, élevée pour sa chair. Un petit poulet mâle est un coquelet, un poulet femelle est une poulette.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="responsive">
<div class="gallery">
<img class="poisson" title="poisson" src="https://t2.uc.ltmcdn.com/fr/images/8/8/9/img_comment_cuire_du_poisson_a_la_vapeur_11988_600.jpg" alt="image de viande de poisson" >
<div class="desc">Les poissons sont des animaux vertébrés aquatiques à branchies, pourvus de nageoires et dont le corps est le plus souvent couvert d'écailles.
<form method="POST" action="panier.php">
<input type="submit" name="add" value="Ajouter au Panier">
</form>
</div>
</div>
</div>
<div class="clearfix"></div>
</body>
</html>
<file_sep>/rush00/ancien/legume.php
<?php
include ("index.php"); ?>
<!DOCTYPE html>
<html>
<body>
<?php
$data = unserialize(file_get_contents("../private/data"));
$i=0;
$j=0;
echo "<table id='boutique'>";
foreach ($data as $elem)
{
while($data[$j++][2] == "Legume")
{
echo "<tr><td class='type'>".$data[$i][1]."</td></tr>";
echo "<tr><td><img src='".$data[$i][6]."'/ style='width:20%;'></td><tr/>";
echo "<tr><td class='acheter_articles'><a href='detail.php?produit=".$data[$i][0]."'>Voir les produits !</a></td></tr>";
$i++;
}
}
echo "</table>";
?>
</body>
</html>
<file_sep>/rush00/install.php
<?php
session_start();
$_SESSION['acheter'] = "";
if(!file_exists("private/passwd"))
{
mkdir("private", 0777, TRUE);
$tab_count = array(array("login" => "admin", "passwd" => hash(sha512, "<PASSWORD>")));
$serialised_count = serialize($tab_count);
file_put_contents("private/passwd", $serialised_count);
}
if(!file_exists("private/categorie"))
{
$tab_cat[cat1]["Legume"] = "Legume";
$tab_cat[cat2]["Fruit"] = "Fruit";
$tab_cat[cat3]["Viande"] = "Viande";
$tab_cat[cat4]["Produits laitier"] = "Produits laitier";
$serialised_cat = serialize($tab_cat);
file_put_contents("private/categorie", $serialised_cat);
$unserialised = unserialize(file_get_contents("private/categorie"));
}
include ('srcs/get_data.php');
?>
<file_sep>/day01/ex09/ft_plit.php
#!/usr/bin/php
<?php
function ft_split($s1)
{
$tab = explode (" ", $s1);
if ($s1 != NULL)
{
sort ($tab);
}
return ($tab);
}
print_r(ft_split("Hello World AAA"));
?>
<file_sep>/day02/ex01/one_more_time.php
#!/usr/bin/php
<?php
if ($argc < 3)
{
if(preg_match("/([L|l]undi|[M|m]ardi|[M|m]ercredi|[J|j]eudi|[V|v]endredi|[S|s]amdi|[D|d]imam\nche)/", $argv[1]))
{
$time = preg_replace("/([L|l]undi |[M|m]ardi |[M|m]ercredi |[J|j]eudi |[V|v]endredi |[S|s]amdi |[D|d]imanche )/","", $argv[1]);
}
else {
echo "Wrong Format";
return;
}
if(preg_match("/([J|j]anvier|[F|f]evrier|[M|m]ars|[A|a]vril|[M|m]ai|[J|j]uin|[J|j]uillet|[A|a]o[u|û]t|[S|s]eptembre|[O|o]ctobre|[N|n]ovembre|[D|d]ecembre)/", $argv[1]))
{
$time = explode(" ", $time);
$len_year = strlen($time[2]);
$len_day_num = strlen($time[0]);
$len_time = strlen($time[3]);
if ($len_year != 4 || !preg_match("#[1-9]#", $time[2]))
{
echo "Wrong Format";
return;
}
if ($len_day_num > 2)
{
echo "Wrong Format";
return;
}
if ($len_time != 8)
{
echo "Wrong Format";
return;
}
if ($time[1] == "janvier" || $time[1] == "Janvier")
$time[1] = " January ";
if ($time[1] == "fevrier " || $time[1] == "Fevrier")
$time[1] = " February ";
if ($time[1] == "avril" || $time[1] == "Avril")
$time[1] = " April ";
if ($time[1] == "mai" || $time[1] == "Mai")
$time[1] = " May ";
if ($time[1] == "juin" || $time[1] == "Juin")
$time[1] = " June ";
if ($time[1] == "juillet" || $time[1] == "Juillet")
$time[1] = " July ";
if ($time[1] == "aout" || $time[1] == "Aout" || $time[1] == "août" || $time[1] == "Août")
$time[1] = " August ";
if ($time[1] == "septembre" || $time[1] == "Septembre")
$time[1] = " September ";
if ($time[1] == "octobre" || $time[1] == "Octobre")
$time[1] = " October ";
if ($time[1] == "novembre" || $time[1] == "Novembre")
$time[1] = " November ";
if ($time[1] == "decembre" || $time[1] == "Decembre")
$time[1] = " December ";
$time = implode($time);
}
else
{
echo "Wrong Format";
return;
}
$date = strtotime($time);
$date = $date - 3600;
echo $date;
}
else
echo "Wrong number of parameters";
?>
<file_sep>/rush00/srcs/admin/supp_categorie.php
<?PHP
session_start();
if ((isset($_POST['categorie']) && $_POST['categorie'] != NULL)&&
(isset($_POST['submit']) && $_POST['submit'] === "valider"))
{
$ok = 0;
$content = unserialize(file_get_contents("../../private/categorie"));
if (array_search($_POST['categorie'], $content[cat1]))
{
$return = array_search($_POST['categorie'], $content[cat1]);
unset($content[cat1][$return]);
$content[cat1] = array_values($content[cat1]);
$ok = 1;
}
elseif (array_search($_POST['categorie'], $content[cat2]))
{
$return = array_search($_POST['categorie'], $content[cat2]);
unset($content[cat2][$return]);
$content[cat2] = array_values($content[cat2]);
$ok = 1;
}
elseif (array_search($_POST['categorie'], $content[cat3]))
{
$return = array_search($_POST['categorie'], $content[cat3]);
unset($content[cat3][$return]);
$content[cat3] = array_values($content[cat3]);
$ok = 1;
}
elseif (array_search($_POST['categorie'], $content[cat4]))
{
$return = array_search($_POST['categorie'], $content[cat4]);
unset($content[cat4][$return]);
$content[cat4] = array_values($content[cat4]);
$ok = 1;
}
elseif (array_search($_POST['categorie'], $content[cat5]))
{
$return = array_search($_POST['categorie'], $content[cat5]);
unset($content[cat5][$return]);
$content[cat5] = array_values($content[cat5]);
$ok = 1;
}
}
else
{
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
exit();
}
echo $ok;
if ($ok == 0)
{
$_SESSION['supp_cat'] = 0;
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
exit();
}
else if ($ok == 1)
{
$serialized = serialize($content);
file_put_contents("../../private/categorie", $serialized);
$_SESSION['supp_cat'] = 1;
echo "<meta http-equiv='refresh' content='0,url=categories.php'>";
exit();
}
?>
<file_sep>/day01/ex10/do_op.php
#!/usr/bin/php
<?php
if ($argc == 4)
{
$chiffre1 = trim ($argv[1]);
$operateur = trim ($argv[2]);
$chiffre3 = trim ($argv[3]);
if ($operateur == "+")
{
echo $chiffre1 + $chiffre3;
}
if ($operateur == "-")
{
echo $chiffre1 - $chiffre3;
}
if ($operateur == "/")
{
echo $chiffre1 / $chiffre3;
}
if ($operateur == "*")
{
echo $chiffre1 * $chiffre3;
}
if ($operateur == "%")
{
echo $chiffre1 % $chiffre3;
}
}
else
echo "tu fais n'importe quoi";
?>
<file_sep>/rush00/srcs/connection/create.php
<?php
session_start();
include ('header_connection.php');
if($_SESSION['loggued_on_user'] == "" || $_SESSION['loggued_on_user'] == "admin")
{
if ($_POST["login"] != "" && $_POST["passwd"] != "" && $_POST["submit"] == "OK")
{
$passwd = <PASSWORD>(sha512,$_POST["passwd"]);
// if (file_exists("../../private") == FALSE)
// {
// mkdir ("../../private", 0777, TRUE);
// }
// if (file_exists("../../private/passwd") == FALSE)
// {
// $tab = array(array("login" => $_POST["login"], "passwd" => <PASSWORD>));
// $serialised = serialize($tab);
// file_put_contents("../../private/passwd", $serialised);
// echo "Votre compte a ete cree";
// }
// else
// {
$content = FALSE;
$unserialised = unserialize(file_get_contents("../../private/passwd"));
foreach($unserialised as $elem)
{
if($elem["login"] == $_POST["login"] || $_POST["login"] == "admin")
{
$content = TRUE;
}
}
if ($content == FALSE)
{
$unserialised[] = array("login" => $_POST["login"], "passwd" => <PASSWORD>);
$new_serialized = serialize($unserialised);
file_put_contents("../../private/passwd", $new_serialized);
?>
<h1>Votre compte a ete cree</h1>
<?php
}
else
{
echo "Votre compte existe deja\n";
}
// }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Créer un compte:</h1>
<div class="connection">
<form method="POST" action="create.php">
Identifiant: <input type="text" name="login" value="">
</br>
Mot de passe: <input type="<PASSWORD>" name="passwd" value="">
</br>
<input type="submit" name="submit" value="OK">
</form>
</div>
</body>
</html>
<?php
}
else
{
?>
<h1>Votre compte existe deja, vous etes actuellement connecter. Veilliez vous deconnecter pour créer un nouveau compte</h1>
<?php
}
?>
<file_sep>/rush00/srcs/admin/modif_product.php
<?php
session_start();
function get_data($content)
{
$i=0;
if((isset($_POST['id']) && $_POST['id'] != NULL) &&
(isset($_POST['type']) && $_POST['type'] != NULL) &&
(isset($_POST['categorie']) && $_POST['categorie'] != NULL) &&
($_POST['categorie'] == "Fruit" || $_POST['categorie'] == "Legume" ||
$_POST['categorie'] == 'Viande' || $_POST['categorie'] == "Produits laitier") &&
(isset($_POST['quantite']) && $_POST['quantite'] != NULL) &&
(isset($_POST['poids']) && $_POST['poids'] != NULL) &&
(isset($_POST['prix']) && $_POST['prix'] != NULL) &&
(isset($_POST['image']) && $_POST['image'] != NULL) &&
(isset($_POST['submit']) && $_POST['submit'] == "valider") &&
$_POST['categorie'] == $content[$i++][2])
{
$tab[0] = $_POST['id'];
$tab[1] = $_POST['type'];
$tab[2] = $_POST['categorie'];
$tab[3] = $_POST['quantite'];
$tab[4] = $_POST['poids'];
$tab[5] = $_POST['prix'];
$tab[6] = $_POST['image'];
}
else
{
$_SESSION["modifier"] = 0;
header('Location: products.php');
exit();
}
return($tab);
}
$id = FAlSE;
$content = unserialize(file_get_contents("../../private/data"));
$data = get_data($content);
foreach($content as $key=>$elem)
{
if($data[0] == $elem[0])
{
$id = TRUE;
$content[$key][1] = $data[1];
$content[$key][2] = $data[2];
$content[$key][3] = $data[3];
$content[$key][4] = $data[4];
$content[$key][5] = $data[5];
$content[$key][6] = $data[6];
}
}
if ($id == FALSE)
{
$_SESSION['modifier'] = 0;
echo "<meta http-equiv='refresh' content='0,url=admin-products.php'>";
}
$serialized = serialize($content);
file_put_contents("../../private/data", $serialized);
$_SESSION["modifier"] = 1;
echo "<meta http-equiv='refresh' content='0,url=products.php'>";
exit();
?>
<file_sep>/day02/ex04/photo.php
#!/usr/bin/php
<?php
$curl_init = curl_init($argv[1]);
$curl_ex = curl_exec($curl_init);
$file = file_get_contents($argv[1]);
echo $file;
?>
<file_sep>/rush00/srcs/connection/connection.php
<?php
include ('header_connection.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Connection</title>
</head>
<body>
<h1>Connection:</h1>
<div class="connection">
<form method="POST" action="login.php">
Identifiant:<input type="text" name="login" value="" />
</br>
Mot de passe: <input type="text" name="passwd" value="" />
</br>
<input type="submit" name="submit" value="OK" />
</form>
</div>
</body>
</html>
<file_sep>/day04/ex05/chat.php
<?php
date_default_timezone_set('Europe/Paris');
if (file_exists("../private/chat") == TRUE)
{
$content = unserialize(file_get_contents("../private/chat"));
foreach ($content as $elem)
{
$time = date("H:i",$elem["time"]);
echo "[";
echo $time;
echo "]";
echo $elem["login"];
echo ": ";
echo $elem["msg"];
echo "</br>";
}
}
?>
<file_sep>/rush00/srcs/Articles_precis.php
<?php
include ("header.php"); ?>
<!DOCTYPE html>
<html>
<body>
<?php
$data = unserialize(file_get_contents("../private/data"));
$j=0;
echo "<table id='boutique'>";
echo "<tr><td class='id'>".$data[$_GET[id]][1]."</td></tr>";
echo "<tr><td><img src='".$data[$_GET[id]][6]."'/ style='width:50%;'></td><tr/>";
echo "<tr><td class='acheter_articles'><a href='detail.php?produit=".$data[$_GET[id]][0]."'>Voir les produits !</a></td></tr>";
$_GET[id]++;
echo "</table>";
?>
</body>
</html>
<file_sep>/day01/ex08/test.php
#!/usr/bin/php
<?php
include ("ft_is_sort.php");
$tab = array("aaa", "bb", "c", "d", "e");
// $tab[] = "ET qu'est-ce qu'on fait maintenant ?";
if (ft_is_sort($tab))
echo "Le tableau est trie\n";
else
echo "Le tableau n'est pas trie\n";
?>
<file_sep>/rush00/srcs/connection/logout.php
<?php
session_start();
include ('header_connection.php');
if ($_SESSION["loggued_on_user"] != "")
{
$_SESSION["loggued_on_user"] = "";
$_SESSION["loggued_on_passwd"] = "";
?><html>
<head>
<meta charset="UTF-8">
<title>boutique</title>
</head>
<body>
<h1>Vous etes deconnecté</h1>
</body>
</html><?php
}
else
{
?><html><body><h1>Vous n'êtes pas connecté</h1></body></html><?php
}
?>
<file_sep>/day02/ex02/loupe.php
#!/usr/bin/php
<?php
$file_content = file_get_contents($argv[1]);
$delimiteur = explode("title", $file_content);
print_r($delimiteur);
?>
<file_sep>/rush00/srcs/connection/login.php
<?php
session_start();
include ('header_connection.php');
include ('auth.php');
$i = 0;
$passwd = hash(sha512, $_POST['passwd']);
if ($_SESSION['loggued_on_user'] != "")
{
?><h1>Vous etes connecté</h1><?php
}
else
{
?><h1>Connection:</h1>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Connection</title>
</head>
<body>
<div class="connection">
<form method="POST" action="login.php">
Identifiant:<input type="text" name="login" value="" />
</br>
Mot de passe: <input type="<PASSWORD>" name="passwd" value="" />
</br>
<input type="submit" name="submit" value="OK" />
</form>
</div>
</body>
</html><?php
}
if (auth($_POST["login"], $_POST["passwd"]) == TRUE && $_SESSION['loggued_on_user'] == "")
{
$_SESSION['loggued_on_user'] = $_POST['login'];
$_SESSION['loggued_on_passwd'] = $passwd;
?>
<html>
<head>
<meta charset="UTF-8">
<title>boutique</title>
</head>
<body>
<h1>Vous etes connecté</h1>
</body>
</html>
<?php
echo "<meta http-equiv='refresh' content='0,url=login.php'>";
}
if(auth($_POST["login"], $_POST["passwd"]) == FALSE && $_POST["submit"] == "OK")
{
$_SESSION["loggued_on_user"] = "";
?>
<h2>- Identifiant ou Mot de passe incorrecte.</h2>
<h2>- Il faut crée un compte pour se connecter.</h2>
<h2>- Il faut vous deconnecter avant de changer de compte.</h2>
<?php
}
?>
|
e1619bb6fbbe0498b2008186c29191f65e31b0fe
|
[
"Markdown",
"SQL",
"PHP"
] | 60 |
SQL
|
williamsbs/Piscine-PHP
|
8d11387351fde064bc49af6c59317bc29f384745
|
1a9da8c0098338942d4015f2e7dbe9685ca28d45
|
refs/heads/main
|
<file_sep>Blogr landing page challenge from https://www.frontendmentor.io (https://www.frontendmentor.io/challenges/blogr-landing-page-EX2RLAApP/hub/blogr-landing-page-7wdxNKjAc)
Live page - https://bloggrs.netlify.app
<file_sep>const menu = document.querySelector(".menu-icons");
const menuImgs = document.querySelectorAll(".menu-icons img");
const mobileMenu = document.querySelector(".nav-links");
const subMenu = document.getElementById("connect");
const subMenuLinks = document.querySelector(".sub-menu");
function toggleMenu(x, y) {
x.forEach((img) => {
img.classList.toggle("hide");
});
y.classList.toggle("hide");
}
menu.addEventListener("click", () => {
toggleMenu(menuImgs, mobileMenu);
});
subMenu.addEventListener("click", () => {
subMenuLinks.classList.toggle("hide");
if (subMenu.classList.contains("fa-angle-down")) {
subMenu.classList.remove("fa-angle-down");
subMenu.classList.add("fa-angle-up");
} else {
subMenu.classList.remove("fa-angle-up");
subMenu.classList.add("fa-angle-down");
}
});
const hero = document.querySelector(".hero");
const nav = document.querySelector("header");
const appearOptions = {
threshold: 0.3,
rootMargin: "0px 0px 0px 0px",
};
const appearOnScroll = new IntersectionObserver(function (
entries,
appearOnScroll
) {
entries.forEach((entry) => {
if (!entry.isIntersecting) {
nav.classList.add("nav-scrolled");
} else {
nav.classList.remove("nav-scrolled");
}
});
},
appearOptions);
appearOnScroll.observe(hero);
|
7f71793fda0d2efc3f7e77ea5a68d7e32185445a
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
valy-s/blogr-landing-page
|
3c3d97af7cdcfd5c95d89f92699e50c277dafb1c
|
22c5dd11f1081b224d745ab6ffe3b6a7f7ae1a7f
|
refs/heads/master
|
<file_sep>export function render(el, Component) {}
|
f4e5b71b1cdc8ccd75f7fc604bb3f802bab40d23
|
[
"JavaScript"
] | 1 |
JavaScript
|
Myagi/my-react-starter
|
f1a08fec6f1e7dcf55f211161517522bac9f90b6
|
5756832f4481ea9a87060ab97e06d76e36683edb
|
refs/heads/master
|
<repo_name>Gabriel-Giovani/barber-app<file_sep>/src/stacks/MainStack.js
import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import Preload from '../screens/Preload';
import Login from '../screens/Login';
import Register from '../screens/Register';
import MainTab from './MainTab';
import BarberScreen from '../screens/Barber';
const Stack = createStackNavigator();
const { Navigator } = Stack;
export default () => (
<Navigator
screenOptions={{
initRouteName: 'Preload',
headerShown: false
}}
>
<Stack.Screen name='Preload' component={Preload} />
<Stack.Screen name='Login' component={Login} />
<Stack.Screen name='Register' component={Register} />
<Stack.Screen name='MainTab' component={MainTab} />
<Stack.Screen name='Barber' component={BarberScreen} />
</Navigator>
);<file_sep>/src/screens/Search/styles.js
import React from 'react';
import styled from 'styled-components/native';
export const Container = styled.SafeAreaView`
flex: 1;
background-color: #331A1A;
`;
export const SearchArea = styled.View`
background-color: #FFF;
height: 40px;
border-radius: 30px;
flex-direction: row;
align-items: center;
padding-left: 20px;
padding-right: 20px;
margin: 10px 10px 10px 30px;
`;
export const SearchInput = styled.TextInput`
flex: 1;
font-size: 16px;
color: #999;
`;
export const BackButton = styled.TouchableOpacity`
position: absolute;
left: 0;
top: 27px;
z-index: 9;
`;<file_sep>/src/screens/Favorites/index.js
import React, { useState } from 'react';
import { Container, BackButton, Header, HeaderText } from './styles';
import { ListArea, LoadingIcon, Scroller } from '../Home/styles';
import { useNavigation } from '@react-navigation/native';
import { RefreshControl } from 'react-native';
import BackIcon from '../../assets/back.svg';
import BarberCard from '../../components/BarberCard';
const barberAvatar = require('../../assets/barber-shop-logo.png');
export default() => {
const navigation = useNavigation();
const [isLoading, setIsLoading] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const handleBackButtonClick = () => {
navigation.goBack();
};
const handleRefresh = () => {
setIsRefreshing(false);
};
return(
<Container>
<Scroller
refreshControl={
<RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} />
}
>
<Header>
<HeaderText>Favoritos</HeaderText>
</Header>
{
isLoading && <LoadingIcon size='large' color='#FFF' />
}
<ListArea>
<BarberCard
key={1}
data={{
id: 1,
avatar: barberAvatar,
name: '<NAME>',
stars: 4
}}
/>
<BarberCard
key={2}
data={{
id: 2,
avatar: barberAvatar,
name: '<NAME>',
stars: 4.5
}}
/>
<BarberCard
key={3}
data={{
id: 3,
avatar: barberAvatar,
name: '<NAME>',
stars: 4
}}
/>
<BarberCard
key={4}
data={{
id: 4,
avatar: barberAvatar,
name: '<NAME>',
stars: 5
}}
/>
<BarberCard
key={5}
data={{
id: 5,
avatar: barberAvatar,
name: '<NAME>',
stars: 4.5
}}
/>
<BarberCard
key={6}
data={{
id: 6,
avatar: barberAvatar,
name: '<NAME>',
stars: 3.5
}}
/>
</ListArea>
</Scroller>
<BackButton onPress={handleBackButtonClick}>
<BackIcon width='44' height='44' fill='#FFF' />
</BackButton>
</Container>
);
}<file_sep>/src/screens/Profile/index.js
import React, { useState } from 'react';
import {
Container,
BackButton,
UserInfo,
WelcomeUserText,
WelcomeText,
UserNameText,
UserAvatar,
UserPhoto,
LogoutButton,
LogoutButtonText,
ProfileMenu
} from './styles';
import { useNavigation } from '@react-navigation/native';
import BackIcon from '../../assets/back.svg';
import { RefreshControl } from 'react-native';
import { Scroller, LoadingIcon } from '../Home/styles';
import NavPrevIcon from '../../assets/nav_prev.svg';
import NavNextIcon from '../../assets/nav_next.svg';
import Swiper from 'react-native-swiper';
import BarberCard from '../../components/BarberCard';
import MenuItemCard from '../../components/MenuItemCard';
const chatIcon = require('../../assets/chat.png');
const notificationIcon = require('../../assets/notification.png');
const walletIcon = require('../../assets/wallet.png');
const couponIcon = require('../../assets/coupons.png');
const favoriteIcon = require('../../assets/heart.png');
const cardIcon = require('../../assets/credit-card.png');
const dataIcon = require('../../assets/data-people.png');
export default() => {
const navigation = useNavigation();
const [isRefreshing, setIsRefreshing] = useState(false);
const handleRefresh = () => {
setIsRefreshing(false);
};
const handleLogoutClick = async() => {
navigation.reset({
routes: [{ name: 'Login' }]
});
};
return(
<Container>
<Scroller
refreshControl={
<RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} />
}
>
<UserInfo>
<WelcomeUserText>
<WelcomeText>Olá,</WelcomeText>
<UserNameText><NAME></UserNameText>
</WelcomeUserText>
<UserAvatar>
<UserPhoto source={require('../../assets/user.png')} />
</UserAvatar>
</UserInfo>
<ProfileMenu>
<MenuItemCard
icon={chatIcon}
title={'Chats'}
subtitle={'Minhas conversas'}
qtdNotifications={'3'}
/>
<MenuItemCard
icon={notificationIcon}
title={'Notificações'}
subtitle={'Minha central de notificações'}
qtdNotifications={'2'}
/>
<MenuItemCard
icon={chatIcon}
title={'Carteira'}
subtitle={'Meu saldo e QR code'}
/>
<MenuItemCard
icon={couponIcon}
title={'Cupons'}
subtitle={'Meus cupons de desconto'}
qtdNotifications={'1'}
/>
<MenuItemCard
icon={favoriteIcon}
title={'Favoritos'}
subtitle={'Meus barbeiros favoritos'}
/>
<MenuItemCard
icon={cardIcon}
title={'Formas de pagamento'}
subtitle={'Minhas formas de pagamento'}
/>
<MenuItemCard
icon={dataIcon}
title={'Dados pessoais'}
subtitle={'Minhas informações da conta'}
/>
</ProfileMenu>
<LogoutButton onPress={handleLogoutClick}>
<LogoutButtonText>SAIR</LogoutButtonText>
</LogoutButton>
</Scroller>
</Container>
);
}<file_sep>/src/components/StarsNote/index.js
import React from 'react';
import { StarsArea, StarView, StarText } from './styles';
import FullStar from '../../assets/star.svg';
import HalfStar from '../../assets/star_half.svg';
import EmptyStar from '../../assets/star_empty.svg';
export default ({stars, showNumber}) => {
// The star will have the following values:
// 0 = Empty
// 1 = Half
// 2 = Full
let starsValues = [0, 0, 0, 0, 0];
let floor = Math.floor(stars);
let left = stars - floor;
let i: number;
for(i = 0; i < floor; i++){
starsValues[i] = 2;
}
if(left > 0)
starsValues[i] = 1;
const defineIconNote = (value) => {
switch(value){
case 0:
return <EmptyStar width='18' height='18' fill='#FF9200' />
case 1:
return <HalfStar width='18' height='18' fill='#FF9200' />
case 2:
return <FullStar width='18' height='18' fill='#FF9200' />
}
};
return(
<StarsArea>
{
starsValues.map((star, index) => (
<StarView key={index}>
{ defineIconNote(star) }
</StarView>
))
}
{ showNumber && <StarText>{ stars }</StarText> }
</StarsArea>
);
}<file_sep>/src/screens/Appointments/index.js
import React, { useState } from 'react';
import {
Container,
ListArea,
AppointmentAgain,
AppointmentAgainTitle,
AppointmentAgainText,
AppointmentAgainBarberAvatar,
AppointmentDetails,
AppointmentDetailsText,
AppointmentAgainButton,
AppointmentAgainButtonText,
ListTitle
} from './styles';
import { Scroller, LoadingIcon } from '../Home/styles';
import { Header, HeaderText, BackButton } from '../Favorites/styles';
import BackIcon from '../../assets/back.svg';
import { RefreshControl } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import AppointmentCard from '../../components/AppointmentCard';
import Swiper from 'react-native-swiper';
import BarberCard from '../../components/BarberCard';
import { Favorites, FavoritesTitle } from '../Profile/styles';
const barberAvatar = require('../../assets/barber-shop-logo.png');
export default() => {
const navigation = useNavigation();
const [isRefreshing, setIsRefreshing] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const handleRefresh = () => {
setIsRefreshing(false);
};
const handleBackButtonClick = () => {
navigation.goBack();
};
return(
<Container>
<Scroller
refreshControl={
<RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} />
}
>
<Header>
<HeaderText>Agendamentos</HeaderText>
</Header>
<AppointmentAgain>
<AppointmentAgainTitle>
<AppointmentAgainText>Agende de novo</AppointmentAgainText>
<AppointmentAgainBarberAvatar source={require('../../assets/barber-shop-logo.png')} />
</AppointmentAgainTitle>
<AppointmentDetails>
<AppointmentDetailsText>Corte masculino</AppointmentDetailsText>
<AppointmentDetailsText>R$ 29,90</AppointmentDetailsText>
</AppointmentDetails>
<AppointmentAgainButton>
<AppointmentAgainButtonText>Agendar novamente</AppointmentAgainButtonText>
</AppointmentAgainButton>
</AppointmentAgain>
<Favorites>
<FavoritesTitle>Mais agendados por você</FavoritesTitle>
<Swiper
style={{height: 120}}
showsPagination={false}
autoplay
>
<BarberCard
key={1}
data={{
id: 1,
avatar: barberAvatar,
name: '<NAME>',
stars: 4
}}
/>
<BarberCard
key={2}
data={{
id: 2,
avatar: barberAvatar,
name: '<NAME>',
stars: 4.5
}}
/>
<BarberCard
key={3}
data={{
id: 3,
avatar: barberAvatar,
name: '<NAME>',
stars: 4
}}
/>
<BarberCard
key={4}
data={{
id: 4,
avatar: barberAvatar,
name: '<NAME>',
stars: 5
}}
/>
<BarberCard
key={5}
data={{
id: 5,
avatar: barberAvatar,
name: '<NAME>',
stars: 4.5
}}
/>
<BarberCard
key={6}
data={{
id: 6,
avatar: barberAvatar,
name: '<NAME>',
stars: 3.5
}}
/>
</Swiper>
</Favorites>
{
isLoading && <LoadingIcon size='large' color='#FFF' />
}
<ListArea>
<ListTitle>Histórico</ListTitle>
<AppointmentCard
cancelable
appointment={{
barberName: '<NAME>',
serviceName: 'Corte masculino',
servicePrice: '29,90',
serviceDate: '30/08/2021',
serviceHour: '13:00'
}}
/>
<AppointmentCard
cancelable={false}
appointment={{
barberName: '<NAME>',
serviceName: 'Sobrancelha',
servicePrice: '15,00',
serviceDate: '10/07/2021',
serviceHour: '18:00'
}}
/>
<AppointmentCard
cancelable={false}
appointment={{
barberName: '<NAME>',
serviceName: 'Corte masculino',
servicePrice: '29,90',
serviceDate: '30/06/2021',
serviceHour: '12:00'
}}
/>
</ListArea>
</Scroller>
<BackButton onPress={handleBackButtonClick}>
<BackIcon width='44' height='44' fill='#FFF' />
</BackButton>
</Container>
);
}<file_sep>/src/screens/Login/index.js
import React, { useState, useContext } from 'react';
import { Container, InputArea, CustomButton, CustomButtonText, RegisterMessageButton, RegisterMessageButtonText, RegisterMessageButtonTextBold } from './styles';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-community/async-storage';
import { UserContext } from '../../contexts/UserContext';
import BarberLogo from '../../assets/barber.svg';
import LoginInput from '../../components/LoginInput';
import EmailIcon from '../../assets/email.svg';
import LockIcon from '../../assets/lock.svg';
export default () => {
const { dispatch: userDispatch } = useContext(UserContext);
const navigation = useNavigation();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleMessageButtonClick = () => {
navigation.reset({
routes: [{ name: 'Register' }]
});
};
const handleLoginButtonCLick = async() => {
if(email !== '' && password !== ''){
if(email === '<EMAIL>' && password === '<PASSWORD>'){
await AsyncStorage.setItem('token', '123');
navigation.reset({
routes:[{name: 'MainTab'}]
});
} else
alert('E-mail e/ou senha incorreto(s)!');
} else
alert('Preencha os campos!');
};
return (
<Container>
<BarberLogo
width='100%'
height='160'
/>
<InputArea>
<LoginInput
Icon={EmailIcon}
placeholder='Digite seu email'
value={email}
onChangeText={(text) => setEmail(text)}
/>
<LoginInput
Icon={LockIcon}
placeholder='Digite sua senha'
value={password}
onChangeText={(text) => setPassword(text)}
password
/>
<CustomButton onPress={handleLoginButtonCLick}>
<CustomButtonText>LOGIN</CustomButtonText>
</CustomButton>
</InputArea>
<RegisterMessageButton onPress={handleMessageButtonClick}>
<RegisterMessageButtonText>Ainda não possui uma conta? </RegisterMessageButtonText>
<RegisterMessageButtonTextBold>Cadastre-se</RegisterMessageButtonTextBold>
</RegisterMessageButton>
</Container>
);
};<file_sep>/src/components/AppointmentCard/styles.js
import React from 'react';
import styled from 'styled-components/native';
export const AppointmentCard = styled.View`
background-color: #FFF;
margin-bottom: 20px;
border-radius: 20px;
padding: 15px;
`;
export const BarberInfo = styled.View`
flex: 1;
flex-direction: row;
align-items: center;
margin-bottom: 10px;
`;
export const BarberAvatar = styled.Image`
width: 88px;
height: 88px;
margin-right: 10px;
`;
export const BarberName = styled.Text`
font-size: 18px;
font-weight: bold;
color: #321718;
`;
export const AppointmentInfo = styled.View`
`;
export const ServiceInfo = styled.View`
flex-direction: row;
justify-content: space-between;
margin-bottom: 5px;
`;
export const DateHourInfo = styled.View`
flex-direction: row;
justify-content: space-between;
margin-bottom: 10px;
`;
export const ServiceName = styled.Text`
font-size: 16px;
font-weight: bold;
color: #321718;
`;
export const ServicePrice = styled.Text`
font-size: 16px;
font-weight: bold;
color: #321718;
`;
export const DateHourText = styled.Text`
border-radius: 10px;
font-size: 16px;
color: #777;
`;
export const CancelButton = styled.TouchableOpacity`
margin-top: 20px;
background-color: #E29550;
border-radius: 10px;
padding: 10px 15px;
align-items: center;
justify-content: center;
`;
export const CancelButtonText = styled.Text`
font-size: 14px;
font-weight: bold;
color: #FFF;
`;
export const FinishedButton = styled.TouchableOpacity`
margin-top: 20px;
background-color: #999;
border-radius: 10px;
padding: 10px 15px;
align-items: center;
justify-content: center;
`;
export const FinishedButtonText = styled.Text`
font-size: 14px;
font-weight: bold;
color: #000;
`;
export const Rating = styled.View`
margin-top: 10px;
flex-direction: row;
justify-content: space-between;
`;
export const RatingText = styled.Text`
font-size: 14px;
color: #000;
`;<file_sep>/src/stacks/MainTab.js
import React from 'react';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import HomeScreen from '../screens/Home';
import SearchScreen from '../screens/Search';
import AppointementsScreen from '../screens/Appointments';
import FavoritesScreen from '../screens/Favorites';
import ProfileScreen from '../screens/Profile';
import CustomTabBar from '../components/CustomTabBar';
const Tab = createBottomTabNavigator();
export default() => (
<Tab.Navigator
tabBar={
props => <CustomTabBar {...props} />
}
>
<Tab.Screen name='Home' component={HomeScreen} />
<Tab.Screen name='Search' component={SearchScreen} />
<Tab.Screen name='Appointments' component={AppointementsScreen} />
<Tab.Screen name='Favorites' component={FavoritesScreen} />
<Tab.Screen name='Profile' component={ProfileScreen} />
</Tab.Navigator>
);<file_sep>/src/components/BarberModal/styles.js
import React from 'react';
import styled from 'styled-components/native';
export const Modal = styled.Modal`
`;
export const ModalArea = styled.View`
flex: 1;
background-color: rgba(0, 0, 0, 0.5);
justify-content: flex-end;
`;
export const ModalBody = styled.View`
background-color: #331A1A;
border-top-left-radius: 20px;
border-top-right-radius: 20px;
min-height: 300px;
padding: 10px 20px 40px 20px;
`;
export const CloseButton = styled.TouchableOpacity`
width: 40px;
height: 40px;
`;
export const ModalItem = styled.View`
background-color: #462628;
border-radius: 10px;
margin-bottom: 15px;
padding: 10px;
`;
export const BarberInfo = styled.View`
flex-direction: row;
align-items: center;
`;
export const BarberAvatar = styled.Image`
width: 56px;
height: 56px;
border-radius: 20px;
margin-right: 15px;
`;
export const BarberName = styled.Text`
color: #FFF;
font-weight: bold;
font-size: 18px;
`;
export const ServiceInfo = styled.View`
flex-direction: row;
justify-content: space-between;
`;
export const ServiceName = styled.Text`
font-size: 16px;
font-weight: bold;
color: #FFF;
`;
export const ServicePrice = styled.Text`
font-size: 16px;
font-weight: bold;
color: #FFF;
`;
export const ScheduleButton = styled.TouchableOpacity`
background-color: #E07119;
height: 60px;
justify-content: center;
align-items: center;
border-radius: 10px;
`;
export const ScheduleButtonText = styled.Text`
color: #FFF;
font-size: 17px;
font-weight: bold;
`;
export const DateInfo = styled.View`
flex-direction: row;
`;
export const DatePrevArea = styled.TouchableOpacity`
flex: 1;
justify-content: flex-end;
align-items: flex-end;
`;
export const DateNextArea = styled.TouchableOpacity`
flex: 1;
align-items: flex-start;
`;
export const DateTitleArea = styled.View`
width: 140px;
justify-content: center;
align-items: center;
`;
export const DateTitle = styled.Text`
color: #DB945D;
font-size: 17px;
font-weight: bold;
`;
export const DateList = styled.ScrollView`
margin-top: 20px;
`;
export const DateItem = styled.TouchableOpacity`
width: 45px;
justify-content: center;
align-items: center;
border-radius: 10px;
padding-top: 5px;
padding-bottom: 5px;
margin: 3px;
`;
export const DateItemWeekDay = styled.Text`
font-size: 16px;
font-weight: bold;
`;
export const DateItemNumber = styled.Text`
font-size: 16px;
font-weight: bold;
`;
export const HoursList = styled.ScrollView`
`;
export const HourItem = styled.TouchableOpacity`
width: 75px;
height: 40px;
justify-content: center;
align-items: center;
border-radius: 10px;
`;
export const HourItemText = styled.Text`
font-size: 16px;
font-weight: bold;
color: #FFF;
`;<file_sep>/src/screens/Barber/index.js
import React, { useState } from 'react';
import {
Container,
Scroller,
FakeSwiper,
PageBody,
BarberInfoArea,
ServiceArea,
TestimonialArea,
SwipeDot,
SwipeActiveDot,
SwipeItem,
SwipeImage,
BarberAvatar,
BarberInfo,
BarberInfoName,
BarberFavoriteButton,
BackButton,
LoadingIcon,
ServiceItem,
ServiceInfo,
ServiceName,
ServicePrice,
ServiceChooseButton,
ServiceChooseButtonText,
ServicesTitle,
TestimonialCard,
TestimonialInfo,
TestimonialName,
TestimonialBody
} from './styles';
import { useNavigation, useRoute } from '@react-navigation/native';
import Swiper from 'react-native-swiper';
import StarsNote from '../../components/StarsNote';
import EmptyFavoriteIcon from '../../assets/favorite.svg';
import FullFavoriteIcon from '../../assets/favorite_full.svg';
import BackIcon from '../../assets/back.svg';
import NavPrevIcon from '../../assets/nav_prev.svg';
import NavNextIcon from '../../assets/nav_next.svg';
import BarberModal from '../../components/BarberModal';
export default() => {
const navigation = useNavigation();
const route = useRoute();
const { id, avatar, name, photos, stars } = route.params;
const [barberInfo, setBarberInfo] = useState({
id,
avatar,
name,
stars
});
const [isLoading, setIsLoading] = useState(false);
const [favorited, setFavorited] = useState(false);
const [selectedService, setSelectedService] = useState(null);
const [showModal, setShowModal] = useState(false);
const handleBackButtonClick = () => {
navigation.goBack();
};
const handleChangeFavorited = async() => {
setFavorited(!favorited);
};
const handleServiceChoose = (keyService) => {
setSelectedService(keyService);
setShowModal(true);
};
return(
<Container>
<Scroller>
{
photos && photos.length > 0 ?
<Swiper
style={{height: 240}}
dot={<SwipeDot />}
activeDot={<SwipeActiveDot />}
paginationStyle={{ top: 15, right: 15, bottom: null, left: null }}
autoplay
>
{
photos.map((photo, index) => (
<SwipeItem key={index}>
<SwipeImage source={photo.url} resizeMode='cover' />
</SwipeItem>
))
}
</Swiper>
:
<FakeSwiper></FakeSwiper>
}
<PageBody>
<BarberInfoArea>
<BarberAvatar source={avatar} />
<BarberInfo>
<BarberInfoName>{name}</BarberInfoName>
<StarsNote stars={stars} showNumber={true} />
</BarberInfo>
<BarberFavoriteButton>
{
favorited ?
<FullFavoriteIcon onPress={handleChangeFavorited} width='24' height='24' fill='#FF0000' />
:
<EmptyFavoriteIcon onPress={handleChangeFavorited} width='24' height='24' fill='#FF0000' />
}
</BarberFavoriteButton>
</BarberInfoArea>
{
isLoading && <LoadingIcon size='large' color='#FFF' />
}
<ServiceArea>
<ServicesTitle>Lista de serviços</ServicesTitle>
<ServiceItem>
<ServiceInfo>
<ServiceName>Corte masculino</ServiceName>
<ServicePrice>R$ 29,90</ServicePrice>
</ServiceInfo>
<ServiceChooseButton onPress={handleServiceChoose}>
<ServiceChooseButtonText>Agendar</ServiceChooseButtonText>
</ServiceChooseButton>
</ServiceItem>
<ServiceItem>
<ServiceInfo>
<ServiceName>Corte masculino</ServiceName>
<ServicePrice>R$ 29,90</ServicePrice>
</ServiceInfo>
<ServiceChooseButton onPress={handleServiceChoose}>
<ServiceChooseButtonText>Agendar</ServiceChooseButtonText>
</ServiceChooseButton>
</ServiceItem>
<ServiceItem>
<ServiceInfo>
<ServiceName>Corte masculino</ServiceName>
<ServicePrice>R$ 29,90</ServicePrice>
</ServiceInfo>
<ServiceChooseButton onPress={handleServiceChoose}>
<ServiceChooseButtonText>Agendar</ServiceChooseButtonText>
</ServiceChooseButton>
</ServiceItem>
</ServiceArea>
<TestimonialArea>
<Swiper
style={{height: 110}}
showsPagination={false}
showsButtons
prevButton={<NavPrevIcon width='35' height='35' fill='#FFF' />}
nextButton={<NavNextIcon width='35' height='35' fill='#FFF' />}
>
<TestimonialCard>
<TestimonialInfo>
<TestimonialName><NAME></TestimonialName>
<StarsNote stars={5} showNumber={false} />
</TestimonialInfo>
<TestimonialBody>Excelente profissional!</TestimonialBody>
</TestimonialCard>
<TestimonialCard>
<TestimonialInfo>
<TestimonialName><NAME></TestimonialName>
<StarsNote stars={5} showNumber={false} />
</TestimonialInfo>
<TestimonialBody>Corte perfeito. Nota 10!!</TestimonialBody>
</TestimonialCard>
<TestimonialCard>
<TestimonialInfo>
<TestimonialName><NAME></TestimonialName>
<StarsNote stars={4.5} showNumber={false} />
</TestimonialInfo>
<TestimonialBody>Muito bom!</TestimonialBody>
</TestimonialCard>
</Swiper>
</TestimonialArea>
</PageBody>
</Scroller>
<BackButton onPress={handleBackButtonClick}>
<BackIcon width='44' height='44' fill='#FFF' />
</BackButton>
<BarberModal
visible={showModal}
setShowModal={setShowModal}
barber={{
available: [],
avatar,
name: '<NAME>',
}}
service={{
name: 'Corte masculino',
price: 'RS 29,90'
}}
/>
</Container>
);
}<file_sep>/src/screens/Favorites/styles.js
import React from 'react';
import styled from 'styled-components/native';
export const Container = styled.SafeAreaView`
flex: 1;
background-color: #331A1A;
`;
export const BackButton = styled.TouchableOpacity`
position: absolute;
left: 0;
top: 27px;
z-index: 9;
`;
export const Header = styled.View`
flex: 1;
margin-left: 30px;
margin-top: 15px;
`;
export const HeaderText = styled.Text`
font-size: 20px;
font-weight: bold;
color: #FFF;
`;<file_sep>/src/components/LoginInput/index.js
import React from 'react';
import { InputArea, Input } from './styles';
export default ({ Icon, placeholder, value, onChangeText, type, password }) => {
return (
<InputArea>
<Icon width='24' height='24' fill='#331918' />
<Input
placeholder={placeholder}
placeholderTextColor='#331918'
value={value}
onChangeText={onChangeText}
secureTextEntry={password}
/>
</InputArea>
);
}<file_sep>/src/components/MenuItemCard/index.js
import React from 'react';
import {
ProfileMenuItem,
ProfileMenuItemIcon,
ProfileMenuItemQtd,
ProfileMenuItemText,
ProfileMenuItemTextSub,
ProfileMenuItemTextTitle,
ProfileMenuItemTextContent,
ProfileMenuItemQtdText
} from './styles';
export default ({ icon, title, subtitle, qtdNotifications }) => {
return (
<ProfileMenuItem>
<ProfileMenuItemText>
<ProfileMenuItemIcon source={icon} />
<ProfileMenuItemTextContent>
<ProfileMenuItemTextTitle>{title}</ProfileMenuItemTextTitle>
<ProfileMenuItemTextSub>{subtitle}</ProfileMenuItemTextSub>
</ProfileMenuItemTextContent>
</ProfileMenuItemText>
{
qtdNotifications &&
<ProfileMenuItemQtd>
<ProfileMenuItemQtdText>{qtdNotifications}</ProfileMenuItemQtdText>
</ProfileMenuItemQtd>
}
</ProfileMenuItem>
);
}<file_sep>/src/screens/Profile/styles.js
import React from 'react';
import styled from 'styled-components/native';
export const Container = styled.SafeAreaView`
flex: 1;
background-color: #331A1A;
`;
export const BackButton = styled.TouchableOpacity`
position: absolute;
left: 0;
top: 27px;
z-index: 9;
`;
export const UserInfo = styled.View`
margin-top: 20px;
padding: 10px 20px;
flex-direction: row;
justify-content: space-between;
align-items: center;
`;
export const WelcomeUserText = styled.View`
`;
export const WelcomeText = styled.Text`
font-size: 20px;
color: #FFF;
`;
export const UserNameText = styled.Text`
font-size: 24px;
font-weight: bold;
color: #FFF;
`;
export const UserAvatar = styled.View`
`;
export const UserPhoto = styled.Image`
width: 60px;
height: 60px;
`;
export const Favorites = styled.View`
margin-bottom: 10px;
`;
export const FavoritesTitle = styled.Text`
margin-left: 20px;
margin-bottom: 10px;
font-size: 20px;
font-weight: bold;
color: #FFF;
`;
export const LogoutButton = styled.TouchableOpacity`
margin-top: 20px;
margin-bottom: 60px;
align-items: center;
justify-content: center;
border-radius: 10px;
padding: 10px;
background-color: rgba(224, 113, 25, .5);
`;
export const LogoutButtonText = styled.Text`
font-size: 18px;
color: #FFF;
`;
export const ProfileMenu = styled.View`
margin-top: 30px;
`;<file_sep>/src/screens/Home/index.js
import React, { useState } from 'react';
import {
Container,
Scroller,
HeaderArea,
HeaderTitle,
SearchButton,
LocationArea,
LocationInput,
LocationFinder,
LoadingIcon,
ListArea,
PromoCard,
PromoTextView,
PromoTextPercentage,
PromoDescription,
PromoDescriptionTextBold,
PromoDescriptionText,
PromoImageView,
PromoImage,
} from './styles';
import SearchIcon from '../../assets/search.svg';
import MyLocationIcon from '../../assets/my_location.svg';
import { useNavigation } from '@react-navigation/native';
import { request, PERMISSIONS } from 'react-native-permissions';
import Geolocation from '@react-native-community/geolocation';
import { Platform, RefreshControl } from 'react-native';
import BarberCard from '../../components/BarberCard';
const barberAvatar = require('../../assets/barber-shop-logo.png');
export default() => {
const navigation = useNavigation();
const [locationText, setLocationText] = useState('');
const [location, setLocation] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const [barbers, setBarbers] = useState([]);
const handleRefresh = () => {
setIsRefreshing(false);
};
const handleLocationSearch = () => {
setLocation({});
};
return(
<Container>
<Scroller
refreshControl={
<RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} />
}
>
<HeaderArea>
<HeaderTitle numberOfLines={2}>
Encontre o seu barbeiro favorito
</HeaderTitle>
<SearchButton onPress={() => navigation.navigate('Search')}>
<SearchIcon width='26' heght='26' fill='#FFF' />
</SearchButton>
</HeaderArea>
<PromoCard>
<PromoTextView>
<PromoTextPercentage>50%</PromoTextPercentage>
<PromoDescription>
<PromoDescriptionTextBold>OFF</PromoDescriptionTextBold>
<PromoDescriptionText>em qualquer corte</PromoDescriptionText>
</PromoDescription>
</PromoTextView>
<PromoImageView>
<PromoImage source={require('../../assets/promo.png')} />
</PromoImageView>
</PromoCard>
<LocationArea>
<LocationInput
placeholder='Onde você está?'
placeholderTextColor='#999'
value={locationText}
onChangeText={(e) => setLocationText(e)}
onEndEditing={handleLocationSearch}
/>
<LocationFinder>
<MyLocationIcon width='24' heght='24' fill='#999' />
</LocationFinder>
</LocationArea>
{
isLoading && <LoadingIcon size='large' color='#FFF' />
}
<ListArea>
<BarberCard
key={1}
data={{
id: 1,
avatar: barberAvatar,
name: '<NAME>',
stars: 4
}}
/>
<BarberCard
key={2}
data={{
id: 2,
avatar: barberAvatar,
name: '<NAME>',
stars: 4.5
}}
/>
<BarberCard
key={3}
data={{
id: 3,
avatar: barberAvatar,
name: '<NAME>',
stars: 4
}}
/>
<BarberCard
key={4}
data={{
id: 4,
avatar: barberAvatar,
name: '<NAME>',
stars: 5
}}
/>
<BarberCard
key={5}
data={{
id: 5,
avatar: barberAvatar,
name: '<NAME>',
stars: 4.5
}}
/>
<BarberCard
key={6}
data={{
id: 6,
avatar: barberAvatar,
name: '<NAME>',
stars: 3.5
}}
/>
</ListArea>
</Scroller>
</Container>
);
}
|
207975df6c8ccaee56b806c585887a6216a28c29
|
[
"JavaScript"
] | 16 |
JavaScript
|
Gabriel-Giovani/barber-app
|
2a9400a708fd47fe42a22c124a596bd9c7b09dd1
|
db0f5fc35e3179cab4452d0025ca688bff616b15
|
refs/heads/master
|
<repo_name>kaffo/VeracityTest<file_sep>/VeracityTest/Consumers/ConsoleConsumer.cs
using System;
using System.Collections.Generic;
using System.Text;
using VeracityTest.Data;
namespace VeracityTest.Consumers
{
public class ConsoleConsumer : IConsumer
{
private IDataQueue _dataQueue;
public ConsoleConsumer(IDataQueue dataQueue)
{
_dataQueue = dataQueue;
}
public void OnItemAdded()
{
DataItem item = _dataQueue.GetNextItem(ConsumerType.CONSOLE);
if (item != null) { Console.Out.WriteLine($"{item.Payload}"); }
}
}
}
<file_sep>/VeracityTest/Data/DataQueue.cs
using System;
using System.Collections.Generic;
using System.Text;
using VeracityTest.Consumers;
namespace VeracityTest.Data
{
public class DataQueue : IDataQueue
{
private Dictionary<ConsumerType, IConsumer> _listenerList;
private List<DataItem> _dataQueue;
public event ItemAddedEventHandler ItemAdded;
public DataQueue()
{
_listenerList = new Dictionary<ConsumerType, IConsumer>();
_dataQueue = new List<DataItem>();
}
public bool AddItem(DataItem item)
{
_dataQueue.Add(item);
ItemAdded?.Invoke();
return true;
}
public DataItem GetNextItem()
{
if (_dataQueue.Count > 0)
{
DataItem item = _dataQueue[0];
_dataQueue.RemoveAt(0);
return item;
} else
{
return null;
}
}
public DataItem GetNextItem(ConsumerType consumerType)
{
foreach (DataItem currentItem in _dataQueue)
{
if (currentItem.ConsumerType == consumerType)
{
_dataQueue.Remove(currentItem);
return currentItem;
}
}
return null;
}
public void RegisterListener(ConsumerType consumerType, IConsumer consumer)
{
if (!_listenerList.ContainsKey(consumerType))
{
_listenerList.Add(consumerType, consumer);
ItemAdded += consumer.OnItemAdded;
}
}
}
}
<file_sep>/VeracityTest/Data/DataQueueDebug.cs
using System;
using System.Collections.Generic;
using System.Text;
using VeracityTest.Consumers;
namespace VeracityTest.Data
{
public class DataQueueDebug : IDataQueue
{
public event ItemAddedEventHandler ItemAdded;
public bool AddItem(DataItem item)
{
Console.Out.WriteLine($"Added {item.ConsumerType}:{item.Payload}");
return true;
}
public DataItem GetNextItem()
{
return new DataItem(ConsumerType.CONSOLE, "DUMMY");
}
public DataItem GetNextItem(ConsumerType consumerType)
{
return new DataItem(consumerType, "DUMMY");
}
public void RegisterListener(ConsumerType consumerType, IConsumer consumer)
{
Console.Out.WriteLine($"Attempted to register {consumer.ToString()} as {consumerType}");
}
}
}
<file_sep>/VeracityTest/Producers/FileProducer.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using VeracityTest.Data;
using VeracityTest.Consumers;
namespace VeracityTest.Producers
{
public class FileProducer : IProducer
{
private static IDataQueue _dataQueue;
private static FileInfo _inputFileInfo;
private Thread _producerThread;
private static bool _runThread = true;
public FileProducer(IDataQueue dataQueue, FileInfo inputFileInfo)
{
// Check the input file exists
if (!inputFileInfo.Exists) { throw new Exception($"File {inputFileInfo.FullName} passed to producer doesn't exist!"); }
_dataQueue = dataQueue;
_inputFileInfo = inputFileInfo;
_producerThread = new Thread(RunProducer);
}
~FileProducer()
{
if (_runThread == true)
{
StopProducer();
}
}
private static void RunProducer(object obj)
{
int delay;
StreamReader input = File.OpenText(_inputFileInfo.FullName);
try
{
delay = (int)obj;
}
catch (InvalidCastException)
{
delay = 5000;
}
while (_runThread)
{
string currentLine = input.ReadLine();
if (currentLine != null)
{
List<string> lineSplit = new List<string>(currentLine.Split(','));
if (lineSplit.Count != 2) { continue; }
string lineType = lineSplit[0].ToLower();
ConsumerType currentType = ConsumerType.CONSOLE;
if (lineType.Equals("console"))
{
currentType = ConsumerType.CONSOLE;
} else if (lineType.Equals("file"))
{
currentType = ConsumerType.FILE;
} else
{
continue;
}
DataItem currentItem = new DataItem(currentType, lineSplit[1]);
_dataQueue.AddItem(currentItem);
}
Thread.Sleep(delay);
}
Thread.Sleep(0);
}
public void StartProducer(int productionDelay)
{
if (productionDelay > 0 && !_producerThread.IsAlive)
{
_runThread = true;
_producerThread.Start(productionDelay);
}
}
public void StopProducer()
{
if (_producerThread != null && _producerThread.IsAlive)
{
_runThread = false;
_producerThread.Join();
}
}
}
}
<file_sep>/VeracityTest/Consumers/IConsumer.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace VeracityTest.Consumers
{
public enum ConsumerType
{
CONSOLE,
FILE
}
public interface IConsumer
{
void OnItemAdded();
}
}
<file_sep>/VeracityTest/Program.cs
using System;
using System.IO;
using System.Threading;
using VeracityTest.Producers;
using VeracityTest.Consumers;
using VeracityTest.Data;
using System.Threading.Tasks;
using System.Diagnostics;
namespace VeracityTest
{
class Program
{
static void Main(string[] args)
{
if (args.Length <= 0)
{
Console.WriteLine("usage: ./VeracityTest <input file path> <time to run (ms)> <delay between producer writes (ms)>");
Console.ReadLine();
return;
}
FileInfo inputFile = new FileInfo(args[0]);
if (!inputFile.Exists)
{
Console.WriteLine($"File {inputFile.FullName} doesn't exist!");
Console.ReadLine();
return;
}
Console.WriteLine("control+c to quit early");
int runLength = 10000;
int delay = 500;
if (args.Length > 1 && int.TryParse(args[1], out int val))
{
runLength = val;
}
if (args.Length > 2 && int.TryParse(args[2], out int val2))
{
delay = val2;
}
IDataQueue dataQueue = new DataQueue();
IProducer producer = new FileProducer(dataQueue, inputFile);
IConsumer consoleConsumer = new ConsoleConsumer(dataQueue);
IConsumer fileConsumer = new FileConsumer(dataQueue, new FileInfo(@".\output.txt"));
dataQueue.RegisterListener(ConsumerType.CONSOLE, consoleConsumer);
dataQueue.RegisterListener(ConsumerType.FILE, fileConsumer);
producer.StartProducer(delay);
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
while (stopWatch.ElapsedMilliseconds < runLength)
{
Thread.Sleep(500);
}
stopWatch.Stop();
producer.StopProducer();
}
}
}
<file_sep>/VeracityTest/Data/DataItem.cs
using System;
using System.Collections.Generic;
using System.Text;
using VeracityTest.Consumers;
namespace VeracityTest.Data
{
public class DataItem
{
private ConsumerType _consumerType;
private string _payload;
public ConsumerType ConsumerType { get => _consumerType; }
public string Payload { get => _payload; }
public DataItem(ConsumerType consumerType, string payload)
{
_consumerType = consumerType;
_payload = payload;
}
}
}
<file_sep>/VearacityUnitTests/DataQueueTests/DataQueueTests.cs
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
using VeracityTest.Consumers;
using VeracityTest.Data;
using Moq;
namespace VearacityUnitTests.DataQueueTests
{
[TestFixture]
class DataQueueTests
{
[Test]
public void CheckDataQueueInputCountMatchesOutputCount()
{
IDataQueue dataQueue = new DataQueue();
var consumer = new Mock<IConsumer>();
int inCount = 10;
int outCount = 0;
consumer.Setup(c => c.OnItemAdded()).Callback(() => outCount++);
dataQueue.RegisterListener(ConsumerType.CONSOLE, consumer.Object);
for (int i = 0; i < inCount; i++)
{
dataQueue.AddItem(new DataItem(ConsumerType.CONSOLE, ""));
}
Assert.That(inCount.Equals(outCount), $"Expected outCount to be {inCount} but was {outCount}");
}
[Test]
public void CheckDataQueueDequeueTypeCorrect()
{
IDataQueue dataQueue = new DataQueue();
var consumer = new Mock<IConsumer>();
ConsumerType inType = ConsumerType.CONSOLE;
ConsumerType outType = ConsumerType.FILE;
consumer.Setup(c => c.OnItemAdded()).Callback(() => outType = dataQueue.GetNextItem(inType).ConsumerType);
dataQueue.RegisterListener(inType, consumer.Object);
dataQueue.AddItem(new DataItem(inType, "DUMMY"));
Assert.That(inType.Equals(outType), $"Expected type to be {inType} but was {outType}");
}
}
}
<file_sep>/VeracityTest/Producers/IProducer.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace VeracityTest.Producers
{
public interface IProducer
{
void StartProducer(int productionDelay);
void StopProducer();
}
}
<file_sep>/VeracityTest/Consumers/FileConsumer.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using VeracityTest.Data;
namespace VeracityTest.Consumers
{
public class FileConsumer : IConsumer
{
private IDataQueue _dataQueue;
private FileInfo _outputFile;
public FileConsumer(IDataQueue dataQueue, FileInfo outputFile)
{
if (!outputFile.Exists)
{
StreamWriter sw = File.CreateText(outputFile.FullName);
sw.Close();
}
_dataQueue = dataQueue;
_outputFile = outputFile;
}
public void OnItemAdded()
{
DataItem item = _dataQueue.GetNextItem(ConsumerType.FILE);
if (item != null) {
using (StreamWriter file = new StreamWriter(_outputFile.FullName, true))
{
file.WriteLine(item.Payload);
}
}
}
}
}
<file_sep>/VeracityTest/Data/IDataQueue.cs
using System;
using System.Collections.Generic;
using System.Text;
using VeracityTest.Consumers;
namespace VeracityTest.Data
{
public delegate void ItemAddedEventHandler();
public interface IDataQueue
{
void RegisterListener(ConsumerType consumerType, IConsumer consumer);
bool AddItem(DataItem item);
event ItemAddedEventHandler ItemAdded;
DataItem GetNextItem();
DataItem GetNextItem(ConsumerType consumerType);
}
}
|
6b0ce6efc20371670f0b1cd51e6505721043f397
|
[
"C#"
] | 11 |
C#
|
kaffo/VeracityTest
|
c1a5a09ab0ec4f9a36fe3a7041fc8b4c79d2b9ea
|
e85eff30b336fad0d9272fd15e033c983c7cb717
|
refs/heads/master
|
<file_sep># calculator_in_c
This is just a basic project to test my c++ skills at initial level
<file_sep>#include<stdio.h>
#include<stdlib.h>
void addition()
{
int num1, num2;
printf("Enter the two numbers with space between them: \n");
scanf("%d %d",&num1,&num2);
printf("%d\n",num1+num2);
}
void subtraction()
{
int num1, num2;
printf("Enter the two numbers with space between them: \n");
scanf("%d %d",&num1,&num2);
printf("%d\n",num1+num2);
}
void multiplication()
{
int num1, num2;
printf("Enter the two numbers with space between them: \n");
scanf("%d %d",&num1,&num2);
printf("%d\n",num1*num2);
}
void division()
{
float num1, num2;
printf("Enter the two numbers with space between them: \n");
scanf("%f %f",&num1,&num2);
printf("%f\n",num1/num2);
}
int main()
{
int choice;
printf("----------Darklord's Calculator----------\n");
printf("=========================================\n");
printf("Operations available\n");
printf("1). Addition\n");
printf("2). Subtraction\n");
printf("3). Multiplication\n");
printf("4). Division\n");
printf("Enter your choice: \n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
addition();
break;
}
case 2:
{
subtraction();
break;
}
case 3:
{
multiplication();
break;
}
case 4:
{
division();
break;
}
default:
{
printf("please enter a valid choice:\n");
break;
}
}
return 0;
}
|
30aa35f43f0ae9cd05f45e22d32ee8542147620a
|
[
"Markdown",
"C"
] | 2 |
Markdown
|
Rohit-Prajapati-1897/calculator_in_c
|
a9f7df0a7d1c674350c0edae459114e0a557f285
|
b74f2cb09b3e63da10465a3b962f8666d59beb0b
|
refs/heads/master
|
<repo_name>supcomstudents/cv-parser<file_sep>/Dockerfile
FROM alpine:3.7
ENV PYTHONUNBUFFERED 1
RUN apk update && \
apk upgrade && \
apk add --no-cache \
gcc g++ paxctl libgcc libstdc++ make cmake musl-dev libffi-dev openssl-dev linux-headers libxml2-dev libxslt-dev python python-dev python3 python3-dev libc-dev libunwind-dev alpine-sdk xz poppler-dev pango-dev m4 libtool perl autoconf automake coreutils zlib-dev freetype-dev glib-dev libpng freetype libintl libltdl cairo
# This next RUN is from https://github.com/BWITS/Docker-builder/blob/master/pdf2htmlEX/alpine/Dockerfile
# Used here with 3.7 because of libunwind-dev, which is not available on alpine 3.2's package index
RUN cd / && \
git clone https://github.com/BWITS/fontforge.git && \
cd fontforge && \
./bootstrap --force && \
./configure --without-iconv && \
make && \
make install && \
cd / && \
git clone git://github.com/coolwanglu/pdf2htmlEX.git && \
cd pdf2htmlEX && \
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig && \
cmake . && make && sudo make install && \
rm -rf /fontforge /libspiro /libuninameslist /pdf2htmlEX
RUN mkdir /code
WORKDIR /code
COPY ./requirements.txt /requirements.txt
COPY ./entrypoint.sh /code/entrypoint.sh
COPY ./cv-parser /cv-parser
RUN pip3 install --upgrade setuptools && pip3 install --upgrade pip
RUN pip3 install -r /requirements.txt
ENTRYPOINT ["/bin/sh", "entrypoint.sh"]
<file_sep>/cv-parser/dateregex.py
import re
from .textCleaners import clean_text
class DateRegex:
"""DateRegex class used to find the a duration (specified by two dates) in various formats."""
not_alpha_numeric = r'[^a-zA-Z\d]'
# Various month format definitions
months_short = r'(jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|(aug)|(sep)|(oct)|(nov)|(dec)'
months_long = r'(january)|(february)|(march)|(april)|(may)|(june)|(july)|(august)|(september)|(october)|(november)|(december)'
months_numeric = r'(?<![\d])\d{1,2}(?![\d])'
month_alphabetic = r'(' + months_short + r'|' + months_long + r')'
month_numeric_long = r'([\d]{1,2})(?=[^A-Za-z]{1}[\d]{4})'
year = r'((20|19)(\d{2}))'
# Double (normal) year range (e.g.: 2013 - 2014)
double_year_range = year + not_alpha_numeric + r"{1,3}" + year
# Multi year range (e.g.: 2013 - 2014 - 2015)
multi_year_range = r'(' + year + '(' + not_alpha_numeric + r'{1,3}' + year + '){1,5})|(' + year +\
not_alpha_numeric + r'{1,3}' + r')'
# Start Date definitions in various formats
start_date_alphabetic = month_alphabetic + not_alpha_numeric + r"{1,3}" + year
start_date_numeric = months_numeric + not_alpha_numeric + r'{1,3}' + year
start_date_numeric_long = r'[\d]{1,2}[^a-zA-Z\d]?' + months_numeric + not_alpha_numeric + r'?' + year
start_date_alphabetic_long = r'[\d]{1,2}[^a-zA-Z\d]?' + month_alphabetic + not_alpha_numeric + r'?' + year
# End Date definitions in various formats
end_date_alphabetic = r'((' + month_alphabetic + not_alpha_numeric + r"{1,3}" + year + r')|(present)|(now)|(today))'
end_date_numeric = r'((' + months_numeric + not_alpha_numeric + r"{1,3}" + year + r')|(present)|(now)|(today))'
end_date_numeric_long = r'(([\d]{1,2}[^a-zA-Z\d]?' + months_numeric + not_alpha_numeric + r"?" + year + r')|(present)|(now)|(today))'
end_date_alphabetic_long = r'(([\d]{1,2}[^a-zA-Z\d]?' + month_alphabetic + not_alpha_numeric + r"?" + year + r')|(present)|(now)|(today))'
# Date Range alphabetic (e.g.: April 2013 - May 2014)
date_range_alphabetic = r"(" + start_date_alphabetic + not_alpha_numeric + r"{1,3}" + end_date_alphabetic + r")|(" + double_year_range + r")"
# Date Range numberic (e.g.: 01.2014 - 12.2014)
date_range_numeric = r"(" + start_date_numeric + not_alpha_numeric + r"{1,3}" + end_date_numeric + r")"
# Date Range numeric long format (e.g.: 15.01.2014 - 31.07.2015)
date_range_numeric_long = r"(" + start_date_numeric_long + not_alpha_numeric + r"{1,3}" + end_date_numeric_long + r")"
# Date Range alphabetic long format (e.g.: 15. May 2015 - 16. July 2017)
date_range_alphabetic_long = r"(" + start_date_alphabetic_long + not_alpha_numeric + r"{1,3}" + end_date_alphabetic_long + r")"
# MM.YYYY-MM.YYYY Date range in either alphabetic or numeric format
date_range = r'(' + date_range_alphabetic + r'|' + date_range_numeric + r')' + r'(' + not_alpha_numeric + r'{1,4}|$)'
# DD.MM.YYYY - DD.MM.YYYY Date range in numeric format
date_range_long_numeric = r'(' + date_range_numeric_long + r')' + not_alpha_numeric + r'{1,4}'
# DD.MM.YYYY - DD.MM.YYYY Date range in alphabetic format
date_range_long_alphabetic = r'(' + date_range_numeric_long + r')' + not_alpha_numeric + r'{1,4}'
# Open-ended durations, where only start date is present (e.g: 2.2015 - )
start_date_only = r'(?<![^A-Za-z]{5})' + r'(' + start_date_numeric + r'|' + start_date_alphabetic + r')' + r'(?![^A-Za-z]{5})'
# Month range (e.g.: From 02-04 2014 finds 02-04)
month_range = r'(' + month_alphabetic + r'|' + months_numeric + r')' + not_alpha_numeric + r"{1,4}" + r'(' + \
month_alphabetic + r'|' + months_numeric + r')' + not_alpha_numeric + r"{1,2}" + year
# Initialize variables that will hold the found start and end date values (months and years)
start_month = -1
start_year = -1
end_month = -1
end_year = -1
resume_text = ""
duration_found = False
def __init__(self, resume_text):
self.resume_text = resume_text
def find_number_of_durations(self):
"""Finds the number of durations in the resume, by searching for YYYY occurences,
that is NOT followed by any digit for the next 10 characters."""
# 01.2012 - 03.2014 will be counted once, as only the "2014" is picked up by the regex.
# Good approximation for counting the total number of durations in the text.
general_year_finder = r'\d{4}((?=[^\d]{10})|$)'
regular_expression = re.compile(general_year_finder, re.IGNORECASE)
regex_result = re.findall(regular_expression, self.resume_text)
return len(regex_result)
def calculate_experience_duration(self):
"""Calculates the date range in resume_text"""
# Clean resume text for date recognition
self.replace_to_with_hyphen_in_resume_text()
self.resume_text = clean_text(self.resume_text)
# Recognize durations of various formats
self.find_full_date_range_numeric()
self.find_full_date_range_alphabetic()
self.find_month_and_year_range()
self.find_month_ranges()
self.find_unclosed_date_expression()
self.standardize_month_number()
return {
'start_year': self.start_year,
'end_year': self.end_year,
'start_month': self.start_month,
'end_month': self.end_month
}
def reset_found_dates(self):
"""Resets the found date members of the class."""
self.start_month = -1
self.start_year = -1
self.end_year = -1
self.end_month = -1
def find_year_range(self):
""""Finds a year range such as 2012 - 2013 or 2013 - 2014 - 2015"""
regular_expression = re.compile(self.multi_year_range, re.IGNORECASE)
regex_result = re.search(regular_expression, self.resume_text)
if regex_result and not self.duration_found:
self.reset_found_dates()
duration = regex_result.group()
self.find_start_year(duration)
self.find_end_year_in_multirange(duration)
self.start_month = '0' + str(1)
self.end_month = '0' + str(1)
self.duration_found = True
# print(str(self.start_month) + "/" + str(self.start_year) + " - " + str(self.end_month) + "/" + str(
# self.end_year))
def find_full_date_range_numeric(self):
"""Finds full date ranges in long version with day e.g.:( 01/01/2012-01/03/2014)"""
regular_expression = re.compile(self.date_range_long_numeric, re.IGNORECASE)
regex_result = re.search(regular_expression, self.resume_text)
if regex_result and not self.duration_found:
self.reset_found_dates()
duration = regex_result.group()
self.find_start_date(duration, self.month_numeric_long)
self.find_end_date(duration, self.month_numeric_long)
self.duration_found = True
def find_full_date_range_alphabetic(self):
"""Finds full date ranges in long version with day e.g.:(21 Jun, 2010 to 11 Sep, 2012)"""
regular_expression = re.compile(self.date_range_alphabetic_long, re.IGNORECASE)
regex_result = re.search(regular_expression, self.resume_text)
if regex_result and not self.duration_found:
self.reset_found_dates()
duration = regex_result.group()
self.find_start_date_with_alphabetic(duration, self.months_short, self.months_numeric)
self.find_end_date_with_alphabetic(duration, self.months_short, self.months_numeric)
self.duration_found = True
# print(str(self.start_month) + "/" + str(self.start_year) + " - " + str(self.end_month) + "/" + str(self.end_year))
def find_month_and_year_range(self):
"""Finds month and year ranges in both numeric and alphabetic ways
04/2017 - 01/2018 || mar/2018 - jun/2019 || july/2015 - may/2016"""
regular_expression = re.compile(self.date_range, re.IGNORECASE)
regex_result = re.search(regular_expression, self.resume_text)
if regex_result and not self.duration_found:
self.reset_found_dates()
duration = regex_result.group()
self.find_start_date_with_alphabetic(duration, self.months_short, self.months_numeric)
self.find_end_date_with_alphabetic(duration, self.months_short, self.months_numeric)
self.duration_found = True
# print(str(self.start_month) + "/" + str(self.start_year) + " - " + str(self.end_month) + "/" + str(self.end_year))
def find_month_ranges(self):
"""Find month ranges such as 04-05. 2017"""
regular_expression = re.compile(self.month_range, re.IGNORECASE)
regex_result = re.search(regular_expression, self.resume_text)
if regex_result and not self.duration_found:
duration = regex_result.group()
self.find_start_date_with_alphabetic(duration, self.months_short, self.months_numeric)
# Find end month (start searching from start month)
start_month_result = self.find_start_month_alphabetic(self.months_short, duration)
if not start_month_result:
start_month_result = self.find_start_month(self.months_numeric, duration)
month_regex = re.compile(self.months_short, re.IGNORECASE)
month_result = re.search(month_regex, duration[start_month_result.end():])
if month_result:
current_month = self.get_month_index(month_result.group())
self.end_month = current_month
else:
month_regex = re.compile(self.months_numeric, re.IGNORECASE)
month_result = re.search(month_regex, duration[start_month_result.end():])
if month_result:
current_month = month_result.group()
self.end_month = int(current_month)
self.end_year = self.start_year
# print(str(self.start_month) + "/" + str(self.start_year) + " - " + str(self.end_month) + "/" + str(
# self.end_year))
self.duration_found = True
def find_unclosed_date_expression(self):
"""Finds date expressions, where the end-date was not specified at all."""
start_only_regular_expression = re.compile(self.start_date_only, re.IGNORECASE)
start_only_regex_result = re.search(start_only_regular_expression, self.resume_text)
if start_only_regex_result and not self.duration_found:
duration = start_only_regex_result.group()
self.find_start_date_with_alphabetic(duration, self.months_short, self.months_numeric)
# print(str(self.start_month) + '/' + str(self.start_year))
self.duration_found = True
def replace_to_with_hyphen_in_resume_text(self):
"""Replaces occurrences of "to" and "until" with "-". This is useful when the candidate describes the duration as
01/2014 to 02/2015."""
self.resume_text = self.resume_text.replace(" to ", " - ")
self.resume_text = self.resume_text.replace(" until ", " - ")
def find_start_date(self, duration, month_regex_type):
"""Extracts the start date from a given duration. E.g.: 04.2012 from 04.2012-05.2013"""
if self.find_start_year(duration):
self.find_start_month(month_regex_type, duration)
def find_start_date_with_alphabetic(self, duration, month_regex_alphabetic, month_regex_numeric):
"""Extracts the alphanumeric start date from a duration."""
if self.find_start_year(duration):
if not self.find_start_month_alphabetic(month_regex_alphabetic, duration):
self.find_start_month(month_regex_numeric, duration)
def find_start_year(self, duration):
"""Extracts the start year from a duration"""
year_regex = re.compile(self.year)
year_result = re.search(year_regex, duration)
if year_result:
self.start_year = int(year_result.group())
return year_result
def find_start_month(self, month_regex_expression, duration):
"""Extracts the start month from a duration"""
month_regex = re.compile(month_regex_expression, re.IGNORECASE)
month_result = re.search(month_regex, duration)
if month_result:
current_month = month_result.group()
self.start_month = int(current_month)
return month_result
def find_start_month_alphabetic(self, month_regex_expression, duration):
"""Extracts the alphabetic start month from a duration"""
month_regex = re.compile(month_regex_expression, re.IGNORECASE)
month_result = re.search(month_regex, duration)
if month_result:
current_month = self.get_month_index(month_result.group())
self.start_month = int(current_month)
return month_result
def find_end_date(self, duration, month_regex_expression):
"""Finds the end date in the given duration"""
if self.find_end_year(duration):
self.find_end_month(month_regex_expression, duration)
def find_end_date_with_alphabetic(self, duration, month_regex_alphabetic, month_regex_numeric):
"""Finds the end date in the given duration"""
if self.find_end_year(duration):
if not self.find_end_month_alphabetic(month_regex_alphabetic, duration):
self.find_end_month(month_regex_numeric, duration)
def is_end_date_now(self, duration):
"""Returns true if the duration contains 'present', 'now', 'today', or '...'"""
return duration.lower().find('present') != -1 or duration.lower().find(
'now') != -1 or duration.lower().find('today') != -1 or duration.lower().find('...') != -1
def find_end_year(self, duration):
"""Extracts the end year from a given duration"""
start_year = self.find_start_year(duration)
end_year_result = re.search(self.year, duration[start_year.end():])
if end_year_result:
self.end_year = int(end_year_result.group())
return end_year_result
def find_end_year_in_multirange(self, duration):
"""Extracts the end year in a multi-year duration. Eg.: extracts 2015 from 2012 - 2013 - 2014"""
year_regex = re.compile(self.year + r'$')
end_year_result = re.search(year_regex, duration)
if end_year_result:
self.end_year = int(end_year_result.group())
return end_year_result
def find_end_month(self, month_regex_expression, duration):
"""Extracts the end-month from a duration"""
start_year = self.find_start_year(duration)
month_regex = re.compile(month_regex_expression, re.IGNORECASE)
month_result = re.search(month_regex, duration[start_year.end():])
if month_result:
current_month = month_result.group()
self.end_month = int(current_month)
return month_result
def find_end_month_alphabetic(self, month_regex_expression, duration):
"""Extracts the alphabetic end month from a duration"""
start_year = self.find_start_year(duration)
month_regex = re.compile(month_regex_expression, re.IGNORECASE)
month_result = re.search(month_regex, duration[start_year.end():])
if month_result:
current_month = self.get_month_index(month_result.group())
self.end_month = int(current_month)
return month_result
def standardize_month_number(self):
"""Feeds a leading zero to the month if it was not written with double digits.
E.g.: (february) 2 -> 02, (may) 5 -> 05"""
if len(str(self.start_month)) < 2:
self.start_month = '0' + str(self.start_month)
if len(str(self.end_month)) < 2:
self.end_month = '0' + str(self.end_month)
def get_month_index(self, month):
"""Returns the numeric representation of an alphabetic month"""
month_dict = {'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, 'jul': 7, 'aug': 8, 'sep': 9,
'oct': 10, 'nov': 11, 'dec': 12}
return month_dict[month.lower()]<file_sep>/cv-parser/scraper.py
import os
import subprocess
from selenium import webdriver
class Scraper:
"""WebDriver used for opening, rendering, and scraping HTML files."""
def __init__(self):
chromedriver = os.path.dirname(os.path.abspath(__file__)) + "/webdriver/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
self.browser = webdriver.Chrome(chromedriver)
self.browser.set_window_position(-100000, 0) # move browser window out of screen
def __exit__(self, exc_type, exc_val, exc_tb):
self.browser.close()
def convert_pdf_to_html(file_path):
""""Converts the file to HTML to PDF and returns the path.
The returned value is None if the file could not be converted."""
path_of_generated_html = os.path.splitext(file_path)[0] + ".html"
directory_of_file = os.path.dirname(os.path.abspath(path_of_generated_html))
if not os.path.exists(path_of_generated_html):
if execute_pdf_to_html_process(file_path, directory_of_file) is not 0:
print('The file ' + file_path + " can't be converted to html. Sorry.")
return None
return path_of_generated_html
def execute_pdf_to_html_process(filename, destination_dir=None):
"""Converts the PDF file specified by filename to PDF file, by calling the pdf2htmlEX
in a separate 'terminal process'. Optionally puts it in the destination_dir. If destination_dir
is empty, the execution folder is used, i.e. the folder in which the pdf was found."""
if destination_dir is None:
destination_dir = os.path.dirname(filename)
command = "pdf2htmlEX --dest-dir " + destination_dir + " --optimize-text 1 " + filename
else:
command = "pdf2htmlEX --dest-dir " + destination_dir + " --optimize-text 1 " + filename
process_status_code = subprocess.call(command, shell=True)
return process_status_code
def convert_html_resume_to_object(path_to_html):
"""Parses the html resume line by line into a list of "line dictionaries".
For each line the font-type, font-size, left-margin, font-color, page-number
and text are extracted and stored in a dict. At the end the list of dictionaries is returned."""
scraper = Scraper()
url_to_file = "file:///" + path_to_html
scraper.browser.get(url_to_file)
resume_lines = []
page_container = scraper.browser.find_element_by_id("page-container")
for page in page_container.find_elements_by_class_name("pf"):
# Scroll with the browser to the page to make the page (dynamically) render.
scraper.browser.execute_script("arguments[0].scrollIntoView();", page)
for line in page.find_elements_by_class_name("t"):
line_props = get_line_properties(line)
line_props['page_number'] = page.get_attribute("data-page-no")
resume_lines.append(line_props)
return resume_lines
def get_line_properties(line):
"""Takes a html (line) element as a input and puts its details (font-size, font-family, left-margin, text-color
and text) into a dictionary. Thus creating a dictionary that contains the text and its visual properties."""
font_size = line.value_of_css_property("font-size")
font_family = line.value_of_css_property("font-family")
left_margin = get_corrected_left_margin(line)
font_color = line.value_of_css_property("color")
bottom_margin = line.value_of_css_property("bottom")
text = line.text
return {
'font_size': font_size,
'font_family': font_family,
'left_margin': left_margin,
'font_color': font_color,
'bottom_margin': bottom_margin,
'line_text': text,
'page_number': 0
}
def get_corrected_left_margin(line):
"""Unfortunately in some cases a "tabbing" is not identified by the pdf -> html converter properly, and instead
of giving the correct left-margin, the converter assigns an incorrect left margin and adds many blank spaces
to the beginning of the text. Example:
Work Experinece:
.....
Internship
Now if internship is written with the font-size/color etc. of section keywords, it will be recognized as section keyword,
meanwhile in reality its left margin shouldn't mach the left margin of section keywords.
The function looks into such cases and increases the left margin value for such lines. The amount is not relevant,
only the fact, that it has significantly higher left-margin, hence the multiplication with 5"""
left_margin_value = line.value_of_css_property("left")
text = line.text
if text[:5].strip() == "":
left_margin_value = float(left_margin_value[:-2]) # Remove the px post-script
left_margin_value *= 5
left_margin_value = str(left_margin_value) + "px"
return left_margin_value<file_sep>/README.md
# cv-parser
## Introduction
Traditional open-source parsers accomplish resume parsing, by extracting and cleaning the text, only to apply a rule-based approach to extract the necessary information. The approach in itself is not flawed, however these parsers tend to focus on information extraction, rather than making sure that the text is clean and well structured. Namely these resume parsers lose structural information such as font-size, font-color or tabbing and thus lose the ability to precisely identify sections (skills section, work experience section), as well as individual work experiences.
The goal of the project was to develop a resume parser that heavily relies on the structural and visual information of the resume. The final product converts the pdf resume to html (using pdf2htmlEx), and then applies web scraping technologies to identify sections using the resume’s structural and visual information such as font-size, font-color, bottom-margin, left-margin etc.
## Open tasks
* Add flask server with REST API
* Finish Dockerfile & add docker-compose
* Add a full setup guide to this documentation
* ... Keep improving the parser!
### Credit
All the credit for the parser itself goes to [Tamas](https://github.com/orgs/motius/people/TamasNeumer). I just built the infrastructure around it to make life easier.
<file_sep>/cv-parser/parser.py
from pkg_resources import resource_string, resource_listdir
import json
from os import path
from collections import defaultdict
from .scraper import *
from .textCleaners import *
from .dateregex import *
from string import punctuation
from nltk.corpus import stopwords
def extract_information_into_json(html_path):
"""Parses the resume (of html format), extracts the relevant information, and returns it in a dictionary."""
# Load section separator keywords (education, work experience, skills etc.) and their synonymes.
section_separator_keywords_dict = load_section_separator_keywords_from_dictionary()
# Load the external HTML resume to the memory using an internal representation (dictionary).
resume_object = convert_html_resume_to_object(html_path)
# Find sections in the resume using section separator keywords.
parsed_resume = break_text_into_sections(resume_object, section_separator_keywords_dict)
# Find the individual expereinces in the work experience section and find out their durations and used skills.
parsed_resume = parse_work_experience(resume_object, parsed_resume)
# Use a "learning algorithm" to identify yet unknown skills in the skills section
learn_skills_from_resume(parsed_resume)
# analyze the skill section for known skills / programming languages
parsed_resume = parse_skills(parsed_resume)
# Return the results as a json data.
json_data = json.dumps(parsed_resume)
return json_data
def load_section_separator_keywords_from_dictionary():
"""Loads the section keywords (e.g.: "Work Experience", "Skills") from the resources into a dictionary.
The key is always the filename (E.g.: Skills.txt -> Skills) and the values are the list of keywords (skill, skills,
abilities, languages etc."""
keywords_dict = {}
for name in resource_listdir('resources.keywordlists', ''):
if os.path.splitext(name)[1] == '.txt':
keywords_dict[os.path.splitext(name)[0]] = \
resource_string('resources.keywordlists', name).decode("utf-8", "strict").splitlines()
return keywords_dict
def break_text_into_sections(resume_info, keywords_dict):
"""Breaks the resume into sections and returns a dictionary that contains section keywords (work experience,
skills etc.) as keys and the lines that correspond to the key as list of values."""
visual_properties_of_resume = get_visual_properties_of_section_keywords(resume_info, keywords_dict)
visual_properties_of_keywords_in_resume = deduce_visual_properties_of_keywords_in_resume(
visual_properties_of_resume)
return break_resume_in_sections(resume_info, keywords_dict, visual_properties_of_keywords_in_resume)
def get_visual_properties_of_section_keywords(resume_object, keywords_dict):
"""Section keywords are typically written with different style. (Capitals, bold (font-family), font-size,
left margin, font-color etc.) This function extracts the visual properties of the section keywords found in
the resume and returns these as a dictionary."""
# Collect occurrences of visual properties.
# E.g. for font-size: 46px : ["Education", "Work"], 42px : ["Skills", "Summary"] ...
font_size_dict = defaultdict(list)
font_family_dict = defaultdict(list)
left_margin_dict = defaultdict(list)
font_color_dict = defaultdict(list)
# Store the number of occurrences of different visual properties. (e.g.: font_size : {'48px': 8, '44.16px': 1})
# Properties of lines, where the entire line was written with capitals:
all_caps_properties = {
'font_size': {},
'font_family': {},
'left_margin': {},
'font_color': {},
'number_of_capital_matches': 0
}
# Properties of texts, where the line entirely matched the section keyword
entire_match_properties = {
'font_size': {},
'font_family': {},
'left_margin': {},
'font_color': {},
}
for line in resume_object:
line_text = clean_text_from_nonbasic_characters(line['line_text'])
# key = Skills, values = [Abilities, Areas of Experience, Areas of Expertise, Areas of Knowledge]
for key, value_list in keywords_dict.items():
# Sort the values by their length in descending order. This is important otherwise "Experience" will be
# matched before than "Work Experience" or "Areas of Experience" and these are more concrete / specific.
value_list = sorted(value_list, key=len, reverse=True)
for keyword in value_list:
if keyword_found_in_text(keyword, line_text):
font_size_dict[line['font_size']].append(line_text)
font_family_dict[line['font_family']].append(line_text)
left_margin_dict[line['left_margin']].append(line_text)
font_color_dict[line['font_color']].append(line_text)
# If keywords are written with capitals, collect their visual properties.
if keyword_found_in_text_with_capitals(keyword, line_text):
all_caps_properties = add_line_props_to_dict(line, all_caps_properties)
all_caps_properties['number_of_capital_matches'] += 1
# If currnet line fully matches the keyword, collect their visual properties.
if keyword_fully_matches_text(keyword, line_text):
entire_match_properties = add_line_props_to_dict(line, entire_match_properties)
break
return {
'font_size_dict': font_size_dict,
'font_family_dict': font_family_dict,
'left_margin_dict': left_margin_dict,
'font_color_dict': font_color_dict,
'all_caps_properties': all_caps_properties,
'entire_match_properties': entire_match_properties,
'number_of_capital_matches': all_caps_properties['number_of_capital_matches']
}
def keyword_found_in_text(keyword, line_text):
"""Returns true if the given keyword is matched anywhere in the text."""
if (re.search(keyword, line_text, re.IGNORECASE)) is not None:
return True
return False
def keyword_found_in_text_with_capitals(keyword, line_text):
"""Returns true if the given keyword's capitalized version is matched anywhere in the text"""
if (re.search(keyword.upper(), line_text)) is not None:
return True
return False
def keyword_fully_matches_text(keyword, line_text):
"""Returns true, if the text only contains the keyword and it matches the current keyword"""
# Remove any non-number / non-letter characters and strip off additional start/end white-spaces
line_text = replace_any_non_letter_or_number_character(line_text)
if re.fullmatch(keyword.upper(), line_text.upper()) is not None:
return True
return False
def add_line_props_to_dict(line, visual_properties_dict):
"""Extracts the visual properties of the line and adds it to the dictionary.
Returns the dictionary where the values have been "updated" with the current line's values."""
if line['font_size'] not in visual_properties_dict['font_size'].keys():
visual_properties_dict['font_size'][line['font_size']] = 1
else:
visual_properties_dict['font_size'][line['font_size']] += 1
if line['font_color'] not in visual_properties_dict['font_color'].keys():
visual_properties_dict['font_color'][line['font_color']] = 1
else:
visual_properties_dict['font_color'][line['font_color']] += 1
if line['left_margin'] not in visual_properties_dict['left_margin'].keys():
visual_properties_dict['left_margin'][line['left_margin']] = 1
else:
visual_properties_dict['left_margin'][line['left_margin']] += 1
if line['font_family'] not in visual_properties_dict['font_family'].keys():
visual_properties_dict['font_family'][line['font_family']] = 1
else:
visual_properties_dict['font_family'][line['font_family']] += 1
return visual_properties_dict
def deduce_visual_properties_of_keywords_in_resume(visual_properties_of_resume):
"""Based on the visual properties of section keywords gathered earlier, deduces the properties (font-size,
font-color etc.) that is common for section keywords. If the number of capital matches were at least 3 it is
assumed that all section keywords were written with capitals."""
properties_of_keywords_in_resume = {}
properties_of_keywords_in_resume = deduce_font_color(properties_of_keywords_in_resume,
visual_properties_of_resume)
properties_of_keywords_in_resume = deduce_font_family(properties_of_keywords_in_resume,
visual_properties_of_resume)
properties_of_keywords_in_resume = deduce_font_size(properties_of_keywords_in_resume,
visual_properties_of_resume)
properties_of_keywords_in_resume = deduce_left_margin(properties_of_keywords_in_resume,
visual_properties_of_resume)
# If at least three section keywords were written with capital, we guess, that all of them are with capitals.
if visual_properties_of_resume['number_of_capital_matches'] > 2:
properties_of_keywords_in_resume['section_keywords_written_in_capital'] = True
else:
properties_of_keywords_in_resume['section_keywords_written_in_capital'] = False
return properties_of_keywords_in_resume
def deduce_font_color(properties_of_keywords_in_resume, structural_properties_of_resume):
"""Takes the font-color that has at least 3 occurrences in all_caps_properties and
entire_match_properties. If the font-colors match it returns the font-color immediately. If not,
it returns the font-color with the more occurrences."""
all_caps_properties = {}
entire_match_properties = {}
# key = colors, value = frequency of color in section keywords
if bool(structural_properties_of_resume['all_caps_properties']['font_color']):
# sort keys (colors) in descending order of the occurrences
sorted_colors_by_occurrence = sorted(structural_properties_of_resume['all_caps_properties']['font_color'],
key=lambda k:
structural_properties_of_resume['all_caps_properties']['font_color'][k],
reverse=True)
for color in sorted_colors_by_occurrence:
if structural_properties_of_resume['all_caps_properties']['font_color'][color] > 2:
all_caps_properties[color] = \
structural_properties_of_resume['all_caps_properties']['font_color'][
color]
break
if bool(structural_properties_of_resume['entire_match_properties']['font_color']):
sorted_colors_by_occurrence = sorted(structural_properties_of_resume['entire_match_properties']['font_color'],
key=lambda k:
structural_properties_of_resume['entire_match_properties']['font_color'][
k],
reverse=True)
for color in sorted_colors_by_occurrence:
if structural_properties_of_resume['entire_match_properties']['font_color'][color] > 2:
entire_match_properties[color] = \
structural_properties_of_resume['entire_match_properties']['font_color'][
color]
break
if bool(all_caps_properties) and bool(entire_match_properties):
all_caps_color, all_caps_occurrence = all_caps_properties.popitem()
entire_match_color, entire_match_occurrence = entire_match_properties.popitem()
if all_caps_color == entire_match_color:
properties_of_keywords_in_resume['font_color'] = all_caps_color
return properties_of_keywords_in_resume
if all_caps_occurrence > entire_match_occurrence:
properties_of_keywords_in_resume['font_color'] = all_caps_color
return properties_of_keywords_in_resume
else:
properties_of_keywords_in_resume['font_color'] = entire_match_color
return properties_of_keywords_in_resume
# If only one of all_caps_properties / entire_match_properties exist --> take that.
if bool(all_caps_properties):
all_caps_color, all_caps_occurrence = all_caps_properties.popitem()
properties_of_keywords_in_resume['font_color'] = all_caps_color
return properties_of_keywords_in_resume
if bool(entire_match_properties):
entire_match_color, entire_match_occurrence = entire_match_properties.popitem()
properties_of_keywords_in_resume['font_color'] = entire_match_color
return properties_of_keywords_in_resume
return properties_of_keywords_in_resume
def deduce_font_size(properties_of_keywords_in_resume, structural_properties_of_resume):
"""Takes the largest font size that has more than 2 occurrences in all_caps_properties and
entire_match_properties. If the font-size matches it returns the font-size immediately. If not,
it returns the font-size with the more occurrences."""
all_caps_properties = {}
entire_match_properties = {}
if bool(structural_properties_of_resume['all_caps_properties']['font_size']):
keys = structural_properties_of_resume['all_caps_properties']['font_size'].keys()
sorted_float_keys = sorted([float(key[:-2]) for key in keys], reverse=True)
for float_key in sorted_float_keys:
string_key = str(float_key)
if string_key.endswith(".0"):
string_key = string_key[:-2]
if structural_properties_of_resume['all_caps_properties']['font_size'][string_key + "px"] > 2:
all_caps_properties[string_key + "px"] = \
structural_properties_of_resume['all_caps_properties']['font_size'][
string_key + "px"]
break
if bool(structural_properties_of_resume['entire_match_properties']['font_size']):
keys = structural_properties_of_resume['entire_match_properties']['font_size'].keys()
sorted_float_keys = sorted([float(key[:-2]) for key in keys], reverse=True)
for float_key in sorted_float_keys:
string_key = str(float_key)
if string_key.endswith(".0"):
string_key = string_key[:-2]
if structural_properties_of_resume['entire_match_properties']['font_size'][string_key + "px"] > 2:
entire_match_properties[string_key + "px"] = \
structural_properties_of_resume['entire_match_properties']['font_size'][
string_key + "px"]
break
if bool(all_caps_properties) and bool(entire_match_properties):
key_all, value_all = all_caps_properties.popitem()
key_entire, value_entire = entire_match_properties.popitem()
if key_all == key_entire:
properties_of_keywords_in_resume['font_size'] = key_all
return properties_of_keywords_in_resume
if value_all > value_entire:
properties_of_keywords_in_resume['font_size'] = key_all
return properties_of_keywords_in_resume
else:
properties_of_keywords_in_resume['font_size'] = key_entire
return properties_of_keywords_in_resume
if bool(all_caps_properties):
key_all, value_all = all_caps_properties.popitem()
properties_of_keywords_in_resume['font_size'] = key_all
return properties_of_keywords_in_resume
if bool(entire_match_properties):
key_entire, value_entire = entire_match_properties.popitem()
properties_of_keywords_in_resume['font_size'] = key_entire
return properties_of_keywords_in_resume
return properties_of_keywords_in_resume
def deduce_left_margin(properties_of_keywords_in_resume, structural_properties_of_resume):
"""Takes the smallest left margin that has more than 2 occurrences in all_caps_properties and
entire_match_properties. If both left_margin matched it returns the left_margin immediately. If not,
it returns the left_margin with the more occurrences."""
all_caps_properties = {}
entire_match_properties = {}
if bool(structural_properties_of_resume['all_caps_properties']['left_margin']):
keys = structural_properties_of_resume['all_caps_properties']['left_margin'].keys()
sorted_float_keys = sorted([float(key[:-2]) for key in keys], reverse=False)
for float_key in sorted_float_keys:
string_key = str(float_key)
if string_key.endswith(".0"):
string_key = string_key[:-2]
if structural_properties_of_resume['all_caps_properties']['left_margin'][string_key + "px"] > 2:
all_caps_properties[string_key + "px"] = \
structural_properties_of_resume['all_caps_properties']['left_margin'][
string_key + "px"]
break
if bool(structural_properties_of_resume['entire_match_properties']['left_margin']):
keys = structural_properties_of_resume['entire_match_properties']['left_margin'].keys()
sorted_float_keys = sorted([float(key[:-2]) for key in keys], reverse=False)
for float_key in sorted_float_keys:
string_key = str(float_key)
if string_key.endswith(".0"):
string_key = string_key[:-2]
if structural_properties_of_resume['entire_match_properties']['left_margin'][string_key + "px"] > 2:
entire_match_properties[string_key + "px"] = \
structural_properties_of_resume['entire_match_properties']['left_margin'][
string_key + "px"]
break
if bool(all_caps_properties) and bool(entire_match_properties):
key_all, value_all = all_caps_properties.popitem()
key_entire, value_entire = entire_match_properties.popitem()
if key_all == key_entire:
properties_of_keywords_in_resume['left_margin'] = key_all
return properties_of_keywords_in_resume
if value_all > value_entire:
properties_of_keywords_in_resume['left_margin'] = key_all
return properties_of_keywords_in_resume
else:
properties_of_keywords_in_resume['left_margin'] = key_entire
return properties_of_keywords_in_resume
if bool(all_caps_properties):
key_all, value_all = all_caps_properties.popitem()
properties_of_keywords_in_resume['left_margin'] = key_all
return properties_of_keywords_in_resume
if bool(entire_match_properties):
key_entire, value_entire = entire_match_properties.popitem()
properties_of_keywords_in_resume['left_margin'] = key_entire
return properties_of_keywords_in_resume
return properties_of_keywords_in_resume
def deduce_font_family(properties_of_keywords_in_resume, structural_properties_of_resume):
"""Takes the most used font family that has more than 2 occurrences in all_caps_properties and
entire_match_properties. If both font families are the same it returns the font family immediately. If not,
it returns the font family with the more occurrences."""
all_caps_properties = {}
entire_match_properties = {}
if bool(structural_properties_of_resume['all_caps_properties']['font_family']):
sorted_keys_by_value = sorted(structural_properties_of_resume['all_caps_properties']['font_family'],
key=lambda k:
structural_properties_of_resume['all_caps_properties']['font_family'][k],
reverse=True)
for key in sorted_keys_by_value:
if structural_properties_of_resume['all_caps_properties']['font_family'][key] > 2:
all_caps_properties[key] = \
structural_properties_of_resume['all_caps_properties']['font_family'][
key]
break
if bool(structural_properties_of_resume['entire_match_properties']['font_family']):
sorted_keys_by_value = sorted(structural_properties_of_resume['entire_match_properties']['font_family'],
key=lambda k:
structural_properties_of_resume['entire_match_properties']['font_family'][k],
reverse=True)
for key in sorted_keys_by_value:
if structural_properties_of_resume['entire_match_properties']['font_family'][key] > 2:
entire_match_properties[key] = \
structural_properties_of_resume['entire_match_properties']['font_family'][
key]
break
if bool(all_caps_properties) and bool(entire_match_properties):
key_all, value_all = all_caps_properties.popitem()
key_entire, value_entire = entire_match_properties.popitem()
if key_all == key_entire:
properties_of_keywords_in_resume['font_family'] = key_all
return properties_of_keywords_in_resume
if value_all > value_entire:
properties_of_keywords_in_resume['font_family'] = key_all
return properties_of_keywords_in_resume
else:
properties_of_keywords_in_resume['font_family'] = key_entire
return properties_of_keywords_in_resume
if bool(all_caps_properties):
key_all, value_all = all_caps_properties.popitem()
properties_of_keywords_in_resume['font_family'] = key_all
return properties_of_keywords_in_resume
if bool(entire_match_properties):
key_entire, value_entire = entire_match_properties.popitem()
properties_of_keywords_in_resume['font_family'] = key_entire
return properties_of_keywords_in_resume
return properties_of_keywords_in_resume
def break_resume_in_sections(resume_info, keywords_dict, visual_properties_of_keywords_in_resume):
"""Breaks the resume into sections (Skills, WorkExpereince), using the visual properties of keywords."""
result = defaultdict(list)
if not is_amount_of_visual_properties_data_satisfactory(visual_properties_of_keywords_in_resume):
print("Less then three visual properties were extracted for section keywords. "
"Resume was not broken into sections.")
return result
# Lines that were not recognized as section keyword will be put under this section in the output.
current_section_keyword = ""
for line in resume_info:
if line_has_visual_properties_of_section_keywords(line, visual_properties_of_keywords_in_resume):
# Check if line matches any section keyword, and if so get the matched section keyword
line_matches_section_keyword = False
section_keyword_match_found = section_keyword_matched_in_line(line, keywords_dict, current_section_keyword)
if current_section_keyword != section_keyword_match_found:
current_section_keyword = section_keyword_match_found
line_matches_section_keyword = True
# If not matched, but section_keywords are with capital, and line is capital -> it is probably section keyword
if not line_matches_section_keyword and line['line_text'].strip():
if visual_properties_of_keywords_in_resume['section_keywords_written_in_capital']:
if is_text_all_capital(line["line_text"]) and not clean_text_from_nonbasic_characters(
line['line_text']):
current_section_keyword = line['line_text']
# If keywords are with capital, but this text is not, then simply append to current section's text
else:
result[current_section_keyword].append(line['line_text'])
# Since line had visual properties of section keywords assume it is.
else:
current_section_keyword = line['line_text']
# If it's a normal line append it to the current section we are in.
elif current_section_keyword and line['line_text'].strip():
result[current_section_keyword].append(line['line_text'])
return result
def is_amount_of_visual_properties_data_satisfactory(visual_properties_of_keywords_in_resume):
"""If we have at least 4 visual properties (including capital keywords) OR
we have at least 3 AND we know that sections words are written with capitals return true."""
visual_property_names = list(visual_properties_of_keywords_in_resume.keys())
return len(visual_property_names) > 3 or \
(len(visual_property_names) == 3
and visual_properties_of_keywords_in_resume['section_keywords_written_in_capital'])
def line_has_visual_properties_of_section_keywords(line, visual_properties_of_keywords_in_resume):
"""Returns true if the line's given visual property is similar to the property of section keywords"""
result = True
for visual_property in visual_properties_of_keywords_in_resume.keys():
if visual_property != "section_keywords_written_in_capital":
if visual_properties_of_keywords_in_resume[visual_property] != line[visual_property]:
result = False
break
else:
if visual_properties_of_keywords_in_resume[visual_property]:
if line['line_text'] != line['line_text'].upper():
result = False
break
return result
def section_keyword_matched_in_line(line, keywords_dict, current_section_keyword):
"""Iterates over the section keyword dictionary and checks if the current line's text contains any of the
section keywords. If so, it returns the found section keyword. If no matches found returns current_section_keyword"""
for section_keyword_name, section_keyword_variations in keywords_dict.items():
for section_keyword in section_keyword_variations:
if (re.search(
section_keyword.upper(),
clean_text_from_nonbasic_characters(line['line_text']).upper())) is not None:
return section_keyword_name
return current_section_keyword
def is_text_all_capital(text):
"""Returns true of the entire text is written with capitals. False otherwise."""
return text == text.upper()
def parse_work_experience(resume_object, parsed_resume):
"""Identify individual work experiences, find the duration of the job and look for skills in their text."""
if 'WorkExperience' not in parsed_resume:
return parsed_resume
# Filter out empty lines and find the start and end index of the WE section in resume_object
parsed_resume_no_empty_lines = [line for line in parsed_resume['WorkExperience'] if
replace_newline_with_space(line).strip()]
filtered_resume_info = [line for line in resume_object if replace_newline_with_space(line['line_text'].strip())]
work_exp_indexes = find_workexperience_line_indexes_in_resume_object(parsed_resume_no_empty_lines,
filtered_resume_info)
# Create containers and append the first work expereince to our dictionary
job_experiences = []
job = {
'description': [],
'startDate': "",
'endDate': "",
"skills": []
}
job['description'].append(filtered_resume_info[work_exp_indexes["start_index"]]['line_text'])
complete_resume_text = get_complete_work_experince_text(work_exp_indexes, filtered_resume_info)
# Guess the number of experiences in the text, based on the found durations.
numer_of_expected_work_experiences = find_number_of_dates_in_text(complete_resume_text)
# Find end of section based on change in horizontal difference and left-margin difference
find_section_based_on_horizontal_diff_and_leftmargin_diff(work_exp_indexes, filtered_resume_info,
job_experiences, job)
# If we didn't find at least half of the experiences, find sections that were seperated by new lines.
if len(job_experiences) <= numer_of_expected_work_experiences / 2:
job_experiences_new = find_section_based_on_enter(resume_object, parsed_resume)
if len(job_experiences_new) > len(job_experiences):
job_experiences = job_experiences_new
# If we didn't find at least half of the experiences, find sections based only on the horizontal difference between lines.
if len(job_experiences) <= numer_of_expected_work_experiences / 2:
job_experiences_new = find_section_based_on_horizontal_diff_only(resume_object, parsed_resume)
if len(job_experiences_new) > len(job_experiences):
job_experiences = job_experiences_new
# If we didn't find at least half of the experiences, find sections based on left margin.
if len(job_experiences) <= numer_of_expected_work_experiences / 2:
job_experiences_new = find_section_based_on_left_margin_only(work_exp_indexes, filtered_resume_info)
if len(job_experiences_new) > len(job_experiences):
job_experiences = job_experiences_new
job_experiences = find_dates_in_job(job_experiences)
job_experiences = find_skills_in_job(job_experiences)
parsed_resume['WorkExperience'] = job_experiences
return parsed_resume
def find_workexperience_line_indexes_in_resume_object(parsed_resume_no_empty_lines, filtered_resume_info):
"""Finds the first and last indexes in resume_object, where the lines correspond to the work_experience.
Returns the index if found, else None."""
we_first_line_text = "" if not parsed_resume_no_empty_lines else parsed_resume_no_empty_lines[0]
we_last_line_text = "" if not parsed_resume_no_empty_lines else parsed_resume_no_empty_lines[-1]
first_line_index = 0
last_line_index = 0
if we_first_line_text and we_last_line_text:
for i, line in enumerate(filtered_resume_info):
if line['line_text'] == we_first_line_text:
first_line_index = i
if line['line_text'] == we_last_line_text:
last_line_index = i
return {'start_index': first_line_index, 'end_index': last_line_index}
def get_complete_work_experince_text(work_exp_indexes, filtered_resume_info):
"""Extract the text of a given work experience from the reusme, using the work_exp_indexes that
determint the start and end line (index) in the filtered_resume_info"""
text = ""
for index in range(work_exp_indexes['start_index'] + 1, work_exp_indexes['end_index'] + 1):
text += filtered_resume_info[index]['line_text'] + '\n'
return text
def find_number_of_dates_in_text(text):
"""Finds the number of durations in the text. (01/2016-02/2016 counts as one.)"""
dr = DateRegex(text)
return dr.find_number_of_durations()
def find_section_based_on_horizontal_diff_and_leftmargin_diff(work_exp_indexes, filtered_resume_info,
job_experiences, job):
"""Default work experience sectioning strategy, where both horizontal and vertical spacing is used to determine,
whether a new section is starting."""
previous_horizontal_diffs = []
if work_exp_indexes['start_index'] != 0 and work_exp_indexes['end_index'] != 0:
for index in range(work_exp_indexes['start_index'] + 1, work_exp_indexes['end_index'] + 1):
# New Section based on Horizontal change?
horizontal_space_diff_between_current_and_last_line = \
int(float(filtered_resume_info[index - 1]['bottom_margin'][:-2]) -
float(filtered_resume_info[index]['bottom_margin'][:-2]))
pageChange = filtered_resume_info[index]['page_number'] != filtered_resume_info[index - 1][
'page_number']
new_section_based_on_change_in_horizontal_distance = \
is_new_section_based_on_horizontal_difference(pageChange,
horizontal_space_diff_between_current_and_last_line,
previous_horizontal_diffs)
previous_horizontal_diffs.append(abs(horizontal_space_diff_between_current_and_last_line))
# New Section based on Left margin change?
new_section_based_on_change_in_left_margin = False
left_margin_diff_between_current_and_last_line = \
int(float(filtered_resume_info[index - 1]['left_margin'][:-2]) -
float(filtered_resume_info[index]['left_margin'][:-2]))
if left_margin_diff_between_current_and_last_line > 0:
new_section_based_on_change_in_left_margin = True
if new_section_based_on_change_in_horizontal_distance and new_section_based_on_change_in_left_margin:
job_experiences.append(job)
job = {
'description': [filtered_resume_info[index]['line_text']],
'startDate': "",
'endDate': "",
"skills": []
}
else:
job['description'].append(filtered_resume_info[index]['line_text'])
job_experiences.append(job)
def is_new_section_based_on_horizontal_difference(pageChange, horizontal_space_diff_between_current_and_last_line,
previous_horizontal_diffs):
"""
Returns true, if based on pageChange and horizontal-diff a new section is starting.
horizontal_space_diff is negative if:
- We are on a new page
- A new column started on the same page
If delta_H is positive and it is greater than the previous delta_H with at least * TRESHOLD times, then new section
"""
HORIZONTAL_DIFF_TRESHOLD = 1.4
if not previous_horizontal_diffs: return False
return pageChange or (horizontal_space_diff_between_current_and_last_line > 0 and
previous_horizontal_diffs and
horizontal_space_diff_between_current_and_last_line > (
previous_horizontal_diffs[-1] * HORIZONTAL_DIFF_TRESHOLD))
def find_section_based_on_enter(resume_object, parsed_resume):
"""A fallback work experience separation strategy, where blank lines are used to identify new sections."""
parsed_resume_no_empty_lines = [line for line in parsed_resume['WorkExperience'] if
replace_newline_with_space(line).strip()]
work_exp_indexes = find_workexperience_line_indexes_in_resume_object(parsed_resume_no_empty_lines,
resume_object)
job_experiences = []
job = {
'description': [],
'startDate': "",
'endDate': "",
"skills": []
}
job['description'].append(resume_object[work_exp_indexes["start_index"]]['line_text'])
we_found = False
if work_exp_indexes['start_index'] != 0 and work_exp_indexes['end_index'] != 0:
for index in range(work_exp_indexes['start_index'] + 1, work_exp_indexes['end_index'] + 1):
if not replace_newline_with_space(resume_object[index]['line_text']).strip():
we_found = True
job_experiences.append(job)
job = {
'description': [],
'startDate': "",
'endDate': "",
"skills": []
}
else:
job['description'].append(resume_object[index]['line_text'])
if we_found:
job_experiences.append(job)
return job_experiences
def find_section_based_on_horizontal_diff_only(resume_object, parsed_resume):
"""A fallback work experience separation strategy, where only the horizontal difference
is used to identify new sections."""
parsed_resume_no_empty_lines = [line for line in parsed_resume['WorkExperience'] if
replace_newline_with_space(line).strip()]
work_exp_indexes = find_workexperience_line_indexes_in_resume_object(parsed_resume_no_empty_lines,
resume_object)
job_experiences = []
job = {
'description': [],
'startDate': "",
'endDate': "",
"skills": []
}
job['description'].append(resume_object[work_exp_indexes["start_index"]]['line_text'])
previous_horizontal_diffs = []
we_found = False
if work_exp_indexes['start_index'] != 0 and work_exp_indexes['end_index'] != 0:
for index in range(work_exp_indexes['start_index'] + 1, work_exp_indexes['end_index'] + 1):
# New Section based on Horizontal change?
horizontal_space_diff_between_current_and_last_line = \
int(float(resume_object[index - 1]['bottom_margin'][:-2]) -
float(resume_object[index]['bottom_margin'][:-2]))
pageChange = resume_object[index]['page_number'] != resume_object[index - 1][
'page_number']
new_section_based_on_change_in_horizontal_distance = \
is_new_section_based_on_horizontal_difference(pageChange,
horizontal_space_diff_between_current_and_last_line,
previous_horizontal_diffs)
previous_horizontal_diffs.append(abs(horizontal_space_diff_between_current_and_last_line))
if new_section_based_on_change_in_horizontal_distance:
we_found = True
job_experiences.append(job)
job = {
'description': [resume_object[index]['line_text']],
'startDate': "",
'endDate': "",
"skills": []
}
else:
job['description'].append(resume_object[index]['line_text'])
if we_found:
job_experiences.append(job)
return job_experiences
def find_section_based_on_left_margin_only(work_exp_indexes, filtered_resume_info):
"""A fallback work experience separation strategy, where only the left margin is used to indentify new sections."""
job_experiences = []
job = {
'description': [],
'startDate': "",
'endDate': "",
"skills": []
}
job['description'].append(filtered_resume_info[work_exp_indexes["start_index"]]['line_text'])
we_found = False
if work_exp_indexes['start_index'] != 0 and work_exp_indexes['end_index'] != 0:
for index in range(work_exp_indexes['start_index'] + 1, work_exp_indexes['end_index'] + 1):
new_section_based_on_change_in_left_margin = False
left_margin_diff_between_current_and_last_line = \
int(float(filtered_resume_info[index - 1]['left_margin'][:-2]) -
float(filtered_resume_info[index]['left_margin'][:-2]))
if left_margin_diff_between_current_and_last_line > 0:
new_section_based_on_change_in_left_margin = True
if new_section_based_on_change_in_left_margin:
we_found = True
job_experiences.append(job)
job = {
'description': [filtered_resume_info[index]['line_text']],
'startDate': "",
'endDate': "",
"skills": []
}
else:
job['description'].append(filtered_resume_info[index]['line_text'])
if we_found:
job_experiences.append(job)
return job_experiences
def find_dates_in_job(job_experiences):
"""Finds the duration of each job experience and adds it to the given job's dictionary."""
for job in job_experiences:
job_text = get_full_job_description_text(job)
dr = DateRegex(job_text)
duration_dict = dr.calculate_experience_duration()
job['startDate'] = ""
job['endDate'] = ""
if duration_dict['start_month'] != -1 and duration_dict['start_year'] != -1:
job['startDate'] = '01.' + str(duration_dict['start_month']) + "." + str(duration_dict['start_year'])
if duration_dict['end_month'] != -1 or duration_dict['end_year'] != -1:
job['endDate'] = '01.' + str(duration_dict['end_month']) + "." + str(duration_dict['end_year'])
if duration_dict['start_month'] == -1 and duration_dict['end_month'] == -1 and \
duration_dict['start_year'] != -1 and duration_dict['end_year'] != -1:
job['startDate'] = '01.01.' + str(duration_dict['start_year'])
job['endDate'] = '31.12.' + str(duration_dict['end_year'])
return job_experiences
def get_full_job_description_text(job):
"""Returns the job_description as a continuous text, concatenated from the separate lines."""
job_text = ""
for line in job['description']:
job_text += (line + " ") # EOL " " to help date extraction
return job_text.replace(" ", " ")
def find_skills_in_job(job_experiences):
"""Looks through each job experiences and analyzes its text for known skills."""
for job in job_experiences:
job_text = get_full_job_description_text(job)
job_text = remove_end_of_sentence_punctuation(job_text)
if "skills" in job:
job["skills"] = find_skills_in_text(job_text.lower())
return job_experiences
def find_skills_in_text(text):
"""Looks through the entire skill section, looking for skills."""
skills = resource_string('resources.extracted-lists', "skills_to_find.txt").decode("utf-8",
"strict").splitlines()
skills.sort(key=len, reverse=True)
found_skills = []
for skill in skills:
match = re.search(r'((?<=^)|(?<=[^a-zA-Z\d]))' + re.escape(skill.lower()) + r'(?=$|[^a-zA-Z\d])', text.lower())
if match:
text = text.replace(match.group(), "")
found_skills.append(skill)
return found_skills
def find_skills_for_skill_learning(word, known_word_but_not_skill, found_skills_set):
"""Checks whether the given word is a skill, or not a skill."""
skills = resource_string('resources.extracted-lists', "skills_to_find.txt").decode("utf-8",
"strict").splitlines()
if word.lower() in known_word_but_not_skill:
return False
if word.lower() in skills:
if found_skills_set is not None:
found_skills_set.add(word.lower())
return True
known_word_but_not_skill.add(word.lower())
return False
def parse_skills(resume_dict):
"""Creates 'SkillsRecognizedInSkillSection' that contains the list of the recognized skills and creates
'SkillsCleaned' that contains the cleaned text of the skill section."""
if "Skills" in resume_dict:
skills_text = ""
for line in resume_dict["Skills"]:
skills_text += (line + " ")
skills_text = clean_text_for_skill_extraction(skills_text).lower()
skills_text = remove_end_of_sentence_punctuation(skills_text)
resume_dict["SkillsRecognizedInSkillSection"] = find_skills_in_text(skills_text)
resume_dict["SkillsCleaned"] = skills_text
return resume_dict
def learn_skills_from_resume(resume_dict):
"""Checks each word of the skill section, whether it is a known skill. If there is an unknown word, between to
known skill-words, then we can assume, that the word in the middle is also a skill, hence it is added to the skill
dictionary."""
skills_to_avoid = resource_string('resources.extracted-lists', "skills_to_avoid.txt").decode("utf-8",
"strict").splitlines()
if "Skills" in resume_dict:
skills_text = ""
for line in resume_dict["Skills"]:
skills_text += (line + " ")
skills_text = clean_text_for_skill_extraction(skills_text).lower()
skills_text = remove_end_of_sentence_punctuation(skills_text)
skills_list = skills_text.split(' ')
# Filter list from stopwords
stop_words = stopwords.words('english') + list(punctuation)
skills_list = [skill for skill in skills_list if skill not in stop_words]
known_words = set()
found_skills = set()
if len(skills_list) >= 3:
for x in range(1, len(skills_list) - 1):
prev_is_skill = find_skills_for_skill_learning(skills_list[x - 1], known_words, found_skills)
current_is_not_skill = not find_skills_for_skill_learning(skills_list[x], known_words, found_skills)
next_is_skill = find_skills_for_skill_learning(skills_list[x + 1], known_words, found_skills)
if prev_is_skill and current_is_not_skill and next_is_skill and skills_list[x].lower() not in skills_to_avoid:
file_path = path.relpath("resources/extracted-lists/skills_to_find.txt")
with open(file_path, "a") as myfile:
myfile.write("\n" + skills_list[x])
<file_sep>/cv-parser/resumeparser.py
import argparse
import sys
from main.parser import *
def create_arg_parser():
""""Creates and returns the ArgumentParser object."""
parser = argparse.ArgumentParser(description='Extract skills and work experience from IT-resumes.')
parser.add_argument('inputDirectory',
help='Path to the directory that contains the resumes.')
parser.add_argument('--targetDirectory',
help='Path to the target directory that will contain the output.')
return parser
def passed_arguments_are_correct(parsed_args):
"""Checks if the passed arguments are valid directories. Returns true if they are, false if not."""
if not os.path.isdir(parsed_args.inputDirectory):
print('Argument passed for inputDirectory is not valid. Please provide a valid directory!')
return False
if parsed_args.targetDirectory is not None:
if not os.path.isdir(parsed_args.targetDirectory):
print('Argument passed for targetDirectory is not valid. Please provide a valid directory!')
return False
return True
def start_resume_parsing(parsed_args):
"""Starts the resume parsing for each file found in the input directory"""
print('Parsing resumes in dir:', parsed_args.inputDirectory)
for root, dirs, files in os.walk(parsed_args.inputDirectory):
if files.__len__() == 0:
print("The directory doesn't contain any files!")
return
for filename in files:
if filename.endswith(".pdf") or filename.endswith(".PDF"):
file_path = os.path.join(root, filename)
parse_resume(file_path, parsed_args.targetDirectory)
def parse_resume(resume_path, target_dir):
"""Parses the resume provided in resume_path and puts the output in target_dir"""
renamed_resume_path = remove_blanks_from_filename(resume_path)
os.rename(resume_path, renamed_resume_path)
print("Processing: " + renamed_resume_path)
html_resume_path = convert_pdf_to_html(renamed_resume_path)
if html_resume_path is not None:
json_data = extract_information_into_json(html_resume_path)
filename = os.path.split(renamed_resume_path)[1]
if target_dir is None:
target_dir = os.path.split(renamed_resume_path)[0]
output_path = os.path.join(target_dir, os.path.splitext(filename)[0] + ".json")
with open(output_path, 'w') as outfile:
outfile.write(json_data + '\n')
def remove_blanks_from_filename(file_path):
new_name = file_path.replace(" ", "_")
return new_name
if __name__ == "__main__":
arg_parser = create_arg_parser()
parsed_args = arg_parser.parse_args(sys.argv[1:])
if passed_arguments_are_correct(parsed_args):
start_resume_parsing(parsed_args)
<file_sep>/requirements.txt
asn1crypto==0.23.0
attrs==17.2.0
Automat==0.6.0
certifi==2017.7.27.1
cffi==1.11.2
chardet==3.0.4
colorama==0.3.9
constantly==15.1.0
cryptography==2.1.1
cssselect==1.0.1
datefinder==0.6.1
hyperlink==17.3.1
idna==2.6
incremental==17.5.0
lxml==4.1.0
memory-profiler==0.51.0
nltk==3.2.5
nose==1.3.7
numpy==1.13.3
parsel==1.2.0
psutil==5.4.3
pyasn1==0.3.7
pyasn1-modules==0.1.5
pycparser==2.18
PyDispatcher==2.0.5
pyOpenSSL==17.3.0
python-dateutil==2.6.1
pytz==2017.3
queuelib==1.4.2
regex==2016.1.10
requests==2.18.4
Scrapy==1.4.0
selenium==3.6.0
service-identity==17.0.0
six==1.11.0
Twisted==17.9.0
urllib3==1.22
vmprof==0.4.10
w3lib==1.18.0
yappi==0.98
zope.interface==4.4.3
|
d77bcf1b8f1581a3c9db648a047a2d38cd0899ae
|
[
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 7 |
Dockerfile
|
supcomstudents/cv-parser
|
ffc855f2cd655f4881b1e8fb7c57250edd1a8609
|
ba044615b946cf745a441b911e1e86613dadde73
|
refs/heads/master
|
<repo_name>krzysztofpal/MnistRecognizer<file_sep>/MnistRecognizer/Modules/Database/Db.cs
using Microsoft.EntityFrameworkCore;
using MnistRecognizer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MnistRecognizer.Modules.Database
{
public class Db : DbContext
{
public const string connection_string = @"Server=(localdb)\mssqllocaldb;Database=MnistRecognizer;Trusted_Connection=True;ConnectRetryCount=0";
public Db(DbContextOptions<Db> options) : base(options)
{
}
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//{
// optionsBuilder.UseSqlServer(connection_string);
// base.OnConfiguring(optionsBuilder);
//}
public DbSet<HistoryModel> History { get; set; }
public DbSet<NetworkModel> Networks { get; set; }
public DbSet<Layer> Layers { get; set; }
}
}
<file_sep>/MnistRecognizer/Modules/Storage/IImageStore.cs
namespace MnistRecognizer.Modules.Storage
{
public interface IImageStore
{
string SaveImage(byte[] image, int image_class);
int ImagesCount();
string GetAbsolutePath(string type, string name);
string[] GetAllImagesNames(int type);
string ZipRepo();
string ZipImagesOfType(int type);
}
}<file_sep>/MnistRecognizer/Controllers/StorageController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MnistRecognizer.Modules.Database;
using MnistRecognizer.Modules.Storage;
namespace MnistRecognizer.Controllers
{
public class StorageController : Controller
{
INetworkProposalStorage storage;
private Db db;
public StorageController(INetworkProposalStorage storage, Db db)
{
this.storage = storage ?? throw new ArgumentNullException(nameof(storage));
this.db = db;
}
public IActionResult Index()
{
return View();
}
public IActionResult GetFiles()
{
var models = storage.GetModels(db);
return Json(models);
}
public IActionResult Zip()
{
var path = storage.Zip(db);
return PhysicalFile(path, "application/octet-stream", "Projekty_sieci.json");
}
}
}<file_sep>/MnistRecognizer/Controllers/MnistController.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MnistRecognizer.Models;
using MnistRecognizer.Modules.Database;
using MnistRecognizer.Modules.NeuralNetwork;
using MnistRecognizer.Modules.Storage;
namespace MnistRecognizer.Controllers
{
public class MnistController : Controller
{
IMnistInterpreter mnist;
IImageStore image_store;
INetworkProposalStorage network_store;
private Db db;
public MnistController(IMnistInterpreter mnist, IImageStore image_store, INetworkProposalStorage network_store, Db db)
{
this.mnist = mnist ?? throw new ArgumentNullException(nameof(mnist));
this.image_store = image_store ?? throw new ArgumentNullException(nameof(image_store));
this.network_store = network_store ?? throw new ArgumentNullException(nameof(network_store));
this.db = db;
}
public IActionResult Index()
{
return View();
}
public IActionResult NetworkDesigner()
{
return View();
}
[HttpPost]
public IActionResult SaveImage([FromBody]SaveImageData postdata)
{
var path = image_store.SaveImage(postdata.ImageBytes(), postdata.Number);
var image = new Bitmap(path);
var result = mnist.Evaluate(image);
var name = Path.GetFileName(path);
var history = new HistoryModel()
{
nazwaObrazka = name,
numerPrzedstawiany = postdata.Number,
results = result
};
db.Entry(history).State = EntityState.Added;
db.SaveChanges();
return Ok(result);
}
[HttpPost]
public IActionResult SaveNetwork([FromBody] NetworkModel model)
{
if(model == null)
throw new ArgumentNullException(nameof(model));
network_store.Save(model, db);
return Ok();
}
public IActionResult History()
{
var names = image_store.GetAllImagesNames(1);
var h = db.History.ToList();
return Json(h);
}
}
}<file_sep>/MnistRecognizer/Modules/NeuralNetwork/IMnistInterpreter.cs
using System.Drawing;
namespace MnistRecognizer.Modules.NeuralNetwork
{
public interface IMnistInterpreter
{
double[] Evaluate(Bitmap img);
}
}<file_sep>/MnistTester/Testers/XorTester.cs
using NNSharp.DataTypes;
using NNSharp.IO;
using System;
using System.Collections.Generic;
using System.Text;
namespace MnistTester.Testers
{
public class XorTester
{
public const string xor_path = @"C:\Users\Admin\source\repos\MnistRecognizer\Models\xor-release.json";
public IData Run()
{
var reader = new ReaderKerasModel(xor_path);
var model = reader.GetSequentialExecutor();
var arr = new Data2D(1, 1, 2, 4);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 2; j++)
{
arr[0, 0, j, i] = j == 0 ? i / 2 : i % 2;
}
}
Data2D result = model.ExecuteNetwork(arr) as Data2D;
return result;
}
}
}
<file_sep>/MnistRecognizer/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MnistRecognizer.Models;
using MnistRecognizer.Modules.Storage;
namespace MnistRecognizer.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IImageStore imageStore;
public HomeController(ILogger<HomeController> logger, IImageStore _imageStore)
{
_logger = logger;
imageStore = _imageStore;
}
public IActionResult Index()
{
int count = imageStore.ImagesCount();
return View(count);
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>/MnistRecognizer/Models/Layer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace MnistRecognizer.Models
{
public class Layer
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[ForeignKey(nameof(Network))]
public int NetworkID { get; set; }
public int KernelLength { get; set; }
public int KernelWidth { get; set; }
public int Stride { get; set; }
public int Padding { get; set; }
public virtual NetworkModel Network { get; set; }
}
}
<file_sep>/MnistRecognizer/Modules/Storage/ImageStore.cs
using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
namespace MnistRecognizer.Modules.Storage
{
public class ImageStore : IImageStore
{
private readonly IWebHostEnvironment host;
public ImageStore(IWebHostEnvironment _host)
{
host = _host;
}
public string SaveImage(byte[] image, int image_class)
{
string content_path = host.ContentRootPath;
string path_to_storage = Path.Combine(content_path, "image_store");
if (Directory.Exists(path_to_storage) == false)
Directory.CreateDirectory(path_to_storage);
string path_to_destination = Path.Combine(path_to_storage, image_class.ToString());
if (Directory.Exists(path_to_destination) == false)
Directory.CreateDirectory(path_to_destination);
string file_path = Path.Combine(path_to_destination, Guid.NewGuid().ToString() + ".png");
File.WriteAllBytes(file_path, image);
return file_path;
}
public int ImagesCount()
{
string content_path = host.ContentRootPath;
string path_to_storage = Path.Combine(content_path, "image_store");
if (Directory.Exists(path_to_storage) == false)
return 0;
int count = 0;
for(int i = 0; i < 10; i++)
{
string directory_path = Path.Combine(path_to_storage, i.ToString());
if (Directory.Exists(directory_path))
{
count += Directory.GetFiles(directory_path).Length;
}
}
return count;
}
public string GetAbsolutePath(string type, string name)
{
string path = Path.Combine(host.ContentRootPath, "image_store", type, name);
if (System.IO.File.Exists(path))
return path;
else
return null;
}
public string[] GetAllImagesNames(int type)
{
if (type < 0 || type > 9)
return null;
string path = Path.Combine(host.ContentRootPath, "image_store", type.ToString());
if (Directory.Exists(path) == false)
return null;
var files = Directory.GetFiles(path);
files = files.Select(x => Path.GetFileName(x)).ToArray();
return files;
}
public string ZipRepo()
{
string temp = Path.Combine(host.ContentRootPath, "temp.zip");
if (File.Exists(temp))
File.Delete(temp);
string path = Path.Combine(host.ContentRootPath, "image_store");
ZipFile.CreateFromDirectory(path, temp, CompressionLevel.Optimal, true);
return temp;
}
public string ZipImagesOfType(int type)
{
if (type < 0 || type > 9)
return null;
string path = Path.Combine(host.ContentRootPath, "image_store", type.ToString());
if (Directory.Exists(path) == false)
return null;
string temp = Path.Combine(host.ContentRootPath, "temp.zip");
if (File.Exists(temp))
File.Delete(temp);
ZipFile.CreateFromDirectory(path, temp, CompressionLevel.Optimal, true);
return temp;
}
}
}
<file_sep>/MnistRecognizer/Modules/Storage/INetworkProposalStorage.cs
using MnistRecognizer.Models;
using MnistRecognizer.Modules.Database;
using System.Collections.Generic;
namespace MnistRecognizer.Modules.Storage
{
public interface INetworkProposalStorage
{
void Save(NetworkModel model, Db db);
List<NetworkModel> GetModels(Db db);
string Zip(Db db);
}
}<file_sep>/MnistRecognizer/Models/HistoryModel.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace MnistRecognizer.Models
{
public class HistoryModel
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public int numerPrzedstawiany { get; set; }
public string nazwaObrazka { get; set; }
[NotMapped]
public double[] results
{
get => JsonConvert.DeserializeObject<double[]>(resultsString);
set => resultsString = JsonConvert.SerializeObject(value);
}
public string resultsString { get; set; }
}
}
<file_sep>/MnistTester/Program.cs
using NNSharp.DataTypes;
using NNSharp.IO;
using System;
using System.Drawing;
namespace MnistTester
{
class Program
{
const string xor_nn = @"C:\Users\Admin\source\repos\MnistRecognizer\Models\xor-release.json";
const string cnn_nn = @"C:\Users\Admin\source\repos\MnistRecognizer\Models\cnn-release.json";
const string zero_test_path = @"C:\Users\Admin\source\repos\MnistRecognizer\TestSamples\0.png";
static void Main(string[] args)
{
var reader = new ReaderKerasModel(cnn_nn);
var model = reader.GetSequentialExecutor();
var array = new Data2D(28, 28, 1, 1);
Bitmap img = new Bitmap(zero_test_path);
for(int i = 0; i < img.Height; i++)
{
for(int j = 0; j < img.Width; j++)
{
Color pixel = img.GetPixel(j,i);
double value = (pixel.R + pixel.G + pixel.B) / 3;
value = value / 255;
array[i, j, 0, 0] = value;
}
}
var result = model.ExecuteNetwork(array);
int a = 5;
}
}
}
<file_sep>/MnistRecognizer/Modules/Storage/NetworkProposalStorage.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using MnistRecognizer.Models;
using MnistRecognizer.Modules.Database;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace MnistRecognizer.Modules.Storage
{
public class NetworkProposalStorage : INetworkProposalStorage
{
IWebHostEnvironment host;
public NetworkProposalStorage(IWebHostEnvironment host)
{
this.host = host ?? throw new ArgumentNullException(nameof(host));
}
public void Save(NetworkModel model, Db db)
{
db.Entry(model).State = Microsoft.EntityFrameworkCore.EntityState.Added;
db.SaveChanges();
db.Entry(model).GetDatabaseValues();
model.Layers.ToList().ForEach(x => x.NetworkID = model.ID);
model.Layers.ToList().ForEach(x => db.Entry(x).State = Microsoft.EntityFrameworkCore.EntityState.Added);
db.SaveChanges();
}
public List<NetworkModel> GetModels(Db db)
{
var n = db.Networks.Include(x=>x.Layers).Where(x=>x.Layers != null && x.Layers.Count >= 2).ToList();
n.ForEach(x => x.Layers.ForEach(y => y.Network = null));
return n;
}
/// <summary>
/// Generates JSON file from all the history
/// </summary>
/// <returns></returns>
public string Zip(Db db)
{
var models = GetModels(db);
string temp = Path.Combine(host.ContentRootPath, "temp.json");
if (File.Exists(temp))
File.Delete(temp);
var json = JsonConvert.SerializeObject(models);
File.WriteAllText(temp, json);
return temp;
}
}
}
<file_sep>/MnistRecognizer/Modules/NeuralNetwork/MnistCnnNetwork.cs
using Microsoft.AspNetCore.Hosting;
using NNSharp.DataTypes;
using NNSharp.IO;
using NNSharp.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace MnistRecognizer.Modules.NeuralNetwork
{
public class MnistCnnNetwork : IMnistInterpreter
{
string cnn_nn => Path.Combine(host.ContentRootPath, "cnn-release.json");
SequentialModel model;
IWebHostEnvironment host;
public MnistCnnNetwork(IWebHostEnvironment host)
{
this.host = host;
}
public double[] Evaluate(Bitmap img)
{
if (model == null)
{
var reader = new ReaderKerasModel(cnn_nn);
model = reader.GetSequentialExecutor();
}
var array = new Data2D(28, 28, 1, 1);
for (int i = 0; i < img.Height; i++)
{
for (int j = 0; j < img.Width; j++)
{
Color pixel = img.GetPixel(j, i);
double value = 255 - pixel.A;
value = value / 255;
array[i, j, 0, 0] = value;
}
}
var result = model.ExecuteNetwork(array) as Data2D;
double[] toreturn = new double[10];
for (int i = 0; i < 10; i++)
{
toreturn[i] = result[0, 0, i, 0];
}
return toreturn;
}
}
}
<file_sep>/MnistRecognizer/Models/SaveImageData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MnistRecognizer.Models
{
public class SaveImageData
{
public string Base64 { get; set; }
public int Number { get; set; }
public byte[] ImageBytes()
{
return Convert.FromBase64String(Base64);
}
}
}
<file_sep>/MnistRecognizer/Controllers/GalleryController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using MnistRecognizer.Modules.Storage;
namespace MnistRecognizer.Controllers
{
public class GalleryController : Controller
{
IImageStore store;
public GalleryController(IImageStore store)
{
this.store = store;
}
public IActionResult Index()
{
return View();
}
public IActionResult Images(int type)
{
var data = store.GetAllImagesNames(type);
data = data.Select(x => $"/Gallery/GetImage?type={type}&name={x}").ToArray();
var model = new GalleryRequest()
{
Names = data,
Type = type
};
return View(model);
}
public class GalleryRequest
{
public int Type { get; set; }
public string[] Names { get; set; }
}
public IActionResult GetImage(string type, string name)
{
var path = store.GetAbsolutePath(type, name);
if(path != null)
return PhysicalFile(path, "image/png");
else return NotFound();
}
public IActionResult GetRepo()
{
var path = store.ZipRepo();
return PhysicalFile(path, "application/zip", "Repozytorium testowe.zip");
}
public IActionResult ZipImages(int type)
{
var path = store.ZipImagesOfType(type);
return PhysicalFile(path, "application/zip", $"Repozytorium testowe - {type}.zip");
}
}
}
|
047961619a0a78c8ffb6b2b8c61d3dbec80592e3
|
[
"C#"
] | 16 |
C#
|
krzysztofpal/MnistRecognizer
|
5b2f1fd6684a2c6c8e6ac41e21b7721de2b9f47d
|
c0f18a631f7a43cf5452ea0e65e3df330b26aa98
|
refs/heads/main
|
<repo_name>canvasdevelopers/slobjs<file_sep>/index.js
function runslobjs(options){
return true;
}
module.exports.slobjs=runslobjs;
|
74a27a0db06be368f978f993e78b6e6d9d5321da
|
[
"JavaScript"
] | 1 |
JavaScript
|
canvasdevelopers/slobjs
|
4e1e59db45a20108755161516f105e4671f9a800
|
2fdde040064f7d8b1d65962b0df20140d7110664
|
refs/heads/master
|
<file_sep>package com.msy.lyj.fragment;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import cn.bmob.v3.exception.BmobException;
import com.msy.lyj.R;
import com.msy.lyj.R.id;
import com.msy.lyj.activity.DetailActivity;
import com.msy.lyj.adapter.HomeFragmentListViewAdapter;
import com.msy.lyj.adapter.MyPagerFragmentAdapter;
import com.msy.lyj.application.MyApplication;
import com.msy.lyj.base.BaseActivity;
import com.msy.lyj.base.BaseFragment;
import com.msy.lyj.base.BaseInterface;
import com.msy.lyj.bean.ActionInfo;
import com.msy.lyj.utils.FindActionInfoUtils;
import com.msy.lyj.utils.FindActionInfoUtils.FindAllActionInfosListener;
import com.msy.lyj.view.utils.XListView;
import com.msy.lyj.view.utils.XListView.IXListViewListener;
public class HomeFragment extends BaseFragment implements BaseInterface,
android.view.View.OnClickListener {
private ImageView mHomeBack, mHomeSearch;// 控件对象
private XListView mHomeFragmentXListView;
private EditText mHomeEditText;
private View v;
private List<ActionInfo> actionInfos;//数据源
private HomeFragmentListViewAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_home, null);
return v;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews();
initDatas();
initViewOpras();
}
@Override
public void initViews() {
mHomeFragmentXListView = (XListView) findById(R.id.fragment_home_listview);
// mHomeBack.setOnClickListener(this);
// mHomeEditText.setOnClickListener(this);
// mHomeSearch.setOnClickListener(this);
}
@Override
public void initDatas() {
/***
*
* 初始化数据源,ListView适配操作
*
*/
actionInfos = new ArrayList<ActionInfo>();
actionInfos = (List<ActionInfo>) MyApplication.getDatas(true, "ActionInfos");
if (actionInfos == null) {
actionInfos = new ArrayList<ActionInfo>();
}
for (ActionInfo actionInfo : actionInfos) {
// LogI("从全局拿到的数据库活动的信息"+actionInfo.toString());
}
adapter = new HomeFragmentListViewAdapter(act,actionInfos);
mHomeFragmentXListView.setAdapter(adapter);
//查询数据库中的ActionInfo中的所有信息
FindActionInfoUtils.findAllActionInfos(1, null, 0, 0, new FindAllActionInfosListener() {
@Override
public void getActionInfo(List<ActionInfo> info,BmobException ex) {
if (ex == null) {
//Log.i("myTag", "查询成功!!!"+info.toString());
//把从服务器获取的数据保存到全局Map中
MyApplication.setDatas("ActionInfos", info);
//更新Adapter,实现刷新
adapter.updateDatas(info);
}else {
LogI("从服务器读取数据失败的原因"+ex.getErrorCode()+","+ex.getLocalizedMessage());
}
}
});
/**
*
* 获取全局的数据,如果它为空,需要去new ,,,,用刷新操作可以解决这个问题
*/
}
@Override
public void initViewOpras() {
//设置下拉刷新和加载的监听事件
mHomeFragmentXListView.setPullLoadEnable(true);
mHomeFragmentXListView.setPullRefreshEnable(true);
mHomeFragmentXListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ActionInfo object=(ActionInfo) parent.getItemAtPosition(position);
if(object==null){
return;
}
//toastInfoShort(object+"111");
Intent intent = new Intent(act,DetailActivity.class) ;
intent.putExtra("actionitem", object);
startActivity(intent);
}
});
mHomeFragmentXListView.setXListViewListener(new IXListViewListener() {
@Override
public void onRefresh() {
FindActionInfoUtils.findAllActionInfos(1, null, 0, 0, new FindAllActionInfosListener() {
@Override
public void getActionInfo(List<ActionInfo> info, BmobException ex) {
//从服务器 中获取数据,更新列表
adapter.updateDatas(info);
mHomeFragmentXListView.stopRefresh();
}
});
}
@Override
public void onLoadMore() {
//忽略n条从服务器中获取的数据
mHomeFragmentXListView.stopLoadMore();
}
});
}
/***
*
* 在Fragment中不能去用OnClick方法去实现监听
*
*/
// public void fragmenthomebackClick(View v) {
//
//
//
// }
@Override
public void onClick(View v) {
// switch (v.getId()) {
// case R.id.fragment_home_back:
//
// // mHomeBack.setImageAlpha(3);
//
// // 退出本系统
// /**
// *
// * getActivity和onAttach()方法都能够得到上下文环境
// *
// * Fragment相当于Activity的一个控件
// */
// AlertDialog.Builder builder = new Builder(getActivity());
//
// builder.setCancelable(false);
// builder.setTitle("提示");
// builder.setMessage("忍心抛弃我吗,主人");
// builder.setNegativeButton("取消", new OnClickListener() {
//
// @Override
// public void onClick(DialogInterface arg0, int arg1) {
//
// // mHomeBack.setImageAlpha(1);
// }
// });
//
// builder.setPositiveButton("确定", new OnClickListener() {
//
// @Override
// public void onClick(DialogInterface arg0, int arg1) {
// /**
// * 参数为0,表示正常退出,参数为1,表示不正常退出
// */
//
// System.exit(0);
//
// }
// });
//
// // 设置警告对话框的位置和透明度
// AlertDialog alertDialog = builder.create();
//
// Window window = alertDialog.getWindow();
// window.setGravity(Gravity.CENTER);
// WindowManager.LayoutParams wp = window.getAttributes();
// wp.alpha = 0.6f;
// window.setAttributes(wp);
// alertDialog.show();
//
// break;
//搜索框
// case R.id.fragment_home_searchinput:
//
// break;
//
// //搜索按钮
// case R.id.fragment_home_search:
//
// break;
}
}
<file_sep>package com.msy.lyj.adapter;
import java.util.List;
import com.msy.lyj.R;
import com.msy.lyj.base.BaseActivity;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/***
*
* MineFragmentÍđGirdViewÁ─╩╩┼ń▓┘θ└Ó
*
* @author Administrator
*
*/
public class MineFragmentGridViewAdapter extends BaseAdapter {
private Context context;
private List<String> datas;
private int[] mImgs = { R.drawable.my_youhui, R.drawable.my_shoucang,
R.drawable.my_send, R.drawable.my_order, R.drawable.my_gather,
R.drawable.my_shezhi };
public MineFragmentGridViewAdapter(List<String> datas, BaseActivity act) {
this.context = act;
this.datas = datas;
}
@Override
public int getCount() {
return datas.size();
}
@Override
public Object getItem(int position) {
return datas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View v, ViewGroup arg2) {
if (v == null) {
v = LayoutInflater.from(context).inflate(
R.layout.minefragment_girdview_item, null);
}
TextView mGirdViewItemTv = (TextView) v
.findViewById(R.id.minefragment_girdview_item_tv);
ImageView mGirdViewItemIv = (ImageView) v
.findViewById(R.id.minefragment_girdview_item_iv);
mGirdViewItemTv.setText(datas.get(position));
mGirdViewItemIv.setImageResource(mImgs[position]);
return v;
}
}
<file_sep>package com.msy.lyj.adapter;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import android.widget.Toast;
/***
*
* Viewpager的适配器
*
* ViewPager+Fragment数据源混合操作
*
*/
public class MyPagerFragmentAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerFragmentAdapter(FragmentManager fm,List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
<file_sep>
package com.msy.lyj.utils;
import java.io.File;
import android.content.Context;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class ImageLoaderutils {
private static ImageLoader loader;
private static ImageLoaderConfiguration.Builder confbuilder;
private static ImageLoaderConfiguration conf;
private static DisplayImageOptions.Builder optbuilder;
private static DisplayImageOptions opt;
//返回注册号的imageloader对象
public static ImageLoader getInstance(Context context)
{
loader=ImageLoader.getInstance();
confbuilder=new ImageLoaderConfiguration.Builder(context);
File file=new File("/mnt/sdcard/gather/imageloader");
//制定sdcard缓存的路径
confbuilder.discCache(new UnlimitedDiscCache(file));
//缓存的图片个数
confbuilder.discCacheFileCount(100);
//缓存的最大容量
confbuilder.discCacheSize(1024*1024*10*10);
conf=confbuilder.build();
loader.init(conf);
return loader;
}
//返回显示图片使得opt
public static DisplayImageOptions getOpt(int EmptyPicture,int FailPicture)
{
optbuilder=new DisplayImageOptions.Builder();
//uri 加载默认图片
optbuilder.showImageForEmptyUri(EmptyPicture);
//图片获取失败 加载的默认图片
optbuilder.showImageOnFail(FailPicture);
optbuilder.cacheInMemory(true);//做内存缓存
optbuilder.cacheOnDisc(true);//做硬盘缓存
opt=optbuilder.build();
return opt;
}
//返回显示图片使得opt ListView中 用户的头像
/*public static DisplayImageOptions getOpt2()
{
optbuilder=new DisplayImageOptions.Builder();
//uri 加载默认图片
optbuilder.showImageForEmptyUri(R.drawable.r7);
//图片获取失败 加载的默认图片
optbuilder.showImageOnFail(R.drawable.r7);
optbuilder.cacheInMemory(true);//做内存缓存
optbuilder.cacheOnDisc(true);//做硬盘缓存
opt=optbuilder.build();
return opt;
}
//返回显示图片使得opt ListView中 活动的图像
public static DisplayImageOptions getOpt3(int EmptyPicture,int FailPicture)
{
optbuilder=new DisplayImageOptions.Builder();
//uri 加载默认图片
optbuilder.showImageForEmptyUri(EmptyPicture);
//图片获取失败 加载的默认图片
optbuilder.showImageOnFail(FailPicture);
optbuilder.cacheInMemory(true);//做内存缓存
optbuilder.cacheOnDisc(true);//做硬盘缓存
opt=optbuilder.build();
return opt;
}*/
}
<file_sep>package com.msy.lyj.adapter;
import java.util.List;
import com.msy.lyj.R;
import com.msy.lyj.activity.DetailActivity;
import com.msy.lyj.base.BaseActivity;
import com.msy.lyj.bean.Messages;
import com.msy.lyj.utils.FindMessageInfoUtils.FindAllMessagesListener;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class DetailsListViewAdapter extends BaseAdapter {
Context context;
List<Messages> info;
public DetailsListViewAdapter(BaseActivity act, List<Messages> info) {
this.context = act;
this.info = info;
}
@Override
public int getCount() {
return info.size();
}
@Override
public Object getItem(int position) {
return info.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View v, ViewGroup arg2) {
if (v == null) {
v = LayoutInflater.from(context).inflate(R.layout.act_details_lv_item, null);
}
TextView tvUser = (TextView) v.findViewById(R.id.act_details_item_username_tv);
TextView tvMsg = (TextView) v.findViewById(R.id.act_details_item_message_tv);
tvUser.setText("ÆÀÂÛÈË£º "+info.get(position).getActionUser());
tvMsg.setText("ÆÀÂÛÄÚÈÝ£º "+info.get(position).getActionMessage());
return v;
}
}
<file_sep>package com.msy.lyj.activity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.ActionBar.LayoutParams;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;
import com.baidu.mapapi.search.core.PoiInfo;
import com.msy.lyj.R;
import com.msy.lyj.adapter.PublishSpinnerAdapter;
import com.msy.lyj.application.MyApplication;
import com.msy.lyj.baidumap.BaiduActivity;
import com.msy.lyj.base.BaseActivity;
import com.msy.lyj.base.BaseInterface;
import com.msy.lyj.bean.ActionInfo;
public class PublishActionActivity extends BaseActivity implements BaseInterface, OnClickListener {
private ImageView mPublishInsertPicture;// 点击添加图片
private LinearLayout mShowTime;// 显示时间
private DatePickerDialog mDatePickerDialog;// 日期选择对话框
private TextView mPublishTime;// 显示时间信息的控件
private Spinner mPublishSpinner;// Spinner控件
private String mStrSpinnerType;// 活动选择的类型值
private EditText mActionName, mActionDesc, mActionDetails, mActionRMB;// 键盘输入活动的名称、简介、详情
private String mStrActionName, mStrActionDesc, mStrActionDetails, mStrActionRMB;// 手机输入获取的值信息
private Button mPublishBtn;// 发布活动的点击按钮
// 数据源
private List<String> datas;
private String mStrDate;// 用户选择的日期
private String mStrTime;// 用户选择的时间
private TimePickerDialog mTimePickerDialog;// 时间选择对话框
private LinearLayout mAddPicLin1, mAddPicLin2;
private File savePublishPictureFile = new File("sdcard/actionpic.jpg");// 相片存储的位置
private List<Bitmap> mBitmaps = new ArrayList<Bitmap>();;// 存储选择添加到活动中的相片的集合
private LinearLayout mPublishSelectAddress;// 获取选择地点的控件
private TextView mPublishSelectAddressTv;// 地图显示在发布活动中的信息控件
private ActionInfo mActionInfo;// 包裹活动的bean类
private String mStrActionAddress; // 选择活动的地点
private String mStrActionCity; // 活动所在城市
private PoiInfo mcurrentpoiInfo;
private String[] filePublishPicPath;// 存储选择上传图片的url
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.act_public);
initViews();
initDatas();
initViewOpras();
}
@Override
public void initViews() {
// 获取添加图片的控件
mPublishInsertPicture = (ImageView) findById(R.id.act_public_action_iv_addpicture);
// 获取放置图片的控件
mAddPicLin1 = (LinearLayout) findById(R.id.act_publish_gather_send_img_add_lin1);
mAddPicLin2 = (LinearLayout) findById(R.id.act_publish_gather_send_img_add_lin2);
// 获取选择地点的控件对象
mPublishSelectAddress = (LinearLayout) findById(R.id.act_public_action_lin_address);
// 获取显示地点的文本对象
mPublishSelectAddressTv = (TextView) findById(R.id.act_publish_SelectAddressTv);
mPublishSelectAddress.setOnClickListener(this);
// 设置添加图片的点击操作
mPublishInsertPicture.setOnClickListener(this);
// 获取活动的信息
mActionName = (EditText) findById(R.id.act_publish_action_name);
//获取活动简介
mActionDesc = (EditText) findById(R.id.act_publish_action_desc);
mActionDetails = (EditText) findById(R.id.act_publish_action_details);
//mActionRMB = (EditText) findById(R.id.act_publish_action_rmb);
mPublishBtn = (Button) findById(R.id.act_publish_action_button);
// 时间的文本控件
mPublishTime = (TextView) findById(R.id.act_publish_tv_time);
// Spinner控件获取
mPublishSpinner = (Spinner) findById(R.id.act_publish_spinner);
// 获取时间的控件
mShowTime = (LinearLayout) findById(R.id.act_public_action_lin_time);
}
@Override
public void initDatas() {
// 获取当前时间的方法
final Calendar calendar = Calendar.getInstance();
// 创建时间、时期选择对话框对象
mDatePickerDialog = new DatePickerDialog(act, new OnDateSetListener() {
// 用户最终选择时间的回调方法
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
if (calendar.get(Calendar.YEAR) > year) {
toastInfoShort("时间选择有误");
return;
}
if (calendar.get(Calendar.YEAR) == year) {
if (calendar.get(Calendar.MONTH) > monthOfYear) {
toastInfoShort("时间选择有误");
return;
} else if (calendar.get(Calendar.MONTH) == monthOfYear) {
if (calendar.get(Calendar.DAY_OF_MONTH) > dayOfMonth) {
toastInfoShort("时间选择有误");
return;
}
}
}
mStrDate = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
if (mTimePickerDialog != null) {
mTimePickerDialog.show();
}
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
mTimePickerDialog = new TimePickerDialog(act, new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hour, int minute) {
if (calendar.get(Calendar.HOUR_OF_DAY) > hour) {
toastInfoShort("时间选择有误");
return;
} else if (calendar.get(Calendar.HOUR_OF_DAY) == hour) {
}
if (minute < 10) {
mStrTime = mStrDate + " " + hour + ":" + "0" + minute;
} else {
mStrTime = mStrDate + " " + hour + ":" + minute;
}
// 显示时间到时间控件上
mPublishTime.setText(mStrTime);
}
}, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
mShowTime.setOnClickListener(this);
datas = new ArrayList<String>();
datas.add("生活");
datas.add("人文");
datas.add("DIY");
datas.add("健康");
datas.add("经济");
datas.add("体育");
datas.add("历史");
datas.add("娱乐");
datas.add("科技");
datas.add("国际");
// Spinner的适配操作
mPublishSpinner.setAdapter(new PublishSpinnerAdapter(this, datas));
// 发布按钮的注册点击事件操作
mPublishBtn.setOnClickListener(this);
}
@Override
public void initViewOpras() {
// mPublishSpinner的回调监听事件
mPublishSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View item, int position, long flag) {
// 获取用户点击选取的活动类型
mStrSpinnerType = datas.get(position);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.act_public_action_lin_time:
// 展示用户选择的时间和日期
showTimes();
break;
case R.id.act_public_action_iv_addpicture:
// 跳转到相册
jumpPhoto();
break;
case R.id.act_public_action_lin_address:
// 跳转的百度Map
jumpBaiDuMap();
break;
case R.id.act_publish_action_button:
// 发布活动
publishAction();
break;
}
}
/**
*
* 发布活动
*/
private void publishAction() {
LogI("能进到发布活动点击事件");
mActionInfo = new ActionInfo();
mStrActionName = getTvContent(mActionName);
//新闻简介
mStrActionDesc = getTvContent(mActionDesc);
mStrActionDetails = getTvContent(mActionDetails);
mStrActionRMB = getTvContent(mActionRMB);
if (mStrActionName.equals("")) {
toastInfoShort("请输入活动名称");
return;
}
if (mStrActionDesc.equals("")) {
toastInfoShort("请输入活动简介");
return;
}
if (mStrActionDetails.length() < 6) {
toastInfoShort("活动详情最少输入六个数");
return;
}
if (mStrActionAddress == null) {
toastInfoShort("请选择活动地点");
return;
}
if (mStrTime == null) {
toastInfoShort("请选择活动开始时间");
return;
}
LogI("选择图片的个数" + mBitmaps.size());
Log.i("myTag", mBitmaps.size() + "");
if (mBitmaps.size() < 1) {
toastInfoShort("最少选择一张活动照片");
return;
}
// 批量上传图片
// 上传照片路径的url数组的集合
filePublishPicPath = new String[mBitmaps.size()];
// 把选择的图片上传到本地
// 默认存储在sdcard下
// File filepath = new
// File(Environment.getExternalStorageDirectory().getAbsolutePath());
for (int i = 0; i < mBitmaps.size(); i++) {
File filepath = new File("sdcard/action/upload");
/**
* mkdir:创建同级文件夹 mkdirs:创建分级文件夹
*/
if (!filepath.exists()) {
filepath.mkdirs();
}
File filepic = new File(filepath, "action-" + i + ".jpg");
try {
mBitmaps.get(i).compress(CompressFormat.JPEG, 100, new FileOutputStream(filepic));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
filePublishPicPath[i] = filepic.getAbsolutePath();
}
/***
*
* 上传图片到服务器的文件夹中
*
*
*/
final ProgressDialog progressDialog = progressDialogShows(false, "图片上传中", null);
BmobFile.uploadBatch(filePublishPicPath, new UploadBatchListener() {
int numPic = 0;
@Override
public void onSuccess(List<BmobFile> actionPics, List<String> urls) {
progressDialog.setMessage("正在上传第" + numPic + "张图片");
// 1、files-上传完成后的BmobFile集合,是为了方便大家对其上传后的数据进行操作,例如你可以将该文件保存到表中
// 2、urls-上传文件的完整url地址
/*
* if (urls.size() == filePublishPicPath.length) {//
* 如果数量相等,则代表文件全部上传完成 // do something progressDialog.dismiss();
* toastInfoShort("图片上传成功"); }
*/
if (numPic < mBitmaps.size()) {
return;
}
progressDialog.dismiss();
toastInfoShort("上传图片完成");
// 上传完成
// 把Bean对象上传到数据库表中
// 设置活动属性
// 获取当前的时间
Calendar calendar = Calendar.getInstance();
int years = calendar.get(Calendar.YEAR);
int months= calendar.get(Calendar.MONTH);
int days = calendar.get(Calendar.DAY_OF_MONTH);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
String date = years+"-"+months+"-"+days;
String mCurrentTime = null;
if (minute < 10) {
mCurrentTime = date +" "+ hours + ":0" + minute;
} else {
mCurrentTime =date +" "+hours + ":" + minute;
}
//Log.i("myTag", "当前的时间" + mCurrentTime);
mActionInfo.setActionCurrentTime(mCurrentTime);// 设置活动发布时的当前时间
mActionInfo.setActionName(mStrActionName); // 设置活动名称
mActionInfo.setActionClass(mStrSpinnerType); // 设置活动类别
mActionInfo.setActionDesc(mStrActionDesc); // 设置活动简介
mActionInfo.setActionDetails(mStrActionDetails);// 设置活动详情
mActionInfo.setActionSite(mStrActionAddress); // 设置活动地址
mActionInfo.setActionCity(mStrActionCity); // 设置活动所在城市
//mActionInfo.setActionRMB(mStrActionRMB); // 设置活动话费金额
mActionInfo.setActionTime(mStrTime); // 设置活动开始时间
mActionInfo.setActionPicture(actionPics);// 设置上传多张BmobFile类型的图片
mActionInfo.setActionUserId(MyApplication.userInfo.getObjectId()); // 设置上传活动的用户ID
mActionInfo.setActionPoint(
new BmobGeoPoint(mcurrentpoiInfo.location.longitude, mcurrentpoiInfo.location.latitude));
// 保存到数据库表中
mActionInfo.save(new SaveListener<String>() {
@Override
public void done(String objectId, BmobException ex) {
if (ex == null) {
toastInfoShort("创建数据成功:" + objectId);
finish();
} else {
Log.i("bmob", "失败:" + ex.getMessage() + "," + ex.getErrorCode());
}
}
});
}
@Override
public void onError(int statuscode, String errormsg) {
progressDialog.dismiss();
toastInfoShort("错误码" + statuscode + ",错误描述:" + errormsg);
}
@Override
public void onProgress(int curIndex, int curPercent, int total, int totalPercent) {
// 1、curIndex--表示当前第几个文件正在上传
// 2、curPercent--表示当前上传文件的进度值(百分比)
// 3、total--表示总的上传文件数
// 4、totalPercent--表示总的上传进度(百分比)
numPic = curIndex;
}
});
// 上传Bean类到数据库
}
// 跳转的百度Map
/****
*
*
* 获取到连接BaiduMap的key值: <KEY>
*/
private void jumpBaiDuMap() {
// 跳转到地图搜搜索页面
act.startActivity(new Intent(act, BaiduActivity.class));
}
// 跳转到相册
private void jumpPhoto() {
// 点击用户头像,跳到相册
Intent intent = new Intent(Intent.ACTION_PICK);
// 类型
intent.setType("image/*");
// 加一个裁剪效果 (第二个属性改为true,不能实现剪切的效果)
intent.putExtra("crop", "circleCrop");
// 裁剪的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// 裁剪的像素点
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
intent.putExtra("noFaceDetection", true);
// 存放的位置
intent.putExtra("output", Uri.fromFile(savePublishPictureFile));
startActivityForResult(intent, 666);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 666) {
LogI("头像上传把!!!!!!!!!" + requestCode);
// 上传到服务器的操作前的准备(把照片选择完之后发布在活动中)
upLoadServiceMachine();
}
}
private void upLoadServiceMachine() {
// 获取资源文件,,,此处模拟去操作去相册选择,,供以后使用
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
// R.drawable.more_juhui);
// 去相册拍完照之后返回的照片
Bitmap bitmap = BitmapFactory.decodeFile(savePublishPictureFile.getAbsolutePath());
mBitmaps.add(bitmap);
if (mBitmaps.size() < 4) {
// 每一次移除上次的错误
mAddPicLin1.removeAllViews();
for (int i = 0; i < mBitmaps.size(); i++) {
Bitmap currentBitmap = mBitmaps.get(i);
ImageView imageView = new ImageView(act);
// MarginLayoutParams marginLayoutParams = new
// MarginLayoutParams(imageView.getLayoutParams());
// marginLayoutParams.setMargins(10, 10, 10, 10);
// imageView.setLayoutParams(marginLayoutParams);
WindowManager manager = getWindowManager();
int width1 = manager.getDefaultDisplay().getWidth() / 5;
int height1 = width1 * 2 / 3;
//
// imageView.getLayoutParams().width = width1;
// imageView.getLayoutParams().height = height1;
imageView.setLayoutParams(new LayoutParams(width1, height1));
imageView.setImageBitmap(currentBitmap);
mAddPicLin1.addView(imageView);
}
mAddPicLin1.addView(mPublishInsertPicture);
} else if (mBitmaps.size() == 4) {
mAddPicLin1.removeView(mPublishInsertPicture);
Bitmap currentBitmap2 = mBitmaps.get(3);
ImageView imageView2 = new ImageView(act);
WindowManager manager = getWindowManager();
int width1 = manager.getDefaultDisplay().getWidth() / 5;
int height1 = width1 * 2 / 3;
imageView2.setLayoutParams(new LayoutParams(width1, height1));
imageView2.setImageBitmap(currentBitmap2);
mAddPicLin1.addView(imageView2);
mAddPicLin2.addView(mPublishInsertPicture);
} else if (4 < mBitmaps.size() && mBitmaps.size() <= 7) {
mAddPicLin2.removeAllViews();
for (int i = 4; i < mBitmaps.size(); i++) {
Bitmap currentBitmap2 = mBitmaps.get(i);
ImageView imageView2 = new ImageView(act);
WindowManager manager = getWindowManager();
int width1 = manager.getDefaultDisplay().getWidth() / 5;
int height1 = width1 * 2 / 3;
imageView2.setLayoutParams(new LayoutParams(width1, height1));
imageView2.setImageBitmap(currentBitmap2);
mAddPicLin2.addView(imageView2);
}
mAddPicLin2.addView(mPublishInsertPicture);
} else if (mBitmaps.size() == 8) {
mAddPicLin2.removeView(mPublishInsertPicture);
Bitmap currentBitmap2 = mBitmaps.get(3);
ImageView imageView2 = new ImageView(act);
WindowManager manager = getWindowManager();
int width1 = manager.getDefaultDisplay().getWidth() / 5;
int height1 = width1 * 2 / 3;
imageView2.setLayoutParams(new LayoutParams(width1, height1));
imageView2.setImageBitmap(currentBitmap2);
mAddPicLin2.addView(imageView2);
}
// 点击用户头像,跳到相册
/*
* Intent intent = new Intent(Intent.ACTION_PICK);
*
* // 类型 intent.setType("image/*");
*
* // 加一个裁剪效果 (第二个属性改为true,不能实现剪切的效果) intent.putExtra("crop",
* "circleCrop");
*
* // 裁剪的比例 intent.putExtra("aspectX", 1); intent.putExtra("aspectY",
* 1);
*
* // 裁剪的像素点 intent.putExtra("outputX", 300); intent.putExtra("outputY",
* 300);
*
* intent.putExtra("scale", true); intent.putExtra("return-data", true);
* intent.putExtra("noFaceDetection", true);
*
* // 存放的位置 intent.putExtra("output", Uri.fromFile(saveUserHeadFile ));
*
* startActivityForResult(intent, 666);
*/
}
// 返回,销毁此页面
public void fragmenthomebackClick(View v) {
act.finish();
}
private void showTimes() {
LogI("跳过来了");
if (mDatePickerDialog != null) {
mDatePickerDialog.show();
}
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
mStrActionAddress = (String) MyApplication.getDatas(false, "pointInfoname");
// String address = (String) MyApplication.getDatas(true,
// "pointInfoaddress");
mStrActionCity = (String) MyApplication.getDatas(false, "pointInfonamecity");
mcurrentpoiInfo = (PoiInfo) MyApplication.getDatas(false, "currentpoiInfo");
if (mStrActionAddress == null) {
return;
}
mPublishSelectAddressTv.setText(mStrActionAddress);
}
}
<file_sep># dashengxinwen
这是一款开源的项目
<file_sep>package com.msy.lyj.baidumap;
import java.util.List;
import android.app.Activity;
import android.opengl.Visibility;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.msy.lyj.R;
import com.msy.lyj.application.MyApplication;
/**
* key: <KEY>
*
*/
public class BaiduActivity extends Activity {
private MapView mMapView;// 展示地图数据的View
private BaiduMap mBaiduMap;// 百度地图的控制器
private PoiSearch mPoiSearch;// 检索对象
private EditText mEtInput;//输入要搜索的地点
private ImageView mIvSearch;//搜索的控件
private TextView mMarketextViewName;//弹出覆盖物点击事件的地点名称
private TextView mMarketextViewDesc;//弹出覆盖物点击事件的地点详情
private Button mMarkerBtnPosititity;//确认按钮
private Button mMarkerBtnNativitity;//取消按钮
private List<PoiInfo> poiInfos;//所有检索到的
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.act_baidumap_search);
// 获取地图控件引用
mMapView = (MapView) findViewById(R.id.bmapView);
mBaiduMap = mMapView.getMap();
// 获取控件
mEtInput = (EditText) findViewById(R.id.act_main_et);
mIvSearch = (ImageView) findViewById(R.id.act_main_iv);
// 第一步,创建POI检索实例
mPoiSearch = PoiSearch.newInstance();
// 第二步,创建POI检索监听者;当检索到数据时自动回调此方法
// 第三步,设置POI检索监听者;重写回调方法
mPoiSearch
.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
@Override
public void onGetPoiResult(PoiResult result) {
// if (result != null) {
// List<PoiInfo> resultPois = result.getAllPoi();
// PoiInfo poiInfo = resultPois.get(0);
// StringBuffer sb = new StringBuffer();
// sb.append("address:" + poiInfo.address).append(
// ",phone:" + poiInfo.phoneNum);
// Log.i("myTag", sb.toString());
// } else {
// Log.i("myTag", "没有检索到结果");
// }
if (result == null) {
return;
}
poiInfos = result.getAllPoi();//获取检索到的所有覆盖物
mBaiduMap.clear();
// 创建PoiOverlay
PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
// 设置overlay可以处理标注点击事件
mBaiduMap.setOnMarkerClickListener(overlay);
// 设置PoiOverlay数据
overlay.setData(result);
// 添加PoiOverlay到地图中
overlay.addToMap();
overlay.zoomToSpan();
return;
}
@Override
public void onGetPoiIndoorResult(PoiIndoorResult arg0) {
}
@Override
public void onGetPoiDetailResult(PoiDetailResult arg0) {
}
});
}
/**
* 搜索地点
*
* @param v
*/
public void onSearchPoiClick(View v) {
// 第四步,发起检索请求;
mPoiSearch.searchInCity((new PoiCitySearchOption())
.city(mEtInput.getText().toString().trim())
.keyword(mEtInput.getText().toString().trim()).pageNum(0));// 注意:页数
}
@Override
protected void onDestroy() {
super.onDestroy();
// 在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
// 在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
// 在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mMapView.onPause();
}
// 第一步,构造自定义 PoiOverlay 类;
private class MyPoiOverlay extends PoiOverlay {
public MyPoiOverlay(BaiduMap baiduMap) {
super(baiduMap);
}
@Override
public boolean onPoiClick(int index) {
super.onPoiClick(index);
final PoiInfo currentpoiInfo = poiInfos.get(index);
final View view = getLayoutInflater().inflate(R.layout.act_badidu_marker, null);
//获取点击覆盖物的名称和详细信息
mMarketextViewName = (TextView) view.findViewById(R.id.act_baidu_marker_tv_name);
mMarketextViewDesc = (TextView) view.findViewById(R.id.act_baidu_marker_tv_desc);
//获取确认、取消的监控
mMarkerBtnPosititity= (Button) view.findViewById(R.id.act_baidu_marker_btn1);
mMarkerBtnNativitity = (Button) view. findViewById(R.id.act_baidu_marker_btn2);
if (currentpoiInfo == null) {
return false;
}
//设置到控件上
mMarketextViewName.setText(currentpoiInfo.name);
mMarketextViewDesc.setText(currentpoiInfo.address);
//确认的点击操作
mMarkerBtnPosititity.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//把数据存储到全局,回显到发布页面
MyApplication.setDatas("pointInfoname", currentpoiInfo.name);
MyApplication.setDatas("pointInfoaddress", currentpoiInfo.address);
MyApplication.setDatas("pointInfocity", currentpoiInfo.city);
MyApplication.setDatas("currentpoiInfo", currentpoiInfo);
//关闭该Activity
finish();
}
});
//取消的点击操作
mMarkerBtnNativitity.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// v.callOnClick();
//隐藏布局
//view.setVisibility(View.GONE);
mBaiduMap.hideInfoWindow();
}
});
//创建InfoWindow展示的view
/*Button button = new Button(getApplicationContext());
button.setBackgroundResource(R.drawable.popup); */
//定义用于显示该InfoWindow的坐标点
//LatLng pt = new LatLng(39.86923, 116.397428);
//创建InfoWindow , 传入 view, 地理坐标, y 轴偏移量
InfoWindow mInfoWindow = new InfoWindow(view , currentpoiInfo.location, -27);
//显示InfoWindow
mBaiduMap.showInfoWindow(mInfoWindow);
return true;
}
}
}
<file_sep>package com.msy.lyj.activity;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.bmob.v3.exception.BmobException;
import com.msy.lyj.R;
import com.msy.lyj.adapter.MyPagerFragmentAdapter;
import com.msy.lyj.application.MyApplication;
import com.msy.lyj.base.BaseActivity;
import com.msy.lyj.base.BaseInterface;
import com.msy.lyj.bean.ActionInfo;
import com.msy.lyj.fragment.HomeFragment;
import com.msy.lyj.fragment.MessageFragment;
import com.msy.lyj.fragment.MineFragment;
import com.msy.lyj.fragment.MoreFragment;
import com.msy.lyj.utils.FindActionInfoUtils;
import com.msy.lyj.utils.FindActionInfoUtils.FindAllActionInfosListener;
public class HomeActivity extends BaseActivity implements BaseInterface,
OnClickListener {
private ViewPager mHomeViewPager;// ViewPager对象
private ImageView mAddImageView;//主页中Add按钮
private List<Fragment> fragments;
private DrawerLayout mHomeActDraw;
private LinearLayout mln_center,mln_left;
// 选项卡资源
private LinearLayout[] mLinears = new LinearLayout[4];
private ImageView[] mIvs = new ImageView[4];
private TextView[] mTvs = new TextView[4];
// 选项卡的id
private int[] mLinearIds = { R.id.act_home_shouye_lin,
R.id.act_home_xinxi_lin, R.id.act_home_wode_lin,
R.id.act_home_gengduo_lin };
private int[] mLinearIvIds = { R.id.act_home_shouye_lin_iv,
R.id.act_home_xinxi_lin_iv, R.id.act_home_wode_lin_iv,
R.id.act_home_gengduo_lin_iv };
private int[] mLinearTvIds = { R.id.act_home_shouye_lin_tv,
R.id.act_home_xinxi_lin_tv, R.id.act_home_wode_lin_tv,
R.id.act_home_gengduo_lin_tv };
// 图片中的资源
private int[] drawerOns = { R.drawable.tuijianon, R.drawable.redianon,
R.drawable.wo, R.drawable.chazhaoon };
private int[] drawerOffs = { R.drawable.tuijianoff, R.drawable.redianoff,
R.drawable.wo0, R.drawable.chazhaooff};
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.act_homes);
initViews();
initDatas();
initViewOpras();
}
@Override
public void initViews() {
for (int i = 0; i < 4; i++) {
mLinears[i] = (LinearLayout) findById(mLinearIds[i]);
mIvs[i] = (ImageView) findById(mLinearIvIds[i]);
mTvs[i] = (TextView) findById(mLinearTvIds[i]);
//ViewPager对象
mHomeViewPager = (ViewPager) findById(R.id.act_home_viewpager);
//Add按钮
mAddImageView = (ImageView) findById(R.id.act_home_jiahao);
//获取DrawLayout
mHomeActDraw = (DrawerLayout) findById(R.id.act_home_dl);
//获取DrawLayout的左右视图控件
mln_center = (LinearLayout) this.findViewById(R.id.lin_center);
mln_left = (LinearLayout) this.findViewById(R.id.lin_left);
mAddImageView.setOnClickListener(this);
mLinears[i].setOnClickListener(this);
}
}
@Override
public void initDatas() {
/***
* 監聽抽屉的事件
*/
mHomeActDraw.setDrawerListener(new DrawerListener() {
float fromX = 1.0f;
float fromY = 1.0f;
/***
* 状态发生时回调
*
* 回调中:1、回调结束
* 2、恢复闲置:0
*/
@Override
public void onDrawerStateChanged(int arg0) {
}
/***
* 滑动的百分比
*
*/
@Override
public void onDrawerSlide(View arg0, float arg1) {
if (arg0 == mln_left) {
//mln_center.setX(200*(arg1*100.0f)/100.0f);
float toX = 1-(arg1*0.1f);
ScaleAnimation scaleAnimation = new ScaleAnimation(
fromX,
toX,
fromY,
toX,
ScaleAnimation.RELATIVE_TO_SELF,1.0f,
ScaleAnimation.RELATIVE_TO_SELF,1.0f);
fromX = toX;
fromY = toX;
scaleAnimation.setDuration(2);
scaleAnimation.setFillAfter(true);
mln_center.startAnimation(scaleAnimation);
}
}
@Override
public void onDrawerOpened(View arg0) {
}
@Override
public void onDrawerClosed(View arg0) {
}
});
//fragment数据源的初始化
fragments = new ArrayList<Fragment>();
fragments.add(new HomeFragment());
fragments.add(new MessageFragment());
fragments.add(new MineFragment());
fragments.add(new MoreFragment());
//Log.i("myTag", fragments.size()+"");
mHomeViewPager.setAdapter(new MyPagerFragmentAdapter(getSupportFragmentManager(),fragments));
}
@Override
public void initViewOpras() {
mHomeViewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int i) {
sollckClick(i);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
/***
*
* 选项卡的点击事件
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.act_home_shouye_lin:
sollckClick(0);
mHomeViewPager.setCurrentItem(0);
break;
case R.id.act_home_xinxi_lin:
sollckClick(1);
mHomeViewPager.setCurrentItem(1);
break;
case R.id.act_home_wode_lin:
sollckClick(2);
mHomeViewPager.setCurrentItem(2);
break;
case R.id.act_home_gengduo_lin:
sollckClick(3);
mHomeViewPager.setCurrentItem(3);
break;
case R.id.act_home_jiahao:
startActivity(new Intent(this,PublishActionActivity.class));
break;
}
}
/**
* 选项卡的切换操作
* @param i 用户点击的操作
*/
private void sollckClick(int i) {
for (int j = 0; j < 4; j++) {
if (i == j) {
mIvs[i].setImageResource(drawerOns[i]);
}else {
mIvs[j].setImageResource(drawerOffs[j]);
}
}
}
/**
*
* 双击退出
*/
private boolean flag = false;
@Override
public void onBackPressed() {
if (flag) {
//退出
//退出的方法
super.onBackPressed();
}else {
toastInfoShort("再按一次返回键退出本应用");
flag = true;
//线程一定要开启
new Thread(){
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
flag = false;
};
}.start();
}
}
}
<file_sep>package com.msy.lyj.fragment;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import c.system;
import cn.bmob.v3.exception.BmobException;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.View.OnClickListener;
import java.util.List;
import com.msy.lyj.R;
import com.msy.lyj.activity.FindActionInfosActivity;
import com.msy.lyj.adapter.MyMoreGridViewAdapter;
import com.msy.lyj.application.MyApplication;
import com.msy.lyj.base.BaseFragment;
import com.msy.lyj.base.BaseInterface;
import com.msy.lyj.bean.ActionInfo;
import com.msy.lyj.utils.FindActionInfoUtils;
import com.msy.lyj.utils.FindActionInfoUtils.FindAllActionInfosListener;
public class MoreFragment extends BaseFragment implements BaseInterface,
OnClickListener {
// 免费,热度,附近的按钮
private Button hotBtn, nearBtn;
private WebView mMoreFragmentWebView;
private TextView mTopTv;
private ImageView mBack;// 上方的返回按钮
// private String[] datas = {"北京","天津","南京","郑州","平顶山","周口","杭州","上海"};
// GridView数据
private GridView moreGridView;
public String[] names = { "生活", "人文", "DIY", "健康", "经济", "体育", "历史", "娱乐",
"科技", "国际" };
public int[] imgs = { R.drawable.more_zhoubian, R.drawable.more_shaoer,
R.drawable.more_diy, R.drawable.more_jianshen,
R.drawable.more_jishi, R.drawable.more_yanchu,
R.drawable.more_zhanlan, R.drawable.more_shalong,
R.drawable.more_pincha, R.drawable.more_juhui };
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_more, null);
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
initViews();
initDatas();
initViewOpras();
}
@Override
public void initViews() {
// 免费,热度,附近的按钮
// freeBtn = (Button) act.findViewById(R.id.frag_more_free_btn);
hotBtn = (Button) act.findViewById(R.id.frag_more_hot_btn);
nearBtn = (Button) act.findViewById(R.id.frag_more_near_btn);
// GridView
moreGridView = (GridView) act.findViewById(R.id.frag_more_gridview);
mMoreFragmentWebView = (WebView) act
.findById(R.id.more_fragment_webview);
mTopTv = (TextView) act.findViewById(R.id.more_fragment_top_tv);
mBack = (ImageView) findById(R.id.more_fragment_top_back);
}
@Override
public void initDatas() {
// 给免费,热度,附近的按钮添加点击时间
// freeBtn.setOnClickListener(this);
hotBtn.setOnClickListener(this);
nearBtn.setOnClickListener(this);
mBack.setOnClickListener(this);
// GridView操作
moreGridView.setAdapter(new MyMoreGridViewAdapter(act, names, imgs));
}
@Override
public void initViewOpras() {
moreGridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String actionType = names[position];
FindActionInfoUtils.findAllActionInfos(4, actionType, 0, 0,
new FindAllActionInfosListener() {
@Override
public void getActionInfo(List<ActionInfo> info,
BmobException ex) {
if (ex == null) {
Intent intent = new Intent(act,
FindActionInfosActivity.class);
MyApplication.setDatas("actionInfos", info);
MyApplication.setDatas("actionType",
actionType);
startActivity(intent);
}
}
});
}
});
/**
* 默认是去调用浏览器来加载页面数据
*/
if (mMoreFragmentWebView == null) {
return;
}
mMoreFragmentWebView.loadUrl("http://www.baidu.com");
// 设置支持js
mMoreFragmentWebView.getSettings().setJavaScriptEnabled(true);
/**
* Client:帮助webView去处理各种通知,或者请求事件
*/
mMoreFragmentWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i("myTag", "url:" + url);
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, url);
}
});
/**
* ChromeClient:帮助webView去处理Js的事件,网站的标题,加载的进度
*/
mMoreFragmentWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
// MainActivity.this.setTitle(title);
mTopTv.setText(title);
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
// //免费的监听
// case R.id.frag_more_free_btn:
//
// FindActionInfoUtils.findAllActionInfos(6, null, 0, 0, new
// FindAllActionInfosListener() {
//
// @Override
// public void getActionInfo(List<ActionInfo> info, BmobException ex) {
//
//
// if (ex == null) {
//
// Intent intent = new Intent(act, FindActionInfosActivity.class);
// MyApplication.setDatas("actionInfos", info);
// MyApplication.setDatas("actionType", "免费");
// startActivity(intent);
//
// }
//
// }
// });
// break;
// 热门的监听
case R.id.frag_more_hot_btn:
FindActionInfoUtils.findAllActionInfos(7, null, 0, 0,
new FindAllActionInfosListener() {
@Override
public void getActionInfo(List<ActionInfo> info,
BmobException ex) {
if (ex == null) {
Intent intent = new Intent(act,
FindActionInfosActivity.class);
MyApplication.setDatas("actionInfos", info);
MyApplication.setDatas("actionType", "热点");
startActivity(intent);
}
}
});
break;
// 附近的监听
case R.id.frag_more_near_btn:
FindActionInfoUtils.findAllActionInfos(8, null, 0, 0,
new FindAllActionInfosListener() {
@Override
public void getActionInfo(List<ActionInfo> info,
BmobException ex) {
if (ex == null) {
Intent intent = new Intent(act,
FindActionInfosActivity.class);
MyApplication.setDatas("actionInfos", info);
MyApplication.setDatas("actionType", "附近");
startActivity(intent);
}
}
});
break;
case R.id.more_fragment_top_back:
AlertDialog.Builder builder = new Builder(act);
builder.setCancelable(false);
builder.setTitle("温馨提示");
builder.setMessage("您确定要离开我吗,主人");
builder.setPositiveButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
builder.setNegativeButton("确认",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
System.exit(0);
}
});
// 设置警告对话框的位置和透明度
AlertDialog alertDialog = builder.create();
Window window = alertDialog.getWindow();
window.setGravity(Gravity.CENTER);
WindowManager.LayoutParams wp = window.getAttributes();
wp.alpha = 0.6f;
window.setAttributes(wp);
alertDialog.show();
break;
}
}
}
|
d0e96a2d478d844d45e67044569262aebe934ad4
|
[
"Markdown",
"Java"
] | 10 |
Java
|
hongquanyingma/dashengxinwen
|
13ff0c7837c00b13e9b6000ec59521a3360be3e3
|
d5c50958da35ef695267d84e9b05516012fc86da
|
refs/heads/master
|
<repo_name>DreamVB/File-Lister<file_sep>/FileLister.py
import glob
import sys
# Open html include file
f = open("inc\\html.inc","r")
# Check file mode
if f.mode == "r":
# Read the contents of file into header
header = f.read()
# Close file
f.close()
footer = """ </body>
</html>"""
if len(sys.argv) < 3:
print("Folder path is required.")
exit(1)
# Get the path that we will be scaning
scan_path = sys.argv[1]
outfile = sys.argv[2]
# Extract scan folder path
lz_path = scan_path[0:scan_path.rindex("\\") + 1]
# Set buffer to html include data
strbuff = header
# Add page header
strbuff += "<span class='path'>" + lz_path + "</span>"
# Add tag for unsorted list
strbuff += "<ul>\n"
# Get a list of files.
results = glob.glob(scan_path)
# Check that files were found
if len(results) == 0:
print("Not files were found in the selected path.")
exit(1)
# Print files
for file in results:
# Extract filename
lz_file = file[file.rindex("\\") + 1:]
# Add html list tag to final data
strbuff += "<li><a href=" + lz_file + ">" + lz_file + "</a></li>\n"
# Add html ending tags for unordered list
strbuff += "<ul></div>\n"
# Add html footer
strbuff += footer
# Save the data to the output filename
f = open(outfile,"w")
f.write(strbuff)
f.close()
<file_sep>/README.md
# File-Lister
Output a HTML display of files in a folder
<h3>How to use the script</h3>
Open a new console window and type<br>
<code>py FileLister.py c:\windows\system32\*.dll output.html</code>
<br>
The above example will create a html file with all dynamic dll files in the system folder.
|
520e271d1399a1e90482dfd00b16b526615e22a9
|
[
"Markdown",
"Python"
] | 2 |
Python
|
DreamVB/File-Lister
|
f40f14c1312ee2c9a851d1e075ddde9b37f998f5
|
0587bf8cba77d0dc7ba438aed00e57b536683e28
|
refs/heads/master
|
<file_sep># Bootcamp-ES6-1of3
Makeup assignment for University of Minnesota Coding Boot Camp
This Javascript ES6 and React application dynamically populates a friends list with characters from two JSON files.
Javascript ES6 syntax used in this project:
-variable declarations let and const
-the string method startsWith
-ternary conditional notation a ? b : c
-arrow notation for functions
-ES2015 modules
-classes
<file_sep>import React from "react";
import Wrapper from "./components/Wrapper";
import Title from "./components/Title";
import FriendCard from "./components/FriendCard";
import friends from "./friends.json";
import dextersLab from "./dexter.json";
var allFriends = [...friends, ...dextersLab];
console.log(allFriends);
class App extends React.Component {
state = {
allFriends: allFriends
};
remove = (id) => {
this.setState({
allFriends: this.state.allFriends.filter(function (friend) {
return friend.id !== id;
})
});
}
render() {
return (
<Wrapper>
<Title>Friends List</Title>
{allFriends.map((friend) => <FriendCard
id={friend.id}
image={friend.image}
location={friend.location}
name={friend.name}
occupation={friend.occupation}
startsWithS={friend.name.startsWith("S") ? "true": "false"}
remove={this.remove}
/>)}
</Wrapper>
);
}
}
export default App;
|
7fd5ca7b16f89da8a87092460e8c9c406078711a
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
craigcorsi/Bootcamp-ES6-1of3
|
991ef09bd4ce1a6507f64fb8c76aeb3b5f88bbf1
|
3976935a18381d09effbacd3443bc92f0c8b4b9a
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import allure
import pytest
import time
from selenium import webdriver
@allure.feature("百度搜索")
@pytest.mark.parametrize("test_data1", ["allure", "pytest", "unittest"])
def test_steps_demo(test_data1):
with allure.step("打开百度网页"):
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
with allure.step(f"输入搜索词:{test_data1}"):
driver.find_element_by_id("kw").send_keys(test_data1)
time.sleep(2)
driver.find_element_by_id("su").click()
time.sleep(2)
with allure.step("保存图片"):
driver.save_screenshot("./screenshots/baidu.jpg")
allure.attach.file("./screenshots/baidu.jpg", name="百度搜索截图", attachment_type=allure.attachment_type.JPG)
with allure.step("关闭浏览器"):
driver.quit()<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/12 23:40
# @Author : Yuki
import yaml
import pytest
class Test_yamlDemo:
@pytest.mark.parametrize("evn", yaml.safe_load(open("./evn.yml")))
def test_readyaml(self, evn):
if "test" in evn:
print("这是测试环境的ip:", evn["test"])
# print(evn)
elif "dev" in evn:
print("这是开发环境", evn["dev"])
# print(evn)
def test_yaml(self):
print(yaml.safe_load(open("./evn.yml")))<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 20:30
# @Author : Yuki
from selenium.webdriver.common.by import By
from pageobject.page.add_member_page import AddMemberPage
from pageobject.page.base_page import BasePage
from pageobject.page.contact_page import ContactPage
class MainPage(BasePage):
_base_url = "https://work.weixin.qq.com/wework_admin/frame#index"
def goto_contact(self):
self._driver.find_element(By.CSS_SELECTOR, ".frame_nav_item_title").click()
return ContactPage(self._driver)
def goto_add_member(self):
self._driver.find_element(By.CSS_SELECTOR, ".index_service_cnt_itemWrap:nth-child(1)").click()
return AddMemberPage(self._driver)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/17 20:40
# @Author : Yuki
from time import sleep
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
"""
强制等待
sleep(3)
隐式等待:设置一个等待时间,轮询查找(默认0.5s)元素是否出现,如果没有出现就抛出异常,是一个全局的等待
self.driver.implicitly_wait(3)
显示等待:在代码中定义等待条件,当条件发生时才继续执行代码。
程序每隔一段时间(默认0.5s)进行条件判断,如果条件成立,则执行下一步,否则继续等待,直到超过设置的最长时间
"""
class TestHogwarts():
def setup(self):
# 实例化driver
self.driver = webdriver.Firefox()
# 窗口最大化
self.driver.maximize_window()
# 设置隐式等待,使用后无需在方法中每句代码后再去添加sleep()方法;而是自行每步等待5s,使之可以有时间找到元素继续测试,避免网速慢等原因导致元素未被加载,从而导致用例执行失败
self.driver.implicitly_wait(5)
def teardown(self):
# 回收driver
self.driver.quit()
def test_hogwarts(self):
# 通过driver.get打开一个url
self.driver.get("https://ceshiren.com/")
self.driver.find_element_by_link_text("精华帖").click()
"""
# 显示等待中的自定义函数方法;该方法必须要写一个参数-->因为until调用wait函数时,把self.driver传给了wait
def wait(x):
return len(self.driver.find_elements_by_css_selector("#show-tag-info > .d-button-label")) >= 1
# 显示等待,当wait()函数中返回的该元素个数(len代表个数)>=1,则继续执行。否则在设置的10s达到之前,继续等待
# 传参时,wait不能加(),否则意味着调用,不会再传参
WebDriverWait(self.driver, 10).until(wait)
self.driver.find_element_by_link_text("BAT 大厂测试开发技能成长最佳实践 | 霍格沃兹测试学院课程体系").click()
"""
# 也可以不去自定义方法,采用内置方法
WebDriverWait(self.driver, 10).until(
expected_conditions.element_to_be_clickable((By.XPATH, '//*[@id="show-tag-info"]')))
self.driver.find_element_by_link_text("BAT 大厂测试开发技能成长最佳实践 | 霍格沃兹测试学院课程体系").click()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/20 20:30
# @Author : Yuki
def test_search1(coonDB):
print("search1")
def test_search2(coonDB):
print("search2")<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/3 23:15
# @Author : Yuki
"""
模块:
包含python定义和语句的文件
.py文件
可以作为脚本运行
模块的导入
1、import 模块名
2、from 模块名 import <方法 | 变量 | 类>
3、from 模块名 import *
常用方法:
dir() 找出当前模块定义的对象
dir(sys) 找出参数模块定义的对象
"""
import sys
print("\n", dir(sys))
print("\n", sys.path)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/18 13:08
# @Author : Yuki
import time
print(time.asctime())
print(time.time()) # 时间戳
print(time.localtime())
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
# 获取两天前的时间
now_timestamp = time.time()
two_day_before = now_timestamp - 60*60*24*2
time_tuple = time.localtime(two_day_before)
print(time.strftime("%Y-%m-%d %H:%M:%S", time_tuple))<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 20:35
# @Author : Yuki
from pageobject.page.base_page import BasePage
from pageobject.page.main_page import MainPage
class TestAddMember:
# def setup_class(self):
# # 实例化类,使之可以调用所属方法
# self.main = MainPage()
def test_add_member(self):
self.main = MainPage()
result = self.main.goto_add_member().add_member().get_memeber_list()
assert "Ben" in result
#
# def test_contact_add_member(self):
# self.main.goto_contact().goto_add_member().add_member()
#
# def teardown(self):
# self.main._driver.quit()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/19 22:22
# @Author : Yuki
import pytest
from typing import List
def pytest_collection_modifyitems(
session: "Session", config: "Config", items: List["Item"]
) -> None:
for item in items:
item.name = item.name.encode('utf-8').decode('unicode-escape')
item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')
# scope="session" 整个session域只执行一次
@pytest.fixture(scope="session")
def coonDB():
print("连接数据库")
yield
print("断开数据库连接")
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/29 20:29
# @Author : Yuki
"""
1、启动app
2、关闭app
3、重启app
4、进入首页
"""
from appium import webdriver
from appium_test.page.base_page import BasePage
from appium_test.page.main_page import MainPage
class App(BasePage):
def start(self):
desire_cap = {
"platformName": "android",
"deviceName": "127.0.0.1:7555",
"appPackage": "com.tencent.wework",
"appActivity": ".launch.LaunchSplashActivity",
"noReset": "true"
}
self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desire_cap)
self.driver.implicitly_wait(5)
def restart(self):
pass
def stop(self):
pass
def goto_main(self):
return MainPage(self.driver)<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/1 20:54
# @Author : Yuki
# int_a = 1
# float_a =0.2
# complex_a = 0.2j
#
#
# # 通过type查看变量的数据类型
# print(type(int_a))
# print(type(float_a))
# print(type(complex_a))
#
#
# # 输出字符串换行符
# str_b = "bbbbb\n"
# print(str_b)
#
# # 需要将符号打印出来,使用\ 或者 r 忽略转义符
# str_c = "ccccc\\n"
# str_d = r"ddddd\n"
#
# print(str_c)
# print(str_d)
#
# str_a = "aaaaa"
# print(type(str_a))
#
# # 多个字符串连接使用空格 or +
# str_e = "hello" "yuki"
# print(str_e)
# str_f = "bye"+"momo"
# print(str_f)
#
# # 切片使用[start: stop: step] [开始:结束:步长] 步长默认是1
# str_g = "1234567"
# # 打印字符串的第一个字符
# print(str_g[0])
# print(str_g[1])
# print(str_g[2])
#
# print(str_g[0:5])
# print(str_g[0:5:2])
list1 = [1, 2, 3, 4, 5, 6, 7]
# 打印列表中的第一个数字
print(list1[0])
# 列表切片 [开始:结束:步长] 步长默认为1
print(list1[0:5:2])
# 复制并打印列表
print(list1[:])
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/29 20:33
# @Author : Yuki
from appium.webdriver.common.mobileby import MobileBy
from appium_test.page.base_page import BasePage
from appium_test.page.contact_page import ContactPage
class MainPage(BasePage):
# def __init__(self, driver):
# self.driver = driver
def goto_contact(self):
# Todo 跳转通讯录页面
self.driver.find_element(MobileBy.XPATH, "//*[@text='通讯录']").click()
return ContactPage(self.driver)<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/18 11:47
# @Author : Yuki
import os
# os.mkdir("testdir")
# os.removedirs("testdir")
# 打印当前目录下的内容,并用list返回
# print(os.listdir("./"))
# 打印当前文件的绝对路径
# print(os.getcwd())
# 先判断该目录下不存在对应文件夹or文件时,再进行创建
print(os.path.exists("bbb"))
if not os.path.exists("bbb"):
os.mkdir("bbb")
if not os.path.exists("bbb/a.txt"):
f = open("bbb/a.txt", "w")
f.write("hello, os using~")
f.close()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
class House:
# 静态属性->变量;类变量->在类之中,方法之外
door = "red"
floor = "white"
# 构造函数,是在类实例化的时候直接执行
def __init__(self):
print(self.door)
# 实例变量->在类之中,方法之中,以self.变量名的方式去定义,实例变量的作用域为这个类中的所有方法
self.balcony = "大"
# 动态属性 -> 方法(函数)
def sleep(self):
print("房子是用来睡觉的")
# 普通变量 -> 在类之中,方法之中,但不会以self.命名
window = "磨砂"
print(window)
self.wall = "乳胶漆"
def cook(self):
print("房子是用来做饭的")
print(self.balcony)
print(self.wall)
# 实例化-> 变量 = 类()
north_house = House()
china_house = House()
# 调用类变量
print(House.door)
print(north_house.door)
"""
调用方法,方法1中的实例变量可以在方法2中使用,
但仅调用方法2时,会报错,因为在调用方法2之前未调用方法1,则方法1中的示例变量就不会被声明,
所以要想实例变量有用,则需要在调用方法2前先调用方法1.
若想要变量在全局使用,则应将变量放在构造函数中。
因为构造函数在类实例化时会直接执行,变量也就直接被声明。
"""
north_house.sleep()
north_house.cook()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/20 12:32
# @Author : Yuki
import time
def func1(t1): # 最外层管理 装饰器的参数
def func2(func): # 管理传入的函数对象
def func3(t2): # 最内层管理被装饰函数的参数
if func1:
print("开始的时间为:", time.strftime("%S"))
func(t2) # 代表传入的函数被调用
print("我是func3")
print("结束的时间为:", time.strftime("%S"))
else:
func(t2) # 代表传入的函数被调用
print("我是func3")
return func3
return func2
@func1(t1=True)
def be_decorate(t2):
print("被装饰器装饰的函数")
time.sleep(t2)
# be_decorate(3)
f1 = func1(t1=True)
f2 = f1(be_decorate)
f2(3)<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 18:29
# @Author : Yuki
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.remote.webdriver import WebDriver
"""
basepage 每次就做driver实例化的作用,
"""
class BasePage:
# 定于类变量
_base_url = ""
def __init__(self, driver: WebDriver = None):
self._driver = ""
if driver is None:
option = Options()
option.debugger_address = "localhost:9222"
self._driver = webdriver.Chrome(options=option)
# 实例化driver
# self._driver = webdriver.Chrome()
else:
self._driver = driver
if self._base_url != "":
self._driver.get(self._base_url)
self._driver.implicitly_wait(5)
def find(self, by, locator):
return self._driver.find_element(by, locator)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/29 20:42
# @Author : Yuki
# from appium_test.page.memberInvite_page import MemberInvitePage
from appium.webdriver.common.mobileby import MobileBy
from appium_test.page.base_page import BasePage
class AddMemberPage(BasePage):
# def __init__(self, driver):
# self.driver = driver
def add_member(self, name, gender, tel):
# Todo 添加成员方法,添加成功后返回成员邀请页面
from appium_test.page.memberInvite_page import MemberInvitePage
self.driver.find_element(MobileBy.XPATH, "//*[contains(@text,'姓名')]/../android.widget.EditText").send_keys(name)
self.driver.find_element(MobileBy.XPATH, "//*[@text='男']").click()
if gender == '男':
self.driver.find_element(MobileBy.XPATH, "//*[@text='男']").click()
else:
self.driver.find_element(MobileBy.XPATH, "//*[@text='女']").click()
self.driver.find_element(MobileBy.ID, "com.tencent.wework:id/f9s").send_keys(tel)
self.driver.find_element(MobileBy.ID, "com.tencent.wework:id/hk6").click()
toasttext = self.driver.find_element(MobileBy.XPATH, "//*[@class='android.widget.Toast']").text
assert '添加成功' == toasttext
return MemberInvitePage(self.driver)<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/8 16:06
# @Author : Yuki
"""
字面量插值,格式化输出必须给定指定的类型
"""
print("My name is Yuki")
name = "hogwarts"
print('my name is %s' % name)
age = 18
print('my name is %s, my age is %d, num is %f' % (name, age, 5.201314))
num = 5.201
print('my name is %s, my age is %d, num is %f' % (name, age, num))
# 浮点数默认保留6位小数,可自行定制显示n位小数 %.nf
print('my name is %s, my age is %d, num is %.2f' % (name, age, num))
"""
字面量插值,format()方法,不用给定类型
用法:str.format()
可以将字符串、列表、字典进行拼接
"""
print('we are {} and {}'.format('tom', 'jerry'))
print('my name is {} ,and my age is {}'.format(name, age))
print('my name is {0} ,and my age is {1}'.format(name, age))
print('my name is {0} ,and my age is {1}, {0}{1}{0}'.format(name, age))
list1 = ['lili', 'momo', 'tom']
dic2 = {'name': 'momo', 'gender': 'male'}
print('my list is {}, dict is {}'.format(list1, dic2))
print('my list is {0}, dict is {1}'.format(list1, dic2))
# 列表和字典想要一个一个赋值时,需要解包处理
print('we are {}、 {} and {}'.format(*list1))
print('my name is {name} ,and my gender is {gender}'.format(**dic2))
"""
F-string:字符串格式化,支持3.6以上版本
使用方法:f'{变量名}'
大括号内可以是表达式or函数or常量
"""
print(f'my name is {name}, age is {age}, my list is {list1}, my dict is {dic2}')
print(f"my list is {list1[0]}")
print(f"my dict is {dic2['gender']}")
# 大括号内的表达式
print(f"my name is {name.upper()}")
print(f"my age is {24}")
print(f"result is {(lambda x:x+1)(2)}")
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 22:52
# @Author : Yuki
import sys
print(sys.path)<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/18 13:43
# @Author : Yuki
import urllib.request
response: object=urllib.request.urlopen("http://www.baidu.com")
print(response.status)
# print(response.read())
print(response.headers)<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/29 16:49
# @Author : Yuki
import pytest
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from hamcrest import *
class TestAppiumParam:
"""
"skipServerInstallation": "true",//跳过安装程序
"noReset": "true"//不要清除缓存,初始化应用
"unicodeKeyBoard": "true",//输入中文必需
"resetKeyBoard": "true"//输入中文必需
autoGrantPermissions :让appium自动授权app权限,如果noReset为True,则该条不生效
"""
def setup(self):
desire_cap = {
"platformName": "android",
"deviceName": "127.0.0.1:7555",
"appPackage": "com.xueqiu.android",
"appActivity": ".view.WelcomeActivityAlias",
"skipServerInstallation": "true",
"noReset": "true",
"unicodeKeyBoard": "true",
"resetKeyBoard": "true"
}
self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desire_cap)
self.driver.implicitly_wait(5)
def teardown(self):
# self.driver.quit()
self.driver.find_element(MobileBy.ID, "com.xueqiu.android:id/action_close").click()
@pytest.mark.parametrize('searchKey, type, except_price', [
('alibaba', '09988', 270),
('xiaomi', '01810', 22)
])
def test_searchParam(self, searchKey, type, except_price):
self.driver.find_element(MobileBy.ID, "com.xueqiu.android:id/tv_search").click()
self.driver.find_element(MobileBy.ID, "com.xueqiu.android:id/search_input_text").send_keys(searchKey)
self.driver.find_element(MobileBy.ID, "com.xueqiu.android:id/name").click()
current_price = float(self.driver.find_element(MobileBy.XPATH,
f"//*[@text='{type}']/../../..//*[@resource-id='com.xueqiu.android:id/current_price']").text)
# except_price = 289
print(f"当前的价格是{current_price}")
assert_that(current_price, close_to(except_price, except_price * 0.1))
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/8 17:14
# @Author : Yuki
"""
文件读取
操作步骤:
1、打开文件,获取文件描述符
2、操作文件描述符(读 | 写)
3、关闭文件(文件读写操作完成后,应及时关闭文件)
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
参数说明:
name:文件名称的字符串值
mode:只读r。写入w,追加a,默认文件访问模式为只读r
buffering:寄存区缓存
0:不寄存
1:访问文件时会寄存行
>1:寄存区的缓冲大小
<0:寄存区的缓冲大小为系统默认
图片要使用rb去读取二进制格式
正常的文本使用rt,也是默认的格式
"""
# 打开文件
f = open('Demo_data.txt')
# 查看文件是否可读,并输出结果
print(f.readable())
"""
注意:readline和readlines一起使用的时候,是都生效的
比如readline已经读取了两行,再执行readlines,则会输出的剩下未读取的所有行
如果先执行readlines ,后执行的readline则输出为空
"""
# 将文件每次读取一行,换行符不会被读取
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
# 将文件每行全部读出,并存放在一个列表内,换行符也会被读取
print(f.readlines(), '\n')
# 关闭文件
f.close()
"""
with跟open一起使用,则不需要再去写close文件;
with语句块,可以将文件打开,执行完毕后,自动关闭这个文件
"""
with open('Demo_data.txt') as f:
print(f.readlines())
# 图片要使用rb去读取二进制格式
with open('1.jpg', 'rb') as f:
print(f.readlines())<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/1 21:32
# @Author : Yuki
#
# # 分支结构
# a = 0
# if a == 0:
# print("a=0")
# else:
# print("a!=0")
#
# # 多重分支
# b = 9
# if b == 1:
# print("b == 1")
# elif b == 2:
# print("b == 2")
# elif b == 3:
# print("b == 3")
# else:
# print("b不等于1,2,3")
#
# x = 8
# xx = 8
# if xx > 1:
# yy = 3 * xx - 5
# elif -1 <= xx <= 1:
# yy = xx + 2
# elif xx < -1:
# yy = 5 * xx + 3
# print(yy)
#
# if x >= -1:
# if x <= 1:
# y = x + 2
# else:
# y = 3 * x - 5
# else:
# y = 5 * x + 3
# print(y)
# result = 0
# for i in range(1, 20, 2):
# print(i)
# result = result + i
# print(result)
# for i in range(0, 5):
# print(i)
# print("\n")
#
# # break 指跳出循环不再执行
# for i in range(0, 5):
# if i == 3:
# break
# print(i)
# print("\n")
#
# # continue 指跳出本次循环,要继续执行剩下的循环
# for i in range(0, 5):
# if i == 3:
# continue
# print(i)
import random
computer_num = random.randint(1, 100)
print(computer_num)
while True:
person_num = int(input("请输入一个数字:\n"))
if person_num > computer_num:
print("小一点")
elif person_num < computer_num:
print("大一点")
elif person_num == computer_num:
print("bingo~")
break
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/8 17:42
# @Author : Yuki
import json
"""
json是由列表和字典组成的
"""
dataDic = {
"name": ["yuki", "momo"],
"age": 18,
"gender": "girl"
}
# 查看并打印dataDic的类型
print(type(dataDic))
# 将数据类型转换成字符串
data1 = json.dumps(dataDic)
print(data1)
print(type(data1))
# 将字符串转换成json
data2 = json.loads(data1)
print(type(data2))
# 将数据类型转换成字符串并存储在文件中
# 把文件打开,把里面的字符串转换成数据类型
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/21 21:40
# @Author : Yuki
import pystache
class TestMustache:
def test_mustache(self):
pystache.render(
"Hi {{person}}!",
{"person": "Yuki"}
)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/29 20:34
# @Author : Yuki
from appium.webdriver.common.mobileby import MobileBy
from appium_test.page.base_page import BasePage
from appium_test.page.memberInvite_page import MemberInvitePage
class ContactPage(BasePage):
# def __init__(self, driver):
# self.driver = driver
def goto_addMemberPage(self):
# Todo 跳转同事邀请页面
self.driver.find_element(MobileBy.XPATH, "//*[@text='添加成员']").click()
return MemberInvitePage(self.driver)<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/17 23:29
# @Author : Yuki
import pytest
# 当一个方法上面加上@pytest.fixture() 装饰器就变成了fixture方法
# yield 也相当于return,如果需要返回值,直接写在yield后面即可
# yield 前面的操作相当于setup操作,yield后面的操作相当于teardown操作
"""
当测试用例方法需要调用fixture方法时,在参数中传入fixture方法名login
当测试用例方法需要fixture方法的返回值时,一定要将fixture方法名传入参数
fixture里面的参数scope,可以控制fixture的作用范围:session>module>class>function(默认是function)
"""
@pytest.fixture()
def login():
print("登录")
username = "yuki"
password = <PASSWORD>
# return [username, password]
yield [username, password]
print("登出")
def test_case1(login):
print(login)
print("这是方法1,需要登录")
def test_case2():
print("这是方法2,不需要登录")
def test_case3(login):
print(login)
print(f"这是方法3,需要登录,账号是{login}")
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/29 12:32
# @Author : Yuki
"""
https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/touch-actions.md
TouchAction
TouchAction对象包含一系列事件。
在所有appium客户端库中,都会创建触摸对象并为其分配一系列事件。
规范中可用的事件是:
press
release
moveTo
tap
wait
longPress
cancel
perform
"""
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
class TestTouchAction:
def setup(self):
desire_cap = {
"platformName": "android",
"deviceName": "127.0.0.1:7555",
"appPackage": "com.xueqiu.android",
"appActivity": ".view.WelcomeActivityAlias",
"noReset": "true"
}
self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desire_cap)
self.driver.implicitly_wait(5)
def teardown(self):
self.driver.quit()
def test_touchAction(self):
# 定义一个TouchAction类
action = TouchAction(self.driver)
# 打印界面的宽和高
# print(self.driver.get_window_rect())
# press按住,move_to移动到,release释放,perform执行
action.press(x=360, y=1150).move_to(x=360, y=400).release().perform()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/11 21:15
# @Author : Yuki
import pytest
# 笛卡尔积,用来生成多个用例组合
@pytest.mark.parametrize("a", [1, 2, 3])
@pytest.mark.parametrize("b", [4, 5, "x"])
def test_case2(a, b):
print(f"a= {a} b= {b}")
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/18 14:06
# @Author : Yuki
import _thread
import logging
from time import ctime, sleep
logging.basicConfig(level=logging.INFO)
loops = [2, 4]
def loop(nloop, nsec, lock):
logging.info("strat loop" + str(nloop) + " at " + ctime())
sleep(nsec)
logging.info("end loop" + str(nloop) + " at " + ctime())
lock.release()
# def loop0():
# logging.info("strat loop0 at " + ctime())
# sleep(4)
# logging.info("end loop0 at " + ctime())
#
#
# def loop1():
# logging.info("strat loop1 at " + ctime())
# sleep(2)
# logging.info("end loop1 at " + ctime())
def main():
logging.info("strat all at " + ctime())
locks = []
nloops = range(len(loops))
for i in nloops:
lock = _thread.allocate_lock()
lock.acquire()
locks.append(lock) # 将获取到的lock全部放入locks列表中
for i in nloops:
_thread.start_new_thread(loop, (i, loops[i], locks[i]))
for i in nloops:
while locks[i].locked(): pass
# _thread.start_new_thread(loop0, ())
# _thread.start_new_thread(loop1, ())
# loop0()
# loop1()
# sleep(5) # 主线程加这个强制等待且时间大于其他线程,原因是当主线程结束时,其他线程也会强制结束,_thread没有守护线程的功能,所以必须强制等待
logging.info("end all at " + ctime())
if __name__ == '__main__':
main()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/18 21:17
# @Author : Yuki
"""
闭包函数:
在函数内又定义了函数,且外层函数返回的是内层函数的对象
例如func1()代表调用这个函数,而func1则仅是函数的对象
即:调用外层函数时是无法执行内层函数的代码。
想要执行内层函数的代码,需要先调用外层函数,再对结果值进行调用;直接调用内层函数时不行的。
注意:
1、定义的全局变量在外层函数、内层函数都能被调用
2、定义在外层函数的变量,能被内层函数调用
3、但内层函数的变量,不可被外层函数调用
"""
def func1():
name = "func1的鲸鱼"
print(name)
print("我是func1")
def func2():
name = "func2的鲸鱼"
print(name)
print("我是func2")
return func2
# 调用外层函数func1()
func1()
print("\n")
# 调用内层函数func2()
func22 = func1() # func22 == func1() == func2
func22() # func22() == func2()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 18:44
# @Author : Yuki
from selenium.webdriver.common.by import By
from pageobject.page.base_page import BasePage
class Register(BasePage):
def register(self):
self.find(By.ID, "corp_name").send_keys("Momo's Company")
self.find(By.ID, "manager_name").send_keys("Momo")<file_sep>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import allure
import pytest
import sys
import yaml
sys.path.append('..')
from pythonCode.calc import Calculator
def get_datas():
with open("./datas/calc.yml", encoding="utf-8") as f:
mydatas = yaml.safe_load(f)
class TestCalc:
# 提取每个方法里都要重复的实例化
def setup_class(self):
print("在整个类之前执行setup")
self.calc = Calculator()
def teardown_class(self):
print("在整个类之后执行teardown")
# 重复方法参数化
@pytest.mark.parametrize('a, b, c', [
(1, 1, 2),
(-1, -1, 1)
])
@pytest.mark.add
def test_add(self, a, b, c):
# 每个方法里进行实例化
# calc = Calculator()
# 在allure报告中添加一些日志(文本、html) allure.attach()
allure.attach("这是一个相加的测试用例", name='这是文本型', attachment_type=allure.attachment_type.TEXT)
allure.attach(
'<img src="https://ceshiren.com/uploads/default/original/2X/c/c49051f32076a3903e1a56a0bde6199bddd5f07b.jpeg" width="100%">',
name='html类型', attachment_type=allure.attachment_type.HTML)
# 断言
assert c == self.calc.add(a, b)
@pytest.mark.parametrize('a, b, c', [
(1, 1, 1),
(2, 2, 1)
])
@pytest.mark.div
def test_div(self, a, b, c):
# 每个方法里进行实例化
# calc = Calculator()
# 在allure报告中添加一些日志(图片、视频) allure.attach.file()
allure.attach.file('C:\\Users\\Julia\\Pictures\\Camera Roll\\lisa.JPG', name='这是一张图片',
attachment_type=allure.attachment_type.JPG)
assert c == self.calc.div(a, b)
## 原始的方法
# def test_add(self):
# calc = Calculator()
# assert 2 == calc.add(1, 1)
#
# def test_div(self):
# calc = Calculator()
# assert 2 == calc.div(2, 1)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/29 21:05
# @Author : Yuki
"""
基类:
存放一些最基本的方法,用的最频繁的方法
1、实例化driver
2、查找元素
"""
from appium import *
from appium.webdriver.webdriver import WebDriver
class BasePage:
def __init__(self, driver:WebDriver = None):
"""
初始化driver
"""
self.diver = driver
def find(self, locator):
return self.diver.find_element(*locator)
def find_and_click(self, locator):
self.find(locator).click()
# def find_and_scroll_and_click(self):
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 20:30
# @Author : Yuki
from selenium.webdriver.common.by import By
from pageobject.page.base_page import BasePage
class ContactPage(BasePage):
def goto_add_member(self):
from pageobject.page.add_member_page import AddMemberPage
return AddMemberPage(self._driver)
def get_memeber_list(self):
# 这个元素查找出来返回的是一个列表
name_list = self._driver.find_elements(By.CSS_SELECTOR, ".member_colRight_memberTable_td:nth-child(2)")
# 定义一个空列表
list1 = []
# 用循环把返回列表中的值都取出来存到定义的空列表中
for name in name_list:
list1.append(name.text)
return list1
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 18:29
# @Author : Yuki
from selenium.webdriver.common.by import By
from pageobject.page.base_page import BasePage
from pageobject.page.register import Register
class Main(BasePage):
_base_url = "https://work.weixin.qq.com/"
def doto_register(self):
self.find(By.CSS_SELECTOR, "index_head_info_pCDownloadBtn").click()
return Register(self._driver)
def goto_login(self):
pass
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/18 13:46
# @Author : Yuki
import math
print(math.ceil(5.5))
print(math.floor(5.5))
print(math.sqrt(16))
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/18 15:08
# @Author : Yuki
import yaml
print(yaml.load(open("demo.yml"), Loader=yaml.FullLoader))
print("\n")
print(yaml.load("""
a: 1
b: 2
""", Loader=yaml.FullLoader))
print("\n")
print(yaml.dump({'a': [1, 2]}))
print(yaml.dump([[1, 2, 3], {'a': 1, 'b': 2, 'c': 3}]))
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/20 12:20
# @Author : Yuki
"""
实现被装饰函数有参数的情况
"""
import time
def func1(func):
def func2(m_time):
print("开始的时间为:", time.strftime("%S"))
func(m_time) # 代表传入的函数被调用
print("我是func2")
print("结束的时间为:", time.strftime("%S"))
return func2
@func1
def be_decorate(m_time):
print("被装饰器装饰的函数")
time.sleep(m_time)
be_decorate(3)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/8 20:32
# @Author : Yuki
class Bicycle:
def run(self, km):
print(f"一共用脚骑了{km}公里")
# EBicycle()类继承自Bicycle
class EBicycle(Bicycle):
# 如果属性需要传参定义,那么可以使用构造函数
# valume是电动车初始电量
def __init__(self, valume):
self.valume = valume
# vol是充电的电量
def fill_charge(self, vol):
self.valume = self.valume + vol
print(f"充了{vol}度电,现在的电量为{self.valume}")
# power_km 是电动车所有电量能跑的里程数;km是要跑的里程数
def run(self, km):
power_km = self.valume * 10
if power_km > km:
print(f"我使用电瓶车骑了{km}公里")
else:
print(f"我使用电瓶车骑了{power_km}公里")
# # 非继承调用方法
# bike = Bicycle()
# bike.run(km - power_km)
# 继承调用方法
super().run(km - power_km)
ebike = EBicycle(2)
# ebike.fill_charge(3)
ebike.run(10)
# bike = Bicycle()
# bike.run(10)
<file_sep>list_yuki = [1, 2, 3, 4, 5]
# list.append(x):在列表的末尾添加一个元素
list_yuki.append(66)
print("使用append在列表尾部添加一个元素66:", list_yuki)
print("\n")
# list.insert(i, x):在给定的位置插入一个元素,第一个参数i是要插入元素的索引,0代表头部
list_yuki.insert(0, 99)
print("在列表头部插入元素99:", list_yuki)
print("\n")
list_yuki.insert(2, 22)
print("在列表第三个位置插入元素22:", list_yuki)
print("\n")
# list.remove(x):移除列表中第一个值为x的元素
list_yuki.remove(22)
print("移除列表中的1:", list_yuki)
print("\n")
# list.pop(i):删除列表中给定位置的元素并返回它,若没有给定位置,则会删除并返回列表中的最后一个函数
list_yuki.pop(0)
print("移除列表中的第一位元素:", list_yuki)
list_yuki.pop()
print("未给出索引位置,则默认移除列表中最后一个元素并返回:", list_yuki)
print("\n")
# list.sort():对列表中的元素进行默认升序排列
# list.sort(reverse=True):对列表中的元素进行降序排列
# list.reverse():反转列表中的元素
list_momo = [5, 2, 4, 1, 3]
print("列表顺序为:", list_momo)
list_momo.reverse()
print("列表反转后顺序为:", list_momo)
list_momo.sort()
print("列表升序为:", list_momo)
list_momo.sort(reverse=True)
print("列表降序为:", list_momo)
print("\n")
"""
元组:使用()进行定义
tuple、list、range都是序列数据类型
元组是不可变的,可以通过解包、索引来访问
tuple.count(x) 用来统计该元组中x出现的个数
tuple.index(x) 用来得到该元组中x的索引
"""
# 元组的定义
tuple_yuki = (1, 2, 3)
tuple_yuki2 = 1, 2, 3
print("tuple_yuki", tuple_yuki)
print(type(tuple_yuki))
print("tuple_yuki2", tuple_yuki2)
print(type(tuple_yuki2))
# 元组的不可变特性:元组内的值不可变,执行会报错;但是嵌套在元组里的列表,可以进行修改
a = [1, 2, 3]
tuple_yuki4 = (1, 2, a)
print(tuple_yuki4)
tuple_yuki4[2][0] = "a"
print(tuple_yuki4)
# tuple.count(x) 用来统计该元组中x出现的个数
tuple_yuki5 = (1, 2, 3, "a", "a", "b")
print(tuple_yuki5.count(3))
print(tuple_yuki5.count("a"))
print(tuple_yuki5.count("c"))
# tuple.index(x) 用来得到该元组中x的索引,当元组中x存在多个时,返回的是第一个x的索引
print(tuple_yuki5.index(3))
print(tuple_yuki5.index("a"))
# 列表推导式
"""
用for循环生成一个平方列表[1,4,9]
1、先定义一个列表
2、使用range()函数生产数字1,2,3;range(x,y)是左闭右开,生产的元素为x,x+1 ... y-1
3、使用list.append()来插入列表元素
"""
list_squre1 = []
for i in range(1, 4):
print(i)
# i = i * i 等同于 i = i**2
i = i ** 2
list_squre1.append(i)
print(list_squre1)
"""
集合:基本用法包括成员检测和消除重复元素
可以使用{}orset()函数创建集合
要创建一个空集合只能用set()而不能用{},空的{}类型是字典
"""
conA = {1}
conB = set()
len(conB)
print("conA的类型是:", type(conA))
print("conA的长度是:", len(conA))
print("conB的类型是:", type(conB))
print("conB的长度是:", len(conB), "\n")
a = {1, 2, 3}
b = {3, 4, 5}
print("集合a、b的并集:", a.union(b))
print("集合a、b的交集:", a.intersection(b))
print("集合a、b的差集:", a.difference(b), "\n")
# 将字符串去重变成集合
print({i for i in "abcaassddw"})
"""
将字符串去重变成无序集合 or 有序列表
sort 与 sorted 区别:
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
sorted(iterable, key=None, reverse=False)
iterable -- 可迭代对象。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
返回重新排序的列表。
"""
# 将字符串去重变成集合
c = "aabbxbcdbs"
print("c的类型是:", type(c))
print("将字符串c去重变成无序集合:", set(c)) # set是集合,这里利用的是集合不重复的特点,但是set是无序集合,所以打印出来的顺序与字符串不一致
print("set(c)的类型是:", type(set(c)))
# 将字符串先转换成list,再使用sorted()按照原list顺序进行去重后返回
list_c3 = sorted(set(c), key=list(c).index) # sorted(L)返回一个排序后的L,不改变原始的L
print("list_c3的类型是:", type(list_c3))
print("将字符串c去重后变成不改变顺序的列表:", list_c3)
"""
字典:
以【关键字】为索引
关键字可以是任意不可变类型,通常是字符串或数字
字典内key可以重复,但是会被覆盖
dict.pop(x) 指删除字典中key为x的键值对
"""
momo_dict = {"a": 1, "b": 2}
momo_dict2 = dict(a=1, b=2)
print("将字典dict打印出来:", momo_dict)
print("将字典dict2打印出来:", momo_dict2)
# 打印字典里的所有关键字
print("字典momo_dict里的所有关键字:", momo_dict.keys())
# 打印字典里的所有值
print("字典momo_dict里的所有值:", momo_dict.values())
momo_dict3 = {"a": 1, "b": 2, "c": 3, "d": 4}
print("将字典dict3打印出来:", momo_dict3)
momo_dict3.pop("a")
print("删除字典中key为a的所有键值对后输出:", momo_dict3)
# 字典内key可以重复,但是会被覆盖
momo_dict4 = {"a": 1, "b": 2, "a": 3, "d": 4}
print("将字典dict4打印出来,查看重名的key是否被覆盖:", momo_dict4)<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import allure
import pytest
def test_attach_text():
allure.attach("这是一个纯文本", attachment_type=allure.attachment_type.TEXT)
def test_attach_html():
allure.attach("<body>这是一段html body块</body>", "html测试块", attachment_type=allure.attachment_type.HTML)
def test_attach_photo():
# 当allure报告中图片显示不出来时,请注意图片路径:将\修改为/或者\\
# 图片应该是attach.file
allure.attach.file("G:/PycharmProjects/LagouPractice_Yuki/testing/1.jpg", name="这是一张图片", attachment_type=allure.attachment_type.JPG)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/12 22:53
# @Author : Yuki
"""
@pytest.fixture
装饰器用来装饰一个方法,被装饰方法的方法名可以作为一个参数传入到测试方法中;
可以使用这种方式来完成测试之前的初始化,也可以返回数据给测试函数。
作用:一些方法需要依赖前置方法,比如需要执行登录才能继续执行自身方法
-------*------
1、如果被装饰的方法有返回值,那么在其他方法中直接输出方法名==输出该方法的返回值(如果没有设置返回值,则输出None)
"""
import pytest
class Test_fixture():
# 登录方法
@pytest.fixture()
def login(self):
print("登录账号")
return ("tom", "<PASSWORD>")
@pytest.fixture()
def afterLogin(self):
print("完成登录后的操作")
def test_case1(self,login):
print(login)
print("这是方法1,需要登录")
def test_case2(self):
print("这是方法2,不需要登录")
def test_case3(self, login, afterLogin):
print(login)
print(f"这是方法3,需要登录,账号是{login}")
<file_sep>[pytest]
markers=add
div<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/20 20:37
# @Author : Yuki
import pytest
"""
fixture参数化, 带参数传递
在@pytest.fixture()中,通过params=传递参数,fixture方法login()中加入request
"""
@pytest.fixture(params=[("tom", 123456), ("jerry", 654321)], ids=["用户Tom", "用户jerry"])
def login(request):
# print(request.param)
print("登录")
yield request.param
print("登出")
def test_case1(login):
print("test_case1")
print(login)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/29 13:58
# @Author : Yuki
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
class TestWebdriverWait:
def setup(self):
desire_cap = {
"platformName": "android",
"deviceName": "127.0.0.1:7555",
"appPackage": "com.xueqiu.android",
"appActivity": ".view.WelcomeActivityAlias",
"noReset": "true"
}
self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desire_cap)
self.driver.implicitly_wait(5)
def teardown(self):
self.driver.quit()
def test_webdriverWait(self):
self.driver.find_element(MobileBy.ID, "com.xueqiu.android:id/tv_search").click()
self.driver.find_element(MobileBy.ID, "com.xueqiu.android:id/search_input_text").send_keys("alibaba")
self.driver.find_element(MobileBy.XPATH, "//*[@text='阿里巴巴']").click()
self.driver.find_element(MobileBy.XPATH,"//*[@text='股票']").click()
locator = (MobileBy.XPATH, "//*[@text='09988']/../../..//*[@resource-id='com.xueqiu.android:id/current_price']")
# 加隐式等待,首先引入包WebDriverWait,参数设置driver,timeout等待时长---》意思是在10s内如果这个locator可以点击,则继续执行,否则返回异常(默认每0.5s进行查找)
# 还有一个与之对应的相反方法until_not
WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable(locator))
# *locator -->意思是解元组,
ele = self.driver.find_element(*locator)
print(ele)
current_price = float(ele)
except_price = 170
assert current_price > except_price
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/8 18:37
# @Author : Yuki
"""
类(Class):抽象的概念,一类事物
方法:类中定义的函数,对外提供的服务
类变量:类变量在整个实例化的对象中是公用的
实例引用:实例化一个对象
实例变量:以‘self.变量名’的方式定义的变量
"""
# 通过class关键字,定义一个类Person
class Person:
# 定义类变量:在整个实例化的对象中是公用的
name = "default"
age = 0
gender = "male"
weight = 0
# 定义类的方法
"""
构造方法,在类实例化的时候被调用
例如我们可以在这里设置属性,set_name、age、gender、weight
"""
def __init__(self, name, age, gender, weight):
print("init function")
# self.变量名的方式,访问到的变量,叫做实例变量(即每一个实例拥有的属性)
self.name = name
self.age = age
self.gender = gender
self.weight = weight
# # self.name 调用的是类里面的name属性,set_name 方法是给每个实例设置不同name;age\gender\weight同理
# def set_name(self, name):
# self.name = name
#
# def set_age(self, age):
# self.age = age
#
# def set_gender(self, gender):
# self.gender = gender
#
# def set_weight(self, weight):
# self.weight = weight
@classmethod
def eat(self):
print(f"{self.name} is eating")
def play(self):
print(f"{self.name} is playing")
def jump(self):
print(f"{self.name} is jumping")
"""
类变量和实例变量的区别:
1、都是可以被修改的
2、类变量是需要类来访问,实例变量需要实例来访问
类方法和实例方法的区别:
1、类方法是不能访问 实例方法
2、类方法要通过添加一个装饰器 @classmethod 才能访问实例方法
"""
# 类的实例化,创造了一个实例,zs就是实例化的对象
zs = Person("zhangsan", 20, "男", 120)
# 调用类的方法
zs.eat()
# # 为这个对象设置属性
# zs = Person()
# zs.set_name("zhangsan")
# zs.set_age(18)
# zs.set_gender("male")
# zs.set_weight(120)
print(f"zs的姓名是:{zs.name}, 年龄是:{zs.age}, 性别是:{zs.gender}, 体重是:{zs.weight}")
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/21 22:42
# @Author : Yuki
import requests
from requests.auth import HTTPBasicAuth
def test_authDemo():
r = requests.get(url="http://httpbin.testing-studio.com/basic-auth/momo/123456",
auth=HTTPBasicAuth("momo", "123456"))
print(r.status_code)
print(r.text)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 14:58
# @Author : Yuki
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
class TestAction():
def setup(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(10)
def teardown(self):
self.driver.quit()
def test_clickCase(self):
self.driver.get("http://sahitest.com/demo/clicks.htm")
element_click = self.driver.find_element_by_xpath("//input[@value='click me']")
element_doubleclick = self.driver.find_element_by_xpath("//input[@value='dbl click me']")
element_rightclick = self.driver.find_element_by_xpath("//input[@value='right click me']")
# 定义一个anction
action = ActionChains(self.driver)
# 点击
action.click(element_click)
# 右击
action.context_click(element_rightclick)
# 双击
action.double_click(element_doubleclick)
# 调用perform去执行之前的方法
action.perform()
def test_movetoelement(self):
self.driver.get("https://www.baidu.com/")
element = self.driver.find_element(By.ID, "s-usersetting-top")
# 定义一个anction
action = ActionChains(self.driver)
# 移动到元素
action.move_to_element(element)
# 调用perform去执行之前的方法
action.perform()
def test_dragdrop(self):
self.driver.get("http://sahitest.com/demo/dragDropMooTools.htm")
dragele = self.driver.find_element(By.ID, "dragger")
dropele = self.driver.find_element_by_xpath("/html/body/div[2]")
# 定义一个anction
action = ActionChains(self.driver)
# 拖拽
action.drag_and_drop(dragele, dropele)
# 调用perform去执行之前的方法
action.perform()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/29 20:38
# @Author : Yuki
from appium.webdriver.common.mobileby import MobileBy
from appium_test.page.addMember_page import AddMemberPage
from appium_test.page.base_page import BasePage
class MemberInvitePage(BasePage):
# def __init__(self, driver):
# self.driver = driver
def goto_addMemberByManual(self):
# Todo 跳转手动新建成员页面
self.driver.find_element(MobileBy.XPATH, "//*[@text='手动输入添加']").click()
return AddMemberPage(self.driver)
<file_sep># 函数的定义
# 位置参数
def func1(a, b, c):
print("函数func1的参数a", a)
print("函数func1的参数b", b)
print("函数func1的参数c", c)
print("\n")
return None
# 函数的调用
func1(1, 2, 3)
"""
默认参数:
默认参数在定义函数的时候使用k=v的形式定义
调用函数时,如果没有传递参数,则会使用默认参数
"""
def func2(a=1):
print("func2()未传递参数,直接使用默认参数:", a)
print("\n")
return a
func2()
"""
关键字参数:
调用函数时,使用k=v的形式进行传参
在函数调用or定义中,关键字参数必须跟随在位置参数的后面
"""
def func3(a, b, c):
print("func3()参数a的值为:", a)
print("func3()参数b的值为:", b)
print("func3()参数c的值为:", c)
print("\n")
# 全部使用关键字传参
func3(b=2, a=1, c=3)
# 想要一起使用关键字传参和位置传参
func3(4, c=6, b=5)
"""
lambda表达式(匿名函数)
"""
func4 = lambda x, y: x * y
print("func4()两个参数的积为:", func4(5, 6))
def func4_same(x, y):
print("用def定义函数func4_same()的参数乘积是:", x * y)
print("\n")
func4_same(5, 6)
def func5(a=5):
return a
# 查看并打印返回值
print(func5())
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/3 23:46
# @Author : Yuki
try:
num1 = int(input("请输入一个除数:"))
num2 = int(input("请输入一个被除数:"))
print(num1 / num2)
# 抛出指定的异常
# except ZeroDivisionError:
# print("被除数不能为0")
# except ValueError:
# print("输入的需要是数值型整数")
# try:
# 执行代码
# except:
# 发生异常时执行的代码
# else:
# 没有异常时执行的代码、
# finally:
# 不管有没有异常都会执行的代码
except:
print("被除数不能为0 或 输入的需要是数值型整数")
else:
print("没有异常哦~")
finally:
print("已经执行完了")
# 抛出异常raise Exception
x = int(input("请输入一个数值型整数:"))
if x > 5:
raise Exception("这是抛出的异常信息!!")
# 自定义的异常类
class MyException(Exception):
def __init__(self, value1, value2):
self.value1 = value1
self.value2 = value2
# 抛出自定义的异常类
raise MyException("value1", "value2")
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/21 20:39
# @Author : Yuki
import json
import requests
from jsonpath import jsonpath
from hamcrest import *
from jsonschema import validate
class TestDemo:
def test_get(self):
r = requests.get('https://httpbin.testing-studio.com/get')
print(r.status_code)
print(r.text)
print(r.json())
assert r.status_code == 200
def test_query(self):
payload = {
"level": 1,
"name": "Yuki"
}
r = requests.get("https://httpbin.testing-studio.com/get", params=payload)
print(r.text)
assert r.status_code == 200
def test_post_form(self):
payload = {
"level": 1,
"name": "Yuki"
}
r = requests.post("https://httpbin.testing-studio.com/post", data=payload)
print(r.text)
assert r.status_code == 200
def test_headers(self):
r = requests.get('https://httpbin.testing-studio.com/get', headers={"name": "Yuki"})
print(r.status_code)
print(r.text)
print(r.json())
assert r.status_code == 200
assert r.json()["headers"]["Name"] == "Yuki"
# json断言
def test_post_json(self):
payload = {
"level": 1,
"name": "Yuki"
}
r = requests.post("https://httpbin.testing-studio.com/post", json=payload)
print(r.text)
assert r.status_code == 200
assert r.json()["json"]["level"] == 1
# jsonpath 断言
def test_hogwarts_json(self):
r = requests.post("https://home.testing-studio.com/categories.json")
print(r.text)
assert r.status_code == 200
assert r.json()["category_list"]["categories"][0]["name"] == "社区治理"
print(jsonpath(r.json(), "$..name"))
assert jsonpath(r.json(), "$..name")[0] == "社区治理"
# hamcrest 断言
def test_hamcrest(self):
r = requests.post("https://home.testing-studio.com/categories.json")
print(r.text)
assert r.status_code == 200
assert_that(r.json()["category_list"]["categories"][0]["name"], equal_to("社区治理"))
# schema 断言
def test_jsonschema(self):
r = requests.post("https://home.testing-studio.com/categories.json")
data = r.json()
with open("./demo_schema.json", encoding="utf-8") as f:
schema = json.load(f)
print(schema)
validate(data, schema=schema)
def test_headers_cookies(self):
url = "http://httpbin.testing-studio.com/cookies"
headers = {
'User-Agent': 'Yuki'
}
cookie_data = {
"Yuki": "girl",
"Momo": "babe"
}
r = requests.get(url=url, headers=headers, cookies=cookie_data)
print(r.request.headers)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 20:31
# @Author : Yuki
from selenium import webdriver
from selenium.webdriver.common.by import By
from pageobject.page.base_page import BasePage
from pageobject.page.contact_page import ContactPage
class AddMemberPage(BasePage):
def add_member(self):
driver = self._driver
driver.find_element(By.ID, "username").send_keys("Ben")
driver.find_element(By.ID, "memberAdd_acctid").send_keys("0505")
driver.find_element(By.ID, "memberAdd_phone").send_keys("11122223333")
driver.find_element(By.CSS_SELECTOR, ".js_btn_save").click()
return ContactPage(driver)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/20 10:00
# @Author : Yuki
class Bicycle():
def run(self, km):
print(f"自行车骑行里程为{km}公里")
# A类继承自B类:class A(B)
class EBicycle(Bicycle):
# 如果属性需要传参定义,那么需要使用构造函数
def __init__(self, valume):
self.valume = valume
def fill_charge(self, vol):
self.valume = self.valume + vol
print(f"充了{vol}度电,现在的电量为{self.valume}")
def run(self, km):
"""
每骑行10km消耗1度电,电量耗尽时自行车继续骑行
思路:
1、要知道当前的电量,就能得到能跑的最大里程数
2、将最大里程数与需要骑行的里程数做比较,大于等于则只用电动车骑行;否则需要电动车+自行车骑行
"""
if self.valume * 10 >= km:
print(f"用电动车骑行了{km}公里")
elif self.valume * 10 < km:
print(f"用电动车骑行了{self.valume*10}公里")
# bike = Bicycle()
# bike.run(km - self.valume*10)
super().run(km - self.valume*10)
ebike = EBicycle(1)
ebike.fill_charge(2)
ebike.run(50)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/20 20:30
# @Author : Yuki
"""
conftest.py 用法
查找顺序
1、测试用例会优先读 取当前模块下的fixture 方法
2、其次读取当前目录下定义的conftest.py 文件里面定义的fixture方法
3、如果当前文件或者当前目录没有,才会去项目目录下一层一层往上找。
需要注意
conftest.py文件名是不能换的
conftest.py与运行的用例要在同一个package下,并且有__init__.py文件
不需要import导入conftest.py,pytest用例会自动查找
所有同目录测试文件运行前都会执行conftest.py文件
全局的配置和前期工作都可以写在这里,放在某个包下,就是这 个包数据共享的地方。
"""
import pytest
# scope="session" 整个session域只执行一次
@pytest.fixture(scope="session")
def coonDB():
print("连接数据库-subProgram")
yield
print("断开数据库连接-subProgram")
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/17 23:51
# @Author : Yuki
import pytest
@pytest.fixture(scope="module")
def coonDB():
print("连接数据库")
yield
print("断开数据库连接")
def test_case1(coonDB):
print("test_case1")
class TestDemo1:
def test_a1(self, coonDB):
print("test_a1")
def test_b1(self, coonDB):
print("test_b1")
class TestDemo2:
def test_a2(self, coonDB):
print("test_a2")
def test_b2(self, coonDB):
print("test_b2")
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/29 16:25
# @Author : Yuki
import pytest
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from hamcrest import *
class TestWebdriverWait:
def setup(self):
desire_cap = {
"platformName": "android",
"deviceName": "127.0.0.1:7555",
"appPackage": "com.xueqiu.android",
"appActivity": ".view.WelcomeActivityAlias",
"noReset": "true"
}
self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desire_cap)
self.driver.implicitly_wait(5)
def teardown(self):
# self.driver.quit()
pass
def test_getAttribute(self):
search_ele = self.driver.find_element_by_id("com.xueqiu.android:id/tv_search")
print(search_ele.get_attribute("resource-id"))
assert "search" in search_ele.get_attribute("resource-id")
def test_hamrest(self):
# 断言10满足equal_to(x),否则抛出异常提示
assert_that(10, equal_to(10), '提示:断言未通过')
# 断言12满足 close_to(10, 2)--》10 上下浮动2,
assert_that(12, close_to(10, 2))
# 断言字符串包含kitty
assert_that("hello kitty", contains_string("kitty"))<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/29 20:40
# @Author : Yuki
class TestAppWechat:
def setup(self):
pass
|
9114b27928c18c908ec3ed9da51d817b2216377a
|
[
"Python",
"INI"
] | 59 |
Python
|
JuliaZxr/LagouPractice_Yuki
|
d9e58cebc5c3d45a29cab85d7990dd1c2a961a53
|
0e469cb1a19c1bb438de0ab143ae13d5bf60f9dd
|
refs/heads/beta
|
<repo_name>mrzac/Jeedom-Volets<file_sep>/core/class/Volets.class.php
<?php
require_once dirname(__FILE__) . '/../../../../core/php/core.inc.php';
class Volets extends eqLogic {
public static function deamon_info() {
$return = array();
$return['log'] = 'Volets';
$return['launchable'] = 'ok';
$return['state'] = 'nok';
foreach(eqLogic::byType('Volets') as $Volet){
if($Volet->getIsEnable()){
$listener = listener::byClassAndFunction('Volets', 'pull', array('Volets_id' => $Volet->getId()));
if (!is_object($listener))
return $return;
if ($Volet->getConfiguration('DayNight')){
$cron = cron::byClassAndFunction('Volets', 'ActionJour', array('Volets_id' => $Volet->getId()));
if (!is_object($cron))
return $return;
$cron = cron::byClassAndFunction('Volets', 'ActionNuit', array('Volets_id' => $Volet->getId()));
if (!is_object($cron))
return $return;
}
}
}
$return['state'] = 'ok';
return $return;
}
public static function deamon_start($_debug = false) {
log::remove('Volets');
self::deamon_stop();
$deamon_info = self::deamon_info();
if ($deamon_info['launchable'] != 'ok')
return;
if ($deamon_info['state'] == 'ok')
return;
foreach(eqLogic::byType('Volets') as $Volet)
$Volet->save();
}
public static function deamon_stop() {
$listener = listener::byClassAndFunction('Volets', 'pull');
if (is_object($listener))
$listener->remove();
$cron = cron::byClassAndFunction('Volets', 'ActionJour');
if (is_object($cron))
$cron->remove();
$cron = cron::byClassAndFunction('Volets', 'ActionNuit');
if (is_object($cron))
$cron->remove();
}
public static function pull($_option) {
log::add('Volets', 'debug', 'Objet mis à jour => ' . json_encode($_option));
$Volet = Volets::byId($_option['Volets_id']);
if (is_object($Volet) && $Volet->getIsEnable()) {
$Event = cmd::byId($_option['event_id']);
if(is_object($Event)){
switch($Event->getlogicalId()){
case 'azimuth360':
log::add('Volets', 'info', 'Gestion des volets par l\'azimuth');
$Volet->ActionAzimute($_option['value']);
break;
case 'sunrise':
log::add('Volets', 'info', 'Replanification de l\'ouverture au lever du soleil');
$timstamp=$Volet->CalculHeureEvent($_option['value'],'DelaisDay');
$Schedule=date("i",$timstamp) . ' ' . date("H",$timstamp) . ' * * * *';
$cron = $Volet->CreateCron($Schedule, 'ActionJour');
break;
case 'sunset':
log::add('Volets', 'info', 'Replanification de la fermeture au coucher du soleil');
$timstamp=$Volet->CalculHeureEvent($_option['value'],'DelaisNight');
$Schedule=date("i",$timstamp) . ' ' . date("H",$timstamp) . ' * * * *';
$cron = $Volet->CreateCron($Schedule, 'ActionNuit');
break;
}
}
}
}
public static function ActionJour($_option) {
log::add('Volets', 'debug', 'Objet mis à jour => ' . json_encode($_option));
$Volet = Volets::byId($_option['Volets_id']);
if (is_object($Volet) && $Volet->getIsEnable()) {
log::add('Volets', 'info', 'Exécution de la gestion du lever du soleil '.$Volet->getHumanName());
$result=$Volet->EvaluateCondition('open','DayNight');
if($result){
$Action=$Volet->getConfiguration('action');
$Volet->ExecuteAction($Action['open']);
}else{
log::add('Volets', 'info', 'Replanification de l\'évaluation des conditiond d\'ouverture au lever du soleil');
$timstamp=$Volet->CalculHeureEvent(date('Hi'),'DelaisEval');
$Schedule=date("i",$timstamp) . ' ' . date("H",$timstamp) . ' * * * *';
$cron = $Volet->CreateCron($Schedule, 'ActionJour', array('Volets_id' => intval($Volet->getId())));
}
}
}
public static function ActionNuit($_option) {
log::add('Volets', 'debug', 'Objet mis à jour => ' . json_encode($_option));
$Volet = Volets::byId($_option['Volets_id']);
if (is_object($Volet) && $Volet->getIsEnable()) {
log::add('Volets', 'info', 'Exécution de la gestion du coucher du soleil '.$Volet->getHumanName());
$result=$Volet->EvaluateCondition('close','DayNight');
if($result){
$Action=$Volet->getConfiguration('action');
$Volet->ExecuteAction($Action['close']);
}else{
log::add('Volets', 'info', 'Replanification de l\'évaluation des conditiond de fermeture au coucher du soleil');
$timstamp=$Volet->CalculHeureEvent(date('Hi'),'DelaisEval');
$Schedule=date("i",$timstamp) . ' ' . date("H",$timstamp) . ' * * * *';
$cron = $Volet->CreateCron($Schedule, 'ActionNuit', array('Volets_id' => intval($Volet->getId())));
}
}
}
public function checkJour() {
$heliotrope=eqlogic::byId($this->getConfiguration('heliotrope'));
if(is_object($heliotrope)){
$sunrise=$heliotrope->getCmd(null,'sunrise');
if(is_object($sunrise)){
$value=$sunrise->execCmd();
$Jours= new DateTime('@' .$this->CalculHeureEvent($value,'DelaisDay'));
}
else{
log::add('Volets','debug','L\'objet "sunrise" n\'a pas été trouvé');
return false;
}
$sunset=$heliotrope->getCmd(null,'sunset');
if(is_object($sunset)){
$value=$sunset->execCmd();
$Nuit= new DateTime('@' .$this->CalculHeureEvent($value,'DelaisNight'));
}
else{
log::add('Volets','debug','L\'objet "sunset" n\'a pas été trouvé');
return false;
}
$Now=new DateTime();
if($Now>$Jours && $Now<$Nuit)
return true;
}
return false;
}
public function CheckAngle($Azimuth) {
$Droite=$this->getConfiguration('Droite');
$Gauche=$this->getConfiguration('Gauche');
$Centre=$this->getConfiguration('Centre');
if(is_array($Droite)&&is_array($Centre)&&is_array($Gauche)){
$AngleCntDrt=$this->getAngle(
$Centre['lat'],
$Centre['lng'],
$Droite['lat'],
$Droite['lng']);
$AngleCntGau=$this->getAngle(
$Centre['lat'],
$Centre['lng'],
$Gauche['lat'],
$Gauche['lng']);
log::add('Volets','info','La fenêtre d\'ensoleillement '.$this->getHumanName().' est comprise entre : '.$AngleCntDrt.'° et '.$AngleCntGau.'°');
if ($AngleCntDrt < $AngleCntGau){
if($AngleCntDrt <= $Azimuth && $Azimuth <= $AngleCntGau)
return true;
}else{
if($AngleCntDrt <= $Azimuth && $Azimuth <= 360)
return true;
if(0 <= $Azimut && $Azimuth <= $AngleCntGau)
return true;
}
}
return false;
}
public function SelectAction($Azimuth) {
$Action=false;
$StateCmd=$this->getCmd(null,'state');
if(!is_object($StateCmd))
return false;
$isInWindows=$this->getCmd(null,'isInWindows');
if(!is_object($isInWindows))
return false;
if($this->CheckAngle($Azimuth)){
if(!$StateCmd->execCmd() || $StateCmd->execCmd()!= ""){
$StateCmd->event(true);
log::add('Volets','info',$this->getHumanName().' Le soleil est dans la fenêtre');
if($isInWindows->execCmd()){
$Action='open';
log::add('Volets','info',$this->getHumanName().' Le plugin est configuré en mode hiver');
}else{
$Action='close';
log::add('Volets','info',$this->getHumanName().' Le plugin est configuré en mode été');
}
}
}else{
if($StateCmd->execCmd() || $StateCmd->execCmd()!= ""){
$StateCmd->event(false);
log::add('Volets','info',$this->getHumanName().' Le soleil n\'est pas dans la fenêtre');
if($isInWindows->execCmd()){
$Action='close';
log::add('Volets','info',$this->getHumanName().' Le plugin est configuré en mode été');
}else{
$Action='open';
log::add('Volets','info',$this->getHumanName().' Le plugin est configuré en mode hiver');
}
}
}
$StateCmd->save();
return $Action;
}
public function ActionAzimute($Azimuth) {
if($this->getCmd(null,'isArmed')->execCmd()){
if($this->checkJour()){
log::add('Volets', 'info', 'Exécution de '.$this->getHumanName());
$Evenement=$this->SelectAction($Azimuth);
if($Evenement != false){
$result=$this->EvaluateCondition($Evenement,'Helioptrope');
if($result){
log::add('Volets','info',$this->getHumanName().' Les conditions sont remplies');
$Action=$this->getConfiguration('action');
$this->ExecuteAction($Action[$Evenement]);
}
}
return;
}
log::add('Volets','debug',$this->getHumanName().' Il fait nuit, la gestion par azimuth est désactivé');
}
else
log::add('Volets','debug',$this->getHumanName().' Gestion par azimute désactivé');
}
public function ExecuteAction($Action) {
foreach($Action as $cmd){
if (isset($cmd['enable']) && $cmd['enable'] == 0)
continue;
try {
$options = array();
if (isset($cmd['options'])) {
$options = $cmd['options'];
}
scenarioExpression::createAndExec('action', $cmd['cmd'], $options);
} catch (Exception $e) {
log::add('Volets', 'error', __('Erreur lors de l\'éxecution de ', __FILE__) . $action['cmd'] . __('. Détails : ', __FILE__) . $e->getMessage());
}
$Commande=cmd::byId(str_replace('#','',$cmd['cmd']));
if(is_object($Commande)){
if($this->getConfiguration('isRandom'))
sleep(rand(0,$this->getConfiguration('DelaisPresence')));
log::add('Volets','debug',$this->getHumanName().' Exécution de '.$Commande->getHumanName());
$Commande->event($cmd['options']);
}
}
}
public function CalculHeureEvent($HeureStart, $delais) {
if(strlen($HeureStart)==3)
$Heure=substr($HeureStart,0,1);
else
$Heure=substr($HeureStart,0,2);
$Minute=floatval(substr($HeureStart,-2));
if($this->getConfiguration($delais)!='')
$Minute+=floatval($this->getConfiguration($delais));
while($Minute>=60){
$Minute-=60;
$Heure+=1;
}
return mktime($Heure,$Minute);
}
public function CreateCron($Schedule, $logicalId) {
$cron =cron::byClassAndFunction('Volets', $logicalId, array('Volets_id' => $this->getId()));
if (!is_object($cron)) {
$cron = new cron();
$cron->setClass('Volets');
$cron->setFunction($logicalId);
$cron->setOption(array('Volets_id' => $this->getId()));
$cron->setEnable(1);
$cron->setDeamon(0);
$cron->setSchedule($Schedule);
$cron->save();
}
else{
$cron->setSchedule($Schedule);
$cron->save();
}
return $cron;
}
public function EvaluateCondition($evaluate,$TypeGestion){
foreach($this->getConfiguration('condition') as $condition){
if(($evaluate==$condition['evaluation']||$condition['evaluation']=='all') && ($TypeGestion==$condition['TypeGestion']||$condition['TypeGestion']=='all')){
$expression = scenarioExpression::setTags($condition['expression']);
$message = __('Evaluation de la condition : [', __FILE__) . trim($expression) . '] = ';
$result = evaluate($expression);
if (is_bool($result)) {
if ($result) {
$message .= __('Vrai', __FILE__);
} else {
$message .= __('Faux', __FILE__);
}
} else {
$message .= $result;
}
log::add('Volets','info',$this->getHumanName().' : '.$message);
if(!$result){
log::add('Volets','info',$this->getHumanName().' Les conditions ne sont pas remplies');
return false;
}
}
}
return true;
}
public function getAngle($latitudeOrigine,$longitudeOrigne, $latitudeDest,$longitudeDest) {
$longDelta = $longitudeDest - $longitudeOrigne;
$y = sin($longDelta) * cos($latitudeDest);
$x = (cos($latitudeOrigine)*sin($latitudeDest)) - (sin($latitudeOrigine)*cos($latitudeDest)*cos($longDelta));
$angle = rad2deg(atan2($y, $x));
while ($angle < 0) {
$angle += 360;
}
return floatval($angle % 360);
}
public function StartDemon() {
if($this->getIsEnable()){
$heliotrope=eqlogic::byId($this->getConfiguration('heliotrope'));
if(is_object($heliotrope)){
$sunrise=$heliotrope->getCmd(null,'sunrise');
if(!is_object($sunrise))
return false;
$sunset=$heliotrope->getCmd(null,'sunset');
if(!is_object($sunset))
return false;
$listener = listener::byClassAndFunction('Volets', 'pull', array('Volets_id' => $this->getId()));
if (!is_object($listener))
$listener = new listener();
$listener->setClass('Volets');
$listener->setFunction('pull');
$listener->setOption(array('Volets_id' => $this->getId()));
$listener->emptyEvent();
if ($this->getConfiguration('Helioptrope'))
$listener->addEvent($heliotrope->getCmd(null,'azimuth360')->getId());
if ($this->getConfiguration('DayNight')){
$listener->addEvent($sunrise->getId());
$listener->addEvent($sunset->getId());
$value=$sunrise->execCmd();
$timstamp=$this->CalculHeureEvent($value,'DelaisDay');
$Schedule=date("i",$timstamp) . ' ' . date("H",$timstamp) . ' * * * *';
$cron = $this->CreateCron($Schedule, 'ActionJour', array('Volets_id' => intval($this->getId())));
$value=$sunset->execCmd();
$timstamp=$this->CalculHeureEvent($value,'DelaisNight');
$Schedule=date("i",$timstamp) . ' ' . date("H",$timstamp) . ' * * * *';
$cron = $this->CreateCron($Schedule, 'ActionNuit', array('Volets_id' => intval($this->getId())));
}
$listener->save();
}
}
}
public static function AddCommande($eqLogic,$Name,$_logicalId,$Type="info", $SubType='binary',$visible,$Template='') {
$Commande = $eqLogic->getCmd(null,$_logicalId);
if (!is_object($Commande))
{
$Commande = new VoletsCmd();
$Commande->setId(null);
$Commande->setName($Name);
$Commande->setIsVisible($visible);
$Commande->setLogicalId($_logicalId);
$Commande->setEqLogic_id($eqLogic->getId());
$Commande->setType($Type);
$Commande->setSubType($SubType);
}
$Commande->setTemplate('dashboard',$Template );
$Commande->setTemplate('mobile', $Template);
$Commande->save();
return $Commande;
}
public function postSave() {
self::AddCommande($this,"Position du soleil","state","info", 'binary',true,'sunInWindows');
$isInWindows=self::AddCommande($this,"Etat mode","isInWindows","info","binary",false,'isInWindows');
$inWindows=self::AddCommande($this,"Mode","inWindows","action","other",true,'inWindows');
$inWindows->setValue($isInWindows->getId());
$inWindows->save();
$isArmed=self::AddCommande($this,"Etat d'activation","isArmed","info","binary",false,'lock');
$Armed=self::AddCommande($this,"Activer","arme","action","other",true,'lock');
$Armed->setValue($isArmed->getId());
$Armed->save();
$this->StartDemon();
}
public function postRemove() {
$listener = listener::byClassAndFunction('Volets', 'pull', array('Volets_id' => $this->getId()));
if (is_object($listener))
$listener->remove();
$cron = cron::byClassAndFunction('Volets', 'ActionJour', array('Volets_id' => $this->getId()));
if (is_object($cron))
$cron->remove();
$cron = cron::byClassAndFunction('Volets', 'ActionNuit', array('Volets_id' => $this->getId()));
if (is_object($cron))
$cron->remove();
}
}
class VoletsCmd extends cmd {
public function execute($_options = null) {
switch($this->getLogicalId()){
case 'arme':
case 'inWindows':
$Listener=cmd::byId(str_replace('#','',$this->getValue()));
if (is_object($Listener)) {
if($Listener->execCmd())
$Listener->event(false);
else
$Listener->event(true);
$Listener->setCollectDate(date('Y-m-d H:i:s'));
$Listener->save();
}
break;
}
}
}
?>
<file_sep>/doc/fr_FR/Commandes.asciidoc
Pour chaque equipement, le plugin vas creer des commande
image::../images/Volets_screenshot_Widget.jpg[]
=== Le mode et son etat
Ces 2 commandes vont vous permetre de basculer le plugin en mode été ou hivers.
C'est a vous de determiner a quel moment on doit gerer se changement
image::../images/ModeClose.png[]
L'icone si dessus montre le mode été, le volet fermé lorsque le soleil est dans la fenetre
image::../images/ModeOpen.png[]
L'icone si dessus montre le mode hivers, le volet ouvert lorsque le soleil est dans la fenetre
=== la position du soleil
Cette commande nous informe si le soleil est dans la fenetre ou pas
image::../images/SunInWindows.png[]
Dans la fenetre
image::../images/SunOutWindows.png[]
Hors fenetres
<file_sep>/doc/ru_RU/index.asciidoc
= Gestion de volets
== Description
Ce plugin a pour but de gérer facilement et automatiquement vos volets.
Celui-ci est entièrement basé sur le plugin Heliotrope qui est un prérequis pour l'utilisation de ce plugin.
Une fois configurer,
* le plugin gérera automatiquement l'ouverture et la fermerture de vos volets au levée du soleil et à la tombée de la nuit
* En mode été, il fermera les volets lorsque le soleil sera dans la fenêtre, afin de préserver une température idéal dans la maison
* En mode hiver, il ouvrira les volets pour permettre au soleil de chauffer la piece et faire des économies d'énergie
== Commande et widget
include::Commandes.asciidoc[]
== Paramétrage
include::Parametrage.asciidoc[]<file_sep>/desktop/php/Volets.php
<?php
if (!isConnect('admin')) {
throw new Exception('{{401 - Accès non autorisé}}');
}
sendVarToJS('eqType', 'Volets');
$eqLogics = eqLogic::byType('Volets');
//include_file('desktop', 'OpenLayers', 'js', 'Volets');
?>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<KEY>"></script>
<div class="row row-overflow">
<div class="col-lg-2">
<div class="bs-sidebar">
<ul id="ul_eqLogic" class="nav nav-list bs-sidenav">
<a class="btn btn-default eqLogicAction" style="width : 50%;margin-top : 5px;margin-bottom: 5px;" data-action="add"><i class="fa fa-plus-circle"></i> {{Ajouter}}</a>
<li class="filter" style="margin-bottom: 5px;"><input class="filter form-control input-sm" placeholder="{{Rechercher}}" style="width: 100%"/></li>
<?php
foreach ($eqLogics as $eqLogic)
echo '<li class="cursor li_eqLogic" data-eqLogic_id="' . $eqLogic->getId() . '"><a>' . $eqLogic->getHumanName(true) . '</a></li>';
?>
</ul>
</div>
</div>
<div class="col-lg-10 col-md-9 col-sm-8 eqLogicThumbnailDisplay" style="border-left: solid 1px #EEE; padding-left: 25px;">
<legend>{{Mes Zones de gestion volets}}</legend>
<div class="eqLogicThumbnailContainer">
<div class="cursor eqLogicAction" data-action="add" style="background-color : #ffffff; height : 200px;margin-bottom : 10px;padding : 5px;border-radius: 2px;width : 160px;margin-left : 10px;" >
<center>
<i class="fa fa-plus-circle" style="font-size : 7em;color:#94ca02;"></i>
</center>
<span style="font-size : 1.1em;position:relative; top : 23px;word-break: break-all;white-space: pre-wrap;word-wrap: break-word;;color:#94ca02"><center>Ajouter</center></span>
</div>
<?php
foreach ($eqLogics as $eqLogic) {
$opacity = '';
if ($eqLogic->getIsEnable() != 1) {
$opacity = '
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100);
-o-filter: grayscale(100%);
-ms-filter: grayscale(100%);
filter: grayscale(100%); opacity: 0.35;';
}
echo '<div class="eqLogicDisplayCard cursor" data-eqLogic_id="' . $eqLogic->getId() . '" style="background-color : #ffffff; height : 200px;margin-bottom : 10px;padding : 5px;border-radius: 2px;width : 160px;margin-left : 10px;' . $opacity . '" >';
echo "<center>";
echo '<img src="plugins/Volets/doc/images/Volets_icon.png" height="105" width="95" />';
echo "</center>";
echo '<span style="font-size : 1.1em;position:relative; top : 15px;word-break: break-all;white-space: pre-wrap;word-wrap: break-word;"><center>' . $eqLogic->getHumanName(true, true) . '</center></span>';
echo '</div>';
}
?>
</div>
</div>
<div class="col-lg-10 eqLogic" style="border-left: solid 1px #EEE; padding-left: 25px;display: none;">
<form class="form-horizontal">
<fieldset>
<legend>
<i class="fa fa-arrow-circle-left eqLogicAction cursor" data-action="returnToThumbnailDisplay"></i> {{Général}}
<i class="fa fa-cogs eqLogicAction pull-right cursor expertModeVisible" data-action="configure"></i>
<a class="btn btn-default btn-xs pull-right expertModeVisible eqLogicAction" data-action="copy"><i class="fa fa-copy"></i>{{Dupliquer}}</a>
<a class="btn btn-success btn-xs eqLogicAction pull-right" data-action="save"><i class="fa fa-check-circle"></i> Sauvegarder</a>
<a class="btn btn-danger btn-xs eqLogicAction pull-right" data-action="remove"><i class="fa fa-minus-circle"></i> Supprimer</a>
</legend>
</fieldset>
</form>
<div class="row" style="padding-left:25px;">
<ul class="nav nav-tabs" id="tab_zones">
<li class="active"><a href="#tab_general"><i class="fa fa-cogs"></i> {{Général}}</a></li>
<li class="SelectMap"><a href="#tab_map"><i class="fa fa-map"></i> {{Afficher la carte}}</a></li>
<li><a href="#tab_condition"><i class="fa fa-pencil"></i> {{Conditions d'exécution}}</a></li>
<li><a href="#tab_ouverture"><i class="fa fa-pencil"></i> {{Actions d'ouverture}}</a></li>
<li><a href="#tab_fermeture"><i class="fa fa-pencil"></i> {{Actions de fermeture}}</a></li>
<li><a href="#tab_cmd"><i class="fa fa-pencil"></i> {{Commandes du plugin}}</a></li>
</ul>
<div class="tab-content TabCmdZone">
<div class="tab-pane active" id="tab_general">
<form class="form-horizontal">
<fieldset>
<div class="form-group ">
<label class="col-sm-2 control-label">{{Nom de la Zone}}
<sup>
<i class="fa fa-question-circle tooltips" title="Indiquer le nom de votre zone" style="font-size : 1em;color:grey;"></i>
</sup>
</label>
<div class="col-sm-5">
<input type="text" class="eqLogicAttr form-control" data-l1key="id" style="display : none;" />
<input type="text" class="eqLogicAttr form-control" data-l1key="name" placeholder="{{Nom du groupe de zones}}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" >{{Objet parent}}
<sup>
<i class="fa fa-question-circle tooltips" title="Indiquer l'objet dans lequel le widget de cette zone apparaitra sur le Dashboard" style="font-size : 1em;color:grey;"></i>
</sup>
</label>
<div class="col-sm-5">
<select id="sel_object" class="eqLogicAttr form-control" data-l1key="object_id">
<option value="">{{Aucun}}</option>
<?php
foreach (object::all() as $object)
echo '<option value="' . $object->getId() . '">' . $object->getName() . '</option>';
?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">
{{Catégorie}}
<sup>
<i class="fa fa-question-circle tooltips" title="Choisissez une catégorie
Cette information n'est pas obigatoire mais peut être utile pour filtrer les widgets" style="font-size : 1em;color:grey;"></i>
</sup>
</label>
<div class="col-md-8">
<?php
foreach (jeedom::getConfiguration('eqLogic:category') as $key => $value) {
echo '<label class="checkbox-inline">';
echo '<input type="checkbox" class="eqLogicAttr" data-l1key="category" data-l2key="' . $key . '" />' . $value['name'];
echo '</label>';
}
?>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" >
{{Etat du widget}}
<sup>
<i class="fa fa-question-circle tooltips" title="Choisissez les options de visibilité et d'activation
Si l'équipement n'est pas activé, il ne sera pas utilisable dans Jeedom ni visible sur le Dashboard
Si l'équipement n'est pas visible, il sera caché sur le Dashboard" style="font-size : 1em;color:grey;"></i>
</sup>
</label>
<div class="col-sm-5">
<label>{{Activer}}</label>
<input type="checkbox" class="eqLogicAttr" data-label-text="{{Activer}}" data-l1key="isEnable" checked/>
<label>{{Visible}}</label>
<input type="checkbox" class="eqLogicAttr" data-label-text="{{Visible}}" data-l1key="isVisible" checked/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">{{Exécution des actions aléatoires}}
<sup>
<i class="fa fa-question-circle tooltips" title="{{En activant cette fonction, les actions se produiront les unes après les autres avec un délai aléatoire (entre 0 et 10s)}}"></i>
</sup>
</label>
<div class="col-sm-5">
<label>{{Présence}}</label>
<input type="checkbox" class="eqLogicAttr" data-label-text="{{Activer}}" data-l1key="configuration" data-l2key="isRandom" />
</div>
</div>
<div class="form-group Presence" style="display: none;">
<label class="col-sm-2 control-label">{{Temps maximum pour la simulation de présence (min)}}
<sup>
<i class="fa fa-question-circle tooltips" title="Saisir le délai maximum entre l'execution des action (min)"></i>
</sup>
</label>
<div class="col-sm-5">
<input type="text" class="eqLogicAttr form-control" data-l1key="configuration" data-l2key="DelaisPresence" placeholder="{{Saisir le délai maximum entre l'execution des action (min)}}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">{{Héliotrope}}
<sup>
<i class="fa fa-question-circle tooltips" title="Sélectioner l'équipement du plugin Héliotrope source"></i>
</sup>
</label>
<div class="col-sm-5">
<select class="eqLogicAttr" data-l1key="configuration" data-l2key="heliotrope">
<option>Aucun</option>
<?php
foreach(eqLogic::byType('heliotrope') as $heliotrope)
echo '<option value="'.$heliotrope->getId().'">'.$heliotrope->getName().'</option>';
?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" >
{{Choisir les gestions desirer}}
<sup>
<i class="fa fa-question-circle tooltips" title="Choisissez les types de gestion que vous souhaitez pour cette zone" style="font-size : 1em;color:grey;"></i>
</sup>
</label>
<div class="col-sm-5">
<label>{{Jour / Nuit}}</label>
<input type="checkbox" class="eqLogicAttr" data-label-text="{{Jour / Nuit}}" data-l1key="configuration" data-l2key="DayNight" checked/>
<label>{{Position du soleil}}</label>
<input type="checkbox" class="eqLogicAttr" data-label-text="{{Position du soleil}}" data-l1key="configuration" data-l2key="Helioptrope" checked/>
</div>
</div>
<!--div class="form-group">
<label class="col-sm-2 control-label">{{Choisir le type de gestion du groupe}}
<sup>
<i class="fa fa-question-circle tooltips" title="Sélectionner le type de gestion"></i>
</sup>
</label>
<div class="col-sm-5">
<select class="eqLogicAttr" data-l1key="configuration" data-l2key="TypeGestion">
<option value="DayNight">Jour / Nuit</option>
<option value="Helioptrope">Position du soleil</option>
</select>
</div>
</div-->
<div class="form-group">
<label class="col-sm-2 control-label">{{Délai au lever du jour (min)}}
<sup>
<i class="fa fa-question-circle tooltips" title="Saisir le délai avant (-) ou après (+)"></i>
</sup>
</label>
<div class="col-sm-5">
<input type="text" class="eqLogicAttr form-control" data-l1key="configuration" data-l2key="DelaisDay" placeholder="{{Délai au lever du jour (min)}}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">{{Délai à la tombée de la nuit (min)}}
<sup>
<i class="fa fa-question-circle tooltips" title="Saisir le délai avant (-) ou après (+)"></i>
</sup>
</label>
<div class="col-sm-5">
<input type="text" class="eqLogicAttr form-control" data-l1key="configuration" data-l2key="DelaisNight" placeholder="{{Délai à la tombée de la nuit (min)}}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">{{Délais de réévaluation (min)}}
<sup>
<i class="fa fa-question-circle tooltips" title="Saisir le délai de réévaluation des conditions (min)"></i>
</sup>
</label>
<div class="col-sm-5">
<input type="text" class="eqLogicAttr form-control" data-l1key="configuration" data-l2key="DelaisEval" placeholder="{{Délai de réévaluation (min)}}"/>
</div>
</div>
<input type="hidden" class="eqLogicAttr form-control" data-l1key="configuration" data-l2key="Droite"/>
<input type="hidden" class="eqLogicAttr form-control" data-l1key="configuration" data-l2key="Centre"/>
<input type="hidden" class="eqLogicAttr form-control" data-l1key="configuration" data-l2key="Gauche"/>
</fieldset>
</form>
</div>
<div class="tab-pane active" id="tab_map">
<div id="MyMap" style="width:800px;height:600px;margin:auto;"></div>
</div>
<div class="tab-pane" id="tab_condition">
<form class="form-horizontal">
<fieldset>
<legend>{{Les conditions d'exécution :}}
<sup>
<i class="fa fa-question-circle tooltips" title="Saisir toutes les conditions d'exécution de la gestion"></i>
</sup>
<a class="btn btn-success btn-xs conditionAttr" data-action="add" style="margin-left: 5px;">
<i class="fa fa-plus-circle"></i>
{{Ajouter Condition}}
</a>
</legend>
<div class="div_Condition"></div>
</fieldset>
</form>
</div>
<div class="tab-pane" id="tab_ouverture">
<form class="form-horizontal">
<fieldset>
<legend>{{Les actions d'ouverture :}}
<sup>
<i class="fa fa-question-circle tooltips" title="Saisir toutes les actions à mener à l'ouverture"></i>
</sup>
<a class="btn btn-success btn-xs ActionAttr" data-action="add" style="margin-left: 5px;">
<i class="fa fa-plus-circle"></i>
{{Ajouter une Action}}
</a>
</legend>
<div class="div_action"></div>
</fieldset>
</form>
</div>
<div class="tab-pane" id="tab_fermeture">
<form class="form-horizontal">
<fieldset>
<legend>{{Les actions de fermeture :}}
<sup>
<i class="fa fa-question-circle tooltips" title="Saisir toutes les actions à mener à la fermeture"></i>
</sup>
<a class="btn btn-success btn-xs ActionAttr" data-action="add" style="margin-left: 5px;">
<i class="fa fa-plus-circle"></i>
{{Ajouter une Action}}
</a>
</legend>
<div class="div_action"></div>
</fieldset>
</form>
</div>
<div class="tab-pane " id="tab_cmd">
<table id="table_cmd" class="table table-bordered table-condensed">
<thead>
<tr>
<th>Nom</th>
<th>Paramètre</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
<form class="form-horizontal">
<fieldset>
<div class="form-actions">
<a class="btn btn-danger eqLogicAction" data-action="remove"><i class="fa fa-minus-circle"></i> {{Supprimer}}</a>
<a class="btn btn-success eqLogicAction" data-action="save"><i class="fa fa-check-circle"></i> {{Sauvegarder}}</a>
</div>
</fieldset>
</form>
</div>
</div>
<?php include_file('desktop', 'Volets', 'js', 'Volets'); ?>
<?php include_file('core', 'plugin.template', 'js'); ?>
<file_sep>/plugin_info/install.php
function Volets_install(){
foreach(eqLogic::byType('Volets') as $eqLogic){
$eqLogic->save();
}
}
function Volets_update(){
foreach(eqLogic::byType('Volets') as $eqLogic){
$eqLogic->save();
}
}
|
ae4bb2acc9bd80dc06d474d7196434d676e9e9ae
|
[
"AsciiDoc",
"PHP"
] | 5 |
PHP
|
mrzac/Jeedom-Volets
|
3ee019dcd21fa528607b024eb3d79a171ccc9c4e
|
ff38c5450f079d25ec2743293007a17a2cb081c9
|
refs/heads/main
|
<file_sep>#pragma once
#include "debug.h"
#define MOUNT_DIR(type, device, dir, opts) \
INFO("Mounting %s\n", dir); \
util_system("mount -t %s %s %s -o %s", type, device, dir, opts)
#define REMOUNT(dir) \
INFO("Remounting %s\n", dir); \
util_system("mount -o remount %s", dir)
#define MOUNT_FS() \
INFO("Mounting file system\n"); \
util_system("mount -a -t no nfs no nfs4 no smbfs no cifs no codafs no ncpfs no shfs no fuse no fuseblk no glusterfs no davfs no fuse.glusterfs -O no_netdev")
<file_sep>#pragma once
#include <signal.h>
#define REBOOT() \
run_scripts("/etc/rc6.d", "stop"); \
sync(); \
reboot(RB_AUTOBOOT);
#define POWEROFF() \
run_scripts("/etc/rc0.d", "stop"); \
sync(); \
reboot(LINUX_REBOOT_CMD_POWER_OFF);
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <limits.h>
#include <string.h>
#include <dirent.h>
#include <fcntl.h>
#include <linux/reboot.h>
#include <sys/reboot.h>
#include "bool.h"
#include "util.h"
#include "debug.h"
#include "mount.h"
#include "config.h"
#include "handler.h"
#include "service/service.h"
void set_hostname(void) {
char hostname[HOST_NAME_MAX] = {0};
read_file_content("/etc/hostname", hostname, HOST_NAME_MAX);
int fd = open("/proc/sys/kernel/hostname", O_WRONLY | O_CREAT, 0644);
if (fd == -1) {
WARN("Failed to read hostname\n");
return;
}
INFO("Setting hostname %s\n", hostname);
write(fd, hostname, strlen(hostname));
close(fd);
}
void run_startup(void) {
pid_t pid = getpid();
signal(SIGCHLD, SIG_IGN);
if (pid != 1) {
ERROR("Please run as PID-1\n");
return;
}
REMOUNT("/");
MOUNT_FS();
RUN("swapon -a");
set_hostname();
INFO("Executing runlevel 3\n");
run_scripts("/etc/rc3.d", "start");
read_service("/etc/init.d");
START_TTY("1");
read_operation();
reap_processes();
}
int main(int argc, char **args) {
read_service("/etc/init.d");
read_operation();
if (argc > 1) {
switch(*args[1]) {
case '6':
REBOOT();
break;
case '0':
POWEROFF();
break;
default:
printf("Unhandled event: %s\n", args[1]);
break;
}
}
else {
run_startup();
}
return 0;
}
<file_sep>#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <limits.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include "bool.h"
#include "util.h"
#include "debug.h"
int util_stristr(char *haystack, char *needle) {
char *ptr = needle;
char *begin = haystack;
while (*haystack) {
if (*haystack++ == *needle) {
if (!(*++needle))
return haystack - begin;
}
else
needle = ptr;
}
return -1;
}
BOOL util_mem_exists(char *haystack, char *needle) {
char *ptr = needle;
while (*haystack) {
if (*haystack++ == *needle) {
if (!(*++needle))
return TRUE;
}
else
needle = ptr;
}
return FALSE;
}
char *read_file_content(char *file, char *ptr, int len) {
int fd = open(file, O_RDONLY);
struct stat st = {0};
fstat(fd, &st);
char *buffer = malloc(st.st_size * sizeof(char));
if (ptr == NULL)
read(fd, buffer, st.st_size);
else {
read(fd, ptr, len);
buffer = ptr;
}
close(fd);
return buffer;
}
void util_system(const char *fmt, ...) {
char *buffer;
va_list args;
va_start(args, fmt);
vasprintf(&buffer, fmt, args);
va_end(args);
DEBUG("%s\n", buffer);
system(buffer);
free(buffer);
}
void sockprintf(int fd, const char *fmt, ...) {
char *buffer;
va_list args;
va_start(args, fmt);
int len = vasprintf(&buffer, fmt, args);
va_end(args);
send(fd, buffer, len, MSG_NOSIGNAL);
free(buffer);
}
<file_sep>#pragma once
#include <stdint.h>
enum {
START,
STOP,
RESTART,
STATUS,
RUNNING,
DEAD
} typedef operation_t;
struct protocol_t {
uint8_t name_len;
operation_t op;
} typedef csum_t;
<file_sep>#pragma once
#include <sys/stat.h>
#include "bool.h"
#define START_TTY(x) spawn((char *[]){"/sbin/agetty", "--noclear", "tty"x"", NULL});
#define RUNNABLE(str) ((*str) != '.' && strcmp(str, "README"))
#define LEN(x) (sizeof(x) / sizeof(*x))
#define RUN(x) system(x)
//define EXISTS(x) (stat(x, &(stat){0}) == 0)
/* utilities */
char *read_file_content(char *, char *, int);
int util_stristr(char *, char *);
void sockprintf(int, const char *, ...);
void util_system(const char *, ...);
void reap_processes(void);
void run_scripts(char *, char *);
void spawn(char **);
/* shutdown utilities */
void wait_for_death(void);
void killall(int);
<file_sep>#pragma once
#define ERROR(fmt, ...) printf("\x1b[91mERROR\x1b[0m: " fmt, ##__VA_ARGS__)
#define WARN(fmt, ...) printf("\x1b[93mWARN\x1b[0m: " fmt, ##__VA_ARGS__)
#define INFO(fmt, ...) printf("\x1b[92mINFO\x1b[0m: " fmt, ##__VA_ARGS__)
#ifdef DEBUG
#define DEBUG printf("\x1b[95mDEBUG\x1b[0m: " fmt, ##__VA_ARGS__)
#else
#define DEBUG(...)
#endif
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include "util.h"
#include "debug.h"
void run_scripts(char *directory, char *action) {
struct dirent *file = NULL;
DIR *dir = opendir(directory);
while ((file = readdir(dir))) {
if (RUNNABLE(file->d_name)) {
DEBUG("Running %s/%s\n", directory, file->d_name);
util_system("%s/%s %s", directory, file->d_name, action);
}
}
closedir(dir);
}
<file_sep>#pragma once
#define RUNLEVEL "2"
/*
S - true single user mode usually drops you into a minimal root shell
1 - Administrative mode, you get a standard login request before access
2 - Multi-user without TCP/IP networking -- could use serial ports for other logins
3 - Multi-user with TCP/IP networking and text
4 - To be determined by the system owner
5 - Multi-User with TCP/IP networking and graphic console
6 - reboot
0 - shutdown and power down
*/
<file_sep>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <signal.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/un.h>
#include <sys/socket.h>
#include "../util.h"
#include "../bool.h"
#include "../debug.h"
#include "protocol.h"
#include "service.h"
service_t *head = NULL;
char *find_property(char data[], char property[]) {
int off = util_stristr(data, property);
if (off != -1) {
int end = util_stristr(data + off, "\n") - 1;
return strndup(data + off, end);
}
else {
return NULL;
}
}
service_t *parse_service(char *file) {
service_t *service = malloc(1 * sizeof(service_t));
char *buff = read_file_content(file, NULL, -1);
snprintf(service->file, PATH_MAX, "/etc/init.d/%s", file);
service->name = strdup(file);
return service;
}
void read_service(char *path) {
INFO("Preparing services.\n");
chdir(path);
struct dirent *file = NULL;
DIR *dir = opendir(path);
while ((file = readdir(dir))) {
if (*file->d_name == '.') continue;
service_t *service = parse_service(file->d_name);
if (service) {
add_service(service);
}
else {
WARN("Failed to parse service: %s\n", file->d_name);
}
}
closedir(dir);
}
void add_service(service_t *service) {
if (!head) {
head = service;
}
else {
service->next = head;
head = service;
}
}
void modify_service(int fd, service_t *service, char *state) {
pid_t pid = fork();
if (pid != 0)
return;
char *run[] = {service->file, state, NULL};
INFO("Starting service: %s\n", service->file);
close(1);
close(2);
dup2(fd, 1);
dup2(fd, 2);
execvp(run[0], run);
}
service_t *find_service(char *name) {
service_t *tmp = head;
while (tmp) {
if (!strcmp(tmp->name, name))
return tmp;
tmp = tmp->next;
}
return NULL;
}
void service_ctl(int fd, char *name, operation_t op) {
service_t *service = find_service(name);
if (!service) {
sockprintf(fd, "Failed to find service: %s\n", name);
return;
}
switch (op) {
case START:
modify_service(fd, service, "start");
break;
case STOP:
modify_service(fd, service, "stop");
break;
case RESTART:
modify_service(fd, service, "restart");
break;
case STATUS:
modify_service(fd, service, "status");
break;
}
}
void read_operation(void) {
int fd = socket(AF_UNIX, SOCK_STREAM, 0), client;
struct sockaddr_un addr = {AF_UNIX, SERVER};
unlink(SERVER);
INFO("Starting service daemon\n");
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
ERROR("Failed to bind for service manager.\n");
return;
}
if (listen(fd, 1) == -1) {
ERROR("Failed to listen for service manager.\n");
return;
}
socklen_t len = sizeof(addr);
csum_t csum = {0};
while (TRUE) {
if ((client = accept(fd, (struct sockaddr *)&addr, &len)) != -1) {
int n = recv(client, &csum, sizeof(csum), MSG_NOSIGNAL);
if (csum.name_len > 0) {
char name[csum.name_len + 1];
name[csum.name_len] = 0;
recv(client, name, csum.name_len, MSG_NOSIGNAL);
service_ctl(client, name, csum.op);
}
close(client);
}
}
ERROR("Failed to init service system\n");
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <limits.h>
#include <string.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <linux/reboot.h>
#include <sys/reboot.h>
#include "util.h"
#include "handler.h"
void run_reboot(void) {
/*
puts("Going for a reboot");
killall(SIGTERM);
wait_for_death();
killall(SIGKILL);
system("umount -a -r");
reboot(RB_AUTOBOOT);
*/
sync();
reboot(RB_AUTOBOOT);
}
void run_shutdown(void) {
/*
puts("Going for a shutdown");
killall(SIGTERM);
wait_for_death();
killall(SIGKILL);
*/
sync();
reboot(LINUX_REBOOT_CMD_POWER_OFF);
}
void run_halt(void) {
sync();
reboot(LINUX_REBOOT_CMD_POWER_OFF);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include "bool.h"
#include "debug.h"
#include "handler.h"
void reap_processes(void) {
while (TRUE) {
for (int i = 0; i < 10; i++)
waitpid(-1, NULL, WNOHANG);
waitpid(-1, 0, 0);
}
}
// fork and exec is very normal for starting processes
void spawn(char **args) {
pid_t pid = fork();
if (pid == -1) {
ERROR("Failed to fork for spawn\n");
return;
}
else if (pid == 0) {
setsid();
execvp(args[0], args);
_exit(1);
}
}
<file_sep>#pragma once
#include <limits.h>
#include <signal.h>
#include "../bool.h"
#define SERVER "/tmp/rich.socket"
#define USER_DIR "/etc/richinit/services/user"
#define SYSTEM_DIR "/etc/richinit/services/system"
struct service_t {
char file[PATH_MAX], *name;
struct service_t *next;
} typedef service_t;
#define CHECK_SERVICE(service) \
(service->file && \
service->name &&)
#define TERMPROC(pid) \
if (pid) { \
kill(pid, SIGTERM); \
waitpid(pid, NULL, WNOHANG); \
kill(pid, SIGKILL); \
}
service_t *find_service(char *);
void add_service(service_t *);
void start_service(int, service_t *);
void read_operation(void);
void read_services(void);
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <limits.h>
#include <dirent.h>
#include <fcntl.h>
#include "debug.h"
#define WAIT_ROUNDS 20
// will rewrite this aids soon
void wait_for_death(void) {
struct dirent *file = NULL;
for (int i = 0; i < WAIT_ROUNDS; i++) {
DIR *dir = opendir("/proc/");
while ((file = readdir(dir))) {
if (*file->d_name >= '0' && *file->d_name <= '9') {
if (atoi(file->d_name) > 0) {
closedir(dir);
dir = NULL;
break;
}
}
}
if (dir) {
closedir(dir);
INFO("All processes died.");
return;
}
sleep(2);
}
}
void killall(int signal) {
struct dirent *file = NULL;
DIR *dir = opendir("/proc/");
while ((file = readdir(dir))) {
if (*file->d_name >= '0' && *file->d_name <= '9') {
pid_t pid = atoi(file->d_name);
if (pid > 2)
kill(pid, signal);
}
}
closedir(dir);
}
|
c85f44a960ac59c4f9e8a56987f3f77345505f58
|
[
"C"
] | 14 |
C
|
richsorg/richinit
|
13428be68d8b7be90a15fa479fe68a1794f4333b
|
164f20c2386cf25ca2ddfc97de7546201abd12e0
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using HtmlAgilityPack;
namespace MarkQuerier
{
class Program
{
static KeyValuePair<string, string>[] schools;
static System.IO.StreamWriter writer;
static void Main(string[] args)
{
Initialize();
Console.Write("选择要查询的学校序号或考号文件:");
var num = Console.ReadLine();
int i;
while (true)
{
if (int.TryParse(num, out i))//不能解析字符串为数字 或 数字>=学校列表长度
{
if (i > schools.Length || i < 0)
{
Console.Write("错误序号,请重新输入学校序号:");
num = Console.ReadLine();
continue;
}
else
{
FromSpecificSchool(i);
break;
}
}
else if (System.IO.File.Exists(num))
{
FromFile(num);
break;
}
else
{
Console.WriteLine("不存在文件");
continue;
}
}
Console.ReadLine();
Program_Exited(null, null);
}
private static void Initialize()
{
writer = new System.IO.StreamWriter("marks.csv", false, Encoding.UTF8);
writer.AutoFlush = true;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
System.Diagnostics.Process.GetCurrentProcess().Exited += Program_Exited;
AppDomain.CurrentDomain.ProcessExit += Program_Exited;
var lines = System.IO.File.ReadAllLines("schoolnumber.csv");//读取学校列表
schools = Array.ConvertAll(lines, str =>
{
var strs = str.Split(',');
var kvp = new KeyValuePair<string, string>(strs[0], strs[1]);
return kvp;
});
for (int i = 0; i < schools.Length; i++)//输出学校列表
{
var kvp = schools[i];
Console.WriteLine("{0}:{1}", i, kvp.Value);
}
Console.WriteLine("{0}:All", schools.Length);
}
private static void FromSpecificSchool(int i)
{
Console.WriteLine("按回车即停止,保存为csv文件并退出");
if (i == schools.Length)
{
for (int j = 0; j < schools.Length; j++)
{
ExecuteQuerying(j);
}
}
else
ExecuteQuerying(i);
}
private static void FromFile(string file)
{
Console.WriteLine("按回车即停止,保存为csv文件并退出");
var dict = Load(file);
Parallel.ForEach(dict, item =>
{
if (string.IsNullOrEmpty(item.Key))
{
return;//continue
}
new Query(new Student() { ExamReference = item.Key, Birth = item.Value, School = "广附" }, WriteMark, ReportFault).Execute();
});
}
private static void ExecuteQuerying(int i)
{
var kvp = schools[i];
QueryAllStudentsIn(kvp.Value, kvp.Key);
}
static void QueryAllStudentsIn(string schoolName, string schoolNumber)
{
for (int i = 1; i < 3; i++)//1&2 理科-文科
{
Parallel.For(1, 1000, (n, state) =>
{
var examRef = string.Format("01{0}{1}", schoolNumber.Insert(2, i.ToString()), n.ToString().PadLeft(3, '0'));
var query = new Query(new Student() { ExamReference = examRef, School = schoolName }, WriteMark, ReportFault);
query.Execute();
if (!query.Successful)
{
state.Break();
}
});
}
}
/// <summary>
/// 错误处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Program.ThrowError(e.ExceptionObject as Exception ?? new Exception());
}
static void Program_Exited(object sender, EventArgs e)
{
writer.Close();
System.Diagnostics.Process.Start("marks.csv");
}
static Dictionary<string, string> Load(string file)
{
var refs = new Dictionary<string, string>();
using (var reader = new System.IO.StreamReader(file, Encoding.Default))
{
while (!reader.EndOfStream)
{
var strs = reader.ReadLine().Split(',');
switch (strs.Length)
{
case 1:
refs.Add(strs[0], null);
break;
case 2:
refs.Add(strs[0], strs[1]);
break;
case 3:
refs.Add(strs[0], strs[2]);
break;
default:
Program.ThrowError(new ArgumentException("file format is incorrrect"));
return refs;
}
}
}
return refs;
}
/// <summary>
/// 输出分数
/// </summary>
/// <param name="student"></param>
static void WriteMark(Student student)
{
string line =
string.Format("{0},{1},{2},{3},{4},{5}", student.ExamReference,
student.School,
student.Name,
student.Birth,
student.Mark,
student.Recruiting);
ClearCurrentLine();
Console.WriteLine(line);
writer.WriteLine(line);
}
private static void ClearCurrentLine()
{
Console.Write("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
}
static void ReportFault(Student student)
{
ClearCurrentLine();
Console.Write("考号:{0} 无法查询", student.ExamReference);
}
/// <summary>
/// 不抛出错误,保证查询继续进行
/// </summary>
/// <param name="e"></param>
public static void ThrowError(Exception e)
{
//throw e;
Console.Error.WriteLine(e.Message);
}
}
}
<file_sep>markquerier
===========<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
namespace MarkQuerier
{
class Query
{
static readonly string[] birthmonths = { "9301", "9302", "9303", "9304", "9305", "9306", "9307", "9308", "9309", "9310", "9311", "9312",
"9401", "9402", "9403", "9404", "9405", "9406", "9407", "9408", "9409", "9410", "9411", "9412",
"9201", "9202", "9203", "9204", "9205", "9206", "9207", "9208", "9209", "9210", "9211", "9212",
"9501", "9502", "9503", "9504", "9505", "9506", "9507", "9508", "9509", "9510", "9511", "9512"};
public event Action<Student> Querried;
public event Action<Student> Fault;
public Student Info { get; private set; }
public bool Successful { get; set; }
public Query(string examRef, Action<Student> action = null, Action<Student> action2 = null)
: this(new Student() { ExamReference = examRef }, action, action2)
{
}
public Query(Student info, Action<Student> action, Action<Student> fault)
{
if (info.ExamReference.Length == 9)//少0格式
{
info.ExamReference.PadLeft(10, '0');
}
if (info.ExamReference.Length == 10)
{
this.Info = info;
this.Querried = action;
this.Fault = fault;
}
else
{
throw new ArgumentException("考号不正确", "info");
}
}
public void Execute()
{
try
{
if (!string.IsNullOrEmpty(Info.Birth))
{
if (QueryMarkOnce())
{
Done();
return;
}
}
if (QueryMarkTask())
{
Done();
}
else
{
var temp = Fault;
if (temp != null)
{
temp(this.Info);
}
//Successful = false; default
}
}
catch (Exception e)
{
Program.ThrowError(e);
}
}
private void Done()
{
QueryRecruiting(GetRecruiting(this.Info.ExamReference, this.Info.Birth));
var temp = Querried;
if (temp != null)
{
temp(this.Info);
}
Successful = true;
}
private void ExecuteTask(object state)
{
Execute();
}
public async void ExecuteAsync()
{
await Task.Factory.StartNew(ExecuteTask, this.Info);
}
private bool QueryMarkOnce()
{
HtmlDocument page;
page = GetMark(this.Info.ExamReference, this.Info.Birth);
return (QueryMark(page));
}
private bool QueryMarkTask()
{
HtmlDocument page;
foreach (var mon in birthmonths)
{
page = GetMark(this.Info.ExamReference, mon);
if (QueryMark(page))
{
this.Info.Birth = mon;
return true;
}
}
return false;
}
private bool QueryMark(HtmlDocument doc)
{
var marksHtml = doc.DocumentNode.LastChild.LastChild.PreviousSibling.ChildNodes[7];
var children = marksHtml.ChildNodes;
if (children.Count == 5)
{
var tr = marksHtml.ChildNodes[3].ChildNodes;
this.Info.Name = tr[3].ChildNodes[3].InnerText;
var text = tr[9].InnerText.Trim();
this.Info.Mark = text.Substring(text.Length - 3).Trim();
return true;
}
else if (children.Count == 3)
{
//失败!!!
//mark = string.Empty;
this.Info.Mark = "unknow";
return false;
}
else
{
this.Info.Mark = "unknow";
Program.ThrowError(new ArgumentException("unknow", "doc"));
return false;
}
}
private bool QueryRecruiting(HtmlDocument doc)
{
var body = doc.DocumentNode.LastChild.ChildNodes[3].ChildNodes;
if (body.Count == 17)
{
var recruitingHtml = body[9].ChildNodes[3].ChildNodes[1].ChildNodes[7];
this.Info.Recruiting = recruitingHtml.InnerText.Trim();
return true;
}
else if (body.Count == 15)
{
//失败!!!
this.Info.Recruiting = "unknow";
return false;
}
else
{
this.Info.Recruiting = "unknow";
Program.ThrowError(new ArgumentException("unknow", "doc"));
return false;
}
}
static HtmlDocument GetMark(string examRef, string birth)
{
string url = string.Format("http://wap.5184.com/NCEE_WAP/controller/examEnquiry/performExamEnquiryWithoutAuthForGZ?categoryCode=CE_1&examReferenceNo={0}&birthday={1}&mobileNo=13760703318&examYear=2012&userName=%E9%82%B1%E5%B0%9A%E6%98%AD&redirected_url=http://wap.wirelessgz.cn/myExamWeb/wap/school/gaokao/myUniversity!main.action", examRef, birth);
return new HtmlWeb().Load(url);
}
/// <summary>
/// 不是我起的名字...教育网起的..查询录取
/// </summary>
/// <param name="examRef"></param>
/// <param name="birth"></param>
/// <returns></returns>
static HtmlDocument GetRecruiting(string examRef, string birth)
{
string url = string.Format("http://wap.5184.com/NCEE_WAP/controller/examEnquiry/performRecruitedEnquiryWithoutAuth?categoryCode=CE_1&examReferenceNo={0}&birthday={1}&mobileNo=13760703318&examYear=2012&userName=01<PASSWORD>04&redirected_url=http://wap.wirelessgz.cn/myExamWeb/wap/school/gaokao/myUniversity!main.action", examRef, birth);
return new HtmlWeb().Load(url);
}
}
}
|
728fce76685477ecdd5ac3ff0585902701ce8654
|
[
"Markdown",
"C#"
] | 3 |
C#
|
jeffreye/markquerier
|
414a5c7e3b450ddda21745e91e0d793824ce2f35
|
8b692e0e59e3e5d0f383e8d45ddff78b944b343d
|
refs/heads/master
|
<repo_name>wingyplus/sloth<file_sep>/sloth_test.go
package sloth
import (
"io/ioutil"
"os"
"testing"
"time"
)
func init() {
resetTime()
}
func TestCreateFileAtFirstWrite(t *testing.T) {
makeTempDir("TestWrite")
defer os.RemoveAll("TestWrite")
f := &File{
Filename: "TestWrite/test-write.log",
}
defer f.Close()
f.Write([]byte("Hello world"))
if len(ls("TestWrite")) != 1 {
t.Error("Expect has a file in folder TestWrite")
}
}
func TestAutoRotate(t *testing.T) {
makeTempDir("TestAutoRotate")
defer os.RemoveAll("TestAutoRotate")
f := &File{
Filename: "TestAutoRotate/test-auto-rotate.log",
Every: 1 * time.Millisecond,
}
defer f.Close()
f.Write([]byte("Hello world"))
updateTime()
f.Write([]byte("Hello world"))
if total := len(ls("TestAutoRotate")); total != 2 {
t.Error("Expect have 2 file in folder TestWrite but got", total)
}
if s := cat("TestAutoRotate/test-auto-rotate_20160203_1545.log"); s != "Hello world" {
t.Error("Expect `Hello World` in file content but got", s)
}
resetTime()
}
func TestCleanMainLog(t *testing.T) {
makeTempDir("TestClearMainLog")
defer os.RemoveAll("TestClearMainLog")
f := &File{
Filename: "TestClearMainLog/test-auto-rotate.log",
Every: 1 * time.Millisecond,
}
defer f.Close()
f.Write([]byte("Hello world"))
updateTime()
f.Write([]byte("Hello world 2"))
if cat("TestClearMainLog/test-auto-rotate.log") != "Hello world 2" {
t.Error("Main log should clean after backup log")
}
resetTime()
}
func TestWrite(t *testing.T) {
makeTempDir("TestWrite")
defer os.RemoveAll("TestWrite")
f := &File{
Filename: "TestWrite/test-write.log",
Every: 1 * time.Millisecond,
}
defer f.Close()
_, err := f.Write([]byte("Hello world"))
if err != nil {
t.Error(err)
}
if s := cat("TestWrite/test-write.log"); s != "Hello world" {
t.Error("Expect `Hello World` in file content but got", s)
}
}
func cat(filename string) string {
if b, err := ioutil.ReadFile(filename); err == nil {
return string(b)
}
return ""
}
func ls(dir string) []os.FileInfo {
if infos, err := ioutil.ReadDir(dir); err == nil {
return infos
}
return nil
}
func makeTempDir(dir string) {
os.MkdirAll(dir, 0744)
}
func updateTime() {
timeNow = func() time.Time {
return time.Date(2016, time.February, 3, 15, 45, 0, 0, time.UTC)
}
}
func resetTime() {
timeNow = func() time.Time {
return time.Date(2016, time.February, 3, 15, 40, 0, 0, time.UTC)
}
}
<file_sep>/sloth.go
package sloth
import (
"fmt"
"io"
"os"
"path/filepath"
"time"
)
// for mock in this package
var timeNow = time.Now
// Make sure Logger always implements io.Writer
var _ io.WriteCloser = (*File)(nil)
// File wrap os.File to manage rotate logic
type File struct {
Filename string
Every time.Duration
file *os.File
createdAt time.Time
}
// Write data to the file
func (f *File) Write(b []byte) (n int, err error) {
if f.file == nil {
if err = f.openNew(); err != nil {
return
}
}
if now := timeNow(); f.Every > 0 && now.Sub(f.createdAt) >= f.Every {
if err = f.backup(); err != nil {
return
}
if err = f.openNew(); err != nil {
return
}
}
return f.file.Write(b)
}
// Close the file
func (f *File) Close() error {
return f.file.Close()
}
// Name return file name
func (f *File) Name() string { return f.file.Name() }
func (f *File) backup() error {
name := f.Name()
f.Close()
return os.Rename(name, filepath.Join(filepath.Dir(name), backupName(name)))
}
func (f *File) openNew() (err error) {
f.file, err = os.OpenFile(f.Filename, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
f.createdAt = timeNow()
return
}
func backupName(filename string) string {
ext := filepath.Ext(filename)
name := filepath.Base(filename)
prefix := name[:len(name)-len(ext)]
return fmt.Sprintf("%s_%s%s", prefix, timeNow().Format("20060102_1504"), ext)
}
<file_sep>/README.md
# sloth
Logger rotate by period
|
d0320d782a72ce44b0e5213ee6be21da4c083f65
|
[
"Markdown",
"Go"
] | 3 |
Go
|
wingyplus/sloth
|
beb16989706604bd99fef3d0b78e29bef6a5521c
|
3d7376156bc09a43d5cca332a4114619582cd225
|
refs/heads/master
|
<file_sep>/*
* Copyright (C) 2015 SEC BFO, Inc. All Rights Reserved.
*/
package com.thinkgem.jeesite.movieclub.portal.controller;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.movieclub.consumer.entity.Consumer;
import com.thinkgem.jeesite.movieclub.consumer.service.ConsumerService;
import com.thinkgem.jeesite.movieclub.vo.ConsumerVO;
import com.thinkgem.jeesite.movieclub.vo.MessageResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
@RequestMapping(value = "${frontPath}/consumer")
public class ConsumerPortalController
extends BaseController{
@Autowired
private ConsumerService consumerService;
@ModelAttribute
public Consumer get(@RequestParam(required=false) String id) {
Consumer entity = null;
if (StringUtils.isNotBlank(id)){
entity = consumerService.get(id);
}
if (entity == null){
entity = new Consumer();
}
return entity;
}
//@ResponseBody
@RequestMapping(value = "/resetPassword", method = RequestMethod.GET)
public String resetPassword(HttpServletRequest request, HttpServletResponse response, Model model) {
String token = request.getParameter("token");
Consumer consumer = null;
consumer = consumerService.getByToken(token, "rt");
if(consumer != null){
model.addAttribute("consumer", consumer);
return "modules/consumer/resetPasswordForm";
}else{
return "modules/consumer/tokenExpireForm";
}
}
//@ResponseBody
@RequestMapping(value = "/activeRegisterUser", method = RequestMethod.GET)
public String activeRegisterUser(HttpServletRequest request, HttpServletResponse response, Model model) {
String token = request.getParameter("token");
Consumer consumer = null;
consumer = consumerService.getByToken(token, "rt");
if(consumer != null){
consumerService.activeRegisterUser(consumer.getId());
MessageResultVO result=new MessageResultVO();
result.setTitle("Active Register User");
result.setMessage("Successful!.");
result.setDesc("Congratulations! Active Register User Successfully.");
model.addAttribute("result", result);
return "modules/consumer/successForm";
}else{
return "modules/consumer/tokenExpireForm";
}
}
@RequestMapping(value = "/resetNow")
public String resetPassword(Consumer consumer, Model model, RedirectAttributes redirectAttributes) {
String newPassword = <PASSWORD>();
consumerService.updatePassword(consumer.getId(), newPassword);
addMessage(redirectAttributes, "reset password success");
MessageResultVO result=new MessageResultVO();
result.setTitle("Rest Password Successful");
result.setMessage("Successful!.");
result.setDesc("Congratulations! Resetting Password Successfully.");
model.addAttribute("result", result);
return "modules/consumer/successForm";
//return Const.APIResult.SUCCESS_MESSAGE;
}
}
<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.comment.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.movieclub.comment.entity.MovieConsumerComments;
import java.util.List;
/**
* commentDAO接口
* @author eric.wang
* @version 2015-10-16
*/
@MyBatisDao
public interface MovieConsumerCommentsDao extends CrudDao<MovieConsumerComments> {
public List<MovieConsumerComments> getMovieComments(MovieConsumerComments param);
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.genre.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.movieclub.genre.entity.MovieGenre;
import com.thinkgem.jeesite.movieclub.genre.service.MovieGenreService;
/**
* movie genreController
* @author eric.wang
* @version 2015-10-12
*/
@Controller
@RequestMapping(value = "${adminPath}/genre/movieGenre")
public class MovieGenreController extends BaseController {
@Autowired
private MovieGenreService movieGenreService;
@ModelAttribute
public MovieGenre get(@RequestParam(required=false) String id) {
MovieGenre entity = null;
if (StringUtils.isNotBlank(id)){
entity = movieGenreService.get(id);
}
if (entity == null){
entity = new MovieGenre();
}
return entity;
}
@RequiresPermissions("genre:movieGenre:view")
@RequestMapping(value = {"list", ""})
public String list(MovieGenre movieGenre, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<MovieGenre> page = movieGenreService.findPage(new Page<MovieGenre>(request, response), movieGenre);
model.addAttribute("page", page);
return "modules/genre/movieGenreList";
}
@RequiresPermissions("genre:movieGenre:view")
@RequestMapping(value = "form")
public String form(MovieGenre movieGenre, Model model) {
model.addAttribute("movieGenre", movieGenre);
return "modules/genre/movieGenreForm";
}
@RequiresPermissions("genre:movieGenre:edit")
@RequestMapping(value = "save")
public String save(MovieGenre movieGenre, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, movieGenre)){
return form(movieGenre, model);
}
movieGenreService.save(movieGenre);
addMessage(redirectAttributes, "save movie genre successful.");
return "redirect:"+Global.getAdminPath()+"/genre/movieGenre/?repage";
}
@RequiresPermissions("genre:movieGenre:edit")
@RequestMapping(value = "delete")
public String delete(MovieGenre movieGenre, RedirectAttributes redirectAttributes) {
movieGenreService.delete(movieGenre);
addMessage(redirectAttributes, "delete movie genre successful.");
return "redirect:"+Global.getAdminPath()+"/genre/movieGenre/?repage";
}
}<file_sep>/*
* Copyright (C) 2015 SEC BFO, Inc. All Rights Reserved.
*/
package com.thinkgem.jeesite.movieclub.vo;
public class ContactVO
{
private String objType; // obj_type
private String name; // name
private String company; // company
private String email; // email
private String phone; // phone
private String comments;
public String getObjType()
{
return objType;
}
public void setObjType(String objType)
{
this.objType = objType;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getCompany()
{
return company;
}
public void setCompany(String company)
{
this.company = company;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getPhone()
{
return phone;
}
public void setPhone(String phone)
{
this.phone = phone;
}
public String getComments()
{
return comments;
}
public void setComments(String comments)
{
this.comments = comments;
}
}
<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.movie.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.movieclub.movie.entity.Movie;
import java.util.List;
/**
* movieDAO接口
* @author marvin.ma
* @version 2015-10-15
*/
@MyBatisDao
public interface MovieDao extends CrudDao<Movie> {
public List<Movie> getMovieListWithoutRecommendation (Movie movie);
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.tag.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.movieclub.tag.entity.MovieTag;
import com.thinkgem.jeesite.movieclub.tag.dao.MovieTagDao;
/**
* tagService
* @author marvin.ma
* @version 2015-10-15
*/
@Service
@Transactional(readOnly = true)
public class MovieTagService extends CrudService<MovieTagDao, MovieTag> {
public MovieTag get(String id) {
return super.get(id);
}
public List<MovieTag> findList(MovieTag movieTag) {
return super.findList(movieTag);
}
public Page<MovieTag> findPage(Page<MovieTag> page, MovieTag movieTag) {
return super.findPage(page, movieTag);
}
@Transactional(readOnly = false)
public void save(MovieTag movieTag) {
super.save(movieTag);
}
@Transactional(readOnly = false)
public void delete(MovieTag movieTag) {
super.delete(movieTag);
}
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.contact.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.movieclub.contact.entity.Contact;
/**
* ContactDAO接口
* @author eric.wang
* @version 2015-10-15
*/
@MyBatisDao
public interface ContactDao extends CrudDao<Contact> {
}<file_sep>package com.thinkgem.jeesite.movieclub.sysconfig.service;
import com.thinkgem.jeesite.movieclub.sysconfig.dao.SysConfDao;
import com.thinkgem.jeesite.movieclub.sysconfig.entity.SysConf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
@Service
@Transactional(readOnly = true)
public class SysConfigService {
protected Logger logger = LoggerFactory.getLogger(getClass());
private SysConfDao sysConfDao;
private static final Properties properties = new Properties();
private static Map<String, String> configs;
public SysConfigService() {
/**
* 加载数据库数据,遍历properties中的数据 没有的初始化到数据库
* 将数据写入到一个map里面.
*/
configs = loadConfigMap();
try {
properties.load(ClassLoader.getSystemResourceAsStream("sys.config.properties"));
} catch (FileNotFoundException e) {
logger.error("Can't not load the file 'sys.config.properties' :" + e.getMessage());
} catch (IOException e) {
logger.error("IOException when loading 'sys.config.properties'" + e.getCause());
}
Iterator it = properties.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
//配置不存在时将配置写入数据库并添加到缓存.
if (!configs.containsKey(key)) {
SysConf conf = new SysConf();
conf.setKey(key);
conf.setValue(value);
conf.setDelFlag("0");
sysConfDao.insert(conf);
configs.put(key, value);
}
configs.put(key, value);
}
}
public Map<String, String> loadConfigMap() {
Map<String, String> configs = new HashMap<String, String>();
Map<String, String> regionMap = sysConfDao.loadConfigMap();
String key = null;
String value = null;
for (Map.Entry<String, String> entry : regionMap.entrySet()) {
if ("key".equals(entry.getKey())) {
key = entry.getValue();
} else if ("value".equals(entry.getKey())) {
value = entry.getValue();
}
}
configs.put(key, value);
return configs;
}
@Transactional(readOnly = false)
public void update(SysConf sysConf) {
sysConfDao.update(sysConf);
}
// public MailConfig getMailConfig() {
// MailConfig mailConfig = new MailConfig();
// mailConfig.setMailServer(configs.get(Const.SysConfigKey.MAIL_SERVER_KEY));
// mailConfig.setMailUsername(configs.get(Const.SysConfigKey.MAIL_USER_KEY));
// mailConfig.setPassword(configs.get(Const.SysConfigKey.MAIL_PASSWORD_KEY));
// return mailConfig;
// }
}
<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.consumer.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.thinkgem.jeesite.common.persistence.DataEntity;
import org.hibernate.validator.constraints.Length;
import java.util.Date;
/**
* consumerEntity
*
* @author eric.wang
* @version 2015-10-12
*/
public class Consumer extends DataEntity<Consumer> {
private static final long serialVersionUID = 1L;
private String email; // email
private String firstName; // first_name
private String lastName; // last_name
private String nickName; //nick_name
private String gender; // gender
private Date birthday; // birthday
private String password; // <PASSWORD>
private String userRoleId; // user_role_id
private String roleName; // roleName
private String webAccessToken; // access_token_web
private Date webTokenExpireDate; // token_expire_date_web
private String mobileAccessToken; // access_token_mobile
private Date mobileTokenExpireDate; // token_expire_date_mobile
private String resetPasswordToken; // reset_password_token
private Date resetPasswordTokenExpireDate; // reset_password_token_expire_date
private String thirdAccessToken; // access_token_third
private Date thirdTokenExpireDate; // token_expire_date_third
private boolean active; // active
private String userImage; // user_image
private String facebookId;
private String twitterId;
private String googleId;
public Consumer() {
super();
}
public Consumer(String id) {
super(id);
}
@Length(min = 1, max = 200, message = "email长度必须介于 1 和 200 之间")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Length(min = 0, max = 40, message = "first_name长度必须介于 0 和 40 之间")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Length(min = 0, max = 40, message = "last_name长度必须介于 0 和 40 之间")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Length(min = 0, max = 10, message = "gender长度必须介于 0 和 10 之间")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Length(min = 1, max = 100, message = "password长度必须介于 1 和 100 之间")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Length(min = 0, max = 64, message = "user_role_id长度必须介于 0 和 64 之间")
public String getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(String userRoleId) {
this.userRoleId = userRoleId;
}
@Length(min = 0, max = 64, message = "user_role_id长度必须介于 0 和 64 之间")
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@Length(min = 0, max = 255, message = "access_token长度必须介于 0 和 255 之间")
public String getWebAccessToken() {
return webAccessToken;
}
public void setWebAccessToken(String accessToken) {
this.webAccessToken = accessToken;
}
@Length(min = 0, max = 255, message = "access_token长度必须介于 0 和 255 之间")
public String getMobileAccessToken() {
return mobileAccessToken;
}
public void setMobileAccessToken(String accessToken) {
this.mobileAccessToken = accessToken;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getWebTokenExpireDate() {
return webTokenExpireDate;
}
public void setWebTokenExpireDate(Date webTokenExpireDate) {
this.webTokenExpireDate = webTokenExpireDate;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getMobileTokenExpireDate() {
return mobileTokenExpireDate;
}
public void setMobileTokenExpireDate(Date mobileTokenExpireDate) {
this.mobileTokenExpireDate = mobileTokenExpireDate;
}
public boolean isActive()
{
return active;
}
public void setActive(boolean active)
{
this.active = active;
}
@Length(min = 0, max = 255, message = "user_image长度必须介于 0 和 255 之间")
public String getUserImage() {
return userImage;
}
public void setUserImage(String userImage) {
this.userImage = userImage;
}
public String getResetPasswordToken()
{
return resetPasswordToken;
}
public void setResetPasswordToken(String resetPasswordToken)
{
this.resetPasswordToken = resetPasswordToken;
}
public Date getResetPasswordTokenExpireDate()
{
return resetPasswordTokenExpireDate;
}
public void setResetPasswordTokenExpireDate(Date resetPasswordTokenExpireDate)
{
this.resetPasswordTokenExpireDate = resetPasswordTokenExpireDate;
}
public String getNickName()
{
return nickName;
}
public void setNickName(String nickName)
{
this.nickName = nickName;
}
public String getThirdAccessToken()
{
return thirdAccessToken;
}
public void setThirdAccessToken(String thirdAccessToken)
{
this.thirdAccessToken = thirdAccessToken;
}
public Date getThirdTokenExpireDate()
{
return thirdTokenExpireDate;
}
public void setThirdTokenExpireDate(Date thirdTokenExpireDate)
{
this.thirdTokenExpireDate = thirdTokenExpireDate;
}
public String getFacebookId()
{
return facebookId;
}
public void setFacebookId(String facebookId)
{
this.facebookId = facebookId;
}
public String getTwitterId()
{
return twitterId;
}
public void setTwitterId(String twitterId)
{
this.twitterId = twitterId;
}
public String getGoogleId()
{
return googleId;
}
public void setGoogleId(String googleId)
{
this.googleId = googleId;
}
}<file_sep>package com.thinkgem.jeesite.movieclub.vo;
public class ConsumerVO {
private String id;
private String email;
private String firstName;
private String lastName;
private String gender;
private String birthday;
private String password;
private String newPassword;
private String nickName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
}
<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.sysconfig.entity;
import org.hibernate.validator.constraints.Length;
import com.thinkgem.jeesite.common.persistence.DataEntity;
/**
* sysconfigEntity
* @author eric.wang
* @version 2015-10-14
*/
public class SysConf extends DataEntity<SysConf> {
private static final long serialVersionUID = 1L;
private String key; // key
private String value; // value
private String description; // description
public SysConf() {
super();
}
public SysConf(String id){
super(id);
}
@Length(min=1, max=100, message="key长度必须介于 1 和 100 之间")
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Length(min=1, max=255, message="value长度必须介于 1 和 255 之间")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Length(min=1, max=255, message="description长度必须介于 1 和 255 之间")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.movie_tag.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.movieclub.movie_tag.entity.MovieTagLink;
/**
* movie_tagDAO接口
* @author marvin.ma
* @version 2015-10-16
*/
@MyBatisDao
public interface MovieTagLinkDao extends CrudDao<MovieTagLink> {
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.genre.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.movieclub.genre.entity.MovieGenre;
import com.thinkgem.jeesite.movieclub.genre.dao.MovieGenreDao;
/**
* movie genreService
* @author eric.wang
* @version 2015-10-12
*/
@Service
@Transactional(readOnly = true)
public class MovieGenreService extends CrudService<MovieGenreDao, MovieGenre> {
public MovieGenre get(String id) {
return super.get(id);
}
public List<MovieGenre> findList(MovieGenre movieGenre) {
return super.findList(movieGenre);
}
public Page<MovieGenre> findPage(Page<MovieGenre> page, MovieGenre movieGenre) {
return super.findPage(page, movieGenre);
}
@Transactional(readOnly = false)
public void save(MovieGenre movieGenre) {
super.save(movieGenre);
}
@Transactional(readOnly = false)
public void delete(MovieGenre movieGenre) {
super.delete(movieGenre);
}
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.recommendation.web;
import java.util.List;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.thinkgem.jeesite.movieclub.movie.entity.Movie;
import com.thinkgem.jeesite.movieclub.movie.service.MovieService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.movieclub.recommendation.entity.Recommendation;
import com.thinkgem.jeesite.movieclub.recommendation.service.RecommendationService;
/**
* RecommendationController
* @author eric.wang
* @version 2015-10-13
*/
@Controller
@RequestMapping(value = "${adminPath}/recommendation/recommendation")
public class RecommendationController extends BaseController {
@Autowired
private MovieService movieService;
@Autowired
private RecommendationService recommendationService;
@ModelAttribute
public Recommendation get(@RequestParam(required=false) String id) {
Recommendation entity = null;
if (StringUtils.isNotBlank(id)){
entity = recommendationService.get(id);
}
if (entity == null){
entity = new Recommendation();
}
return entity;
}
@ModelAttribute
public Recommendation getByMovieId(@RequestParam(required=false) String movieId) {
Recommendation entity = null;
if (StringUtils.isNotBlank(movieId)) {
entity = recommendationService.getByMovieId(movieId);
}
if (entity == null) {
entity = new Recommendation();
}
return entity;
}
@RequiresPermissions("recommendation:recommendation:view")
@RequestMapping(value = {"list", ""})
public String list(Recommendation recommendation, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<Recommendation> page = recommendationService.findPage(new Page<Recommendation>(request, response), recommendation);
model.addAttribute("page", page);
return "modules/recommendation/recommendationList";
}
@RequiresPermissions("recommendation:recommendation:view")
@RequestMapping(value = "form")
public String form(Recommendation recommendation, Model model) {
model.addAttribute("recommendation", recommendation);
return "modules/recommendation/recommendationForm";
}
@RequiresPermissions("recommendation:recommendation:edit")
@RequestMapping(value = "save")
public String save(Recommendation recommendation, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, recommendation)) {
return form(recommendation, model);
}
recommendationService.save(recommendation);
addMessage(redirectAttributes, "Save recommendation successful.");
return "redirect:"+Global.getAdminPath()+"/recommendation/recommendation/?repage";
}
@RequiresPermissions("recommendation:recommendation:edit")
@RequestMapping(value = "delete")
public String delete(Recommendation recommendation, RedirectAttributes redirectAttributes) {
recommendationService.delete(recommendation);
addMessage(redirectAttributes, "Delete recommendation successful.");
return "redirect:"+Global.getAdminPath()+"/recommendation/recommendation/?repage";
}
@RequestMapping(value = "searchMovieList", method = RequestMethod.GET)
@ResponseBody
public List<Movie> searchMovieList(@RequestParam(required=false) String movieName, @RequestParam(required=false) String movieGenre) {
Movie movie = new Movie();
movie.setTitle(movieName);
movie.setGenre(movieGenre);
List<Movie> movieList = movieService.getMovieListWithoutRecommendation(movie);
return movieList;
}
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.comment.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.movieclub.comment.entity.MovieConsumerComments;
import com.thinkgem.jeesite.movieclub.comment.service.MovieConsumerCommentsService;
/**
* commentController
* @author eric.wang
* @version 2015-10-16
*/
@Controller
@RequestMapping(value = "${adminPath}/comment/movieConsumerComments")
public class MovieConsumerCommentsController extends BaseController {
@Autowired
private MovieConsumerCommentsService movieConsumerCommentsService;
@ModelAttribute
public MovieConsumerComments get(@RequestParam(required=false) String id) {
MovieConsumerComments entity = null;
if (StringUtils.isNotBlank(id)){
entity = movieConsumerCommentsService.get(id);
}
if (entity == null){
entity = new MovieConsumerComments();
}
return entity;
}
@RequiresPermissions("comment:movieConsumerComments:view")
@RequestMapping(value = {"list", ""})
public String list(MovieConsumerComments movieConsumerComments, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<MovieConsumerComments> page = movieConsumerCommentsService.findPage(new Page<MovieConsumerComments>(request, response), movieConsumerComments);
model.addAttribute("page", page);
return "modules/comment/movieConsumerCommentsList";
}
@RequiresPermissions("comment:movieConsumerComments:view")
@RequestMapping(value = "form")
public String form(MovieConsumerComments movieConsumerComments, Model model) {
model.addAttribute("movieConsumerComments", movieConsumerComments);
return "modules/comment/movieConsumerCommentsForm";
}
@RequiresPermissions("comment:movieConsumerComments:edit")
@RequestMapping(value = "save")
public String save(MovieConsumerComments movieConsumerComments, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, movieConsumerComments)){
return form(movieConsumerComments, model);
}
movieConsumerCommentsService.save(movieConsumerComments);
addMessage(redirectAttributes, "保存comment成功");
return "redirect:"+Global.getAdminPath()+"/comment/movieConsumerComments/?repage";
}
@RequiresPermissions("comment:movieConsumerComments:edit")
@RequestMapping(value = "delete")
public String delete(MovieConsumerComments movieConsumerComments, RedirectAttributes redirectAttributes) {
movieConsumerCommentsService.delete(movieConsumerComments);
addMessage(redirectAttributes, "删除comment成功");
return "redirect:"+Global.getAdminPath()+"/comment/movieConsumerComments/?repage";
}
}<file_sep>package com.thinkgem.jeesite.movieclub.util;
public class Message {
public static class Consumer {
public static final String EMAIL_ALREADY_REGISTERED = "this email has already registered.";
public static final String DATE_FORMAT_NOT_VALIDATE = "the format of the birthday is not validate.";
public static final String ACCOUNT_DOES_NOT_EXISTS = "the account %s is not exists.";
public static final String ACCOUNT_IS_INACTIVE = "the account is inactive,please activate it";
public static final String ACCOUNT_HAS_ALREADY_ACTIVE = "the account is active already,please enjoy it";
public static final String ACCOUNT_DOES_NOT_EXISTS_OR_PASSWORD_NOT_CORRECT = "the account %s is not exists or the password is not correct.";
public static final String RESET_PASSWORD_EMAIL_TITLE = "Reset the password of %s@<PASSWORD>";
public static final String ACTIVE_ACCOUNT_EMAIL_TITLE = "Active your account %s@MovieClub";
public static final String ACCOUNT_DOES_NOT_EXISTS_OR_TOKEN_EXPIRED = "the account %s is not exists or token expired";
}
}
<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.genre.entity;
import org.hibernate.validator.constraints.Length;
import com.thinkgem.jeesite.common.persistence.DataEntity;
/**
* movie genreEntity
* @author eric.wang
* @version 2015-10-12
*/
public class MovieGenre extends DataEntity<MovieGenre> {
private static final long serialVersionUID = 1L;
private String genreName; // Genre Title
private String genreImage; // Filename of Genre poster
private String genreImageTitle; // Title of featured genre movie
private String sortOrder; // Change the order of menu on front end
private String status; // 1 - published, 2 - unpublished
public MovieGenre() {
super();
}
public MovieGenre(String id){
super(id);
}
@Length(min=1, max=255, message="Genre Title长度必须介于 1 和 255 之间")
public String getGenreName() {
return genreName;
}
public void setGenreName(String genreName) {
this.genreName = genreName;
}
@Length(min=0, max=255, message="Filename of Genre poster长度必须介于 0 和 255 之间")
public String getGenreImage() {
return genreImage;
}
public void setGenreImage(String genreImage) {
this.genreImage = genreImage;
}
@Length(min=0, max=255, message="Title of featured genre movie长度必须介于 0 和 255 之间")
public String getGenreImageTitle() {
return genreImageTitle;
}
public void setGenreImageTitle(String genreImageTitle) {
this.genreImageTitle = genreImageTitle;
}
@Length(min=0, max=6, message="Change the order of menu on front end长度必须介于 0 和 6 之间")
public String getSortOrder() {
return sortOrder;
}
public void setSortOrder(String sortOrder) {
this.sortOrder = sortOrder;
}
@Length(min=0, max=1, message="1 - published, 2 - unpublished长度必须介于 0 和 1 之间")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.comment.entity;
import org.hibernate.validator.constraints.Length;
import com.thinkgem.jeesite.common.persistence.DataEntity;
/**
* commentEntity
* @author eric.wang
* @version 2015-10-16
*/
public class MovieConsumerComments extends DataEntity<MovieConsumerComments> {
private static final long serialVersionUID = 1L;
private String parentCommentId; // parent_comment_id
private String movieId; // movie_id
private String consumerId; // consumer_id
private String commentDescription; // comment_description
private String firstName;
private String lastName;
private String nickName;
public MovieConsumerComments() {
super();
}
public MovieConsumerComments(String id){
super(id);
}
@Length(min=1, max=64, message="parent_comment_id长度必须介于 1 和 64 之间")
public String getParentCommentId() {
return parentCommentId;
}
public void setParentCommentId(String parentCommentId) {
this.parentCommentId = parentCommentId;
}
@Length(min=1, max=64, message="movie_id长度必须介于 1 和 64 之间")
public String getMovieId() {
return movieId;
}
public void setMovieId(String movieId) {
this.movieId = movieId;
}
@Length(min=1, max=64, message="consumer_id长度必须介于 1 和 64 之间")
public String getConsumerId() {
return consumerId;
}
public void setConsumerId(String consumerId) {
this.consumerId = consumerId;
}
public String getCommentDescription() {
return commentDescription;
}
public void setCommentDescription(String commentDescription) {
this.commentDescription = commentDescription;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getNickName()
{
return nickName;
}
public void setNickName(String nickName)
{
this.nickName = nickName;
}
}<file_sep>/**
*
*/
package com.thinkgem.jeesite.movieclub.api.mobile;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.movieclub.consumer.entity.Consumer;
import com.thinkgem.jeesite.movieclub.consumer.service.ConsumerService;
import com.thinkgem.jeesite.movieclub.mail.MailService;
import com.thinkgem.jeesite.movieclub.util.Const;
import com.thinkgem.jeesite.movieclub.util.Message;
import com.thinkgem.jeesite.movieclub.vo.ConsumerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.text.ParseException;
import java.util.*;
/**
* ConsumerAPIController
*
* @author jason.xu
* @version 2015-10-12
*/
@Controller
@RequestMapping(value = "${mobileApiPath}/consumer")
public class ConsumerAPIController extends BaseController {
@Autowired
private MailService mailService;
@Autowired
private ConsumerService consumerService;
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public String register(@RequestBody ConsumerVO consumerVO) {
try {
Consumer consumer = consumerService.getByEmail(consumerVO.getEmail());
//验证有限是否已经注册
if (null == consumer) {
consumer = new Consumer();
//生日
Date birthday = DateUtils.parseDate(consumerVO.getBirthday(), "yyyy-MM-dd");
consumer.setBirthday(birthday);
String resetPasswordToken = createNewToken();
consumer.setEmail(consumerVO.getEmail());
consumer.setFirstName(consumerVO.getFirstName());
consumer.setLastName(consumerVO.getLastName());
consumer.setNickName(consumerVO.getNickName());
consumer.setGender(consumerVO.getGender());
consumer.setPassword(consumerVO.getPassword());
consumer.setActive(false);
consumer.setResetPasswordToken(resetPasswordToken);
consumer.setResetPasswordTokenExpireDate(getResetPasswordExpireDate());
consumerService.save(consumer);
sendActiveEmail(consumer, resetPasswordToken);
return Const.APIResult.SUCCESS_MESSAGE;
} else {
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.Consumer.ACCOUNT_NOT_EXIST, Message.Consumer.EMAIL_ALREADY_REGISTERED);
}
} catch (ParseException e) {
e.printStackTrace();
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.KNOWN_ISSUE, Message.Consumer.DATE_FORMAT_NOT_VALIDATE);
} catch (Exception e) {
e.printStackTrace();
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.SERVER_ERROR, e.getMessage());
}
}
@ResponseBody
@RequestMapping(value = "/sendActiveEmail", method = RequestMethod.POST)
public String resendActiveEmail(@RequestBody ConsumerVO consumerVO) {
try {
Consumer consumer = consumerService.getByEmail(consumerVO.getEmail());
if (null == consumer) {
String errMsg = String.format(Message.Consumer.ACCOUNT_DOES_NOT_EXISTS, consumerVO.getEmail());
if (logger.isDebugEnabled()) {
logger.debug(errMsg);
}
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.Consumer.ACCOUNT_NOT_EXIST, errMsg);
} else {
if (consumer.isActive()) {
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.Consumer.ACCOUNT_HAS_ALREADY_ACTIVE, Message.Consumer.ACCOUNT_HAS_ALREADY_ACTIVE);
}
String token = createNewToken();
consumerService.updateResetPasswordToken(consumer.getId(), token, getResetPasswordExpireDate());
sendActiveEmail(consumer, token);
return Const.APIResult.SUCCESS_MESSAGE;
}
} catch (Exception e) {
e.printStackTrace();
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.SERVER_ERROR, e.getMessage());
}
}
@ResponseBody
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@RequestBody ConsumerVO consumerVO) {
try {
Consumer consumer = consumerService.getByEmail(consumerVO.getEmail());
if (null == consumer) {
String errMsg = String.format(Message.Consumer.ACCOUNT_DOES_NOT_EXISTS, consumerVO.getEmail());
if (logger.isDebugEnabled()) {
logger.debug(errMsg);
}
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.Consumer.ACCOUNT_NOT_EXIST, errMsg);
} else {
if (!consumer.isActive()) {
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.Consumer.ACCOUNT_NOT_ACTIVE, Message.Consumer.ACCOUNT_IS_INACTIVE);
}
if (logger.isDebugEnabled()) {
logger.debug(consumer.getEmail() + " " + consumer.getPassword());
}
Date birthday = DateUtils.parseDate(consumerVO.getBirthday(), "yyyy-MM-dd");
consumer.setBirthday(birthday);
consumer.setGender(consumerVO.getGender());
consumer.setFirstName(consumerVO.getFirstName());
consumer.setLastName(consumerVO.getLastName());
consumerService.save(consumer);
return Const.APIResult.SUCCESS_MESSAGE;
}
} catch (ParseException e) {
e.printStackTrace();
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.DATE_FORMAT_ERROR, Message.Consumer.DATE_FORMAT_NOT_VALIDATE);
} catch (Exception e) {
e.printStackTrace();
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.SERVER_ERROR, e.getMessage());
}
}
@ResponseBody
@RequestMapping(value = "/login", method = RequestMethod.POST)
public Object login(@RequestBody ConsumerVO consumerVO) {
try {
Consumer consumer = consumerService.validate(consumerVO.getEmail(), consumerVO.getPassword());
if (null == consumer) {
String errMsg = String.format(Message.Consumer.ACCOUNT_DOES_NOT_EXISTS_OR_PASSWORD_NOT_CORRECT, consumerVO.getEmail());
if (logger.isDebugEnabled()) {
logger.debug(errMsg);
}
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.Consumer.ACCOUNT_VERIFICATION_FAILURE, errMsg);
} else {
if (!consumer.isActive()) {
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.Consumer.ACCOUNT_NOT_ACTIVE, Message.Consumer.ACCOUNT_IS_INACTIVE);
}
//当单点登录或者token已过期时更新token
if (Global.isMobileSSOEnable()
|| consumer.getMobileTokenExpireDate().before(new Date())) {
//更新数据用于返回给前台
String newToken = createNewToken();
consumer.setMobileAccessToken(newToken);
consumer.setMobileTokenExpireDate(getExpireDate());
consumerService.updateMobileAccessToken(consumer.getId(), newToken, getExpireDate());
}
return consumer;
}
} catch (Exception e) {
e.printStackTrace();
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.SERVER_ERROR, e.getMessage());
}
}
@ResponseBody
@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
public String changePassword(@RequestBody ConsumerVO consumerVO) {
try {
Consumer consumer = consumerService.validate(consumerVO.getEmail(), consumerVO.getPassword());
if (null == consumer) {
String errMsg = String.format(Message.Consumer.ACCOUNT_DOES_NOT_EXISTS_OR_PASSWORD_NOT_CORRECT, consumerVO.getEmail());
if (logger.isDebugEnabled()) {
logger.debug(errMsg);
}
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.Consumer.ACCOUNT_VERIFICATION_FAILURE, errMsg);
} else {
String newPassword = consumerVO.getNewPassword();
consumerService.updatePassword(consumer.getId(), newPassword);
return Const.APIResult.SUCCESS_MESSAGE;
}
} catch (Exception e) {
e.printStackTrace();
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.SERVER_ERROR, e.getMessage());
}
}
@ResponseBody
@RequestMapping(value = "/forgetPassword", method = RequestMethod.POST)
public String forgetPassword(@RequestBody ConsumerVO consumerVO) {
try {
Consumer consumer = consumerService.getByEmail(consumerVO.getEmail());
if (null == consumer) {
String errMsg = String.format(Message.Consumer.ACCOUNT_DOES_NOT_EXISTS, consumerVO.getEmail());
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.Consumer.ACCOUNT_NOT_EXIST, errMsg);
} else {
if (!consumer.isActive()) {
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.Consumer.ACCOUNT_NOT_ACTIVE, Message.Consumer.ACCOUNT_IS_INACTIVE);
}
String resetPasswordToken = createNewToken();
consumerService.updateResetPasswordToken(consumer.getId(), resetPasswordToken, getResetPasswordExpireDate());
sendResetPasswordEmail(consumer, resetPasswordToken);
return Const.APIResult.SUCCESS_MESSAGE;
}
} catch (Exception e) {
e.printStackTrace();
return String.format(Const.APIResult.ERROR_MESSAGE, e.getMessage());
}
}
private String createNewToken() {
return UUID.randomUUID().toString();
}
private Date getExpireDate() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.SECOND, Global.getTokenExpireSeconds());
return calendar.getTime();
}
private Date getResetPasswordExpireDate() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.SECOND, Global.getResetPasswordTokenExpireSeconds());
return calendar.getTime();
}
private void sendActiveEmail(Consumer consumer, String resetPasswordToken) {
String activeConsumerUrl = String.format(
"%s%s?token=%s",
Global.getHomeUrl(),
Const.WebPath.ACTIVE_ACCOUNT_WEB_PATH,
resetPasswordToken
);
Map<String, String> param = new HashMap<String, String>();
param.put("userName", consumer.getNickName());
param.put("activeConsumerUrl", activeConsumerUrl);
mailService.sendTemplateMail(
Global.getEmailFrom(),
consumer.getEmail(),
String.format(Message.Consumer.ACTIVE_ACCOUNT_EMAIL_TITLE, consumer.getNickName()),
param,
Const.MailTemplateNames.ACTIVE_ACCOUNT_EMAIL_TEMPLATE_NAME);
}
private void sendResetPasswordEmail(Consumer consumer, String resetPasswordToken) {
Map<String, String> params = new HashMap<String, String>();
String emailTitle = String.format(Message.Consumer.RESET_PASSWORD_EMAIL_TITLE, consumer.getNickName());
String url = String.format(
"%s%s?token=%s",
Global.getHomeUrl(),
Const.WebPath.RESET_PASSWORD_WEB_PATH,
resetPasswordToken
);
params.put("userName", consumer.getNickName());
params.put("resetPasswordUrl", url);
//TODO call send forget password email.
mailService.sendTemplateMail(Global.getEmailFrom(), consumer.getEmail(), emailTitle, params, Const.MailTemplateNames.RESET_PASSWORD_EMAIL_TEMPLATE_NAME);
}
}<file_sep>/*
* Copyright (C) 2014 SEC BFO, Inc. All Rights Reserved.
*/
package com.thinkgem.jeesite.movieclub.mail;
import com.thinkgem.jeesite.movieclub.mail.template.MailTemplate;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Component
public class MailService {
protected Logger log = LoggerFactory.getLogger(getClass());
@Autowired
protected JavaMailSender mailSender;
@Autowired
private MailTemplate mailTemplate;
@Autowired
protected SimpleMailMessage simpleMailTemplate;
@Autowired
protected FreeMarkerConfigurer freeMarkerConfigurer;
// @Autowired
// @Qualifier("mdMessageSender")
// protected MailMessageSender messageSender;
/**
* Send Simple Text Mail
*
* @param toList
* @param subject
* @param mailMsg
*/
public void sendSimpleMessage(String[] toList, String subject, String mailMsg) {
this.sendSimpleMessage(toList, null, subject, mailMsg);
}
/**
* Send Simple Text Mail
*
* @param toList
* @param cc
* @param subject
* @param mailMsg
*/
public void sendSimpleMessage(String[] toList, String[] cc, String subject, String mailMsg) {
SimpleMailMessage msg = new SimpleMailMessage(simpleMailTemplate);
msg.setTo(toList);
msg.setSubject(subject);
msg.setText(mailMsg);
msg.setCc(cc);
try {
this.mailSender.send(msg);
} catch (MailException ex) {
log.error(ex.getMessage());
}
}
/**
* Send HTML Text Mail
*
* @param toList
* @param subject
* @param htmlMailMsg
*/
public void sendHtmlMessage(String from, String[] toList, String subject, String htmlMailMsg) {
try {
MimeMessage mailMessage = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, "utf-8");
messageHelper.setTo(toList);
messageHelper.setFrom(from);
messageHelper.setSubject(subject);
messageHelper.setText(htmlMailMsg, true);
this.mailSender.send(mailMessage);
} catch (MessagingException e) {
log.error(e.getMessage());
}
}
/**
* Send Contains Attachment Message
*
* @param toList
* @param subject
* @param htmlMailMsg
*/
public void sendAttachmentMessage(String from, String[] toList, String subject, String htmlMailMsg, List<File> files) {
this.sendMultiMessage(from, toList, subject, htmlMailMsg, files, false);
}
/**
* Send Contains Inline Image Message
*
* @param toList
* @param subject
* @param htmlMailMsg
*/
public void sendInlineImgMessage(String from, String[] toList, String subject, String htmlMailMsg, List<File> files) {
this.sendMultiMessage(from, toList, subject, htmlMailMsg, files, true);
}
/**
* @param toList
* @param subject
* @param htmlMailMsg
*/
public void sendMultiMessage(String from, String[] toList, String subject, String htmlMailMsg, List<File> files, Boolean isAttachInline) {
try {
MimeMessage mailMessage = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");
messageHelper.setTo(toList);
messageHelper.setFrom(from);
messageHelper.setSubject(subject);
messageHelper.setText(htmlMailMsg, true);
if (CollectionUtils.isNotEmpty(files) && isAttachInline != null) {
if (isAttachInline) {
List<String> cidList = new ArrayList<String>();
for (File file : files) {
cidList.add("<br><img src='cid:" + MimeUtility.encodeWord(file.getName()) + "'>");
}
messageHelper.setText(htmlMailMsg + StringUtils.join(cidList, ""), true);
for (File file : files) {
messageHelper.addInline(MimeUtility.encodeWord(file.getName()), new FileSystemResource(file));
}
} else {
for (File file : files) {
messageHelper.addAttachment(MimeUtility.encodeWord(file.getName()), new FileSystemResource(file));
}
}
}
this.mailSender.send(mailMessage);
} catch (MessagingException e) {
log.error(e.getMessage());
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage());
}
}
/**
* @param from
* @param to
* @param subject
* @param paramMap
* @param templateName
* @return
*/
public Boolean sendTemplateMail(String from, String to, String subject, Map paramMap, String templateName) {
String[] toList = new String[]{to};
return sendTemplateMail(from, toList, null, subject, paramMap, templateName);
}
/**
* @param from
* @param toList
* @param subject
* @param paramMap
* @param templateName
* @return
*/
public Boolean sendTemplateMail(String from, String[] toList, String subject, Map paramMap, String templateName) {
return sendTemplateMail(from, toList, null, subject, paramMap, templateName);
}
/**
* Send Mail Using Freemarker Template With isAsynchronous
*
* @param from
* @param toList
* @param cc
* @param subject
* @param paramMap
* @param templateName
* @return
*/
public Boolean sendTemplateMail(String from, String[] toList, String[] cc, String subject, Map paramMap, String templateName) {
Boolean flag = true;
log.info(String.format("Send mail from:%s, to: %s, cc: %s, subject: %s.", from, Arrays.toString(toList), Arrays.toString(cc), subject));
try {
String content = mailTemplate.getMailText(paramMap, templateName);
MimeMessage mailMessage = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, false, "utf-8");
messageHelper.setSubject(subject);
messageHelper.setFrom(from);
messageHelper.setTo(toList);
if (ArrayUtils.isNotEmpty(cc)) {
messageHelper.setCc(cc);
}
messageHelper.setText(content, true);
// if (configProp.getBccMailEnable() == 1) {
// messageHelper.setBcc(configProp.getBccMailAddress().split(","));
// }
this.mailSender.send(mailMessage);
log.debug(generateEMailLog(toList, cc, subject, content));
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
log.error(e.getMessage());
flag = false;
}
log.info("Send mail " + (flag ? "successful" : "failure"));
return flag;
}
protected String generateEMailLog(String[] to, String[] cc, String subject, String mailMsg) {
String log = "\r\n ======= 发送邮件 ========" + "\r\n";
log += "=============================================" + "\r\n";
log += "To:\r\n" + StringUtils.join(to, "\r\n") + "\r\n";
log += "-------------------------\r\n";
log += "Title:\t" + subject + "\r\n";
log += "-----------------------------------------\r\n";
log += mailMsg + "\r\n";
log += "=============================================";
return log;
}
}
<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.tag.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.movieclub.tag.entity.MovieTag;
import com.thinkgem.jeesite.movieclub.tag.service.MovieTagService;
/**
* tagController
* @author marvin.ma
* @version 2015-10-15
*/
@Controller
@RequestMapping(value = "${adminPath}/tag/movieTag")
public class MovieTagController extends BaseController {
@Autowired
private MovieTagService movieTagService;
@ModelAttribute
public MovieTag get(@RequestParam(required=false) String id) {
MovieTag entity = null;
if (StringUtils.isNotBlank(id)){
entity = movieTagService.get(id);
}
if (entity == null){
entity = new MovieTag();
}
return entity;
}
@RequiresPermissions("tag:movieTag:view")
@RequestMapping(value = {"list", ""})
public String list(MovieTag movieTag, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<MovieTag> page = movieTagService.findPage(new Page<MovieTag>(request, response), movieTag);
model.addAttribute("page", page);
return "modules/tag/movieTagList";
}
@RequiresPermissions("tag:movieTag:view")
@RequestMapping(value = "form")
public String form(MovieTag movieTag, Model model) {
model.addAttribute("movieTag", movieTag);
return "modules/tag/movieTagForm";
}
@RequiresPermissions("tag:movieTag:edit")
@RequestMapping(value = "save")
public String save(MovieTag movieTag, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, movieTag)){
return form(movieTag, model);
}
movieTagService.save(movieTag);
addMessage(redirectAttributes, "保存tag成功");
return "redirect:"+Global.getAdminPath()+"/tag/movieTag/?repage";
}
@RequiresPermissions("tag:movieTag:edit")
@RequestMapping(value = "delete")
public String delete(MovieTag movieTag, RedirectAttributes redirectAttributes) {
movieTagService.delete(movieTag);
addMessage(redirectAttributes, "删除tag成功");
return "redirect:"+Global.getAdminPath()+"/tag/movieTag/?repage";
}
}<file_sep>alter table sys_user add first_name varchar(40);
alter table sys_user add last_name varchar(40);
alter table sys_user add gender varchar(10);
alter table sys_user add birthday datetime;<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.permission.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.thinkgem.jeesite.movieclub.consumer_role.service.ConsumerRoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.movieclub.permission.entity.Permission;
import com.thinkgem.jeesite.movieclub.permission.service.PermissionService;
/**
* permissionController
* @author marvin.ma
* @version 2015-10-19
*/
@Controller
@RequestMapping(value = "${adminPath}/permission/permission")
public class PermissionController extends BaseController {
@Autowired
private PermissionService permissionService;
@ModelAttribute
public Permission get(@RequestParam(required=false) String id) {
Permission entity = null;
if (StringUtils.isNotBlank(id)){
entity = permissionService.get(id);
}
if (entity == null){
entity = new Permission();
}
return entity;
}
@RequiresPermissions("permission:permission:view")
@RequestMapping(value = {"list", ""})
public String list(Permission permission, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<Permission> page = permissionService.findPage(new Page<Permission>(request, response), permission);
model.addAttribute("page", page);
return "modules/permission/permissionList";
}
@RequiresPermissions("permission:permission:view")
@RequestMapping(value = "form")
public String form(Permission permission, Model model) {
model.addAttribute("permission", permission);
return "modules/permission/permissionForm";
}
@RequiresPermissions("permission:permission:edit")
@RequestMapping(value = "save")
public String save(Permission permission, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, permission)){
return form(permission, model);
}
permissionService.save(permission);
addMessage(redirectAttributes, "保存permission成功");
return "redirect:"+Global.getAdminPath()+"/permission/permission/?repage";
}
@RequiresPermissions("permission:permission:edit")
@RequestMapping(value = "delete")
public String delete(Permission permission, RedirectAttributes redirectAttributes) {
permissionService.delete(permission);
addMessage(redirectAttributes, "删除permission成功");
return "redirect:"+Global.getAdminPath()+"/permission/permission/?repage";
}
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.genre.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.movieclub.genre.entity.MovieGenre;
/**
* movie genreDAO接口
* @author eric.wang
* @version 2015-10-12
*/
@MyBatisDao
public interface MovieGenreDao extends CrudDao<MovieGenre> {
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.recommendation.service;
import java.util.List;
import com.thinkgem.jeesite.movieclub.movie.entity.Movie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.movieclub.recommendation.entity.Recommendation;
import com.thinkgem.jeesite.movieclub.recommendation.dao.RecommendationDao;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* RecommendationService
* @author eric.wang
* @version 2015-10-13
*/
@Service
@Transactional(readOnly = true)
public class RecommendationService extends CrudService<RecommendationDao, Recommendation> {
@Autowired
private RecommendationDao recommendationDao;
public Recommendation get(String id) {
return super.get(id);
}
public Recommendation getByMovieId(String movieId) {
return recommendationDao.getByMovieId(movieId);
}
public List<Recommendation> findList(Recommendation recommendation) {
return super.findList(recommendation);
}
public Page<Recommendation> findPage(Page<Recommendation> page, Recommendation recommendation) {
return super.findPage(page, recommendation);
}
@Transactional(readOnly = false)
public void save(Recommendation recommendation) {
super.save(recommendation);
}
@Transactional(readOnly = false)
public void delete(Recommendation recommendation) {
super.delete(recommendation);
}
}<file_sep>/*
* Copyright (C) 2015 SEC BFO, Inc. All Rights Reserved.
*/
package com.thinkgem.jeesite.test.vo;
import java.util.Date;
public class Content
{
private String android_update_id;
private String version_name;
private String version_code;
private String file;
private String date_created;
public String getAndroid_update_id()
{
return android_update_id;
}
public void setAndroid_update_id(String android_update_id)
{
this.android_update_id = android_update_id;
}
public String getVersion_name()
{
return version_name;
}
public void setVersion_name(String version_name)
{
this.version_name = version_name;
}
public String getVersion_code()
{
return version_code;
}
public void setVersion_code(String version_code)
{
this.version_code = version_code;
}
public String getFile()
{
return file;
}
public void setFile(String file)
{
this.file = file;
}
public String getDate_created()
{
return date_created;
}
public void setDate_created(String date_created)
{
this.date_created = date_created;
}
}
<file_sep>package com.thinkgem.jeesite.modules.sys.rest;
import com.thinkgem.jeesite.modules.sys.entity.Login;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.exception.AuthenException;
import com.thinkgem.jeesite.modules.sys.exception.PasswordResetException;
import com.thinkgem.jeesite.modules.sys.exception.UnknowAccountException;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.HResult;
import com.thinkgem.jeesite.modules.sys.utils.MyHttpClientUtils;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@Controller
@RequestMapping(value = "${restPath}/sys/rest")
public class LoginRest {
@Autowired
private SystemService systemService;
public static final String loginUrl = "http://cinelibre.ph/api/login_user/";
@RequestMapping(value = "/loginVerify", method = RequestMethod.POST)
public synchronized
@ResponseBody
String loginVerify(@RequestBody Login login){
String email = null;
String content = null;
JSONObject obj = null;
User user = null;
try {
email = login.getEmail_ID();
String password = login.getUser_password();
content = MyHttpClientUtils.doPost(loginUrl+"email_ID/"+email+"/user_password/"+password,null,"UTF-8");
user = systemService.login(email, password);
} catch (PasswordResetException e) {
e.printStackTrace();
} catch (AuthenException e) {
e.printStackTrace();
} catch (UnknowAccountException e) {
e.printStackTrace();
}
return content;
}
/*@RequestMapping(value = "/loginVerify2", method = RequestMethod.POST)
public synchronized
@ResponseBody
String login(){
String email = "<EMAIL>";
String password = "<PASSWORD>";
String content = MyHttpClientUtils.doPost(loginUrl+"email_ID/"+URLEncoder.encode(email)+"/user_password/"+password,null,"UTF-8");
JSONObject obj = JSONObject.fromObject(content);
return content;
}
public static void main(String[] args)
{
String content = MyHttpClientUtils.doPost("http://localhost:8080/movieclub/r/sys/rest/loginVerify2",null,"UTF-8");
System.out.println(content);
}*/
}
<file_sep>/*
* Copyright (C) 2015 SEC BFO, Inc. All Rights Reserved.
*/
package com.thinkgem.jeesite.movieclub.vo;
import java.util.Date;
public class CommentVO
{
private String parentCommentId; // parent_comment_id
private String movieId; // movie_id
private String consumerId; // consumer_id
private String commentDescription; // comment_description
private String firstName;
private String lastName;
private String nickName;
private Date createDate;
public String getParentCommentId()
{
return parentCommentId;
}
public void setParentCommentId(String parentCommentId)
{
this.parentCommentId = parentCommentId;
}
public String getMovieId()
{
return movieId;
}
public void setMovieId(String movieId)
{
this.movieId = movieId;
}
public String getConsumerId()
{
return consumerId;
}
public void setConsumerId(String consumerId)
{
this.consumerId = consumerId;
}
public String getCommentDescription()
{
return commentDescription;
}
public void setCommentDescription(String commentDescription)
{
this.commentDescription = commentDescription;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getNickName()
{
return nickName;
}
public void setNickName(String nickName)
{
this.nickName = nickName;
}
public Date getCreateDate()
{
return createDate;
}
public void setCreateDate(Date createDate)
{
this.createDate = createDate;
}
}
<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.api.mobile;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.movieclub.comment.entity.MovieConsumerComments;
import com.thinkgem.jeesite.movieclub.comment.service.MovieConsumerCommentsService;
import com.thinkgem.jeesite.movieclub.consumer.entity.Consumer;
import com.thinkgem.jeesite.movieclub.consumer.service.ConsumerService;
import com.thinkgem.jeesite.movieclub.util.Const;
import com.thinkgem.jeesite.movieclub.util.Message;
import com.thinkgem.jeesite.movieclub.vo.CommentVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
/**
* commentController
* @author eric.wang
* @version 2015-10-16
*/
@Controller
@RequestMapping(value = "${mobileApiPath}/comments")
public class CommentsAPIController
extends BaseController {
@Autowired
private MovieConsumerCommentsService movieConsumerCommentsService;
@Autowired
private ConsumerService consumerService;
@RequestMapping(value = "/addComment", method = RequestMethod.POST)
@ResponseBody
public String addToBucket(@RequestBody CommentVO commentVO,@RequestParam(required=false) String token) {
Consumer consumer = consumerService.getByToken(token,"mt");
if (null != consumer) {
MovieConsumerComments comment = new MovieConsumerComments();
BeanUtils.copyProperties(commentVO, comment);
movieConsumerCommentsService.save(comment);
return Const.APIResult.SUCCESS_MESSAGE;
}else {
return String.format(Const.APIResult.ERROR_MESSAGE, Const.StatusCode.Consumer.ACCOUNT_NOT_EXIST_OR_TOKEN_EXPIRED, Message.Consumer.ACCOUNT_DOES_NOT_EXISTS_OR_TOKEN_EXPIRED);
}
}
@RequestMapping(value = "/getMovieComments", method = RequestMethod.GET)
@ResponseBody
public List<CommentVO> getMyBucket(@RequestParam(required=true) String id){
List<CommentVO> list=new ArrayList<CommentVO>();
List<MovieConsumerComments> movieComments= movieConsumerCommentsService.getMovieComments(id);
for(MovieConsumerComments item : movieComments){
CommentVO commentVO=new CommentVO();
BeanUtils.copyProperties(item, commentVO);
list.add(commentVO);
}
return list;
}
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.contact.entity;
import org.hibernate.validator.constraints.Length;
import com.thinkgem.jeesite.common.persistence.DataEntity;
/**
* ContactEntity
* @author eric.wang
* @version 2015-10-15
*/
public class Contact extends DataEntity<Contact> {
private static final long serialVersionUID = 1L;
private String objType; // obj_type
private String name; // name
private String company; // company
private String email; // email
private String phone; // phone
private String consumerId;
public Contact() {
super();
}
public Contact(String id){
super(id);
}
@Length(min=0, max=10, message="obj_type长度必须介于 0 和 10 之间")
public String getObjType() {
return objType;
}
public void setObjType(String objType) {
this.objType = objType;
}
@Length(min=0, max=255, message="name长度必须介于 0 和 255 之间")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Length(min=0, max=255, message="company长度必须介于 0 和 255 之间")
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
@Length(min=0, max=64, message="phone长度必须介于 0 和 64 之间")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getConsumerId()
{
return consumerId;
}
public void setConsumerId(String consumerId)
{
this.consumerId = consumerId;
}
}<file_sep>package com.thinkgem.jeesite.movieclub.vo;
public class SysConfig {
private String mediaServerProtocol;
private String mediaServerIP;
private String mediaServerPort;
public String getMediaServerProtocol() {
return mediaServerProtocol;
}
public void setMediaServerProtocol(String mediaServerProtocol) {
this.mediaServerProtocol = mediaServerProtocol;
}
public String getMediaServerIP() {
return mediaServerIP;
}
public void setMediaServerIP(String mediaServerIP) {
this.mediaServerIP = mediaServerIP;
}
public String getMediaServerPort() {
return mediaServerPort;
}
public void setMediaServerPort(String mediaServerPort) {
this.mediaServerPort = mediaServerPort;
}
}
<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.bucket.entity;
import org.hibernate.validator.constraints.Length;
import com.thinkgem.jeesite.common.persistence.DataEntity;
/**
* BucketEntity
* @author eric.wang
* @version 2015-10-16
*/
public class MovieBucket extends DataEntity<MovieBucket> {
private static final long serialVersionUID = 1L;
private String movieId; // movie_id
private String consumerId; // consumer_id
public MovieBucket() {
super();
}
public MovieBucket(String id){
super(id);
}
@Length(min=1, max=64, message="movie_id长度必须介于 1 和 64 之间")
public String getMovieId() {
return movieId;
}
public void setMovieId(String movieId) {
this.movieId = movieId;
}
@Length(min=1, max=64, message="consumer_id长度必须介于 1 和 64 之间")
public String getConsumerId() {
return consumerId;
}
public void setConsumerId(String consumerId) {
this.consumerId = consumerId;
}
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.permission.entity;
import org.hibernate.validator.constraints.Length;
import com.thinkgem.jeesite.common.persistence.DataEntity;
/**
* permissionEntity
* @author marvin.ma
* @version 2015-10-19
*/
public class Permission extends DataEntity<Permission> {
private static final long serialVersionUID = 1L;
private String permissionName; // permission_name
private String description; // description
public Permission() {
super();
}
public Permission(String id){
super(id);
}
@Length(min=0, max=64, message="permission_name长度必须介于 0 和 64 之间")
public String getPermissionName() {
return permissionName;
}
public void setPermissionName(String permissionName) {
this.permissionName = permissionName;
}
@Length(min=0, max=255, message="description长度必须介于 0 和 255 之间")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.movie.service;
import java.util.ArrayList;
import java.util.List;
import com.thinkgem.jeesite.movieclub.movie_tag.entity.MovieTagLink;
import com.thinkgem.jeesite.movieclub.movie_tag.service.MovieTagLinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.movieclub.movie.entity.Movie;
import com.thinkgem.jeesite.movieclub.movie.dao.MovieDao;
/**
* movieService
* @author marvin.ma
* @version 2015-10-15
*/
@Service
@Transactional(readOnly = true)
public class MovieService extends CrudService<MovieDao, Movie> {
@Autowired
private MovieTagLinkService movieTagLinkService;
@Autowired
private MovieDao movieDao ;
public Movie get(String id) {
Movie movie = super.get(id);
//add by marvin: 2015-10-16 14:00
//use for: 设置 movie tags 相关信息
List<String> tags = new ArrayList<String>();
MovieTagLink movieTagLink = new MovieTagLink();
movieTagLink.setMovieId(id);
List<MovieTagLink> linkList = movieTagLinkService.findList(movieTagLink);
for (MovieTagLink tmpLink : linkList) {
//tags += tags == null || tags.length() <= 0 ? tmpLink.getTagId() : "," + tmpLink.getTagId();
tags.add(tmpLink.getTagId());
}
movie.setTags(tags);
return movie;
}
public List<Movie> findList(Movie movie) {
return super.findList(movie);
}
public List<Movie> getMovieListWithoutRecommendation(Movie movie) {
return movieDao.getMovieListWithoutRecommendation(movie);
}
public Page<Movie> findPage(Page<Movie> page, Movie movie) {
return super.findPage(page, movie);
}
@Transactional(readOnly = false)
public void save(Movie movie) {
super.save(movie);
}
@Transactional(readOnly = false)
public void delete(Movie movie) {
super.delete(movie);
}
}<file_sep>package com.thinkgem.jeesite.movieclub.mail;
import java.util.Map;
public class MailEntity {
private static final long serialVersionUID = -6020807260087167958L;
private String[] to;
private String[] cc;
private String subject;
private Map paramMap;
private String templateName;
public String[] getTo() {
return to;
}
public void setTo(String[] to) {
this.to = to;
}
public String[] getCc() {
return cc;
}
public void setCc(String[] cc) {
this.cc = cc;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public Map getParamMap() {
return paramMap;
}
public void setParamMap(Map paramMap) {
this.paramMap = paramMap;
}
public String getTemplateName() {
return templateName;
}
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
}
<file_sep>/*
SQLyog Ultimate v11.11 (64 bit)
MySQL - 5.6.26
*********************************************************************
*/
insert into `sys_office` (`id`, `parent_id`, `parent_ids`, `name`, `sort`, `area_id`, `code`, `type`, `grade`, `address`, `zip_code`, `master`, `phone`, `fax`, `email`, `USEABLE`, `PRIMARY_PERSON`, `DEPUTY_PERSON`, `create_by`, `create_date`, `update_by`, `update_date`, `remarks`, `del_flag`) values('00000000000000000000000000000000','1','0,1,','用户组','30','2','00000000000000000000000000000000','2','1','','','','','','','1','','','1','2015-09-24 16:37:10','1','2015-09-24 16:37:10','','0');<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.consumer_role.service;
import java.util.List;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.movieclub.consumer_role.entity.ConsumerRole;
import com.thinkgem.jeesite.movieclub.consumer_role.dao.ConsumerRoleDao;
/**
* consumer_roleService
* @author marvin.ma
* @version 2015-10-19
*/
@Service
@Transactional(readOnly = true)
public class ConsumerRoleService extends CrudService<ConsumerRoleDao, ConsumerRole> {
public ConsumerRole get(String id) {
return super.get(id);
}
public List<ConsumerRole> findList(ConsumerRole consumerRole) {
return super.findList(consumerRole);
}
public Page<ConsumerRole> findPage(Page<ConsumerRole> page, ConsumerRole consumerRole) {
return super.findPage(page, consumerRole);
}
@Transactional(readOnly = false)
public void save(ConsumerRole consumerRole) {
super.save(consumerRole);
}
@Transactional(readOnly = false)
public void delete(ConsumerRole consumerRole) {
super.delete(consumerRole);
}
}<file_sep>/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.movieclub.contact.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.movieclub.contact.entity.Contact;
import com.thinkgem.jeesite.movieclub.contact.service.ContactService;
/**
* ContactController
* @author eric.wang
* @version 2015-10-15
*/
@Controller
@RequestMapping(value = "${adminPath}/contact/contact")
public class ContactController extends BaseController {
@Autowired
private ContactService contactService;
@ModelAttribute
public Contact get(@RequestParam(required=false) String id) {
Contact entity = null;
if (StringUtils.isNotBlank(id)){
entity = contactService.get(id);
}
if (entity == null){
entity = new Contact();
}
return entity;
}
@RequiresPermissions("contact:contact:view")
@RequestMapping(value = {"list", ""})
public String list(Contact contact, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<Contact> page = contactService.findPage(new Page<Contact>(request, response), contact);
model.addAttribute("page", page);
return "modules/contact/contactList";
}
@RequiresPermissions("contact:contact:view")
@RequestMapping(value = "form")
public String form(Contact contact, Model model) {
model.addAttribute("contact", contact);
return "modules/contact/contactForm";
}
@RequiresPermissions("contact:contact:edit")
@RequestMapping(value = "save")
public String save(Contact contact, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, contact)){
return form(contact, model);
}
contactService.save(contact);
addMessage(redirectAttributes, "保存Contact成功");
return "redirect:"+Global.getAdminPath()+"/contact/contact/?repage";
}
@RequiresPermissions("contact:contact:edit")
@RequestMapping(value = "delete")
public String delete(Contact contact, RedirectAttributes redirectAttributes) {
contactService.delete(contact);
addMessage(redirectAttributes, "删除Contact成功");
return "redirect:"+Global.getAdminPath()+"/contact/contact/?repage";
}
}
|
574e7bf3b93671b5f6140f15e2cdea68959b1d94
|
[
"Java",
"SQL"
] | 38 |
Java
|
movitech/MovieClub
|
d50a9aaa895642b9785dcd626d8b8e1239786fd4
|
efd625f46ecd4068b78464690bc5a04aed8e941c
|
refs/heads/master
|
<file_sep>//
// Global.swift
// ISSChalange
//
// Created by <NAME> on 6/17/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
/*****************API Key***********************/
let BASE_URL = "http://api.open-notify.org/"
let ISS_NOW_URL = BASE_URL + "iss-now.json"
let PASS_URL = BASE_URL + "iss-pass.json"
let ASTROS_URL = BASE_URL + "astros.json"
/*****************Object Key***********************/
var ActivityIndicatorViewInSuperviewAssociatedObjectKey = "_UIViewActivityIndicatorViewInSuperviewAssociatedObjectKey";
/*****************User Defaults Key***********************/
enum UserDefaultsKeys : String {
case ISSLatitude
case ISSLongitude
}
<file_sep>//
// WService.swift
// ISSChalange
//
// Created by <NAME> on 6/17/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
class WService: NSObject {
static let sharedInstance = WService()
func getISSCurrentLocation(completion: @escaping (Result<IssPositionResponse, Error>) -> ()) {
guard let url_ = URL(string: ISS_NOW_URL) else { return }
URLSession.shared.dataTask(with: url_) { (data, resp, err) in
// if is error response
if let err = err {
completion(.failure(err))
return
}
// if is successful response
do {
let position = try JSONDecoder().decode(IssPositionResponse.self, from: data!)
completion(.success(position))
} catch let jsonError {
completion(.failure(jsonError))
}
}.resume()
}
func getISSPassTimess(lat : String, lon : String, completion: @escaping (Result<PassTimesResponse, Error>) -> ()) {
guard let url_ = URL(string: PASS_URL + "?lat=\(lat)&" + "lon=\(lon)") else { return }
URLSession.shared.dataTask(with: url_) { (data, resp, err) in
// if is error response
if let err = err {
completion(.failure(err))
return
}
// if is successful response
do {
let passTimes = try JSONDecoder().decode(PassTimesResponse.self, from: data!)
completion(.success(passTimes))
} catch let jsonError {
completion(.failure(jsonError))
}
}.resume()
}
func getISSAstros(completion: @escaping (Result<AstroResponse, Error>) -> ()) {
guard let url_ = URL(string: ASTROS_URL) else { return }
URLSession.shared.dataTask(with: url_) { (data, resp, err) in
// if is error response
if let err = err {
completion(.failure(err))
return
}
// if is successful response
do {
let astros = try JSONDecoder().decode(AstroResponse.self, from: data!)
completion(.success(astros))
} catch let jsonError {
completion(.failure(jsonError))
}
}.resume()
}
}
<file_sep>//
// PassTimes.swift
// ISSChalange
//
// Created by <NAME> on 6/17/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
struct PassTimesResponse : Decodable {
var message : String?
var response : [Pass]?
}
struct Pass : Decodable {
var risetime : Double?
var duration : Int?
}
<file_sep>//
// PassengersViewController.swift
// ISSChalange
//
// Created by <NAME> on 6/17/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class PassengersViewController: UIViewController {
@IBOutlet weak var mTableView: UITableView!
var mListAstros : [Astro] = []
override func viewDidLoad() {
super.viewDidLoad()
getListPassengers()
}
func getListPassengers() {
self.showActivityIndicatoryInSuperview()
WService.sharedInstance.getISSAstros { (res) in
switch res {
case .success(let astrosRes):
self.mListAstros = astrosRes.people!
DispatchQueue.main.async {
self.mTableView.reloadData()
self.hideActivityIndicatoryInSuperview()
}
case .failure(let err):
DispatchQueue.main.async {
self.hideActivityIndicatoryInSuperview()
}
self.showAlertViewInSuperview("Failed to fetch astros", message: err.localizedDescription, completion: {
print("Failed to fetch astros:", err)
})
}
}
}
}
extension PassengersViewController : UITableViewDataSource, UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.mListAstros.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "astroTableViewCell", for: indexPath) as! AstroTableViewCell
// Configure the cell...
cell.initcell(astro: self.mListAstros[indexPath.row] )
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
class AstroTableViewCell: UITableViewCell {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var craft: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func initcell(astro : Astro){
self.name?.text = astro.name
self.craft?.text = astro.craft
}
}
<file_sep>//
// CustomView.swift
// ISSChalange
//
// Created by <NAME> on 6/17/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class LoadingView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.black.withAlphaComponent(0.15)
let loadingView: UIView = UIView()
loadingView.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
loadingView.center = self.center
loadingView.backgroundColor = UIColor.black.withAlphaComponent(0.6)
loadingView.clipsToBounds = true
loadingView.layer.cornerRadius = 10
loadingView.tintColor = UIColor.gray
let actInd: UIActivityIndicatorView = UIActivityIndicatorView()
actInd.frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0);
actInd.style = UIActivityIndicatorView.Style.whiteLarge
actInd.color = UIColor.white
actInd.center = CGPoint(x: loadingView.frame.size.width / 2, y: loadingView.frame.size.height / 2);
actInd.startAnimating()
loadingView.addSubview(actInd)
self.addSubview(loadingView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>//
// ViewController.swift
// ISSChalange
//
// Created by <NAME> on 6/17/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import MapKit
class MainViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
var timer : Timer?
let mLocationManager = CLLocationManager()
var userLocation : CLLocation?
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
startTracking()
initLocationManager()
}
func initLocationManager() {
self.mLocationManager.requestAlwaysAuthorization()
self.mLocationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
mLocationManager.delegate = self
mLocationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
mLocationManager.startUpdatingLocation()
}
}
let regionraduis : CLLocationDistance = 1000000
func centerMapOnLocation(location : CLLocation){
let coordinateRegion = MKCoordinateRegion.init(center: location.coordinate, latitudinalMeters: regionraduis, longitudinalMeters: regionraduis)
mapView.setRegion(coordinateRegion, animated: true)
}
func startTracking() {
self.timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(refreshLocationISS), userInfo: ["score": 10], repeats: true)
}
func stopTracking() {
if self.timer != nil {
self.timer!.invalidate()
self.timer = nil
}
}
@objc func refreshLocationISS(){
WService.sharedInstance.getISSCurrentLocation{ (res) in
switch res {
case .success(let position):
print(String(describing: position.message!))
// show artwork on map
DispatchQueue.main.async {
if let latitude : String = position.iss_position?.latitude, let longitude = position.iss_position?.longitude {
let coordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: Double(latitude) as! CLLocationDegrees , longitude: Double(longitude) as! CLLocationDegrees)
let myAnnotation: MKPointAnnotation = MKPointAnnotation()
myAnnotation.coordinate = CLLocationCoordinate2DMake(coordinate.latitude, coordinate.longitude);
myAnnotation.title = "Point ISS"
self.mapView.addAnnotation(myAnnotation)
self.centerMapOnLocation(location: CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude))
UserDefaults.standard.setValueISSLocationCoordinateLatidud(value: latitude)
UserDefaults.standard.setValueISSLocationCoordinateLongitude(value: longitude)
}
}
case .failure(let err):
print("Failed to fetch position:", err)
self.stopTracking()
self.showAlertViewInSuperview("Failed to fetch position", message: err.localizedDescription, completion: {
self.stopTracking()
})
}
}
}
deinit {
stopTracking()
}
}
extension MainViewController : MKMapViewDelegate, CLLocationManagerDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
if !(annotation is MKPointAnnotation) {
return nil
}
let annotationIdentifier = "PointISS"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
annotationView!.canShowCallout = true
}
else {
annotationView!.annotation = annotation
}
var pinImage = UIImage(named: "point_blue_ic")
//Testing if ISS in above location
if self.userLocation != nil{
if self.calculateDistance(ISSLocation: CLLocation(latitude: annotation.coordinate.latitude, longitude:annotation.coordinate.longitude ))
{
pinImage = UIImage(named: "point_spring_ic")
}
}
annotationView!.image = pinImage
return annotationView
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
self.userLocation = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude)
}
func calculateDistance(ISSLocation : CLLocation) -> Bool {
//Measuring distance between ISS and User (in km)
let distance = self.userLocation!.distance(from: ISSLocation) / 1000
if distance <= 60
{
return true
}
else{
return false
}
}
}
<file_sep>//
// UIViewController.swift
// ISSChalange
//
// Created by <NAME> on 6/17/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
extension UIViewController{
typealias CompletionHandlerConfirmExit = () -> Void
/**********************Alert View*******************/
func showAlertViewInSuperview(_ Title:String, message:String , completion:@escaping () -> Void) {
let alertController = UIAlertController(title: Title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
alertController.dismiss(animated: true, completion: completion) })
alertController.addAction(defaultAction)
UIApplication.topViewController()!.present(alertController, animated: true, completion: nil)
}
/**********************Activity Indicator*******************/
func showActivityIndicatoryInSuperview() {
let window = UIApplication.shared.keyWindow!
let loadingView = LoadingView(frame: CGRect(x: window.frame.origin.x, y: window.frame.origin.y, width: window.frame.width, height: window.frame.height))
// loadingView.
window.addSubview(loadingView)
objc_setAssociatedObject(UIApplication.shared.keyWindow?.rootViewController! as Any, &ActivityIndicatorViewInSuperviewAssociatedObjectKey, loadingView, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
func hideActivityIndicatoryInSuperview() {
if let ActivityIndicatory = objc_getAssociatedObject(UIApplication.shared.keyWindow?.rootViewController as Any, &ActivityIndicatorViewInSuperviewAssociatedObjectKey) {
(ActivityIndicatory as AnyObject).removeFromSuperview()
}
}
}
<file_sep>//
// UserDefaults.swift
// ISSChalange
//
// Created by <NAME> on 6/18/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
extension UserDefaults {
func isKeyPresentInUserDefaults(key: String) -> Bool {
return UserDefaults.standard.object(forKey: key) != nil
}
//MARK: Retrieve latitude Coordinate
func getValueLocationISSCoordinateLatidud() -> String {
return UserDefaults.standard.string(forKey: UserDefaultsKeys.ISSLatitude.rawValue)!
}
//MARK: Retrieve longitude Coordinate
func getValueLocationISSCoordinateLongitude() -> String {
return UserDefaults.standard.string(forKey: UserDefaultsKeys.ISSLongitude.rawValue)!
}
//MARK: save latitude Coordinate
func setValueISSLocationCoordinateLatidud(value: String) {
set(value, forKey: UserDefaultsKeys.ISSLatitude.rawValue)
}
//MARK: save longitude Coordinate
func setValueISSLocationCoordinateLongitude(value: String){
set(value, forKey: UserDefaultsKeys.ISSLongitude.rawValue)
}
}
<file_sep>//
// Date.swift
// ISSChalange
//
// Created by <NAME> on 6/18/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
extension Date
{
func convertUnixtimeInterval() -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" //Specify your format that you want
return dateFormatter.string(from: self)
}
}
<file_sep>//
// Astros.swift
// ISSChalange
//
// Created by <NAME> on 6/17/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
struct AstroResponse : Decodable {
var message : String?
var number : Int?
var people : [Astro]?
}
struct Astro : Decodable {
var name : String?
var craft : String?
}
<file_sep>//
// AboveLocationViewController.swift
// ISSChalange
//
// Created by <NAME> on 6/17/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class AboveLocationViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mTitleLabel: UILabel!
@IBOutlet weak var mDescLabel: UILabel!
let mLocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
initLocationManager()
}
func initLocationManager() {
self.mLocationManager.requestAlwaysAuthorization()
self.mLocationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
mLocationManager.delegate = self
mLocationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
mLocationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
// print("locations = \(locValue.latitude) \(locValue.longitude)")
self.calculateDistance(UserLatitude: locValue.latitude, UserLongitude: locValue.longitude)
}
func calculateDistance(UserLatitude : Double, UserLongitude : Double) {
let ISSLatitude = UserDefaults.standard.getValueLocationISSCoordinateLatidud()
let ISSLongitude = UserDefaults.standard.getValueLocationISSCoordinateLongitude()
//User location
let userLocation = CLLocation(latitude: UserLatitude, longitude: UserLongitude)
//ISS location
let ISSLocation = CLLocation(latitude: Double(ISSLatitude) as! CLLocationDegrees, longitude: Double(ISSLongitude) as! CLLocationDegrees)
//Measuring distance between ISS and User (in km)
let distance = userLocation.distance(from: ISSLocation) / 1000
if distance <= 60
{
self.mTitleLabel.text = "ISS is hovering above your location";
}
else{
self.mTitleLabel.text = "ISS is not hovering above your location";
}
self.mDescLabel.text = String("The distance between you and ISS is \(String(format:"%.2f", distance)) Km")
}
}
<file_sep>//
// Station.swift
// International Space Station
//
// Created by <NAME> on 6/17/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
struct IssPositionResponse : Decodable {
var timestamp : Int?
var message : String?
var iss_position : Position?
}
struct Position : Decodable {
var latitude : String?
var longitude: String?
}
<file_sep># ISSLocation
Tracking location of the ISS (International Space Station)
Use this IOS APP map to find out where the International Space Station (ISS) is.
Display a list of the actual passengers of the ISS.
Tell the user if the ISS is over his own location within a radius of
10 km.
Let the user know at which time the ISS will be passing above his location.
This application create with Swift 5, use 100% functionalities/tools the iOS SDK (URLSession, MapKit ...).
<file_sep>//
// PassTimesViewController.swift
// ISSChalange
//
// Created by <NAME> on 6/17/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import MapKit
class PassTimesViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mTableView: UITableView!
let mLocationManager = CLLocationManager()
var mListPassTimes = [Pass]()
override func viewDidLoad() {
super.viewDidLoad()
initLocationManager()
}
func initLocationManager() {
self.mLocationManager.requestAlwaysAuthorization()
// For use in foreground
self.mLocationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
mLocationManager.delegate = self
mLocationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
mLocationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
self.mLocationManager.stopUpdatingLocation()
self.getPassTimes(lat: "\(locValue.latitude)", lon: "\(locValue.longitude)")
}
func getPassTimes(lat : String, lon : String) {
WService.sharedInstance.getISSPassTimess(lat: lat, lon: lon) { (res) in
switch res {
case .success(let passTimesRes):
DispatchQueue.main.async {
self.mListPassTimes = passTimesRes.response!
self.mTableView.reloadData()
}
case .failure(let err):
DispatchQueue.main.async {
self.hideActivityIndicatoryInSuperview()
}
self.showAlertViewInSuperview("Failed to fetch astros", message: err.localizedDescription, completion: {
print("Failed to fetch astros:", err)
})
}
}
}
}
extension PassTimesViewController : UITableViewDataSource, UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.mListPassTimes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "passTimeTableViewCell", for: indexPath) as! PassTimeTableViewCell
// Configure the cell...
cell.initcell(pass: self.mListPassTimes[indexPath.row] )
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
class PassTimeTableViewCell: UITableViewCell {
@IBOutlet weak var duration: UILabel!
@IBOutlet weak var risetime: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func initcell(pass : Pass){
self.risetime?.text = Date(timeIntervalSince1970: pass.risetime!).convertUnixtimeInterval()
let (h, m, s) = convertSecondsToHMS(pass.duration!)
self.duration?.text = String(describing: "\(h) Hours, \(m) Minutes, \(s) Seconds")
}
func convertSecondsToHMS(_ seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
}
|
2cc31f10c52d76d8bdd6f4fed9ed361e1a79dda7
|
[
"Swift",
"Markdown"
] | 14 |
Swift
|
lhouch/ISSLocation
|
bda4961e2a07ad120aad9a80c5a6f2763f174502
|
ec989a79bee930353a345f36693b4ea13fefd81d
|
refs/heads/master
|
<repo_name>symphony-snippets/taskgroup-dev-react<file_sep>/browser-sync.gulp.js
import browserSync from 'browser-sync';
import serveStatic from 'serve-static';
export default (gulp, plugins, config, done) => {
if (config.IS_PROD) {
done();
return;
}
const { INIT_CWD, SITE = "tacoshop", ENV = "manage" } = process.env;
if (!config.MANAGE_URL) {
console.log('No URL specified, using default');
}
return browserSync.init({
notify: false,
proxy: `https://${ENV}.symphonycommerce.com/${SITE}${config.MANAGE_URL}`,
https: true,
rewriteRules: [
{
match: new RegExp("//stats.g.doubleclick.net/dc.js"),
fn: function() {
return '/main.min.js';
}
}
],
middleware: serveStatic(config.STAGING)
});
}
<file_sep>/build-clean.gulp.js
import del from 'del';
export default (gulp, plugins, config) => {
var toDelete = [
config.STAGING,
config.MASTER
];
return del(toDelete, {
force: true
});
}
<file_sep>/_sequence.gulp.js
import _ from 'lodash';
import gulpLoadPlugins from 'gulp-load-plugins';
export default (gulp, plugins, config, done) => {
_.assign(plugins, gulpLoadPlugins());
const { INIT_CWD, SITE = "tacoshop", NODE_ENV } = process.env;
const { packageJson, BRANCH_NAME } = config;
let {
beforeBundle = [],
afterBundle = [] } = config.taskSequences;
if (!config.IS_MASTER && !config.IS_TEST) {
afterBundle = [
'dev-react:browser-sync',
...afterBundle]
}
let sequence = [
...beforeBundle,
'dev-react:build-clean',
'dev-react:browserify',
...afterBundle
]
config.STAGING = 'build';
config.MASTER = 'dist';
config.IS_PROD = NODE_ENV == 'production';
config.IS_DEV = !config.IS_PROD;
config.S3 = "//s3.amazonaws.com/sneakpeeq-sites";
config.CDN = "//d20b8ckvu6gb0w.cloudfront.net";
plugins.runSequence(
...(_.compact(sequence)),
done
);
}
<file_sep>/karma.conf.js
module.exports = function(config) {
var browserifyTransform = ['babelify'];
var reporters = ['spec', 'failed'];
var files = `${process.env.INIT_CWD}/test/**/*.spec.js`;
if (process.env.COVERAGE) {
browserifyTransform.push(require('browserify-istanbul')({
ignore: ['**/node_modules/**', '**/*.spec.js'],
defaultIgnore: true
}));
reporters.push('coverage');
}
config.set({
basePath: '',
files: [files],
plugins: [
'karma-chrome-launcher',
'karma-failed-reporter',
'karma-spec-reporter',
'karma-browserify',
'karma-mocha',
'babelify',
'karma-coverage'
],
frameworks: ['browserify', 'mocha'],
preprocessors: {
[files]: ['browserify']
},
browserify: {
debug: true,
transform: browserifyTransform
},
browsers: ['Chrome'],
reporters: reporters,
coverageReporter: {
dir: `${process.env.INIT_CWD}/coverage`,
reporters: [{
type: 'html',
subdir: 'report-html'
}, {
type: 'text',
}]
},
colors: true
})
};<file_sep>/browserify.gulp.js
import browserify from 'browserify';
import babelify from 'babelify';
import watchify from 'watchify';
import stringify from 'stringify';
import bulkify from 'bulkify';
import source from 'vinyl-source-stream';
import hmr from 'browserify-hmr';
import notify from 'gulp-notify';
export default (gulp, plugins, config) => {
const { INIT_CWD } = process.env;
let appBundler = browserify({
entries: './app/main.jsx',
extensions: ['.js', '.jsx'],
debug: config.IS_DEV,
cache: {},
packageCache: {},
fullPaths: config.IS_DEV
});
(() => {
return !config.IS_PROD ?
appBundler.plugin(hmr, {
url: 'https://localhost:3123',
tlskey: INIT_CWD + '/key.pem',
tlscert: INIT_CWD + '/cert.pem'
}) : appBundler;
})()
.transform(babelify)
.transform(bulkify);
var rebundle = function () {
var start = Date.now();
console.log('Building APP bundle');
return appBundler
.bundle()
.on('error', function (error) { console.error(error.toString()); })
.pipe(source('main.min.js'))
.pipe(gulp.dest(config.STAGING))
.pipe(notify(function () {
console.log('APP bundle built in ' + (Date.now() - start) + 'ms');
}));
};
appBundler = watchify(appBundler, {
poll: true,
verbose: true
});
appBundler.on('update', rebundle);
return rebundle();
}
<file_sep>/upload-manager.gulp.js
import buffer from 'vinyl-buffer';
export default (gulp, plugins, config) => {
const {AWS_HEADERS, MASTER, S3_PATH } = config;
const path = `${process.env.PWD}/${MASTER}`;
return gulp.src([
`${path}/*.js`,
`${MASTER}/*.html`,
`${MASTER}/*.css`,
], {
cwd: MASTER
})
.pipe(buffer())
.pipe(plugins.rename((path) => {
path.dirname += `${S3_PATH}`;
}))
.pipe(plugins.publisher.publish(AWS_HEADERS, {
createOnly: false,
force:true
}))
.pipe(plugins.awspublish.reporter());
}
<file_sep>/karma-test-coverage.gulp.js
const karma = require('karma-as-promised');
export default (gulp, plugins, config) => {
process.env.COVERAGE = true;
return karma.server.start({
configFile: `${process.env.INIT_CWD}/karma.conf.js`,
singleRun: true
});
}
<file_sep>/README.md
## React Development Task Group
### Build Config
Create a file called build-config.json in the root of your react project.
```
{
"tasks": {
"dev": ["dev-react:_sequence"],
"test":["dev-react:_test_sequence"],
"deploy":["dev-react:_deploy_sequence"]
},
"taskGroups": {
"dev-react": {
"devEnabled": true,
"deployEnabled":true
}
},
"MANAGE_URL": "/admin/customer/cs/orders", // url to proxy for development
"S3_PATH": "/symphony-cs-apps/", // S3 path (not including bucket)
"S3_FILENAME": "advancedTab.main.min.js"
}
```
### Commands
* **gulp dev** - development with auto update on save. Only need to refresh the browser if updating actions or reducers
* **gulp test** - not yet implemented
* **gulp deploy** - *DO NOT RUN LOCALLY*, should only be run by Circle CI to deploy to S3
### Environment Variables
Set the following environment variables in Circle CI to enable deployment to S3.
* AWS_ACCESSKEY
* AWS_BUCKET
* AWS_SECRETKEY<file_sep>/_test_sequence.gulp.js
import _ from 'lodash';
import gulpLoadPlugins from 'gulp-load-plugins';
export default (gulp, plugins, config, done) => {
_.assign(plugins, gulpLoadPlugins());
const { INIT_CWD, SITE = "tacoshop" } = process.env;
const { packageJson, BRANCH_NAME } = config;
let sequence = [
'dev-react:_sequence',
'dev-react:karma-test-coverage'
]
const integrationLocation = `/org/${SITE}/api/v1/manage/integration/${BRANCH_NAME}_${packageJson.name}`;
config.IS_TEST = true;
config.DEST = `${INIT_CWD}/serve-static${integrationLocation}`;
plugins.runSequence(
...(_.compact(sequence)),
() => {
done();
process.exit(0);
}
);
}
|
1ba05d353dce03694b0e50b03ea936c820fa82c6
|
[
"JavaScript",
"Markdown"
] | 9 |
JavaScript
|
symphony-snippets/taskgroup-dev-react
|
372f42245b0cce75eabea72243990e9f1986f1df
|
eb829cc1cfaf3bcecd629b25a833bb89e4b456cc
|
refs/heads/master
|
<repo_name>edse/social<file_sep>/src/Edse/UserBundle/EdseUserBundle.php
<?php
namespace Edse\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class EdseUserBundle extends Bundle
{
}
<file_sep>/src/Edse/UserBundle/Model/OAuthUserProvider.php
<?php
namespace Edse\UserBundle\Model;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUserProvider as BaseOAuthUserProvider;
class OAuthUserProvider extends BaseOAuthUserProvider { }
|
86dc51af1df5f06fe7865cb0a1b23888cbfd0787
|
[
"PHP"
] | 2 |
PHP
|
edse/social
|
e131f192c31ab21f0b0f89e315a8dba9e3f40c72
|
5a5111b08eeaf780a0efa29a1c958c51a84212d6
|
refs/heads/master
|
<repo_name>christocarr/hangman<file_sep>/src/request.js
'use strict'
const getGame = async (wordCount) => {
const response = await fetch(`https://api.wordnik.com/v4/words.json/randomWord?hasDictionaryDef=true&maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=5&maxLength=-1&api_key=`)
if (response.status === 200) {
const data = await response.json()
return data.word
} else {
throw new Error('Unable to get new puzzle')
}
}
export default getGame
|
b4818947b1255781e305733f6a419fdc6e933ae8
|
[
"JavaScript"
] | 1 |
JavaScript
|
christocarr/hangman
|
e572a958755923155d6250b7b512af91000a2ce4
|
eff4482958edef4217d0780ed4994fdaf3676b74
|
refs/heads/master
|
<repo_name>pilot-fly/wuziqi<file_sep>/wuziqi.js
$(function(){
var c=document.getElementById("c");
var $audio=$("#audio");
var audio=$("#audio").get(0);
var audio1=$("#audio1").get(0);
var ctx=c.getContext('2d');
var sep=40;
var sr=5;
var br=40;
var time=[10,9,8,7,6,5,4,3,2,1,0];
var time1=[10,9,8,7,6,5,4,3,2,1,0];
//画棋盘
function huan(x){
return (x+0.5)*sep+0.5;
}
function qipan(){
ctx.save();
ctx.fillStyle='#BC7905';
ctx.fillRect(0,0,600,600);
ctx.restore();
ctx.save();
ctx.fillStyle='#FCC621';
ctx.fillRect(huan(0),huan(0),560.5,560.5);
ctx.restore();
ctx.save();
ctx.beginPath();
for(var i=0;i<15;i++){
ctx.moveTo(huan(0),huan(i));
ctx.lineTo(huan(14),huan(i));
ctx.moveTo(huan(i),huan(0));
ctx.lineTo(huan(i),huan(14));
}
ctx.stroke();
ctx.closePath();
ctx.restore();
}
qipan();
//画小圆
function scil(x,y){
ctx.save();
ctx.beginPath();
ctx.arc(huan(x),huan(y),sr,0,Math.PI*2);
ctx.fill();
ctx.closePath();
ctx.restore();
}
scil(7,7);
scil(3,3);
scil(3,11);
scil(11,3);
scil(11,11);
//画表盘
function biaopan(cp){
cp.save();
cp.beginPath();
cp.translate(100,100);
for(var i=0;i<60;i++){
if(i%5==0){
cp.moveTo(0,-50);
}else{
cp.moveTo(0,-70);
}
cp.lineTo(0,-80);
cp.rotate(Math.PI/180*6);
}
cp.closePath();
cp.stroke();
cp.restore();
cp.save();
cp.font = "80px serif";
cp.fillStyle="#fff";
cp.textAlign="center";
cp.textBaseline = "middle";
cp.fillText("10",100,100);
cp.restore();
}
//黑白落子的时间
var blackT=document.getElementById("blackT");
var ctx1=blackT.getContext('2d');
var whiteT=document.getElementById("whiteT");
var ctx2=whiteT.getContext('2d');
biaopan(ctx1);
biaopan(ctx2);
function pan(ctx1,qiming){
ctx1.clearRect(0,0,200,200);
ctx1.save();
ctx1.beginPath();
ctx1.translate(100,100);
ctx1.arc(0,0,80,0,Math.PI*2);
ctx1.closePath();
ctx1.stroke();
ctx1.restore();
}
var de=0;//黑棋时间小点
var deg=0;//白棋时间小点
//黑棋时间
function render(cp,ming,t){
cp.clearRect(0,0,200,200);
pan(cp,ming);
cp.save();
cp.beginPath();
cp.translate(100,100);
cp.rotate(Math.PI/180*de);
cp.arc(0,-80,10,0,Math.PI*2);
cp.fill();
cp.closePath();
cp.restore();
de+=1;
if(de===360){
alert("时间到,白棋胜,结束游戏");
clearInterval(t);
}
cp.save();
cp.font = "80px serif";
cp.fillStyle="#fff";
cp.textAlign="center";
cp.textBaseline = "middle";
cp.fillText(time1[Math.floor(de/33)],100,100);
cp.restore();
audio1.play();
}
//白棋时间
function render1(cp,ming,t){
cp.clearRect(0,0,200,200);
pan(cp,ming);
cp.save();
cp.beginPath();
cp.translate(100,100);
cp.rotate(Math.PI/180*deg);
cp.arc(0,-80,10,0,Math.PI*2);
cp.fill();
cp.closePath();
cp.restore();
cp.save();
cp.font = "80px serif";
cp.fillStyle="#fff";
cp.textAlign="center";
cp.textBaseline = "middle";
cp.fillText(time[Math.floor(deg/33)],100,100);
cp.restore();
deg+=1;
if(deg===360){
alert("时间到,黑棋胜,结束游戏");
clearInterval(t);
}
audio1.play();
}
var bt=setInterval(function(){
render(ctx1,"黑棋",bt);
},100);
var wt=setInterval(function(){
render1(ctx2,"白棋",wt);
},100);
clearInterval(bt);
clearInterval(wt);
//画棋子
var qizi=[];
function luozi(x,y,r,color){
ctx.save();
ctx.translate(huan(x),huan(y));
ctx.beginPath();
ctx.arc(0,0,r,0,Math.PI*2);
var g=ctx.createRadialGradient(-4,-4,0,0,0,20);
if(color==='black'){
g.addColorStop(0.1,"#eee");
g.addColorStop(0.2,"#eee");
g.addColorStop(1,"black");
ctx.fillStyle=g;
}else{
g.addColorStop(0.1,"#fff");
g.addColorStop(0.2,"#fff");
g.addColorStop(1,"#eee");
ctx.fillStyle=g;
}
qizi[x+"_"+y]=color;
ctx.fill();
ctx.closePath();
ctx.restore();
audio.play();
// qizi.push({x:x,y:y,color:color});
// console.table(qizi);
}
//判断是否已有某个棋子
function you(x,y){
var kai=false;
$.each(qizi,function(i,v){
if(qizi[i].x==x&&qizi[i].y==y){
kai=true;
}
});
return kai;
// console.log(qizi[i].x)
}
var flag=true;
$(c).on('click',function(e){
var bian=0;
var a=Math.floor(e.offsetX/sep);
var b=Math.floor(e.offsetY/sep);
// if(you(a,b)){
// return;
// }
if(qizi[a+"_"+b]){
return;
}
if(flag){
luozi(a,b,20,"black");
clearInterval(bt);
de=0;
wt=setInterval(function(){
render1(ctx2,"白棋",wt);
},100);
}else{
luozi(a,b,20,"white");
clearInterval(wt);
deg=0;
bt=setInterval(function(){
render(ctx1,"黑棋",bt);
},100);
}
console.log(flag);
flag=!flag;
});
//暂停、继续、重新开局
$("#zan").on('click',function(){
if(flag){
clearInterval(bt);
}
else{
clearInterval(wt);
}
});
$("#jixu").on('click',function(){
if(flag){
bt=setInterval(function(){
render(ctx1,"黑棋",bt);
},100);
}
else{
wt=setInterval(function(){
render1(ctx2,"白棋",wt);
},100);
}
});
$("#xin").on("click",function(){
location.href="wuziqi.html";
});
//游戏规则
$("#gui").on("click",function(){
$("#guize").css("display","block");
});
$("#fan").on("click",function(){
$("#guize").css("display","none");
});
});
|
75c891537df16d5bd650f766a010d44c1f31a22d
|
[
"JavaScript"
] | 1 |
JavaScript
|
pilot-fly/wuziqi
|
cd9ee75dec7a1fa6258f29dfa7d4a9ea7d689738
|
92264bb02aa670facacac14adbee7baad33b122c
|
refs/heads/master
|
<file_sep>#!/bin/bash
set -e
set -u
rm -f db-undercursor.result
undertest='*mvom/renderer.vim'
#undertest='*mvom/*/location.vim'
/Applications/MacVim.app/Contents/MacOS/Vim \
--cmd 'profile start db-undercursor.result' \
--cmd "profile! file $undertest" \
-c 'MVOMenable' \
-c '1000 | call mvom#renderer#RePaintMatches()' \
-c '1000 | call mvom#renderer#RePaintMatches()' \
-c '3000 | call mvom#renderer#RePaintMatches()' \
-c '4000 | call mvom#renderer#RePaintMatches()' \
-c '4006 | call mvom#renderer#RePaintMatches()' \
-c '4007 | call mvom#renderer#RePaintMatches()' \
-c '4008 | call mvom#renderer#RePaintMatches()' \
-c "profdel file $undertest" \
test.txt
|
225c4f3193d958674750e1f6b9609d7bd3e551c3
|
[
"Shell"
] | 1 |
Shell
|
dsummersl/vim-sluice
|
25bbd4aa7aeb75dda4abd3ea246f76fdbfe9fb7b
|
16003e16ba5fdbc0211112c087b1d8f168249677
|
refs/heads/master
|
<file_sep>module PgbackupsArchive
VERSION = "1.0.0"
end
|
2404acb3d15622864eec667bbb576020c66f7fc1
|
[
"Ruby"
] | 1 |
Ruby
|
retailos/pgbackups-archive
|
7a594c6f341544b232c9ca2b237ecd0bb6a9e367
|
51e5630f35ea572b009118c46bbfe127a41db116
|
refs/heads/master
|
<repo_name>httvhutceoscop/yii2cozy<file_sep>/frontend/views/site/contact.php
<?php
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \frontend\models\ContactForm */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
$this->title = 'Contact Us';
$this->params['breadcrumbs'][] = $this->title;
?>
<!-- BEGIN PAGE TITLE/BREADCRUMB -->
<div class="parallax colored-bg pattern-bg" data-stellar-background-ratio="0.5">
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1 class="page-title"><?= Html::encode($this->title) ?></h1>
<ul class="breadcrumb">
<li><a href="index.html">Home </a></li>
<li><a href="contacts.html">Contacts</a></li>
</ul>
</div>
</div>
</div>
</div>
<!-- END PAGE TITLE/BREADCRUMB -->
<!-- BEGIN CONTENT WRAPPER -->
<div class="content contacts">
<div id="contacts_map"></div>
<div class="container">
<div class="row">
<div id="contacts-overlay" class="col-sm-7">
<i id="contacts-overlay-close" class="fa fa-minus"></i>
<ul class="col-sm-6">
<li><i class="fa fa-map-marker"></i> 24th Street, New York, USA</li>
<li><i class="fa fa-envelope"></i> <a href="mailto:<EMAIL>"><EMAIL></a></li>
</ul>
<ul class="col-sm-6">
<li><i class="fa fa-phone"></i> Tel.: 00351 123 456 789</li>
<li><i class="fa fa-print"></i> Fax: 00351 456 789 101</li>
</ul>
</div>
<!-- BEGIN MAIN CONTENT -->
<div class="main col-sm-4 col-sm-offset-8">
<h2 class="section-title">Contact Form</h2>
<p class="col-sm-12 center">If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.</p>
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<div class="col-sm-12">
<?= $form->field($model, 'name')->textInput([
//'autofocus' => true,
'placeholder' => 'Name',
'class' => 'form-control required fromName'])->label(false)
?>
<?= $form->field($model, 'email')->textInput([
'placeholder' => 'Email',
'class' => 'form-control required fromName'])->label(false)
?>
<?= $form->field($model, 'subject')->textInput([
'placeholder' => 'Subject',
'class' => 'form-control required fromName'])->label(false)
?>
<?= $form->field($model, 'body')->textarea([
//'rows' => 6,
'placeholder' => 'Message',
'class' => 'form-control required'])->label(false)
?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-sm-4">{image}</div><div class="col-sm-8">{input}</div></div>',
])->label('Verification Code <small>(click to change code)</small>') ?>
</div>
<div class="center">
<?= Html::submitButton('<i class="fa fa-envelope"></i> Send Message', [
'class' => 'btn btn-default-color btn-lg submit_form',
'name' => 'contact-button'])
?>
</div>
<?php ActiveForm::end(); ?>
</div>
<!-- END MAIN CONTENT -->
</div>
</div>
</div>
<!-- END CONTENT WRAPPER -->
<script type="text/javascript">
// var singleMarker = [
// {
// "id": 0,
// "title": "Cozy Real State",
// "latitude": 40.727815,
// "longitude": -73.993544,
// "image": "http://placehold.it/700x603",
// "description": "Lafayette St New York, NY <br> Phone: 00351 123 456 789",
// "map_marker_icon": "images/markers/coral-marker-cozy.png"
// }
// ];
//
// (function ($) {
// "use strict";
//
// $(document).ready(function () {
// //Create contacts map. Usage: Cozy.contactsMap(marker_JSON_Object, map canvas, map zoom);
// Cozy.contactsMap(singleMarker, 'contacts_map', 14);
// });
// })(jQuery);
</script>
<file_sep>/frontend/views/site/index.php
<?php
/* @var $this yii\web\View */
$this->title = 'My Yii Application';
?>
<!-- BEGIN HOME SLIDER SECTION -->
<div class="revslider-container">
<div class="revslider" >
<ul>
<li data-transition="fade" data-slotamount="7">
<img src="http://placehold.it/1920x605" alt="" />
<div class="caption sfr slider-title" data-x="70" data-y="120" data-speed="800" data-start="1300" data-easing="easeOutBack" data-end="9600" data-endspeed="700" data-endeasing="easeInSine">HOME SWEET HOME!</div>
<div class="caption sfl slider-subtitle" data-x="75" data-y="190" data-speed="800" data-start="1500" data-easing="easeOutBack" data-end="9700" data-endspeed="500" data-endeasing="easeInSine">Cozy it's the perfect Template for Real Estate.</div>
<a href="#" class="caption sfb btn btn-default btn-lg" data-x="75" data-y="260" data-speed="800" data-easing="easeOutBack" data-start="1600" data-end="9800" data-endspeed="500" data-endeasing="easeInSine">Learn More</a>
</li>
<li data-transition="fade">
<img src="http://placehold.it/1920x605" alt="" />
<div class="caption sfr slider-title" data-x="450" data-y="120" data-speed="800" data-start="1300" data-easing="easeOutBack" data-end="9600" data-endspeed="500" data-endeasing="easeInSine">EASY TO CUSTOMIZE</div>
<div class="caption sfl slider-subtitle" data-x="455" data-y="190" data-speed="800" data-start="1500" data-easing="easeOutBack" data-end="9700" data-endspeed="500" data-endeasing="easeInSine">With more than 20 custom HTML pages<br/>available and lots of useful features to<br/>help you promote and sell your properties.</div>
<a href="#" class="caption sfb btn btn-default btn-lg" data-x="455" data-y="310" data-speed="800" data-easing="easeOutBack" data-start="1600" data-end="9800" data-endspeed="500" data-endeasing="easeInSine">Learn More</a>
</li>
<li data-transition="fade">
<img src="http://placehold.it/1920x605" alt="" />
<div class="caption sfr slider-title" data-x="70" data-y="120" data-speed="800" data-start="1300" data-easing="easeOutBack" data-end="9600" data-endspeed="500" data-endeasing="easeInSine">FULLY RESPONSIVE<br/>& RETINA READY</div>
<div class="caption sfl slider-subtitle" data-x="75" data-y="250" data-speed="800" data-start="1500" data-easing="easeOutBack" data-end="9700" data-endspeed="500" data-endeasing="easeInSine">Cozy will fit perfectly in all types<br/>of screens and devices.</div>
<a href="#" class="caption sfb btn btn-default btn-lg" data-x="75" data-y="340" data-speed="800" data-easing="easeOutBack" data-start="1600" data-end="9800" data-endspeed="500" data-endeasing="easeInSine">Try it out!</a>
<div class="caption sfr sfl" data-x="800" data-y="140" data-speed="800" data-start="1800" data-easing="easeOutBack" data-end="9800" data-endspeed="500" data-endeasing="easeInSine"><img src="images/qrc.png" alt="Cozy QRC"></div>
</li>
<li data-transition="fade">
<img src="http://placehold.it/1920x605" alt="" />
<div class="caption sfr slider-title" data-x="450" data-y="150" data-speed="800" data-start="1300" data-easing="easeOutBack" data-end="9600" data-endspeed="500" data-endeasing="easeInSine">BUILT IN HTML5 & CSS3</div>
<div class="caption sfl slider-subtitle" data-x="455" data-y="220" data-speed="800" data-start="1500" data-easing="easeOutBack" data-end="9700" data-endspeed="500" data-endeasing="easeInSine">Clean and well commented code.</div>
<a href="#" class="caption sfb btn btn-default btn-lg" data-x="455" data-y="280" data-speed="800" data-easing="easeOutBack" data-start="1600" data-end="9800" data-endspeed="500" data-endeasing="easeInSine">Learn More</a>
<div class="caption sfl str" data-x="70" data-y="170" data-speed="700" data-start="1000" data-easing="easeOutBack" data-end="9600" data-endspeed="700" data-endeasing="easeInSine"><img src="images/htm-icon.png" alt="html5"></div>
<div class="caption sfb stt" data-x="220" data-y="230" data-speed="700" data-start="1200" data-easing="easeOutBack" data-end="9700" data-endspeed="500" data-endeasing="easeInSine"><img src="images/plus.png" alt="plus"></div>
<div class="caption sfr stl" data-x="250" data-y="170" data-speed="700" data-start="1400" data-easing="easeOutBack" data-end="9800" data-endspeed="500" data-endeasing="easeInSine"><img src="images/css-icon.png" alt="css3"></div>
</li>
</ul>
</div>
</div>
<!-- END HOME SLIDER SECTION -->
<!-- BEGIN HOME ADVANCED SEARCH -->
<div id="home-advanced-search" class="open">
<div id="opensearch"></div>
<div class="container">
<div class="row">
<div class="col-sm-12">
<form>
<div class="form-group">
<div class="form-control-large">
<input type="text" class="form-control" name="location" placeholder="City, State, Country, etc...">
</div>
<div class="form-control-large">
<select id="search_prop_type" name="search_prop_type" data-placeholder="Type of Property">
<option value=""> </option>
<option value="residential">Residential</option>
<option value="commercial">Commercial</option>
<option value="land">Land</option>
</select>
</div>
<div class="form-control-small">
<select id="search_status" name="search_status" data-placeholder="Status">
<option value=""> </option>
<option value="sale">For Sale</option>
<option value="rent">For Rent</option>
</select>
</div>
<div class="form-control-small">
<select id="search_bedrooms" name="search_bedrooms" data-placeholder="Bedrooms">
<option value=""> </option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="5plus">5+</option>
</select>
</div>
<div class="form-control-small">
<select id="search_bathrooms" name="search_bathrooms" data-placeholder="Bathrooms">
<option value=""> </option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="4plus">4+</option>
</select>
</div>
<div class="form-control-small">
<select id="search_minprice" name="search_minprice" data-placeholder="Min. Price">
<option value=""> </option>
<option value="0">$0</option>
<option value="25000">$25000</option>
<option value="50000">$50000</option>
<option value="75000">$75000</option>
<option value="100000">$100000</option>
<option value="150000">$150000</option>
<option value="200000">$200000</option>
<option value="300000">$300000</option>
<option value="500000">$500000</option>
<option value="750000">$750000</option>
<option value="1000000">$1000000</option>
</select>
</div>
<div class="form-control-small">
<select id="search_maxprice" name="search_maxprice" data-placeholder="Max. Price">
<option value=""> </option>
<option value="25000">$25000</option>
<option value="50000">$50000</option>
<option value="75000">$75000</option>
<option value="100000">$100000</option>
<option value="150000">$150000</option>
<option value="200000">$200000</option>
<option value="300000">$300000</option>
<option value="500000">$500000</option>
<option value="750000">$750000</option>
<option value="1000000">$1000000</option>
<option value="1000000plus">>$1000000</option>
</select>
</div>
<button type="submit" class="btn btn-fullcolor">Search</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- END HOME ADVANCED SEARCH -->
<!-- BEGIN PROPERTIES SLIDER WRAPPER-->
<div class="parallax pattern-bg" data-stellar-background-ratio="0.5">
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1 class="section-title" data-animation-direction="from-bottom" data-animation-delay="50">Featured Properties</h1>
<div id="featured-properties-slider" class="owl-carousel fullwidthsingle" data-animation-direction="from-bottom" data-animation-delay="250">
<div class="item">
<div class="image">
<a href="properties-detail.html"></a>
<img src="http://placehold.it/760x670" alt="" />
</div>
<div class="price">
<i class="fa fa-home"></i>For Sale
<span>$950,000</span>
</div>
<div class="info">
<h3><a href="properties-detail.html">Luxury Apartment with great views</a></h3>
<p>Curabitur dignissim tortor ut scelerisque consectetur. Praesent pulvinar placerat lorem, et ultricies urna ultrices vel. Praesent eu libero a sapien adipiscing interdum feugiat id lectus.</p>
<a href="properties-detail.html" class="btn btn-default">Read More</a>
</div>
</div>
<div class="item">
<div class="image">
<a href="properties-detail.html"></a>
<img src="http://placehold.it/760x670" alt="" />
</div>
<div class="price">
<i class="fa fa-home"></i>For Sale
<span>$1,253,000</span>
</div>
<div class="info">
<h3><a href="properties-detail.html">Stunning Villa with 5 bedrooms</a></h3>
<p>Praesent eu libero a sapien adipiscing interdum feugiat id lectus. Curabitur dignissim tortor ut scelerisque consectetur. Praesent pulvinar placerat lorem.</p>
<a href="properties-detail.html" class="btn btn-default">Read More</a>
</div>
</div>
<div class="item">
<div class="image">
<a href="properties-detail.html"></a>
<img src="http://placehold.it/760x670" alt="" />
</div>
<div class="price">
<i class="fa fa-home"></i>For Rent
<span>$850</span>
</div>
<div class="info">
<h3><a href="properties-detail.html">Modern construction with parking space</a></h3>
<p>Curabitur dignissim tortor ut scelerisque consectetur. Praesent pulvinar placerat lorem, et ultricies urna ultrices vel. Praesent eu libero a sapien adipiscing interdum feugiat id lectus. Praesent pulvinar placerat lorem, et ultricies.</p>
<a href="properties-detail.html" class="btn btn-default">Read More</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END PROPERTIES SLIDER WRAPPER -->
<!-- BEGIN CONTENT WRAPPER -->
<div class="content">
<div class="container">
<div class="row">
<!-- BEGIN MAIN CONTENT -->
<div class="main col-sm-8">
<h1 class="section-title" data-animation-direction="from-bottom" data-animation-delay="50">Recent Properties</h1>
<div class="grid-style1 clearfix">
<div class="item col-md-4" data-animation-direction="from-bottom" data-animation-delay="200">
<div class="image">
<a href="properties-detail.html">
<h3>Luxury Apartment with great views</h3>
<span class="location">Upper East Side, New York</span>
</a>
<img src="http://placehold.it/760x670" alt="" />
</div>
<div class="price">
<i class="fa fa-home"></i>For Sale
<span>$950,000</span>
</div>
<ul class="amenities">
<li><i class="icon-area"></i> 2150 Sq Ft</li>
<li><i class="icon-bedrooms"></i> 4</li>
<li><i class="icon-bathrooms"></i> 3</li>
</ul>
</div>
<div class="item col-md-4" data-animation-direction="from-bottom" data-animation-delay="400">
<div class="image">
<a href="properties-detail.html">
<h3>Stunning Villa with 5 bedrooms</h3>
<span class="location">Miami Beach, Florida</span>
</a>
<img src="http://placehold.it/760x670" alt="" />
</div>
<div class="price">
<i class="fa fa-home"></i>For Sale
<span>$1,253,000</span>
</div>
<ul class="amenities">
<li><i class="icon-area"></i> 3470 Sq Ft</li>
<li><i class="icon-bedrooms"></i> 5</li>
<li><i class="icon-bathrooms"></i> 2</li>
</ul>
</div>
<div class="item col-md-4" data-animation-direction="from-bottom" data-animation-delay="600">
<div class="image">
<a href="properties-detail.html">
<h3>Recent construction with 3 bedrooms</h3>
<span class="location">Park Slope, New York</span>
</a>
<img src="http://placehold.it/760x670" alt="" />
</div>
<div class="price">
<i class="fa fa-home"></i>For Sale
<span>$560,000</span>
</div>
<ul class="amenities">
<li><i class="icon-area"></i> 1800 Sq Ft</li>
<li><i class="icon-bedrooms"></i> 3</li>
<li><i class="icon-bathrooms"></i> 2</li>
</ul>
</div>
<div class="item col-md-4" data-animation-direction="from-bottom" data-animation-delay="200">
<div class="image">
<a href="properties-detail.html">
<h3>Modern construction with parking space</h3>
<span class="location">Midtown, New York</span>
</a>
<img src="http://placehold.it/760x670" alt="" />
</div>
<div class="price">
<i class="fa fa-home"></i>For Rent
<span>$850</span>
</div>
<ul class="amenities">
<li><i class="icon-area"></i> 1300 Sq Ft</li>
<li><i class="icon-bedrooms"></i> 1</li>
<li><i class="icon-bathrooms"></i> 2</li>
</ul>
</div>
<div class="item col-md-4" data-animation-direction="from-bottom" data-animation-delay="400">
<div class="image">
<a href="properties-detail.html">
<h3>Single Family Townhouse</h3>
<span class="location">Cobble Hill, New York</span>
</a>
<img src="http://placehold.it/760x670" alt="" />
</div>
<div class="price">
<i class="fa fa-home"></i>For Sale
<span>$846,000</span>
</div>
<ul class="amenities">
<li><i class="icon-area"></i> 1580 Sq Ft</li>
<li><i class="icon-bedrooms"></i> 2</li>
<li><i class="icon-bathrooms"></i> 2</li>
</ul>
</div>
<div class="item col-md-4" data-animation-direction="from-bottom" data-animation-delay="600">
<div class="image">
<a href="properties-detail.html">
<h3>3 bedroom villa with garage for rent</h3>
<span class="location">Bal Harbour, Florida</span>
</a>
<img src="http://placehold.it/760x670" alt="" />
</div>
<div class="price">
<i class="fa fa-home"></i>For Rent
<span>$1,500</span>
</div>
<ul class="amenities">
<li><i class="icon-area"></i> 2000 Sq Ft</li>
<li><i class="icon-bedrooms"></i> 3</li>
<li><i class="icon-bathrooms"></i> 2</li>
</ul>
</div>
</div>
<h1 class="section-title" data-animation-direction="from-bottom" data-animation-delay="50">Latest News</h1>
<div class="grid-style1">
<div class="item col-md-4" data-animation-direction="from-bottom" data-animation-delay="250">
<div class="image">
<a href="blog-detail.html">
<span class="btn btn-default"><i class="fa fa-file-o"></i> Read More</span>
</a>
<img src="http://placehold.it/766x515" alt="" />
</div>
<div class="tag"><i class="fa fa-file-text"></i></div>
<div class="info-blog">
<ul class="top-info">
<li><i class="fa fa-calendar"></i> July 30, 2014</li>
<li><i class="fa fa-comments-o"></i> 2</li>
<li><i class="fa fa-tags"></i> Properties, Prices, best deals</li>
</ul>
<h3>
<a href="blog-detail.html">How to get your dream property for the best price?</a>
</h3>
<p>Sed rutrum urna id tellus euismod gravida. Praesent placerat, mauris ac pellentesque fringilla, tortor libero condimen.</p>
</div>
</div>
<div class="item col-md-4" data-animation-direction="from-bottom" data-animation-delay="450">
<div class="image">
<a href="blog-detail.html">
<span class="btn btn-default"><i class="fa fa-file-o"></i> Read More</span>
</a>
<img src="http://placehold.it/766x515" alt="" />
</div>
<div class="tag"><i class="fa fa-film"></i></div>
<div class="info-blog">
<ul class="top-info">
<li><i class="fa fa-calendar"></i> July 24, 2014</li>
<li><i class="fa fa-comments-o"></i> 4</li>
<li><i class="fa fa-tags"></i> Tips, Mortgage</li>
</ul>
<h3>
<a href="blog-detail.html">7 tips to get the best mortgage.</a>
</h3>
<p>Sed rutrum urna id tellus euismod gravida. Praesent placerat, mauris ac pellentesque fringilla, tortor libero condimen.</p>
</div>
</div>
<div class="item col-md-4" data-animation-direction="from-bottom" data-animation-delay="650">
<div class="image">
<a href="blog-detail.html">
<span class="btn btn-default"><i class="fa fa-file-o"></i> Read More</span>
</a>
<img src="http://placehold.it/766x515" alt="" />
</div>
<div class="tag"><i class="fa fa-file-text"></i></div>
<div class="info-blog">
<ul class="top-info">
<li><i class="fa fa-calendar"></i> July 05, 2014</li>
<li><i class="fa fa-comments-o"></i> 1</li>
<li><i class="fa fa-tags"></i> Location, Price, House</li>
</ul>
<h3>
<a href="blog-detail.html">House, location or price: What's the most important factor?</a>
</h3>
<p>Sed rutrum urna id tellus euismod gravida. Praesent placerat, mauris ac pellentesque fringilla, tortor libero condimen.</p>
</div>
</div>
</div>
<div class="center"><a href="blog-listing1.html" class="btn btn-default-color" data-animation-direction="from-bottom" data-animation-delay="850">View All News</a></div>
</div>
<!-- END MAIN CONTENT -->
<!-- BEGIN SIDEBAR -->
<div class="sidebar col-sm-4">
<!-- BEGIN SIDEBAR ABOUT -->
<div class="col-sm-12">
<h2 class="section-title" data-animation-direction="from-bottom" data-animation-delay="50">About Us</h2>
<p class="center" data-animation-direction="from-bottom" data-animation-delay="200">
Aliquam faucibus elit sed tempus molestie, aenean sodales venenatis.
<strong>Vestibulum pulvinar</strong> arcu suscipit, volutpat velit nec, euismod nibh vestibulum ut
sodales lacus, eget mattis arcu. Curabitur quis augue magna.
<a href="about.html">Learn More</a>
</p>
</div>
<!-- END SIDEBAR ABOUT -->
<!-- BEGIN SIDEBAR AGENTS -->
<div class="col-sm-12">
<h2 class="section-title" data-animation-direction="from-bottom" data-animation-delay="50">Our Agents</h2>
<ul class="agency-detail-agents">
<li class="col-lg-12" data-animation-direction="from-bottom" data-animation-delay="200">
<a href="agent-detail.html"><img src="http://placehold.it/307x307" alt="" /></a>
<div class="info">
<a href="agent-detail.html"><h3><NAME></h3></a>
<span class="location">Manhattan, New York</span>
<p>Curabitur quis augue magna volutpat velit nec, euismod nibh vestibulum.</p>
<a href="agent-detail.html">Learn More »</a>
</div>
</li>
<li class="col-lg-12" data-animation-direction="from-bottom" data-animation-delay="400">
<a href="agent-detail.html"><img src="http://placehold.it/307x307" alt="" /></a>
<div class="info">
<a href="agent-detail.html"><h3><NAME></h3></a>
<span class="location">Miami, Florida</span>
<p>Curabitur quis augue magna volutpat velit nec, euismod nibh vestibulum.</p>
<a href="agent-detail.html">Learn More »</a>
</div>
</li>
<li class="col-lg-12" data-animation-direction="from-bottom" data-animation-delay="600">
<a href="agent-detail.html"><img src="http://placehold.it/307x307" alt="" /></a>
<div class="info">
<a href="agent-detail.html"><h3><NAME></h3></a>
<span class="location">Beverly Hills, California</span>
<p>Curabitur quis augue magna volutpat velit nec, euismod nibh vestibulum.</p>
<a href="agent-detail.html">Learn More »</a>
</div>
</li>
</ul>
</div>
<!-- END SIDEBAR AGENTS -->
<!-- BEGIN AGENCIES -->
<div id="agencies" class="col-sm-12" data-animation-direction="fade" data-animation-delay="250">
<h2 class="section-title">Our Agencies</h2>
<div class="mapborder">
<div id="map_agency" class="gmap"></div>
</div>
<select id="agency" name="agency" data-placeholder="Choose an agency">
<option value=""> </option>
<!-- The list of agencies will be automatically created.
Set the list of agencies in the file js/agencies.js -->
</select>
</div>
<!-- END AGENCIES -->
</div>
<!-- END SIDEBAR -->
</div>
</div>
</div>
<!-- END CONTENT WRAPPER -->
<!-- BEGIN TESTIMONIALS -->
<div class="parallax dark-bg" style="background-image:url(http://placehold.it/1920x800);" data-stellar-background-ratio="0.5">
<div class="container">
<div class="row">
<div class="col-sm-12" data-animation-direction="from-top" data-animation-delay="50">
<h2 class="section-title">Testimonials</h2>
<div id="testimonials-slider" class="owl-carousel testimonials">
<div class="item">
<blockquote class="text">
<p>Lorem ipsum dolor sit amet consectetur adipiscing elit. Pellentesque elementum libero enim, eget gravida nunc laoreet et. Nullam ac enim auctor, fringilla risus at, imperdiet turpis.</p>
</blockquote>
<div class="col-md-5 center">
<div class="author">
<img src="http://placehold.it/61x61" alt="" />
<div>
<NAME><br>
<span>CEO at Lorem Ipsum Agency</span>
</div>
</div>
</div>
</div>
<div class="item">
<blockquote class="text">
<p>Pellentesque elementum libero enim, eget gravida nunc laoreet et. Nullam ac enim auctor, fringilla risus at, imperdiet turpis.</p>
</blockquote>
<div class="col-md-5 center">
<div class="author">
<img src="http://placehold.it/61x61" alt="" />
<div>
<NAME><br>
<span>CTO at Dolor Sit Amet Agency</span>
</div>
</div>
</div>
</div>
<div class="item">
<blockquote class="text">
<p>Lorem ipsum dolor sit amet consectetur adipiscing elit. Pellentesque elementum libero enim, eget gravida nunc laoreet et. Nullam ac enim auctor, fringilla risus at, imperdiet turpis. Nullam ac enim auctor, fringilla risus at, imperdiet turpis.</p>
</blockquote>
<div class="col-md-5 center">
<div class="author">
<img src="http://placehold.it/61x61" alt="" />
<div>
<NAME><br>
<span>UFO at Some Agency</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END TESTIMONIALS --><file_sep>/frontend/views/layouts/main.php
<?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use yii\helpers\Url;
use frontend\assets\AppAsset;
use common\widgets\Alert;
AppAsset::register($this);
$appAsset = new AppAsset();
$baseUrl = $appAsset->baseUrl;
$basePath = $appAsset->basePath;
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<!-- Page Title -->
<title><?= Html::encode($this->title) ?></title>
<meta name="keywords" content="real estate, responsive, retina ready, modern html5 template, bootstrap, css3" />
<meta name="description" content="Cozy - Responsive Real Estate HTML5 Template" />
<meta name="author" content="<NAME>, giá rẻ đẹp" />
<!-- Mobile Meta Tag -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Fav and touch icons -->
<link rel="shortcut icon" type="image/x-icon" href="<?=$baseUrl?>/images/fav_touch_icons/favicon.ico" />
<link rel="apple-touch-icon" href="<?=$baseUrl?>/images/fav_touch_icons/apple-touch-icon.png" />
<link rel="apple-touch-icon" sizes="72x72" href="<?=$baseUrl?>/images/fav_touch_icons/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="114x114" href="<?=$baseUrl?>/images/fav_touch_icons/apple-touch-icon-114x114.png" />
<!-- IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Google Web Font -->
<link href="http://fonts.googleapis.com/css?family=Raleway:300,500,900%7COpen+Sans:400,700,400italic" rel="stylesheet" type="text/css" />
<?= Html::csrfMetaTags() ?>
<!-- Revolution Slider CSS settings -->
<link rel="stylesheet" type="text/css" href="<?=$baseUrl?>/rs-plugin/css/settings.css" media="screen" />
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<!-- BEGIN WRAPPER -->
<div id="wrapper">
<!-- BEGIN HEADER -->
<header id="header">
<div id="top-bar">
<div class="container">
<div class="row">
<div class="col-sm-12">
<ul id="top-info">
<li>Phone: 800-123-4567</li>
<li>Email: <a href="mailto:<EMAIL>"><EMAIL></a></li>
</ul>
<ul id="top-buttons">
<li><a href="#"><i class="fa fa-sign-in"></i> Login</a></li>
<li><a href="#"><i class="fa fa-pencil-square-o"></i> Register</a></li>
<li class="divider"></li>
<li>
<div class="language-switcher">
<span><i class="fa fa-globe"></i> English</span>
<ul>
<li><a href="#">Deutsch</a></li>
<li><a href="#">Español</a></li>
<li><a href="#">Français</a></li>
<li><a href="#">Português</a></li>
</ul>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<div id="nav-section">
<div class="container">
<div class="row">
<div class="col-sm-12">
<a href="<?=Yii::$app->homeUrl?>" class="nav-logo"><img src="images/logo.png" alt="Cozy Logo" /></a>
<!-- BEGIN SEARCH -->
<div id="sb-search" class="sb-search">
<form>
<input class="sb-search-input" placeholder="Search..." type="text" value="" name="search" id="search">
<input class="sb-search-submit" type="submit" value="">
<i class="fa fa-search sb-icon-search"></i>
</form>
</div>
<!-- END SEARCH -->
<!-- BEGIN MAIN MENU -->
<nav class="navbar">
<button id="nav-mobile-btn"><i class="fa fa-bars"></i></button>
<ul class="nav navbar-nav">
<li class="dropdown">
<a class="active" href="<?=Yii::$app->homeUrl?>">Home</a>
</li>
<li class="dropdown">
<a href="#" data-toggle="dropdown" data-hover="dropdown">Properties<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="properties-detail.html">Properties Detail</a></li>
<li><a href="properties-list.html">Properties List</a></li>
<li><a href="properties-grid.html">Properties Grid</a></li>
<li><a href="properties-grid2.html">Properties Grid 2</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" data-toggle="dropdown" data-hover="dropdown">Pages<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="about.html">About Us</a></li>
<li class="dropdown-submenu">
<a href="#">Agency</a>
<ul class="dropdown-menu">
<li><a href="agency-detail.html">Agency Detail</a></li>
<li><a href="agency-listing.html">Agency Listing</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="#">Agent</a>
<ul class="dropdown-menu">
<li><a href="agent-detail.html">Agent Detail</a></li>
<li><a href="agent-listing.html">Agent Listing</a></li>
</ul>
</li>
<li><a href="pricing-tables.html">Pricing Tables</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="register.html">Register</a></li>
<li><a href="faq.html">FAQ</a></li>
<li><a href="404.html">404</a></li>
<li class="divider"></li>
<li><a tabindex="-1" href="#"> Separated link </a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" data-toggle="dropdown" data-hover="dropdown">Blog<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="blog-detail.html">Blog Detail</a></li>
<li><a href="blog-listing1.html">Blog Listing 1</a></li>
<li><a href="blog-listing2.html">Blog Listing 2</a></li>
<li><a href="blog-listing3.html">Blog Listing 3</a></li>
<li><a href="blog-listing4.html">Blog Listing 4</a></li>
</ul>
</li>
<li><a href="<?=Url::to(['/site/contact'])?>">Contacts</a></li>
</ul>
</nav>
<!-- END MAIN MENU -->
</div>
</div>
</div>
</div>
</header>
<!-- END HEADER -->
<div class="wrap_content">
<?php
// NavBar::begin([
// 'brandLabel' => 'My Company',
// 'brandUrl' => Yii::$app->homeUrl,
// 'options' => [
// 'class' => 'navbar-inverse navbar-fixed-top',
// ],
// ]);
// $menuItems = [
// ['label' => 'Home', 'url' => ['/site/index']],
// ['label' => 'About', 'url' => ['/site/about']],
// ['label' => 'Contact', 'url' => ['/site/contact']],
// ];
// if (Yii::$app->user->isGuest) {
// $menuItems[] = ['label' => 'Signup', 'url' => ['/site/signup']];
// $menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
// } else {
// $menuItems[] = '<li>'
// . Html::beginForm(['/site/logout'], 'post')
// . Html::submitButton(
// 'Logout (' . Yii::$app->user->identity->username . ')',
// ['class' => 'btn btn-link']
// )
// . Html::endForm()
// . '</li>';
// }
// echo Nav::widget([
// 'options' => ['class' => 'navbar-nav navbar-right'],
// 'items' => $menuItems,
// ]);
// NavBar::end();
?>
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?//= Alert::widget() ?>
<?= $content ?>
</div>
<!-- BEGIN FOOTER -->
<footer id="footer">
<div id="footer-top" class="container">
<div class="row">
<div class="block col-sm-3">
<a href="index.html"><img src="images/logo.png" alt="Cozy Logo" /></a>
<br><br>
<p>Cozy is a simple clean and modern HTML template designed for Real Estate business. This template has a lot of useful features and it's highly customizable so you can turn it into your own awesome website.</p>
</div>
<div class="block col-sm-3">
<h3>Contact Info</h3>
<ul class="footer-contacts">
<li><i class="fa fa-map-marker"></i> 24th Street, New York, USA</li>
<li><i class="fa fa-phone"></i> 00351 123 456 789</li>
<li><i class="fa fa-envelope"></i> <a href="mailto:<EMAIL>"><EMAIL></a></li>
</ul>
</div>
<div class="block col-sm-3">
<h3>Helpful Links</h3>
<ul class="footer-links">
<li><a href="properties-list.html">All Properties Available</a></li>
<li><a href="agent-listing.html">Look for an Agent</a></li>
<li><a href="agency-listing.html">Look for an Agency</a></li>
<li><a href="pricing-tables.html">See our Pricing Tables</a></li>
</ul>
</div>
<div class="block col-sm-3">
<h3>Latest Listings</h3>
<ul class="footer-listings">
<li>
<div class="image">
<a href="properties-detail.html"><img src="http://placehold.it/760x670" alt="" /></a>
</div>
<p><a href="properties-detail.html">Luxury Apartment with great views<span>+</span></a></p>
</li>
<li>
<div class="image">
<a href="properties-detail.html"><img src="http://placehold.it/760x670" alt="" /></a>
</div>
<p><a href="properties-detail.html">Stunning Villa with 5 bedrooms<span>+</span></a></p>
</li>
<li>
<div class="image">
<a href="properties-detail.html"><img src="http://placehold.it/760x670" alt="" /></a>
</div>
<p><a href="properties-detail.html">Recent construction with 3 bedrooms.<span>+</span></a></p>
</li>
</ul>
</div>
</div>
</div>
<!-- BEGIN COPYRIGHT -->
<div id="copyright">
<div class="container">
<div class="row">
<div class="col-sm-12">
© Fisall <?= date('Y') ?> - All rights reserved. Developed by <a href="http://www.toilamit.com" target="_blank">toilamit</a>
<!-- BEGIN SOCIAL NETWORKS -->
<ul class="social-networks">
<li><a href="#"><i class="fa fa-facebook"></i></a></li>
<li><a href="#"><i class="fa fa-twitter"></i></a></li>
<li><a href="#"><i class="fa fa-google"></i></a></li>
<li><a href="#"><i class="fa fa-pinterest"></i></a></li>
<li><a href="#"><i class="fa fa-youtube"></i></a></li>
<li><a href="#"><i class="fa fa-rss"></i></a></li>
</ul>
<!-- END SOCIAL NETWORKS -->
</div>
</div>
</div>
</div>
<!-- END COPYRIGHT -->
</footer>
<!-- END FOOTER -->
</div>
<!-- END WRAPPER -->
<!-- Libs -->
<script src="js/common.js"></script>
<script src="js/owl.carousel.min.js"></script>
<script src="js/chosen.jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="js/infobox.min.js"></script>
<!-- jQuery Revolution Slider -->
<script type="text/javascript" src="rs-plugin/js/jquery.themepunch.tools.min.js"></script>
<script type="text/javascript" src="rs-plugin/js/jquery.themepunch.revolution.min.js"></script>
<!-- Template Scripts -->
<script src="js/variables.js"></script>
<script src="js/scripts.js"></script>
<!-- Agencies list -->
<script src="js/agencies.js"></script>
<script type="text/javascript">
(function($){
"use strict";
$(document).ready(function(){
//Create agencies map with markers and populate dropdown agencies list.
Cozy.agencyMap(agencies, "map_agency");
});
})(jQuery);
</script>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
|
ac489351b8659cbe405b4065975ef2b0e1b31deb
|
[
"PHP"
] | 3 |
PHP
|
httvhutceoscop/yii2cozy
|
55a50c58aa6b910e8afbae73e15cae67cf667a9c
|
07c34c2c85efc26b73641b6265b6ef7dc4ab3adc
|
refs/heads/master
|
<repo_name>CesarDuvanCabraCoy/ProyectoBibliotecaOptima<file_sep>/src/utils/Utils.java
package utils;
import java.awt.Container;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
public class Utils {
public static void generateBasicGrid(Container comp, int quantityColumns, GridBagConstraints gbc){
gbc.weightx = 1;
for (int i = 0; i < quantityColumns; i++) {
gbc.gridx = i;
comp.add(new JLabel(""), gbc);
}
}
public static void generateBasicLabelsPCs(Container comp, int quantityRows, GridBagConstraints gbc) {
gbc.weighty = 10;
gbc.fill = GridBagConstraints.BOTH;
for (int i = 0; i < quantityRows; i++) {
gbc.weighty= 100;
gbc.gridy = i;
comp.add(new JLabel("A"), gbc);
System.out.println("El hijo de puta i: " + i);
}
}
}
<file_sep>/src/views/JTBMain.java
package views;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JToolBar;
import controllers.JBActions;
import controllers.MainController;
public class JTBMain extends JToolBar{
private static final long serialVersionUID = 1L;
private MainController mainController;
private JButton jbStatistics;
public JTBMain(MainController mainController) {
this.mainController = mainController;
this.setBackground(Color.decode("#44adf5"));
this.setFloatable(false);
this.setRollover(true);
init();
}
private void init() {
this.addSeparator();
addButton(jbStatistics, ConstantsGUI.URL_IMAGE_STATISTICS, JBActions.SHOW_STATISTICS, ConstantsGUI.TT_JB_STATISTICS, true);
}
private void addButton(JButton jb, String urlImage, JBActions command, String toolTip, boolean enabled) {
jb = new JButton(new ImageIcon(getClass().getResource(urlImage)));
jb.setEnabled(enabled);
jb.addActionListener(mainController);
jb.setActionCommand(command.toString());
jb.setToolTipText(toolTip);
this.add(jb);
}
}<file_sep>/src/controllers/MainController.java
package controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JSlider;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import models.ManagerLibrary;
import views.JBoardStadisticas;
import views.MainWindow;
public class MainController implements ActionListener, ChangeListener{
private MainWindow mainWindow;
private ManagerLibrary managerLibrary;
private JBoardStadisticas boardStadisticas;
private Timer timerStudents;
private boolean playing;
public MainController() {
managerLibrary = new ManagerLibrary();
this.mainWindow = new MainWindow(this);
boardStadisticas = new JBoardStadisticas();
mainWindow.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event) {
switch (JBActions.valueOf(event.getActionCommand())) {
case PLAY_SIMULATION:
playSimulation();
break;
default:
break;
}
}
private void playSimulation() {
int pcs = mainWindow.getQuantityPcs();
int maxTimeService = mainWindow.getMaxTimeService();
int numberOfDays = mainWindow.getNumberOfDays();
managerLibrary.playSimulation(pcs, maxTimeService, numberOfDays);
mainWindow.updateBoard(managerLibrary.getComputers());
mainWindow.disableButtonInitSim();
playing = true;
managerLibrary.start();
paintBoard();
generateStudents();
}
private void paintBoard() {
SwingWorker<Void, Void> refreshBoard = new SwingWorker<Void, Void>(){
@Override
protected Void doInBackground() throws Exception {
while (playing) {
mainWindow.updateBoard(managerLibrary.getComputers());
mainWindow.setValueStudentsAttended(managerLibrary.getAllStudents().size());
mainWindow.setValueCurrentDay(managerLibrary.getNumberCurrentDay());
Thread.sleep(20);
}
return null;
}
};
refreshBoard.execute();
}
private void validateNumberDays() {
int students= 0;
if (managerLibrary.getNumberCurrentDay() == managerLibrary.getNumberOfDays()) {
playing = false;
managerLibrary.stop();
students=managerLibrary.getAllStudents().size()/managerLibrary.getNumberOfDays();
boardStadisticas.paintStadistics(students, 121, 12, 12);
}else {
managerLibrary.initNewDay();
//boardStadisticas.paintStadistics(students, 121, 12, 12);
}
}
private void generateStudents() {
timerStudents = new Timer(((int)(Math.random() * 700) + 70), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (playing) {
managerLibrary.generateStudents();
if (managerLibrary.getCurrentDayStudents().size() >= managerLibrary.getNumberMaxStudentsByDay()) {
try {
validateNumberDays();
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
});
timerStudents.start();
}
@Override
public void stateChanged(ChangeEvent e) {
switch (JSActions.valueOf(((JSlider)(e.getSource())).getName())) {
case DAYS:
System.out.println("Modificaci�n de hora");
mainWindow.setValueDays();
break;
case PCS:
System.out.println("Modificaci�n de pcs");
mainWindow.setValuePCs();
break;
case SERVICE_TIME:
System.out.println("Modificaci�n de service");
mainWindow.setValueServiceTime();
break;
default:
break;
}
}
}
<file_sep>/src/models/ComputerState.java
package models;
public enum ComputerState {
FREE, OCCUPIED, DAMAGED
}
<file_sep>/src/views/JPBoard.java
package views;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import models.Computer;
public class JPBoard extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
private ArrayList<Computer> computers;
public JPBoard() {
computers = new ArrayList<Computer>();
this.setBackground(Color.WHITE);
this.setLayout(new GridLayout(20, 1));
}
public void updateBoard(ArrayList<Computer> computers) {
this.computers = computers;
this.repaint();
}
private void drawComputer(Computer com, int x, int y, Graphics g) {
g.drawImage(new ImageIcon(getClass().getResource(ConstantsGUI.URL_PC)).getImage(), x, y, this);
defineColorStatePC(com, g);
g.fillRect(x+30, y, 10, 10);
g.setColor(Color.BLACK);
g.drawString("Id: " + com.getId(), x, y +50);
}
private void defineColorStatePC(Computer com, Graphics g) {
switch (com.getComputerState()) {
case FREE:
g.setColor(Color.decode("#25ec0e"));
break;
case DAMAGED:
g.setColor(Color.RED);
break;
case OCCUPIED:
g.setColor(Color.BLUE);
break;
default:
break;
}
}
private void paintBoard(Graphics g) {
int x = 20;
int y = 30;
for (int i = 0; i < computers.size(); i++) {
drawComputer(computers.get(i), x, y, g);
if (x <= (this.getWidth() - 130)) {
x+=120;
}
else{
y+=100;
x = 20;
}
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
paintBoard(g);
}
}
<file_sep>/src/controllers/JSActions.java
package controllers;
public enum JSActions {
PCS, SERVICE_TIME, DAYS
}
<file_sep>/src/views/MainWindow.java
package views;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import controllers.MainController;
import models.Computer;
public class MainWindow extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JPMain jpMain;
private JTBMain jtbMain;
private MainController mainController;
public MainWindow(MainController mainController) {
this.mainController = mainController;
this.setTitle(ConstantsGUI.TITLE_JF_MAIN);
this.setExtendedState(MAXIMIZED_BOTH);
this.setIconImage(new ImageIcon(getClass().getResource(ConstantsGUI.URL_IMAGE_ICON)).getImage());
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.setMinimumSize(new Dimension(700, 900));
init();
this.setVisible(true);
}
private void init() {
jtbMain = new JTBMain(mainController);
this.add(jtbMain, BorderLayout.NORTH);
jpMain = new JPMain(mainController);
this.add(jpMain);
}
public void updateBoard(ArrayList<Computer> computers) {
jpMain.updateBoard(computers);
this.repaint();
this.revalidate();
}
public int getQuantityPcs() {
return jpMain.getQuantityPcs();
}
public void setValueDays() {
jpMain.setValueDays();
}
public void setValuePCs() {
jpMain.setValuePCs();
}
public void setValueServiceTime() {
jpMain.setValueServiceTime();
}
public void disableButtonInitSim() {
jpMain.disableButtonInitSim();
}
public int getMaxTimeService() {
return jpMain.getMaxTimeService();
}
public void setValueCurrentDay(int currentDay) {
jpMain.setValueCurrentDay(currentDay);
}
public int getNumberOfDays() {
return jpMain.getNumberOfDays();
}
public void setValueStudentsAttended(int students) {
jpMain.setValueStudentsAttended(students);
}
}
<file_sep>/src/models/Computer.java
package models;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class Computer {
private int id;
private int quantityStudents;
private int quantityTimesRequested;
private ComputerState computerState;
private long serviceTime;
private Student currentStudent;
public Computer(int id, int quantityStudents,ComputerState computerState) {
this.id = id;
this.quantityStudents = quantityStudents;
this.quantityTimesRequested = 0;
this.computerState = computerState;
this.serviceTime = 0;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getQuantityStudents() {
return quantityStudents;
}
public void setQuantityStudents(int quantityStudents) {
this.quantityStudents = quantityStudents;
}
public int getQuantityTimesRequested() {
return quantityTimesRequested;
}
public void setQuantityTimesRequested(int quantityTimesRequested) {
this.quantityTimesRequested = quantityTimesRequested;
}
public ComputerState getComputerState() {
return computerState;
}
public void setComputerState(ComputerState computerState) {
this.computerState = computerState;
}
public long getServiceTime() {
return serviceTime;
}
public void setServiceTime(long serviceTime) {
this.serviceTime = serviceTime;
}
public Student getCurrentStudent() {
return currentStudent;
}
public void setCurrentStudent(Student currentStudent) {
this.currentStudent = currentStudent;
this.computerState=ComputerState.OCCUPIED;
quantityTimesRequested++;
serviceTime+=currentStudent.getConsumptionTime();
occupy();
}
private void occupy() {
Timer timer = new Timer(600 * currentStudent.getConsumptionTime(), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
unSetStudent();
}
});
timer.start();
}
public void unSetStudent() {
this.currentStudent = null;
this.computerState=defineState();
}
private ComputerState defineState() {
int ran = (int) (Math.random() * 100);
System.out.println();
ComputerState state = null;
if (ran <= 90) {
state =ComputerState.FREE;
}
if (ran > 90){
state= ComputerState.DAMAGED;
}
return state;
}
@Override
public String toString() {
return "Computer [id=" + id + ", quantityStudents=" + quantityStudents + ", quantityTimesRequested="
+ quantityTimesRequested + ", computerState=" + computerState + ", serviceTime=" + serviceTime + "]";
}
}
|
94492efcd42586b5f8451100bd67fbd3483bc014
|
[
"Java"
] | 8 |
Java
|
CesarDuvanCabraCoy/ProyectoBibliotecaOptima
|
8f451658ad0a547bf2c350ef875b21e14d04d01f
|
564e17194936693fc14487ed9d287de83007dce4
|
refs/heads/master
|
<file_sep>import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home/Home.vue';
import Login from '../views/Login/Login.vue';
import Registrate from '../views/Registrate/Registrate.vue';
import NewEvent from '../views/NewEvent/NewEvent.vue';
import User from '../views/User/User.vue';
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/login',
name: 'Login',
component: Login,
meta: { loggedIn: true }
},
{
path: '/registrate',
name: 'Registrate',
component: Registrate,
meta: { loggedIn: true }
},
{
path: '/newevent',
name: 'NewEvent',
component: NewEvent,
meta: { guest: true }
},
{
path: '/user',
name: 'User',
component: User,
meta: { guest: true }
}
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.loggedIn)) {
if (localStorage.getItem('token')) {
next('/user');
} else {
next();
}
} else if (to.matched.some(record => record.meta.guest)) {
if (localStorage.getItem('token') == null) {
next('/login');
} else {
next();
}
} else {
next();
}
});
export default router;
<file_sep>// Utilities
import { mount, createLocalVue } from '@vue/test-utils';
// Libraries
import Vue from 'vue';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';
// Components
import StatusMessage from '@/components/StatusMessage/StatusMessage.vue';
const localVue = createLocalVue();
localVue.use(Vuex, VueRouter);
describe('StatusMessage component', () => {
let vuetify;
beforeEach(() => {
Vue.use(Vuetify);
vuetify = new Vuetify();
});
test('test if Foter is rendered', () => {
const store = new Vuex.Store({
state: { statusMessage: 'warning' },
getters: {
statusMessage: state => state.statusMessage
}
});
// Arrange;
const wrapper = mount(StatusMessage, {
localVue,
vuetify,
store
});
// Assert
const statusMessageText = wrapper.find('#statusMessageText');
expect(statusMessageText.text()).toBe('warning');
});
});
<file_sep>// Utilities
import { mount, createLocalVue } from '@vue/test-utils';
// Libraries
import Vue from 'vue';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';
// Components
import User from '@/views/User/User.vue';
const localVue = createLocalVue();
localVue.use(Vuex, VueRouter);
jest.mock('vuex-map-fields', () => ({
mapFields: jest.fn()
}));
describe('/user', () => {
const store = new Vuex.Store({
state: {
user: { username: 'Artur', name: 'artur', email: '<EMAIL>' }
},
getters: {
user: state => state.user
}
});
let vuetify;
beforeEach(() => {
Vue.use(Vuetify);
vuetify = new Vuetify();
});
test('Test if User is rendered', () => {
// Arrange;
const wrapper = mount(User, {
localVue,
vuetify,
store
});
// Assert
expect(wrapper.element).toMatchSnapshot();
});
test('Test if user information is displayed', () => {
// Arrange;
const wrapper = mount(User, {
localVue,
vuetify,
store
});
const userName = wrapper.find('#userName');
const name = wrapper.find('#name');
const email = wrapper.find('#email');
expect(userName.text()).toBe('Artur');
expect(name.text()).toBe('artur');
expect(email.text()).toBe('<EMAIL>');
});
});
<file_sep>// Utilities
import { mount, createLocalVue } from '@vue/test-utils';
import { getField, updateField } from 'vuex-map-fields';
import store from '@/store/index.js';
// Libraries
import Vue from 'vue';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';
// Components
import Registrate from '@/views/Registrate/Registrate.vue';
const localVue = createLocalVue();
localVue.use(Vuex, VueRouter);
describe('/registrate', () => {
let vuetify;
beforeEach(() => {
Vue.use(Vuetify);
vuetify = new Vuetify();
});
test('Test if Registrate is rendered', () => {
// Arrange;
const wrapper = mount(Registrate, {
localVue,
vuetify,
store
});
// Assert
expect(wrapper.element).toMatchSnapshot();
});
test('It should pass data to state.newEvent', async () => {
// Arrange;
const store = new Vuex.Store({
state: {
newUser: {
name: '',
username: '',
email: '',
password: '',
verifypassword: ''
}
},
mutations: { updateField },
getters: { getField }
});
const wrapper = mount(Registrate, {
localVue,
vuetify,
store
});
const inputUserName = wrapper.find('#inputUserName');
const inputName = wrapper.find('#inputName');
const inputEmail = wrapper.find('#inputEmail');
const inputPassword = wrapper.find('#inputPassword');
const inputVerifypassword = wrapper.find('#inputVerifypassword');
inputUserName.setValue('Artur');
inputName.setValue('Stockholm');
inputEmail.setValue('Its always cool to have a cape');
inputPassword.setValue('<PASSWORD>');
inputVerifypassword.setValue('<PASSWORD>');
await wrapper.vm.$nextTick();
expect(store.state.newUser.username).toBe(inputUserName.element.value);
expect(store.state.newUser.name).toBe(inputName.element.value);
expect(store.state.newUser.email).toBe(inputEmail.element.value);
expect(store.state.newUser.password).toBe(inputPassword.element.value);
expect(store.state.newUser.verifypassword).toBe(
inputVerifypassword.element.value
);
});
});
<file_sep>// Utilities
import { mount, createLocalVue } from '@vue/test-utils';
// Libraries
import Vue from 'vue';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';
// Components
import EventContainer from '@/components/Events/EventContainer/EventContainer.vue';
const localVue = createLocalVue();
localVue.use(Vuex, VueRouter);
describe('EventContainer component', () => {
let vuetify;
beforeEach(() => {
Vue.use(Vuetify);
vuetify = new Vuetify();
});
const store = new Vuex.Store({
state: { user: 'Artur' },
getters: {
isLoggedIn: state => state.token,
user: state => state.user
}
});
const event = {
participant: ['Lova', 'Marja', 'Artur'],
likes: ['Marja', 'Artur'],
comments: [],
_id: '5f6e59d2e426280017acbf20',
name: 'Nutcracker',
place: 'Dramaten Stockholm',
date: '2020-11-19',
typeOfEvent: 'Ballet',
createdBy: 'Artur',
description: 'Se the classical Ballet by <NAME>',
__v: 0
};
test('test if props value is displayed', async () => {
const wrapper = mount(EventContainer, {
localVue,
vuetify,
store,
propsData: { event }
});
const eventType = wrapper.find('#typeOfEvent');
const nameOfEvent = wrapper.find('#eventName');
const eventPlaceDate = wrapper.find('#eventPlaceDate');
const eventDescription = wrapper.find('#eventDescription');
const ineventCreatedByput = wrapper.find('#eventCreatedBy');
expect(eventType.text()).toContain(event.typeOfEvent);
expect(nameOfEvent.text()).toContain(event.name);
expect(eventPlaceDate.text()).toContain(event.place);
expect(eventDescription.text()).toContain(event.description);
expect(ineventCreatedByput.text()).toContain(event.createdBy);
});
test('test if like icons & badge is toggled when v-if is true/false', async () => {
const store = new Vuex.Store({
state: { user: 'Artur' },
getters: {
isLoggedIn: state => state.token,
user: state => state.user
}
});
const wrapper = mount(EventContainer, {
localVue,
vuetify,
store,
propsData: { event }
});
const badgeLikeTrueUser = wrapper.find('#badgeLikeTrueUser');
const badgeLikeFalseUser = wrapper.find('#badgeLikeFalseUser');
expect(badgeLikeTrueUser.exists()).toBe(true);
expect(badgeLikeFalseUser.exists()).toBe(false);
});
test('test if participant icons & badge is toggled when v-if is true/false', async () => {
const store = new Vuex.Store({
state: { user: 'Artur' },
getters: {
isLoggedIn: state => state.token,
user: state => state.user
}
});
const wrapper = mount(EventContainer, {
localVue,
vuetify,
store,
propsData: { event }
});
const badgeAttendingTrueUser = wrapper.find('#badgeAttendingTrueUser');
const badgeAttendingfalseUser = wrapper.find('#badgeAttendingfalseUser');
expect(badgeAttendingTrueUser.exists()).toBe(true);
expect(badgeAttendingfalseUser.exists()).toBe(false);
});
});
<file_sep>import { updateField } from 'vuex-map-fields';
//*************************/
//*** GLOBAL MUTATIONS ***/
//***********************/
const mutations = {
updateField,
allEvents(state, events) {
state.allEvents = events;
state.filterEvents = events;
console.log(state.allEvents);
},
changeTokenState(state, token) {
state.token = token;
state.errorMessage = null;
console.log(state.token, 'Change token state');
console.log(localStorage.getItem('token'), 'show localstorage');
},
changeUserState(state, user) {
state.user = user;
state.newEvent.createdBy = user.username;
},
statusMessage(state, response) {
state.statusMessage = response;
},
filterEventMutation(state) {
const filterEventTag = state.filterEventTag;
const filterEvent = state.filterEvents;
let foundEvents = [];
foundEvents = filterEvent.filter(item =>
item.typeOfEvent.match(filterEventTag)
);
state.allEvents = foundEvents;
},
resetFilter(state) {
state.allEvents = state.filterEvents;
}
};
export default mutations;
<file_sep>// Utilities
import { mount, createLocalVue } from '@vue/test-utils';
// Libraries
import Vue from 'vue';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';
// Components
import Carousel from '@/components/Carousel/Carousel.vue';
const localVue = createLocalVue();
localVue.use(Vuex, VueRouter);
describe('Carousel component', () => {
let vuetify;
beforeEach(() => {
Vue.use(Vuetify);
vuetify = new Vuetify();
});
test('test if Carousel item is there and is displayed is rendered', () => {
// Arrange;
const wrapper = mount(Carousel, {
localVue,
vuetify
});
// //Act
const container = wrapper.find('.v-carousel');
const textContent = container.text('');
// Assert
expect(textContent).toBe('Creativity');
});
});
<file_sep>// Utilities
import { mount, createLocalVue } from '@vue/test-utils';
// Libraries
import Vue from 'vue';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';
// Components
import Logout from '@/components/Header/Logout/Logout.vue';
const localVue = createLocalVue();
localVue.use(Vuex, VueRouter);
describe('Logout component', () => {
let vuetify;
beforeEach(() => {
Vue.use(Vuetify);
vuetify = new Vuetify();
});
test('test if loggout is exist when logged in', async () => {
const store = new Vuex.Store({
state: { token: true },
getters: {
isLoggedIn: state => state.token
}
});
const wrapper = mount(Logout, {
localVue,
vuetify,
store
});
const logoutLink = wrapper.find('#logoutLink');
expect(logoutLink.exists()).toBe(true);
});
test('It should activate logOut on click', () => {
const actions = {
logOut: jest.fn()
};
const store = new Vuex.Store({
state: { token: true },
getters: {
isLoggedIn: state => state.token
},
actions
});
// Arrange;
const wrapper = mount(Logout, {
localVue,
vuetify,
store
});
const button = wrapper.find('#logoutLink');
wrapper.vm.$on('logOut');
expect(actions.logOut).toHaveBeenCalledTimes(0);
button.trigger('click');
expect(actions.logOut).toHaveBeenCalledTimes(1);
});
});
<file_sep>// Utilities
import { mount, createLocalVue } from '@vue/test-utils';
import { getField, updateField } from 'vuex-map-fields';
import store from '@/store/index.js';
// Libraries
import Vue from 'vue';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';
// Components
import Login from '@/views/Login/Login.vue';
const localVue = createLocalVue();
localVue.use(Vuex, VueRouter);
describe('/login', () => {
let vuetify;
beforeEach(() => {
Vue.use(Vuetify);
vuetify = new Vuetify();
});
test('Test if Login is rendered', () => {
// Arrange;
const wrapper = mount(Login, {
localVue,
vuetify,
store
});
// Assert
expect(wrapper.element).toMatchSnapshot();
});
test('It should activate login on click', () => {
const actions = {
login: jest.fn()
};
const store = new Vuex.Store({
state: {
login: {
username: '',
password: ''
}
},
actions,
mutations: { updateField },
getters: { getField }
});
// Arrange;
const wrapper = mount(Login, {
localVue,
vuetify,
store
});
const button = wrapper.find('.v-btn');
wrapper.vm.$on('login');
expect(actions.login).toHaveBeenCalledTimes(0);
button.trigger('click');
expect(actions.login).toHaveBeenCalledTimes(1);
});
test('It should pass data to state.login', async () => {
// Arrange;
const store = new Vuex.Store({
state: {
login: {
username: '',
password: ''
}
},
mutations: { updateField },
getters: { getField }
});
const wrapper = mount(Login, {
localVue,
vuetify,
store
});
const inputUserName = wrapper.find('#inputUserName');
const inputPassword = wrapper.find('#inputPassword');
inputUserName.setValue('Artur');
inputPassword.setValue('<PASSWORD>');
await wrapper.vm.$nextTick();
expect(store.state.login.username).toBe(inputUserName.element.value);
expect(store.state.login.password).toBe(inputPassword.element.value);
});
});
<file_sep>import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions.js';
import mutations from './mutations.js';
import getters from './getters.js';
Vue.use(Vuex);
//*********************/
//*** GLOBAL STATE ***/
//*******************/
export default new Vuex.Store({
state: {
newUser: {
name: '',
username: '',
email: '',
password: '',
verifypassword: ''
},
login: {
username: '',
password: ''
},
allEvents: '',
newEvent: {
name: '',
place: '',
description: '',
date: '',
typeOfEvent: '',
createdBy: ''
},
commentEvent: 'testar kommentar på event',
token: localStorage.getItem('token') || '',
user: '',
statusMessage: null,
filterEventTag: '',
filterEvents: ''
},
actions: actions,
mutations: mutations,
getters: getters
});
<file_sep>import Axios from 'axios';
import router from '../router/index';
let url;
if (process.env.NODE_ENV === 'development') {
url = 'http://localhost:5000/api';
} else {
url = 'https://incognito-backend.herokuapp.com/api';
}
const api = Axios.create({
baseURL: url
});
//***********************/
//*** GLOBAL ACTIONS ***/
//*********************/
const actions = {
async login({ state, commit, dispatch }) {
api
.post('/users/login', state.login)
.then(async res => {
const token = res.data.token;
const user = res.data.user;
Axios.defaults.headers.common['Authorization'] = token;
localStorage.setItem('token', token);
await commit('changeUserState', user);
commit('changeTokenState', token);
dispatch('statusMessageHandeling', res.data.msg);
router.push('/');
})
.catch(async error => {
dispatch('statusMessageHandeling', error.response.data.msg);
console.log(error);
});
},
async getUser({ commit }) {
Axios.get('https://incognito-backend.herokuapp.com/api/users/profile')
.then(res => {
console.log('sending getUser');
const user = res.data.user;
console.log(res, 'see response');
commit('changeUserState', user);
})
.catch(error => {
console.log(error.response);
});
},
async registration({ state, dispatch }) {
api
.post('/users/register', state.newUser)
.then(res => {
console.log(res.data.msg);
dispatch('statusMessageHandeling', res.data.msg);
router.push('/login');
})
.catch(error => {
console.log(error.response);
dispatch('statusMessageHandeling', error.response.data.msg);
});
},
async commentingevent({ state, dispatch }) {
console.log(state.user.username);
const userName = state.user.username;
const comment = state.commentEvent;
const eventId = '5f69d7c2568199adb10d910f';
api
.post('/events/commentingevent', {
userName,
comment,
eventId
})
.then(res => {
dispatch('statusMessageHandeling', res.data.msg);
console.log(res, 'response');
})
.catch(error => {
console.log(error.response);
dispatch('statusMessageHandeling', error.response.data.msg);
});
},
async attendingToEvent({ state, dispatch }, event) {
const eventId = event._id;
const userName = state.user.username;
api
.post('/events/attending', {
userName,
eventId
})
.then(res => {
dispatch('getEvents');
console.log(res, 'response');
})
.catch(error => {
console.log(error.response);
});
},
async likeEvent({ state, dispatch }, event) {
const eventId = event._id;
const userName = state.user.username;
api
.post('/events/like', {
userName,
eventId
})
.then(res => {
console.log(res, 'response');
dispatch('getEvents');
})
.catch(error => {
console.log(error.response);
});
},
async getEvents({ commit }) {
api
.get('/events/all')
.then(async res => {
const events = res.data.events[0];
commit('allEvents', events);
})
.catch(error => {
console.log(error.response);
});
},
async newEvent({ state, dispatch }) {
api
.post('/events/register', state.newEvent)
.then(res => {
console.log(res, 'created event');
dispatch('getEvents');
dispatch('statusMessageHandeling', res.data.msg);
router.push('/');
})
.catch(async error => {
dispatch('statusMessageHandeling', error.response.data.msg);
});
},
async logOut({ commit }) {
const token = localStorage.removeItem('token');
delete Axios.defaults.headers.common['Authorization'];
router.push('/login');
const user = '';
await commit('changeTokenState', token);
commit('changeUserState', user);
},
async statusMessageHandeling({ commit }, value) {
await commit('statusMessage', value);
const reset = null;
setTimeout(() => {
commit('statusMessage', reset);
}, 2400);
},
filterEvent({ commit }) {
commit('filterEventMutation');
},
resetFilter({ commit }) {
commit('resetFilter');
}
};
export default actions;
|
b5cd2ae36fbb3f0567ad4c2176364d402fdecc05
|
[
"JavaScript"
] | 11 |
JavaScript
|
Artur-Hoppner/Introvert
|
cd102c7acf29be062458d77319194afcec3a294a
|
e4f5f6a7fe21f9e7963730570a652e366fac2a2b
|
refs/heads/main
|
<repo_name>egolovko/lab2<file_sep>/Lab2, 70.py
"""
NAME
Lab2, 70
DESCRIPTION
This program calculates the sum of the power series, defined on the segment [A, B], with precision
"""
A = 0.
B = 1.
def s(x: float, positive_eps: float) -> float:
""" Calculate the value of sum of the power series, defined on segment [0, 1], with precision eps
:param x: the parameter of the sum of the power series
:param eps: precision
:return: return the calculated sum of the power series with precision eps
"""
n = 0
fraction = x/2
sigma = fraction
x = -x
negative_eps = -positive_eps
while not (negative_eps < fraction < positive_eps):
n += 1
fraction *= x*n*n / (2*n + 1) / (2*n + 2)
sigma += fraction
return sigma
def _display_result(inp: float, eps: float, out: float):
""" Display the result (out) of f(x) for inp
:param inp: program input value
:param eps: precision
:param out: calculated value
"""
print(f"for x = {inp:.5f}")
print(f"for eps = {eps:.4e}")
print(f"result = {out:.9f}")
def _display_error(error: BaseException):
""" Display the error with custom description
:param error: error with custom description
"""
print("***** Error")
print(error)
def _check_point(x:float) -> bool:
""" Check the domain of function s(x, eps) for x
:param x: the first parameter for S(x, eps) that must be checked
:return: True if x is domain else False
"""
return A <= x <= B
def _check_eps(eps:float) -> bool:
""" Check the eps value to positive
:param eps: the second parameter for S(x, eps) that must be checked
:return: True if x is positive else False
"""
return eps > 0
def input_float(prompt:str="") -> float:
""" Send input request and return converted value if it possible
:param prompt: custom description
:return: converted value from terminal/command prompt
:raises KeyboardInterrupt: if Ctrl+C was pressed when program wait the input
:raises ValueError: if input value not possible to convert
:raises Exception: If no input
"""
try:
input_data = input(prompt)
except KeyboardInterrupt:
raise KeyboardInterrupt("Input was aborted")
except:
raise Exception("There are no input to convert to float.")
try:
float_data = float(input_data)
except ValueError:
raise ValueError("Invalid data format. Input data must contain symbols for number translation. \n" + \
"Check the example on the end of input request message and try again.")
return float_data
def input_with_check(prompt:str="", check=lambda x: True) -> float:
""" Get float value and check it by check function
:param prompt: custom description
:param check: function (f(x:float) -> bool) that can check value
:return: correct input data
:raises ValueError: if data not correct (function check(x) return False)
"""
data = input_float(prompt)
if not check(data):
raise ValueError(f"Incorrect data. Point must be in ({A} <= input number <= {B}) and eps must be positive")
return data
def _main():
"""Program entry point"""
print(f"This program calculates the sum of the power series, defined on the segment [{A}, {B}], with precision")
print("This program is coded by <NAME>, K-12.")
try:
point = input_with_check(f"Enter the point ({A} <= number <= {B})(Example: 0.22): ", _check_point)
eps = input_with_check("Enter the precision (Example 1e-6): ", _check_eps)
except Exception as e:
_display_error(e)
else:
print("***** do calculations ...", end=" ")
output_data = s(point, eps)
print("done")
_display_result(point, eps, output_data)
if __name__ == "__main__":
try:
_main()
except KeyboardInterrupt:
_display_error(KeyboardInterrupt("Program was aborted"))
|
020903958f619d5e08c4cd165cfb8ddd0144e920
|
[
"Python"
] | 1 |
Python
|
egolovko/lab2
|
155a99c9799ed4e02ec8abf6415ed56dae93fbf3
|
225f1e554a43c7bae69928642e759c1c75161f36
|
refs/heads/master
|
<repo_name>Mohd-Huzaifa-Ansari/mppolytechnic.github.io<file_sep>/mppolytechnic.ac.in/js/validate.js
// JavaScript Document
function makeUppercase()
{
document.reg.stdname.value=document.reg.stdname.value.toUpperCase();
}
function makeUppercase1()
{
document.reg.fname.value=document.reg.fname.value.toUpperCase();
}
function makeUppercase2()
{
document.reg.col.value=document.reg.col.value.toUpperCase();
}
function makeUppercase3()
{
document.feed.name.value=document.feed.name.value.toUpperCase();
}
function makeUppercase4()
{
document.contact.name.value=document.contact.name.value.toUpperCase();
}
function ValidateAlpha(evt)
{
var keyCode=(evt.which)?evt.which:evt.keyCode
if ((keyCode >= 65 && keyCode <= 97) || keyCode == 32 || (keyCode >= 97 && keyCode <= 122 ||keyCode ==8 ))
{
return true;
}
return false;
}
function ValidateNum(evt1)
{
var keyCode=(evt1.which)?evt1.which:evt1.keyCode
if (keyCode >= 48 && keyCode <= 57 || keyCode ==8)
{
return true;
}
return false;
}
function reg()
{
if(document.date.name.value=="")
{
alert("Please fill Your Name.");
document.date.name.focus();
return false;
}
if(document.date.fname.value=="")
{
alert("Please fill Your Father Name.");
document.date.fname.focus();
return false;
}
if(document.date.mname.value=="")
{
alert("Please fill Your Mother Name.");
document.date.mname.focus();
return false;
}
if(document.date.number.value=="")
{
alert("Please fill your Mob. No.");
document.date.number.focus();
return false;
}
if(document.date.add.value=="")
{
alert("Please fill your Address");
document.date.add.focus();
return false;
}
if(document.date.email.value=="")
{
alert("Please Fill Your Email ID");
document.date.email.focus();
return false;
}
e=document.date.email.value;
f1=e.indexOf('@');
f2=e.indexOf('@',f1+1);
e1=e.indexOf('.');
e2=e.indexOf('.',e1+1);
n=e.length;
if(!(f1>0 && f2==-1 && e1>0 && e2==-1 && f1!=e1+1 && e1!=f1+1 && f1!=n-1 && e1!=n-1))
{
alert("Please Enter valid Email");
document.date.email.focus();
return false;
}
if(document.date.pass.value=="")
{
alert("Please Fill Your Password");
document.date.pass.focus();
return false;
}
if(document.date.city.value=="")
{
alert("Please Fill Your City");
document.date.city.focus();
return false;
}
if(document.date.dob.value=="")
{
alert("Please Fill Your Date of birth");
document.date.dob.focus();
return false;
}
if(document.date.gender.value=="")
{
alert("Please Select Your Gender");
document.date.gender.focus();
return false;
}
return true;
}<file_sep>/mppolytechnic.ac.in/about-us.html
<!DOCTYPE html>
<html lang="en">
<!-- Mirrored from mppolytechnic.ac.in/about-us.php by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 08 Sep 2020 05:14:49 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8" /><!-- /Added by HTTrack -->
<head>
<title>MAHARANA PRATAP POLYTECHNIC - GORAKHPUR U.P. INDIA</title>
<link rel="shortcut icon" href="images/favicon.ico">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="author" content="www.mppolytechnic.ac.in">
<meta name="description" content=" Maharana Pratap Polytechnic Gorakhpur (UP) India is Aided Polytechnic Affiliated to Board of Technical education Uttar Pradesh and approved By AICTE which provides Diploma in Engineering in Mechanical,Civil,Electrical,Computer Science, Electronics and Architectural Assitantship established in 1956." data-react-helmet="true" />
<meta name="keywords" content="mppolytechnic,mppolytechnic gorakhpur,Maharana Pratap Polytechnic Gorakhpur (UP),Aided Polytechnic in Uttar Pradesh, Diploma in computer Science|Electronics Engineering | Electrical enginnering | Mechanical engineering | Civil engineering, Board of Technical Education, Polytechnic in Gorakhpur,List of Polytechnic in Uttar Pradesh " data-react-helmet="true" />
<meta name="geo.region" content="IN-UP" />
<meta name="geo.placename" content="MP Polytechnic GORAKHPUR" />
<meta name="geo.position" content="22.351115;78.667743" />
<meta name="ICBM" content="22.351115, 78.667743" />
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" media="all">
<link href="layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
<link href="css/animate.min.css" rel="stylesheet" type="text/css" media="all">
<link href="https://fonts.googleapis.com/css?family=Work+Sans" rel="stylesheet">
<!--<script src="js/sb-admin-datatables.min.js"></script>-->
<style>
#mainav a{
text-decoration:none;
}
*{
font-family: 'Work Sans', sans-serif;
margin:0px;
padding:0px;
}
#phone{
font-size:16px;
}
@media (max-width: 991px){
#gov {
display:none;
}
}
</style>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="../translate.google.com/translate_a/elementa0d8.html?cb=googleTranslateElementInit"></script>
<script type="text/javascript">
$(window).on('load',function(){
$('#myModal').modal('show');
});
</script>
</head>
<body id="top">
<div class="wrapper row0">
<div id="topbar" class="hoc clear">
<div class="fl_left">
<ul class="nospace inline pushright">
<li><i class="fa fa-envelope-o" style="color:#FFFF33;font-size:20px;"></i> <span style="font-size:20px;"><EMAIL></span></li>
<!--<li><i class="fa fa-phone" style="color:#3a9fe5;font-size:20px;"></i> <span style="font-size:20px;">+91 888 766 7635</span></li>
<li><strong>A GOVERNMENT POLYTECHNIC (U.P) INDIA</strong></li>-->
<li> <div id="google_translate_element"></div></li>
</ul>
</div>
<div class="fl_right">
<ul class="faico clear">
<li><i class="fa fa-phone" style="color:#FFFF33;font-size:20px;"></i> <span style="font-size:20px;">0551 2255551</span></li>
<li><a href="https://www.facebook.com/mppolygkp" target="_blank" style="color:#3b5998;font-size:25px;"><i class="fa fa-facebook"></i></a></li>
</ul>
</div>
</div>
</div>
<!-- ################################################################################################ -->
<div class="wrapper row1">
<header id="header">
<div class="row" id="logo" >
<div class="col-lg-8 col-12">
<a href="index-2.html"><img src="images/new-mpp.png" class="img-fluid"></a>
</div>
<div class="col-lg-4 col-12" id="gov">
<a href="#" target="_blank"><img src="images/logo/mahant-circle.png" class="img-fluid"></a>
</div>
<!--<div class="col-lg-2 col-6" >
<a href="https://swachhbharatmission.gov.in" target="_blank" ><img src="images/logo/swach-bharat-logo.png" class="img-fluid"></a> </div>-->
</div>
</header>
</div>
<!-- ################################################################################################ -->
<!--<div class="wrapper row2" style="font-size:12px;">-->
<nav class="navbar navbar-expand-lg sticky-top row2" >
<a class="navbar-brand" href="index-2.html" style="color:#FFFFFF;"><i class="fa fa-institution"></i> </a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"><i class="fa fa-navicon"></i></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav" style="color:#FFFFFF;">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-item nav-link active" href="index-2.html" style="color:#FFFFFF;">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="about-us.html" style="color:#FFFFFF;" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
About Us
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="about-us.html">About Institute</a>
<a class="dropdown-item" href="mission-vision.html">Mission & Vision</a>
<a class="dropdown-item" href="principal-msg.html">Principal’s Message</a>
<a class="dropdown-item" href="#">Rules and Regulations</a>
<a class="dropdown-item" href="#">Infrastructure</a>
</div>
</li>
<li class="nav-item dropdown">
<!-- <a class="nav-item nav-link active" href="commitee.php" style="color:#FFFFFF;">Governance</span></a>-->
<a class="nav-link dropdown-toggle" href="#" style="color:#FFFFFF;" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Governance
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="chairman.html">List of Chairman</a>
<a class="dropdown-item" href="List-of-principal.html">List of Principal</a>
<a class="dropdown-item" href="commitee.html">List of Committee</a>
</div>
<!-- <a class="nav-link dropdown-toggle" href="#" style="color:#FFFFFF;" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Governance
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="principal-msg.php">Principal</a>
<a class="dropdown-item" href="commitee.php">Academic Committee</a>
<a class="dropdown-item" href="finance-commitee.php">Finance Committee</a>
<a class="dropdown-item" href="aicte-commitee.php">AICTE Committee</a>
<a class="dropdown-item" href="scholarship-commitee.php">Scholarship Committee</a>
<a class="dropdown-item" href="sport-commitee.php">Sports Committee</a>
<a class="dropdown-item" href="proctorial-commitee.php">Proctorial Committee</a>
<a class="dropdown-item" href="security-commitee.php">Security & Gardening Committee</a>
<a class="dropdown-item" href="tnp-commitee.php">Training & Placement Committee</a>
</div>-->
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" style="color:#FFFFFF;" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
AICTE
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a href="attachment/EOA_AICTE/EOA_Report_2019-20.pdf" target="_blank" class="dropdown-item">EOA Letter</a>
<a class="dropdown-item" href="#"></a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" style="color:#FFFFFF;" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Academics
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="academic-programmes.html">Academic Programmes</a>
<a class="dropdown-item" href="syllabus.html">Syllabus</a>
<a class="dropdown-item" href="online-study-material.html">Study Material</a>
<a class="dropdown-item" href="admission.html">Admissions</a>
<a class="dropdown-item" href="fee-structure.html">Fees Structure</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" style="color:#FFFFFF;" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Departments
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="civil-department.html">Civil Engineering</a>
<a class="dropdown-item" href="electrical-department.html">Electrical Engineering</a>
<a class="dropdown-item" href="mechanical-department.html">Mechanical (Production)</a>
<a class="dropdown-item" href="mechanical-cad-department.html">Mechanical (CAD)</a>
<a class="dropdown-item" href="computer-science-department.html">Computer Science & Engineering</a>
<a class="dropdown-item" href="electronics-department.html">Electronics Engineering</a>
<a class="dropdown-item" href="architecture-department.html">Architectural Assistantship</a>
<a class="dropdown-item" href="marketing-sales-management.html">Marketing & Sales Management</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" style="color:#FFFFFF;" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Training & Placement
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">Training Statistics</a>
<a class="dropdown-item" href="#">Placement Statistics</a>
<a class="dropdown-item" href="single-student-placement.html">Placed Students Details</a>
<a class="dropdown-item" href="#">Recruiting Partners</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" style="color:#FFFFFF;" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Facilities & Resources
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="hostel.html">Hostels</a>
<a class="dropdown-item" href="library.html">Central Library</a>
<a class="dropdown-item" href="sport.html">Sport & Atheletics</a>
<a class="dropdown-item" href="seminar.html">Auditorium & Seminar Halls</a>
<a class="dropdown-item" href="power.html">24*7 Power Supply</a>
</div>
</li>
<!-- <li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" style="color:#FFFFFF;" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Alumni
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="alumni.php">Alumni Registration</a>
</div>
</li>
<li class="nav-item active">
<a class="nav-item nav-link" href="alumni.php" style="color:#FFFFFF;">Alumni</span></a>
</li>-->
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="contact-us.html" style="color:#FFFFFF;" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Contact us
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="contact-us.html">Address</a>
<a class="dropdown-item" href="map-location.html">Maps & Location</a>
<a class="dropdown-item" href="phone-directory.html">Phone Directory</a>
<a class="dropdown-item" href="feedback.html" role="tab" aria-controls="settings">Feedback / Query</a>
</div>
</li>
</ul>
</div>
</div>
</nav>
<!--</div>-->
<!-- ################################################################################################ -->
<div>
</div>
<!-- ################################################################################################ -->
<style>
#list-messages > img{
height:250;
width:250;
}
</style>
<div class=" container-fluid row3" style="padding:20px;">
<div class="row">
<div class="col-lg-3">
<div class="list-group" id="list-tab" role="tablist">
<a class="list-group-item list-group-item-action active" id="list-home-list" data-toggle="list" href="#list-home" role="tab" aria-controls="home">About Institute</a>
<a class="list-group-item list-group-item-action" id="list-profile-list" data-toggle="list" href="#list-profile" role="tab" aria-controls="profile">Mission & Vision</a>
<a class="list-group-item list-group-item-action" id="list-messages-list" data-toggle="list" href="#list-messages" role="tab" aria-controls="messages">Principal’s Message</a>
<a class="list-group-item list-group-item-action" id="list-settings-list" data-toggle="list" href="#list-settings" role="tab" aria-controls="settings">Rules and Regulations</a>
<a class="list-group-item list-group-item-action" id="list-1" data-toggle="list" href="#list-11" role="tab" aria-controls="settings">Institute Brochure</a>
<a class="list-group-item list-group-item-action" id="list-2" data-toggle="list" href="#list-22" role="tab" aria-controls="settings">Infrastructure</a>
</div>
</div>
<div class="col-lg-9">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active" id="list-home" role="tabpanel" aria-labelledby="list-home-list">
<h1><center><strong>About-Us</strong></center></h1><hr>
<p>After independence many schemes were started for the development of the country. In which the requirement of technicians was paramount‚ whose fulfillment was possible only through technical institutions. But at that time‚ there was acute shortage of technical institutions in the country. In such a situation‚ the establishment of some new technical institution was under the consideration of government. Keeping in view these requirements‚ the ultimate visionary‚ Purvanchal vikas parish Brahmalin Mahant Digvijay Nath Ji Maharaj established Maharana Pratap Shiksha Prishad‚ whose purpose was to remove the backwardness of the eastern region and to educate the people. On 15-07-1956‚ the proposal was passed to start overseer classes in Maharana Pratap Engineering Institute. The contribution of late Dr. <NAME> in shaping of this auspicious idea of Mahant Ji has been unforgottable. The Dr. Shahi completed the admission procedure of first year of Maharana Pratap Engineering Institute in 1956-57 and gave admission to 230 students in civil Engineering. At that time‚ the school was at initial stage and it had not its own bulding Due to this school was started in Prachary Bhavan of Maharana Pratap Degree College.
<br>
Immediately after the establishment of the school‚ <NAME> was worried about the building for which land was required. With the strong efforts of <NAME>‚ a widow named late Smt. <NAME> from a prominent Kayasth family of the town donated her 1.44 Acre Nazul land the civil lines for the construction of building. Surely it was a pious contribution in development of school. The construction of school building was completed on the said land measuring 12‚000 Square feet.
<br>
First of all‚ the principal was required to run the school smoothly because Dr. Shahi was the principal of Maharana Pratap Degree college and he contributed at the time of admission to cooperate mahant Ji. The search of Principal ended very soon because chief Engineer’s Civil Personal Assistant P.A. <NAME> had retired after completing his service <NAME> invited him to work on the post of Principal of his newly constructed institute. He gladcy accepeted it. At the initial stage of institute building‚ <NAME> Singh completed decoration and infrastructure work quickly and efficiently. In the same year the school was transferred to its newly built building.
<br>
By that time‚ the government had not decided any clear policy in the field of technology. In order to make curriculum ( Syllabus) and for conducting examination of various technical institution‚ a council adhoc board was established under the supervision of Roorkie University.
<br>
In the year 1956‚ at the time of first admission the duration of course was only 2 years. Thus‚ first batch appeared in the exam in 1958.
<br>
But shortly after the beginning of the session of 1958‚ in the month of october‚ the dynamic personality Principal <NAME> died and Mr. vishan swaroop working lecturer of civil Engineering was promoted Princial. But in the month of June 1959 <NAME> resigned from service of the school ans went else where. There after‚ <NAME>‚ invited <NAME>ji‚ an honest and active overseer of Irrigation Department to work as principal which was gladly accepted by him since 1959‚ thus <NAME> became the principal of institute.
<br>
During the year 1958-59 the govt formed an institute named “ State board of technical Education” and its headquarter was established in Lucknow. The duration of course was increased from 2 to 3 years.
<br>
Meanwhile the central govt directed state govts. that all the private technical institution should be developed in terms of building‚ infrastructure and staff according to the norms of Indian standard. “All India Technical Council” of northern region Kanpur farmed a committee‚ the committee was directed for inspection of all private institutes and submit their reports to state govt. The committee recommended that there is no justification of establishing second polytechnic in Gorakhpur as one govt. Polytechnic was already working. But state govt rejected aforesaid recommendation of committee and included this institute in the development programme.
<br>
Thus‚ the institute continued to develop with the inspiration of <NAME> under efficient leadership of Late Sri Mohan lal ji. Meanwhile “ All India Technical Council” proposed that if <NAME> wants to run this institute then it should develop institute according to norms.
<br>
Otherwise if parishad is not able to bear the expenses then institute should be handed over to state Government. In this case state Government will run the institute according to fixed norms and give representation to three members its chairman will be director of technical education and name of institute will remain unchanged.
<br>
<NAME> considered the aforesaid proposal of the government and keeping in view the interest of the institute and employees decided to hand over management of the institute to the government. Thus. the institute came under development programme in 1962.
<br>
Under development Programme the government allocated funds for building‚ laboratory‚ workshop‚apparatus‚ library‚ furniture land development and hostel.
<br>
The name of institute was change to Maharana Pratap Polytechnic since July 1962. A Society named “ Maharana Pratap Polytechnic Society ” was got registered for management of this polytechnic.
<br>
With inspiration of <NAME>‚ then principal Sri Mohan Lal ji passed A.M.I.E Course as the principal of institute falling under development programme was required to be degree holder. Mahant ji was not ready to give the responsibility of institute to somebody else.
<br>
Under Development Programme this institute was accorded approval for Civil‚ Mechanical and Electrical Engineering courses. But during 1962-63 due to lack of infrastructure admission procedure was completed only for Civil Engineering. In 1963-64 after developing infrastructure the admission procedure was completed in all trades.
<br>
After availability of sufficient funds froms government‚ 25 acre land was to be acquisition for polytechnic according to norms <NAME> offered 45 acre land near engineering college @ 3200/- Per acre to Mahant ji. But sardar sahib did not register the land in favour of institute despite Mahant ji’s request as delayed sanctioned from government.
<br>
Despite this failure efforts were made for acquisition of land else where. For this purpose‚ <NAME>‚ instructor of Institute made his important contribution and it was with his efforts that deal for acquisition of 10 acres Guava garden of sri Jageshwar Pasi was finalised. Thus land was registered in 1970 and ground floor of main building and 2/3 part of workshop was built in the year 1972. During session 1972-73 the institution was transferred from civil lines to its present place.
<br>
Here it is worth while to mention that before 1962‚ <NAME> and <NAME> <NAME> gracefully worked as president and secretary of the society. Since 1962Director‚ Technical Education and Principal have been working as president and secretary respectively.
<br>
With relentless efforts of then Principal Late sri <NAME>ji part time 4 years diploma course started during 1974-75 but it was stop as government did not give permission‚ Again‚ during 1981-82 parttime courses permission was granted for running courses in Electrical and Mechanical course only which continued till 1986-87.
<br>
In this continuity permission for running two years course for commercial practice was granted by government during 1978-79 in addition to engineering department. Minimum education qualification required for admission in this course was intermediate. During 1981-82‚ Silver jublee of institute was celebrated under leadership of Sri G.D. Srivastav‚ senior lecturer‚ Mechanical which continued for two days. All teachers‚ employees and students participated with great enthusiasm and dedication and made this celebration successful.
<br>
Thus‚ the insttute continued to develop day by day under efficient leadership of <NAME>. Although ‚ lawless elements created hindrance in the way of development and tried to involve sri Mohan lal ji by unfair means but no harm was done due to his fearless nature and co- operation of his intellectual colleagues.
<br>
In the year 1985‚ the cruel hands of death snatched our well determind principal at the end of his tenure. There after‚ sri P.<NAME>al‚ Senior lecturer Electrical Engineering was made officiating Prinicipal Sri G.<NAME> was first principal of this institute who was holding post graduation degree in Engineering as also Dip. ( Pad) from western Germany. After taking over charge of principal‚ he established community Development unit financed by Government of India within a month‚ keeping in view the developmental work done during his tenure‚ he was known as “ Vikas Purush”. Sri srivastav finished incomplete work left by <NAME> ji and with his relentless efforts he brought this developing institute in to the category of developed institute. It was the result of his efforts that the first floor of main building and remaining part of workshop was constructed with the funds‚ received under district scheme. During his tenure‚ the statue of Maharana Pratap was founded in premises of institute.
<br>
Since 1990‚ golden era of technical Educational Institute started. From this year funds were allocated for uplifment of technical Educational institute by world Bank Project. As Sri G.D.Srivastav usd to work keeping in view cleamliness and interest of the institute‚ so the “ detail project report” of this institute was considered exemplary in the directorate. As a results of which maximum fund Rs. 2.5 crore was allocated to this institute under world bank project‚ with this fund hostel having 120 beds‚ laboratory‚ two story building and 12 residential buildings and over head tank were constructed modernization of workshop and laboratory was also done.
<br>
A new course “ Diploma in Mechanical computer aided Design” was started in the year 1995 due to the relentless efforts of Sri Srivastav. Also one year “Post Gratuate Diploma in Marketing and Sales Management”was started according to the policy of government.
<br>
In the year 2009 three new course computer science‚ Architecture Assistantship and Electronics Engineering were started in the institute under self financed scheme with inspiration of then Peethadhishwar param <NAME>aidy nath <NAME> and efforts of Param <NAME>. Apart from this‚ course Mechanical‚ Electrical and Civil Engineering were also started in second shift in the year 2010.
<br>
At present time an efficient administrator and teacher Major <NAME> has been working as officiating Principal and institute is progressing day by day under his leadership.
</p>
</div>
<div class="tab-pane fade" id="list-profile" role="tabpanel" aria-labelledby="list-profile-list">
<h1><center><strong>Our Mission</strong></center></h1><hr>
<p align="justify"><NAME> formed Maharana Pratap Shiksha Parishad in 1932 with an aim of spreading power of education so as to improve the quality of life in this backward region of eastern Uttar Pradesh. After independence when industrialization process began then the need of more technicians was felt for which <NAME> ishtablished Maharana Pratap Engginering Insitute in 1956 to feelfill the demand of technicians in industries. At present Maharana Pratap Polytechnic is running courses which are producing diploma holder engineers to fulfill the demand of industries and other governmental organization. We want this goal to be achieved with better planned endeavor, with pratical and theoretical knowledge, improved skill and practice and with full devotion and dedication.</p><br>
<h1><center><strong>Our Vision</strong></center></h1><hr>
<p>Maharana Pratap Polytechnic wants to be a world class Engineering Institution which is committed to impart quality education in a disciplined environment .We want to transform every student into Industry ready and by ensuring high quality technical education through dissemination of knowledge, insights and intellectual contributions.</p>
</div>
<div class="tab-pane fade" id="list-messages" role="tabpanel" aria-labelledby="list-messages-list">
<h1><center><strong>Principal's Message</strong></center></h1><hr>
<img src="images/pi.jpg" class="img-fluid img-thumbnail float-right" style="margin-left:20px;"/>
<p style="text-align:justify";>
We live in 21st century which is technical era and technology has been embraced and incorporated into our daily lives. Within the constructs of civilized society, the vast rewards of technological innovations have far outweighed the negatives. <br>
We believe that students of Maharana Pratap Polytechnic would not only excel across several dimensions, like knowledge domain, skills, communication and basic human values, but they would also combine these with priceless qualities of mind and heart. It is for this important reason that we have succeeded in maintaining our position among leading Diploma in Engineering in the country.<br>
It gives me immense pleasure to welcome you to this institute which is the one of the oldest polytechnic after Independence in UP established in 1956. This institute have well equipped labs, Computer Centre and library to help students in attaining highest standards in academics, and professional skills.
</p>
<br><br><p align="right"
><strong>Major Pateshwari Singh Principal(Acting)<br>(<NAME> POLYTECHNIC,GORAKHPUR)</strong>
</p>
</div>
<div class="tab-pane fade" id="list-settings" role="tabpanel" aria-labelledby="list-settings-list">
</div>
<div class="tab-pane fade" id="list-11" role="tabpanel" aria-labelledby="list-1"></div>
<div class="tab-pane fade" id="list-22" role="tabpanel" aria-labelledby="list-2"></div>
</div>
</div>
</div>
</div>
<div class="wrapper" style="color:#ffffff;background-color:#010101; border-bottom: 3px solid #FFFFFF;" class=" animate-box fadeInUp animated">
<footer id="footer" class="hoc clear" >
<!-- ################################################################################################ -->
<div class="one_third first">
<h6 class="title" style="color:#FFFFFF">CONTACT US</h6>
<ul class="nospace linklist contact">
<li><i class="fa fa-map-marker"></i>
<address>
Sonauli Road, Gorakhnath,Gorakhpur, U.P - 273015
</address>
</li>
<li><i class="fa fa-phone"></i> 0551 225 5551<br>
<li><i class="fa fa-envelope-o"></i> <EMAIL></li>
</ul>
</div>
<div class="one_third">
<h6 class="title" style="color:#FFFFFF">CURRICULAR ACTIVITIES</h6>
<ul class="nospace linklist contact">
<li><img src="images/new_red.gif"> <a href="ncc-gallery.html" style="color:#FFFFFF;" >NCC</a></li>
<li> <img src="images/new_red.gif"> <a href="Cultural-Programme.html" style="color:#FFFFFF;" >Cultural Programme</a></li>
<li> <img src="images/new_red.gif"> <a href="Sports-Games.html" style="color:#FFFFFF;" >Sports & Games</a></li>
<li> <img src="images/new_red.gif"> <a href="News-Events.html" style="color:#FFFFFF;" >News & Events</a></li>
</ul>
</div>
<div class="one_third">
<h6 class="title" style="color:#FFFFFF">REACH OUT HERE</h6>
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3561.8977588410266!2d83.35591823938272!3d26.77952881370108!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x399144352e291fd5%3A0x325bdd828ebafd4d!2sMaharana+Pratap+Polytechnic!5e0!3m2!1sen!2sin!4v1554976095101!5m2!1sen!2sin" width="400" height="300" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
<!-- ################################################################################################ -->
</footer>
</div>
<!-- ################################################################################################ -->
<div class="wrapper" style="background-color:#1a1a1a; color:#FFFFFF;">
<div id="copyright" class="hoc clear">
<!-- ################################################################################################ -->
<p class="fl_left">Copyright © 2020 - All Rights Reserved - <a href="index.html" style="color:#FFFFFF;">MP Polytechnic - Gorakhpur(U.P).</a> </p>
<p class="fl_right">Designed by <a target="_blank" href="https://www.techsrijan.com/" style="color:#FFFFFF;"style="color:#FFFFFF;" title="Techsrijan Consultancy Services Pvt Ltd">Techsrijan Consultancy Services Pvt Ltd.</a></p>
<!-- ################################################################################################ -->
</div>
<center>
<p> Visitor Counter
<img src=digits/4/2.gif><img src=digits/4/6.gif><img src=digits/4/7.gif><img src=digits/4/0.gif><img src=digits/4/0.gif><img src=digits/4/1.gif>
</center>
</div>
<!-- ################################################################################################ -->
<a id="backtotop" href="#top"><i class="fa fa-chevron-up"></i></a>
<!-- JAVASCRIPTS-->
<script src="js/validate.js"> </script>
<script src="layout/scripts/jquery.min.js"></script>
<script src="layout/scripts/jquery.backtotop.js"></script>
<script src="layout/scripts/jquery.mobilemenu.js"></script>
<script src="layout/scripts/jquery.flexslider-min.js"></script>
<script src="js/bootstrap.min.js"> </script>
</body>
<!-- Mirrored from mppolytechnic.ac.in/about-us.php by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 08 Sep 2020 05:14:51 GMT -->
</html><file_sep>/README.md
# mppolytechnic.github.io
|
fb8562d40b3f762a0d5f9dc378f26c8425acc49c
|
[
"JavaScript",
"HTML",
"Markdown"
] | 3 |
JavaScript
|
Mohd-Huzaifa-Ansari/mppolytechnic.github.io
|
c0a071310b7f0833fbe154c1580d8a2082917faa
|
a64bb6fa8e7027e92aa5f5277d6c3015763b3c27
|
refs/heads/master
|
<repo_name>renecastrejon/angular2-sample<file_sep>/app/main.ts
/*
main.ts se encarga de cargar el modulo inicial
Este archivo debe cargarse antes en index.html
SECUENCIA:
1. index.html => Carga systemjs.js que contiene una config. para cargar main.ts
2. main.ts => Contiene la configuracion para hacer el bootstraping
*/
import { platformBrowserDynamic } from
'@angular/platform-browser-dynamic'
import { AppModule } from './app.module'
platformBrowserDynamic().bootstrapModule(AppModule)
<file_sep>/app/events-app.component.ts
//Para usar las palabras de reservada de angular como '@Component'
import { Component } from '@angular/core'
//Con esto se especifica que es un componente
@Component({
//Este es un identificador del componente que se puede usar
//en un HTML, <events-app></events-app>
selector:'events-app',
//Con esto se pasa algo para mostrar cuando
//se cargue el componente
template:`
<nav-bar></nav-bar>
<router-outlet></router-outlet>
`
})
//Clase que representa un componente a ser exportada
export class EventsAppComponent{
}
<file_sep>/app/Events/shared/create-event.component.ts
import {Component, OnInit} from '@angular/core'
import {Router} from '@angular/router'
import {EventService} from './event.service'
@Component({
templateUrl:'app/Events/shared/create-event.component.html',
styles:[`
em { float:right; color:#E05C65; padding-left:10px;}
.error input {background-color:#E3C3C5;}
`]
})
export class CreateEventComponent implements OnInit{
isDirty:boolean = true
event:any
constructor(private router:Router, private eventService:EventService){
}
ngOnInit(){
}
saveEvent(formValues){
this.eventService.saveEvent(formValues)
this.isDirty = false
this.router.navigate(['/events'])
}
cancel(){
this.router.navigate(['/events'])
}
}
<file_sep>/app/app.module.ts
import {NgModule} from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { RouterModule} from '@angular/router'
import {FormsModule, ReactiveFormsModule} from '@angular/forms'
import {
EventsListComponent,
EventThumbnailComponent,
EventService,
EventDetailsComponent,
CreateEventComponent,
EventRouteActivator,
EventListResolver,
CreateSessionComponent
} from './events/index'
//Componentes importados
import {EventsAppComponent} from './events-app.component'
import {NavBarComponent} from './nav/navBar.component'
import {ToastrService} from './common/toastr.service'
import {appRoutes} from './routes'
import {Error404Component} from './errors/404.component'
import {AuthService} from './user/auth.service'
@NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
RouterModule.forRoot(appRoutes)
],
//La declaracion de los componentes debe realizarse aqui
//con la siguiente sentencia
declarations: [
EventsAppComponent,
EventsListComponent,
EventThumbnailComponent,
EventDetailsComponent,
CreateEventComponent,
CreateSessionComponent,
Error404Component,
NavBarComponent
],
//Declaracion de servicios
providers:[
EventService,
ToastrService,
EventRouteActivator,
AuthService,
EventListResolver,
{
provide:'canDeactivateCreateEvent',
useValue:checkDirtyState
}
],
//Como este es el componente que esta hasta arriba de la aplicacion
//se debe hacer un bootstraping, (como un first-run)
bootstrap: [EventsAppComponent],
})
export class AppModule {
}
function checkDirtyState(component:CreateEventComponent){
if(component.isDirty)
return window.confirm('You havent save. Continue exiting?')
return true
}
<file_sep>/app/user/user.model.ts
export interface IUser{
id:number,
firstName:string,
lastName:string,
userName:string
}
<file_sep>/app/Events/event-list.component.ts
//PARENT COMPONENT
import {Component, OnInit} from '@angular/core'
import {EventService} from './shared/event.service'
import {ToastrService} from '../common/toastr.service'
import {ActivatedRoute} from '@angular/router'
import {IEvent} from './shared/index'
@Component({
template:
`
<div>
<h1>Upcoming Events</h1>
<hr/>
<div class="row">
<div *ngFor="let event of events" class="col-md-5">
<event-thumbnail #thumbnail [event]="event" (click)="handleClickEvent(event.name)"></event-thumbnail>
</div>
</div>
<button class="btn btn-primary">Message</button>
<!--Esta linea accede a la propiedad del child component-->
<span>{{thumbnail?.somePropertie}}</span>
</div>
`
})
//INPUTS
//<event-thumbnail #thumbnail [event]="event1"></event-thumbnail>
//Esta linea especifica que el componente event-thumbnail
//tiene un input llamado event y que se le pasa el valor
//de event1(variable definida abajo)
export class EventsListComponent implements OnInit{
events:IEvent[]
//Datos para mostrar en la aplicacion mediante un servicio,
constructor(private eventService:EventService, private toastr:ToastrService,
private route:ActivatedRoute){
}
ngOnInit(){
//Se obtienen datos de forma sincronica
//this.events = this.eventService.getEvents()
//Asi se obtienen datos de forma asincronica
//this.eventService.getEvents().subscribe(events => { this.events = events })
//Si se requiere esperar a que la llamada asincronica termine
//y despues cargar el componente ya con los datos, entonces se debe utilizar resolve
this.events = this.route.snapshot.data['events']
}
handleClickEvent(eventName){
this.toastr.success(eventName)
}
}
<file_sep>/app/Events/shared/event-list-resolver.service.ts
import {Injectable} from '@angular/core'
import {EventService} from './event.service'
import {Resolve} from '@angular/router'
@Injectable()
export class EventListResolver implements Resolve<any> {
constructor(private eventService:EventService){
}
resolve() {
//map retorna el dato mapeado a esa variable
return this.eventService.getEvents().map(events => events)
}
}
<file_sep>/app/Events/event-details/create-session.component.ts
import {Component, OnInit} from '@angular/core'
import {FormControl, FormGroup, Validators} from '@angular/forms'
import {ISession} from '../shared/index'
@Component({
templateUrl:'app/Events/event-details/create-session.component.html',
styles: [`
em {float:right; color:#E05C65; padding-left:10px;}
.error input {background-color:#E3C3C5;}
.error ::-webkit-input-placeholder { color: #999; }
.error :-moz-placeholder { color: #999; }
.error ::-moz-placeholder { color: #999; }
.error :ms-input-placeholder { color: #999; }
`]
})
//data must be parser in all the current behavior
export class CreateSessionComponent implements OnInit{
newSessionForm: FormGroup
name: FormControl
presenter: FormControl
duration: FormControl
level: FormControl
abstract: FormControl
ngOnInit(){
this.name = new FormControl('', Validators.required)
this.presenter = new FormControl('', Validators.required)
this.duration = new FormControl('', Validators.required)
this.level = new FormControl('', Validators.required)
this.abstract = new FormControl('', [Validators.required, Validators.maxLength(400)])
this.newSessionForm = new FormGroup({
name:this.name,
presenter:this.presenter,
duration:this.duration,
level:this.level,
abstract:this.abstract
})
}
saveSession(formValues){
let session:ISession ={
id:undefined,
name:formValues.name,
duration:+formValues.duration,
level:formValues.level,
presenter:formValues.presenter,
abstract:formValues.abstract,
voters:[]
}
console.log(session)
}
}
|
ab5c8bdd988e325893a47e666d4e3366445ca270
|
[
"TypeScript"
] | 8 |
TypeScript
|
renecastrejon/angular2-sample
|
62912dfdf4d39e464ba8045db53f4dfeb1a3a451
|
42cdf70c9cb2ac73d47736d2e3f0783acc5c20f1
|
refs/heads/master
|
<file_sep>import React from 'react'
import Link from 'gatsby-link'
import PropTypes from 'prop-types'
import Img from 'gatsby-image'
const propTypes = {
data: PropTypes.object.isRequired,
}
class AllBlogPosts extends React.Component {
render() {
const posts = this.props.data.allContentfulBlogPost.edges
console.log(posts)
return (
<div>
<h1>Hi from the all blog posts page</h1>
<p>you have arrived at the list of all of our posts</p>
<Link to="/">Go back to the homepage</Link>
<ul>
{posts.map(({ node: post }) => {
const {
slug,
id,
title,
date,
author
} = post
console.log(post, author, date)
return (
<li key={title} >
<Link to={slug}>{title}</Link>
<div>{date.substring(0, 10)} - {author[0].fullName} - {author[0].twitter}</div>
<Img style={{ margin: 0 }}
resolutions={author[0].avatar.responsiveResolution}
/>
</li>)
})
}
</ul>
</div>
);
}
}
export default AllBlogPosts;
export const pageQuery = graphql`
query allBlogQuery {allContentfulBlogPost {
edges {
node {
slug
id
title
date
author {
fullName
twitter
avatar {
responsiveResolution (width: 100) {
width
height
src
srcSet
}
}
}
}
}
}
}`
<file_sep>---
title: "Hackathon Progress"
author: "carriere4"
date: "03/17/2018"
---
Happy St. Patrick's Day!
9:00am: Arrive at off-site location. I've brought snacks, drinks, LOTS of Cool Brew coffee, and a few beers. Everyone is bringing their extra monitors in addition to their laptops in order to maximize productivity. We've got an awesome space for it. My good friend allowed us to use his company's conference room. We've got 2 big whiteboards, a massive TV for demos, and tables on rollers to configure the space however we want.
9:05am: Cole arrives. We start setting up. We quickly realize that we are going to need extension cords to make the space + laptops + extra monitors all work together. Evan arrives.
9:20am: I'm resourceful. Call wife. Ask her to wake teenage daughter and bribe her to drive over extention cords.
9:52am: Daughter arrives with extension cords. She departs with my Jeep (part of the bribe).
10:00am: We are all set up and ready to crank. George hasn't arrived yet but we've hit another snag. The wifi is super-fast. But there are no ports open on the router for what we are trying to do. We can't connect laptops to iPhones. Stuck. Problem-solving ensues. I call my buddy about asking his IT guy to open the port we need. The just finished a security audit - not going to happen. More attemps at workarounds. At 10:45am I call it. We back to the office where we can make progress on the app - not the router issues.
11:10am: Settled in and cranking.
11:15am: Encounter database issue.
11:30am: I bring everyone a Guiness Stout. It IS St. Patrick's Day. Don't judge.
3:30pm: Break for lunch. At District Donuts, Cole, George and Evan figure out the solution to the database issues.
4:05pm: Cole fixes the database problem we were having.
4:20pm: I go out to get cough drops for George (we will all benefit though). While I was gone, I missed Evan's jubilant cry of "I'm a f*king hacker, bitches!" Apparently, we are making progress.
5:45pm: I hit a bug in Gatsby and George is still trying to fix it at 6:30pm
7:25pm: I've fixed my issues (along with George's help) by deleting every line that throws an error until there are no more errors. Site is back working with lesser functionality. Damn. Database progress proceeding, but slowly. George is cranking. Evan has been quiet, so I assume there is progress. No shouts of exultation, but no cursing either.
8:36pm: shouts of "what the hell?" and "I had that same error! It didn't make sense." Also Evan: "Xcode is being an asshole."
10:05pm: Charles returns with the pizza and proves to all that he can count to four. Cole is chagrined. Cole has been less than successful in counting to four this week.
11:00pm: After trashing the old website and starting over, George has put me on a more resonable and responsible path.
11:05pm: Cole to FireBase database: "how did you get WORSE?"
12:00pm: We lunch on Hola Nola tortilla chips, leftover pizza, and donuts. Don't judge. We are making progress.
2:05pm: First beer. Don't judge. We are making progress. I promise.
<file_sep>Wow. Not much sleep. I think you forget how to sleep as you get older. I'm excited about today. Wearing my NASA shirt because I'm expecting to launch today!
9:30am: grabbed an espresso and donuts from District Donuts. Side note: I LOVE that place.
9:45am: arrived at Scandy to find that Evan had beaten me here. We discuss donuts, sleep (or lack thereof) and code. Cole arrives. Donut consumption and status updates ensue.
|
0f7f291723645eef0dc7a2bccecec1386f5b48f2
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
Scandy-co/cappy-web
|
52548b9db6717f6428be1393ce70208fc08ecdb1
|
c9acc44a7b5f3b023ee05580e32aaf1104add609
|
refs/heads/master
|
<repo_name>SiavashMT/GloVe<file_sep>/README.md
Simple Python Implementation of Global Vectors for Word Representation (GloVe)
Example Usage:
```
import nltk
from nltk.corpus import brown
import logging
logging.getLogger().setLevel(logging.INFO)
nltk.download('brown')
data = brown.sents(categories=['news'])[:100]
glove = GloVe()
glove.train(data, number_of_iterations=20, optimizer='adagrad')
print(glove.word_mapping)
```
Implemented Based-on:
[1] http://www.aclweb.org/anthology/D14-1162
[2] http://www.foldl.me/2014/glove-python/ (https://github.com/hans/glove.py)<file_sep>/glove_py.py
from typing import List
from scipy import sparse
import numpy as np
from random import shuffle
import logging
def adagrad(weight, grad, sum_grad_squared, learning_rate: float):
weight -= (learning_rate * grad / np.sqrt(sum_grad_squared))
return weight
def sgd(weight, grad, learning_rate: float):
weight -= learning_rate * grad
return weight
def rmsprop(weight, grad, mean_square_weight, learning_rate: float, beta: float = 0.9):
mean_square_weight = beta * mean_square_weight + (1. - beta) * grad ** 2
weight -= (learning_rate * grad / np.sqrt(mean_square_weight))
return weight, mean_square_weight
class GloVe:
def __init__(self, window_size: int = 10, word_vector_dimension=100):
self._window_size = window_size
self._word_vector_dimension = word_vector_dimension
def initialize_word_vectors_and_biases(self):
self.W = (np.random.rand(self.vocab_size, self._word_vector_dimension) - 0.5) / \
float(self._word_vector_dimension + 1)
self.W_tilde = (np.random.rand(self.vocab_size, self._word_vector_dimension) - 0.5) / \
float(self._word_vector_dimension + 1)
self.b = (np.random.rand(self.vocab_size) - 0.5) / float(self._word_vector_dimension + 1)
self.b_tilde = (np.random.rand(self.vocab_size) - 0.5) / float(self._word_vector_dimension + 1)
@staticmethod
def get_vocabs_from_corpus(corpus: List[List[str]]):
return {word for doc in corpus for word in doc}
def build_co_occurrence_matrix(self, corpus: List[List[str]], alpha: float = 0.75,
x_max: int = 100):
vocabs = GloVe.get_vocabs_from_corpus(corpus=corpus)
id_to_word_map = {i: word for i, word in enumerate(vocabs)}
word_to_id_map = {v: k for k, v in id_to_word_map.items()}
vocab_size = len(vocabs)
logging.info("Vocabulary size is {}".format(vocab_size))
co_occurrence_matrix = sparse.lil_matrix((vocab_size, vocab_size), dtype=np.float64)
for i, doc in enumerate(corpus):
word_ids = [word_to_id_map[word] for word in doc]
for center_i, center_id in enumerate(word_ids):
context_ids = word_ids[max(0, center_i - self._window_size): center_i]
contexts_len = len(context_ids)
for left_i, left_id in enumerate(context_ids):
distance = contexts_len - left_i
increment = 1.0 / float(distance)
co_occurrence_matrix[center_id, left_id] += increment
co_occurrence_matrix[left_id, center_id] += increment
self.co_occurrence_matrix = co_occurrence_matrix
self.id_to_word_map = id_to_word_map
self.word_to_id_map = word_to_id_map
self.vocab_size = vocab_size
self.alpha = alpha
self.x_max = x_max
self.f_co_occurrence_matrix = self.f(x_max, alpha)
self.log_co_occurrence_matrix = self.co_occurrence_matrix.tocsr().log1p()
def f(self, x_max, alpha):
def _f(x):
return min(x / x_max, 1) ** alpha
_f_vectorized = np.vectorize(_f, otypes=[np.float])
result = self.co_occurrence_matrix.tocsr()
result.data = _f_vectorized(self.co_occurrence_matrix.tocsr().data)
return result
def train(self, corpus: List[List[str]], number_of_iterations: int, alpha: float = 0.75,
x_max: int = 100, optimizer: str = "sgd",
learning_rate: float = 0.1, optimizer_params: dict = {}, display_iteration: int=1):
self.build_co_occurrence_matrix(corpus=corpus, alpha=alpha, x_max=x_max)
self.initialize_word_vectors_and_biases()
id_pairs = [(x, y) for x, y in zip(*self.co_occurrence_matrix.nonzero())]
if optimizer == 'adagrad':
sum_grad_w_sq = np.zeros((self.vocab_size, self._word_vector_dimension))
sum_grad_b_sq = np.zeros(self.vocab_size)
sum_grad_w_tilde_sq = np.zeros((self.vocab_size, self._word_vector_dimension))
sum_grad_b_tilde_sq = np.zeros(self.vocab_size)
elif optimizer == 'rmsprop':
mean_square_w = np.zeros((self.vocab_size, self._word_vector_dimension))
mean_square_w_tilde = np.zeros((self.vocab_size, self._word_vector_dimension))
mean_square_b = np.zeros(self.vocab_size)
mean_square_b_tilde = np.zeros(self.vocab_size)
for iteration in range(number_of_iterations):
shuffle(id_pairs)
total_cost = 0
for i, j in id_pairs:
inner_cost = (self.W[i, :].transpose().dot(self.W_tilde[j, :]) + self.b[i] + self.b_tilde[j] -
self.log_co_occurrence_matrix[i, j])
grad_b_tilde_j = grad_b_i = self.f_co_occurrence_matrix[i, j] * inner_cost
grad_w_i = self.W_tilde[j, :] * grad_b_i
grad_w_tilde_j = self.W[i, :] * grad_b_tilde_j
if optimizer == 'sgd':
self.b[i] = sgd(self.b[i], grad_b_i, learning_rate)
self.b_tilde[j] = sgd(self.b_tilde[j], grad_b_tilde_j, learning_rate)
self.W[i] = sgd(self.W[i], grad_w_i, learning_rate)
self.W_tilde[j] = sgd(self.W_tilde[j], grad_w_tilde_j, learning_rate)
elif optimizer == 'adagrad':
sum_grad_w_sq[i] += grad_w_i ** 2
sum_grad_b_sq[i] += grad_b_i ** 2
sum_grad_w_tilde_sq[j] += grad_w_tilde_j ** 2
sum_grad_b_tilde_sq[j] += grad_b_tilde_j ** 2
self.b[i] = adagrad(self.b[i], grad_b_i, sum_grad_b_sq[i], learning_rate)
self.b_tilde[j] = adagrad(self.b_tilde[j], grad_b_tilde_j, sum_grad_b_tilde_sq[j], learning_rate)
self.W[i] = adagrad(self.W[i], grad_w_i, sum_grad_w_sq[i], learning_rate)
self.W_tilde[j] = adagrad(self.W_tilde[j], grad_w_tilde_j, sum_grad_w_tilde_sq[j], learning_rate)
elif optimizer == 'rmsprop':
self.b[i], mean_square_b[i] = rmsprop(self.b[i], grad_b_i, mean_square_b[i], learning_rate,
**optimizer_params)
self.b_tilde[j], mean_square_b_tilde[j] = rmsprop(self.b_tilde[j], grad_b_tilde_j,
mean_square_b_tilde[j], learning_rate,
**optimizer_params)
self.W[i], mean_square_w[i] = rmsprop(self.W[i], grad_w_i, mean_square_w[i], learning_rate,
**optimizer_params)
self.W_tilde[j], mean_square_w_tilde[j] = rmsprop(self.W_tilde[j], grad_w_tilde_j,
mean_square_w_tilde[j], learning_rate,
**optimizer_params)
cost = self.f_co_occurrence_matrix[i, j] * inner_cost
total_cost += cost
if iteration % display_iteration == 0:
logging.info('Iteration: {}, Total Cost: {}'.format(iteration, total_cost))
@property
def word_mapping(self):
return {self.id_to_word_map[i]: (self.W[i] + self.W_tilde[i])/2 for i in range(self.vocab_size)}
<file_sep>/requirements.txt
numpy == 1.15.4
scipy == 1.1.0
nltk == 3.4
|
c90a0ceb1291e21f2ccaae8c0bc137afe8e45a9f
|
[
"Markdown",
"Python",
"Text"
] | 3 |
Markdown
|
SiavashMT/GloVe
|
6cd85bc61534f17cf818626a54e9cda07da9caa4
|
25c5f441cf90772f41a81dbea9c86e541eccfa06
|
refs/heads/master
|
<repo_name>mschumak/StainAnalysis-plugin<file_sep>/README.md
<h1 align="center">Stain Analysis Plugin</h1>
This plugin calculates the percentage area of a region of interest which has been stained using an IHC biomarker. The color deconvolution method described by Ruifrok <sup>[1]</sup> is used to separate the color channels. The stain of interest is selected and a threshold image is then obtained by applying a linear thresholding algorithm on the deconvolved image. Finally, the percentage of pixels that have been stained is calculated using the threshold image. All the processing is done in the highest resolution.
## User Manual
##### 1. Open the WSI image and define the region of interest (ROI).
##### 2. Load the “Stain Analysis” plugin from the pulldown list of Algorithms (Fig 1.)
<div align="right">
<img src="https://github.com/sedeen-piip-plugins/StainAnalysis-plugin/blob/master/Images/StainAnalysis_1_1.png"/>
</div>
<div align="right">
<h6><strong>Fig1.</strong> Select the Stain Analysis Plugin.</h6>
</div>
##### 3. Select the stain using the Selected Stain pulldown menu (Fig 2.). The plugin provides a number of "built in" stain vectors: Hematoxylin and Eosin (H&E), Hematoxylin and DAB (H DAB), and Hematoxylin, Eosin and DAB (H&E DAB) [1] .
<div align="right">
<img src="https://github.com/sedeen-piip-plugins/StainAnalysis-plugin/blob/master/Images/StainAnalysis_1_2.png"/>
</div>
<div align="right">
<h6><strong>Fig2.</strong> Select stain option.</h6>
</div>
##### 4. Users can also determine their own vectors to achieve an accurate stain separation. This option is available in two ways: “From ROI” or “Load From File”. If the “From ROI” option is set, users also need to choose three ROIs to compute the stain vectors. Select small ROIs areas which are intensely stained with only one of the stain, without empty background. If the staining method uses only 2 colors instead of 3, for the 3rd selection just select a small ROI from the background. The plug-in will compute the stain vectors based on three regions <sup>[1]</sup>.
##### The computed stain vectors will be saved in default directory (the Sedeen folder in the same directory as the image): "Path to the image/sedeen/" as “StainsFile.csv” file for future use. The stain vectors can be provided by “.csv” file by selecting “Load From File” option. An example of the “.csv” file will be provided in the plug-in directory. This file needs to be copied in default directory: “Path to the image/sedeen/”.
##### 5. The stain of interest should be selected from the Display pull down menu.
##### 6. If desired, modify the Threshold value which is in the range 0.0 to 300.0.
##### 7. The Processing ROI option allows the % staining to be calculated over a user defined ROI. (Fig 3). If an ROI is not selected then the calculation will be done over the displayed region.
<div align="right">
<img src="https://github.com/sedeen-piip-plugins/StainAnalysis-plugin/blob/master/Images/StainAnalysis_1_3.png"/>
</div>
<div align="right">
<h6><strong>Fig3.</strong> Select the Processing ROI.</h6>
</div>
##### 8. Clicking on the Run button will execute the algorithm. The calculated % area is shown in the results panel. A color overlay shows which pixels are included in the % stain calculation. Use the Show Result checkbox to toggle the overlay on and off. The overlay is generated at the resolution of the displayed image but the calculation is carried out at full image resolution.
<div align="right">
<img src="https://github.com/sedeen-piip-plugins/StainAnalysis-plugin/blob/master/Images/StainAnalysis_1_4.png"/>
</div>
<div align="right">
<h6><strong>Fig4.</strong> Select the Processing ROI.</h6>
</div>
<b> <sup> [1] </sup> </b> <sub> <NAME> and <NAME>, “Quantification of histochemical staining by color deconvolution,” Anal. Quant. Cytol. Histol., vol. 23, no. 4, pp. 291–299, 2001. </sub>
## Authors
Stain Analysis Plugin was developed by **<NAME>** and **<NAME>**, Martel lab at Sunnybrook Research Institute (SRI), University of Toronto and was partially funded by [NIH grant](https://itcr.cancer.gov/funding-opportunities/pathology-image-informatics-platform-visualization-analysis-and-management).
## Copyright & License
Copyright (c) 2021 Sunnybrook Research Institute
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<file_sep>/StainVectorMath.h
/*=============================================================================
*
* Copyright (c) 2021 Sunnybrook Research Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*=============================================================================*/
#ifndef SEDEEN_SRC_PLUGINS_STAINANALYSIS_STAINVECTORMATH_H
#define SEDEEN_SRC_PLUGINS_STAINANALYSIS_STAINVECTORMATH_H
#include <vector>
#include <array>
#include <cmath>
#include <numeric>
#include <algorithm>
///A class with static methods to operate on stain vectors
class StainVectorMath
{
public:
///Sort order for the stain vectors in SortStainVectors.
enum SortOrder {
ASCENDING,
DESCENDING
};
public:
///Compute the inverse of a 3x3 matrix using Boost qvm
static void Compute3x3MatrixInverse(const double (&inputMat)[9], double (&inversionMat)[9]);
///Make a 3x3 matrix, expressed as a 9-element array, have unitary rows. Preserve rows of zeros
static void Make3x3MatrixUnitary(const double (&inputMat)[9], double (&unitaryMat)[9]);
///Check the Norm values of sets of three input elements, replace with a unitary row if zero
static void ConvertZeroRowsToUnitary(const double (&inputMat)[9], double (&unitaryMat)[9]);
///Check the norm values of sets of elements, normalize the row of values in the third argument and replace zero rows with that
static void ConvertZeroRowsToUnitary(const double (&inputMat)[9], double (&unitaryMat)[9], const double (&replacementVals)[3]);
///Check whether rows of the given matrix sum to zero, but do not have all zero values
static std::array<bool, 3> RowSumZeroCheck(const double (&inputMat)[9]);
///Multiply a 3x3 matrix and a 3x1 vector to produce a 3x1 vector
static void Multiply3x3MatrixAndVector(const double (&inputMat)[9], const double (&inputVec)[3], double (&outputVec)[3]);
///Sort a 9-element stain vector profile according to R, G, and B values, in ascending or descending order depending on the third argument value.
static void SortStainVectors(const double(&inputMat)[9], double(&outputMat)[9], const int &sortOrder = SortOrder::DESCENDING);
///Return an array of values of type Ty with size N normalized to unit length. Returns input array if norm is 0.
template<class Ty, std::size_t N>
static std::array<Ty, N> NormalizeArray(std::array<Ty, N> arr) {
std::array<Ty, N> out;
Ty norm = Norm<std::array<Ty, N>::iterator, Ty>(arr.begin(), arr.end());
//Check if the norm is zero. Return the input array if so.
//Compare against C++11 zero initialization of the type Ty
//Also check if the input container is empty
if ((norm == Ty{}) || (arr.empty())) {
return arr;
}
else {
//Copy the input array to the out array
std::copy(arr.begin(), arr.end(), out.begin());
//Iterate through the out array, divide values by norm
for (auto p = out.begin(); p != out.end(); ++p) {
*p = static_cast<Ty>(*p / norm);
}
return out;
}
}//end NormalizeArray
///Calculate the norm of all the elements in a container, where each element is of type Ty
template<typename Iter_T, class Ty>
static Ty Norm(Iter_T first, Iter_T last) {
return static_cast<Ty>(sqrt(std::inner_product(first, last, first, Ty{}))); //Use C++11 zero initialization of type Ty
}//end Norm
};
#endif
<file_sep>/ColorDeconvolutionKernel.h
/*=============================================================================
*
* Copyright (c) 2021 Sunnybrook Research Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*=============================================================================*/
#ifndef SEDEEN_SRC_IMAGE_FILTER_KERNELS_COLORDECONVOLUTION_H
#define SEDEEN_SRC_IMAGE_FILTER_KERNELS_COLORDECONVOLUTION_H
#include "Global.h"
#include "Geometry.h"
#include "Image.h"
#include "image/filter/Kernel.h"
#include "global/ColorSpace.h"
#include <cstdio>
#include <sstream>
#include <memory>
#include <filesystem> //Requires C++17
//Plugin includes
#include "StainProfile.h"
namespace sedeen {
namespace image {
namespace tile {
/// \ingroup algorithm_kernels
/// Color Deconvolution
/// Apply colour deconvolution method described in:
//Ruifrok AC, Johnston DA. Quantification of histochemical
//staining by color deconvolution. Analytical & Quantitative
//Cytology & Histology 2001; 23: 291-299
class PATHCORE_IMAGE_API ColorDeconvolution : public Kernel {
public:
/// Display options for the output image
enum DisplayOptions {
STAIN1,
STAIN2,
STAIN3
};
/// Creates a colour deconvolution Kernel with selected
// color-deconvolution matrix
//
/// \param
///
explicit ColorDeconvolution(DisplayOptions displayOption, std::shared_ptr<StainProfile>,
bool applyThreshold, double threshold, bool stainQuantityOnly = false);
virtual ~ColorDeconvolution();
private:
/// \cond INTERNAL
virtual RawImage doProcessData(const RawImage &source);
virtual const ColorSpace& doGetColorSpace() const;
///Given an input RGBA image and stain vectors, output either an RGBA or a Grayscale image
RawImage separateStains(const RawImage &source, double (&stainVec)[9]);
///Apply threshold to source image, output RGB or averaged grayscale if stainQuantityOnly is false
RawImage thresholdOnly(const RawImage &source);
///Arguments are: the 3 OD values, the 9-element RGB output, the 3-element stain quantity output, the stain vector matrix, and the inverse of the matrix
void GetSeparateColorsForPixel(double(&pixelOD)[3], double(&RGB_sep)[9],
double(&quant)[3], double(&stainVec_matrix)[9], double(&inverse_matrix)[9]);
///Original argument list (overload)
void GetSeparateColorsForPixel(double (&pixelOD)[3], double (&RGB_sep)[9],
double (&stainVec_matrix)[9], double (&inverse_matrix)[9]);
///Get the boolean value of m_grayscaleQuanityOnly
const bool& GetGrayscaleQuantityOnly() const { return m_grayscaleQuantityOnly; }
///Set the output color space
void SetOutputColorSpace(const ColorSpace& os) { m_outputColorSpace = os; }
// rows of matrix are stains, columns are color channels
ColorDeconvolution::DisplayOptions m_DisplayOption;
bool m_grayscaleQuantityOnly;
bool m_applyThreshold;
double m_threshold;
//Normalization for grayscale stain quantities: -log_10(1/255) is 2.40, so set 2.55 to be channel 255 = norm factor 100
const double m_grayscaleNormFactor;
///ColorSpace of the source (input) image
///ColorSpace of the output image
ColorSpace m_outputColorSpace;
std::shared_ptr<StainProfile> m_stainProfile;
/// \endcond
};
} // namespace tile
} // namespace image
} // namespace sedeen
#endif<file_sep>/CMakeLists.txt
PROJECT( StainAnalysis-plugin )
CMAKE_MINIMUM_REQUIRED( VERSION 3.13 )
# Enable C++17 features
SET(CMAKE_CXX_STANDARD 17)
INCLUDE(FetchContent)
#Note which version of Sedeen Viewer this plugin was last compiled and tested with
SET(SEDEENSDK_VERSION "5.5.0.20200610" CACHE STRING "Last version of Sedeen Viewer the plugin was compiled and tested with")
# Define project description variables
SET( DISPLAY_NAME_TEXT "Stain Analysis and Separation" CACHE STRING "Name of the plugin as it should be displayed in Sedeen Viewer")
SET( SUPPORT_URL_TEXT "http://pathcore.com/support/plugin/info/${PROJECT_NAME}" CACHE STRING "Location users can find help with the plugin" )
SET( DEVELOPER_TEXT "Sunnybrook Research Institute" CACHE STRING "Name of the author or organization that created the plugin" )
# Load the Sedeen dependencies
SET(PROGRAMFILESX86 "PROGRAMFILES\(X86\)")
FIND_PACKAGE( SEDEENSDK REQUIRED
HINTS ../../..
"$ENV{${PROGRAMFILESX86}}/Sedeen Viewer SDK/v5.5.0.20200610/msvc2017"
"$ENV{PROGRAMFILES}/Sedeen Viewer SDK/v5.5.0.20200610/msvc2017" )
# Load the included OpenCV libs
FIND_PACKAGE(SEDEENSDK_OPENCV REQUIRED
HINTS ../../..
"$ENV{${PROGRAMFILESX86}}/Sedeen Viewer SDK/v5.5.0.20200610/msvc2017"
"$ENV{PROGRAMFILES}/Sedeen Viewer SDK/v5.5.0.20200610/msvc2017" )
#Add OpenMP for parallel programming
#This is not essential to the plugin and can be omitted
FIND_PACKAGE(OpenMP)
IF(OPENMP_FOUND)
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
ENDIF()
IF(NOT BOOST_ROOT)
SET(BOOST_ROOT "BOOST_ROOT-NOTFOUND" CACHE PATH "Preferred installation prefix of the Boost C++ library")
ENDIF()
IF(NOT BOOST_VERSION)
SET(BOOST_VERSION "BOOST_VERSION-NOTFOUND" CACHE STRING "Boost library version number")
ENDIF()
FIND_PACKAGE(Boost ${BOOST_VERSION} REQUIRED COMPONENTS)
INCLUDE(cmake/CMakeRC.cmake)
cmrc_add_resource_library(stain-resources ALIAS stain::rc NAMESPACE stain
defaultprofiles/HematoxylinPDABFromRJ.xml
defaultprofiles/HematoxylinPEosinFromRJ.xml
defaultprofiles/HematoxylinPEosinPDABFromRJ.xml
defaultprofiles/HematoxylinPEosinSample.xml)
# Fetch TinyXML2 files. Do not build as a subproject
FetchContent_Declare(
TinyXML2
GIT_REPOSITORY https://github.com/leethomason/tinyxml2.git
GIT_TAG 1dee28e51f9175a31955b9791c74c430fe13dc82
)
#61a4c7d507322c9f494f5880d4c94b60e4ce9590
# Check if the tinyxml2 files have already been populated
FetchContent_GetProperties(TinyXML2)
STRING(TOLOWER "TinyXML2" TinyXML2Name)
IF(NOT ${TinyXML2Name}_POPULATED)
#Fetch TinyXML2 using the details from FetchContent_Declare
FetchContent_Populate(TinyXML2)
ENDIF()
#Fetch the OpticalDensityThreshold respository. Do not build as a subproject
FetchContent_Declare(
OpticalDensityThreshold
GIT_REPOSITORY https://github.com/sedeen-piip-plugins/OpticalDensityThreshold.git
GIT_TAG de819961664eb76b11dd7c4782c1f10226b8db62
)
FetchContent_GetProperties(OpticalDensityThreshold)
STRING(TOLOWER "OpticalDensityThreshold" OpticalDensityThresholdName)
IF(NOT ${OpticalDensityThresholdName}_POPULATED)
FetchContent_Populate(OpticalDensityThreshold)
ENDIF()
SET(OPTICAL_DENSITY_THRESHOLD_DIR ${${OpticalDensityThresholdName}_SOURCE_DIR})
INCLUDE_DIRECTORIES( ${INCLUDE_DIRECTORIES}
${SEDEENSDK_INCLUDE_DIR}
${SEDEENSDK_OPENCV_INCLUDE_DIR}
${BOOST_ROOT}
${${TinyXML2Name}_SOURCE_DIR}
${OPTICAL_DENSITY_THRESHOLD_DIR}
)
LINK_DIRECTORIES( ${LINK_DIRECTORIES}
${SEDEENSDK_LIBRARY_DIR}
${SEDEENSDK_OPENCV_LIBRARY_DIR}
)
# Build the code into a module library
ADD_LIBRARY( ${PROJECT_NAME} MODULE
${PROJECT_NAME}.cpp
${PROJECT_NAME}.h
${${TinyXML2Name}_SOURCE_DIR}/tinyxml2.h
${${TinyXML2Name}_SOURCE_DIR}/tinyxml2.cpp
${OPTICAL_DENSITY_THRESHOLD_DIR}/ODConversion.h
${OPTICAL_DENSITY_THRESHOLD_DIR}/ODThresholdKernel.h
${OPTICAL_DENSITY_THRESHOLD_DIR}/ODThresholdKernel.cpp
StainProfile.h StainProfile.cpp
ColorDeconvolutionKernel.h ColorDeconvolutionKernel.cpp
StainVectorMath.h StainVectorMath.cpp
)
# Link the library against the Sedeen SDK libraries
TARGET_LINK_LIBRARIES( ${PROJECT_NAME}
${SEDEENSDK_LIBRARIES}
${SEDEENSDK_OPENCV_LIBRARIES}
stain::rc
)
#Create or update the .info file in the build directory
STRING( TIMESTAMP DATE_CREATED_TEXT "%Y-%m-%d" )
CONFIGURE_FILE( "infoTemplate.info.in" "${PROJECT_NAME}.info" )
#Set the relative directory where the plugin should be located
SET( PLUGIN_RELATIVE_DIR "plugins/cpp/piip/${PROJECT_NAME}" )
# Set the install destination directory
IF( NOT PLUGIN_DESTINATION_DIR )
IF( ${SEDEEN_FOUND} )
SET( TEMPPLUGINDIR "${PATHCORE_DIR}/${PLUGIN_RELATIVE_DIR}" )
ELSE()
SET( TEMPPLUGINDIR "PLUGIN_DESTINATION_DIR-NOTFOUND" )
MESSAGE( SEND_ERROR "PLUGIN_DESTINATION_DIR not found. Set this to the target installation directory of the plugin within Sedeen Viewer (e.g. $ENV{PROGRAMFILES}/Sedeen Viewer/plugins/cpp/piip/${PROJECT_NAME}).")
ENDIF()
SET(PLUGIN_DESTINATION_DIR ${TEMPPLUGINDIR} CACHE PATH "Installation directory for the plugin within Sedeen Viewer")
ENDIF()
# Install the plugin and .info file in the PLUGIN_DESTINATION_DIR directory
IF( ${SEDEEN_FOUND} )
INSTALL(TARGETS ${PROJECT_NAME} LIBRARY
DESTINATION "${PLUGIN_DESTINATION_DIR}")
INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.info"
DESTINATION "${PLUGIN_DESTINATION_DIR}" )
INSTALL(DIRECTORY "${SEDEENSDK_DIR}/bin/"
DESTINATION "${PLUGIN_DESTINATION_DIR}"
FILES_MATCHING PATTERN "opencv*0.dll" )
ENDIF()
#For debugging: shows all variables and their values
#get_cmake_property(_variableNames VARIABLES)
#list (SORT _variableNames)
#foreach (_variableName ${_variableNames})
# message(STATUS "${_variableName}=${${_variableName}}")
#endforeach()
<file_sep>/StainAnalysis-plugin.cpp
/*=============================================================================
*
* Copyright (c) 2021 Sunnybrook Research Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*=============================================================================*/
// StainAnalysis-plugin.cpp : Defines the exported functions for the DLL application.
//
#include "StainAnalysis-plugin.h"
#include "ODConversion.h"
#include <sstream>
#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
// Sedeen headers
#include "Algorithm.h"
#include "Geometry.h"
#include "Global.h"
#include "Image.h"
#include "image/io/Image.h"
#include "image/tile/Factory.h"
#include <cmrc/cmrc.hpp>
CMRC_DECLARE(stain);
// Poco header needed for the macros below
#include <Poco/ClassLibrary.h>
// Declare that this object has AlgorithmBase subclasses
// and declare each of those sub-classes
POCO_BEGIN_MANIFEST(sedeen::algorithm::AlgorithmBase)
POCO_EXPORT_CLASS(sedeen::algorithm::StainAnalysis)
POCO_END_MANIFEST
namespace sedeen {
namespace algorithm {
StainAnalysis::StainAnalysis()
: m_displayArea(),
m_openProfile(),
m_stainSeparationAlgorithm(),
m_stainVectorProfile(),
m_regionToProcess(),
m_stainResultType(),
m_stainToDisplay(),
m_applyDisplayThreshold(),
m_displayThreshold(),
m_saveSeparatedImage(),
m_saveFileFormat(),
m_saveFileAs(),
m_result(),
m_outputText(),
m_report(""),
m_displayThresholdDefaultVal(0.20),
m_displayThresholdMaxVal(3.0),
m_thresholdStepSizeVal(0.01),
m_pixelWarningThreshold(1e8), //100,000,000 pixels, ~400 MB
m_colorDeconvolution_factory(nullptr)
{
// Build the list of stain vector file names
m_stainProfileFullPathNames.push_back(""); // Leave a blank place for the loaded file
// HematoxylinPEosinSample
m_stainProfileFullPathNames.push_back(HematoxylinPEosinSampleFilename());
// HematoxylinPEosin from Ruifrok and Johnston
m_stainProfileFullPathNames.push_back(HematoxylinPEosinFromRJFilename());
// HematoxylinPDAB from Ruifrok and Johnston
m_stainProfileFullPathNames.push_back(HematoxylinPDABFromRJFilename());
// HematoxylinPEosinPDAB from Ruifrok and Johnston
m_stainProfileFullPathNames.push_back(HematoxylinPEosinPDABFromRJFilename());
//Create stain vector profiles for the loaded and default profiles, push to vector
//Loaded
m_LoadedStainProfile = std::make_shared<StainProfile>();
m_stainProfileList.push_back(m_LoadedStainProfile);
m_stainVectorProfileOptions.push_back("Loaded From File");
//Loop over the rest
for (auto it = m_stainProfileFullPathNames.begin()+1; it != m_stainProfileFullPathNames.end(); ++it) {
std::shared_ptr<StainProfile> tsp = std::make_shared<StainProfile>();
//Convert path to string, read stain profile, and check whether the read was successful
auto const fs = cmrc::stain::get_filesystem();
if (auto const is_file = fs.is_file((*it).generic_string())) {
auto const file = fs.open((*it).generic_string());
if (tsp->readStainProfile(file.begin(), file.size())) {
m_stainProfileList.push_back(tsp);
// Get the name of the profile
m_stainVectorProfileOptions.push_back(tsp->GetNameOfStainProfile());
continue;
}
}
// make a dummy one
m_stainProfileList.push_back(std::make_shared<StainProfile>());
m_stainVectorProfileOptions.push_back("Profile failed to load");
}
//Populate the analysis model and separation algorithm lists with a temporary StainProfile
auto tempStainProfile = std::make_shared<StainProfile>();
//The stain analysis model options
m_stainAnalysisModelOptions = tempStainProfile->GetStainAnalysisModelOptions();
//The stain separation algorithm options
m_separationAlgorithmOptions = tempStainProfile->GetStainSeparationAlgorithmOptions();
//Clean up
tempStainProfile.reset();
//Define the list of results to display
//(grayscale quantity versus re-coloured with stain vectors)
m_stainResultTypeOptions.push_back("Stain RGB colours");
m_stainResultTypeOptions.push_back("Grayscale quantity");
//Define the default list of names of stains to display
m_stainToDisplayOptions.push_back("Stain 1");
m_stainToDisplayOptions.push_back("Stain 2");
m_stainToDisplayOptions.push_back("Stain 3");
//Choose what format to write the separated images in
//Define the list of possible save types (flat image vs whole slide image)
m_saveFileFormatOptions.push_back("Flat image (tif/png/bmp/gif/jpg)");
//TODO: enable saving a whole slide image
//m_saveFileFormatOptions.push_back("Whole Slide Image (.svs)");
//List the actual extensions that should be included in the save dialog window
m_saveFileExtensionText.push_back("tif");
m_saveFileExtensionText.push_back("png");
m_saveFileExtensionText.push_back("bmp");
m_saveFileExtensionText.push_back("gif");
m_saveFileExtensionText.push_back("jpg");
//TODO: enable saving a whole slide image
//m_saveFileExtensionText.push_back("svs");
}//end constructor
StainAnalysis::~StainAnalysis() {
}//end destructor
void StainAnalysis::init(const image::ImageHandle& image) {
if (isNull(image)) return;
//
// bind algorithm members to UI and initialize their properties
// Bind system parameter for current view
m_displayArea = createDisplayAreaParameter(*this);
//Allow the user to choose a stain vector profile xml file
sedeen::file::FileDialogOptions openFileDialogOptions = defineOpenFileDialogOptions();
m_openProfile = createOpenFileDialogParameter(*this, "Stain Profile File",
"Open a file containing a stain vector profile",
openFileDialogOptions, true);
m_stainVectorProfile = createOptionParameter(*this, "Stain Vector Profile",
"Select the stain vector profile to use; either from the file, or one of the pre-defined profiles", 0,
m_stainVectorProfileOptions, false);
m_regionToProcess = createGraphicItemParameter(*this, "Apply to ROI (None for Display Area)",
"Choose a Region of Interest on which to apply the stain separation algorithm. Choosing no ROI will apply the stain separation to the whole slide image.",
true); //optional. None means apply to whole slide
//List of result types to display (re-coloured with stain vectors or grayscale quantity)
m_stainResultType = createOptionParameter(*this, "Result Type",
"Choose the type of separated image to display (RGB colours from stain vectors or grayscale stain quantity",
0, m_stainResultTypeOptions, false);
//List of options of the stains to be shown
m_stainToDisplay = createOptionParameter(*this, "Show Separated Stain",
"Choose which of the defined stains to show in the display area", 0, m_stainToDisplayOptions, false);
//User can choose whether to apply the threshold or not
m_applyDisplayThreshold = createBoolParameter(*this, "Apply Threshold",
"If Apply Threshold is set, the threshold value in the slider below will be applied to the stain-separated images, including in the saved images",
true, false); //default value, optional
// Init the user defined threshold value
//auto color = getColorSpace(image);
//auto max_value = (1 << bitsPerChannel(color)) - 1;
m_displayThreshold = createDoubleParameter(*this,
"OD Threshold", // Widget label
"Threshold value to apply to the separated images. Images will be saved with this threshold applied.", // Widget tooltip
m_displayThresholdDefaultVal, // Initial value
0.0, // minimum value
m_displayThresholdMaxVal, // maximum value
m_thresholdStepSizeVal,
false);
//Allow the user to write separated images to file
m_saveSeparatedImage = createBoolParameter(*this, "Save Separated Image",
"If checked, the final image will be saved to an output file, of the type chosen in the Save File Format list.",
false, false);
m_saveFileFormat = createOptionParameter(*this, "Save File Format",
"Output image files can be saved as one of five flat image types.",
0, m_saveFileFormatOptions, false);
//Allow the user to choose where to save the image files
sedeen::file::FileDialogOptions saveFileDialogOptions = defineSaveFileDialogOptions();
m_saveFileAs = createSaveFileDialogParameter(*this, "Save As...",
"The output image will be saved to this file name. If the file name includes an extension of type TIF/PNG/BMP/GIF/JPG, it will override the Save File Format choice.",
saveFileDialogOptions, true);
// Bind result
m_outputText = createTextResult(*this, "Text Result");
m_result = createImageResult(*this, "StainAnalysisResult");
}//end init
void StainAnalysis::run() {
//These have to be checked before the parameters are used
//Check if the stain profile has changed
bool stainProfile_changed = m_stainVectorProfile.isChanged();
//Check whether the stain profile file has changed
bool loadedFile_changed = m_openProfile.isChanged();
//Get which of the stain vector profiles has been selected by the user
int chosenProfileNum = m_stainVectorProfile;
//The user does not have to select a file,
//but if none is chosen, one of the defaults must be selected
bool loadResult = LoadStainProfileFromFileDialog();
//Check whether the user selected to load from file and if so, that it loaded correctly
if (chosenProfileNum == 0 && (loadResult == false)) {
m_outputText.sendText("The stain profile file cannot be read. Please click Reset before loading a different file, or choose one of the default profiles.");
return;
}
//else
// Has display area changed
bool display_changed = m_displayArea.isChanged();
//Get the stain profile that should be used
//Use the vector::at operator to do bounds checking
std::shared_ptr<StainProfile> chosenStainProfile;
try {
chosenStainProfile = m_stainProfileList.at(chosenProfileNum);
}
catch (const std::out_of_range& rangeerr) {
rangeerr.what();
//The index is out of range. Throw error message
m_outputText.sendText("The stain profile cannot be found. Choose a default stain profile.");
return;
}
if (chosenStainProfile == nullptr) {
m_outputText.sendText("The stain profile did not load properly. Click Reset and try another stain profile.");
return;
}
//Check the chosenStainProfile to ensure it is built correctly. End running if not
bool checkProfile = chosenStainProfile->CheckProfile();
if (!checkProfile) {
//Something is wrong with the selected stain profile. Show error message, stop running
m_outputText.sendText("The chosen stain profile did not load properly. Click Reset and try another stain profile.");
return;
}
// Build the operational pipeline
bool pipeline_changed = buildPipeline(chosenStainProfile, (stainProfile_changed || loadedFile_changed));
// Update results
if ( pipeline_changed || display_changed || stainProfile_changed || loadedFile_changed ) {
//Check whether the user wants to write to image files, that the field is not blank,
//and that the file can be created or written to
std::string outputFilePath;
if (m_saveSeparatedImage == true) {
//Get the full path file name from the file dialog parameter
sedeen::algorithm::parameter::SaveFileDialog::DataType fileDialogDataType = this->m_saveFileAs;
outputFilePath = fileDialogDataType.getFilename();
//Is the file field blank?
if (outputFilePath.empty()) {
m_outputText.sendText("The filename is blank. Please choose a file to save the image to, or uncheck Save Separated Images.");
return;
}
//Does the file exist or can it be created, and can it be written to?
bool validFileCheck = StainProfile::checkFile(outputFilePath, "w");
if (!validFileCheck) {
m_outputText.sendText("The file name selected cannot be written to. Please choose another, or check the permissions of the directory.");
return;
}
//Does it have a valid extension? RawImage.save relies on the extension to determine save format
std::string theExt = getExtension(outputFilePath);
int extensionIndex = findExtensionIndex(theExt);
//findExtensionIndex returns -1 if not found
if (extensionIndex == -1) {
std::stringstream ss;
ss << "The extension of the file is not a valid type. The file extension must be: ";
auto vec = m_saveFileExtensionText;
for (auto it = vec.begin(); it != vec.end()-1; ++it) {
ss << (*it) << ", ";
}
std::string last = vec.back();
ss << "or " << last << ". Choose a correct file type and try again." << std::endl;
m_outputText.sendText(ss.str());
return;
}
//Check whether the output image as specified will have more pixels than the given threshold
double estPixels = EstimateOutputImageSize();
bool largeOutputFlag = (estPixels > m_pixelWarningThreshold) ? true : false;
std::string estStorageSize = EstimateImageStorageSize(estPixels);
std::stringstream fileSaveUpdate;
if (largeOutputFlag) {
//The output file size will be large and will take a long time to save
fileSaveUpdate << "WARNING: The region to be saved is large. This may take a long time to complete." << std::endl;
fileSaveUpdate << "The estimated size of the output file to be saved is " << estStorageSize << std::endl;
fileSaveUpdate << "Saving image as " << outputFilePath << std::endl;
}
else {
fileSaveUpdate << "Stain separation and image saving in progress." << std::endl;
fileSaveUpdate << "Saving image as " << outputFilePath << std::endl;
}
//Write temporary text to the result window.
//It will be replaced when file saving is finished.
m_outputText.sendText(fileSaveUpdate.str());
}
//This is where the magic happens.
if (nullptr != m_colorDeconvolution_factory) {
m_result.update(m_colorDeconvolution_factory, m_displayArea, *this);
}
//A previous version included an "intermediate result" here, to display
//a blurry temporary image (rather than just black) while calculations proceeded
// Update the output text report
if (false == askedToStop()) {
std::string report = generateCompleteReport(chosenStainProfile);
//If an output file should be written and the algorithm ran successfully, save images
if (m_saveSeparatedImage == true) {
//Save the result as a flat image file
bool saveResult = SaveFlatImageToFile(outputFilePath);
//Check whether saving was successful
std::stringstream ss;
if (saveResult) {
ss << std::endl << "Stain-separated image saved as " << outputFilePath << std::endl;
report.append(ss.str());
}
else {
ss << std::endl << "Saving the stain-separated image failed. Please check the file name and directory permissions." << std::endl;
report.append(ss.str());
}
}
//Finally, send the report to the results window
m_outputText.sendText(report);
}
}//end if UI changes
// Ensure we run again after an abort
// a small kludge that causes buildPipeline() to return TRUE
if (askedToStop()) {
m_colorDeconvolution_factory.reset();
}
}//end run
bool StainAnalysis::buildPipeline(std::shared_ptr<StainProfile> chosenStainProfile, bool somethingChanged) {
using namespace image::tile;
bool pipeline_changed = false;
// Get source image properties
auto source_factory = image()->getFactory();
auto source_color = source_factory->getColorSpace();
//Set this one to change the stain profile
double conv_matrix[9] = { 0.0 };
bool doProcessing = false;
if ( pipeline_changed || somethingChanged
|| m_regionToProcess.isChanged()
|| m_stainSeparationAlgorithm.isChanged()
|| m_stainVectorProfile.isChanged()
|| m_stainResultType.isChanged()
|| m_stainToDisplay.isChanged()
|| m_applyDisplayThreshold.isChanged()
|| m_displayThreshold.isChanged()
|| m_displayArea.isChanged()
|| m_saveSeparatedImage.isChanged()
|| m_saveFileFormat.isChanged()
|| m_saveFileAs.isChanged()
|| (nullptr == m_colorDeconvolution_factory) )
{
//Choose value from the enumeration in ColorDeconvolution
image::tile::ColorDeconvolution::DisplayOptions DisplayOption;
switch (m_stainToDisplay)
{
case 0:
DisplayOption = image::tile::ColorDeconvolution::DisplayOptions::STAIN1;
break;
case 1:
DisplayOption = image::tile::ColorDeconvolution::DisplayOptions::STAIN2;
break;
case 2:
DisplayOption = image::tile::ColorDeconvolution::DisplayOptions::STAIN3;
break;
default:
break;
}
//Kernel is affected by the display threshold settings, and choice of stain quantity or colour image
auto colorDeconvolution_kernel =
std::make_shared<image::tile::ColorDeconvolution>(DisplayOption, chosenStainProfile,
m_applyDisplayThreshold, m_displayThreshold, m_stainResultType);
// Create a Factory for the composition of these Kernels
auto non_cached_factory =
std::make_shared<FilterFactory>(source_factory, colorDeconvolution_kernel);
// Wrap resulting Factory in a Cache for speedy results
m_colorDeconvolution_factory =
std::make_shared<Cache>(non_cached_factory, RecentCachePolicy(30));
pipeline_changed = true;
}//end if parameter values changed
// Constrain processing to the region of interest provided, if set
std::shared_ptr<GraphicItemBase> region = m_regionToProcess;
if (pipeline_changed && (nullptr != region)) {
// Constrain the output of the pipeline to the region of interest provided
auto constrained_factory = std::make_shared<RegionFactory>(m_colorDeconvolution_factory, region->graphic());
// Wrap resulting Factory in a Cache for speedy results
m_colorDeconvolution_factory = std::make_shared<Cache>(constrained_factory, RecentCachePolicy(30));
}
return pipeline_changed;
}//end buildPipeline
///Define the open file dialog options outside of init
sedeen::file::FileDialogOptions StainAnalysis::defineOpenFileDialogOptions() {
sedeen::file::FileDialogOptions theOptions;
theOptions.caption = "Open stain vector profile: ";
//theOptions.flags = sedeen::file::FileDialogFlags:: None currently needed
//theOptions.startDir; //no current preference
//Define the file type dialog filter
sedeen::file::FileDialogFilter theDialogFilter;
theDialogFilter.name = "Stain Vector Profile (*.xml)";
theDialogFilter.extensions.push_back("xml");
theOptions.filters.push_back(theDialogFilter);
return theOptions;
}//end defineOpenFileDialogOptions
///Define the save file dialog options outside of init
sedeen::file::FileDialogOptions StainAnalysis::defineSaveFileDialogOptions() {
sedeen::file::FileDialogOptions theOptions;
theOptions.caption = "Save separated images as...";
//theOptions.flags = sedeen::file::FileDialogFlags:: None currently needed
//theOptions.startDir; //no current preference
//Define the file type dialog filter
sedeen::file::FileDialogFilter theDialogFilter;
theDialogFilter.name = "Image type";
//Add extensions in m_saveFileExtensionText to theDialogFilter.extensions
//Note: std::copy does not work here
for (auto it = m_saveFileExtensionText.begin(); it != m_saveFileExtensionText.end(); ++it) {
theDialogFilter.extensions.push_back(*it);
}
theOptions.filters.push_back(theDialogFilter);
return theOptions;
}//end defineSaveFileDialogOptions
///Access the member file dialog parameter, load into member stain profile
bool StainAnalysis::LoadStainProfileFromFileDialog() {
//Get the full path file name from the file dialog parameter
sedeen::algorithm::parameter::OpenFileDialog::DataType fileDialogDataType = this->m_openProfile;
if (fileDialogDataType.empty()) {
//There is nothing selected in the file dialog box
return false;
}
//else
auto profileLocation = fileDialogDataType.at(0);
std::string theFile = profileLocation.getFilename();
//Does it exist and can it be read from?
if (StainProfile::checkFile(theFile, "r")) {
//Read the stain profile, return false if reading fails
bool readFileCheck = m_LoadedStainProfile->readStainProfile(theFile);
if (readFileCheck) {
m_stainProfileFullPathNames[0] = theFile;
return true;
}
else {
m_LoadedStainProfile->ClearProfile();
m_stainProfileFullPathNames[0] = "";
return false;
}
}
//else
return false;
}//end LoadStainProfileFromFileDialog
double StainAnalysis::EstimateOutputImageSize() {
//Has a region of interest been set?
bool roiSet = m_regionToProcess.isUserDefined();
std::shared_ptr<GraphicItemBase> theRegionOfInterest = m_regionToProcess;
DisplayRegion displayRegion = m_displayArea;
auto displayAreaSize = displayRegion.output_size;
double estSize;
//If a region of interest has been set, use the
if (roiSet && theRegionOfInterest != nullptr) {
Rect rect = containingRect(theRegionOfInterest->graphic());
double sizeFromRect = static_cast<double>(rect.height())
* static_cast<double>(rect.width());
estSize = sizeFromRect;
}
else {
//No region of interest set. Constrain to display area
double sizeFromDisplayArea = static_cast<double>(displayAreaSize.height())
* static_cast<double>(displayAreaSize.width());
estSize = sizeFromDisplayArea;
}
return estSize;
}//end EstimateOutputImageSize
std::string StainAnalysis::EstimateImageStorageSize(const double &pix) {
const double bytesPerPixel(4.0);
const double estStorageSize = bytesPerPixel * pix;
if (estStorageSize < 1.0) { return "0 bytes"; }
//bytes? kB? MB? GB? TB?
int power = static_cast<int>(std::log(estStorageSize) / std::log(1024.0));
double val = estStorageSize / std::pow(1024.0, power*1.0);
std::stringstream ss;
ss << std::setprecision(3) << val << " ";
if (power == 0) {
ss << "bytes";
}
else if (power == 1) {
ss << "kB";
}
else if (power == 2) {
ss << "MB";
}
else if (power == 3) {
ss << "GB";
}
else {
ss << "TB";
}
return ss.str();
}//end EstimateImageStorageSize
bool StainAnalysis::SaveFlatImageToFile(const std::string &p) {
//It is assumed that error checks have already been performed, and that the type is valid
//In RawImage::save, the used file format is defined by the file extension.
//Supported extensions are : .tif, .png, .bmp, .gif, .jpg
std::string outFilePath = p;
bool imageSaved = false;
//Access the output from the output factory
auto outputFactory = m_colorDeconvolution_factory;
auto compositor = std::make_unique<image::tile::Compositor>(outputFactory);
sedeen::image::RawImage outputImage;
//Has a region of interest been set?
bool roiSet = m_regionToProcess.isUserDefined();
std::shared_ptr<GraphicItemBase> theRegion = m_regionToProcess;
//If a region of interest has been set, constrain output to that area
if (roiSet && theRegion != nullptr) {
Rect rect = containingRect(theRegion->graphic());
//If an ROI is set, output the highest resolution (level 0)
outputImage = compositor->getImage(0, rect);
}
else {
//No region of interest set. Constrain to display area
DisplayRegion region = m_displayArea;
outputImage = compositor->getImage(region.source_region, region.output_size);
}
//Save the outputImage to a file at the given location
imageSaved = outputImage.save(outFilePath);
//true on successful save, false otherwise
return imageSaved;
}//end SaveFlatImageToFile
const std::string StainAnalysis::getExtension(const std::string &p) {
namespace fs = std::filesystem; //an alias
const std::string errorVal = std::string(); //empty
//Convert the string to a filesystem::path
fs::path filePath(p);
//Does the filePath have an extension?
bool hasExtension = filePath.has_extension();
if (!hasExtension) { return errorVal; }
//else
fs::path ext = filePath.extension();
return ext.string();
}//end getExtension
const int StainAnalysis::findExtensionIndex(const std::string &x) const {
const int notFoundVal = -1; //return -1 if not found
//This method works if the extension has a leading . or not
std::string theExt(x);
auto range = std::find(theExt.begin(), theExt.end(), '.');
theExt.erase(range);
//Find the extension in the m_saveFileExtensionText vector
auto vec = m_saveFileExtensionText;
auto vecIt = std::find(vec.begin(), vec.end(), theExt);
if (vecIt != vec.end()) {
ptrdiff_t vecDiff = vecIt - vec.begin();
int extLoc = static_cast<int>(vecDiff);
return extLoc;
}
else {
return notFoundVal;
}
}//end fileExtensionIndex
std::string StainAnalysis::generateCompleteReport(std::shared_ptr<StainProfile> theProfile) const {
//Combine the output of the stain profile report
//and the pixel fraction report, return the full string
std::ostringstream ss;
ss << generatePixelFractionReport();
ss << std::endl;
ss << generateStainProfileReport(theProfile);
return ss.str();
}//end generateCompleteReport
std::string StainAnalysis::generateStainProfileReport(std::shared_ptr<StainProfile> theProfile) const
{
//I think using assert is a little too strong here. Use different error handling.
assert(nullptr != theProfile);
int numStains = theProfile->GetNumberOfStainComponents();
if (numStains < 0) {
return "Error reading the stain profile. Please change your settings and try again.";
}
//Get the profile contents, place in the output stringstream
std::ostringstream ss;
ss << std::left << std::setw(5);
ss << "Using stain profile: " << theProfile->GetNameOfStainProfile() << std::endl;
ss << "Number of component stains: " << numStains << std::endl;
ss << std::endl;
//These are cumulative, not if...else
//Stain one
if (numStains >= 1) {
std::array<double, 3> rgb = theProfile->GetStainOneRGB();
ss << std::left;
ss << "Stain 1: " << theProfile->GetNameOfStainOne() << std::endl;
ss << "R: " << std::setw(10) << std::setprecision(5) << rgb[0] <<
"G: " << std::setw(10) << std::setprecision(5) << rgb[1] <<
"B: " << std::setw(10) << std::setprecision(5) << rgb[2] <<
std::endl;
}
//Stain two
if (numStains >= 2) {
std::array<double, 3> rgb = theProfile->GetStainTwoRGB();
ss << std::left;
ss << "Stain 2: " << theProfile->GetNameOfStainTwo() << std::endl;
ss << "R: " << std::setw(10) << std::setprecision(5) << rgb[0] <<
"G: " << std::setw(10) << std::setprecision(5) << rgb[1] <<
"B: " << std::setw(10) << std::setprecision(5) << rgb[2] <<
std::endl;
}
//Stain three
if (numStains == 3) {
std::array<double, 3> rgb = theProfile->GetStainThreeRGB();
ss << std::left;
ss << "Stain 3: " << theProfile->GetNameOfStainThree() << std::endl;
ss << "R: " << std::setw(10) << std::setprecision(5) << rgb[0] <<
"G: " << std::setw(10) << std::setprecision(5) << rgb[1] <<
"B: " << std::setw(10) << std::setprecision(5) << rgb[2] <<
std::endl;
}
ss << std::endl;
//Analysis model and parameters
std::string analysisModel = theProfile->GetNameOfStainAnalysisModel();
auto analysisModelParameters = theProfile->GetAllAnalysisModelParameters();
if (!analysisModel.empty()) {
ss << "Stain analysis model: " << analysisModel << std::endl;
}
if (!analysisModelParameters.empty()) {
ss << generateParameterMapReport(analysisModelParameters) << std::endl;
}
//Separation algorithm and parameters
std::string separationAlgorithm = theProfile->GetNameOfStainSeparationAlgorithm();
auto separationAlgorithmParameters = theProfile->GetAllSeparationAlgorithmParameters();
if (!separationAlgorithm.empty()) {
ss << "Stain separation algorithm: " << separationAlgorithm << std::endl;
}
if (!separationAlgorithmParameters.empty()) {
ss << generateParameterMapReport(separationAlgorithmParameters) << std::endl;
}
//Complete, return the string
return ss.str();
}//end generateStainProfileReport
std::string StainAnalysis::generateParameterMapReport(std::map<std::string, std::string> p) const {
std::stringstream ss;
//Possible parameters are: pTypeNumPixels(), pTypeThreshold(), pTypePercentile(), pTypeHistoBins()
for (auto it = p.begin(); it != p.end(); ++it) {
std::string key = it->first;
std::string val = it->second;
if (!key.compare(StainProfile::pTypeNumPixels())) {
ss << "Number of pixels sampled: " << val << std::endl;
}
else if (!key.compare(StainProfile::pTypeThreshold())) {
ss << "Optical Density threshold applied when computing stain vectors: " << val << std::endl;
}
else if (!key.compare(StainProfile::pTypePercentile())) {
ss << "Histogram range percentile: " << val << std::endl;
}
else if (!key.compare(StainProfile::pTypeHistoBins())) {
ss << "Number of histogram bins: " << val << std::endl;
}
else {
//Unknown key, output anyway
ss << key << ": " << val << std::endl;
}
}
return ss.str();
}//end generateParameterMapReport
std::string StainAnalysis::generatePixelFractionReport() const {
if (m_colorDeconvolution_factory == nullptr) {
return "Error accessing the color deconvolution factory. Cannot generate pixel fraction report.";
}
using namespace image::tile;
// Get image from the output factory
auto compositor = std::make_unique<Compositor>(m_colorDeconvolution_factory);
DisplayRegion region = m_displayArea;
auto output_image = compositor->getImage(region.source_region, region.output_size);
//Check the ColorSpace of output_image to get the number of channels
ColorSpace outputColorSpace = output_image.colorSpace();
//The values of interest for the channelCount are 1 or 3, force to those options
int channelCount = outputColorSpace.channelCount() > 1 ? 3 : 1;
// Get image from the input factory
auto compositorsource = std::make_unique<Compositor>(image()->getFactory());
auto input_image = compositorsource->getImage(region.source_region, region.output_size);
if (m_regionToProcess.isUserDefined()) {
std::shared_ptr<GraphicItemBase> roi = m_regionToProcess;
auto display_resolution = getDisplayResolution(image(), m_displayArea);
Rect rect = containingRect(roi->graphic());
output_image = compositor->getImage(rect, region.output_size);
}
// Determine number of pixels above threshold
//Try to count quickly, taking RGB components into account
unsigned int totalNumPixels = output_image.width()*output_image.height();
std::vector<unsigned short> pixelSetArray(totalNumPixels,0);
int iWidth = output_image.width();
int jHeight = output_image.height();
int i, j = 0;
#pragma omp parallel
{
#pragma omp for private(i) private(j) //collapse(2) is not available in Visual Studio 2017
for (i = 0; i < iWidth; ++i) {
for (j = 0; j < jHeight; ++j) {
//This relies on implicit conversion from boolean operators to integers 0/1
//Use a ternary conditional operator to choose how many channels to consider
pixelSetArray[i*jHeight + j] = (channelCount == 1)
? (false || output_image.at(i, j, 0).as<uint8_t>()) //grayscale output image
: ( output_image.at(i, j, 0).as<uint8_t>() //RGB+ output image
|| output_image.at(i, j, 1).as<uint8_t>()
|| output_image.at(i, j, 2).as<uint8_t>() );
}
}
}
//Using accumulate means no need for comparison operations to 0/1
int numPixels = std::accumulate(pixelSetArray.begin(), pixelSetArray.end(), 0);
double coveredFraction = ((double)numPixels) / ((double)totalNumPixels);
// Calculate results
std::ostringstream ss;
ss << std::left << std::setfill(' ') << std::setw(20);
//ss << "The absolute number of covered pixels is: " << numPixels << std::endl;
//ss << "The absolute number of ROI pixels is: " << totalNumPixels << std::endl;
ss << "Percent of processed region covered by" << std::endl;
ss << "stain, above the displayed threshold : ";
ss << std::fixed << std::setprecision(3) << coveredFraction*100 << " %" << std::endl;
//Show the numerator and denominator of the pixel fraction
ss << "stained / total pixels: ";
ss << numPixels << " / " << totalNumPixels << std::endl;
return ss.str();
}//end generatePixelFractionReport
} // namespace algorithm
} // namespace sedeen
<file_sep>/ColorDeconvolutionKernel.cpp
/*=============================================================================
*
* Copyright (c) 2021 Sunnybrook Research Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*=============================================================================*/
#include "ColorDeconvolutionKernel.h"
#include "ODConversion.h"
#include "StainVectorMath.h"
namespace sedeen {
namespace image {
namespace {
const ColorSpace GrayscaleColorSpace(ColorModel::Grayscale, ChannelType::UInt8); //Const definition of GrayscaleColorSpace
const ColorSpace RGBAColorSpace(ColorModel::RGBA, ChannelType::UInt8); //Const definition of RGBAColorSpace
}
namespace tile {
ColorDeconvolution::ColorDeconvolution( DisplayOptions displayOption,
std::shared_ptr<StainProfile> theProfile,
bool applyThreshold, double threshold, bool stainQuantityOnly /*= false*/) :
m_applyThreshold(applyThreshold),
m_threshold(threshold),
m_DisplayOption(displayOption),
m_stainProfile(theProfile),
m_grayscaleQuantityOnly(stainQuantityOnly),
m_grayscaleNormFactor(100.0),
m_outputColorSpace(ColorModel::RGBA, ChannelType::UInt8) //initialize a default value
{
//If m_grayscaleQuantityOnly is true, set m_outputColorSpace to grayscale
if (GetGrayscaleQuantityOnly()) {
SetOutputColorSpace(GrayscaleColorSpace);
}
else {
SetOutputColorSpace(RGBAColorSpace);
}
}//end constructor
ColorDeconvolution::~ColorDeconvolution(void) {
}//end destructor
RawImage ColorDeconvolution::separateStains(const RawImage &source, double (&stainVec_matrix)[9])
{
int scaleMax = 255;
// initialize 3 output color images and 3 grayscale images
sedeen::Size imageSize = source.size();
std::vector<RawImage> colorImages;
std::vector<RawImage> grayscaleImages;
for (int i = 0; i < 3; i++) {
//Color images: adjust pixel value, assign
colorImages.push_back(RawImage(imageSize, RGBAColorSpace));
colorImages[i].fill(ChannelValue(0)); //ChannelValue is a std::variant, so values can be retrieved as multiple types
//Grayscale images: adjust pixel value, assign
grayscaleImages.push_back(RawImage(imageSize, GrayscaleColorSpace));
grayscaleImages[i].fill(ChannelValue(0));
}
//The inverse can't be calculated if there is a row of zeros. Replace these values first.
//If there is a row of zeros, replace it. Use the default replacement row.
double noZeroRowsMatrix[9] = { 0.0 };
StainVectorMath::ConvertZeroRowsToUnitary(stainVec_matrix, noZeroRowsMatrix);
//Get the inverse of the noZeroRowsMatrix
double inverse_matrix[9] = { 0.0 };
StainVectorMath::Compute3x3MatrixInverse(noZeroRowsMatrix, inverse_matrix);
//Perform faster color -> OD conversion with a lookup table
std::shared_ptr<ODConversion> converter = std::make_shared<ODConversion>();
//loop over all pixels in the given RawImage
int y = 0, x = 0;
for (int j = 0; j < imageSize.width()*imageSize.height(); j++) {
x = j%imageSize.width();
y = j/imageSize.width();
// log transform the source RGB data
int R = source.at(x, y, 0).as<int>();
int G = source.at(x, y, 1).as<int>();
int B = source.at(x, y, 2).as<int>();
double pixelOD[3]; //index is color channel
pixelOD[0] = converter->LookupRGBtoOD(R);
pixelOD[1] = converter->LookupRGBtoOD(G);
pixelOD[2] = converter->LookupRGBtoOD(B);
//The resulting RGB values for the three images
double RGB_sep[9] = { 0.0 };
double stainQuant[3] = { 0.0 };
GetSeparateColorsForPixel(pixelOD, RGB_sep, stainQuant, stainVec_matrix, inverse_matrix);
for (int i = 0; i < 3; i++) { //i index is stain
colorImages.at(i).setValue(x, y, 0, static_cast<int>(RGB_sep[i * 3 ]));
colorImages.at(i).setValue(x, y, 1, static_cast<int>(RGB_sep[i * 3 + 1]));
colorImages.at(i).setValue(x, y, 2, static_cast<int>(RGB_sep[i * 3 + 2]));
colorImages.at(i).setValue(x, y, 3, scaleMax);
int sq = static_cast<int>(stainQuant[i] * m_grayscaleNormFactor);
grayscaleImages.at(i).setValue(x, y, 0, sq);
}
}//end for each pixel
//Return the requested stain image
//Either colorImages, or if GrayscaleQuantityOnly is true, grayscaleImages
if( m_DisplayOption == DisplayOptions::STAIN1 ){
return GetGrayscaleQuantityOnly() ? grayscaleImages[0] : colorImages[0];
}
else if( m_DisplayOption == DisplayOptions::STAIN2 ){
return GetGrayscaleQuantityOnly() ? grayscaleImages[1] : colorImages[1];
}
else if( m_DisplayOption == DisplayOptions::STAIN3 ){
return GetGrayscaleQuantityOnly() ? grayscaleImages[2] : colorImages[2];
}
else {
return source;
}
}//end separateStains
void ColorDeconvolution::GetSeparateColorsForPixel(double(&pixelOD)[3], double(&RGB_sep)[9],
double(&stainVec_matrix)[9], double(&inverse_matrix)[9]) {
double quant[3] = { 0.0 }; //allocated but not accessible when using this overload
GetSeparateColorsForPixel(pixelOD, RGB_sep, quant, stainVec_matrix, inverse_matrix);
}//end GetSeparateColorsForPixel
void ColorDeconvolution::GetSeparateColorsForPixel(double (&pixelOD)[3], double (&RGB_sep)[9],
double(&outQuant)[3], double (&stainVec_matrix)[9], double (&inverse_matrix)[9]) {
//Determine how much of each stain is present at a pixel
double stainQuantity[3] = { 0.0 }; //index is stain number
StainVectorMath::Multiply3x3MatrixAndVector(inverse_matrix, pixelOD, stainQuantity);
for (int i = 0; i < 3; i++) { //i index is stain
//Scale the stain's OD by the amount of stain at this pixel, get the RGB values
double OD_scaled[3]; //index is color channel
//Don't allow negative stain quantities
stainQuantity[i] = (stainQuantity[i] > 0.0) ? stainQuantity[i] : 0.0;
OD_scaled[0] = (stainQuantity[i]) * stainVec_matrix[i * 3];
OD_scaled[1] = (stainQuantity[i]) * stainVec_matrix[i * 3 + 1];
OD_scaled[2] = (stainQuantity[i]) * stainVec_matrix[i * 3 + 2];
double OD_sum = OD_scaled[0] + OD_scaled[1] + OD_scaled[2];
//Determine if the threshold should be applied to this stain's pixel value
bool isAboveThreshold;
if (m_applyThreshold) {
isAboveThreshold = (OD_sum > m_threshold) ? true : false;
}
else {
isAboveThreshold = true;
}
if (isAboveThreshold) {
RGB_sep[i * 3 ] = ODConversion::ConvertODtoRGB(OD_scaled[0]);
RGB_sep[i * 3 + 1] = ODConversion::ConvertODtoRGB(OD_scaled[1]);
RGB_sep[i * 3 + 2] = ODConversion::ConvertODtoRGB(OD_scaled[2]);
outQuant[i] = stainQuantity[i];
}
else {
RGB_sep[i * 3 ] = 0.0;
RGB_sep[i * 3 + 1] = 0.0;
RGB_sep[i * 3 + 2] = 0.0;
outQuant[i] = 0.0;
}
}
}//end GetSeparateColorsForPixel
RawImage ColorDeconvolution::thresholdOnly(const RawImage &source) {
int scaleMax = 255;
// initialize 3 output images
sedeen::Size imageSize = source.size();
std::vector<RawImage> colorImages;
for (int i = 0; i < 3; i++) {
//Color images: adjust pixel value, assign
colorImages.push_back(RawImage(imageSize, ColorSpace(ColorModel::RGBA, ChannelType::UInt8)));
colorImages[i].fill(ChannelValue(0)); //ChannelValue is a std::variant, allowing data to be multiple types
}
//Perform faster OD conversions using a lookup table
std::shared_ptr<ODConversion> converter = std::make_shared<ODConversion>();
//Calculate the OD sum to compare to the threshold
int y = 0, x = 0;
for (int j = 0; j < imageSize.width()*imageSize.height(); j++) {
x = j % imageSize.width();
y = j / imageSize.width();
// log transform the RGB data
int R = source.at(x, y, 0).as<int>();
int G = source.at(x, y, 1).as<int>();
int B = source.at(x, y, 2).as<int>();
double pixelOD[3]; //index is color channel
pixelOD[0] = converter->LookupRGBtoOD(R);
pixelOD[1] = converter->LookupRGBtoOD(G);
pixelOD[2] = converter->LookupRGBtoOD(B);
//Get the total OD at the pixel
double OD_sum = pixelOD[0] + pixelOD[1] + pixelOD[2];
bool isAboveThreshold;
if (m_applyThreshold) {
isAboveThreshold = (OD_sum > m_threshold) ? true : false;
}
else {
isAboveThreshold = true;
}
//If the pixel was determined to be above threshold, add it to the images
for (int i = 0; i < 3; i++) {
if (isAboveThreshold) {
colorImages.at(i).setValue(x, y, 0, static_cast<int>(R));
colorImages.at(i).setValue(x, y, 1, static_cast<int>(G));
colorImages.at(i).setValue(x, y, 2, static_cast<int>(B));
colorImages.at(i).setValue(x, y, 3, scaleMax);
}
else {
colorImages.at(i).setValue(x, y, 0, 0);
colorImages.at(i).setValue(x, y, 1, 0);
colorImages.at(i).setValue(x, y, 2, 0);
colorImages.at(i).setValue(x, y, 3, scaleMax);
}
}
}
//Return the requested stain image
if (m_DisplayOption == DisplayOptions::STAIN1) {
return colorImages[0];
}
else if (m_DisplayOption == DisplayOptions::STAIN2) {
return colorImages[1];
}
else if (m_DisplayOption == DisplayOptions::STAIN3) {
return colorImages[2];
}
else {
return source;
}
}//end thresholdOnly
RawImage ColorDeconvolution::doProcessData(const RawImage &source)
{
double stainVec_matrix[9] = { 0.0 };
//Fill stainVec_matrix with the stain vector profile values
bool checkResult = m_stainProfile->GetNormalizedProfilesAsDoubleArray(stainVec_matrix);
//Get the number of stains in the profile
int numStains = m_stainProfile->GetNumberOfStainComponents();
if (checkResult) {
//Is number of stains set to 1? Threshold only if so
if (numStains == 1) {
return thresholdOnly(source);
}
else if (numStains == 2 || numStains == 3) {
//Stain separation and thresholding
return separateStains(source, stainVec_matrix);
}
else {
return source;
}
}
else {
return source;
}
}//end doProcessData
const ColorSpace& ColorDeconvolution::doGetColorSpace() const
{
return m_outputColorSpace;
}
} // namespace tile
} // namespace image
} // namespace sedeen<file_sep>/StainAnalysis-plugin.h
/*=============================================================================
*
* Copyright (c) 2021 Sunnybrook Research Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*=============================================================================*/
#ifndef SEDEEN_SRC_PLUGINS_STAINANALYSIS_STAINANALYSIS_H
#define SEDEEN_SRC_PLUGINS_STAINANALYSIS_STAINANALYSIS_H
//Convert a macro defined in CMake to a string
#define StringLiteral(stl) #stl
#define MacroToString(macro) StringLiteral(macro)
#include "algorithm/AlgorithmBase.h"
#include "algorithm/Parameters.h"
#include "algorithm/Results.h"
#include <omp.h>
#include <Windows.h>
#include <fstream>
#include <filesystem> //Requires C++17
//Plugin headers
#include "StainProfile.h"
#include "ODThresholdKernel.h"
#include "ColorDeconvolutionKernel.h"
namespace sedeen {
namespace tile {
} // namespace tile
namespace algorithm {
//#define round(x) ( x >= 0.0f ? floor(x + 0.5f) : ceil(x - 0.5f) )
/// Stain Analysis
/// This plugin implements stain separation using the colour deconvolution
/// method described in:
//Ruifrok AC, <NAME>. Quantification of histochemical
//staining by color deconvolution. Analytical & Quantitative
//Cytology & Histology 2001; 23: 291-299.
class StainAnalysis : public algorithm::AlgorithmBase {
public:
StainAnalysis();
virtual ~StainAnalysis();
private:
// virtual function
virtual void init(const image::ImageHandle& image);
virtual void run();
/// Creates the Color Deconvolution pipeline with a cache
//
/// \return
/// TRUE if the pipeline has changed since the call to this function, FALSE
/// otherwise
bool buildPipeline(std::shared_ptr<StainProfile>, bool);
//Define the open file dialog options outside of init
sedeen::file::FileDialogOptions defineOpenFileDialogOptions();
///Define the save file dialog options outside of init
sedeen::file::FileDialogOptions defineSaveFileDialogOptions();
///Access the member file dialog parameter, if possible load the stain profile, return true on success
bool LoadStainProfileFromFileDialog();
///Get the expected number of pixels to be saved in an output file.
double EstimateOutputImageSize();
///Get a human-readable estimate of the storage space required for an output file (with 4 bytes per pixel).
std::string EstimateImageStorageSize(const double &pix);
///Save the separated image to a TIF/PNG/BMP/GIF/JPG flat format file
bool SaveFlatImageToFile(const std::string &p);
///Given a full file path as a string, identify if there is an extension and return it
const std::string getExtension(const std::string &p);
///Search the m_saveFileExtensionText vector for a given extension, and return the index, or -1 if not found
const int findExtensionIndex(const std::string &x) const;
///Create a text report that combines the output of the stain profile and pixel fraction reports
std::string generateCompleteReport(std::shared_ptr<StainProfile>) const;
///Create a text report summarizing the stain vector profile
std::string generateStainProfileReport(std::shared_ptr<StainProfile>) const;
///Create the portion of a text report with model/algorithm parameters from the stain vector profile.
std::string generateParameterMapReport(std::map<std::string, std::string>) const;
///Create a text report stating what fraction of the processing area is covered by the filtered output
std::string generatePixelFractionReport(void) const;
private:
///Names of the default stain profile files
inline static const std::string HematoxylinPEosinSampleFilename() { return "defaultprofiles/HematoxylinPEosinSample.xml"; }
inline static const std::string HematoxylinPEosinFromRJFilename() { return "defaultprofiles/HematoxylinPEosinFromRJ.xml"; }
inline static const std::string HematoxylinPDABFromRJFilename() { return "defaultprofiles/HematoxylinPDABFromRJ.xml"; }
inline static const std::string HematoxylinPEosinPDABFromRJFilename() { return "defaultprofiles/HematoxylinPEosinPDABFromRJ.xml"; }
///List of the full path file names of the stain profiles
std::vector<std::filesystem::path> m_stainProfileFullPathNames;
///List of the connected stain profile objects
std::vector<std::shared_ptr<StainProfile>> m_stainProfileList;
///Keep a pointer directly to the loaded stain profile
std::shared_ptr<StainProfile> m_LoadedStainProfile;
private:
DisplayAreaParameter m_displayArea;
OpenFileDialogParameter m_openProfile;
OptionParameter m_stainSeparationAlgorithm;
OptionParameter m_stainVectorProfile;
GraphicItemParameter m_regionToProcess; //single output region
///Result type is whether to show stain quantity in grayscale, or re-colour with the stain vectors
OptionParameter m_stainResultType;
OptionParameter m_stainToDisplay;
BoolParameter m_applyDisplayThreshold;
/// User defined Threshold value.
algorithm::DoubleParameter m_displayThreshold;
///User choice whether to save the chosen separated image as output
BoolParameter m_saveSeparatedImage;
///Choose what format to write the separated images in
OptionParameter m_saveFileFormat;
///User choice of file name stem and type
SaveFileDialogParameter m_saveFileAs;
/// The output result
ImageResult m_result;
TextResult m_outputText;
std::string m_report;
/// The image factory after color deconvolution
std::shared_ptr<image::tile::Factory> m_colorDeconvolution_factory;
//std::ofstream log_file;
private:
//Member variables
std::vector<std::string> m_stainAnalysisModelOptions;
std::vector<std::string> m_separationAlgorithmOptions;
std::vector<std::string> m_stainVectorProfileOptions;
std::vector<std::string> m_stainResultTypeOptions;
std::vector<std::string> m_stainToDisplayOptions;
std::vector<std::string> m_saveFileFormatOptions;
std::vector<std::string> m_saveFileExtensionText;
const double m_displayThresholdDefaultVal;
const double m_displayThresholdMaxVal;
const double m_thresholdStepSizeVal;
///Number of pixels in an image to be saved over which the user will receive a warning.
const double m_pixelWarningThreshold;
};
} // namespace algorithm
} // namespace sedeen
#endif
<file_sep>/StainVectorMath.cpp
/*=============================================================================
*
* Copyright (c) 2021 Sunnybrook Research Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*=============================================================================*/
#include "StainVectorMath.h"
#include "ODConversion.h"
//Boost includes
#include <boost/qvm/vec.hpp>
#include <boost/qvm/mat.hpp>
#include <boost/qvm/vec_access.hpp>
#include <boost/qvm/mat_access.hpp>
#include <boost/qvm/vec_operations.hpp>
#include <boost/qvm/mat_operations.hpp>
#include <boost/qvm/vec_mat_operations.hpp>
#include <boost/qvm/map_mat_mat.hpp>
///Compute the inverse of a 3x3 matrix using Boost qvm: ensure matrix is unitary before using
void StainVectorMath::Compute3x3MatrixInverse(const double (&inputMat)[9], double (&inversionMat)[9]) {
//Clear the inversionMat (output) array
for (int i = 0; i < 9; i++) { inversionMat[i] = 0.0; }
//Define an output matrix
boost::qvm::mat<double, 3, 3> outputMatrix;
//Reshape to a 3x3 matrix
double reshapedInput[3][3] = { 0.0 };
int i, j = 0;
for (int x = 0; x < 9; x++) {
i = x / 3; //integer division
j = x % 3;
reshapedInput[i][j] = inputMat[x];
}
//Check the determinant of the matrix: is it 0? Thus is the matrix singular?
double theDeterminant = boost::qvm::determinant(reshapedInput);
//Get the inverse of the reshapedInput matrix if the determinant is not zero
//Return matrix of all zeros if the determinant is zero
if (abs(theDeterminant) < ODConversion::GetODMinValue()) {
outputMatrix = boost::qvm::zero_mat<double, 3, 3>();
}
else {
outputMatrix = boost::qvm::transposed(boost::qvm::inverse(reshapedInput));
}
//Assign output values (first index is row), no looping
inversionMat[0] = boost::qvm::A<0, 0>(outputMatrix);
inversionMat[1] = boost::qvm::A<0, 1>(outputMatrix);
inversionMat[2] = boost::qvm::A<0, 2>(outputMatrix);
inversionMat[3] = boost::qvm::A<1, 0>(outputMatrix);
inversionMat[4] = boost::qvm::A<1, 1>(outputMatrix);
inversionMat[5] = boost::qvm::A<1, 2>(outputMatrix);
inversionMat[6] = boost::qvm::A<2, 0>(outputMatrix);
inversionMat[7] = boost::qvm::A<2, 1>(outputMatrix);
inversionMat[8] = boost::qvm::A<2, 2>(outputMatrix);
//void return
}//end Compute3x3MatrixInverse
void StainVectorMath::Make3x3MatrixUnitary(const double (&inputMat)[9], double (&unitaryMat)[9]) {
//Bundle the input values in rows of three
std::vector<std::array<double, 3>> inputRows;
inputRows.push_back(std::array<double, 3>({ inputMat[0], inputMat[1], inputMat[2] }));
inputRows.push_back(std::array<double, 3>({ inputMat[3], inputMat[4], inputMat[5] }));
inputRows.push_back(std::array<double, 3>({ inputMat[6], inputMat[7], inputMat[8] }));
//Get the norm values
std::vector<double> normVals;
normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[0].begin(), inputRows[0].end()));
normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[1].begin(), inputRows[1].end()));
normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[2].begin(), inputRows[2].end()));
//Create output rows
std::vector<std::array<double, 3>> outputRows;
for (auto it = normVals.begin(); it != normVals.end(); ++it) {
bool smallValue = (*it < 10.0*ODConversion::GetODMinValue());
std::array<double, 3> addRow = inputRows[it - normVals.begin()];
if (smallValue) {
//do not modify
}
else {
for (auto p = addRow.begin(); p != addRow.end(); ++p) {
*p = *p / *it;
}
}
outputRows.push_back(addRow);
}
//Assign to the unitary (output) matrix
for (int x = 0; x < 9; x++) {
int i = x / 3;
int j = x % 3;
unitaryMat[x] = outputRows[i][j];
}
}//end Make3x3MatrixUnitary
void StainVectorMath::ConvertZeroRowsToUnitary(const double (&inputMat)[9], double (&unitaryMat)[9]) {
double replacementVals[3] = { 1.0,1.0,1.0 };
StainVectorMath::ConvertZeroRowsToUnitary(inputMat, unitaryMat, replacementVals);
}//end ConvertZeroRowsToUnitary
void StainVectorMath::ConvertZeroRowsToUnitary(const double (&inputMat)[9], double (&unitaryMat)[9], const double (&replacementVals)[3]) {
//Bundle the input values in rows of three
std::vector<std::array<double, 3>> inputRows;
inputRows.push_back(std::array<double, 3>({ inputMat[0], inputMat[1], inputMat[2] }));
inputRows.push_back(std::array<double, 3>({ inputMat[3], inputMat[4], inputMat[5] }));
inputRows.push_back(std::array<double, 3>({ inputMat[6], inputMat[7], inputMat[8] }));
//Get the norm values
std::vector<double> normVals;
normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[0].begin(), inputRows[0].end()));
normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[1].begin(), inputRows[1].end()));
normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[2].begin(), inputRows[2].end()));
//Compare against 10xGetODMinValue, set to unitary row if smaller
std::array<double, 3> replacementArray = { replacementVals[0], replacementVals[1], replacementVals[2] };
auto unitaryRow = StainVectorMath::NormalizeArray(replacementArray);
std::vector<std::array<double, 3>> outputRows;
for (auto it = normVals.begin(); it != normVals.end(); ++it) {
bool smallValue = (*it < 10.0*ODConversion::GetODMinValue());
auto addRow = smallValue ? unitaryRow : inputRows[it-normVals.begin()];
outputRows.push_back(addRow);
}
//Assign to the unitary (output) matrix
for (int x = 0; x < 9; x++) {
int i = x / 3;
int j = x % 3;
unitaryMat[x] = outputRows[i][j];
}
}//end ConvertZeroRowsToUnitary
std::array<bool, 3> StainVectorMath::RowSumZeroCheck(const double (&inputMat)[9]) {
std::array<bool, 3> returnVals;
//Bundle the input values in rows of three
std::vector<std::array<double, 3>> inputRows;
inputRows.push_back(std::array<double, 3>({ inputMat[0], inputMat[1], inputMat[2] }));
inputRows.push_back(std::array<double, 3>({ inputMat[3], inputMat[4], inputMat[5] }));
inputRows.push_back(std::array<double, 3>({ inputMat[6], inputMat[7], inputMat[8] }));
//Get the sums
std::vector<double> rowSums;
rowSums.push_back(std::accumulate(inputRows[0].begin(), inputRows[0].end(), 0.0));
rowSums.push_back(std::accumulate(inputRows[1].begin(), inputRows[1].end(), 0.0));
rowSums.push_back(std::accumulate(inputRows[2].begin(), inputRows[2].end(), 0.0));
//Get the norm values
std::vector<double> normVals;
normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[0].begin(), inputRows[0].end()));
normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[1].begin(), inputRows[1].end()));
normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[2].begin(), inputRows[2].end()));
//For each, if rowSums is zero and normVals is non-zero, returnVals is true
for (int i = 0; i < 3; i++) {
bool checkVal = ((abs(rowSums[i]) < ODConversion::GetODMinValue()) && (normVals[i] > 0.0));
returnVals[i] = checkVal ? true : false;
}
return returnVals;
}//end RowSumZeroCheck
void StainVectorMath::Multiply3x3MatrixAndVector(const double (&inputMat)[9], const double (&inputVec)[3], double (&outputVec)[3]) {
//Clear the output vector
for (int i = 0; i < 3; i++) { outputVec[i] = 0.0; }
//Reshape to a 3x3 matrix
double reshapedMatrix[3][3] = { 0.0 };
int i, j = 0;
for (int x = 0; x < 9; x++) {
i = x / 3;
j = x % 3;
reshapedMatrix[i][j] = inputMat[x];
}
//Assign matrix and input vector to boost::qvm types
boost::qvm::mat<double, 3, 3> inputQVMMatrix = boost::qvm::mref(reshapedMatrix);
boost::qvm::vec<double, 3> inputQVMVector = boost::qvm::zero_vec<double, 3>();
boost::qvm::A<0>(inputQVMVector) = inputVec[0];
boost::qvm::A<1>(inputQVMVector) = inputVec[1];
boost::qvm::A<2>(inputQVMVector) = inputVec[2];
//Multiplication
boost::qvm::vec<double, 3> outputQVMVector;
outputQVMVector = inputQVMMatrix * inputQVMVector;
//Assign to the output vector
outputVec[0] = boost::qvm::A<0>(outputQVMVector);
outputVec[1] = boost::qvm::A<1>(outputQVMVector);
outputVec[2] = boost::qvm::A<2>(outputQVMVector);
//void return
}//end Multiply3x3MatrixAndVector
void StainVectorMath::SortStainVectors(const double(&inputMat)[9], double(&outputMat)[9],
const int &sortOrder /*= SortOrder::ASCENDING */) {
//Define lambdas to set how to compare two stain vectors (as 3-element arrays)
auto ascLambda = [](const std::array<double, 3> a, const std::array<double, 3> b) {
double prec = 1e-3;
//Always put (0,0,0) stain vectors at the end
double aSum = std::abs(std::accumulate(a.begin(), a.end(), 0.0));
double bSum = std::abs(std::accumulate(b.begin(), b.end(), 0.0));
if (aSum < prec) { return false; }
if (bSum < prec) { return true; }
//If first element is the same within error, sort by second element
if (std::abs(a[0] - b[0]) > prec) { return a[0] < b[0]; }
//If second element is the same within error, sort by third element
else if (std::abs(a[1] - b[1]) > prec) { return a[1] < b[1]; }
else { return a[2] < b[2]; }
};
auto descLambda = [](const std::array<double, 3> a, const std::array<double, 3> b) {
double prec = 1e-3;
//Always put (0,0,0) stain vectors at the end
double aSum = std::abs(std::accumulate(a.begin(), a.end(), 0.0));
double bSum = std::abs(std::accumulate(b.begin(), b.end(), 0.0));
if (aSum < prec) { return false; }
if (bSum < prec) { return true; }
//If first element is the same within error, sort by second element
if (std::abs(a[0] - b[0]) > prec) { return a[0] > b[0]; }
//If second element is the same within error, sort by third element
else if (std::abs(a[1] - b[1]) > prec) { return a[1] > b[1]; }
else { return a[2] >= b[2]; }
};
//Bundle the input values in rows of three
std::vector<std::array<double, 3>> inputRows;
inputRows.push_back(std::array<double, 3>({ inputMat[0], inputMat[1], inputMat[2] }));
inputRows.push_back(std::array<double, 3>({ inputMat[3], inputMat[4], inputMat[5] }));
inputRows.push_back(std::array<double, 3>({ inputMat[6], inputMat[7], inputMat[8] }));
//Create output rows
std::vector<std::array<double, 3>> outputRows = inputRows;
//Sort using the appropriate lambda
if (sortOrder == SortOrder::ASCENDING) {
std::sort(outputRows.begin(), outputRows.end(), ascLambda);
}
else if (sortOrder == SortOrder::DESCENDING) {
std::sort(outputRows.begin(), outputRows.end(), descLambda);
}
else {
//do not fill the output matrix
return;
}
//Assign to the output matrix
for (int x = 0; x < 9; x++) {
int i = x / 3;
int j = x % 3;
outputMat[x] = outputRows[i][j];
}
}//end SortStainVectors
<file_sep>/StainProfile.cpp
/*=============================================================================
*
* Copyright (c) 2021 Sunnybrook Research Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*=============================================================================*/
#include "StainProfile.h"
#include <stdexcept>
//#include <cmath>
#include <sstream>
#include <fstream>
#include <iterator>
#include <tinyxml2.h>
#include <filesystem> //requires C++17
StainProfile::StainProfile()
: m_stainAnalysisModelOptions( { "Ruifrok+Johnston Deconvolution" } ),
m_stainSeparationAlgorithmOptions( {"Region-of-Interest Selection",
"Macenko Decomposition", "Non-Negative Matrix Factorization", "Pre-Defined" } )
{
//Build the XML document structure
BuildXMLDocument();
}//end constructor
StainProfile::StainProfile(StainProfile &s)
: StainProfile() //invoking the no-parameter constructor will build the XML document
{
this->SetNameOfStainProfile(s.GetNameOfStainProfile());
this->SetNumberOfStainComponents(s.GetNumberOfStainComponents());
this->SetNameOfStainOne(s.GetNameOfStainOne());
this->SetNameOfStainTwo(s.GetNameOfStainTwo());
this->SetNameOfStainThree(s.GetNameOfStainThree());
this->SetNameOfStainAnalysisModel(s.GetNameOfStainAnalysisModel());
this->SetNameOfStainSeparationAlgorithm(s.GetNameOfStainSeparationAlgorithm());
this->SetAllAnalysisModelParameters(s.GetAllAnalysisModelParameters());
this->SetAllSeparationAlgorithmParameters(s.GetAllSeparationAlgorithmParameters());
this->SetStainOneRGB(s.GetStainOneRGB());
this->SetStainTwoRGB(s.GetStainTwoRGB());
this->SetStainThreeRGB(s.GetStainThreeRGB());
}//end copy constructor
StainProfile::~StainProfile() {
//Smartpointer used for m_xmlDoc,
//and an XMLDocument handles memory management for all its child objects.
//No explicit delete required.
}//end destructor
bool StainProfile::SetNameOfStainProfile(const std::string &name) {
//Direct assignment. Add checks if necessary.
if (m_rootElement == nullptr) {
return false;
}
else {
m_rootElement->SetAttribute(nameOfStainProfileAttribute(), name.c_str());
return true;
}
}//end SetNameOfStainProfile
const std::string StainProfile::GetNameOfStainProfile() const {
std::string result;
if (m_rootElement == nullptr) {
result = std::string();
}
else {
const char* name = m_rootElement->Attribute(nameOfStainProfileAttribute());
result = (name == nullptr) ? std::string() : std::string(name);
}
return result;
}//end GetNameOfStainProfile
bool StainProfile::SetNumberOfStainComponents(const int &components) {
if (m_componentsElement == nullptr) {
return false;
}
//Check if number is 0 or greater.
//If not, do not assign value and return false
if (components >= 0) {
m_componentsElement->SetAttribute(numberOfStainsAttribute(), components);
return true;
}
else {
m_componentsElement->SetAttribute(numberOfStainsAttribute(), -1);
return false;
}
}//end SetNumberOfStainComponents
const int StainProfile::GetNumberOfStainComponents() const {
int components(-1);
if (m_componentsElement == nullptr) {
return -1;
}
else {
tinyxml2::XMLError eResult = m_componentsElement->QueryIntAttribute(numberOfStainsAttribute(), &components);
if (eResult != tinyxml2::XML_SUCCESS) {
return -1;
}
}
return components;
}//end GetNumberOfStainComponents
bool StainProfile::SetNameOfStainOne(const std::string &name) {
//Direct assignment.
if (m_stainOneElement == nullptr) {
return false;
}
else {
m_stainOneElement->SetAttribute(nameOfStainAttribute(), name.c_str());
return true;
}
}//end SetNameOfStainOne
const std::string StainProfile::GetNameOfStainOne() const {
std::string result;
if (m_stainOneElement == nullptr) {
result = std::string();
}
else {
const char* name = m_stainOneElement->Attribute(nameOfStainAttribute());
result = (name == nullptr) ? std::string() : std::string(name);
}
return result;
}//end GetNameOfStainOne
bool StainProfile::SetNameOfStainTwo(const std::string &name) {
//Direct assignment.
if (m_stainTwoElement == nullptr) {
return false;
}
else {
m_stainTwoElement->SetAttribute(nameOfStainAttribute(), name.c_str());
return true;
}
}//end SetNameOfStainTwo
const std::string StainProfile::GetNameOfStainTwo() const {
std::string result;
if (m_stainTwoElement == nullptr) {
result = std::string();
}
else {
const char* name = m_stainTwoElement->Attribute(nameOfStainAttribute());
result = (name == nullptr) ? std::string() : std::string(name);
}
return result;
}//end GetNameOfStainTwo
bool StainProfile::SetNameOfStainThree(const std::string &name) {
//Direct assignment
if (m_stainThreeElement == nullptr) {
return false;
}
else {
m_stainThreeElement->SetAttribute(nameOfStainAttribute(), name.c_str());
return true;
}
}//end SetNameOfStainThree
const std::string StainProfile::GetNameOfStainThree() const {
std::string result;
if (m_stainThreeElement == nullptr) {
result = std::string();
}
else {
const char* name = m_stainThreeElement->Attribute(nameOfStainAttribute());
result = (name == nullptr) ? std::string() : std::string(name);
}
return result;
}//end GetNameOfStainThree
bool StainProfile::SetNameOfStainAnalysisModel(const std::string &name) {
//Check if the stain analysis model name given is in the valid list
//If not, do not assign value and return false
if (std::find(m_stainAnalysisModelOptions.begin(), m_stainAnalysisModelOptions.end(), name)
!= m_stainAnalysisModelOptions.end()) {
//Found. Assign name
m_analysisModelElement->SetAttribute(analysisModelNameAttribute(), name.c_str());
return true;
}//else
return false;
}//end SetNameOfStainAnalysisModel
const std::string StainProfile::GetNameOfStainAnalysisModel() const {
std::string result;
if (m_analysisModelElement == nullptr) {
result = std::string();
}
else {
const char* am = m_analysisModelElement->Attribute(analysisModelNameAttribute());
result = (am == nullptr) ? std::string() : std::string(am);
}
return result;
}//end GetNameOfStainAnalysisModel
bool StainProfile::SetNameOfStainSeparationAlgorithm(const std::string &name) {
//Check if the stain separation algorithm name given is in the valid list
//If not, do not assign value and return false
if (std::find(m_stainSeparationAlgorithmOptions.begin(), m_stainSeparationAlgorithmOptions.end(), name)
!= m_stainSeparationAlgorithmOptions.end()) {
//Found. Assign name
m_algorithmElement->SetAttribute(algorithmNameAttribute(), name.c_str());
return true;
}//else
return false;
}//end SetNameOfStainSeparationAlgorithm
const std::string StainProfile::GetNameOfStainSeparationAlgorithm() const {
std::string result;
if (m_algorithmElement == nullptr) {
result = std::string();
}
else {
const char* alg = m_algorithmElement->Attribute(algorithmNameAttribute());
result = (alg == nullptr) ? std::string() : std::string(alg);
}
return result;
}//end GetNameOfStainSeparationAlgorithm
bool StainProfile::SetStainOneRGB(const double &r, const double &g, const double &b) {
//Place data into a std::array, pass to other overload of this method
std::array<double, 3> rgb = { r,g,b };
return SetStainOneRGB(rgb);
}//end SetStainOneRGB
bool StainProfile::SetStainOneRGB(double rgb[])
{
//Check length of rgb first
//This is a C-style array, so get the size the old way
int len = sizeof(rgb) / sizeof(*rgb); //(total size divided by size of first element)
if (len != 3) {
return false;
}
else {
//Place data into a std::array, pass to other overload of this method
std::array<double, 3> arrayRGB;
for (int i = 0; i < 3; ++i) {
try {
arrayRGB.at(i) = rgb[i];
}
catch (const std::out_of_range& rangeerr) {
rangeerr.what();
//The index is out of range. Return false
return false;
}
}
return SetStainOneRGB(arrayRGB);
}
return false;
}//end SetStainOneRGB(C array)
bool StainProfile::SetStainOneRGB(const std::array<double, 3> &rgb_in) {
//Normalize the array before assigning
std::array<double, 3> rgb = StainVectorMath::NormalizeArray<double, 3>(rgb_in);
//Get the first stain value element, or return false if not found
if (m_stainOneElement == nullptr) { return false; }
//else
tinyxml2::XMLElement* sVals = m_stainOneElement->FirstChildElement(stainValueTag());
if (sVals == nullptr) { return false; }
while (sVals != nullptr) {
if (sVals->Attribute(valueTypeAttribute(), "r")) {
sVals->SetText(rgb[0]);
}
else if (sVals->Attribute(valueTypeAttribute(), "g")) {
sVals->SetText(rgb[1]);
}
else if (sVals->Attribute(valueTypeAttribute(), "b")) {
sVals->SetText(rgb[2]);
}
sVals = sVals->NextSiblingElement(stainValueTag());
}
return true;
}//end SetStainOneRGB(std::array)
const std::array<double, 3> StainProfile::GetStainOneRGB() const {
//Create a zero array to return
std::array<double, 3> out = { 0.0,0.0,0.0 };
double r, g, b; //temp values
//Get the first stain value element, or return false if not found
if (m_stainOneElement == nullptr) { return out; }
tinyxml2::XMLElement* sVals = m_stainOneElement->FirstChildElement(stainValueTag());
if (sVals == nullptr) { return out; }
while (sVals != nullptr) {
if (sVals->Attribute(valueTypeAttribute(), "r")) {
tinyxml2::XMLError rResult = sVals->QueryDoubleText(&r);
if (rResult != tinyxml2::XML_SUCCESS) { return out; }
}
else if (sVals->Attribute(valueTypeAttribute(), "g")) {
tinyxml2::XMLError gResult = sVals->QueryDoubleText(&g);
if (gResult != tinyxml2::XML_SUCCESS) { return out; }
}
else if (sVals->Attribute(valueTypeAttribute(), "b")) {
tinyxml2::XMLError bResult = sVals->QueryDoubleText(&b);
if (bResult != tinyxml2::XML_SUCCESS) { return out; }
}
sVals = sVals->NextSiblingElement(stainValueTag());
}
out[0] = r;
out[1] = g;
out[2] = b;
return out;
}//end GetStainOneRGB
bool StainProfile::SetStainTwoRGB(const double &r, const double &g, const double &b) {
//Place data into a std::array, pass to other overload of this method
std::array<double, 3> rgb = { r,g,b };
return SetStainTwoRGB(rgb);
}//end SetStainTwoRGB
bool StainProfile::SetStainTwoRGB(double rgb[]) {
//Check length of rgb first
//This is a C-style array, so get the size the old way
int len = sizeof(rgb) / sizeof(*rgb);
if (len != 3) {
return false;
}
else {
//Place data into a std::array, pass to other overload of this method
std::array<double, 3> arrayRGB;
for (int i = 0; i < 3; ++i) {
try {
arrayRGB.at(i) = rgb[i];
}
catch (const std::out_of_range& rangeerr) {
rangeerr.what();
//The index is out of range. Return false
return false;
}
}
return SetStainTwoRGB(arrayRGB);
}
return false;
}//end SetStainTwoRGB(C array)
bool StainProfile::SetStainTwoRGB(const std::array<double, 3> &rgb_in) {
//Normalize the array before assigning
std::array<double, 3> rgb = StainVectorMath::NormalizeArray<double, 3>(rgb_in);
//Get the first stain value element, or return false if not found
if (m_stainTwoElement == nullptr) { return false; }
tinyxml2::XMLElement* sVals = m_stainTwoElement->FirstChildElement(stainValueTag());
if (sVals == nullptr) { return false; }
while (sVals != nullptr) {
if (sVals->Attribute(valueTypeAttribute(), "r")) {
sVals->SetText(rgb[0]);
}
else if (sVals->Attribute(valueTypeAttribute(), "g")) {
sVals->SetText(rgb[1]);
}
else if (sVals->Attribute(valueTypeAttribute(), "b")) {
sVals->SetText(rgb[2]);
}
sVals = sVals->NextSiblingElement(stainValueTag());
}
return true;
}//end SetStainTwoRGB(std::array)
const std::array<double, 3> StainProfile::GetStainTwoRGB() const {
//Create a zero array to return
std::array<double, 3> out = { 0.0,0.0,0.0 };
double r, g, b; //temp values
//Get the first stain value element, or return false if not found
if (m_stainTwoElement == nullptr) { return out; }
tinyxml2::XMLElement* sVals = m_stainTwoElement->FirstChildElement(stainValueTag());
if (sVals == nullptr) { return out; }
while (sVals != nullptr) {
if (sVals->Attribute(valueTypeAttribute(), "r")) {
tinyxml2::XMLError rResult = sVals->QueryDoubleText(&r);
if (rResult != tinyxml2::XML_SUCCESS) { return out; }
}
else if (sVals->Attribute(valueTypeAttribute(), "g")) {
tinyxml2::XMLError gResult = sVals->QueryDoubleText(&g);
if (gResult != tinyxml2::XML_SUCCESS) { return out; }
}
else if (sVals->Attribute(valueTypeAttribute(), "b")) {
tinyxml2::XMLError bResult = sVals->QueryDoubleText(&b);
if (bResult != tinyxml2::XML_SUCCESS) { return out; }
}
sVals = sVals->NextSiblingElement(stainValueTag());
}
out[0] = r;
out[1] = g;
out[2] = b;
return out;
}//end GetStainTwoRGB
bool StainProfile::SetStainThreeRGB(const double &r, const double &g, const double &b) {
//Place data into a std::array, pass to other overload of this method
std::array<double, 3> rgb = { r,g,b };
return SetStainThreeRGB(rgb);
}//end SetStainThreeRGB
bool StainProfile::SetStainThreeRGB(double rgb[])
{
//Check length of rgb first
//This is a C-style array, so get the size the old way
int len = sizeof(rgb) / sizeof(*rgb);
if (len != 3) {
return false;
}
else {
//Place data into a std::array, pass to other overload of this method
std::array<double, 3> arrayRGB;
for (int i = 0; i < 3; ++i) {
try {
arrayRGB.at(i) = rgb[i];
}
catch (const std::out_of_range& rangeerr) {
rangeerr.what();
//The index is out of range. Return false
return false;
}
}
return SetStainThreeRGB(arrayRGB);
}
return false;
}//end SetStainThreeRGB(C array)
bool StainProfile::SetStainThreeRGB(const std::array<double, 3> &rgb_in) {
//Normalize the array before assigning
std::array<double, 3> rgb = StainVectorMath::NormalizeArray<double, 3>(rgb_in);
//Get the first stain value element, or return false if not found
if (m_stainThreeElement == nullptr) { return false; }
tinyxml2::XMLElement* sVals = m_stainThreeElement->FirstChildElement(stainValueTag());
if (sVals == nullptr) { return false; }
while (sVals != nullptr) {
if (sVals->Attribute(valueTypeAttribute(), "r")) {
sVals->SetText(rgb[0]);
}
else if (sVals->Attribute(valueTypeAttribute(), "g")) {
sVals->SetText(rgb[1]);
}
else if (sVals->Attribute(valueTypeAttribute(), "b")) {
sVals->SetText(rgb[2]);
}
sVals = sVals->NextSiblingElement(stainValueTag());
}
return true;
}//end SetStainThreeRGB(std::array)
const std::array<double, 3> StainProfile::GetStainThreeRGB() const {
//Create a zero array to return
std::array<double, 3> out = { 0.0,0.0,0.0 };
double r, g, b; //temp values
//Get the first stain value element, or return false if not found
if (m_stainThreeElement == nullptr) { return out; }
tinyxml2::XMLElement* sVals = m_stainThreeElement->FirstChildElement(stainValueTag());
if (sVals == nullptr) { return out; }
while (sVals != nullptr) {
if (sVals->Attribute(valueTypeAttribute(), "r")) {
tinyxml2::XMLError rResult = sVals->QueryDoubleText(&r);
if (rResult != tinyxml2::XML_SUCCESS) { return out; }
}
else if (sVals->Attribute(valueTypeAttribute(), "g")) {
tinyxml2::XMLError gResult = sVals->QueryDoubleText(&g);
if (gResult != tinyxml2::XML_SUCCESS) { return out; }
}
else if (sVals->Attribute(valueTypeAttribute(), "b")) {
tinyxml2::XMLError bResult = sVals->QueryDoubleText(&b);
if (bResult != tinyxml2::XML_SUCCESS) { return out; }
}
sVals = sVals->NextSiblingElement(stainValueTag());
}
out[0] = r;
out[1] = g;
out[2] = b;
return out;
}//end GetStainThreeRGB
bool StainProfile::GetProfilesAsDoubleArray(double (&profileArray)[9]) const {
return GetProfilesAsDoubleArray(profileArray, false);
}//end GetProfileAsDoubleArray
bool StainProfile::GetNormalizedProfilesAsDoubleArray(double (&profileArray)[9]) const {
return GetProfilesAsDoubleArray(profileArray, true);
}//end GetNormalizedProfilesAsDoubleArray
bool StainProfile::GetProfilesAsDoubleArray(double (&profileArray)[9], bool normalize) const {
//This method fills the values of profileArray from local stain profile
//Assigns 0.0 for elements corresponding to components beyond the number set in the profile
int components = this->GetNumberOfStainComponents();
if (components <= 0) {
for (int i = 0; i < 9; i++) { profileArray[i] = 0.0; }
return false;
}
std::array<double, 3> raw_rgb1 = this->GetStainOneRGB();
std::array<double, 3> raw_rgb2 = this->GetStainTwoRGB();
std::array<double, 3> raw_rgb3 = this->GetStainThreeRGB();
std::array<double, 3> rgb1 = normalize ? StainVectorMath::NormalizeArray(raw_rgb1) : raw_rgb1;
std::array<double, 3> rgb2 = normalize ? StainVectorMath::NormalizeArray(raw_rgb2) : raw_rgb2;
std::array<double, 3> rgb3 = normalize ? StainVectorMath::NormalizeArray(raw_rgb3) : raw_rgb3;
//Use the ternary operator for assignment of the profileArray elements
profileArray[0] = (components > 0) ? rgb1[0] : 0.0;
profileArray[1] = (components > 0) ? rgb1[1] : 0.0;
profileArray[2] = (components > 0) ? rgb1[2] : 0.0;
profileArray[3] = (components > 1) ? rgb2[0] : 0.0;
profileArray[4] = (components > 1) ? rgb2[1] : 0.0;
profileArray[5] = (components > 1) ? rgb2[2] : 0.0;
profileArray[6] = (components > 2) ? rgb3[0] : 0.0;
profileArray[7] = (components > 2) ? rgb3[1] : 0.0;
profileArray[8] = (components > 2) ? rgb3[2] : 0.0;
return true;
}//end GetProfilesAsDoubleArray
bool StainProfile::SetProfilesFromDoubleArray(double (&profileArray)[9]) {
//Copy values to ensure they are in local scope
double thisArray[9] = { 0.0 };
for (int i = 0; i < 9; i++) {
thisArray[i] = profileArray[i];
}
//Assume that the contents of profileArray are intentional, and directly set all values
bool check1 = this->SetStainOneRGB(thisArray[0], thisArray[1], thisArray[2]);
bool check2 = this->SetStainTwoRGB(thisArray[3], thisArray[4], thisArray[5]);
bool check3 = this->SetStainThreeRGB(thisArray[6], thisArray[7], thisArray[8]);
return (check1 && check2 && check3);
}//end SetProfileFromDoubleArray
bool StainProfile::checkFile(const std::string &fileString, const std::string &op) {
namespace fs = std::filesystem;
const bool success = true;
const bool errorVal = false;
if (fileString.empty()) { return errorVal; }
//Convert the input fileString into a filesystem::path type
fs::path theFilePath = fs::path(fileString);
//Check if the file exists
bool fileExists = fs::exists(theFilePath);
//If op is set to "r" (read), check that the file can be opened for reading
if (!op.compare("r") && fileExists) {
std::ifstream inFile(fileString.c_str());
bool result = inFile.good();
inFile.close();
return result;
}
//If op is set to "w" (write) and the file exists, check without overwriting
else if (!op.compare("w") && fileExists) {
//Open for appending (do not overwrite current contents)
std::ofstream outFile(fileString.c_str(), std::ios::app);
bool result = outFile.good();
outFile.close();
return result;
}
//If op is set to "w" (write) and the file does not exist, check if the directory exists
else if (!op.compare("w") && !fileExists) {
fs::path parentPath = theFilePath.parent_path();
bool dirExists = fs::is_directory(parentPath);
//If it does not exist, return errorVal
if (!dirExists) { return errorVal; }
//If it exists, does someone (anyone) have write permission?
fs::file_status dirStatus = fs::status(parentPath);
fs::perms dPerms = dirStatus.permissions();
bool someoneCanWrite = ((dPerms & fs::perms::owner_write) != fs::perms::none)
|| ((dPerms & fs::perms::group_write) != fs::perms::none)
|| ((dPerms & fs::perms::others_write) != fs::perms::none);
return dirExists && someoneCanWrite;
}
else {
return errorVal;
}
}//end checkFile
///Public write method, calls private write method
bool StainProfile::writeStainProfile(const std::string &fileString) {
bool checkResult = this->checkFile(fileString, "w");
if (!checkResult) {
return false;
}
else {
tinyxml2::XMLError eResult = this->writeStainProfileToXML(fileString);
if (eResult == tinyxml2::XML_SUCCESS) {
return true;
}
else {
return false;
}
}
return false;
}//end writeStainProfile
///Public read method, calls private read method
bool StainProfile::readStainProfile(const std::string &fileString) {
bool checkResult = this->checkFile(fileString, "r");
if (!checkResult) {
return false;
}
else {
tinyxml2::XMLError eResult = this->readStainProfileFromXMLFile(fileString);
if (eResult == tinyxml2::XML_SUCCESS) {
return true;
}
else {
return false;
}
}
return false;
}//end readStainProfile
/// Public read method, calls private read method
bool StainProfile::readStainProfile(const char *str, size_t size) {
tinyxml2::XMLError eResult = this->readStainProfileFromXMLString(str, size);
if (eResult == tinyxml2::XML_SUCCESS) {
return true;
} else {
return false;
}
} // end readStainProfile
///Private write method that deals with TinyXML2
tinyxml2::XMLError StainProfile::writeStainProfileToXML(const std::string &fileString) {
//Write it!
tinyxml2::XMLError eResult = this->GetXMLDoc()->SaveFile(fileString.c_str());
XMLCheckResult(eResult);
//else
return tinyxml2::XML_SUCCESS;
}//end writeStainProfileToXML
tinyxml2::XMLError StainProfile::readStainProfileFromXMLFile(const std::string &fileString) {
//Clear the current structure
bool clearSuccessful = ClearXMLDocument();
if (!clearSuccessful) {
return tinyxml2::XML_ERROR_PARSING_ELEMENT;
}
//else
//Read it!
tinyxml2::XMLError eResult = this->GetXMLDoc()->LoadFile(fileString.c_str());
XMLCheckResult(eResult);
return parseXMLDoc();
}//end readStainProfileFromXMLFile
tinyxml2::XMLError StainProfile::readStainProfileFromXMLString(const char *str, size_t size) {
// Clear the current structure
bool clearSuccessful = ClearXMLDocument();
if (!clearSuccessful) {
return tinyxml2::XML_ERROR_PARSING_ELEMENT;
}
// else
// Read it!
tinyxml2::XMLError eResult = this->GetXMLDoc()->Parse(str, size);
XMLCheckResult(eResult);
return parseXMLDoc();
} // end readStainProfileFromXMLString
tinyxml2::XMLError StainProfile::parseXMLDoc() {
// Assign the member pointers to children in the loaded data structure
m_rootElement = this->GetXMLDoc()->FirstChildElement(rootTag());
if (m_rootElement == nullptr) {
return tinyxml2::XML_ERROR_PARSING_ELEMENT;
}
m_componentsElement = m_rootElement->FirstChildElement(componentsTag());
if (m_componentsElement == nullptr) {
return tinyxml2::XML_ERROR_PARSING_ELEMENT;
}
tinyxml2::XMLElement *tempStain =
m_componentsElement->FirstChildElement(stainTag());
while (tempStain != nullptr) {
// They must all have an index, or it should be considered an error
int stainIndex(-1);
tinyxml2::XMLError eResult =
tempStain->QueryIntAttribute(indexOfStainAttribute(), &stainIndex);
XMLCheckResult(eResult);
// Choose which stain element to assign tempStain to
if (stainIndex == 1) {
m_stainOneElement = tempStain;
} else if (stainIndex == 2) {
m_stainTwoElement = tempStain;
} else if (stainIndex == 3) {
m_stainThreeElement = tempStain;
}
// tempStain is just a pointer to an existing element
// Dropping it does not create a memory leak
tempStain = tempStain->NextSiblingElement(stainTag());
}
m_analysisModelElement = m_rootElement->FirstChildElement(analysisModelTag());
if (m_analysisModelElement == nullptr) {
return tinyxml2::XML_ERROR_PARSING_ELEMENT;
}
//Parsing any parameters of this element is handled by Get methods
m_algorithmElement = m_rootElement->FirstChildElement(algorithmTag());
if (m_algorithmElement == nullptr) {
return tinyxml2::XML_ERROR_PARSING_ELEMENT;
}
//Parsing any parameters of this element is handled by Get methods
return tinyxml2::XML_SUCCESS;
}//end parseXMLDoc
const std::vector<std::string> StainProfile::GetStainAnalysisModelOptions() const {
return m_stainAnalysisModelOptions;
}//end GetStainAnalysisModelOptions
const std::vector<std::string> StainProfile::GetStainSeparationAlgorithmOptions() const {
return m_stainSeparationAlgorithmOptions;
}//end GetStainSeparationAlgorithmOptions
const int StainProfile::GetVectorIndexFromName(const std::string &name, const std::vector<std::string> &vec) const {
int outIndex(-1);
auto it = std::find(vec.begin(), vec.end(), name);
if (it != vec.end()) {
outIndex = static_cast<int>(std::distance(vec.begin(), it));
}
else {
outIndex = -1;
}
return outIndex;
}//end GetVectorIndexFromName
const std::string StainProfile::GetValueFromStringVector(const int &index,
const std::vector<std::string> &vec) const {
//Check that the given index value is valid
//Use the vector::at operator to do bounds checking
std::string name;
try {
name = vec.at(index);
}
catch (const std::out_of_range& rangeerr) {
rangeerr.what();
//The index is out of range. Return empty string
return std::string();
}
//name found. Return it.
return name;
}//end GetValueFromStringVector
const std::string StainProfile::GetStainAnalysisModelName(const int &index) const {
return GetValueFromStringVector(index, m_stainAnalysisModelOptions);
}//end GetStainAnalysisModelName
const std::string StainProfile::GetStainSeparationAlgorithmName(const int &index) const {
return GetValueFromStringVector(index, m_stainSeparationAlgorithmOptions);
}//end GetStainSeparationAlgorithmName
bool StainProfile::BuildXMLDocument() {
//Instantiate the XMLDocument as shared_ptr
m_xmlDoc = std::make_shared<tinyxml2::XMLDocument>();
//Create a root element and assign it as a child of the XML document
m_rootElement = m_xmlDoc->NewElement(rootTag());
m_rootElement->SetAttribute(nameOfStainProfileAttribute(), "");
m_xmlDoc->InsertFirstChild(m_rootElement);
//Build the next levels of the document structure
m_componentsElement = m_xmlDoc->NewElement(componentsTag());
m_componentsElement->SetAttribute(numberOfStainsAttribute(), "0"); //default value 0
m_rootElement->InsertEndChild(m_componentsElement);
//Build stain one
m_stainOneElement = m_xmlDoc->NewElement(stainTag());
m_stainOneElement->SetAttribute(indexOfStainAttribute(), 1);
m_stainOneElement->SetAttribute(nameOfStainAttribute(), "");
m_componentsElement->InsertEndChild(m_stainOneElement);
//Add the three stain values to stain element one
//r
tinyxml2::XMLElement* rValOne = m_xmlDoc->NewElement(stainValueTag());
rValOne->SetAttribute(valueTypeAttribute(), "r");
rValOne->SetText(0);
m_stainOneElement->InsertEndChild(rValOne);
//g
tinyxml2::XMLElement* gValOne = m_xmlDoc->NewElement(stainValueTag());
gValOne->SetAttribute(valueTypeAttribute(), "g");
gValOne->SetText(0);
m_stainOneElement->InsertEndChild(gValOne);
//b
tinyxml2::XMLElement* bValOne = m_xmlDoc->NewElement(stainValueTag());
bValOne->SetAttribute(valueTypeAttribute(), "b");
bValOne->SetText(0);
m_stainOneElement->InsertEndChild(bValOne);
//Build stain two
m_stainTwoElement = m_xmlDoc->NewElement(stainTag());
m_stainTwoElement->SetAttribute(indexOfStainAttribute(), 2);
m_stainTwoElement->SetAttribute(nameOfStainAttribute(), "");
m_componentsElement->InsertEndChild(m_stainTwoElement);
//Add the three stain values to stain element two
//r
tinyxml2::XMLElement* rValTwo = m_xmlDoc->NewElement(stainValueTag());
rValTwo->SetAttribute(valueTypeAttribute(), "r");
rValTwo->SetText(0);
m_stainTwoElement->InsertEndChild(rValTwo);
//g
tinyxml2::XMLElement* gValTwo = m_xmlDoc->NewElement(stainValueTag());
gValTwo->SetAttribute(valueTypeAttribute(), "g");
gValTwo->SetText(0);
m_stainTwoElement->InsertEndChild(gValTwo);
//b
tinyxml2::XMLElement* bValTwo = m_xmlDoc->NewElement(stainValueTag());
bValTwo->SetAttribute(valueTypeAttribute(), "b");
bValTwo->SetText(0);
m_stainTwoElement->InsertEndChild(bValTwo);
//Build stain three
m_stainThreeElement = m_xmlDoc->NewElement(stainTag());
m_stainThreeElement->SetAttribute(indexOfStainAttribute(), 3);
m_stainThreeElement->SetAttribute(nameOfStainAttribute(), "");
m_componentsElement->InsertEndChild(m_stainThreeElement);
//Add the three stain values to stain element three
//r
tinyxml2::XMLElement* rValThree = m_xmlDoc->NewElement(stainValueTag());
rValThree->SetAttribute(valueTypeAttribute(), "r");
rValThree->SetText(0);
m_stainThreeElement->InsertEndChild(rValThree);
//g
tinyxml2::XMLElement* gValThree = m_xmlDoc->NewElement(stainValueTag());
gValThree->SetAttribute(valueTypeAttribute(), "g");
gValThree->SetText(0);
m_stainThreeElement->InsertEndChild(gValThree);
//b
tinyxml2::XMLElement* bValThree = m_xmlDoc->NewElement(stainValueTag());
bValThree->SetAttribute(valueTypeAttribute(), "b");
bValThree->SetText(0);
m_stainThreeElement->InsertEndChild(bValThree);
//analysis model tag
m_analysisModelElement = m_xmlDoc->NewElement(analysisModelTag());
m_rootElement->InsertEndChild(m_analysisModelElement);
//algorithm tag, which can contain parameter values needed by the algorithm
m_algorithmElement = m_xmlDoc->NewElement(algorithmTag());
m_rootElement->InsertEndChild(m_algorithmElement);
return true;
}//end BuildXMLDocument
bool StainProfile::CheckXMLDocument() {
//Check if the basic structure of this XMLDocument is complete
//Get the pointer to the xmldocument
std::shared_ptr<tinyxml2::XMLDocument> docPtr = this->GetXMLDoc();
if (docPtr == nullptr) {
return false;
}
if (docPtr->NoChildren()) {
return false;
}
//else
//Check that all of the 'Get' operations from this class will be successful
//TODO: additional checks
try {
auto a = this->GetNameOfStainProfile();
auto b = this->GetNumberOfStainComponents();
auto c = this->GetNameOfStainOne();
auto d = this->GetNameOfStainTwo();
auto e = this->GetNameOfStainThree();
auto f = this->GetNameOfStainAnalysisModel();
auto g = this->GetNameOfStainSeparationAlgorithm();
auto h = this->GetStainOneRGB();
auto i = this->GetStainTwoRGB();
auto j = this->GetStainThreeRGB();
double k[9] = { 0.0 };
bool l = this->GetProfilesAsDoubleArray(k, true);
bool m = this->GetProfilesAsDoubleArray(k, false);
if (!l || !m) {
return false;
}
}
catch (...) {
return false;
}
//else
return true;
}//end CheckXMLDocument
bool StainProfile::ClearXMLDocument() {
//Set all of the values in the member XML document to their null values
std::shared_ptr<tinyxml2::XMLDocument> docPtr = this->GetXMLDoc();
//else
//Use the member methods
this->SetNameOfStainProfile("");
this->SetNumberOfStainComponents(0);
this->SetNameOfStainOne("");
this->SetNameOfStainTwo("");
this->SetNameOfStainThree("");
this->SetNameOfStainAnalysisModel("");
this->SetNameOfStainSeparationAlgorithm("");
//Clear the stain vector values using the specific method in this class
this->ClearStainVectorValues();
//Clear the analysis model parameters (if any)
this->ClearAllAnalysisModelParameters();
//Clear the separation algorithm parameters (if any)
this->ClearAllSeparationAlgorithmParameters();
//Success
return true;
}//end ClearXMLDocument
bool StainProfile::ClearStainVectorValues() {
//Set the stain vector values in the member XML document to 0
std::shared_ptr<tinyxml2::XMLDocument> docPtr = this->GetXMLDoc();
this->SetStainOneRGB(0, 0, 0);
this->SetStainTwoRGB(0, 0, 0);
this->SetStainThreeRGB(0, 0, 0);
//Success
return true;
}//end ClearStainVectorValues
bool StainProfile::ClearChildren(tinyxml2::XMLElement* el, const std::string &tag /*= std::string()*/) {
const bool success = true;
const bool errorVal = false;
if (el != nullptr) {
if (!el->NoChildren()) {
if (tag.empty()) {
//If no tag was specified, delete all children
el->DeleteChildren();
return success;
}
else {
while (RemoveSingleChild(el, tag)) {
;//as long as RemoveSingleChild returns true, repeat running it
}
return success;
}
}//else
return errorVal;
}//else
return errorVal;
}//end ClearChildren
bool StainProfile::ClearAllAnalysisModelParameters() {
std::string tag = std::string(parameterTag());
return ClearChildren(m_analysisModelElement, tag);
}//end ClearAnalysisModelParameters
bool StainProfile::ClearAllSeparationAlgorithmParameters() {
std::string tag = std::string(parameterTag());
return ClearChildren(m_algorithmElement, tag);
}//end ClearSeparationAlgorithmParameters
bool StainProfile::RemoveSingleChild(tinyxml2::XMLElement* el, const std::string &tag /*= std::string()*/,
const std::string &att /*= std::string()*/, const std::string &val /*= std::string()*/) {
const bool success = true;
const bool errorVal = false;
tinyxml2::XMLElement* child;
if (el != nullptr) {
if (!el->NoChildren()) {
//Get a reference to the child to be deleted, if it can be found
if (tag.empty()) {
//If tag is an empty string, the child to be deleted is the first one,
//without regard to its xml tag
child = el->FirstChildElement();
//If there is no valid child, return errorVal
if (child == nullptr) { return errorVal; }
}
else {
//If no attribute is specified, choose the first child with the given tag
if (att.empty()) {
child = el->FirstChildElement(tag.c_str());
}
else {
tinyxml2::XMLElement* tempChild = el->FirstChildElement(tag.c_str());
//loop through all child elements with this tag
bool attFound = false;
while (tempChild != nullptr) {
if (val.empty()) {
//If the parameter has the given attribute set to anything,
//set attFound to true
const char* tempAtt = tempChild->Attribute(att.c_str());
if (tempAtt != nullptr) { attFound = true; }
}
else {
//If there is a requested value for the attribute, test with it
const char* tempAtt = tempChild->Attribute(att.c_str(), val.c_str());
if (tempAtt != nullptr) { attFound = true; }
}
if (attFound) {
child = tempChild;
break;
}
//else
tempChild = tempChild->NextSiblingElement(tag.c_str());
}//end while
}
}
//If a child to be deleted is found, delete it, otherwise return errorVal
if (child != nullptr) {
el->DeleteChild(child);
return success;
}
//else
return errorVal;
}//else
return errorVal;
}//else
return errorVal;
}//end RemoveSingleChild
bool StainProfile::RemoveAnalysisModelParameter(const std::string &pType) {
std::string paramTag = std::string(parameterTag());
std::string paramAtt = std::string(parameterTypeAttribute());
return RemoveSingleChild(m_analysisModelElement, paramTag, paramAtt, pType);
}//end RemoveAnalysisModelParameter
bool StainProfile::RemoveSeparationAlgorithmParameter(const std::string &pType) {
std::string paramTag = std::string(parameterTag());
std::string paramAtt = std::string(parameterTypeAttribute());
return RemoveSingleChild(m_algorithmElement, paramTag, paramAtt, pType);
}//end RemoveSeparationAlgorithmParameter
const std::map<std::string, std::string> StainProfile::GetAllParameters(tinyxml2::XMLElement* el) const {
const auto errorVal = std::map<std::string, std::string>();
auto theMap = std::map<std::string, std::string>();
if (el == nullptr) { return errorVal; } //if nothing can be set, return an empty map
if (m_xmlDoc == nullptr) { return errorVal; } //if there is no xml document, return errorVal
//This gets the value of a parameter with param-type given by the type argument, if defined
const char* paramTag = parameterTag();
const char* paramAtt = parameterTypeAttribute();
//Get the first child element, or return empty string if not found
tinyxml2::XMLElement* tempParam = el->FirstChildElement(paramTag);
//Return errorVal if there are no parameter tags
if (tempParam == nullptr) { return errorVal; }
while (tempParam != nullptr) {
const char* tempAtt = tempParam->Attribute(paramAtt);
const char* tempVal = tempParam->GetText();
//If both values exist, create a pair and append to the map
if ((tempAtt != nullptr) && (tempVal != nullptr)) {
std::pair<std::string, std::string> tempPair
= std::pair<std::string, std::string>(std::string(tempAtt), std::string(tempVal));
theMap.insert(tempPair);
}
//repeat loop until there are no more parameters
tempParam = tempParam->NextSiblingElement(paramTag);
}
return theMap;
}//end GetAllParameters
bool StainProfile::SetAllParameters(tinyxml2::XMLElement* el, const std::map<std::string, std::string>& p) {
if (p.empty()) { return false; } //if nothing can be set, return false
if (el == nullptr) { return false; } //if nothing can be set, return false
//Clear all children of the element node before assignment
this->ClearChildren(el);
//Iterate over map, create and assign all parameter element nodes
for (auto it = p.begin(); it != p.end(); ++it) {
std::string key = it->first;
std::string val = it->second;
bool checkVal = this->SetSingleParameter(el, key, val);
if (!checkVal) { return false; }
}
return true;
}//end SetAllParameters
const std::map<std::string, std::string> StainProfile::GetAllAnalysisModelParameters() const {
return GetAllParameters(m_analysisModelElement);
}//end GetAnalysisModelParameters
bool StainProfile::SetAllAnalysisModelParameters(const std::map<std::string, std::string>& p) {
return SetAllParameters(m_analysisModelElement, p);
}//end SetAnalysisModelParameters
const std::map<std::string, std::string> StainProfile::GetAllSeparationAlgorithmParameters() const {
return GetAllParameters(m_algorithmElement);
}//end GetSeparationAlgorithmParameters
bool StainProfile::SetAllSeparationAlgorithmParameters(const std::map<std::string, std::string>& p) {
return SetAllParameters(m_algorithmElement, p);
}//end SetSeparationAlgorithmParameters
const std::string StainProfile::GetSingleParameter(tinyxml2::XMLElement* el, const std::string &type) const {
const std::string errorVal = std::string(); //an empty string
std::string outString = std::string();
if (el == nullptr) { return errorVal; } //if there is no element to get from, return errorVal
if (m_xmlDoc == nullptr) { return errorVal; } //if there is no xml document, return errorVal
if (type.empty()) { return errorVal; } //if no type is specified, return errorVal
//This gets the value of a parameter with param-type given by the type argument, if defined
const char* paramTag = parameterTag();
const char* paramAtt = parameterTypeAttribute();
//Get the first child element, or return empty string if not found
tinyxml2::XMLElement* tempParam = el->FirstChildElement(paramTag);
//Return errorVal if there are no parameter tags
if (tempParam == nullptr) { return errorVal; }
while (tempParam != nullptr) {
if (tempParam->Attribute(paramAtt, type.c_str())) {
const char *buffer = tempParam->GetText();
if (buffer == nullptr) {
//The parameter of the right type was found, but has no value set
outString = errorVal;
}
else {
outString = std::string(buffer);
}
break;
}
//else repeat loop
tempParam = tempParam->NextSiblingElement(paramTag);
}
return outString;
}//end GetSingleParameter
bool StainProfile::SetSingleParameter(tinyxml2::XMLElement* el, const std::string &type, const std::string &val) {
if (type.empty()) { return false; } //if there is no type, nothing can be set; return false
if (el == nullptr) { return false; } //if nothing can be set, return false
if (m_xmlDoc == nullptr) { return false; } //if there is no xml document, return false
//This sets the value of a parameter with param-type given by the type argument
const char* paramTag = parameterTag();
const char* paramAtt = parameterTypeAttribute();
bool attFound = false;
//Get the first child element, if none while loop will not be entered
tinyxml2::XMLElement* tempParam = el->FirstChildElement(paramTag);
//If at least one parameter exists, loop through to find parameter of given type
while (tempParam != nullptr) {
const char* tempAtt = tempParam->Attribute(paramAtt, type.c_str());
if (tempAtt != nullptr) {
tempParam->SetText(val.c_str());
attFound = true;
}
//else
//move to next parameter, prepare to repeat
tempParam = tempParam->NextSiblingElement(paramTag);
}
//if while loop was entered and attribute of given type was not found, create and add it
if(!attFound) {
//Create a new parameter, add to XML document model
tinyxml2::XMLElement* newParam = m_xmlDoc->NewElement(parameterTag());
newParam->SetAttribute(parameterTypeAttribute(), type.c_str());
newParam->SetText(val.c_str());
el->InsertEndChild(newParam);
}
return true;
}//end SetSingleParameter
const std::string StainProfile::GetSingleAnalysisModelParameter(const std::string &type) const {
return GetSingleParameter(m_analysisModelElement, type);
}//end GetSingleAnalysisModelParameter
bool StainProfile::SetSingleAnalysisModelParameter(const std::string &type, const std::string &val) {
return SetSingleParameter(m_analysisModelElement, type, val);
}//end SetSingleAnalysisModelParameter
const std::string StainProfile::GetSingleSeparationAlgorithmParameter(const std::string &type) const {
return GetSingleParameter(m_algorithmElement, type);
}//end GetSingleSeparationAlgorithmParameter
bool StainProfile::SetSingleSeparationAlgorithmParameter(const std::string &type, const std::string &val) {
return SetSingleParameter(m_algorithmElement, type, val);
}//end SetSingleSeparationAlgorithmParameter
const long int StainProfile::GetSeparationAlgorithmNumPixelsParameter() const {
std::string type = this->pTypeNumPixels();
std::string oss = this->GetSingleSeparationAlgorithmParameter(type);
long int outVal(-1); //Set error value here
//Convert oss to long int, if possible. Catch all exceptions (invalid_argument and out_of_range)
try {
outVal = std::stol(oss);
}
catch (...) {
//No additional actions required
}
return outVal;
}//end GetSeparationAlgorithmNumPixelsParameter
bool StainProfile::SetSeparationAlgorithmNumPixelsParameter(const long int& p) {
std::string type = this->pTypeNumPixels();
std::stringstream ss;
ss << p; // << std::endl;
return this->SetSingleSeparationAlgorithmParameter(type, ss.str());
}//end SetSeparationAlgorithmNumPixelsParameter
const double StainProfile::GetSeparationAlgorithmThresholdParameter() const {
std::string type = this->pTypeThreshold();
std::string oss = this->GetSingleSeparationAlgorithmParameter(type);
double outVal(-1.); //Set error value here
//Convert oss to double, if possible. Catch all exceptions (invalid_argument and out_of_range)
try {
outVal = std::stod(oss);
}
catch (...) {
//No additional actions required
}
return outVal;
}//end GetSeparationAlgorithmThresholdParameter
bool StainProfile::SetSeparationAlgorithmThresholdParameter(const double& p) {
std::string type = this->pTypeThreshold();
std::stringstream ss;
ss << p; // << std::endl;
return this->SetSingleSeparationAlgorithmParameter(type, ss.str());
}//end SetSeparationAlgorithmThresholdParameter
const double StainProfile::GetSeparationAlgorithmPercentileParameter() const {
std::string type = this->pTypePercentile();
std::string oss = this->GetSingleSeparationAlgorithmParameter(type);
double outVal(-1.); //Set error value here
//Convert oss to double, if possible. Catch all exceptions (invalid_argument and out_of_range)
try {
outVal = std::stod(oss);
}
catch (...) {
//No additional actions required
}
return outVal;
}//end GetSeparationAlgorithmPercentileParameter
bool StainProfile::SetSeparationAlgorithmPercentileParameter(const double& p) {
std::string type = this->pTypePercentile();
std::stringstream ss;
ss << p; // << std::endl;
return this->SetSingleSeparationAlgorithmParameter(type, ss.str());
}//end SetSeparationAlgorithmPercentileParameter
const int StainProfile::GetSeparationAlgorithmHistogramBinsParameter() const {
std::string type = this->pTypeHistoBins();
std::string oss = this->GetSingleSeparationAlgorithmParameter(type);
int outVal(-1); //Set error value here
//Convert oss to int, if possible. Catch all exceptions (invalid_argument and out_of_range)
try {
outVal = std::stoi(oss);
}
catch (...) {
//No additional actions required
}
return outVal;
}//end GetSeparationAlgorithmHistogramBinsParameter
bool StainProfile::SetSeparationAlgorithmHistogramBinsParameter(const int& p) {
std::string type = this->pTypeHistoBins();
std::stringstream ss;
ss << p; // << std::endl;
return this->SetSingleSeparationAlgorithmParameter(type, ss.str());
}//end SetSeparationAlgorithmHistogramBinsParameter
<file_sep>/StainProfile.h
/*=============================================================================
*
* Copyright (c) 2021 Sunnybrook Research Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*=============================================================================*/
#ifndef SEDEEN_SRC_PLUGINS_STAINANALYSIS_STAINPROFILE_H
#define SEDEEN_SRC_PLUGINS_STAINANALYSIS_STAINPROFILE_H
#include <string>
#include <vector>
#include <array>
#include <memory>
#include <map>
#include "StainVectorMath.h"
//TinyXML2 system for XML handling
#include <tinyxml2.h>
//Macro to exit from a method/function if an XML operation was unsuccessful
#ifndef XMLCheckResult
#define XMLCheckResult(a_eResult) if (a_eResult != tinyxml2::XML_SUCCESS) { return a_eResult; }
#endif
///Class to read and write stain vector profile data to XML files.
///Avoids invoking the Sedeen SDK. Uses TinyXML2 for XML file interactions.
///Stores data in the member XMLDocument structure
class StainProfile
{
public:
///No-parameter constructor (builds XMLDocument structure)
StainProfile();
///Copy constructor
StainProfile(StainProfile &s);
///destructor
virtual ~StainProfile();
///Get/Set the name of the stain profile
bool SetNameOfStainProfile(const std::string &);
///Get/Set the name of the stain profile
const std::string GetNameOfStainProfile() const;
///Get/Set the number of stain components in the profile
bool SetNumberOfStainComponents(const int &);
///Get/Set the number of stain components in the profile
const int GetNumberOfStainComponents() const;
///Get/Set the name of stain one
bool SetNameOfStainOne(const std::string &);
///Get/Set the name of stain one
const std::string GetNameOfStainOne() const;
///Get/Set the name of stain two
bool SetNameOfStainTwo(const std::string &);
///Get/Set the name of stain two
const std::string GetNameOfStainTwo() const;
///Get/Set the name of stain three
bool SetNameOfStainThree(const std::string &);
///Get/Set the name of stain three
const std::string GetNameOfStainThree() const;
///Get/Set the name of the stain analysis model currently selected
bool SetNameOfStainAnalysisModel(const std::string &);
///Get/Set the name of the stain analysis model currently selected
const std::string GetNameOfStainAnalysisModel() const;
///Get/Set the name of the stain separation method currently selected
bool SetNameOfStainSeparationAlgorithm(const std::string &);
///Get/Set the name of the stain separation method currently selected
const std::string GetNameOfStainSeparationAlgorithm() const;
///Set the RGB values for stain one as three doubles
bool SetStainOneRGB(const double&, const double&, const double&);
///Overload: Set the RGB values for stain one as a three-element C-style array
bool SetStainOneRGB(double[]);
///Overload: Set the RGB values for stain one as a C++11 std::array of three doubles
bool SetStainOneRGB(const std::array<double, 3> &);
///Get the RGB values for stain one as a C++11 std::array of three doubles
const std::array<double, 3> GetStainOneRGB() const;
///Set the RGB values for stain two as three doubles
bool SetStainTwoRGB(const double&, const double&, const double&);
///Overload: Set the RGB values for stain two as a three-element C-style array
bool SetStainTwoRGB(double[]);
///Overload: Set the RGB values for stain two as a C++11 std::array of three doubles
bool SetStainTwoRGB(const std::array<double, 3> &);
///Get the RGB values for stain two as a C++11 std::array of three doubles
const std::array<double, 3> GetStainTwoRGB() const;
///Set the RGB values for stain three as three doubles
bool SetStainThreeRGB(const double&, const double&, const double&);
///Overload: Set the RGB values for stain three as a three-element C-style array
bool SetStainThreeRGB(double[]);
///Overload: Set the RGB values for stain three as a C++11 std::array of three doubles
bool SetStainThreeRGB(const std::array<double, 3> &);
///Get the RGB values for stain three as a C++11 std::array of three doubles
const std::array<double, 3> GetStainThreeRGB() const;
public:
///Public write method - returns true/false for success/failure
bool writeStainProfile(const std::string &);
///Public read method - checks file existence first, returns true/false for success/failure
bool readStainProfile(const std::string &);
/// Public read method - reads profile from embedded resource
bool readStainProfile(const char *, size_t);
///General method for retrieving the index position of a given string within a vector of strings, returns -1 if not found
const int GetVectorIndexFromName(const std::string &name, const std::vector<std::string> &vec) const;
///General method for retrieving a name from a given vector at a given index, protected from range errors.
const std::string StainProfile::GetValueFromStringVector(const int &index, const std::vector<std::string> &vec) const;
///Request the list of possible stain analysis model names from the class (presently one option)
const std::vector<std::string> GetStainAnalysisModelOptions() const;
///Request an element of the vector of stain analysis models. Returns std::string() on error.
const std::string GetStainAnalysisModelName(const int &index) const;
///Request the list of possible stain separation algorithm names from the class, static defined in constructor
const std::vector<std::string> GetStainSeparationAlgorithmOptions() const;
///Request an element of the vector of stain separation algorithms. Returns std::string() on error.
const std::string GetStainSeparationAlgorithmName(const int &index) const;
///Get the raw (no normalization applied) stain vector profiles and assign to a 9-element double array
bool GetProfilesAsDoubleArray(double (&profileArray)[9]) const;
///Normalize each vector to 1, then assign the stain vector profiles to a 9-element double array
bool GetNormalizedProfilesAsDoubleArray(double (&profileArray)[9]) const;
///Get the stain vector profiles, normalized or not depending on second parameter, and assign to a 9-element double array
bool GetProfilesAsDoubleArray(double (&profileArray)[9], bool) const;
///Set the values of the stain vector profiles from a 9-element double array
bool SetProfilesFromDoubleArray(double (&profileArray)[9]);
///Check if the file exists and accessible for reading or writing, or that the directory to write to exists
static bool checkFile(const std::string &, const std::string &);
///Check if the basic structure of the stain profile has been assembled
inline bool CheckProfile() { return CheckXMLDocument(); }
///Clear the entire contents of the stain profile
inline bool ClearProfile() { return ClearXMLDocument(); }
///Clear the stain vector values only (no changes to text fields)
bool ClearStainVectorValues();
///Remove all of the child nodes of an element, either all or of a specified tag
bool ClearChildren(tinyxml2::XMLElement* el, const std::string &tag = std::string());
///Clear the analysis model parameters (remove nodes)
bool ClearAllAnalysisModelParameters();
///Clear the separation algorithm parameters (remove nodes)
bool ClearAllSeparationAlgorithmParameters();
///Remove the first child node of an element with a optional tag, optional attribute, and optional attribute value
bool RemoveSingleChild(tinyxml2::XMLElement* el, const std::string &tag = std::string(),
const std::string &att = std::string(), const std::string &val = std::string());
///Remove a single analysis model parameter node with the given param-type value
bool RemoveAnalysisModelParameter(const std::string &pType);
///Remove a single separation algorithm parameter node with the given param-type value
bool RemoveSeparationAlgorithmParameter(const std::string &pType);
public:
///Get all of the parameters for a given element, return empty map on error or no parameters
const std::map<std::string, std::string> GetAllParameters(tinyxml2::XMLElement* el) const;
///Set all of the parameters for a given element, clear and replace all parameters
bool SetAllParameters(tinyxml2::XMLElement* el, const std::map<std::string, std::string>& p);
///Get all of the stain analysis model parameters
const std::map<std::string, std::string> GetAllAnalysisModelParameters() const;
///Set all of the stain analysis model parameters, clear any current values
bool SetAllAnalysisModelParameters(const std::map<std::string, std::string>& p);
///Get all of the separation algorithm parameters
const std::map<std::string, std::string> GetAllSeparationAlgorithmParameters() const;
///Set all of the separation algorithm parameters, clear any current values
bool SetAllSeparationAlgorithmParameters(const std::map<std::string, std::string>& p);
///Get a single parameter with a given param-type from the given element, return empty string if not found
const std::string GetSingleParameter(tinyxml2::XMLElement* el, const std::string &type) const;
///Set a single parameter with a given param-type as a child of the given element, create if it does not exist
bool SetSingleParameter(tinyxml2::XMLElement* el, const std::string &type, const std::string &val);
///Get a single stain analysis model parameter, return empty string if not found
const std::string GetSingleAnalysisModelParameter(const std::string &type) const;
///Set a single stain analysis model parameter, create if it does not exist
bool SetSingleAnalysisModelParameter(const std::string &type, const std::string &val);
///Get a single stain separation algorithm parameter, return empty string if not found
const std::string GetSingleSeparationAlgorithmParameter(const std::string &type) const;
///Set a single separation algorithm parameter, create if it does not exist
bool SetSingleSeparationAlgorithmParameter(const std::string &type, const std::string &val);
///Set/Get the SeparationAlgorithm NumPixels parameter
const long int GetSeparationAlgorithmNumPixelsParameter() const;
///Set/Get the SeparationAlgorithm NumPixels parameter
bool SetSeparationAlgorithmNumPixelsParameter(const long int& p);
///Set/Get the SeparationAlgorithm Threshold parameter
const double GetSeparationAlgorithmThresholdParameter() const;
///Set/Get the SeparationAlgorithm Threshold parameter
bool SetSeparationAlgorithmThresholdParameter(const double & p);
///Set/Get the SeparationAlgorithm Percentile parameter
const double GetSeparationAlgorithmPercentileParameter() const;
///Set/Get the SeparationAlgorithm Percentile parameter
bool SetSeparationAlgorithmPercentileParameter(const double& p);
///Set/Get the SeparationAlgorithm HistogramBins parameter
const int GetSeparationAlgorithmHistogramBinsParameter() const;
///Set/Get the SeparationAlgorithm HistogramBins parameter
bool SetSeparationAlgorithmHistogramBinsParameter(const int& p);
public:
//XML tag strings
//The root tag and one attribute
static inline const char* rootTag() { return "stain-profile"; }
static inline const char* nameOfStainProfileAttribute() { return "profile-name"; }
//The components tag and one attribute
static inline const char* componentsTag() { return "components"; }
static inline const char* numberOfStainsAttribute() { return "numstains"; }
//The stain tag and two attributes
static inline const char* stainTag() { return "stain"; }
static inline const char* indexOfStainAttribute() { return "index"; }
static inline const char* nameOfStainAttribute() { return "stain-name"; }
//The stain value tag and one attribute
static inline const char* stainValueTag() { return "stain-value"; }
static inline const char* valueTypeAttribute() { return "value-type"; }
//The analysis model tag and one attribute
static inline const char* analysisModelTag() { return "analysis-model"; }
static inline const char* analysisModelNameAttribute() { return "model-name"; }
//The algorithm tag and one attribute
static inline const char* algorithmTag() { return "algorithm"; }
static inline const char* algorithmNameAttribute() { return "alg-name"; }
//The parameter tag and one attribute
static inline const char* parameterTag() { return "parameter"; }
static inline const char* parameterTypeAttribute() { return "param-type"; }
//Parameter type possible values
static inline const char* pTypeNumPixels() { return "num-pixels"; }
static inline const char* pTypeThreshold() { return "threshold"; }
static inline const char* pTypePercentile() { return "percentile"; }
static inline const char* pTypeHistoBins() { return "histo-bins"; }
private:
///Build the XMLDocument data structure
bool BuildXMLDocument();
///Check if the basic structure of the member XMLDocument has been assembled
bool CheckXMLDocument();
///Clear the entire contents of the member XMLDocument
bool ClearXMLDocument();
///If file is able to be opened, write the current stain profile to file as XML
tinyxml2::XMLError writeStainProfileToXML(const std::string &);
///If file is able to be opened, read from an XML file and fill variables in this class
tinyxml2::XMLError readStainProfileFromXMLFile(const std::string &);
///Read a stain profile from a string
tinyxml2::XMLError readStainProfileFromXMLString(const char *, size_t);
//Parse XML document
tinyxml2::XMLError parseXMLDoc();
private:
///Store the list of possible stain analysis model names here
const std::vector<std::string> m_stainAnalysisModelOptions;
///Store the list of possible stain separation algorithm names here
const std::vector<std::string> m_stainSeparationAlgorithmOptions;
///An XML document associated with this class: note that elements can't be smartpointers
std::shared_ptr<tinyxml2::XMLDocument> m_xmlDoc;
///Get pointer to the member m_xmlDoc
inline std::shared_ptr<tinyxml2::XMLDocument> GetXMLDoc() { return m_xmlDoc; }
///root element: cannot be a smartpointer because destructor is private and XMLDocument must handle memory management
tinyxml2::XMLElement* m_rootElement;
///components element
tinyxml2::XMLElement* m_componentsElement;
///stain elements
tinyxml2::XMLElement* m_stainOneElement;
tinyxml2::XMLElement* m_stainTwoElement;
tinyxml2::XMLElement* m_stainThreeElement;
///stain analysis model element
tinyxml2::XMLElement* m_analysisModelElement;
///algorithm element
tinyxml2::XMLElement* m_algorithmElement;
};
#endif
|
b6041a588d1b0e7ae421ae82a053e047c58240d1
|
[
"Markdown",
"CMake",
"C++"
] | 10 |
Markdown
|
mschumak/StainAnalysis-plugin
|
3c236139d69453fbd6bddf58d3ed715bd8d2802f
|
22cbcbb773d541e6794ef182ab1d1c0b227e8850
|
refs/heads/master
|
<file_sep># Tietokantakaavio

### Create table lauseet
CREATE TABLE account (
id INTEGER NOT NULL,
date_created DATETIME,
date_modified DATETIME,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(144) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE item (
id INTEGER NOT NULL,
date_created DATETIME,
date_modified DATETIME,
name VARCHAR(100) NOT NULL,
user_id INTEGER NOT NULL,
category VARCHAR(100) NOT NULL,
brand VARCHAR(100) NOT NULL,
weight INTEGER NOT NULL,
volume NUMERIC(5) NOT NULL,
description VARCHAR(500) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY(user_id) REFERENCES account (id)
);
CREATE TABLE gearlist (
id INTEGER NOT NULL,
date_created DATETIME,
date_modified DATETIME,
name VARCHAR(100) NOT NULL,
user_id INTEGER NOT NULL,
description VARCHAR(500) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY(user_id) REFERENCES account (id)
);
CREATE TABLE list_items (
list_id INTEGER,
item_id INTEGER,
FOREIGN KEY(list_id) REFERENCES gearlist (id),
FOREIGN KEY(item_id) REFERENCES item (id)
);
<file_sep>from application import db, bcrypt
from application.models import namedCreated
userRoles = db.Table('user_roles',
db.Column('user_id', db.Integer, db.ForeignKey('account.id')),
db.Column('role_id', db.Integer, db.ForeignKey('role.id'))
)
class Role(db.Model):
__tablename__ = "role"
id = db.Column(db.Integer, primary_key = True)
role = db.Column(db.String(50), nullable = False)
def __init__(self, role):
self.role = role
class User(namedCreated):
__tablename__ = "account"
email = db.Column(db.String(100), nullable=False)
password = db.Column(db.String(60), nullable=False)
items = db.relationship("Item", backref='item', lazy=True)
gearlists = db.relationship("GearList", backref='gearlist', lazy=True, cascade="all,delete")
roles = db.relationship("Role", secondary=userRoles, backref=db.backref('roles'), lazy='dynamic')
def __init__(self, name, email, password):
self.name = name
self.email = email
self.password = <PASSWORD>.generate_password_hash(password).decode('utf-8')
def get_id(self):
return self.id
def is_active(self):
return True
def is_anonymous(self):
return False
def is_authenticated(self):
return True
def has_role(self, role):
for user_role in self.roles:
if user_role.role == role:
return True
return False
<file_sep>#Parannuksia ja puuttuvia featureita
**Puutteita ja bugeja**
+ Varustelistan nimen ja kuvauksen päivityksestä puuttu ilmoitus. Yleensäkin ilmoituksia voisi parantaa.
+ Varusteen, varustelistan tai käyttäjän poistamista ei varmenneta.
+ Desimaalit bugittavat paikoitellen.
+ Käyttäjän ja varustelistan poistamisen yhteydessä pitäisi vielä tutkia miten olisi järkevä toimia riippuvuuksien kanssa. Nyt tietokannan riippuvuuden poistetaan koodilla, mikä ei tunnu kovin siistiltä, tietokantaan on ilmeisesti mahdollista lisätä tieto miten toimia näissä tapauksissa, mutten ehtinyt saada sitä tässä toimimaan.
**Jatkokehitysideoita**
+ Kategorian sijaan, ehkä tägäys toimisi paremmin.
+ Hakutoiminto.
+ Listojen järjestäminen parametrin mukaan. Parantaa käytettävyyttä erityisesti varusteiden määrän kasvaessa.
+ Jonkinlainen checklist toiminnallisuus, tätä voisi käyttää kamoja pakatessa, varmistamaan että kaikki tuli mukaan.
+ Listoihin voisi lisätä myös jonkinlaisen kommentointikentän, johon muutkin käyttäjät voisivat lisätä kommentteja.
+ Tietyn käyttäjän varustelistojen listaaminen.
+ Adminille lisää työkaluja.<file_sep># Sovelluksen asentaminen
Sovellus on tarkoitettu pääasiassa käytettäväksi web-sovelluksena nettiselaimen kautta. Sovelluksen voi kuitenkin asentaa myös omalle koneelle, kokeilua tai muokkaamista varten.
Nämä asennusohjeet käsittelevät asentamista linux-ympäristössä.
#### Asentaminen paikallisesti
Ohjelman paikallista asentamista ja ajamista varten käyttäjällä tulee olla asennettuna python3 ja sqlite3, sekä mahdollisesti git.
**Lataaminen omalle koneelle**
Lataa sovellus zip-tiedostona githubista 'Clone or download' -linkin takaa. Pura tiedosto haluamaasi kansioon.
Vaihtoehtoisesti voit kloonata projektin omalle koneellesi komennolla:
$ git clone https://github.com/juhakaup/ReissuReppu.git
Tällöin koneellasi tulee olla asennettuna myös git.
**Asennus**
Navigoi komentorivillä kansioon johon purit zip-paketin tai kloonasit projektin.
Mene kansioon ReissuReppu.
Luo virtuaaliympäristö ja käynnistä se komennoilla:
$ python3 -m venv venv
$ source venv/bin/activate
Komentorivillä pitäisi nyt lukea (venv) rivin alussa, virtuaaliympäristön käynnissäolon merkiksi.
Asenna nyt sovelluksen tarvitsemat paketit komennolla:
(venv) $ pip install -r requirements.txt
Jos asennuksessa ilmenee ongelmia voit yrittää päivittää itse pip -sovelluksen komennolla:
(venv) $ pip install --upgrade pip
**Ohjelman ajaminen**
Jos kaikki paketit asentuivat onnistuneesti, sovellus voidaan nyt käynnistää komennolla:
(venv) $ python run.py
Sovelluksen pitäisi olla nyt käynnissä ja komentorivillä teksti:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Ennen sovellukseen käyttämistä, pitää sen tietokantaan vielä lisätä tiedot käyttäjärooleista.
Avaa tietokanta sqlite3:lla ja lisää käyttäjäroolit.
$ sqlite3 application/gearlists.db
sqlite> INSERT INTO role (role) VALUES ('ADMIN'), ('USER');
sqlite> .exit
Sovellusta voi nyt käyttää nettiselaimella osoitteessa: http://127.0.0.1:5000/
**Administrator oikeuksien lisääminen käyttäjälle**
Jotta sovelluksen admin-tason työkaluihin pääsisi käsiksi, täytyy jonkin käyttäjän rooleihin lisätä tämä taso. Tämä onnistuu jälleen sqliten avulla. Esimerkissä lisätään käyttäjätaso käyttäjälle jonka id on 1.
$ sqlite3 application/gearlists.db
sqlite> INSERT INTO user_roles (user_id, role_id) VALUES (1,1);
sqlite> .exit
#### Asentaminen Herokuun
Asenna ohjelma ensin paikallisesti, yllä olevien ohjeiden mukaan.
Tämän jälkeen, luo käyttäjätunnus herokuun ja asenna Herokun CLI työkalut.
Ohjeita tähän löytyy täältä: https://devcenter.heroku.com/articles/heroku-cli
Kun olet asentanut työkalut, kirjaudu komentorivillä tilillesi ohjeiden mukaan.
Ennen projektin siirtämistä, pitää Herokuun luoda paikka uudelle sovellukselle.
Tämä onnistuu myös nettiselaimen kautta, mutta luo paikka komentorivillä:
$ heroku create sovelluksen-nimi
Komentorivillä näet sovelluksen osoitteen herokussa.
Lisää sovellus vielä gittiin:
$ git remote add heroku sovelluksen-osoite
Kommitoi tekemäsi muutokset ja siirrä sovellus verkkoon:
$ git add .
$ git commit -m "Sovelluksen siirto herokuun"
$ git push heroku master
Sovellus on nyt verkossa.
Herokuun täytyy vielä määritellä ympäristömuuttuja ja luoda tietokanta jotta sovellus toimisi oikein.
$ heroku config:set HEROKU=1
$ heroku addons:add heroku-postgresql:hobby-dev
Palvelimen tietokantaan on vielä lisättävä käyttäjäroolit.
$ heroku pg:psql
DATABASE=> INSERT INTO role (role) VALUES ('ADMIN'), ('USER');
DATABASE=> \q
Sovellus on nyt käytettävissä nettiselaimella herokun antamassa osoitteessa.<file_sep># ReissuReppu
**Sovellus retkeilyvarustelistojen koostamiseen**
Sovellus retkeilyä harrastavalle tai retkeilystä kiinnostuneelle.
Sovelluksessa kuka tahansa voi tarkistella sovellukseen talletettuja varustelistoja ja suunnitella niiden pohjalta omia varustelistojaan.
Rekisteröitynyt käyttäjä voi myös luoda, muokata ja poistaa omia varustelistojaan sekä lisätä palveluun omia varusteitaan. Rekisteröitynyt käyttäjä voi myös merkitä sovelluksessa olevia varusteita omaan listaansa, jolloin ne ovat käytettävissä omia varustelistoja laadittaessa.
Lisäksi administrator-tason käyttäjä voi poistaa sovelluksesta
Toimintoja:
+ Käyttäjätilin luominen
+ Kirjautuminen
+ Varustelistausten tarkistelu
+ Varustelistausten luominen, muokkaaminen ja poistaminen
+ Varusteiden syöttö, muokkaus ja poisto
+ Varusteiden valinta omaan listaan
[Käyttöohje](https://github.com/juhakaup/ReissuReppu/blob/master/documents/kayttoohje.md)
[Asennusohje](https://github.com/juhakaup/ReissuReppu/blob/master/documents/asennusohje.md)
[Käyttötapaukset](https://github.com/juhakaup/ReissuReppu/blob/master/documents/kayttotapaukset.md)
[Tietokantakaavio ja create table lauseet](https://github.com/juhakaup/ReissuReppu/blob/master/documents/tietokanta.md)
[Puutteita ja parannuksia](https://github.com/juhakaup/ReissuReppu/blob/master/documents/puutteet.md)
**Sovellus verkossa:**
[Linkki sovellukseen](https://reissureppu.herokuapp.com/)
Sovellukseen voi kirjautua tunnuksilla:
Email | Salasana | Rooli
--- | --- | ---
<EMAIL> | salasana | Peruskäyttäjä
<EMAIL> | salasana | Admin
<file_sep>from application import app, db
from application.items.models import Item
from application.items.forms import ItemForm
from flask import redirect, render_template, request, url_for
from flask_login import login_required, current_user
import copy
# Lists all the items
@app.route("/items", methods=["GET"])
def items_index():
userItems = None
otherItems = Item.non_user_items(-1) #Item.query.all()
if current_user.is_authenticated:
userItems = Item.user_items(current_user.id)
otherItems = Item.non_user_items(current_user.id)
return render_template("items/list.html", items = otherItems, userItems = userItems)
# Adding new item to db
@app.route("/items/new/", methods=["POST", "GET"])
@login_required
def item_create():
# New item form
if request.method=="GET":
return render_template("items/new.html", form = ItemForm())
# Form validation
form = ItemForm(request.form)
if not form.validate():
return render_template("items/new.html", form = form)
# Adding new item to db
item = Item(form.name.data)
item.brand = form.brand.data
item.category = form.category.data
item.weight = form.weight.data
item.volume = form.volume.data
item.description = form.description.data
item.user_id = current_user.id
db.session().add(item)
db.session().commit()
return redirect(url_for("items_index"))
# Adding a copy of an item to db for current user
@app.route("/items/copy/<item_id>", methods=["POST"])
@login_required
def item_copy(item_id):
item = Item.query.get(item_id)
newItem = Item(item.name)
newItem.brand = item.brand
newItem.category = item.category
newItem.weight = item.weight
newItem.volume = item.volume
newItem.description = item.description
newItem.user_id = current_user.id
db.session().add(newItem)
db.session().commit()
return redirect(url_for("items_index"))
# Editing existing item form
@app.route("/items/edit/<item_id>", methods=["GET"])
@login_required
def item_edit(item_id):
item = Item.query.get(item_id)
form = ItemForm()
form.name.data = item.name
form.brand.data = item.brand
form.category.data = item.category
form.weight.data = item.weight
form.volume.data = item.volume
form.description.data = item.description
form.user_id.data = item.user_id
form.id.data = item_id
return render_template("items/modify.html", form = form)
# Editing existing item
@app.route("/items/update/<item_id>", methods=["POST"])
@login_required
def item_update(item_id):
item = Item.query.get(item_id)
form = ItemForm(request.form)
form.id.data = item_id
# Form validation
if not form.validate():
return render_template("items/modify.html", form = form)
# Update item in db
item.name = form.name.data
item.brand = form.brand.data
item.category = form.category.data
item.weight = form.weight.data
item.volume = form.volume.data
item.description = form.description.data
db.session().commit()
return redirect(url_for("items_index"))
# Delete item from db
@app.route("/items/rm/<item_id>", methods=["POST"])
@login_required
def item_rm(item_id):
item = Item.query.get(item_id)
db.session.delete(item)
db.session.commit()
userItems = Item.user_items(current_user.id)
otherItems = Item.non_user_items(current_user.id)
return render_template("items/list.html", items = otherItems, userItems = userItems)<file_sep>from application import db
from application.models import namedCreated
from sqlalchemy.sql import text
class Item(namedCreated):
__tablename__ = "item"
user_id = db.Column(db.Integer, db.ForeignKey('account.id'), nullable=False)
category = db.Column(db.String(100), nullable=False)
brand = db.Column(db.String(100), nullable=False)
weight = db.Column(db.Integer, nullable=False)
volume = db.Column(db.Numeric(5), nullable=False)
description = db.Column(db.String(500), nullable=False)
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.id == other.id
def __ne__(self, other):
return self.id != other.id
@staticmethod
def user_items(user_id):
stmt = text("SELECT item.id, item.user_id, item.name, item.category, item.brand, item.weight, item.volume, item.description "
"FROM item WHERE item.user_id = :user_id;").params(user_id = user_id)
res = db.engine.execute(stmt)
response = []
for row in res:
response.append ({"id":row[0], "user_id":row[1], "name":row[2], "category":row[3], "brand":row[4], "weight":row[5], "volume":row[6], "description":row[7]})
return response
@staticmethod
def non_user_items(user_id):
stmt = text("SELECT item.id, item.user_id, item.name, item.category, item.brand, item.weight, item.volume, item.description "
"FROM item WHERE NOT item.user_id = :user_id;").params(user_id = user_id)
res = db.engine.execute(stmt)
response = []
for row in res:
response.append ({"id":row[0], "user_id":row[1], "name":row[2], "category":row[3], "brand":row[4], "weight":row[5], "volume":row[6], "description":row[7]})
return response
<file_sep>from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, TextAreaField, validators
class ListsForm(FlaskForm):
name = StringField("Name", [validators.Length(min=2, max=100), validators.Regexp(r'^[a-zA-Z0-9 öäå!@#$%^&*(),.?":{}|<>]*$')])
description = TextAreaField("Description", [validators.Length(min=2, max=500), validators.Regexp(r'^[a-zA-Z0-9 öäå!@#$%^&*(),.?":{}|<>]*$')])
class Meta:
csrf = False<file_sep>from flask_wtf import FlaskForm
from wtforms import PasswordField, StringField, validators
class LoginForm(FlaskForm):
email = StringField("Email", [validators.Length(min=2, max=100, message=("Please provide a valid email address."))])
password = PasswordField("Password", [validators.Length(min=4), validators.data_required()])
class Meta:
csrf = False
class RegisterForm(FlaskForm):
email = StringField("Email", [validators.Length(min=2, max=100, message=("Email must be between 4 and 100 characters long.")), validators.Email()])
password = PasswordField("Password", [validators.Length(min=4, message=("Password must be between 4 and 100 characters long.")), validators.DataRequired()])
confirm = PasswordField("Confirm password", [validators.EqualTo("password", message="Passwords don't match")])
name = StringField("Name", [validators.Length(min=2, max=144, message=("Name must be between 4 and 100 characters long.")), validators.Regexp(r'^[a-zA-Z0-9 öäå!@#$%^&*(),.?":{}|<>]*$')])
class Meta:
csrf = False<file_sep><!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="utf-8">
<title>ReissuReppu</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{{url_for('static', filename='style.css')}}">
</head>
<body>
<div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom box-shadow">
<h5 class="my-0 mr-md-auto font-weight-normal"> ReissuReppu</h5>
<nav class="my-2 my-md-0 mr-md-3">
<a class="p-2 text-dark" href="{{ url_for('lists_index') }}">Gearlists</a>
<a class="p-2 text-dark" href="{{ url_for('list_create') }}">New Gearlist</a>
<a class="p-2 text-dark" href="{{ url_for('items_index') }}">Browse Items</a>
<a class="p-2 text-dark" href="{{ url_for('item_create') }}">Add New Item</a>
</nav>
{% if current_user.is_authenticated %}
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{ current_user.name }}</a>
<div class="dropdown-menu" aria-labelledby="dropdown01">
<a class="dropdown-item" href="{{ url_for('auth_logout') }}">Logout</a>
{% if current_user.has_role("ADMIN") %}
<a class="dropdown-item" href="{{ url_for('list_users') }}">Users</a>
{% endif %}
</div>
{% else %}
<a class="btn btn-outline-primary" href="{{ url_for('auth_login') }}">Login/Register</a>
{% endif %}
</div>
{% block body %}
<p>
Content.
</p>
{% endblock %}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep>from application import app, db
from application.gearlists.models import GearList
from application.gearlists.forms import ListsForm
from application.items.models import Item
from flask_login import login_required, current_user
# flask
from flask import redirect, render_template, request, url_for
from flask_login import login_required
# Listing all gearlists
@app.route("/lists", methods=["GET"])
def lists_index():
userLists = None
if current_user.is_authenticated:
userLists = GearList.user_lists(current_user.id)
return render_template("gearlists/list.html", allLists = GearList.all_lists(), userLists = userLists)
# Viewing a gearlist
@app.route("/lists/<list_id>", methods=["GET"])
def view_list(list_id):
gearlist = GearList.query.get(list_id)
return render_template("gearlists/view.html", gearlist = gearlist, items = gearlist.items, )
# Creating new gearlist
@app.route("/lists/new/", methods=["POST", "GET"])
@login_required
def list_create():
# form for creating new gearlist
if request.method=="GET":
return render_template("gearlists/new.html", form = ListsForm())
# adding new gearlist to db
form = ListsForm(request.form)
if not form.validate():
return render_template("gearlists/new.html", form = form)
gearlist = GearList(name=form.name.data, user_id=current_user.id, description=form.description.data)
db.session().add(gearlist)
db.session().commit()
return render_template("gearlists/modify.html", gearlist = gearlist, items = gearlist.items,
availableItems = gearlist.available_items(gearlist.user_id), form = form)
# Modify existing gearlist form
@app.route("/lists/modify/<list_id>", methods=["POST"])
@login_required
def modify_list(list_id):
gearlist = GearList.query.get(list_id)
if not (gearlist.user_id == current_user.id or current_user.has_role("ADMIN")):
return redirect(url_for("lists_index"))
form = ListsForm()
form.name.data = gearlist.name
form.description.data = gearlist.description
return render_template("gearlists/modify.html", gearlist = gearlist, items = gearlist.items,
availableItems = gearlist.available_items(gearlist.user_id), form = form)
# Update existing gearlist
@app.route("/lists/<list_id>", methods=["POST"])
@login_required
def update_list(list_id):
gearlist = GearList.query.get(list_id)
if not (gearlist.user_id == current_user.id or current_user.has_role("ADMIN")):
return redirect(url_for("lists_index"))
form = ListsForm(request.form)
if not form.validate():
return render_template("gearlists/modify.html", gearlist = gearlist, items = gearlist.items,
availableItems = gearlist.available_items(gearlist.user_id), form = form)
gearlist.name = form.name.data
gearlist.description = form.description.data
db.session.commit()
return render_template("gearlists/modify.html", gearlist = gearlist, items = gearlist.items,
availableItems = gearlist.available_items(gearlist.user_id), form = form)
# Remove gearlist
@app.route("/lists/rm/<list_id>", methods=["POST"])
@login_required
def delete_list(list_id):
gearlist = GearList.query.get(list_id)
if not (gearlist.user_id == current_user.id or current_user.has_role("ADMIN")):
return redirect(url_for("lists_index"))
for item in gearlist.items:
gearlist.items.remove(item)
db.session.commit()
db.session.delete(gearlist)
db.session.commit()
return redirect(url_for("lists_index"))
# Adding items to a gearlist
@app.route("/lists/<list_id>/<item_id>", methods=["POST"])
@login_required
def additem_list(list_id, item_id):
gearlist = GearList.query.get(list_id)
item = Item.query.get(item_id)
gearlist.items.append(item)
db.session.commit()
form = ListsForm()
form.name.data = gearlist.name
form.description.data = gearlist.description
return render_template("gearlists/modify.html",
gearlist = gearlist, items = gearlist.items,
availableItems = gearlist.available_items(gearlist.user_id), form=form)
# Remove item from a gearlist
@app.route("/lists/rm/<list_id>/<item_id>", methods=["POST"])
@login_required
def rmItem_list(list_id, item_id):
gearlist = GearList.query.get(list_id)
item = Item.query.get(item_id)
gearlist.items.remove(item)
db.session.commit()
form = ListsForm()
form.name.data = gearlist.name
form.description.data = gearlist.description
return render_template("gearlists/modify.html", gearlist = gearlist,
items = gearlist.items,
availableItems = gearlist.available_items(gearlist.user_id), form=form)
<file_sep>from flask import render_template, request, redirect, url_for
from flask_login import login_user, logout_user
from application import app, db, login_required, bcrypt
from application.auth.models import User, Role
from application.auth.forms import LoginForm, RegisterForm
# Login
@app.route("/auth/login", methods = ["GET", "POST"])
def auth_login():
# Login form
if request.method == "GET":
return render_template("auth/loginform.html", form = LoginForm())
# Form validation
form = LoginForm(request.form)
if not form.validate():
return render_template("auth/loginform.html", form = form)
# Check if user in db and password match
user = User.query.filter_by(email=form.email.data).first()
if not user or not bcrypt.check_password_hash(user.password, form.password.data):
return render_template("auth/loginform.html", form = form, error = "No such email or password")
login_user(user)
return redirect(url_for("lists_index"))
# Register new user
@app.route("/auth/register", methods = ["GET","POST"])
def register_user():
# Registeration form
if request.method == "GET":
return render_template("auth/new.html", form = RegisterForm(), error="")
# Form validation
form = RegisterForm(request.form)
if not form.validate():
return render_template("auth/new.html", form = form, error="")
# Check for existing user with the same email
user = User(form.name.data, form.email.data, form.password.data)
if User.query.filter_by(email=user.email).first():
return render_template("auth/new.html", form = form, error="An account with this email already exists")
# Adding new user to db
db.session().add(user)
user.roles.append(Role.query.filter_by(role="USER").first())
db.session().commit()
return redirect(url_for("auth_login"))
# Delete user
@app.route("/auth/rm/<user_id>", methods=["POST"])
@login_required(role="ADMIN")
def remove_user(user_id):
user = User.query.get(user_id)
for item in user.items:
db.session.delete(item)
db.session.delete(user)
db.session.commit()
return redirect(url_for("list_users"))
# Logout user
@app.route("/auth/logout")
def auth_logout():
logout_user()
return redirect(url_for("index"))
# Userlist
@app.route("/auth/")
@login_required(role="ADMIN")
def list_users():
users = User.query.all()
return render_template("/auth/list.html", users = users)
<file_sep>## Käyttötapaukset
**Käyttäjä**
+ Käyttäjä voi rekisteröityä palveluun
+ Käyttäjä voi kirjautua palveluun
+ Käyttäjä voi uloskirjautua palvelusta
-Käyttäjän lisääminen tietokantaan:
INSERT INTO account (name, email, password) VALUES ('<PASSWORD>', '<PASSWORD>', '<PASSWORD>');
+ Admin-tason käyttäjä voi poistaa toisen käyttäjän käyttäjätilin
-Käyttäjän poistaminen tietokannasta:
DELETE FROM account WHERE id = :user_id;
**Varustelistat**
+ Käyttäjä voi tarkistella varustelistauksia
-Kaikki varustelistat yhteenlaskettuine painoineen ja tilavuuksineen saadaan kyselyllä:
SELECT gearlist.id, gearlist.name, gearlist.description, account.name, SUM(item.weight), SUM(item.volume)
FROM gearlist
LEFT JOIN account ON gearlist.user_id = account.id
LEFT JOIN list_items ON gearlist.id = list_items.list_id
LEFT JOIN item ON list_items.item_id = item.id
GROUP BY gearlist.id, account.name);
+ Rekisteröitynyt käyttäjä voi tarkistella omia varustelistojaan
-Käyttäjän omat varustelistat yhteenlaskettuine painoineen ja tilavuuksineen saadaan samankaltaisella kyselyllä:
SELECT gearlist.id, gearlist.name, gearlist.description, account.name, SUM(item.weight), SUM(item.volume)
FROM gearlist
LEFT JOIN account ON gearlist.user_id = account.id
LEFT JOIN list_items ON gearlist.id = list_items.list_id
LEFT JOIN item ON list_items.item_id = item.id
WHERE account.id = :user_id
GROUP BY gearlist.id, account.name);
+ Rekisteröitynyt käyttäjä voi luoda omia varustelistoja
-Varustelistan syöttäminen tietokantaan:
INSERT INTO gearlist (name, user_id, description) VALUES ('Listan nimi', 'user_id', 'Kuvaus');
+ Rekisteröitynyt käyttäjä voi poistaa omia varustelistojaan
+ Admin-tason käyttäjä voi poistaa kenen tahansa varustelistoja
-Varustelistan poistaminen tietokannasta:
DELETE FROM gearlist WHERE id = :gearlist_id;
+ Rekisteröitynyt käyttäjä voi muokata omia varustelistojaan
+ Admin-tason käyttäjä voi muokata kenen tahansa varustelistoja
Varistelistaan voi lisätä varusteita jotka ovat käyttäjän omia ja joita ei ole vielä lisätty listaan.
-Näiden hakeminen onnistuu seuraavalla kyselyllä:
SELECT * FROM item
WHERE item.user_id = :user_id
AND item.id NOT IN (SELECT list_items.item_id FROM list_items WHERE list_items.list_id IS :list_id);
-Varusteen lisääminen varustelistaan:
INSERT INTO list_items (list_id, item_id) VALUES ('list_id' , 'item_id')
-Varusteen poistaminen varustelistasta:
DELETE FROM list_items WHERE list_id = :list_id AND item_id = :item_id;
**Varusteet**
+ Käyttäjä voi tarkistella varusteita listana
-Kaikki varusteet saadaan kyselyllä:
SELECT * FROM item WHERE NOT user_id = :user_id;
Jossa parametrina annetaan user_id = -1. Samalla kyselyllä saadaan listattua muut kun käyttäjän varusteet, antamalla parametrina käyttäjän id:n.
-Käyttäjän omien varusteiden listaaminen onnistuu kyselyllä:
SELECT * FROM item WHERE user_id = :user_id;
+ Rekisteröitynyt käyttäjä voi luoda omia varusteita
-Uuden varusteen lisääminen tietokantaan:
INSERT INTO item (name, user_id, category, brand, weight, volume, description)
VALUES ('nimi', 'user_id', 'kategoria', 'merkki', 'paino', 'tilavuus', 'kuvaus');
+ Rekisteröitynyt käyttäjä voi muokata omia varusteitaan
-Varusteen tietojen päivittäminen tietokannassa:
UPDATE item
SET name = 'nimi',
category = 'kategoria',
brand = 'merkki',
weight = 'paino',
volume = 'tilavuus',
description = 'kuvaus'
WHERE id = :item_id;
+ Rekisteröitynyt käyttäjä voi poistaa omia varusteitaan
-Varusteen poistaminen tietokannasta:
DELETE FROM item WHERE item_id = :item_id;
+ Rekisteröitynyt käyttäjä voi kopioida muiden tekemiä varusteita omaan listaansa
-Tietyn varusteen hakeminen tietokannasta:
SELECT * FROM item WHERE id = :item_id;
<file_sep>from application import db
from application.models import namedCreated
from sqlalchemy.sql import text
# gearlist items table
listItems = db.Table('list_items',
db.Column('list_id',db.Integer, db.ForeignKey('gearlist.id')),
db.Column('item_id',db.Integer, db.ForeignKey('item.id'))
)
class GearList(namedCreated):
__tablename__ = "gearlist"
user_id = db.Column(db.Integer, db.ForeignKey('account.id'), nullable=False)
description = db.Column(db.String(500), nullable=False)
items = db.relationship('Item', secondary=listItems, backref=db.backref('items'), lazy = 'dynamic')
def __init__(self, name, user_id, description):
self.name = name
self.user_id = user_id
self.description = description
@staticmethod
def all_lists():
stmt = text("SELECT gearlist.id, gearlist.name, gearlist.description, account.name, SUM(item.weight), SUM(item.volume) "
"FROM gearlist "
"LEFT JOIN account ON gearlist.user_id = account.id "
"LEFT JOIN list_items ON gearlist.id = list_items.list_id "
"LEFT JOIN item ON list_items.item_id = item.id "
"GROUP BY gearlist.id, account.name")
res = db.engine.execute(stmt)
response = []
for row in res:
response.append ({"list_id":row[0], "name":row[1], "description":row[2], "username":row[3], "weight":row[4], "volume":row[5]})
return response
@staticmethod
def user_lists(user_id):
stmt = text("SELECT gearlist.id, gearlist.name, gearlist.description, account.name, SUM(item.weight), SUM(item.volume) "
"FROM gearlist "
"LEFT JOIN account ON gearlist.user_id = account.id "
"LEFT JOIN list_items ON gearlist.id = list_items.list_id "
"LEFT JOIN item ON list_items.item_id = item.id "
"WHERE account.id = :user_id "
"GROUP BY gearlist.id, account.name").params(user_id=user_id)
res = db.engine.execute(stmt)
response = []
for row in res:
response.append ({"list_id":row[0], "name":row[1], "description":row[2], "username":row[3], "weight":row[4], "volume":row[5]})
return response
def available_items(self, user_id):
stmt = text("SELECT item.id, item.user_id, item.name, item.category, item.brand, item.weight, item.volume, item.description FROM item "
"WHERE item.user_id = :user_id "
"AND item.id NOT IN (SELECT list_items.item_id FROM list_items WHERE list_items.list_id = :gearlist_id);").params(user_id = user_id, gearlist_id = self.id)
res = db.engine.execute(stmt)
response = []
for row in res:
response.append ({"id":row[0], "user_id":row[1], "name":row[2], "category":row[3], "brand":row[4], "weight":row[5], "volume":row[6], "description":row[7]})
return response
def weight(self):
weight = 0
for item in self.items:
weight += item.weight
return weight
def volume(self):
volume = 0
for item in self.items:
volume += item.volume
return volume
def username(self):
stmt = text("SELECT account.name FROM gearlist "
"LEFT JOIN account ON gearlist.user_id = account.id "
"WHERE account.id = :user_id").params(user_id = self.user_id)
res = db.engine.execute(stmt)
response = res.first()
return response[0]
def noItems(self):
i=0
for item in self.items:
i=i+1
return i<file_sep>from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, FloatField, SelectField, validators
class ItemForm(FlaskForm):
name = StringField("Name", [validators.Length(min=2, max=100), validators.Regexp(r'^[a-zA-Z0-9 öäå!@#$%^&*(),.?":{}|<>]*$')])
user_id = IntegerField("User")
brand = StringField("Brand", [validators.Length(min=2, max=100), validators.Regexp(r'^[a-zA-Z0-9 öäå!@#$%^&*(),.?":{}|<>]*$')])
category = SelectField("Category",
choices=[('other', 'Other'), ('shelter', 'Shelter'), ('cooking', 'Cooking'), ('clothing', 'Clothing'),
('hygene', 'Hygene'), ('elec', 'Electronics'), ('sleeping', 'Sleeping'),
('nav', 'Navigation'), ('survival', 'Survival'), ('luxury', 'Luxury')])
weight = IntegerField("Weight in grams", [validators.NumberRange(min=0, max=100000)], default=0)
volume = FloatField("Volume in liters", [validators.NumberRange(min=0, max=99)], default=0)
description = StringField("Description", [validators.Length(min=2, max=500)])
id = IntegerField("id")
class Meta:
csrf = False<file_sep># Käyttöohje
## 1 Sovelluksen toiminta
Kirjautumaton käyttäjä voi tarkistella sovelluksessa olevia varusteita ja varustelistoja.
Varusteiden ja varustelistojen luomista varten on käyttäjän luotava käyttäjätunnus.
Käyttäjätunnuksen luomisen jälkeen käyttäjä voi luoda omia varusteita ja varustelistoja.
## 2 Palveluun rekisteröityminen
Jotta sovelluksessa voisi luoda omia varusteita ja varustelistoja, täytyy käyttäjän luoda ensin käyttäjätili.
#### 2.1 Käytäjätilin luominen
Käyttäjätilin luominen onnistuu etusivun 'Login/Register' -napin kautta. Login -sivun alalaidasta löytyy linkki uuden käyttäjätilin luomiseen; 'Create new account'.
Käyttäjätilin luominen onnistuu täyttämällä kaikki kentät ja painamalla 'Register'.
#### 2.2 Kirjautuminen
Sovellukseen kirjautuminen onnistuu kaikkien sivujen oikeasta ylälaidasta löytyvästä linkistä 'Login/Register'.
Käyttäjää pyydetään kirjautumaan myös silloin jos jokin hänen käyttämänsä toiminto edellyttää kirjautumista.
#### 2.3 Uloskirjautuminen
Kirjautunut käyttäjä voi uloskirjautua sovelluksen oikeasta ylälaidasta löytyvästä pudotusvalikosta, valitsemalla 'Logout'.
## 3 Varusteet
Kaikki palvelun varusteet saa näkyviin kohdasta 'Browse items'.
Rekisteröitynyt käyttäjä voi luoda sovellukseen omia varusteitaan.
Tällöin listataan erikseen käyttäjän omat varusteet ja muut palveluun luodut varusteet.
#### 3.1 Varusteen luominen
Varusteen luominen onnistuu valitsemalla yläpalkista 'Add new item'. Tästä aukeaa uusi sivu johon syötetään varusteen tiedot.
Varuste lisätään sovellukseen painamalla alalaidan nappia 'Add'.
#### 3.2 Varusteen muokkaaminen
Omien varusteiden muokkaaminen onnistuu varustelistan kautta, klikkaamalla varusteen tietojen jälkeen olevaa 'Edit' nappia. Tämä vie uudelle sivulle johon varusteen tiedot on listattu. Muokkauksien tekemisen jälkeen tiedot tallettuvat sovellukseen valitsemalla alalaidasta 'Update'.
#### 3.3 Varusteen poisto
Varustelistauksessa, käyttäjän omien varusteiden jälkeen on punainen 'Delete' nappi. Varusteen voi poistaa painamalla tätä.
Kyseinen varuste häviää kokonaan palvelusta, eikä sitä saa enää takaisin.
#### 3.4 Varusteen kopiointi
Käyttäjä voi kopioida muiden käyttäjien luomia varusteita omaan listaansa valitsemalla varustelistauksessa 'Add to my items'. Tämä luo kopion varusteesta käyttäjän varusteisiin jolloin sitä voi myös muokata ilman että toisen käyttäjän alkuperäinen varuste muuttuu.
## 4 Varustelistat
Palveluun luodut varustelistat saa listattua yläpalkin kohdasta 'Gearlists'.
#### 4.1 Varustelistan tarkistelu
Yksittäisen varustelistan sisältöä voi tarkistella valitsemalla varustelistausten listauksesta kohdan 'View'. Tämä vie sivulle jossa on listattuna varustelistan sisältämän varusteet ja näiden tiedot.
#### 4.2 Varustelistan luominen
Uuden varustelistan luominen onnistuu valitsemalla yläpalkista 'New Gearlist'. Tämä vie sivulle jossa syötetään varustelistan nimi ja kuvaus.
Tietojen syöttämisen jälkeen valitsemalla alalaidasta 'Add items to the list', luodaan varustelista palveluun ja siirrytään muokkamaan sen sisältöä. Tästä lisää seuraavassa kohdassa.
#### 4.3 Varustelistan sisällön muokkaaminen
Varustelistan muokkaminen. Varustelistan muokkaamiseen pääsee painamma Gearlists -sivulta varustelistan jälkeen olevaa edit -nappia.
Uuden varustelistan luomisen yhteydessä, siirrytään muokkausnäkymään automaatisesti.
Varusteiden lisääminen varustelistaan onnistuu sivun alalaidasta kohdasta 'User Items'. Kunkin varusteen perässä on nappi 'Add' -jota painamalla varuste siirtyy varustelistan sisältöön.
Varustelistan sisältö on listattu kohdassa 'Gearlist Items'. Varusteen poistaminen listasta onnistuu tästä kohdasta valitsemalla varusteen kohdalta 'Remove'.
|
131f3995dd99559f5aa8a8a6758de09a0afc8dfb
|
[
"Markdown",
"Python",
"HTML"
] | 16 |
Markdown
|
juhakaup/ReissuReppu
|
f35cb259b5c37fb279d9d91752c2a2f497dd74ba
|
1fabe3ed8cdb30eaccae2bf9228f3e73a88dba84
|
refs/heads/master
|
<repo_name>nuatmochoi/klgrade<file_sep>/0712.py
import tensorflow as tf
import numpy as np
import os
import cv2
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler
np.random.seed(777)
he=tf.contrib.layers.variance_scaling_initializer()
os.environ['CUDA_VISIBLE_DEVICE']='1'
# preprocessing
def train_data(dir,k): # for X
li=[]
train_list = os.listdir(dir)
train_list=train_list[100*k:100*(k+1):]
for img in train_list:
image=cv2.imread('/dog_and_cat/train/'+img, cv2.IMREAD_COLOR)
image=cv2.resize(image, (32, 32), interpolation=cv2.INTER_AREA)
li.append(image)
img_li=np.array(li)
return img_li/255
def convert_label(dir): # for Y
train_list=os.listdir(dir)
for i in train_list:
if "dog" in i:
idx=train_list.index(i)
train_list[idx]=1
elif "cat" in i:
idx = train_list.index(i)
train_list[idx]=0
train_list=np.array(train_list)
data=train_list.reshape(-1,1)
one_hot=OneHotEncoder(sparse=False,categories='auto')
one_hot.fit(data)
label=one_hot.transform(data)
np.random.shuffle(label)
return label
def test_data(dir):
test_list=os.listdir(dir)
test_list=test_list[10000:10300:]+test_list[22500:22800:]
size = len(test_list)
n_arr = np.empty((size, 32, 32, 3), np.float32)
for img in test_list:
image=cv2.imread('/dog_and_cat/train/'+img, cv2.IMREAD_COLOR)
image=cv2.resize(image, (32, 32), interpolation=cv2.INTER_AREA).astype(np.float32)
idx=test_list.index(img)
n_arr[idx]=image
np.random.shuffle(n_arr)
return n_arr/255
def test_label(dir):
test_list=os.listdir(dir)
test_list = test_list[10000:10300:]+test_list[22500:22800:]
for i in test_list:
if "dog" in i:
idx=test_list.index(i)
test_list[idx]=1
elif "cat" in i:
idx = test_list.index(i)
test_list[idx]=0
data=np.array(test_list).reshape(-1,1)
one_hot=OneHotEncoder(sparse=False,categories='auto')
one_hot.fit(data)
label=one_hot.transform(data)
np.random.shuffle(label)
return label
dir_test='/dog_and_cat/test1'
dir_train='/dog_and_cat/train' # 12500 cat, 12500 dog
batch_size=100
epoch_num=5
learning_rate=0.01
keep_prob=1
class Model:
def __init__(self, sess, name):
self.sess=sess
self.name=name
self.Process()
def Process(self):
with tf.variable_scope(self.name):
self.X=tf.placeholder(tf.float32,[None,32,32,3])
self.Y=tf.placeholder(tf.float32,[None,2])
# Layer1
L1=tf.layers.conv2d(self.X,32,3,(1,1),padding="SAME",activation=tf.nn.relu,kernel_initializer=he)
L1=tf.nn.max_pool(L1,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
# L1=tf.nn.dropout(L1,keep_prob)
print(L1.shape)
# Layer2
L2=tf.layers.conv2d(L1,64,3,(1,1),padding="SAME",activation=tf.nn.relu,kernel_initializer=he)
L2=tf.nn.max_pool(L2,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
# L2 = tf.nn.dropout(L2, keep_prob)
print(L2.shape)
# Layer3
L3=tf.layers.conv2d(L2,128,3,(1,1),padding="SAME",activation=tf.nn.relu,kernel_initializer=he)
L3=tf.nn.max_pool(L3,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
# L3 = tf.nn.dropout(L3, keep_prob)
L3_re=tf.reshape(L3,[-1,128*4*4])
print(L3.shape)
# fc
# layer4
W4=tf.get_variable("W4",shape=[128*4*4,650],initializer=he) # Conv. layer에서도 초기값이 어디냐에 따라 목표값을 찾는 과정이 다르므로 해줘야 한다.
b4=tf.Variable(tf.random_normal([650]))
L4=tf.nn.relu(tf.matmul(L3_re,W4)+b4)
print(L4.shape)
# layer5
W5=tf.get_variable("W5",shape=[650,2],initializer=he)
b5=tf.Variable(tf.random_normal([2]))
self.logits=tf.matmul(L4,W5)+b5 # 여기서는 그냥 output값 -> accuracy로 넘어갈 때 softmax 함수를 걸어줘야 함
print(self.logits.shape)
# calc cost func & optimizer
self.cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.logits,labels=self.Y)) # softmax 포함
self.optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(self.cost)
# accuracy
predict=tf.equal(tf.argmax(tf.nn.softmax(self.logits),1), tf.argmax(self.Y,1)) # 확률값
self.accuracy=tf.reduce_mean(tf.cast(predict,tf.float32))
def get_accuracy(self, x,y):
return self.sess.run(self.accuracy,feed_dict={self.X:x,self.Y:y})
def train(self, x, y):
return self.sess.run([self.cost,self.optimizer],feed_dict={self.X:x,self.Y:y})
# initializing
sess=tf.Session()
m1= Model(sess,'m1')
init=tf.global_variables_initializer()
sess.run(init)
print("learning start")
bat_y=convert_label(dir_train)
# seed=0
for epoch in range(epoch_num):
# seed+=1
# np.random.seed(seed)
avg_cost=0
total_batch=int(25000/batch_size)
tmp=0
for i in range(total_batch):
if 0<=i<100 or 125<=i<225:
batch_x = train_data(dir_train, i)
# np.random.shuffle(batch_x)
batch_y=bat_y[100*i:100*(i+1):]
# np.random.shuffle(batch_y)
c,_=m1.train(batch_x,batch_y)
avg_cost+=c/total_batch
tmp += 1
if tmp%10==0:print(tmp)
else:
pass
print("epoch:%04d"%(epoch+1)," cost:{:.9f}".format(avg_cost))
print("learning end")
x_test=test_data(dir_train)
y_test=test_label(dir_train)
print("accuracy:",m1.get_accuracy(x_test,y_test))<file_sep>/histogram.py
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('triangle.jpeg',cv2.IMREAD_GRAYSCALE)
img2=cv2.imread('triangle2.jpeg',cv2.IMREAD_GRAYSCALE)
img3=cv2.imread('triangle3.jpeg',cv2.IMREAD_GRAYSCALE)
img4=cv2.imread('triangle4.jpeg',cv2.IMREAD_GRAYSCALE)
img_list=[img,img2,img3,img4]
def which_more(image):
sum1 = 0
sum2 = 0
h,w=image.shape
for j in range(w):
for i in range(0,int(h/2)+1):
sum1+=image[i-1][j-1]
for i in range(int(h / 2), h + 1):
sum2 += image[i - 1][j - 1]
if abs(sum1-sum2)<200000: # 위아래 차이가 거의 나지 않을 때
sum1 = 0
sum2 = 0
for j in range(h):
for i in range(0, int(w / 2) + 1):
sum1 += image[j - 1][i - 1]
for i in range(int(w / 2), w + 1):
sum2 += image[j - 1][i - 1]
if sum1>sum2: big=90
else: big=270
else:
if sum1>sum2: big=180
else: big=0
return big
def Rotate(image,degree):
h,w =image.shape
if degree==90:
M=cv2.getRotationMatrix2D((w/2,h/2),90,1)
elif degree==180:
M = cv2.getRotationMatrix2D((w / 2, h / 2), 180, 1)
elif degree==270:
M = cv2.getRotationMatrix2D((w / 2, h / 2), 270, 1)
dst = cv2.warpAffine(image, M, (w, h))
return image
plt.imshow(Rotate(img_list[1],which_more(img_list[1])))
plt.show()<file_sep>/rotate.py
import numpy as np
import cv2
import matplotlib.pyplot as plt
import copy
import os
from skimage.transform import match_histograms
import scipy.ndimage
#최대 넓이를 가진 contour 추출
def getMaxContour(contours):
MaxArea = 0
Location = 0
for idx in range(0, len(contours)):
Area = cv2.contourArea(contours[idx])
if Area > MaxArea:
MaxArea = Area
Location = idx
MaxContour = np.array(contours[Location])
return MaxContour, MaxArea
#By Using Extreme point, Set angle
def condition(prev_angle,c0,x,y,set_flag):
box=cv2.boundingRect(c0)
x_c=box[0]; y_c=box[1];w_c=box[2];h_c=box[3]
M = cv2.moments(c0)
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])
leftmost = tuple(c0[c0[:, :, 0].argmin()][0])
rightmost = tuple(c0[c0[:, :, 0].argmax()][0])
topmost = tuple(c0[c0[:, :, 1].argmin()][0])
bottommost = tuple(c0[c0[:, :, 1].argmax()][0])
angle=None
if bottommost[1] > y * (14 / 15) and not (topmost[1] < 10) \
and not (leftmost[0] < 10) and not (rightmost[0] > x * (29 / 30)): # 바닥에 붙어있음
angle = 0
print("attach bottom")
elif topmost[1] < 10 and not (bottommost[1] > y * (29 / 30)) \
and not (rightmost[0] > x * (29 / 30)) and not (leftmost[0] < 10): # 위에 붙어있음
angle = 180
print("attach top")
if (bottommost[0] == leftmost[0] and leftmost[1] == bottommost[1]): # use frame
angle = 0
print("include dummy")
"""
if bottommost[1]>y*(14/15) and rightmost[0]>x*(14/15) and abs(bottommost[1]-rightmost[1])<int(y/3)\
and abs(bottommost[0]-rightmost[0])<int(w_c/2) and not topmost[0]>x*(29/30) and leftmost[0]<x*(1/3) : #5시->11시
if (topmost[0] < cx): #엄지가 밑으로 for flip
angle=-40
else:
angle=-40
print("little tilt minus")
if bottommost[1]>y*(14/15) and leftmost[0]<x*(1/15) and abs(bottommost[1]-leftmost[1])<int(y/3)\
and abs(bottommost[0]-leftmost[0])<int(w_c/2) and not topmost[0]<x*(1/30) and rightmost[0]>x*(2/3): #7시->1시
if (topmost[0] < cx): #엄지가 위로 for flip
angle=40
else:
angle=40
print("little tilt plus")
if topmost[1]<y*(1/15) and leftmost[0]<x*(1/15) and abs(topmost[1]-leftmost[1])<int(y/3)\
and abs(topmost[0]-leftmost[0])<int(w_c/2) and not bottommost[0]<x*(1/30): #and rightmost[0]>x*(2/3): #11시->5시
if (bottommost[0] < cx):
angle=130
else:
angle=130
print("little tilt reverse")
if topmost[1]<y*(1/15) and leftmost[0]>x*(14/15) and abs(topmost[1]-leftmost[1])<int(y/3)\
and abs(topmost[0]-leftmost[0])<int(w_c/2) and not bottommost[0]>x*(29/30): #and rightmost[0]>x*(2/3): #1시->7시
if (bottommost[0] < cx):
angle=-130
else:
angle=-130
print("little tilt reverse minus")
"""
if angle!=None:
set_flag=1
return angle,set_flag
if h_c>=w_c:
if abs(leftmost[1] - rightmost[1]) < 150:
if cy > rightmost[1] and cy > leftmost[1] and not(abs(rightmost[1]-bottommost[1])<10):
angle = 0
print("right,left > center")
elif cy < rightmost[1] and cy < leftmost[1] and not(abs(rightmost[1]-bottommost[1])<10):
angle = 180
print("right,left <center")
if angle!=None:
set_flag=1
return angle,set_flag
elif w_c>h_c:
if abs(topmost[0] - bottommost[0] < 150):
if cx < topmost[0] and cx < bottommost[0]:
angle = 90
print("top,bottom>center")
elif cx > topmost[0] and cx > bottommost[0]:
angle = -90
print("top,bottom<center")
else:
if rightmost[0] > x * (29 / 30) and not (bottommost[0]>x*(29/30)) and not (topmost[0]<x*(29/30)) :
angle = -90
print("attach right")
elif leftmost[0] < x * (1 / 30) and not (bottommost[0]<x*(1/30)) and not (topmost[0]<x*(1/30)):
angle = 90
print("attach left")
elif cy > rightmost[1] and cy > leftmost[1]:
angle = 0
print("right,left < center2")
elif cy < rightmost[1] and cy < leftmost[1]:
angle = 180
print("right,left >center2")
if angle != None:
set_flag=1
return angle,set_flag
else:
return prev_angle,set_flag
def Process(Src,count,set_flag):
r=10
h, w = Src.shape
tl = Src[0:int(round(h / r)), 0:int(round(w / r))]
tr = Src[0:int(round(h / r)), int(round((r - 1) * w / r)):w]
bl = Src[int(round((r - 1) * h / r)):h, 0:int(round(w / r))]
br = Src[int(round((r - 1) * h / r)):h, int(round((r - 1) * w / r)):w]
center=Src[int((2/5)*h):int((3/5)*h),int((2/5)*w):int((3/5)*w)]
sum_cen=0
for i in range(center.shape[0]):
for j in range(center.shape[1]):
sum_cen+=center[i][j]
avg_cen=sum_cen/(center.shape[0]*center.shape[1])
sum=0
for i in range(tl.shape[0]):
for j in range(tl.shape[1]):
sum += tl[i][j]
for i in range(tr.shape[0]):
for j in range(tr.shape[1]):
sum += tr[i][j]
for i in range(bl.shape[0]):
for j in range(bl.shape[1]):
sum += bl[i][j]
for i in range(br.shape[0]):
for j in range(br.shape[1]):
sum += br[i][j]
small_h, small_w = tl.shape
small_area = small_h * small_w
avg_pixel = sum / (small_area * 4)
#IMAGE PREPROCESSING
hist1=cv2.calcHist([Src],[0],None,[256],[0,256])
SrcImg=Src[int(h/10):int(9*h/10),int(w/10):int(9*w/10)]
normalizedImg = np.zeros((800, 800))
SrcImg = cv2.normalize(SrcImg, normalizedImg, 0, 255, cv2.NORM_MINMAX)
y,x=SrcImg.shape
try:
reference = cv2.imread("kah_add_390000.jpg",cv2.IMREAD_GRAYSCALE)
reference = cv2.resize(reference,(y,x),interpolation=cv2.INTER_AREA)
except Exception as e:
print(str(e))
hist2=cv2.calcHist([reference],[0],None,[256],[0,256])
compare=cv2.compareHist(hist1,hist2,cv2.HISTCMP_CORREL)
print("compare hist=",compare)
if compare <-0.13:
SrcImg = match_histograms(SrcImg, reference, multichannel=False).astype('uint8')
SrcImg = cv2.bitwise_not(SrcImg)
SrcImg = match_histograms(SrcImg, reference, multichannel=False).astype('uint8')
mask = np.zeros((y + 2, x + 2), np.uint8)
cv2.floodFill(SrcImg, mask, (int(x / 2), int(y / 2)), 255, flags=(4 | 255 << 8))
if count>=1:
if avg_pixel>avg_cen:
_, BinImg = cv2.threshold(SrcImg,avg_pixel,255, cv2.THRESH_BINARY_INV)
else:
_, BinImg = cv2.threshold(SrcImg, 0, 255, cv2.THRESH_OTSU)
else:
_, BinImg = cv2.threshold(SrcImg, 0, 255, cv2.THRESH_OTSU)
#BinImg=cv2.bitwise_and(SrcImg,SrcImg,mask=BinImg)
kernel=np.ones((3,3),np.uint8)
BinImg4box=cv2.dilate(BinImg,kernel,iterations=50)
BinImg = cv2.dilate(BinImg, kernel, iterations=11)
if count==0:
_,Contours4box, Hierarchybox = cv2.findContours(image=copy.deepcopy(BinImg4box),
mode=cv2.RETR_TREE,
method=cv2.CHAIN_APPROX_NONE)
if Contours4box!=None:
MaxContour4box, _ = getMaxContour(Contours4box)
c4box = MaxContour4box
_, _, angle4box = cv2.fitEllipse(MaxContour4box)
x_4b, y_4b, w_4b, h_4b = cv2.boundingRect(c4box)
nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(cv2.erode(BinImg,kernel,iterations=20),connectivity=8,ltype=cv2.CV_32S)
width_start=None
max_c = 0
for idx in range(nlabels):
if not idx == 0:
if max_c < stats[idx][4]:
max_c = stats[idx][4]
if count==1:
for idx in range(nlabels):
if stats[idx][4]==max_c:
if stats[idx][1] < 10 and stats[idx][3]-stats[idx][1]<stats[0][4]-5 :
width_start=stats[idx][0]
width_end=stats[idx][2]
if width_start!=None:
left_w=int(x/2)-width_start
right_w=width_end-width_start-left_w
imgf=scipy.ndimage.gaussian_filter(cv2.erode(BinImg,kernel,iterations=60),16)
labels, num = scipy.ndimage.label(imgf>25)
#MAKING CONTOUR
_,Contours, Hierarchy = cv2.findContours(image=copy.deepcopy(BinImg),
mode=cv2.RETR_TREE,
method=cv2.CHAIN_APPROX_NONE)
img_raw=np.ones(SrcImg.shape)-SrcImg
MaxContour, _ = getMaxContour(Contours)
Canvas = np.ones(SrcImg.shape, np.uint8)
image=cv2.drawContours(image=Canvas, contours=[MaxContour], contourIdx=0, color=(255), thickness=-1)
#hull=cv2.convexHull(MaxContour)
mask = (Canvas != 255)
RoiImg = copy.deepcopy(BinImg)
RoiImg[mask] = 255
RoiImg = cv2.morphologyEx(src=RoiImg, op=cv2.MORPH_CLOSE, kernel=np.ones((3,3)), iterations=4)
c0=MaxContour
epsilon = 0.01 * cv2.arcLength(c0, True)
c0 = cv2.approxPolyDP(c0, epsilon, True)
M=cv2.moments(MaxContour)
x_c,y_c,w_c,h_c = cv2.boundingRect(c0)
ellipse=cv2.fitEllipse(MaxContour)
_,_,angle=cv2.fitEllipse(MaxContour)
img_e=cv2.ellipse(RoiImg,ellipse,10)
print("w",w_c,"h",h_c)
ratio=float(h_c/w_c)
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])
print("crop_x=",x,",crop_y=",y)
leftmost = tuple(c0[c0[:, :, 0].argmin()][0])
rightmost = tuple(c0[c0[:, :, 0].argmax()][0])
topmost = tuple(c0[c0[:, :, 1].argmin()][0])
bottommost = tuple(c0[c0[:, :, 1].argmax()][0])
"""
plt.subplot(1,2,1)
plt.imshow(img_raw, cmap='bone')
plt.title("center of contour")
plt.axis('off')
plt.scatter([cx], [cy], c="r", s=30)
plt.subplot(1,2,2)
plt.imshow(image, cmap='bone')
plt.plot(
[x_c, x_c + w_c, x_c + w_c, x_c, x_c],
[y_c, y_c, y_c + h_c, y_c + h_c, y_c],
c="r"
)
plt.axis("off")
plt.scatter(
[leftmost[0], rightmost[0], topmost[0], bottommost[0]],
[leftmost[1], rightmost[1], topmost[1], bottommost[1]],
c="b", s=30)
plt.title("Extream Points")
"""
print("\ncenter: (",str(cx),",",str(cy),")")
print("leftmost:",leftmost)
print("rightmost:",rightmost)
print("topmost:",topmost)
print("bottommost:",bottommost)
print()
plt.show()
if count==0:
Src = Src[int(y_4b - y_4b * (1 / 2)):int(y_4b + h_4b + (y_4b + h_4b) * (1 / 2)),
int(x_4b - x_4b * (1 / 2)):int(x_4b + w_4b + (1 / 2) * (x_4b + w_4b))]
#Src = Src[int(y_c - y_c * (1 / 2)):int(y_c + h_c + (y_c + h_c) * (1 / 2)),
# int(x_c - x_c * (1 / 2)):int(x_c + w_c + (1 / 2) * (x_c + w_c))]
#ROTATION PART
if condition(angle,c0,x,y,set_flag)!=None:
angle,set_flag=condition(angle,c0,x,y,set_flag)
print("ellipse angle=",angle)
if angle>135 and not (angle==180):
M1 = cv2.getRotationMatrix2D((w / 2, h / 2), 180-angle, 1)
else:
M1 = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1)
img_end = cv2.warpAffine(Src, M1, (w, h))
#M2=cv2.getRotationMatrix2D((w/2,h/2),180,1)
#if width_start!=None:
# if(left_w>right_w):
# Src=cv2.warpAffine(Src,M2,(w,h))
return img_end, set_flag
li=os.listdir("0724_incomplete/img_test/")
li.sort()
path = '/home/j/python_work/rota/sample'
i=0
for file in li:
Src=None
count=0
set_flag=0
print(file)
Src=cv2.imread("0724_incomplete/img_test/"+file, cv2.IMREAD_GRAYSCALE)
img_end=Process(Src,count,set_flag)[0]
"""
while(set_flag == 0):
count+=1
if Process(Src,count,set_flag)[1]==0:
Src=Process(Src,count,set_flag)[0]
if(count==5):
break
"""
#img_end=Src
count+=1
if Process(Src,count,set_flag)[1]==0:
img_end=Process(img_end,count,set_flag)[0]
cv2.imwrite('0805_2/'+file,img_end)
#plt.title("Rotated Image")
#plt.imshow(img_end)
#plt.show()<file_sep>/README.md
# klgrade
Rule based classification of kl grade
<file_sep>/0812.py
# upside bone's bottommost & down side bone's avg height(leftmost[1] and topmost[1])
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
import copy
import csv
def extreme_point_top(img_top):
Contours, _ = cv2.findContours(image=copy.deepcopy(img_top),
mode=cv2.RETR_TREE,
method=cv2.CHAIN_APPROX_NONE)
MaxContour = max(Contours, key=cv2.contourArea) if Contours else None
c0 = MaxContour
x_c, y_c, w_c, h_c = cv2.boundingRect(c0)
top_w = w_c
if MaxContour is not None:
bottommost = tuple(c0[c0[:, :, 1].argmax()][0])
print(bottommost)
else:
bottommost=(100,170)
return bottommost, top_w
def extreme_point_bottom(img_bottom):
Contours_b, _ = cv2.findContours(image=copy.deepcopy(img_bottom),
mode=cv2.RETR_TREE,
method=cv2.CHAIN_APPROX_NONE)
MaxContour_b = max(Contours_b, key=cv2.contourArea) if Contours_b else None
c_b = MaxContour_b
x_c, y_c, w_c, h_c = cv2.boundingRect(c_b)
bot_w = w_c
if MaxContour_b is not None:
leftmost = tuple(c_b[c_b[:, :, 0].argmin()][0])
topmost = tuple(c_b[c_b[:, :, 1].argmin()][0])
else:
leftmost=(0,0)
topmost=(0,0)
return topmost, leftmost, bot_w
def process(path, csv_writer):
li = os.listdir(path)
li.sort()
sum_ratio = 0
sum_ratio_r = 0
#flag = 0
#flag_r = 0
for file in li:
print(file)
img = cv2.imread(path + file, cv2.IMREAD_GRAYSCALE)
Srcimg = img.copy()
rec=Srcimg.copy()
Srcimg = cv2.bilateralFilter(Srcimg, 9, 75, 75)
Srcimg = cv2.GaussianBlur(Srcimg, (3, 3), 0)
# clahe=cv2.createCLAHE(clipLimit=2.0,tileGridSize=(8,8))
# Srcimg=clahe.apply(Srcimg)
h, w = Srcimg.shape
center3 = img[int(h / 2) - 10:int(h / 2) + 40,
int(w / 2) - 40:int(w / 2) + 40]
# 뼈부분 평균 픽셀
sum_bone = 0
bone = Srcimg[int(h / 4):int(h / 4) + 20, int(w / 2) - 10:int(w / 2) + 10]
bone2=Srcimg[int(3*h/4)-20:int(3*h/4),int(w/2)-10:int(w/2)+10]
cv2.rectangle(rec,(int(w/2)-40,int(h/2)-10),(int(w/2)+40,int(h/2)+40),(255,255,255),1)
cv2.rectangle(rec,(int(w/2)-10,int(h/4)),(int(w/2)+10,int(h/4)+20),(255,0,0),1)
cv2.rectangle(rec,(int(w/2)-10,int(3*h/4)-20),(int(w/2)+10,int(3*h/4)),(255,0,0),1)
for i in range(bone.shape[0]):
for j in range(bone.shape[1]):
sum_bone += bone[i][j]
sum_bone += bone2[i][j]
avg_bone = sum_bone / (bone.shape[0] * bone.shape[1])*2
print(avg_bone)
# 가운데 부분 평균 픽셀
sum_cen = 0
center_area=center3.shape[0] * center3.shape[1]
for i in range(center3.shape[0]):
for j in range(center3.shape[1]):
sum_cen += center3[i][j]
avg = int(sum_cen / center_area)
avg_init = avg
turn_flag = 0
while avg_bone < avg: # 뼈와 거리가 있는 적정값 찾아가도록
avg += 10
if avg > 256:
avg = avg_init
turn_flag = 1
if turn_flag == 1:
avg -= 10
if avg < 10:
break
sum_lt=0; sum_lb=0; sum_rt=0; sum_rb=0
mid_line=int(h/2)+22
img_lt=Srcimg[0:mid_line,0:10]
img_lb=Srcimg[mid_line:h,0:10]
img_rt=Srcimg[0:mid_line,w-10:w]
img_rb=Srcimg[mid_line:h,w-10:w]
small_h,small_w=img_lt.shape
small_area=small_w*small_h
for i in range(small_h):
for j in range(small_w):
sum_lt+=img_lt[i][j]
sum_rt+=img_rt[i][j]
for i in range(img_lb.shape[0]):
for j in range(img_lb.shape[1]):
sum_lb += img_lb[i][j]
sum_rb += img_rb[i][j]
avg_lt=int(sum_lt/small_area)
avg_lb=int(sum_lb/small_area)
avg_rt=int(sum_rt/small_area)
avg_rb=int(sum_rb/small_area)
print(avg_lt, avg_lb, avg_rt, avg_rb, avg)
# left side cropping
img_top_ori_l = Srcimg[0:int(h / 2) + 22, 0:int(w / 2) - 50]
_, img_top_l = cv2.threshold(img_top_ori_l, avg-5, 256, cv2.THRESH_BINARY)
cv2.imwrite("0812/lt/"+file,img_top_l)
cv2.rectangle(rec,(0,0),(int(w/2)-50,int(h/2)+22),(0,0,255),1)
img_bottom_ori_l = Srcimg[int(h / 2) + 22:h, 0:int(w / 2) - 50]
cv2.rectangle(rec,(0,int(h/2)+22),(int(w/2)-50,h),(0,0,255),1)
_, img_bottom_l = cv2.threshold(img_bottom_ori_l, avg-5, 256, cv2.THRESH_BINARY)
cv2.imwrite("0812/lb/"+file, img_bottom_l)
bottommost, top_w = extreme_point_top(img_top_l)
topmost, leftmost, bot_w = extreme_point_bottom(img_bottom_l)
if bottommost[1]!=170:
dist_l=170-bottommost[1]
else:
dist_l=0
dist_bot_l=(leftmost[1] + topmost[1])/2
avg_bot_h = dist_bot_l#+dist_l
longer_w = top_w if top_w > bot_w else bot_w
if dist_bot_l != 0:
ratio = avg_bot_h / longer_w
else:
ratio = 0
if ratio >= 1:
ratio = 0
sum_ratio += ratio
else:
sum_ratio += ratio
# right side cropping
img_top_ori_r = Srcimg[0:int(h / 2) + 22, int(w / 2) + 50:w]
_, img_top_r = cv2.threshold(img_top_ori_r, avg-5, 256, cv2.THRESH_BINARY)
cv2.imwrite("0812/rt/"+file, img_top_r)
cv2.rectangle(rec, (int(w/2)+50,0), (w, int(h /2)+22), (0, 0, 255), 1)
img_bottom_ori_r = Srcimg[int(h / 2) + 22:h, int(w / 2) + 50:w]
_, img_bottom_r = cv2.threshold(img_bottom_ori_r, avg-5, 256, cv2.THRESH_BINARY)
cv2.imwrite("0812/rb/"+file, img_bottom_r)
cv2.rectangle(rec, (int(w / 2) + 50, int(h/2)+22), (w, h), (0, 0, 255), 1)
#plt.imshow(rec,cmap="bone")
#plt.title(file)
#plt.show()
bottommost_r, top_w_r = extreme_point_top(img_top_r)
topmost_r, leftmost_r, bot_w_r = extreme_point_bottom(img_bottom_r)
dist_bot_r = (leftmost_r[1] + topmost_r[1]) / 2
if bottommost_r[1]!=170:
dist_r=170-bottommost_r[1]
else:
dist_r=0
avg_bot_h_r = dist_bot_r#+dist_r
longer_w_r = top_w_r if top_w_r > bot_w_r else bot_w_r
if dist_bot_l != 0:
ratio_r = avg_bot_h_r / longer_w_r
else:
ratio_r = 0
if ratio_r >= 1:
ratio_r = 0
if ratio==0 or ratio_r==0:
ratio_whole=0
else:
ratio_whole = (ratio + ratio_r) / 2
sum_ratio_r += ratio_whole
csv_writer.writerow([file, ratio, ratio_r])
avg_ratio = sum_ratio / len(li)
csv_writer.writerow(['\n'])
csv_writer.writerow(['(Average ratio=)', avg_ratio])
csv_writer.writerow(['\n'])
with open("result.csv", 'w', newline='') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['[FILENAME]', '[LEFT RATIO]', '[RIGHT RATIO]'])
for i in range(5):
csv_writer.writerow(['[KL'+str(i)+']'])
path = 'kl'+str(i)+'/'
process(path, csv_writer)
|
fa8d8000b90875fc33120d6572dab1e9ae987348
|
[
"Markdown",
"Python"
] | 5 |
Python
|
nuatmochoi/klgrade
|
b4f4963a191212400f4d4a98587793013f3e55b6
|
c9c4d677a70db52c45b3f4f26994adcad3283969
|
refs/heads/master
|
<repo_name>nuhmanp/Pizza-Ordering-Bootstrap<file_sep>/js/validations.js
function isEmpty(string){
return string.trim() =="";
}
function areEquivalent(value1, value2){
}
function isChecked(inputSet){
}
function isEmailValid(email){
}<file_sep>/js/script.js
function multiply(){
var result = 1;
for (var i = 0; i < arguments.length; i++) {
result *= arguments[i];
}
return result;
}
function showError(message){
document.getElementById('errors').classList.remove('hidden');
document.getElementById('error').innerHTML = message;
}
function getNumbers(){
var nums = [];
nums.push(document.getElementById('number1').value);
nums.push(document.getElementById('number2').value);
return nums;
}
function divide(){
console.log('divide');
var num1 = document.getElementById('number1').value;
var num2 = document.getElementById('number2').value;
document.getElementById('result').innerHTML = num1/num2;
}
window.onload = function(){
document.getElementById('multiply').onclick = function(){
var num1 = document.getElementById('number1').value;
var num2 = document.getElementById('number2').value;
document.getElementById('result').innerHTML = multiply(num1,num2);
};
document.getElementById('divide').onclick = function(){
//alert("gjgjgj");
//divide();
var numbers = getNumbers();
for (var i = 0; i < numbers.length; i++) {
if(isNaN(numbers[i])){
var index = i+1;
showError("The number " + index + "is not a number!");
return;
}
//Empty case
if(isEmpty(numbers[i])){
alert('Empty');
return;
}
}
};
};
|
74256b7e73e16d68010ef9b6d04979d93e7e57b8
|
[
"JavaScript"
] | 2 |
JavaScript
|
nuhmanp/Pizza-Ordering-Bootstrap
|
765e2c1a59cbd7e474093ac2814536964365b76c
|
565f9ff1138c21ec57cca7d07d8ce40a396ae9cd
|
refs/heads/master
|
<repo_name>Computational-Nonlinear-Optics-ORC/mm-fopo-1<file_sep>/testing/test_coupler.py
import sys
sys.path.append('src')
import coupler
import numpy as np
from numpy.testing import assert_allclose
from scipy.constants import c, pi
import os
from scipy import special
def test_bessel():
assert_allclose(coupler.jv_(0,0), 0.)
assert not(np.isfinite(coupler.kv_(0,0)))
class Test_eigensolver:
e = coupler.Eigensolver(1549e-9, 1555e-9, 10)
e.initialise_fibre(5e-6)
def test_core_clad(self):
assert (self.e.ncore > self.e.nclad).all()
def test_V_number_eigen(self):
u_01, w_01, neff01 = [np.zeros([1, 10]) for i in range(3)]
u_11, w_11, neff11 = [np.zeros([2, 10]) for i in range(3)]
for i in range(10):
u_01[0, i], w_01[0, i], neff01[0, i] = self.e.solve_01(i)
u_11[:, i], w_11[:, i], neff11[:, i] = self.e.solve_11(i)
assert_allclose((u_01[0,:]**2 + w_01[0,:]**2)**0.5, self.e.V_vec)
assert_allclose((u_11[0,:]**2 + w_11[0,:]**2)**0.5, self.e.V_vec)
assert_allclose((u_11[1,:]**2 + w_11[1,:]**2)**0.5, self.e.V_vec)
assert (neff01[0,:] > neff11[0, :]).all()
assert (neff01[0,:] > neff11[1, :]).all()
class Test_coupling:
lmin = 1540e-9
lmax = 1560e-9
N_l = 10
a = 5e-6
N_points = 128
d_vec = [1.1e-6, 1.95e-6]
k01_1, k11_1, couple01_1, couple11_1, \
k01_2, k11_2, couple01_2, couple11_2 = \
coupler.calculate_coupling_coeff(lmin, lmax, a, N_points, N_l, d_vec)
def test_coupling_less(self):
assert (self.k01_1 < self.k11_1).all()
assert (self.k01_2 < self.k11_2).all()
assert (self.k01_1 > self.k01_2).all()
assert (self.k11_1 > self.k11_2).all()<file_sep>/run_tests.sh
#!/bin/bash
cd src/cython_files
rm -rf build *so cython_integrand.c *html
python setup.py build_ext --inplace
cd ../..
pytest testing/*.py
<file_sep>/testing/test_pulse_prep.py
import sys
sys.path.append('src')
from functions import *
import numpy as np
from numpy.testing import assert_allclose, assert_raises,assert_almost_equal
from overlaps import *
class Test_loss:
def test_loss1(a):
fv = np.linspace(200, 600, 1024)
alphadB = np.array([1, 1])
int_fwm = sim_parameters(2.5e-20, 2, alphadB)
int_fwm.general_options(1e-13, 1, 1, 1)
int_fwm.propagation_parameters(10, 1000, 0.1)
sim_wind = sim_window(fv, 1550e-9,1550e-9,int_fwm)
loss = Loss(int_fwm, sim_wind, amax=alphadB)
alpha_func = loss.atten_func_full(sim_wind.fv)
ex = np.zeros_like(alpha_func)
for i, a in enumerate(alpha_func):
ex[i, :] = np.ones_like(a)*alphadB[i]/4.343
assert_allclose(alpha_func, ex)
def test_loss2(a):
fv = np.linspace(200, 600, 1024)
alphadB = np.array([1, 2])
int_fwm = sim_parameters(2.5e-20, 2, alphadB)
int_fwm.general_options(1e-13, 1, 1, 1)
int_fwm.propagation_parameters(10, 1000, 0.1)
sim_wind = sim_window(fv, 1550e-9,1550e-9,int_fwm)
loss = Loss(int_fwm, sim_wind, amax=2*alphadB)
alpha_func = loss.atten_func_full(sim_wind.fv)
maxim = np.max(alpha_func)
assert maxim == 2*np.max(alphadB)/4.343
def test_loss3(a):
fv = np.linspace(200, 600, 1024)
alphadB = np.array([1, 2])
int_fwm = sim_parameters(2.5e-20, 2, alphadB)
int_fwm.general_options(1e-13, 1, 1, 1)
int_fwm.propagation_parameters(10, 1000, 0.1)
sim_wind = sim_window(fv, 1550e-9,1550e-9,int_fwm)
loss = Loss(int_fwm, sim_wind, amax=2*alphadB)
alpha_func = loss.atten_func_full(sim_wind.fv)
minim = np.min(alpha_func)
assert minim == np.min(alphadB)/4.343
def test_fv_creator():
"""
Checks whether the first order cascade is in the freequency window.
"""
class int_fwm1(object):
def __init__(self):
self.N = 10
self.nt = 2**self.N
int_fwm = int_fwm1()
lamp1 = 1549
lamp2 = 1555
lams = 1550
fv, D_freq = fv_creator(lamp1,lamp2, lams, int_fwm)
mins = np.min(1e-3*c/fv)
f1 = 1e-3 * c / lamp1
fs = fv[D_freq['where'][2]]
f2 = 1e-3 * c / lamp2
F = f1 - fs
freqs = (f2 - F, f2, f2 + F, fs, f1, f1+F)
assert_allclose(freqs, [fv[i] for i in D_freq['where']][::-1])
fmin = fv.min()
fmax = fv.max()
assert np.all( [ i < fmax and i > fmin for i in freqs])
def test_noise():
class sim_windows(object):
def __init__(self):
self.w = 10
self.T = 0.1
self.w0 = 9
class int_fwms(object):
def __init__(self):
self.nt = 1024
self.nm = 1
int_fwm = int_fwms()
sim_wind = sim_windows()
noise = Noise(int_fwm, sim_wind)
n1 = noise.noise_func(int_fwm)
n2 = noise.noise_func(int_fwm)
print(n1, n2)
assert_raises(AssertionError, assert_almost_equal, n1, n2)
def test_time_frequency():
nt = 3
dt = np.abs(np.random.rand())*10
u1 = 10*(np.random.randn(2**nt) + 1j * np.random.randn(2**nt))
U = fftshift(dt*fft(u1))
u2 = ifft(ifftshift(U)/dt)
assert_allclose(u1, u2)
"----------------Raman response--------------"
#os.system('rm -r testing_data/step_index/*')
class Raman():
l_vec = np.linspace(1600e-9, 1500e-9, 64)
fv = 1e-12*c/l_vec
index = 0
master_index = 0
M1, M2, Q_large = fibre_overlaps_loader(1)
def test_raman_off(self):
ram = raman_object('off')
ram.raman_load(np.random.rand(10), np.random.rand(1)[0], None)
assert ram.hf == None
def test_raman_load_1(self):
ram = raman_object('on', 'load')
#M1, M2, Q = Q_matrixes(1, 2.5e-20, 1.55e-6, 0.01)
D = loadmat('testing/testing_data/Raman_measured.mat')
t = D['t']
t = np.asanyarray([t[i][0] for i in range(t.shape[0])])
dt = D['dt'][0][0]
hf_exact = D['hf']
hf_exact = np.asanyarray([hf_exact[i][0]
for i in range(hf_exact.shape[0])])
hf = ram.raman_load(t, dt, self.M2)
hf_exact = np.tile(hf_exact, (len(self.M2[1, :]), 1))
assert_allclose(hf, hf_exact)
def test_raman_analytic_1(self):
ram = raman_object('on', 'analytic')
D = loadmat('testing/testing_data/Raman_analytic.mat')
t = D['t']
t = np.asanyarray([t[i][0] for i in range(t.shape[0])])
dt = D['dt'][0][0]
hf_exact = D['hf']
hf_exact = np.asanyarray([hf_exact[i][0]
for i in range(hf_exact.shape[0])])
hf = ram.raman_load(t, dt, self.M2)
assert_allclose(hf, hf_exact)
def test_raman_load_2(self):
ram = raman_object('on', 'load')
D = loadmat('testing/testing_data/Raman_measured.mat')
t = D['t']
t = np.asanyarray([t[i][0] for i in range(t.shape[0])])
dt = D['dt'][0][0]
hf_exact = D['hf']
hf_exact = np.asanyarray([hf_exact[i][0]
for i in range(hf_exact.shape[0])])
hf = ram.raman_load(t, dt, self.M2)
hf_exact = np.tile(hf_exact, (len(self.M2[1, :]), 1))
assert_allclose(hf, hf_exact)
def test_raman_analytic_2(self):
ram = raman_object('on', 'analytic')
D = loadmat('testing/testing_data/Raman_analytic.mat')
t = D['t']
t = np.asanyarray([t[i][0] for i in range(t.shape[0])])
dt = D['dt'][0][0]
hf_exact = D['hf']
hf_exact = np.asanyarray([hf_exact[i][0]
for i in range(hf_exact.shape[0])])
hf = ram.raman_load(t, dt, self.M2)
assert_allclose(hf, hf_exact)
"----------------------------Dispersion operator--------------"
class Test_dispersion(Raman):
int_fwm = sim_parameters(2.5e-20, 2, 0)
int_fwm.general_options(1e-13, raman_object, 1, 'on')
int_fwm.propagation_parameters(10, 10, 1)
fv, D_freq = fv_creator(1549,1555, 1550, int_fwm)
sim_wind = sim_window(fv, 1549e-9, 1.5508e-6, int_fwm)
loss = Loss(int_fwm, sim_wind, amax=10)
alpha_func = loss.atten_func_full(sim_wind.fv)
int_fwm.alphadB = alpha_func
int_fwm.alpha = int_fwm.alphadB
betas = load_disp_paramters(sim_wind.w0)
Dop_large = dispersion_operator(betas, int_fwm, sim_wind)
def test_dispersion_not_same(self):
"""
Asserts that the dispersion of the two modes is not the same.
"""
assert_raises(AssertionError, assert_allclose,
self.Dop_large[0, :], self.Dop_large[1, :])
def test_betap():
c_norm = c*1e-12
lamda_c = 1.5508e-6
w0 = 2 * pi * c / lamda_c
betap1 = load_disp_paramters(w0,lamda_c)
assert_allclose(betap1[0,:2], np.array([0,0]))
D = np.array([19.8e6,21.8e6])
S = np.array([0.068e15,0.063e15])
beta2 = -D[:]*(lamda_c**2/(2*pi*c_norm)) #[ps**2/m]
beta3 = lamda_c**4*S[:]/(4*(pi*c_norm)**2)+lamda_c**3*D[:]/(2*(pi*c_norm)**2) #[ps**3/m]
assert_allclose(betap1[0,:2], np.array([0,0]))
assert_allclose(betap1[1,1], -9.5e-02)
assert_allclose(betap1[:,2:], np.array([beta2, beta3]).T) <file_sep>/src/src/cython_files/clean.sh
rm -rf build *so *html mkl_fft *Prof _pydfti.c spliced_fft
<file_sep>/src/src/oscillator.py
import numpy as np
import sys
sys.path.append('src')
from scipy.constants import c, pi
from joblib import Parallel, delayed
from mpi4py.futures import MPIPoolExecutor
from mpi4py import MPI
from scipy.fftpack import fftshift, fft
import os
import time as timeit
os.system('export FONTCONFIG_PATH=/etc/fonts')
from functions import *
from time import time, sleep
from overlaps import fibre_overlaps_loader
@profile
def oscilate(sim_wind, int_fwm, noise_obj, index,
master_index,
splicers_vec, WDM_vec, M1, M2, Q_large, hf, Dop, dAdzmm, D_pic,
pulse_pos_dict_or, plots, mode_names, ex, fopa, D_param, pm):
u = np.empty(
[int_fwm.nm, len(sim_wind.t)], dtype='complex128')
U = np.empty([int_fwm.nm,
len(sim_wind.t)], dtype='complex128')
p1_pos = D_param['where'][1]
p2_pos = D_param['where'][4]
s_pos = D_param['where'][2]
noise_new_or = noise_obj.noise_func_freq(int_fwm, sim_wind)
u[:, :] = noise_obj.noise
woff1 = (p1_pos+(int_fwm.nt)//2)*2*pi*sim_wind.df
u[0, :] += (D_param['P_p1'])**0.5 * np.exp(1j*(woff1)*sim_wind.t)
woff2 = (s_pos+(int_fwm.nt)//2)*2*pi*sim_wind.df
u[0, :] += (D_param['P_s'])**0.5 * np.exp(1j*(woff2) *
sim_wind.t)
woff3 = (p2_pos+(int_fwm.nt)//2)*2*pi*sim_wind.df
u[1, :] += (D_param['P_p2'])**0.5 * np.exp(1j*(woff3) *
sim_wind.t)
U[:, :] = fftshift(fft(u[:, :]), axes = -1)
w_tiled = np.tile(sim_wind.w + sim_wind.woffset, (int_fwm.nm, 1))
master_index = str(master_index)
ex.exporter(index, int_fwm, sim_wind, u, U, D_param,
0, 0, mode_names, master_index,
'00', 'original pump', D_pic[0], plots)
U_original_pump = np.copy(U[:, :])
# Pass the original pump through the WDM1, port1 is in to the loop, port2
# junk
noise_new = noise_obj.noise_func_freq(int_fwm, sim_wind)
u[:, :], U[:, :] = WDM_vec[0].pass_through(
(U[:, :], noise_new), sim_wind)[0]
max_rounds = arguments_determine(-1)
if fopa:
print('Fibre amplifier!')
max_rounds = 0
ro = -1
t_total = 0
gam_no_aeff = -1j*int_fwm.n2*2*pi/sim_wind.lamda
noise_new = noise_new_or*1
dz,dzstep,maxerr = int_fwm.dz,int_fwm.z,int_fwm.maxerr
Dop = np.ascontiguousarray(Dop / 2)
w_tiled = np.ascontiguousarray(w_tiled)
tsh = sim_wind.tsh
while ro < max_rounds:
ro += 1
print('round', ro)
pulse_pos_dict = [
'round ' + str(ro)+', ' + i for i in pulse_pos_dict_or]
ex.exporter(index, int_fwm, sim_wind, u, U, D_param, 0, ro, mode_names, master_index,
str(ro)+'1', pulse_pos_dict[3], D_pic[5], plots)
U, dz = pulse_propagation(u, dz, dzstep, maxerr, M1, M2, Q_large, w_tiled, tsh, hf, Dop, gam_no_aeff)
ex.exporter(index, int_fwm, sim_wind, u, U, D_param, -1, ro, mode_names, master_index,
str(ro)+'2', pulse_pos_dict[0], D_pic[2], plots)
# pass through WDM2 port 2 continues and port 1 is out of the loop
noise_new = noise_obj.noise_func_freq(int_fwm, sim_wind)
(u[:, :], U[:, :]),(out1, out2) = WDM_vec[1].pass_through(
(U[:, :], noise_new), sim_wind)
ex.exporter(index, int_fwm, sim_wind, u, U, D_param, -1, ro, mode_names, master_index,
str(ro)+'3', pulse_pos_dict[1], D_pic[3], plots)
# Splice7 after WDM2 for the signal
noise_new = noise_obj.noise_func_freq(int_fwm, sim_wind)
(u[:, :], U[:, :]) = splicers_vec[2].pass_through(
(U[:, :], noise_new), sim_wind)[0]
# Modulate the phase to be in phase with what is coming in
pm.modulate(U_original_pump, U)
# Pass again through WDM1 with the signal now
(u[:, :], U[:, :]) = WDM_vec[0].pass_through(
(U_original_pump, U[:, :]), sim_wind)[0]
################################The outbound stuff#####################
ex.exporter(index, int_fwm, sim_wind, out1, out2, D_param, -
1, ro, mode_names, master_index, str(ro)+'4',
pulse_pos_dict[4], D_pic[6], plots)
if max_rounds == 0:
max_rounds =1
consolidate(max_rounds, int_fwm,master_index, index)
return None
@unpack_args
def formulate(index, n2, alphadB, P_p1, P_p2, P_s, spl_losses,
lamda_c, WDMS_pars, lamp1, lamp2, lams, num_cores,
maxerr, ss, ram, plots,
N, nt, master_index, nm, mode_names, fopa,z):
ex = Plotter_saver(plots, True) # construct exporter
"------------------propagation paramaters------------------"
dz_less = 2
int_fwm = sim_parameters(n2, nm, alphadB)
int_fwm.general_options(maxerr, raman_object, ss, ram)
int_fwm.propagation_parameters(N, z, dz_less)
lamda = lamp1*1e-9 # central wavelength of the grid[m]
"---------------------Grid&window-----------------------"
fv, D_freq = fv_creator(lamp1,lamp2, lams, int_fwm)
sim_wind = sim_window(fv, lamda, lamda_c, int_fwm)
"----------------------------------------------------------"
"---------------------Aeff-Qmatrixes-----------------------"
M1, M2, Q_large = fibre_overlaps_loader(sim_wind.dt)
betas = load_disp_paramters(sim_wind.w0)
"----------------------------------------------------------"
"---------------------Loss-in-fibres-----------------------"
slice_from_edge = (sim_wind.fv[-1] - sim_wind.fv[0])/100
loss = Loss(int_fwm, sim_wind, amax=None)
int_fwm.alpha = loss.atten_func_full(fv)
"----------------------------------------------------------"
"--------------------Dispersion----------------------------"
Dop_large = dispersion_operator(betas, int_fwm, sim_wind)
"----------------------------------------------------------"
"--------------------Noise---------------------------------"
noise_obj = Noise(int_fwm, sim_wind)
a = noise_obj.noise_func_freq(int_fwm, sim_wind)
"----------------------------------------------------------"
"---------------Formulate the functions to use-------------"
pulse_pos_dict_or = ('after propagation', "pass WDM2",
"pass WDM1 on port2 (remove pump)",
'add more pump', 'out')
keys = ['loading_data/green_dot_fopo/pngs/' +
str(i)+str('.png') for i in range(7)]
D_pic = [plt.imread(i) for i in keys]
integrand = Integrand(ram, ss, cython = True, timing = False)
dAdzmm = integrand.dAdzmm
raman = raman_object(int_fwm.ram, int_fwm.how)
raman.raman_load(sim_wind.t, sim_wind.dt, M2)
hf = 0*raman.hf
"--------------------------------------------------------"
print(WDMS_pars)
"----------------------Formulate WDMS--------------------"
if WDMS_pars[-1] == 'WDM':
WDM_vec = [WDM(i[0], i[1], sim_wind.fv, fopa,with_resp)
for i, with_resp in zip(WDMS_pars[:-1], ('LP01', 'LP11'))] # WDM up downs in wavelengths [m]
elif WDMS_pars[-1] == 'prc':
WDM_vec = [Perc_WDM(D_freq['where'], i, sim_wind.fv, fopa)
for i in WDMS_pars[:-1]] # WDM up downs in wavelengths [m]
elif WDMS_pars[-1] == 'bandpass':
WDM_vec = [Bandpass_WDM(D_freq['where'], i, sim_wind.fv, fopa)
for i in WDMS_pars[:-1]] # WDM up downs in wavelengths [m]
"--------------------------------------------------------"
"----------------------Formulate splicers--------------------"
splicers_vec = [Splicer(fopa = fopa, loss=i) for i in spl_losses]
"------------------------------------------------------------"
D_param = {**D_freq, **{'P_p1': P_p1, 'P_p2': P_p2, 'P_s': P_s}}
pm = Phase_modulation_infase_WDM(D_freq['where'], WDM_vec[0])
oscilate(sim_wind, int_fwm, noise_obj, index, master_index, splicers_vec,
WDM_vec, M1, M2, Q_large, hf, Dop_large, dAdzmm, D_pic,
pulse_pos_dict_or, plots, mode_names, ex, fopa,D_param,pm )
return None
def main():
"-----------------------------Stable parameters----------------------------"
# Number of computing cores for sweep
num_cores = arguments_determine(1)
# maximum tolerable error per step in integration
maxerr = 1e-14
ss = 1 # includes self steepening term
ram = 'on' # Raman contribution 'on' if yes and 'off' if no
if arguments_determine(-1) == 0:
fopa = True # If no oscillations then the WDMs are deleted to
# make the system in to a FOPA
else:
fopa = False
plots = False # Do you want plots, be carefull it makes the code very slow!
N = 12 # 2**N grid points
nt = 2**N # number of grid points
nplot = 2 # number of plots within fibre min is 2
nm = 2
mode_names = ['LP01', 'LP11a'] # Names of modes for plotting
if 'mpi' in sys.argv:
method = 'mpi'
elif 'joblib' in sys.argv:
method = 'joblib'
else:
method = 'single'
"--------------------------------------------------------------------------"
stable_dic = {'num_cores': num_cores, 'maxerr': maxerr, 'ss': ss, 'ram': ram, 'plots': plots,
'N': N, 'nt': nt, 'nm': nm, 'mode_names': mode_names, 'fopa':fopa}
"------------------------Can be variable parameters------------------------"
n2 = 2.5e-20 # Nonlinear index [m/W]
alphadB = np.array([0,0]) # loss within fibre[dB/m]
z = [5, 10, 25, 50, 100, 200, 400, 600, 800, 1000] # Length of the fibre
z = z[-1]
P_p1 = dbm2w(30.5 - 3)
P_p2 = dbm2w(30.5 - 4)
P_s = dbm2w(30.5 - 3 - 24)#1e-3#1e-3
spl_losses = [0, 0, 1.]
lamda_c = 1.5508e-6
WDMS_pars = ([1549., 1550.],
[1555, 1556.], 'WDM') # WDM up downs in wavelengths [m]
WDMS_pars = ([100, 100, 50, 0, 100, 0],
[100, 100, 100, 0, 100, 0], 'prc') # WDM up downs in wavelengths [m]
# Bandpass filter system [m]
WDMS_pars = []
for i in range(5, 100, 5):
WDMS_pars.append([[100, 100, i, 0, 100, 0],
[100, 100, 100, 0, 0, 0], 'bandpass'])
lamp1 = 1549
lamp2 = [1553.50048583,1554.50204646]#, 1555]
lamp2 = 1553.50048583
#lamp2 = [1553.25]
lams = np.linspace(1549, 1549+5, 256)
#lams = [1550]
lams = lams[5:]
var_dic = {'n2': n2, 'alphadB': alphadB,
'P_p1': P_p1, 'P_p2': P_p2, 'P_s': P_s,
'spl_losses': spl_losses,
'lamda_c': lamda_c, 'WDMS_pars': WDMS_pars,
'lamp1': lamp1,'lamp2': lamp2, 'lams': lams, 'z':z}
"--------------------------------------------------------------------------"
outside_var_key = 'WDMS_pars'
inside_var_key = 'lams'
inside_var = var_dic[inside_var_key]
outside_var = var_dic[outside_var_key]
del var_dic[outside_var_key]
del var_dic[inside_var_key]
"----------------------------Simulation------------------------------------"
D_ins = [{'index': i, inside_var_key: insvar}
for i, insvar in enumerate(inside_var)]
large_dic = {**stable_dic, **var_dic}
if len(inside_var) < num_cores:
num_cores = len(inside_var)
profiler_bool = arguments_determine(0)
for kk, variable in enumerate(outside_var):
create_file_structure(kk)
_temps = create_destroy(inside_var, str(kk))
_temps.prepare_folder()
large_dic['master_index'] = kk
large_dic[outside_var_key] = variable
if profiler_bool:
for i in range(len(D_ins)):
formulate(**{**D_ins[i], ** large_dic})
elif method == 'mpi':
iterables = ({**D_ins[i], ** large_dic} for i in range(len(D_ins)))
with MPIPoolExecutor() as executor:
A = executor.map(formulate, iterables)
else:
A = Parallel(n_jobs=num_cores)(delayed(formulate)(**{**D_ins[i], ** large_dic}) for i in range(len(D_ins)))
_temps.cleanup_folder()
print('\a')
return None
if __name__ == '__main__':
start = time()
main()
dt = time() - start
print(dt, 'sec', dt/60, 'min', dt/60/60, 'hours')
<file_sep>/testing/test_WDM_splicer.py
import sys
sys.path.append('src')
from functions import *
import numpy as np
from numpy.testing import assert_allclose
from scipy.constants import c, pi
class Test_splicer_2m():
x1 = 950
x2 = 1050
N = 15
nt = 2**N
l1, l2 = 900, 1250
f1, f2 = 1e-3 * c / l1, 1e-3 * c / l2
fv = np.linspace(f1, f2, nt)
lv = 1e3 * c / fv
lamda = (lv[-1] + lv[0])/2
fv = np.linspace(200, 600, 1024)
alphadB = np.array([1, 1])
int_fwm = sim_parameters(2.5e-20, 2, alphadB)
int_fwm.general_options(1e-13, 1, 1, 1)
int_fwm.propagation_parameters(10, 1000, 0.1)
sim_wind = sim_window(fv, 1550e-9,1550e-9,int_fwm)
#sim_wind = sim_windows(lamda, lv, 900, 1250, nt)
U1 = 10*(np.random.randn(2, nt) +
1j * np.random.randn(2, nt))
U2 = 10*(np.random.randn(2, nt) +
1j * np.random.randn(2, nt))
splicer = Splicer(loss=np.random.rand()*10)
U_in = (U1, U2)
U1 = U1
U2 = U2
u_in1 = ifft(ifftshift(U1, axes = -1))
u_in2 = ifft(ifftshift(U2, axes = -1))
u_in_tot = np.abs(u_in1)**2 + np.abs(u_in2)**2
U_in_tot = np.abs(U1)**2 + np.abs(U2)**2
a, b = splicer.pass_through(U_in, sim_wind)
u_out1, u_out2 = a[0], b[0]
U_out1, U_out2 = a[1], b[1]
U_out_tot = np.abs(U_out1)**2 + np.abs(U_out2)**2
u_out_tot = np.abs(u_out1)**2 + np.abs(u_out2)**2
def test2_splicer_freq(self):
assert_allclose(self.U_in_tot, self.U_out_tot)
def test2_splicer_time(self):
assert_allclose(self.u_in_tot, self.u_out_tot)
#(l1, l2, fv, fopa=False, with_resp = 'LP01'):
class Test_WDM_1m():
x1 = 1549
x2 = 1555
N = 18
nt = 2**N
f1, f2 = 1e-3 * c / x1, 1e-3 * c / x2
fv = np.linspace(f1, f2, nt)
lv = 1e3 * c / fv
lamda = (lv[-1] + lv[0])/2
alphadB = np.array([1, 1])
int_fwm = sim_parameters(2.5e-20, 2, alphadB)
int_fwm.general_options(1e-13, 1, 1, 1)
int_fwm.propagation_parameters(N, 1000, 0.1)
sim_wind = sim_window(fv, 1550e-9,1550e-9,int_fwm)
WDMS = WDM(x1, x2, fv, fopa = False, with_resp = 'LP01')
U1 = 100*(np.random.randn(2, nt) +
1j * np.random.randn(2, nt))
U2 = 100 * (np.random.randn(2, nt) +
1j * np.random.randn(2, nt))
U_in = (U1, U2)
U_in_tot = np.abs(U1)**2 + np.abs(U2)**2
u_in1 = ifft(fftshift(U1, axes = -1))
u_in2 = ifft(fftshift(U2, axes = -1))
u_in_tot = simps(np.abs(u_in1)**2, sim_wind.t) + \
simps(np.abs(u_in2)**2, sim_wind.t)
a, b = WDMS.pass_through(U_in, sim_wind)
U_out1, U_out2 = a[1], b[1]
u_out1, u_out2 = a[0], b[0]
U_out_tot = np.abs(U_out1)**2 + np.abs(U_out2)**2
u_out_tot = simps(np.abs(u_out1)**2, sim_wind.t) + \
simps(np.abs(u_out2)**2, sim_wind.t)
def test1m_WDM_freq(self):
assert_allclose(self.U_in_tot, self.U_out_tot)
def test1m_WDM_time(self):
assert_allclose(self.u_in_tot, self.u_out_tot, rtol=1e-05)
class Test_perc_1m():
lamp1 = 1549
lamp2 = 1555
lams = 1550
N = 18
nt = 2**N
int_fwm = sim_parameters(2.5e-20, 2, [0,0])
int_fwm.general_options(1e-15, 1, 1, 'on')
int_fwm.propagation_parameters(N, 10, 100)
fv, D_freq = fv_creator(lamp1,lamp2, lams, int_fwm)
sim_wind = sim_window(fv, lamp1*1e-9, 1.5508e-6, int_fwm)
perc = 100 * np.random.rand(len(D_freq['where']))
print(perc)
WDMS = Perc_WDM(D_freq['where'], perc, fv, 'false')
U1 = 100*(np.random.randn(2, nt) +
1j * np.random.randn(2, nt))
U2 = 100 * (np.random.randn(2, nt) +
1j * np.random.randn(2, nt))
U_in = (U1, U2)
U_in_tot = np.abs(U1)**2 + np.abs(U2)**2
u_in1 = ifft(fftshift(U1, axes = -1))
u_in2 = ifft(fftshift(U2, axes = -1))
u_in_tot = simps(np.abs(u_in1)**2, sim_wind.t) + \
simps(np.abs(u_in2)**2, sim_wind.t)
a, b = WDMS.pass_through(U_in, sim_wind)
U_out1, U_out2 = a[1], b[1]
u_out1, u_out2 = a[0], b[0]
U_out_tot = np.abs(U_out1)**2 + np.abs(U_out2)**2
u_out_tot = simps(np.abs(u_out1)**2, sim_wind.t) + \
simps(np.abs(u_out2)**2, sim_wind.t)
def test1m_WDM_freq(self):
assert_allclose(self.U_in_tot, self.U_out_tot)
def test1m_WDM_time(self):
assert_allclose(self.u_in_tot, self.u_out_tot, rtol=1e-05)
class Test_bandpass_1m():
lamp1 = 1549
lamp2 = 1555
lams = 1550
N = 18
nt = 2**N
int_fwm = sim_parameters(2.5e-20, 2, [0,0])
int_fwm.general_options(1e-15, 1, 1, 'on')
int_fwm.propagation_parameters(N, 10, 100)
fv, D_freq = fv_creator(lamp1,lamp2, lams, int_fwm)
sim_wind = sim_window(fv, lamp1*1e-9, 1.5508e-6, int_fwm)
perc = 100 * np.random.rand(len(D_freq['where']))
print(perc)
WDMS = Bandpass_WDM(D_freq['where'], perc, fv, 'false')
U1 = 100*(np.random.randn(2, nt) +
1j * np.random.randn(2, nt))
U2 = 100 * (np.random.randn(2, nt) +
1j * np.random.randn(2, nt))
U_in = (U1, U2)
U_in_tot = np.abs(U1)**2 + np.abs(U2)**2
u_in1 = ifft(fftshift(U1, axes = -1))
u_in2 = ifft(fftshift(U2, axes = -1))
u_in_tot = simps(np.abs(u_in1)**2, sim_wind.t) + \
simps(np.abs(u_in2)**2, sim_wind.t)
a, b = WDMS.pass_through(U_in, sim_wind)
U_out1, U_out2 = a[1], b[1]
u_out1, u_out2 = a[0], b[0]
U_out_tot = np.abs(U_out1)**2 + np.abs(U_out2)**2
u_out_tot = simps(np.abs(u_out1)**2, sim_wind.t) + \
simps(np.abs(u_out2)**2, sim_wind.t)
def test1m_WDM_freq(self):
assert_allclose(self.U_in_tot, self.U_out_tot)
def test1m_WDM_time(self):
assert_allclose(self.u_in_tot, self.u_out_tot, rtol=1e-05)
def test_WDM_phase_modulation():
lamp1 = 1549
lamp2 = 1555
lams = 1550
N = 10
nt = 2**N
int_fwm = sim_parameters(2.5e-20, 2, [0,0])
int_fwm.general_options(1e-15, 1, 1, 'on')
int_fwm.propagation_parameters(N, 10, 100)
fv, D_freq = fv_creator(lamp1,lamp2, lams, int_fwm)
sim_wind = sim_window(fv, lamp1*1e-9, 1.5508e-6, int_fwm)
perc = 100 * np.random.rand(len(D_freq['where']))
WDMS = Bandpass_WDM(D_freq['where'], perc, fv, 'false')
pm = Phase_modulation_infase_WDM(D_freq['where'], WDMS)
U1 = np.random.randint(0,100) * np.random.randn(2, nt) + \
np.random.randint(0,100) * 1j * np.random.randn(2, nt)
U2 = np.random.randint(0,100) * np.random.randn(2, nt) + \
np.random.randint(0,100) * 1j * np.random.randn(2, nt)
U_in = (U1, U2)
a_non = WDMS.pass_through(U_in, sim_wind)[0]
U2cp = np.copy(U2)
pm.modulate(U1,U2)
assert_allclose(U2[1,:],U2cp[1,:])
U_in = (U1, U2)
a_mod= WDMS.pass_through(U_in, sim_wind)[0]
sig_idx = D_freq['where'][2]
e1 = np.abs(a_mod[1][0, sig_idx])**2
e2 = np.abs(a_non[1][0, sig_idx])**2
assert((e1 > e2) or np.allclose(e1,e2,equal_nan=True))
<file_sep>/testing/test_overlaps.py
import sys
sys.path.append('src')
import overlaps
import numpy as np
from numpy.testing import assert_allclose
from scipy.constants import c, pi
import os
def test_loader():
initial = overlaps.fibre_overlaps_loader(1)
os.system('rm loading_data/M1_M2_new_2m.hdf5')
overlaps.main()
ending = overlaps.fibre_overlaps_loader(1)
for i, j in zip(initial,ending):
assert_allclose(i,j)<file_sep>/src/Conversion_efficiency_post_proc.py
import numpy as np
import os
import pickle as pl
import tables
import h5py
from scipy.constants import c, pi
import gc
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from data_plotters_animators import read_variables
from functions import *
import warnings
warnings.filterwarnings('ignore')
import tables
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
from numpy.fft import fftshift
import scipy
from os import listdir
from joblib import Parallel, delayed
font = {'size' : 16}
matplotlib.rc('font'
, **font)
def selmier(l):
a = 0.6961663*l**2/(l**2 - 0.0684043**2)
b = 0.4079426*l**2/(l**2 - 0.1162414**2)
c = 0.8974794*l**2/(l**2 - 9.896161**2)
return (1 + a + b +c)**0.5
class Conversion_efficiency(object):
def __init__(self, freq_band_HW, last, safety, possition, filename=None, filepath='',filename2 = 'CE',filepath2 = 'output_final/'):
self.mode_names = ('LP01', 'LP11a')
self.n = 1.444
self.last = last
self.safety = safety
P_p1, P_p2, P_s, self.fv, self.lv,self.t, self.where, self.L = self.load_input_param(filepath)
if freq_band_HW is 'df':
freq_band_HW = 2* (self.fv[1] - self.fv[0])
self.input_powers = (P_p1, P_p2, P_s)
self.U_in, self.U_out = self.load_spectrum(possition,filename, filepath)
#print(self.U_in.shape)
#print(self.U_out.shape)
#sys.exit()
#self.U_in = dbm2w(np.max(w2dbm(self.U_in[0,:])) - w2dbm(self.U_in))
#self.U_out = dbm2w(w2dbm(np.max(self.U_out[0,0,:])) - w2dbm(self.U_out))
if type(last) is float:
self.last = int(last* self.U_out.shape[1])
else:
self.last = last
self.f_waves = [self.fv[i] for i in self.where]
self.nt = np.shape(self.U_in)[-1]
self.rounds = np.shape(self.U_in)[-2]
self.possition = possition
temp = np.argmin(abs(self.fv - 0.5 * (self.fv[0] + self.fv[-1]) - freq_band_HW))
self.band_idx_seper = [i * temp for i in (-1,1)]
self.lam_waves = [1e-3*c/i for i in self.f_waves]
self.U_large_norm = np.empty_like(self.U_out)
n_vec = [selmier(1e-3*i) for i in self.lam_waves]
self.time_trip = [self.L*n/c for n in n_vec]
for i in range(self.U_large_norm.shape[0]):
self.U_large_norm[i,:,:] =\
w2dbm(np.abs(self.U_out[i,:,:])**2)- np.max(w2dbm(np.abs(self.U_in[0,:])**2))
start_vec = [i - freq_band_HW for i in self.f_waves]
end_vec = [i + freq_band_HW for i in self.f_waves]
P_out_vec = np.empty([6,self.U_out.shape[1]])
count = 0
for start, end in zip(start_vec[:3], end_vec[:3]):
start_i = np.argmin(np.abs(self.fv - start))
end_i = np.argmin(np.abs(self.fv - end))
for ii,UU in enumerate(self.U_out[0,:,:]):
self.spec = UU
P_out_vec[count,ii] = self.calc_P_out(start_i,end_i)
count +=1
for start, end in zip(start_vec[3:], end_vec[3:]):
start_i = np.argmin(np.abs(self.fv - start))
end_i = np.argmin(np.abs(self.fv - end))
for ii,UU in enumerate(self.U_out[1,:,:]):
self.spec = UU
P_out_vec[count,ii] = self.calc_P_out(start_i,end_i)
count +=1
start_i = np.argmin(np.abs(self.fv - start_vec[2]))
end_i = np.argmin(np.abs(self.fv - end_vec[2]))
self.spec = self.U_out[0,0,:] #use compare for FOPA telecoms experiments!
self.spec = self.U_in[0,:]
self.P_signal_in = self.calc_P_out(start_i,end_i)
self.P_out_vec = P_out_vec
#for l, la in enumerate(last):
D_now = {}
D_now['L'] = self.L
D_now['P_out'] = np.mean(self.P_out_vec[:,-self.last::], axis = 1)
D_now['CE'] = D_now['P_out']/ self.P_signal_in
D_now['P_out_std'] = np.std(self.P_out_vec[:,-self.last::], axis = 1)
D_now['CE_std'] = np.std(self.P_out_vec[:,-self.last::] / self.P_signal_in, axis = 1)
D_now['rin'] = 10*np.log10(self.time_trip*D_now['P_out_std']**2 / D_now['P_out']**2)
D_now['input_powers'] = self.input_powers
D_now['frequencies'] = self.f_waves
for i,j in zip(D_now.keys(), D_now.values()):
D_now[i] = [j]
if os.path.isfile(filepath2+filename2+'.pickle'):
with open(filepath2+filename2+'.pickle','rb') as f:
D = pl.load(f)
for i,j in zip(D.keys(), D.values()):
D[i] = j + D_now[i]
else:
D = D_now
with open(filepath2+filename2+'.pickle','wb') as f:
pl.dump(D,f)
self.input_data_formating()
return None
def load_input_param(self, filepath=''):
filename='input_data'
D = read_variables(filepath+filename, '0/0')
P_p1 = D['P_p1']
P_p2 = D['P_p2']
P_s = D['P_s']
fv = D['fv']
lv = D['lv']
t = D['t']
where = D['where']
L = D['L']
return P_p1, P_p2, P_s, fv, lv, t, where, L
def load_spectrum(self, possition,filename='data_large', filepath=''):
U_in = read_variables(filepath + filename, 'input')['U']
U_out = read_variables(filepath + filename, 'results/'+possition)['U']
U_in, U_out = (np.abs(i)**2 * (self.t[1] - self.t[0])**2 for i in (U_in, U_out))
return U_in,U_out
def calc_P_out(self,i,j):
P_out = simps(self.spec[i:j],\
self.fv[i:j])/(2*np.max(self.t))
return P_out
def input_data_formating(self):
unstr_str = r"$P_1=$ {0:.2f} W, $P_s=$ {1:.2f} mW, "+\
r"$P_2=$ {2:.2f} W, "+\
r"$\lambda_1=$ {3:.2f} nm, $\lambda_s=$ {4:.2f} nm, "+\
r"$\lambda_2=$ {5:.2f} nm,"
input_data = (self.input_powers[0], self.input_powers[2]*1e3, self.input_powers[1],
self.lam_waves[1], self.lam_waves[2], self.lam_waves[4])
self.title_string = unstr_str.format(*input_data)
input_data_str = ('P_1', 'P_s', 'P_2', 'l1', 'ls', 'l2')
self._data ={i:j for i, j in zip(input_data_str,input_data)}
return None
def P_out_round(self,P,CE,filepath,filesave):
"""Plots the output average power with respect to round trip number"""
x = range(P.shape[-1])
y = np.asanyarray(P)
names = ('MI', 'P1', 'S', 'PC', 'P2', 'BS')
for i, name in enumerate(names):
fig = plt.figure(figsize=(20.0, 10.0))
plt.subplots_adjust(hspace=0.1)
plt.plot(x, y[i,:], '-')
plt.title(CE.title_string)
plt.grid()
plt.xlabel('Rounds')
plt.ylabel('Output Power (W)')
plt.savefig(filepath+'/'+name+'/power_per_round'+filesave+'.png')
data = (range(len(P)), P)
with open(filepath+'/'+name+'/power_per_round'+filesave+'.pickle','wb') as f:
pl.dump((data,CE._data),f)
plt.clf()
plt.close('all')
return None
def final_1D_spec(self,ii,CE,filename,wavelengths = None):
x,y = self.fv, self.U_large_norm[:,-1,:]
fig = plt.figure(figsize=(20.0, 10.0))
for i in range(y.shape[0]):
plt.plot(x, y[i, :], '-', label=self.mode_names[i])
plt.legend(loc = 2)
plt.title(self.title_string)
plt.grid()
plt.xlabel(r'$f (THz)$')
plt.ylabel(r'Spec (dB)')
#plt.ylim([-200,1])
#plt.xlim([192, 194.5])
plt.savefig(filename+'.png', bbox_inches = 'tight')
data = (x, y)
#with open(filename+str(ii)+'.pickle','wb') as f:
# pl.dump((data,CE._data),f)
plt.clf()
plt.close('all')
return None
def plot_rin(var,var2 = 'rin',filename = 'CE', filepath='output_final/', filesave= None):
var_val, CE,std = read_CE_table(filename,var,var2 = var2,file_path=filepath)
std = std[var2].as_matrix()
if var is 'arb':
var_val = [i for i in range(len(CE))]
fig = plt.figure(figsize=(20.0, 10.0))
plt.plot(var_val, 10*np.log10(CE),'o-')
plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
plt.gca().get_xaxis().get_major_formatter().set_useOffset(False)
plt.xlabel(var)
plt.ylabel('RIN (dBc/hz)')
plt.savefig(filesave+'.png',bbox_inches = 'tight')
data = (var_val, CE,std)
with open(str(filesave)+'.pickle','wb') as f:
pl.dump((fig,data),f)
plt.clf()
plt.close('all')
return None
def read_CE_table(x_key,y_key ,filename, std = False, decibels = False):
with open(filename+'.pickle','rb') as f:
D = pl.load(f)
D['P1'], D['P2'], D['Ps'] = [[D['input_powers'][i][j] for i in range(len(D['input_powers']))] for j in range(3)]
D['f_mi'], D['f_p1'], D['f_s'],\
D['f_pc'], D['f_p2'],\
D['f_bs'] =\
[[D['frequencies'][i][j] for i in range(len(D['frequencies']))] for j in range(6)]
D['l_mi'], D['l_p1'], D['l_s'],\
D['l_pc'], D['l_p2'],\
D['l_bs'] =\
[[1e-3*c/D['frequencies'][i][j] for i in range(len(D['frequencies']))] for j in range(6)]
D['CE_mi'], D['CE_p1'], D['CE_s'],\
D['CE_pc'], D['CE_p2'],\
D['CE_bs'] =\
[[D['CE'][i][j] for i in range(len(D['CE']))] for j in range(6)]
D['CEstd_mi'], D['CEstd_p1'], D['CEstd_s'],\
D['CEstd_pc'], D['CEstd_p2'],\
D['CEstd_bs'] =\
[[D['CE_std'][i][j] for i in range(len(D['CE_std']))] for j in range(6)]
D['P_out_mi'], D['P_out_p1'], D['P_out_s'],\
D['P_out_pc'], D['P_out_p2'],\
D['P_out_bs'] =\
[[D['P_out'][i][j] for i in range(len(D['P_out']))] for j in range(6)]
D['P_out_std_mi'], D['P_out_std_p1'], D['P_out_std_s'],\
D['P_out_std_pc'], D['P_out_std_p2'],\
D['P_out_std_bs'] =\
[[D['P_out_std'][i][j] for i in range(len(D['P_out_std']))] for j in range(6)]
D['rin_mi'], D['rin_p1'], D['rin_s'],\
D['rin_pc'], D['rin_p2'],\
D['rin_bs'] =\
[[D['rin'][i][j] for i in range(len(D['rin']))] for j in range(6)]
x = D[x_key]
if y_key[:2] == 'CE' and decibels == True:
y = 10 * np.log10(np.asarray(D[y_key]))
else:
y = np.asarray(D[y_key])
if std:
try:
err_bars = D['y_key'+'_std']
except KeyError:
sys.exit('There is not error bar for the variable you are asking for.')
else:
err_bars = 0
x,y,err_bars = np.asanyarray(x),np.asanyarray(y), np.asanyarray(y)
return x,y,err_bars
def plot_CE(x_key,y_key,std = True, decibels = False,filename = 'CE', filepath='output_final/', filesave= None):
x, y, err_bars = read_CE_table(x_key,y_key,filepath+filename,decibels = decibels,std = std )
fig = plt.figure(figsize=(20.0, 10.0))
plt.subplots_adjust(hspace=0.1)
mode_labels = ('LP01x','LP01y')
if std:
plt.errorbar(x,y, yerr=err_bars, capsize= 10)
else:
plt.plot(x - 1549,y)
plt.xlabel(x_key)
plt.ylabel(y_key)
plt.grid()
plt.xticks(np.arange(0, 2.75, 0.25))
plt.savefig(filesave+'.png',bbox_inches = 'tight')
data = (x, y,err_bars)
with open(str(filesave)+'.pickle','wb') as f:
pl.dump(data,f)
plt.clf()
plt.close('all')
return None
def contor_plot(CE,fmin = None,fmax = None, rounds = None,folder = None,filename = None):
if rounds is None:
rounds = np.shape(CE.U_large_norm)[0]
CE.ro = range(rounds)
x,y = np.meshgrid(CE.ro[:rounds], CE.fv[:])
z = CE.U_large_norm[:rounds,:,:]
low_values_indices = z < -60 # Where values are low
z[low_values_indices] = -60 # All low values set to 0
for nm in range(z.shape[1]):
fig = plt.figure(figsize=(20,10))
plt.contourf(x,y, z[:,nm,:].T, np.arange(-60,2,2),extend = 'min',cmap=plt.cm.jet)
plt.xlabel(r'$rounds$')
plt.ylim(fmin,fmax)
plt.ylabel(r'$f(THz)$')
plt.colorbar()
plt.title(CE.title_string)
data = (CE.ro, CE.fv, z)
if filename is not None:
plt.savefig(folder+str(nm)+'_'+filename, bbox_inches = 'tight')
plt.clf()
plt.close('all')
else:
plt.show()
if filename is not None:
with open(str(folder+filename)+'.pickle','wb') as f:
pl.dump((data,CE._data),f)
return None
def P_out_round_anim(CE,iii,filesave):
"""Plots the output average power with respect to round trip number"""
tempy = CE.P_out_vec[:iii]
fig = plt.figure(figsize=(7,1.5))
plt.plot(range(len(tempy)), tempy)
plt.xlabel('Oscillations')
plt.ylabel('Power')
plt.ylim(0,np.max(CE.P_out_vec)+0.1*np.max(CE.P_out_vec))
plt.xlim(0,len(CE.P_out_vec))
plt.savefig(filesave+'.png',bbox_inches = 'tight')
plt.close('all')
plt.clf()
return None
def tick_function(X):
l = 1e-3*c/X
return ["%.2f" % z for z in l]
def main2(ii):
ii = str(ii)
which = which_l+ ii
os.system('mkdir output_final/'+str(ii))
os.system('mkdir output_final/'+str(ii)+'/pos'+pos+'/ ;'+'mkdir output_final/'+str(ii)+'/pos'+pos+'/many ;'+'mkdir output_final/'+str(ii)+'/pos'+pos+'/spectra;'
+'mkdir output_final/'+str(ii)+'/pos'+pos+'/powers;'
+'mkdir output_final/'+str(ii)+'/pos'+pos+'/powers/BS;'
+'mkdir output_final/'+str(ii)+'/pos'+pos+'/powers/PC;'
+'mkdir output_final/'+str(ii)+'/pos'+pos+'/powers/MI;'
+'mkdir output_final/'+str(ii)+'/pos'+pos+'/powers/P1;'
+'mkdir output_final/'+str(ii)+'/pos'+pos+'/powers/P2;'
+'mkdir output_final/'+str(ii)+'/pos'+pos+'/powers/S;'
+'mkdir output_final/'+str(ii)+'/pos'+pos+'/casc_powers;'
+'mkdir output_final/'+str(ii)+'/pos'+pos+'/final_specs;')
for i in inside_vec[int(ii)]:
print(ii,i)
CE = Conversion_efficiency(freq_band_HW = 'df',possition = pos,last = 0.5,\
safety = 2, filename = 'data_large',\
filepath = which+'/output'+str(i)+'/data/',filepath2 = 'output_final/'+str(ii)+'/pos'+str(pos)+'/')
fmin,fmax,rounds = 310,330,2000#np.min(CE.fv),np.max(CE.fv),None
fmin,fmax,rounds = None,None, None
#if CE.U_large_norm.shape[0]>1:
# contor_plot(CE,fmin,fmax,rounds,folder = 'output_final/'+str(ii)+'/pos'+pos+'/spectra/',filename= str(ii)+'_'+str(i))
#contor_plot_time(CE, rounds = None,filename = 'output_final/'+str(ii)+'/pos'+pos+'/'+'time_'+str(ii)+'_'+str(i))
CE.P_out_round(CE.P_out_vec,CE,filepath = 'output_final/'+str(ii)+'/pos'+pos+'/powers/', filesave =str(ii)+'_'+str(i))
CE.final_1D_spec(ii,CE,filename = 'output_final/'+str(ii)+'/pos'+pos+'/final_specs/'+'spectrum_fopo_final'+str(i),wavelengths = wavelengths)
del CE
gc.collect()
for x_key,y_key,std, decibel in (('l_s', 'P_out_bs',False, False), ('l_s', 'CE_bs',False, True), ('l_s', 'rin_bs',False, False),\
('l_s', 'P_out_pc',False, False), ('l_s', 'CE_pc',False, True), ('l_s', 'rin_pc',False, False)):
plot_CE(x_key,y_key,std = std,decibels = decibel, filename = 'CE',\
filepath='output_final/'+str(ii)+'/pos'+pos+'/', filesave = 'output_final/'+str(ii)+'/pos'+pos+'/many/'+y_key+str(ii))
return None
#from os.path import , join
data_dump = 'output_dump'
outside_dirs = [f for f in listdir(data_dump)]
inside_dirs = [[f for f in listdir(data_dump+ '/'+out_dir)] for out_dir in outside_dirs ]
which = 'output_dump_pump_wavelengths/7w'
which = 'output_dump_pump_wavelengths/wrong'
which = 'output_dump_pump_wavelengths'
#which = 'output_dump_pump_wavelengths/2_rounds'
#which ='output_dump_pump_powers/ram0ss0'
#which = 'output_dump/'#_pump_powers'
which_l = 'output_dump/output'
outside_vec = range(len(outside_dirs))
#outside_vec = range(2,3)
inside_vec = [range(len(inside) - 1) for inside in inside_dirs]
#inside_vec = [13]
animators = False
spots = range(0,8100,100)
wavelengths = [1200,1400,1050,930,800]
#wavelengths = None
os.system('rm -r output_final ; mkdir output_final')
for pos in ('2',):
#for ii in outside_vec:
A = Parallel(n_jobs=6)(delayed(main2)(ii) for ii in outside_vec)
#os.system('rm -r prev_anim/*; mv animators* prev_anim')
<file_sep>/src/overlaps.py
import numpy as np
from scipy.integrate import dblquad
from scipy.io import loadmat
import h5py
import os
def field0(y, x, w):
return np.exp(-(x**2+y**2)/w**2)
def field1(y, x, w):
return (2*2**0.5*x/w)*np.exp(-(x**2+y**2)/w**2)
def calc_overlaps():
overlaps = np.zeros([2, 8])
neff1 = 1
neff2 = 1
n0 = 1
r = 62.45 # radius of the fibre in microns
# for Q0000
overlaps[:, 0] = (n0/neff1)**2*1/161. # top/bottom
# for Q1111
overlaps[:, -1] = (n0/neff2)**2*1/170. # top/bottom
# for Qeven
# load widths in meters from previous calculations
widths = np.loadtxt('loading_data/widths.dat')
# Convert to microns so we do the integrations in microns
w = widths[0:2]*1e6
def int1(y, x): return field1(y, x, w[1])**2*field0(y, x, w[0])**2
def int2(y, x): return field0(y, x, w[0])**2
def int3(y, x): return field1(y, x, w[1])**2
top = dblquad(int1, -r, r, lambda x: -r, lambda x: r)[0]
bottom = dblquad(int2, -r, r, lambda x: -r,
lambda x: r)[0]*dblquad(int3, -r, r,
lambda x: -r, lambda x: r)[0]
overlaps[:, 1:7] = (n0**2/(neff1*neff2))*top/bottom
overlaps *= 1e12
overlaps /= 3
return overlaps
def fibre_overlaps_loader(dt,filepath='loading_data', fr = 0.18):
"""
Loads, or calculates if not there, the M1, M2 and Q matrixes.
"""
overlap_file = os.path.join(filepath, 'M1_M2_new_2m.hdf5')
kr = 1-fr
if os.path.isfile(overlap_file):
keys = ('M1', 'M2', 'Q')
data = []
with h5py.File(overlap_file, 'r') as f:
for i in keys:
data.append(f.get(str(i)).value)
data = tuple(data)
else:
data = main()
for i in range(data[-1].shape[-1]):
data[-1][1,i] = 2 * kr * data[-1][0, i] + kr * data[-1][1, i]
data[-1][0,:] *= 3 * fr * dt
return data
def save_variables(filename, **variables):
with h5py.File(filename + '.hdf5', 'a') as f:
for i in (variables):
f.create_dataset(str(i), data=variables[i])
return None
def main():
Q_matrix = np.real(calc_overlaps())
mat = loadmat("loading_data/M1_M2_2m.mat", squeeze_me=True)
M1_load = mat['M1']
M2_load = mat['M2']
M2 = np.uint32(M2_load - 1)
M1 = np.empty([5, 8], dtype=np.uint32)
M1[0:4, :] = np.int32(np.real(M1_load[0:4, :] - 1))
M1[4, :] = np.int32(np.real(M1_load[-1, :] - 1))
D = {'M1': M1, 'M2': M2, 'Q': Q_matrix}
save_variables('loading_data/M1_M2_new_2m', **D)
return M1, M2, Q_matrix
if __name__ == '__main__':
if os.path.isfile('loading_data/M1_M2_new_2m.hdf5'):
os.system('rm loading_data/M1_M2_new_2m.hdf5')
main()
<file_sep>/testing/test_small.py
import sys
sys.path.append('src')
from functions import *
import os
import pytest
import numpy as np
from numpy.testing import assert_allclose
import overlaps
def test_read_write1():
#os.system('rm testing_data/hh51_test.hdf5')
A = np.random.rand(10, 3, 5) + 1j * np.random.rand(10, 3, 5)
B = np.random.rand(10)
C = 1
save_variables('hh51_test', '0', filepath='testing/testing_data/',
A=A, B=B, C=C)
A_copy, B_copy, C_copy = np.copy(A), np.copy(B), np.copy(C)
del A, B, C
D = read_variables('hh51_test', '0', filepath='testing/testing_data/')
A, B, C = D['A'], D['B'], D['C']
os.system('rm testing/testing_data/hh51_test.hdf5')
assert_allclose(A, A_copy)
def test_read_write2():
#os.system('rm testing_data/hh52_test.hdf5')
A = np.random.rand(10, 3, 5) + 1j * np.random.rand(10, 3, 5)
B = np.random.rand(10)
C = 1
save_variables('hh52_test', '0', filepath='testing/testing_data/',
A=A, B=B, C=C)
A_copy, B_copy, C_copy = np.copy(A), np.copy(B), np.copy(C)
del A, B, C
D = read_variables('hh52_test', '0', filepath='testing/testing_data/')
A, B, C = D['A'], D['B'], D['C']
# locals().update(D)
os.system('rm testing/testing_data/hh52_test.hdf5')
return None
def test_read_write3():
A = np.random.rand(10, 3, 5) + 1j * np.random.rand(10, 3, 5)
B = np.random.rand(10)
C = 1
save_variables('hh53_test', '0', filepath='testing/testing_data/',
A=A, B=B, C=C)
A_copy, B_copy, C_copy = np.copy(A), np.copy(B), np.copy(C)
del A, B, C
D = read_variables('hh53_test', '0', filepath='testing/testing_data/')
A, B, C = D['A'], D['B'], D['C']
os.system('rm testing/testing_data/hh53_test.hdf5')
assert C == C_copy
return None
def test_dbm2w():
assert dbm2w(30) == 1
def test1_w2dbm():
assert w2dbm(1) == 30
def test2_w2dbm():
a = np.zeros(100)
floor = np.random.rand(1)[0]
assert_allclose(w2dbm(a, -floor), -floor*np.ones(len(a)))
def test3_w2dbm():
with pytest.raises(ZeroDivisionError):
w2dbm(-1)
def test_load_fibre_param():
os.system('rm loading_data/M1_M2_new_2m.hdf5')
M1_,M2_,Q_ = overlaps.fibre_overlaps_loader(1)
M1, M2,Q = overlaps.fibre_overlaps_loader(1)
assert_allclose(M1, np.array([[0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 1, 1, 0, 0, 1, 1],
[0, 1, 0, 1, 0, 1, 0, 1],
[0, 1, 1, 0, 1, 0, 0, 1],
[0, 1, 2, 3, 2, 3, 0, 1]]))
assert_allclose(M2, np.array([[0, 1, 0, 1], [0, 1, 1, 0]]))
assert_allclose(M1,M1_)
assert_allclose(M2, M2_)
assert_allclose(Q, Q_)<file_sep>/src/src/data_plotters_animators.py
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
from scipy.constants import c
import h5py
import sys
import warnings
warnings.simplefilter("ignore", UserWarning)
font = {'size': 18}
mpl.rc('font', **font)
def w2dbm(W, floor=-100):
"""This function converts a power given in W to a power given in dBm.
Inputs::
W(float): power in units of W
Returns::
Power in units of dBm(float)
"""
if type(W) != np.ndarray:
if W > 0:
return 10. * np.log10(W) + 30
elif W == 0:
return floor
else:
print(W)
raise(ZeroDivisionError)
a = 10. * (np.ma.log10(W)).filled(floor/10-3) + 30
return a
class Plotter_saver(object):
def __init__(self, plots, filesaves):
if plots and filesaves:
self.exporter = self.plotter_saver_both
elif plots and not(filesaves):
self.exporter = self.plotter_only
elif not(plots) and filesaves:
self.exporter = self.saver_only
else:
sys.exit("You are not exporting anything,\
wasted calculation")
return None
def plotter_saver_both(self, index, int_fwm, sim_wind, u, U, D_param, which, ro, mode_names, pump_wave='',
filename=None, title=None, im=0, plots=True):
self.plotter(index, int_fwm, sim_wind, u, U, D_param,
which, ro, mode_names, pump_wave,
filename, title, im, plots)
self.saver(index, int_fwm, sim_wind, u, U, D_param,
which, ro, mode_names, pump_wave, filename, title,
im, plots)
return None
def plotter_only(self, index, int_fwm, sim_wind, u, U, D_param, which, ro, mode_names, pump_wave='',
filename=None, title=None, im=0, plots=True):
self.plotter(index, int_fwm, sim_wind, u, U, D_param, which, ro, mode_names, pump_wave,
filename, title, im, plots)
return None
def saver_only(self, index, int_fwm, sim_wind, u, U, D_param,
which, ro, mode_names, pump_wave='',
filename=None, title=None, im=0, plots=True):
self.saver(index, int_fwm, sim_wind, u, U, D_param,
which, ro, mode_names, pump_wave, filename, title,
im, plots)
return None
def plotter(self, index, int_fwm, sim_wind, u, U, D_param, which, ro, mode_names, pump_wave='',
filename=None, title=None, im=0, plots=True):
"""Plots many modes"""
x, y = 1e-3*c/sim_wind.fv, w2dbm(np.abs(U[:, :])**2)
xlim, ylim = [x.min(), x.max()], [y.min(), y.max()]
xlabel, ylabel = r'$\lambda (nm)$', r'$Spectrum (a.u.)$'
filesave = 'output'+pump_wave+'/output' + \
str(index) + '/figures/wavelength/'+filename
plot_multiple_modes(int_fwm.nm, x, y, which, mode_names,
ylim, xlim, xlabel, ylabel, title, filesave, im)
# Frequency
x, y = sim_wind.fv, w2dbm(np.abs(U[:, :])**2)
xlim, ylim = [np.min(x), np.max(x)], [-20, 120]
xlabel, ylabel = r'$f (THz)$', r'$Spectrum (a.u.)$'
filesave = 'output'+pump_wave+'/output' + \
str(index) + '/figures/frequency/'+filename
plot_multiple_modes(int_fwm.nm, x, y, which, mode_names,
ylim, xlim, xlabel, ylabel, title, filesave, im)
# Time
x, y = sim_wind.t, np.abs(u[:, :])**2
xlim, ylim = [np.min(x), np.max(x)], [np.min(y), np.max(y)]
xlabel, ylabel = r'$\lambda (nm)$', r'$Spectrum (W)$'
filesave = 'output'+pump_wave+'/output' + \
str(index) + '/figures/time/'+filename
plot_multiple_modes(int_fwm.nm, x, y, which, mode_names,
ylim, xlim, xlabel, ylabel, title, filesave, im)
return None
def saver(self, index, int_fwm, sim_wind, u, U, D_param,
which, ro, mode_names, pump_wave='', filename=None, title=None,
im=0, plots=True):
"""Dump to HDF5 for postproc"""
if filename[:4] != 'port':
layer = filename[-1]+'/'+filename[:-1]
else:
layer = filename
if ro == 0 and title == 'original pump':
D_save = {**D_param, **{'fv':sim_wind.fv, 'lv':sim_wind.lv, 't': sim_wind.t, 'L': int_fwm.z}}
save_variables('input_data', str(layer), filepath='output'+pump_wave+'/output'+str(index)+'/data/', **D_save)
#extra_data = np.array([int_fwm.tot_z, which, int_fwm.nm,P0_p, P0_s, f_p, f_s, ro])
try:
save_variables('data_large', str(layer), filepath='output'+pump_wave+'/output'+str(index)+'/data/', U=np.abs(U[:, :]))
except RuntimeError:
os.system('rm output'+pump_wave+'/output' +
str(index)+'/data/data_large.hdf5')
save_variables('data_large', layer, filepath='output'+pump_wave+'/output'+str(index)+'/data/', U=np.abs(U[:, :]))
pass
return None
def plot_multiple_modes(nm, x, y, which, mode_names, ylim, xlim, xlabel, ylabel, title, filesave=None, im=None):
"""
Dynamically plots what is asked of it for multiple modes given at set point.
"""
fig = plt.figure(figsize=(20.0, 10.0))
for i, v in enumerate(range(nm)):
v = v+1
plt.plot(x, y[i, :], '-', label=mode_names[i])
plt.ylim(ylim)
plt.xlim(xlim)
plt.legend(loc = 2)
plt.grid()
ax = fig.add_subplot(111, frameon=False)
ax.axes.get_xaxis().set_ticks([])
ax.axes.get_yaxis().set_ticks([])
ax.set_title(title)
ax.yaxis.set_label_coords(-0.05, 0.5)
ax.xaxis.set_label_coords(0.5, -0.05)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if type(im) != int:
newax = fig.add_axes([0.8, 0.8, 0.2, 0.2], anchor='NE')
newax.imshow(im)
newax.axis('off')
if filesave == None:
plt.show()
else:
plt.savefig(filesave, bbox_inched='tight')
plt.close(fig)
return None
def animator_pdf_maker(rounds, pump_index):
"""
Creates the animation and pdf of the FOPO at different parts of the FOPO
using convert from imagemagic. Also removes the pngs so be carefull
"""
print("making pdf's and animations.")
space = ('wavelength', 'freequency', 'time')
for sp in space:
file_loc = 'output/output'+str(pump_index)+'/figures/'+sp+'/'
strings_large = ['convert '+file_loc+'00.png ']
for i in range(4):
strings_large.append('convert ')
for ro in range(rounds):
for i in range(4):
strings_large[i+1] += file_loc+str(ro)+str(i+1)+'.png '
for w in range(1, 4):
if i == 5:
break
strings_large[0] += file_loc+str(ro)+str(w)+'.png '
for i in range(4):
os.system(strings_large[i]+file_loc+str(i)+'.pdf')
file_loca = file_loc+'portA/'
file_locb = file_loc+'portB/'
string_porta = 'convert '
string_portb = 'convert '
for i in range(rounds):
string_porta += file_loca + str(i) + '.png '
string_portb += file_locb + str(i) + '.png '
string_porta += file_loca+'porta.pdf '
string_portb += file_locb+'portb.pdf '
os.system(string_porta)
os.system(string_portb)
for i in range(4):
os.system(
'convert -delay 30 '+file_loc+str(i)+'.pdf '+file_loc+str(i)+'.mp4')
os.system('convert -delay 30 ' + file_loca +
'porta.pdf ' + file_loca+'porta.mp4 ')
os.system('convert -delay 30 ' + file_locb +
'portb.pdf ' + file_locb+'portb.mp4 ')
for i in (file_loc, file_loca, file_locb):
print('rm ' + i + '*.png')
os.system('rm ' + i + '*.png')
os.system('sleep 5')
return None
def read_variables(filename, layer, filepath=''):
with h5py.File(filepath+str(filename)+'.hdf5', 'r') as f:
D = {}
for i in f.get(layer).keys():
try:
D[str(i)] = f.get(layer + '/' + str(i)).value
except AttributeError:
pass
return D
def save_variables(filename, layers, filepath='', **variables):
with h5py.File(filepath + filename + '.hdf5', 'a') as f:
for i in (variables):
f.create_dataset(layers+'/'+str(i), data=variables[i])
return None
<file_sep>/run_postproc.sh
#!/bin/bash
# Simple postprocessing code
source activate intel
python src/Conversion_efficiency_post_proc.py
<file_sep>/testing/test_pulse_prop.py
import sys
sys.path.append('src')
from functions import *
import numpy as np
from numpy.testing import assert_allclose
from overlaps import *
from integrand_and_rk import *
from cython_files.cython_integrand import *
def inputs(nm = 2):
n2 = 2.5e-20 # n2 for silica [m/W]
# 0.0011666666666666668 # loss [dB/m]
alphadB = np.array([0 for i in range(nm)])
gama = 1e-3 # w/m
"-----------------------------General options------------------------------"
maxerr = 1e-13 # maximum tolerable error per step
"----------------------------Simulation parameters-------------------------"
N = 10
z = 10 # total distance [m]
nplot = 10 # number of plots
nt = 2**N # number of grid points
#dzstep = z/nplot # distance per step
dz_less = 1
dz = 1 # starting guess value of the step
lamp1 = 1549
lamp2 = 1555
lams = 1550
lamda_c = 1.5508e-6
lamda = lamp1*1e-9
P_p1 = 1
P_p2 = 1
P_s = 1e-3
return n2, alphadB, gama, maxerr, N, z, nt,\
lamp1, lamp2, lams, lamda_c, lamda, P_p1, P_p2, P_s, dz_less
def same_noise(nm = 2):
n2, alphadB, gama, maxerr, N, z, nt,\
lamp1, lamp2, lams, lamda_c, lamda,\
P_p1, P_p2, P_s, dz_less = inputs(nm)
int_fwm = sim_parameters(n2, nm, alphadB)
int_fwm.general_options(maxerr, raman_object, 1, 'on')
int_fwm.propagation_parameters(N, z, dz_less)
fv, D_freq = fv_creator(lamp1,lamp2, lams, int_fwm)
sim_wind = sim_window(fv, lamda, lamda_c, int_fwm)
noise_obj = Noise(int_fwm, sim_wind)
return noise_obj
noise_obj = same_noise()
def wave_setup(ram, ss, nm, N_sol=1, cython = True, u = None):
n2, alphadB, gama, maxerr, N, z, nt,\
lamp1, lamp2, lams, lamda_c, lamda,\
P_p1, P_p2, P_s, dz_less = inputs(nm)
int_fwm = sim_parameters(n2, nm, alphadB)
int_fwm.general_options(maxerr, raman_object, ss, ram)
int_fwm.propagation_parameters(N, z, dz_less)
fv, D_freq = fv_creator(lamp1,lamp2, lams, int_fwm)
sim_wind = sim_window(fv, lamda, lamda_c, int_fwm)
loss = Loss(int_fwm, sim_wind, amax=int_fwm.alphadB)
alpha_func = loss.atten_func_full(sim_wind.fv)
int_fwm.alphadB = alpha_func
int_fwm.alpha = int_fwm.alphadB
dnerr = [0]
index = 1
master_index = 0
a_vec = [2.2e-6]
M1, M2, Q_large = fibre_overlaps_loader(sim_wind.dt)
betas = load_disp_paramters(sim_wind.w0)
Dop = dispersion_operator(betas, int_fwm, sim_wind)
integrand = Integrand(ram, ss, cython = cython, timing = False)
dAdzmm = integrand.dAdzmm
pulse_pos_dict_or = ('after propagation', "pass WDM2",
"pass WDM1 on port2 (remove pump)",
'add more pump', 'out')
#M1, M2, Q = Q_matrixes(1, n2, lamda, gama=gama)
raman = raman_object('on', int_fwm.how)
raman.raman_load(sim_wind.t, sim_wind.dt, M2)
hf = raman.hf
u = np.empty(
[2, int_fwm.nm, len(sim_wind.t)], dtype='complex128')
U = np.empty([2,int_fwm.nm,
len(sim_wind.t)], dtype='complex128')
w_tiled = np.tile(sim_wind.w + sim_wind.woffset, (int_fwm.nm, 1))
u[0,:, :] = noise_obj.noise
fr = 0.18
kr = 1 -fr
for i in range(Q_large.shape[1]):
Q_large[1,i] = 2 * kr * Q_large[0, i] + kr * Q_large[1, i]
woff1 = (D_freq['where'][1]+(int_fwm.nt)//2)*2*pi*sim_wind.df
u[0,0, :] += (P_p1)**0.5 * np.exp(1j*(woff1)*sim_wind.t)
woff2 = (D_freq['where'][2]+(int_fwm.nt)//2)*2*pi*sim_wind.df
u[0,0, :] += (P_s)**0.5 * np.exp(1j*(woff2) *
sim_wind.t)
woff3 = (D_freq['where'][4]+(int_fwm.nt)//2)*2*pi*sim_wind.df
u[0,1, :] += (P_p2)**0.5 * np.exp(1j*(woff3) *
sim_wind.t)
U = fftshift(sim_wind.dt*fft(u), axes = -1)
gam_no_aeff = -1j*int_fwm.n2*2*pi/sim_wind.lamda
dz,dzstep,maxerr = int_fwm.dz,int_fwm.z,int_fwm.maxerr
Dop = np.ascontiguousarray(Dop)
w_tiled = np.ascontiguousarray(w_tiled)
dt = sim_wind.dt
tsh = sim_wind.tsh
u_temp = np.ascontiguousarray(u[0,:,:])
hf = np.ascontiguousarray(hf)
return U, u_temp,dz,dzstep,maxerr, M1, M2, Q_large, w_tiled, tsh, dt, hf, Dop,gam_no_aeff
"-----------------------Pulse--------------------------------------------"
def pulse_propagations(ram, ss, nm, N_sol=1, cython = True, u = None):
U, u_temp,dz,dzstep,maxerr, M1, M2, Q_large, w_tiled, tsh, dt, hf, Dop,gam_no_aeff = \
wave_setup(ram, ss, nm, N_sol=N_sol, cython = cython, u = u)
U_t, dz = pulse_propagation(u_temp,dz,dzstep,maxerr, M1, M2, Q_large, w_tiled, tsh, hf, Dop,gam_no_aeff)
U[-1,:,:] = U_t
u = np.fft.ifft(np.fft.ifftshift(U, axes = -1))
"""
fig1 = plt.figure()
plt.plot(sim_wind.fv,w2dbm(np.abs(U[0,0,:])**2))
plt.plot(sim_wind.fv,w2dbm(np.abs(U[0,1,:])**2))
plt.savefig('1.png')
plt.close()
fig2 = plt.figure()
plt.plot(sim_wind.fv,w2dbm(np.abs(U[1,0,:])**2))
plt.plot(sim_wind.fv,w2dbm(np.abs(U[1,1,:])**2))
plt.savefig('2.png')
plt.close()
fig3 = plt.figure()
plt.plot(sim_wind.t,np.abs(u[0,0,:])**2)
plt.plot(sim_wind.t,np.abs(u[0,1,:])**2)
plt.savefig('3.png')
plt.close()
fig4 = plt.figure()
plt.plot(sim_wind.t,np.abs(u[1,0,:])**2)
plt.plot(sim_wind.t,np.abs(u[1,1,:])**2)
#plt.xlim(-10*T0, 10*T0)
plt.savefig('4.png')
plt.close()
fig5 = plt.figure()
plt.plot(fftshift(sim_wind.w),(np.abs(U[1,0,:])**2 - np.abs(U[0,0,:])**2 ))
plt.plot(fftshift(sim_wind.w),(np.abs(U[1,1,:])**2 - np.abs(U[0,1,:])**2 ))
plt.savefig('error.png')
plt.close()
fig6 = plt.figure()
plt.plot(sim_wind.t,np.abs(u[0,0,:])**2 - np.abs(u[1,0,:])**2)
plt.plot(sim_wind.t,np.abs(u[0,1,:])**2 - np.abs(u[1,1,:])**2)
plt.savefig('error2.png')
plt.close()
"""
return u, U, maxerr
"--------------------------------------------------------------------------"
class Test_pulse_prop_energy(object):
def __test__(self,u):
E = []
for uu in u:
sums = 0
for umode in uu:
print(umode.shape)
sums += np.linalg.norm(umode)**2
E.append(sums)
np.allclose(E[0], E[1])
def test_energy_r1_ss1_2(self):
u, U, maxerr = pulse_propagations(
'on', 1, nm=2, N_sol=np.abs(10*np.random.randn()))
self.__test__(u)
class Test_cython():
def test_s1_ram_on(self):
ss = 1
ram = 'on'
U, u_temp,dz,dzstep,maxerr, M1, M2, Q_large, w_tiled, tsh, dt, hf, Dop,gam_no_aeff = \
wave_setup(ram, ss, 2, N_sol=10*np.random.randn(), cython = True, u = None)
N1= dAdzmm(u_temp, M1, M2, Q_large, tsh, hf, w_tiled, gam_no_aeff)
N2 = dAdzmm_ron_s1(u_temp,np.conjugate(u_temp), M1, M2, Q_large, tsh, hf, w_tiled,gam_no_aeff)
assert_allclose(N1, N2)
def test_s0_ram_on(self):
ss = 0
ram = 'on'
U, u_temp,dz,dzstep,maxerr, M1, M2, Q_large, w_tiled, tsh, dt, hf, Dop,gam_no_aeff = \
wave_setup(ram, ss, 2, N_sol=10*np.random.randn(), cython = True, u = None)
N1= dAdzmm_ron_s0_cython(u_temp, M1, M2, Q_large, tsh, hf, w_tiled, gam_no_aeff)
N2 = dAdzmm_ron_s0(u_temp,np.conjugate(u_temp), M1, M2, Q_large, tsh, hf, w_tiled,gam_no_aeff)
assert_allclose(N1, N2)
def test_s1_ram_off(self):
ss = 1
ram = 'off'
U, u_temp,dz,dzstep,maxerr, M1, M2, Q_large, w_tiled, tsh, dt, hf, Dop,gam_no_aeff = \
wave_setup(ram, ss, 2, N_sol=10*np.random.randn(), cython = True, u = None)
N1= dAdzmm_roff_s1_cython(u_temp, M1, M2, Q_large, tsh, hf, w_tiled, gam_no_aeff)
N2 = dAdzmm_roff_s1(u_temp,np.conjugate(u_temp), M1, M2, Q_large, tsh, hf, w_tiled,gam_no_aeff)
assert_allclose(N1, N2)
def test_s0_ram_off(self):
ss = 0
ram = 'off'
U, u_temp,dz,dzstep,maxerr, M1, M2, Q_large, w_tiled, tsh, dt, hf, Dop,gam_no_aeff = \
wave_setup(ram, ss, 2, N_sol=10*np.random.randn(), cython = True, u = None)
N1= dAdzmm_roff_s0_cython(u_temp, M1, M2, Q_large, tsh, hf, w_tiled, gam_no_aeff)
N2 = dAdzmm_roff_s0(u_temp,np.conjugate(u_temp), M1, M2, Q_large, tsh, hf, w_tiled,gam_no_aeff)
assert_allclose(N1, N2)
def test_half_disp():
dz = np.random.randn()
shape1 = 2
shape2 = 2**12
u1 = np.random.randn(shape1, shape2) + 1j * np.random.randn(shape1, shape2)
u1 *= 10
Dop = np.random.randn(shape1, shape2) + 1j * np.random.randn(shape1, shape2)
u_python = np.fft.ifft(np.exp(Dop*dz/2) * np.fft.fft(u1))
u_cython = half_disp_step(u1, Dop/2, dz, shape1, shape2)
assert_allclose(np.asarray(u_cython), u_python)
def test_cython_norm():
shape1 = 2
shape2 = 2**12
A = np.random.randn(shape1, shape2) + 1j * np.random.randn(shape1, shape2)
cython_norm = np.asarray(norm(A,shape1,shape2))
python_norm = np.linalg.norm(A,2, axis = -1).max()
assert_allclose(cython_norm, python_norm)
def test_fftishit():
shape1 = 2
shape2 = 2**12
A = np.random.randn(shape1, shape2) + 1j * np.random.randn(shape1, shape2)
cython_shift = np.asarray(cyfftshift(A))
python_shift = np.fft.fftshift(A, axes = -1)
assert_allclose(cython_shift, python_shift)
def test_fft():
shape1 = 2
shape2 = 2**12
A = np.random.randn(shape1, shape2) + 1j * np.random.randn(shape1, shape2)
cython_fft = cyfft(A)
python_fft = np.fft.fft(A)
assert_allclose(cython_fft, python_fft)
def test_ifft():
shape1 = 2
shape2 = 2**12
A = np.random.randn(shape1, shape2) + 1j * np.random.randn(shape1, shape2)
cython_fft = cyifft(A)
python_fft = np.fft.ifft(A)
assert_allclose(cython_fft, python_fft)
class Test_CK_operators:
shape1 = 2
shape2 = 2**12
u1 = np.random.randn(shape1, shape2) + 1j * np.random.randn(shape1, shape2)
A1 = np.random.randn(shape1, shape2) + 1j * np.random.randn(shape1, shape2)
A2 = np.asarray(A2_temp(u1, A1, shape1, shape2))
A3 = np.asarray(A3_temp(u1, A1, A2, shape1,shape2))
A4 = np.asarray(A4_temp(u1, A1, A2, A3, shape1,shape2))
A5 = np.asarray(A5_temp(u1, A1, A2, A3, A4, shape1,shape2))
A6 = np.asarray(A6_temp(u1, A1, A2, A3, A4, A5, shape1,shape2))
A = np.asarray(A_temp(u1, A1, A3, A4, A6, shape1,shape2))
Afourth = np.asarray(Afourth_temp(u1, A1, A3, A4, A5, A6, A, shape1,shape2))
def test_A2(self):
A2_python = self.u1 + (1./5)*self.A1
assert_allclose(self.A2, A2_python)
def test_A3(self):
A3_python = self.u1 + (3./40)*self.A1 + (9./40)*self.A2
assert_allclose(self.A3, A3_python)
def test_A4(self):
A4_python = self.u1 + (3./10)*self.A1 - (9./10)*self.A2 + (6./5)*self.A3
assert_allclose(self.A4, A4_python)
def test_A5(self):
A5_python = self.u1 - (11./54)*self.A1 + (5./2)*self.A2 - (70./27)*self.A3 + (35./27)*self.A4
assert_allclose(self.A5, A5_python)
def test_A6(self):
A6_python = self.u1 + (1631./55296)*self.A1 + (175./512)*self.A2 + (575./13824)*self.A3 +\
(44275./110592)*self.A4 + (253./4096)*self.A5
assert_allclose(self.A6, A6_python)
def test_A(self):
A_python = self.u1 + (37./378)*self.A1 + (250./621)*self.A3 + (125./594) * \
self.A4 + (512./1771)*self.A6
assert_allclose(self.A, A_python)
def test_Afourth(self):
Afourth_python = self.u1 + (2825./27648)*self.A1 + (18575./48384)*self.A3 + (13525./55296) * \
self.A4 + (277./14336)*self.A5 + (1./4)*self.A6
Afourth_python = self.A - Afourth_python
assert_allclose(self.Afourth, Afourth_python)<file_sep>/profiler.sh
#!/bin/bash
echo 'starting...'
rm -r output*
rm -r *__*
source activate intel
export MKL_NUM_THREADS=1
cd src/cython_files
rm -rf build *so cython_integrand.c *html
cython -a cython_integrand.pyx
python setup.py build_ext --inplace
cd ../..
kernprof -l -v src/oscillator.py single 2 1 1
rm main_oscillator.py.lprof<file_sep>/src/src/integrand_and_rk.py
import numpy as np
from scipy.constants import pi
from six.moves import builtins
from numpy.fft import fftshift
from scipy.fftpack import fft, ifft
try:
from cython_files.cython_integrand import *
except ModuleNotFoundError:
print('Warning, cython was not able to complile')
pass
import sys
assert_allclose = np.testing.assert_allclose
import numba
complex128 = numba.complex128
vectorize = numba.vectorize
autojit, jit = numba.autojit, numba.jit
cfunc = numba.cfunc
generated_jit = numba.generated_jit
guvectorize = numba.guvectorize
# Pass through the @profile decorator if line profiler (kernprof) is not in use
# Thanks Paul!
try:
builtins.profile
except AttributeError:
def profile(func):
return func
from time import time
import pickle
trgt = 'cpu'
#trgt = 'parallel'
#trgt = 'cuda'
#@jit(nogil = True)
def dAdzmm_roff_s0(u0,u0_conj, M1, M2, Q, tsh, hf, w_tiled,gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = uabs(u0,u0_conj,M2)
N = nonlin_kerr(M1, Q, u0, M3)
N *= gam_no_aeff
return N
#@jit(nogil = True)
def dAdzmm_roff_s1(u0,u0_conj, M1, M2, Q, tsh, hf, w_tiled,gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = uabs(u0,u0_conj,M2)
N = nonlin_kerr(M1, Q, u0, M3)
N = gam_no_aeff * (N + tsh*ifft(w_tiled * fft(N)))
return N
def dAdzmm_ron_s0(u0,u0_conj, M1, M2, Q, tsh, hf, w_tiled, gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = uabs(u0,u0_conj,M2)
M4 = fftshift(ifft(fft(M3)*hf), axes = -1) # creates matrix M4
N = nonlin_ram(M1, Q, u0, M3, M4)
N *= gam_no_aeff
return N
def dAdzmm_ron_s1(u0,u0_conj, M1, M2, Q, tsh, hf, w_tiled,gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = uabs(u0,u0_conj,M2)
M4 = fftshift(ifft(multi(fft(M3),hf)), axes = -1) # creates matrix M4
N = nonlin_ram(M1, Q, u0, M3, M4)
N = gam_no_aeff * (N + tsh*ifft(multi(w_tiled,fft(N))))
return N
@jit(nopython=True,nogil = True)
def multi(a,b):
return a * b
@guvectorize(['void(complex128[:,:],complex128[:,:], int64[:,:], complex128[:,:])'],\
'(n,m),(n,m),(o,l)->(l,m)',target = trgt)
def uabs(u0,u0_conj,M2,M3):
for ii in range(M2.shape[1]):
M3[ii,:] = u0[M2[0,ii],:]*u0_conj[M2[1,ii],:]
@guvectorize(['void(int64[:,:], complex128[:,:], complex128[:,:],\
complex128[:,:], complex128[:,:], complex128[:,:])'],\
'(w,a),(i,a),(m,n),(l,n),(l,n)->(m,n)',target = trgt)
def nonlin_ram(M1, Q, u0, M3, M4, N):
N[:,:] = 0
for ii in range(M1.shape[1]):
N[M1[0,ii],:] += u0[M1[1,ii],:]*( Q[1,ii] \
*M3[M1[4,ii],:] + \
Q[0,ii]*M4[M1[4,ii],:])
@guvectorize(['void(int64[:,:], complex128[:,:], complex128[:,:],\
complex128[:,:], complex128[:,:])'],\
'(w,a),(i,a),(m,n),(l,n)->(m,n)',target = trgt)
def nonlin_kerr(M1, Q, u0, M3, N):
N[:,:] = 0
for ii in range(M1.shape[1]):
N[M1[0,ii],:] += (Q[1,ii]) \
*u0[M1[1,ii],:]*M3[M1[4,ii],:]
@vectorize(['complex128(float64,float64,complex128,\
float64,complex128,float64)'], target=trgt)
def self_step(n2, lamda, N, tsh, temp, rp):
return -1j*n2*2*rp/lamda*(N + tsh*temp)
class Integrand(object):
def __init__(self,ram, ss, cython = True, timing = False):
if cython:
if ss == 0 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s0_cython
elif ss == 0 and ram == 'on':
self.dAdzmm = dAdzmm_ron_s0_cython
elif ss == 1 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s1_cython
else:
self.dAdzmm = dAdzmm
else:
if ss == 0 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s0
elif ss == 0 and ram == 'on':
self.dAdzmm = dAdzmm_ron_s0
elif ss == 1 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s1
else:
self.dAdzmm = dAdzmm_ron_s1
if timing:
self.dAdzmm = self.timer
def timer(self,u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff):
"""
Times the functions of python, cython etc.
"""
dt1, dt2, dt3, dt4, dt5, dt6, dt7, dt8 = [], [], [], [],\
[], [], [], []
NN = 100
for i in range(NN):
'------No ram, no ss--------'
t = time()
N1 = dAdzmm_roff_s0_cython(u0, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt1.append(time() - t)
t = time()
N2 = dAdzmm_roff_s0(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt2.append(time() - t)
assert_allclose(N1, N2)
'------ ram, no ss--------'
t = time()
N1 = dAdzmm_ron_s0_cython(u0, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt3.append(time() - t)
t = time()
N2 = dAdzmm_ron_s0(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt4.append(time() - t)
assert_allclose(N1, N2)
'------ no ram, ss--------'
t = time()
N1 = dAdzmm_roff_s1_cython(u0, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt5.append(time() - t)
t = time()
N2 = dAdzmm_roff_s1(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt6.append(time() - t)
assert_allclose(N1, N2)
'------ ram, ss--------'
t = time()
N1 = dAdzmm(u0, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt7.append(time() - t)
t = time()
N2 = dAdzmm_ron_s1(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt8.append(time() - t)
assert_allclose(N1, N2)
print('cython_ram(off)_s0: {} +/- {}'.format(np.average(dt1),np.std(dt1)))
print('python_ram(off)_s0: {} +/- {}'.format(np.average(dt2),np.std(dt2)))
print('Cython is {} times faster'.format(np.average(dt2)/np.average(dt1)))
print('--------------------------------------------------------')
print('cython_ram(on)_s0: {} +/- {}'.format(np.average(dt3),np.std(dt3)))
print('python_ram(on)_s0: {} +/- {}'.format(np.average(dt4),np.std(dt4)))
print('Cython is {} times faster'.format(np.average(dt4)/np.average(dt3)))
print('--------------------------------------------------------')
print('cython_ram(off)_s1: {} +/- {}'.format(np.average(dt5),np.std(dt5)))
print('python_ram(off)_s1: {} +/- {}'.format(np.average(dt6),np.std(dt6)))
print('Cython is {} times faster'.format(np.average(dt6)/np.average(dt5)))
print('--------------------------------------------------------')
print('cython_ram(on)_s1: {} +/- {}'.format(np.average(dt7),np.std(dt7)))
print('python_ram(on)_s1: {} +/- {}'.format(np.average(dt8),np.std(dt8)))
print('Cython is {} times faster'.format(np.average(dt8)/np.average(dt7)))
print('--------------------------------------------------------')
sys.exit()
return N
<file_sep>/src/coupler.py
import numpy as np
from scipy.constants import c, pi
import matplotlib.pyplot as plt
from scipy.special import jv, kv
import time
from scipy.optimize import brenth
from scipy.integrate import simps
import sys
import os
import h5py
def jv_(n, z):
return 0.5 * (jv(n-1, z) - jv(n+1, z))
def kv_(n, z):
return -0.5 * (kv(n-1, z) + kv(n+1, z))
class Eigensolver(object):
def __init__(self, lmin, lmax, N):
self.l_vec = np.linspace(lmin, lmax, N)
self._A_ = {'sio2': [0.6965325, 0.0660932**2],
'ge': [0.7083925, 0.0853842**2]}
self._B_ = {'sio2': [0.4083099, 0.1181101**2],
'ge': [0.4203993, 0.1024839**2]}
self._C_ = {'sio2': [0.8968766, 9.896160**2],
'ge': [0.8663412, 9.896175**2]}
def V_func(self, r):
self.V_vec = r * (2 * pi / self.l_vec) * \
(self.ncore**2 - self.nclad**2)**0.5
def indexes(self, l, r):
per_core, per_clad = 'ge', 'sio2'
self.A = [self._A_[str(per_core)], self._A_[str(per_clad)]]
self.B = [self._B_[str(per_core)], self._B_[str(per_clad)]]
self.C = [self._C_[str(per_core)], self._C_[str(per_clad)]]
return self.sellmeier(l)
def initialise_fibre(self, r):
self.ncore, self.nclad = self.indexes(self.l_vec, r)
self.r = r
self.V_func(r)
print('Maximum V number in space is {}'.format(np.max(self.V_vec)))
def sellmeier(self, l):
l = (l*1e6)**2
n = []
for a, b, c in zip(self.A, self.B, self.C):
n.append(
(1 + l*(a[0]/(l - a[1]) + b[0] /
(l - b[1]) + c[0]/(l - c[1])))**0.5)
return n
def equation_01(self, u, i):
w = self.w_equation(u, i)
return jv(0, u) / (u * jv(1, u)) - kv(0, w) / (w * kv(1, w))
def equation_11(self, u, i):
w = self.w_equation(u, i)
return jv(1, u) / (u * jv(0, u)) + kv(1, w) / (w * kv(0, w))
def w_equation(self, u, i):
return (self.V_vec[i]**2 - u**2)**0.5
def solve_01(self, i):
return self.solve_equation(self.equation_01, i)
def solve_11(self, i):
return self.solve_equation(self.equation_11, i)
def solve_equation(self, equation, i):
margin = 1e-15
m = margin
s = []
count = 8
N_points = 2**count
found_all = 2
while found_all < 5:
nm = len(s)
u_vec = np.linspace(margin, self.V_vec[i] - margin, N_points)
eq = equation(u_vec, i)
s = np.where(np.sign(eq[:-1]) != np.sign(eq[1:]))[0] + 1
count += 1
N_points = 2**count
if nm == len(s):
found_all += 1
u_sol, w_sol = np.zeros(len(s)), np.zeros(len(s))
for iss, ss in enumerate(s):
Rr = brenth(equation, u_vec[ss-1], u_vec[ss],
args=(i), full_output=True)
u_sol[iss] = Rr[0]
w_sol[iss] = self.w_equation(Rr[0], i)
if len(s) != 0:
return u_sol, w_sol, self.neff(u_sol, w_sol, i)
else:
print('-No solutions found for some inputs-')
print(' V = ', self.V_vec[i])
print(' R = ', self.r)
print(' l = ', self.l_vec[i])
print('---------------------------')
u = np.linspace(1e-6, self.V_vec[i] - 1e-6, 2048)
e = equation(u, i)
plt.plot(np.abs(u), e)
plt.xlim(u.min(), u.max())
plt.ylim(-10, 10)
plt.show()
sys.exit(1)
def neff(self, u, w, i):
return (((self.ncore[i] / u)**2 +
(self.nclad[i]/w)**2) / (1/u**2 + 1/w**2))**0.5
def integrate(x, y, E):
"""
Integrates twice using Simpsons rule from scipy
to allow 2D integration.
"""
return simps(simps(E, y), x)
class Modes(object):
def __init__(self, a, u_vec, w_vec, neff_vec, lam_vec, grid_points, n):
self.N_points = grid_points
self.a = a
self.set_coordinates(a)
self.u_vec = u_vec
self.w_vec = w_vec
self.k_vec = 2 * pi / lam_vec
self.beta_vec = neff_vec * self.k_vec
self.n = n
def wave_indexing(self, i):
self.u = self.u_vec[0, i]
self.w = self.w_vec[0, i]
self.k = self.k_vec[i]
self.beta = self.beta_vec[0, i]
self.s = self.n * (1/self.u**2 + 1/self.w**2) /\
(jv_(self.n, self.u)/(self.u*jv(self.n, self.u))
+ kv_(self.n, self.w)/(self.w*kv(self.n, self.w)))
def set_coordinates(self, a):
self.x, self.y = [np.linspace(-3*a, 3*a, self.N_points)
for i in range(2)]
self.X, self.Y = np.meshgrid(self.x, self.y)
self.R = ((self.X)**2 + (self.Y)**2)**0.5
self.T = np.arctan(self.Y/self.X)
return None
def E_r(self, r, theta):
r0_ind = np.where(r <= self.a)
r1_ind = np.where(r > self.a)
temp = np.zeros(r.shape, dtype=np.complex128)
r0, r1 = r[r0_ind], r[r1_ind]
temp[r0_ind] = -1j * self.beta*self.a / \
self.u*(0.5*(1 - self.s) * jv(self.n - 1, self.u * r0 / self.a)
- 0.5*(1 + self.s)*jv(self.n + 1, self.u * r0 / self.a))
temp[r1_ind] = -1j * self.beta*self.a*jv(self.n, self.u)\
/ (self.w*kv(self.n, self.w)) \
* (0.5*(1 - self.s) * kv(self.n - 1, self.w * r1 / self.a)
+ 0.5*(1 + self.s)*kv(self.n+1, self.w * r1 / self.a))
return temp*np.cos(self.n*theta) # , temp*np.cos(self.n*theta+pi/2)
def E_theta(self, r, theta):
r0_ind = np.where(r <= self.a)
r1_ind = np.where(r > self.a)
temp = np.zeros(r.shape, dtype=np.complex128)
r0, r1 = r[r0_ind], r[r1_ind]
temp[r0_ind] = 1j * self.beta*self.a / \
self.u*(0.5*(1 - self.s) * jv(self.n - 1, self.u * r0 / self.a)
+ 0.5*(1 + self.s)*jv(self.n+1, self.u * r0 / self.a))
temp[r1_ind] = 1j * self.beta*self.a * \
jv(self.n, self.u)/(self.w*kv(self.n, self.w)) \
* (0.5*(1 - self.s) * kv(self.n - 1, self.w * r1 / self.a)
- 0.5*(1 + self.s)*kv(self.n+1, self.w * r1 / self.a))
return temp*np.sin(self.n*theta)
def E_zeta(self, r, theta):
r0_ind = np.where(r <= self.a)
r1_ind = np.where(r > self.a)
temp = np.zeros(r.shape, dtype=np.complex128)
r0, r1 = r[r0_ind], r[r1_ind]
temp[r0_ind] = jv(self.n, self.u*r0/self.a)
temp[r1_ind] = jv(self.n, self.u) * \
kv(self.n, self.w*r1/self.a)/kv(self.n, self.w)
return temp*np.cos(self.n*theta)
def E_carte(self):
Er = self.E_r(self.R, self.T)
Et = self.E_theta(self.R, self.T)
Ex, Ey, Ez = [], [], []
Ex = Er * np.cos(self.T) - Et * np.sin(self.T)
Ey = Er * np.sin(self.T) + Et * np.cos(self.T)
Ez = self.E_zeta(self.R, self.T)
return Ex, Ey, Ez
def E_abs2(self):
Ex, Ey, Ez = self.E_carte()
return np.abs(Ex)**2 + np.abs(Ey)**2
class Coupling_coeff(Modes):
def __init__(self, a, N_points, ncore, nclad, l_vec, neff):
self.a = a
self.N_points = N_points
self.ncore = ncore
self.nclad = nclad
self.Deltan = ncore - nclad
self.l_vec = l_vec
self.f_vec = c / l_vec
self.set_coordinates(self.a)
self.neff = neff
def fibre_ref(self, d, keep=None):
"""
Creates the refractive index of the fibre if d = -1 or
creates the couplers seperated at a distance of d.
"""
R1 = ((self.X - (self.a + d/2))**2 + (self.Y)**2)**0.5
R2 = ((self.X + (self.a + d/2))**2 + (self.Y)**2)**0.5
if keep == 'left':
rin = np.where(R2 <= self.a)
elif keep == 'right':
rin = np.where(R1 <= self.a)
else:
rin = np.where(np.logical_or(R1 <= self.a, R2 <= self.a))
n0 = np.ones([len(self.l_vec), self.N_points, self.N_points])
n0 = (self.nclad[:, np.newaxis].T*n0.T).T
temp = np.zeros([self.N_points, self.N_points])
for i in range(n0.shape[0]):
temp[rin] = self.Deltan[i]
n0[i, :, :] += temp[:, :]
return n0
def initialise_integrand_vectors(self, d, Eabs2):
self.int1_vec = Eabs2
self.int2_vec = (self.fibre_ref(d)**2 -
self.fibre_ref(d, 'right')**2) \
* Eabs2
return None
def integrals(self):
return integrate(self.x, self.y, self.int2_vec) / \
integrate(self.x, self.y, self.int1_vec)
class Coupling_coefficients(object):
def __init__(self, lmin, lmax, N, a, N_points):
self.lmin = lmin
self.lmax = lmax
self.N = N # number of frequency grid
self.a = a # radius of the two fibres considered
self.N_points = N_points # grid of the mode functions [X, Y]
def fibre_calculate(self):
u, w = self.get_eigenvalues()
self.get_mode_functions(u, w)
return None
def get_eigenvalues(self):
"""
Calculates the eigenvalues of the fibres considered.
"""
e = Eigensolver(self.lmin, self.lmax, self.N)
e.initialise_fibre(self.a)
u_01, w_01, neff01 = [np.zeros([1, self.N]) for i in range(3)]
u_11, w_11, neff11 = [np.zeros([2, self.N]) for i in range(3)]
for i in range(self.N):
u_01[0, i], w_01[0, i], neff01[0, i] = e.solve_01(i)
u_11[:, i], w_11[:, i], neff11[:, i] = e.solve_11(i)
self.e = e
self.neff = neff01, neff11
return (u_01, u_11), (w_01, w_11)
def get_mode_functions(self, u, w):
u_01, u_11 = u
w_01, w_11 = w
neff01, neff11 = self.neff
Eabs01, Eabs11 = [
np.zeros([self.N, self.N_points, self.N_points]) for i in range(2)]
m01 = Modes(self.a, u_01, w_01, neff01, self.e.l_vec, self.N_points, 1)
m11 = Modes(self.a, u_11, w_11, neff11, self.e.l_vec, self.N_points, 0)
for i in range(self.N):
m01.wave_indexing(i)
m11.wave_indexing(i)
Eabs01[i, :, :] = m01.E_abs2()
Eabs11[i, :, :] = m11.E_abs2()
self.Eabs = Eabs01, Eabs11
return None
def create_coupling_coeff(self, d):
neff01, neff11 = self.neff
Eabs01, Eabs11 = self.Eabs
k01, k11 = [np.zeros(self.N) for i in range(2)]
couple01 = Coupling_coeff(
self.a, self.N_points, self.e.ncore,
self.e.nclad, self.e.l_vec, neff01[0, :])
couple11 = Coupling_coeff(self.a, self.N_points, self.e.ncore,
self.e.nclad, self.e.l_vec, neff11[0, :])
couple01.initialise_integrand_vectors(d, Eabs01)
couple11.initialise_integrand_vectors(d, Eabs11)
k01 = couple01.f_vec * (pi / (neff01[0, :] * c)) * couple01.integrals()
k11 = couple11.f_vec * (pi / (neff11[0, :] * c)) * couple11.integrals()
return k01, k11, couple01, couple11
def calculate_coupling_coeff(lmin, lmax, a, N_points, N_l, d_vec):
couple_obj = Coupling_coefficients(lmin, lmax, N_l, a, N_points)
couple_obj.fibre_calculate()
k01_1, k11_1, couple01_1, couple11_1 = couple_obj.create_coupling_coeff(
d_vec[0])
k01_2, k11_2, couple01_2, couple11_2 = couple_obj.create_coupling_coeff(
d_vec[1])
D = {'k01_1': k01_1, 'k11_1': k11_1, 'k01_2': k01_2,
'k11_2': k11_2, 'f_meas': couple11_1.f_vec}
save_coupling_coeff(**D)
return k01_1, k11_1, couple01_1, couple11_1, \
k01_2, k11_2, couple01_2, couple11_2
def save_coupling_coeff(filename = 'coupling_coeff', filepath='loading_data/', **variables):
full_file = filepath + filename + '.hdf5'
if os.path.isfile(full_file):
os.system('rm '+full_file)
with h5py.File(full_file, 'a') as f:
for i in (variables):
f.create_dataset(str(i), data=variables[i])
return None
def main():
lmin = 1540e-9
lmax = 1560e-9
N_l = 20
a = 5e-6
N_points = 1024
d_vec = [1.1e-6, 1.95e-6]
k01_1, k11_1, couple01_1, couple11_1, \
k01_2, k11_2, couple01_2, couple11_2 = \
calculate_coupling_coeff(lmin, lmax, a, N_points, N_l, d_vec)
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
axes[0, 0].plot(couple01_1.l_vec*1e9, k01_1, 'o-', label='LP01')
axes[0, 0].plot(couple01_1.l_vec*1e9, k11_1, 'o-', label='LP11')
axes[1, 0].plot(couple01_1.l_vec*1e9, k11_1/k01_1, 'o-', label='K11/K01')
axes[0, 1].plot(couple01_1.l_vec*1e9, k01_2, 'o-', label='LP01')
axes[0, 1].plot(couple01_1.l_vec*1e9, k11_2, 'o-', label='LP11')
axes[1, 1].plot(couple01_1.l_vec*1e9, k11_2/k01_2, 'o-', label='K11/K01')
axes[0, 0].set_title('WDM1')
axes[0, 1].set_title('WDM2')
axes[0, 0].set_ylabel(r'$\kappa$')
axes[1, 0].set_ylabel(r'$\kappa$')
axes[1, 0].set_xlabel(r'$\lambda (\mu m)$')
axes[1, 1].set_xlabel(r'$\lambda (\mu m)$')
plt.show()
n1_WDM1 = couple01_1.fibre_ref(d_vec[0], 'right')
n0_WDM1 = couple01_1.fibre_ref(d_vec[0])
n1_WDM2 = couple01_1.fibre_ref(d_vec[0], 'right')
n0_WDM2 = couple01_1.fibre_ref(d_vec[0])
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
axes[0, 0].contourf(1e6*couple01_1.X, 1e6*couple01_1.Y, n0_WDM1[0, :, :])
axes[1, 0].contourf(1e6*couple01_1.X, 1e6*couple01_1.Y, n1_WDM1[0, :, :])
axes[0, 1].contourf(1e6*couple01_1.X, 1e6*couple01_1.Y, n0_WDM2[0, :, :])
axes[1, 1].contourf(1e6*couple01_1.X, 1e6*couple01_1.Y, n1_WDM2[0, :, :])
axes[0, 0].set_title('WDM1')
axes[0, 1].set_title('WDM2')
axes[0, 0].set_ylabel(r'$y( \mu m)$')
axes[1, 0].set_ylabel(r'$y( \mu m)$')
axes[1, 0].set_xlabel(r'$x( \mu m)$')
axes[1, 1].set_xlabel(r'$x( \mu m)$')
plt.show()
#n1 = couple.coupled_index(1e-6)
#plt.contourf(1e6*couple.X, 1e6*couple.Y, n1[0, :, :])
# plt.colorbar()
# plt.show()
#xc = np.linspace(-a, a, 1024)
#yc = np.sqrt(-xc**2+a**2)
# fig=plt.figure(1)
#plt.contourf(m01.X, m01.Y,np.abs(mm[0])**2)
#plt.plot(xc, yc, 'black', linewidth=2.0)
#plt.plot(xc, -yc, 'black', linewidth=2.0)
# plt.show()
# fig=plt.figure(1)
#plt.contourf(m11.X, m11.Y,np.abs(mm[0])**2)
#plt.plot(xc, yc, 'black', linewidth=2.0)
#plt.plot(xc, -yc, 'black', linewidth=2.0)
# plt.show()
return None
if __name__ == '__main__':
main()
<file_sep>/src/functions.py
# -*- coding: utf-8 -*-
import sys
import os
try:
from cython_files.cython_integrand import *
except ModuleNotFoundError:
print('Warning, cython was not able to complile')
pass
from numpy.fft import fftshift
from scipy.fftpack import fft, ifft
import numpy as np
from scipy.constants import pi, c
from scipy.io import loadmat
from scipy.interpolate import InterpolatedUnivariateSpline
from scipy.integrate import simps
from math import factorial
from integrand_and_rk import *
from data_plotters_animators import *
import cmath
from time import time
from scipy.fftpack import fft, ifft
from scipy.fftpack import ifftshift
phasor = np.vectorize(cmath.polar)
from functools import wraps
from scipy import interpolate
# Pass through the @profile decorator if
#line profiler (kernprof) is not in use
# Thanks Paul!!
try:
builtins.profile
except AttributeError:
def profile(func):
return func
def arguments_determine(j):
"""
Makes sence of the arguments that are passed through from sys.agrv.
Is used to fix the mpi4py extra that is given. Takes in the possition
FROM THE END of the sys.argv inputs that you require (-1 would be the rounds
for the oscillator).
"""
A = []
a = np.copy(sys.argv)
for i in a[::-1]:
try:
A.append(int(i))
except ValueError:
continue
return A[j]
def unpack_args(func):
if 'mpi' in sys.argv:
@wraps(func)
def wrapper(args):
return func(**args)
return wrapper
else:
return func
def my_arange(a, b, dr, decimals=6):
res = [a]
k = 1
while res[-1] < b:
tmp = round(a + k*dr, decimals)
if tmp > b:
break
res.append(tmp)
k += 1
return np.asarray(res)
def dbm2w(dBm):
"""This function converts a power given in dBm to a power given in W.
Inputs::
dBm(float): power in units of dBm
Returns::
Power in units of W (float)
"""
return 1e-3*10**((dBm)/10.)
def w2dbm(W, floor=-100):
"""This function converts a power given in W to a power given in dBm.
Inputs::
W(float): power in units of W
Returns::
Power in units of dBm(float)
"""
if type(W) != np.ndarray:
if W > 0:
return 10. * np.log10(W) + 30
elif W == 0:
return floor
else:
print(W)
raise(ZeroDivisionError)
a = 10. * (np.ma.log10(W)).filled(floor/10-3) + 30
return a
class raman_object(object):
def __init__(self, a, b=None):
self.on = a
self.how = b
self.hf = None
def raman_load(self, t, dt, M2):
if self.on == 'on':
if self.how == 'analytic':
print(self.how)
t11 = 12.2e-3 # [ps]
t2 = 32e-3 # [ps]
# analytical response
htan = (t11**2 + t2**2)/(t11*t2**2) * \
np.exp(-t/t2*(t >= 0))*np.sin(t/t11)*(t >= 0)
# Fourier transform of the analytic nonlinear response
self.hf = fft(htan)
elif self.how == 'load':
# loads the measured response (Stolen et al. JOSAB 1989)
mat = loadmat('loading_data/silicaRaman.mat')
ht = mat['ht']
t1 = mat['t1']
htmeas_f = InterpolatedUnivariateSpline(t1*1e-3, ht)
htmeas = htmeas_f(t)
htmeas *= (t > 0)*(t < 1) # only measured between +/- 1 ps)
htmeas /= (dt*np.sum(htmeas)) # normalised
# Fourier transform of the measured nonlinear response
self.hf = fft(htmeas)
self.hf = np.tile(self.hf, (len(M2[1, :]), 1))
else:
self.hf = None
return self.hf
def consolidate(max_rounds, int_fwm,master_index, index, filename = 'data_large'):
"""
Loads the HDF5 data and consolidates them for storage size
reduction after the oscillations are done.
"""
layer_0 = '0/0'
filepath = 'output{}/output{}/data/'.format(master_index, index)
file_read = filepath + filename
file_save = filepath + filename+'_conc'
# Input data, small, no need to cons
D = read_variables(file_read, '0/0')
save_variables(file_save, 'input', **D)
U_cons = np.zeros([2,max_rounds, int_fwm.nt], dtype = np.float64)
# Reading of all the oscillating spectra and sending them to a 3D array
unfortmated_string = '{}/{}/U'
with h5py.File(file_read+'.hdf5', 'r') as f:
for pop in range(1,5):
for r in range(max_rounds):
U_cons[:,r,:] = f.get(unfortmated_string.format(pop,r)).value
save_variables(file_save, 'results/'+str(pop), U = U_cons)
os.system('mv '+file_save+'.hdf5 '+file_read+'.hdf5')
return None
class sim_parameters(object):
def __init__(self, n2, nm, alphadB):
self.n2 = n2
self.nm = nm
self.alphadB = alphadB
try:
temp = len(self.alphadB)
except TypeError:
self.alphadB = np.array([self.alphadB])
if self.nm > len(self.alphadB):
print('Asserting same loss per mode')
self.alphadB = np.empty(nm)
self.alphadB = np.tile(alphadB, (nm))
elif self.nm < len(self.alphadB):
print('To many losses for modes, appending!')
for i in range(nm):
self.alphadB[i] = alphadB[i]
else:
self.alphadB = alphadB
def general_options(self, maxerr, raman_object,
ss='1', ram='on', how='load'):
self.maxerr = maxerr
self.ss = ss
self.ram = ram
self.how = how
return None
def propagation_parameters(self, N, z, dz_less):
self.N = N
self.nt = 2**self.N
self.z = z
self.dz = self.z/dz_less
return None
class sim_window(object):
def __init__(self, fv, lamda, lamda_c, int_fwm):
self.fv = fv
self.lamda = lamda
self.fmed = 0.5*(fv[-1] + fv[0])*1e12 # [Hz]
self.deltaf = np.max(self.fv) - np.min(self.fv) # [THz]
self.df = self.deltaf/int_fwm.nt # [THz]
self.T = 1/self.df # Time window (period)[ps]
self.woffset = 2*pi*(self.fmed - c/lamda_c)*1e-12 # [rad/ps]
self.w0 = 2*pi*self.fmed # central angular frequency [rad/s]
self.tsh = 1/self.w0*1e12 # shock time [ps]
self.dt = self.T/int_fwm.nt # timestep (dt) [ps]
self.t = (range(int_fwm.nt)-np.ones(int_fwm.nt)*int_fwm.nt/2)*self.dt
# angular frequency vector [rad/ps]
self.w = 2*pi * np.append(
range(0, int(int_fwm.nt/2)),
range(int(-int_fwm.nt/2), 0, 1))/self.T
self.lv = 1e-3*c/self.fv
class Loss(object):
def __init__(self, int_fwm, sim_wind, amax=None, apart_div=8):
"""
Initialise the calss Loss, takes in the general parameters and
the freequenbcy window. From that it determines where the loss will become
freequency dependent. With the default value being an 8th of the difference
of max and min.
Note: From w-fopo onwards we introduce loss per mode which means we look at
a higher dim array.
"""
self.alpha = int_fwm.alphadB/4.343
if amax is None:
self.amax = self.alpha
else:
self.amax = amax/4.343
self.flims_large = (np.min(sim_wind.fv), np.max(sim_wind.fv))
try:
temp = len(apart_div)
self.begin = apart_div[0]
self.end = apart_div[1]
except TypeError:
self.apart = np.abs(self.flims_large[1] - self.flims_large[0])
self.apart /= apart_div
self.begin = self.flims_large[0] + self.apart
self.end = self.flims_large[1] - self.apart
def atten_func_full(self, fv):
aten = np.zeros([len(self.alpha), len(fv)])
a_s = ((self.amax - self.alpha) / (self.flims_large[0] - self.begin),
(self.amax - self.alpha) / (self.flims_large[1] - self.end))
b_s = (-a_s[0] * self.begin, -a_s[1] * self.end)
for i, f in enumerate(fv):
if f <= self.begin:
aten[:, i] = a_s[0][:] * f + b_s[0][:]
elif f >= self.end:
aten[:, i] = a_s[1][:] * f + b_s[1][:]
else:
aten[:, i] = 0
for i in range(len(self.alpha)):
aten[i, :] += self.alpha[i]
return aten
def plot(self, fv):
fig = plt.figure()
y = self.atten_func_full(fv)
for l, i in enumerate(y):
plt.plot(fv, i, label='mode '+str(l))
plt.xlabel("Frequency (Thz)")
plt.ylabel("Attenuation (cm -1 )")
plt.legend()
plt.savefig(
"loss_function_fibre.png", bbox_inches='tight')
plt.close(fig)
class WDM(object):
def __init__(self, l1, l2, fv, fopa=False, with_resp = 'LP01'):
"""
This class represents a 2x2 WDM coupler. The minimum and maximums are
given and then the object represents the class with WDM_pass the calculation
done.
"""
self.l1 = l1 # High part of port 1
self.l2 = l2 # Low wavelength of port 1
self.f1 = 1e9 * c / self.l1 # High part of port 1
self.f2 = 1e9 * c / self.l2 # Low wavelength of port 1
self.fv = fv*1e12
self.with_resp = with_resp
self.get_req_WDM()
if fopa:
self.U_calc = self.U_calc_over
return None
def load_coupling_coeff(self,filepath='loading_data/', filename = 'coupling_coeff'):
"""
Loads previousluy calculated coupling coefficients
exported from main() in coupler.py.
"""
with h5py.File(filepath+filename+'.hdf5', 'r') as f:
D = {}
for i in f.keys():
D[str(i)] = f.get(str(i)).value
if self.with_resp == 'LP01':
k01, k11 = D['k01_1'],D['k11_1']
else:
k01, k11 = D['k01_2'],D['k11_2']
fmeas = D['f_meas']
return k01, k11, fmeas
def require_coupler_length(self,k):
return (pi/2) / abs(k(self.f1) - k(self.f2))
def get_req_WDM(self):
k01, k11, fmeas = self.load_coupling_coeff()
kinter_lp01 = interpolate.interp1d(fmeas, k01, kind = 'cubic')
kinter_lp11 = interpolate.interp1d(fmeas, k11, kind = 'cubic')
if self.with_resp == 'LP01':
coupling_distance = self.require_coupler_length(kinter_lp01)
else:
coupling_distance = self.require_coupler_length(kinter_lp11)
self.A = self.set_SMR(coupling_distance, kinter_lp01,kinter_lp11)
return None
def set_SMR(self, z, kinter_lp01, kinter_lp11):
"""
Returns the scattering matrix. in form
[(port1-3, port 1-4), (port2-3, port 2-4), nm, nt]
"""
A = np.empty([2,2,2,len(self.fv)], dtype = np.complex128)
for i,kinter in enumerate((kinter_lp01, kinter_lp11)):
gv = kinter(self.fv) * z - kinter(self.f2)*z
A[:,:,i,:] = np.array([[np.sin(gv), 1j * np.cos(gv)],
[1j * np.cos(gv), np.sin(gv)]])
return np.asarray(A)
def U_calc_over(self, U_in):
return U_in
def U_calc(self, U_in):
"""
Uses the SMR
the outputed amplitude
"""
Uout = (self.A[0, 0] * U_in[0] + self.A[0, 1] * U_in[1],)
Uout += (self.A[1, 0] * U_in[0] + self.A[1, 1] * U_in[1],)
return Uout
def pass_through(self, U_in, sim_wind):
"""
Passes the amplitudes through the object. returns the u, U and Uabs
in a form of a tuple of (port1,port2)
"""
U_out = self.U_calc(U_in)
u_out = ()
for i, UU in enumerate(U_out):
u_out += (ifft(fftshift(UU, axes=-1)),)
return ((u_out[0], U_out[0]), (u_out[1], U_out[1]))
def plot(self, filename=False):
fig, ax = plt.subplots(2,1, sharex = True, figsize = (10,8))
ax[0].plot(1e9*c/self.fv, np.abs(self.A[0,0, 0,:])**2,'o-', label="%0.2f" %
(self.l1) + ' nm port')
ax[0].plot(1e9*c/self.fv, np.abs(self.A[1,0, 0,:])**2, 'x-',label="%0.1f" %
(self.l2) + ' nm port')
ax[1].plot(1e9*c/self.fv, np.abs(self.A[0,0, 1,:])**2,'o-', label="%0.2f" %
(self.l1) + ' nm port')
ax[1].plot(1e9*c/self.fv, np.abs(self.A[1,0, 1,:])**2,'x-', label="%0.1f" %
(self.l2) + ' nm port')
ax[0].plot([self.l2, self.l2], [0, 1])
ax[0].plot([self.l1, self.l1], [0, 1])
ax[1].plot([self.l2, self.l2], [0, 1])
ax[1].plot([self.l1, self.l1], [0, 1])
ax[0].set_title('LP01')
ax[1].set_title('LP11')
ax[1].set_xlabel(r'$\lambda (nm)$')
ax[0].set_ylabel('Power Ratio')
ax[1].set_ylabel('Power Ratio')
ax[0].legend(loc='upper center', bbox_to_anchor=(0.5, 1.35), ncol=2)
if filename:
plt.savefig(filename+'.png')
else:
plt.show()
plt.close(fig)
return None
class Perc_WDM(WDM):
def __init__(self, wave_vec, perc_vec, fv, fopa=False):
"""
Wave_vec and perc_vec are the waves and percentage of transmitance
of those waves from port 1 to 3. The order of the waves is from left
to right in the usual wavelength domain.
"""
self.fv = fv*1e12
fmed = 0.5 * (fv[0] + fv[-1])
self.wave_vec_idx = wave_vec
self.perc_vec = [i * 0.01 for i in perc_vec]
self.get_req_WDM()
self.l1, self.l2 = [1e-3*c/fmed for i in range(2)]
if fopa:
self.U_calc = self.U_calc_over
return None
def get_req_WDM(self):
k1 = np.zeros([2,len(self.fv)])
k2 = np.ones(k1.shape)
for i, j in zip(self.wave_vec_idx,self.perc_vec):
k1[:,i] = j
k2[:,i] -= j
k1 = k1**0.5
k2 = k2**0.5
self.A = np.array([[k1, 1j *k2], [1j *k2, k1]])
return None
def plot(self, filename=False):
fig, ax = plt.subplots(2,1, sharex = True, figsize = (10,8))
ax[0].plot(1e9*c/self.fv, np.abs(self.A[0,0, 0,:])**2,'o-', label="%0.2f" %
(self.l1) + ' nm port')
ax[0].plot(1e9*c/self.fv, np.abs(self.A[1,0, 0,:])**2, 'x-',label="%0.1f" %
(self.l2) + ' nm port')
ax[1].plot(1e9*c/self.fv, np.abs(self.A[0,0, 1,:])**2,'o-', label="%0.2f" %
(self.l1) + ' nm port')
ax[1].plot(1e9*c/self.fv, np.abs(self.A[1,0, 1,:])**2,'x-', label="%0.1f" %
(self.l2) + ' nm port')
ax[0].set_title('LP01')
ax[1].set_title('LP11')
ax[1].set_xlabel(r'$\lambda (nm)$')
ax[0].set_ylabel('Power Ratio')
ax[1].set_ylabel('Power Ratio')
ax[0].legend(loc='upper center', bbox_to_anchor=(0.5, 1.35), ncol=2)
if filename:
plt.savefig(filename+'.png')
else:
plt.show()
plt.close(fig)
return None
class Bandpass_WDM(Perc_WDM):
def __init__(self, wave_vec, perc_vec, fv, fopa=False):
"""
Wave_vec and perc_vec are the waves and percentage of transmitance
of those waves from port 1 to 3. The order of the waves is from left
to right in the usual wavelength domain.
"""
self.fv = fv*1e12
fmed = 0.5 * (fv[0] + fv[-1])
self.wave_vec_idx = wave_vec
self.perc_vec = [i * 0.01 for i in perc_vec]
self.get_req_WDM()
self.l1, self.l2 = [1e-3*c/fmed for i in range(2)]
if fopa:
self.U_calc = self.U_calc_over
return None
def get_req_WDM(self):
k1 = np.empty([2,len(self.fv)])
k2 = np.empty(k1.shape)
point_of_sep = self.wave_vec_idx[1] - 1
#point of step between the signal and pump
k1[0,:] = self.perc_vec[1] # LP01 percentage
k1[0,:point_of_sep] = self.perc_vec[2]
k1[1,:] = self.perc_vec[4] # second pump
k2[:,:] = 1 - k1[:,:]
k1 = k1**0.5
k2 = k2**0.5
self.A = np.array([[k1, 1j *k2], [1j *k2, k1]])
return None
def create_file_structure(kk=''):
"""
Is set to create and destroy the filestructure needed
to run the program so that the files are not needed in the repo
"""
folders_large = ('output_dump',
'output_final', 'output'+str(kk))
folders_large += (folders_large[-1] + '/output',)
folders_large += (folders_large[-1] + '/data',)
folders_large += (folders_large[-2] + '/figures',)
outs = folders_large[-1]
folders_figures = ('/frequency', '/time', '/wavelength')
for i in folders_figures:
folders_figures += (i+'/portA', i+'/portB')
for i in folders_figures:
folders_large += (outs + i,)
folders_large += (outs+'/WDMs',)
for i in folders_large:
if not os.path.isdir(i):
os.system('mkdir ' + i)
return None
class Splicer(WDM):
def __init__(self, fopa=False, loss=1):
self.loss = loss
self.c1 = 10**(-0.1*self.loss/2.)
self.c2 = (1 - 10**(-0.1*self.loss))**0.5
if fopa:
self.U_calc = self.U_calc_over
def U_calc_over(self, U_in):
return U_in
def U_calc(self, U_in):
"""
Operates like a beam splitter that
reduces the optical power by the loss given (in dB).
"""
U_out1 = U_in[0] * self.c1 + 1j * U_in[1] * self.c2
U_out2 = 1j * U_in[0] * self.c2 + U_in[1] * self.c1
return U_out1, U_out2
class Maintain_noise_floor(object):
def pass_through(u, noisef):
U = fftshift(fft(u), axis=-1)
U = U + U - noise_f
u = ifft(fftshift(U, axis=-1))
return u
def norm_const(u, sim_wind):
t = sim_wind.t
fv = sim_wind.fv
U_temp = fftshift(fft(u), axes=-1)
first_int = simps(np.abs(U_temp)**2, fv)
second_int = simps(np.abs(u)**2, t)
return (first_int/second_int)**0.5
class Noise(object):
def __init__(self, int_fwm, sim_wind):
self.pquant = np.sum(
1.054e-34*(sim_wind.w*1e12 + sim_wind.w0)/(sim_wind.T*1e-12))
self.pquant = (self.pquant/2)**0.5
self.pquant_f = np.mean(
np.abs(self.noise_func_freq(int_fwm, sim_wind))**2)
return None
def noise_func(self, int_fwm):
seed = np.random.seed(int(time()*np.random.rand()))
noise = self.pquant * (np.random.randn(int_fwm.nm, int_fwm.nt)
+ 1j*np.random.randn(int_fwm.nm, int_fwm.nt))
return noise
def noise_func_freq(self, int_fwm, sim_wind):
self.noise = self.noise_func(int_fwm)
noise_freq = fftshift(fft(self.noise), axes=-1)
return noise_freq
def fv_creator(lamp1,lamp2, lams, int_fwm):
"""
Creates the freequency grid of the
simmualtion and returns it. The signal
input is approximated as close as posible to
the asked value because of the grid.
"""
nt_between_pumps = 2**(int_fwm.N - 4)
fp1, fp2, fs = [1e-3 * c /i for i in (lamp1, lamp2, lams)]
fv1 = np.linspace(fp2, fp1, nt_between_pumps)
df = abs(fv1[1] - fv1[0])
fv0 = [fv1[0] - df]
fv2 = [fv1[-1] + df]
rest = int(2**int_fwm.N - nt_between_pumps)
for i in range(1,rest//2):
fv0.append(fv0[i - 1] - df)
fv2.append(fv2[i - 1] + df)
fv0 = fv0[::-1]
fv = np.concatenate((fv0, fv1, fv2))
check_ft_grid(fv, df)
D_freq = assemble_parameters(fv,fp1, fp2,fs)
return fv, D_freq
def assemble_parameters(fv,fp1, fp2,fs):
"""
Assembles frequency dictionary
which holds frequency indexes and values
of input and expected output.
"""
F = fs - fp1
fmi = fp1 - F
fpc = fp2 - F
fbs = fp2 + F
fmin = fv.min()
fmax = fv.max()
try:
assert np.all( [ i < fmax and i >fmin for i in (fpc, fbs, fmi)])
except AssertionError:
sys.exit('Your grid is too small and you end up with waves off the window.')
where = [np.argmin(np.abs(fv - i)) for i in (fmi, fp1, fs, fpc, fp2, fbs)]
D_freq = {'where':where}
return D_freq
def energy_conservation(entot):
if not(np.allclose(entot, entot[0])):
fig = plt.figure()
plt.plot(entot)
plt.grid()
plt.xlabel("nplots(snapshots)", fontsize=18)
plt.ylabel("Total energy", fontsize=18)
plt.close()
sys.exit("energy is not conserved")
return 0
def check_ft_grid(fv, diff):
"""Grid check for fft optimisation"""
if np.log2(np.shape(fv)[0]) == int(np.log2(np.shape(fv)[0])):
nt = np.shape(fv)[0]
else:
print("fix the grid for optimization \
of the fft's, grid:" + str(np.shape(fv)[0]))
sys.exit(1)
lvio = []
for i in range(len(fv)-1):
lvio.append(fv[i+1] - fv[i])
grid_error = np.abs(np.asanyarray(lvio)[:]) - np.abs(diff)
if not(np.allclose(grid_error, 0, rtol=0, atol=1e-12)):
print(np.max(grid_error))
sys.exit("your grid is not uniform")
assert len(np.unique(fv)) == len(fv)
return 0
class create_destroy(object):
"""
creates and destroys temp folder that is used for computation. Both methods needs to be run
before you initiate a new variable
"""
def __init__(self, variable, pump_wave=''):
self.variable = variable
self.pump_wave = pump_wave
return None
def cleanup_folder(self):
# for i in range(len(self.variable)):
os.system('mv output'+self.pump_wave + ' output_dump/')
return None
def prepare_folder(self):
for i in range(len(self.variable)):
os.system('cp -r output'+self.pump_wave +
'/output/ output'+self.pump_wave+'/output'+str(i))
return None
def dbeta00(lc, filepath='loading_data'):
n = 1.444
w0, w1 = np.loadtxt(os.path.join('loading_data', 'widths.dat'))[:2]
beta0 = (2*pi*n/lc)*((1-lc**2/(pi**2 * n * w0**2)) **
0.5 - (1-2*lc**2/(pi**2 * n * w0**2))**0.5)
beta1 = (2*pi*n/lc)*((1-lc**2/(pi**2 * n * w1**2)) **
0.5 - (1-2*lc**2/(pi**2 * n * w1**2))**0.5)
return beta1 - beta0
def load_disp_paramters(sim_wind,lamda_c=1.5508e-6):
"""
Returns the betas (taylor expansion coefficients) of the Telecom fibre.
"""
c_norm = c*1e-12
betap = np.zeros([2, 4])
dbeta0 = dbeta00(lamda_c)
#D = np.array([20e6, 22.8e6])
D = np.array([19.8*1e6, 21.8*1e6])
S = np.array([0.068e15, 0.063e15])
#S = np.array([0.105*1e15,0.108*1e15])
dbeta1 = -95e-3
beta2 = -D[:]*(lamda_c**2/(2*pi*c_norm)) # [ps**2/m]
beta3 = lamda_c**4*S[:]/(4*(pi*c_norm)**2) + \
lamda_c**3*D[:]/(2*(pi*c_norm)**2) # [ps**3/m]
betap[0, 2] = beta2[0]
betap[0, 3] = beta3[0]
betap[1, 0] = dbeta0
betap[1, 1] = dbeta1
betap[1, 2] = beta2[1]
betap[1, 3] = beta3[1]
return betap
def dispersion_operator(betas, int_fwm, sim_wind):
"""
Calculates the dispersion operator
Inputed are the dispersion operators at the omega0
Local include the taylor expansion to get these opeators at omegac
Returns Dispersion operator
"""
w = sim_wind.w + sim_wind.woffset
Dop = np.zeros((2, w.shape[0]), dtype=np.complex)
Dop -= fftshift(int_fwm.alpha/2, axes=-1)
Dop[0, :] -= 1j*((betas[0, 2]*(w)**2)/2. + (betas[0, 3]*(w)**3)/6.)
Dop[1, :] -= 1j*(betas[1, 0] + betas[1, 1]*(w) +
(betas[1, 2]*(w)**2)/2. + (betas[1, 3]*(w)**3)/6.)
return Dop
class Phase_modulation_infase_WDM(object):
"""
Makes sure that the signal is in phase with the oscillating signal
comiing in so we can get constructive inteference.
"""
def __init__(self, wave_vec_idx, WDM_1):
self.A = WDM_1.A[0]
self.idx = wave_vec_idx[2]
def modulate(self, U1, U2):
dphi = np.angle(U1[0, self.idx] * self.A[0,0, self.idx]) -\
np.angle(U2[0, self.idx] * self.A[1,0, self.idx])
U2[0,:] *= np.exp(1j * dphi)
return None
<file_sep>/src/src/cython_files/build_cython_intel.sh
#!/bin/bash
source activate intel
rm -rf build
if [ ! -f ./build ]; then
mkdir build
fi
source activate intel
LDSHARED="icc -shared" CC=icc python3.6 setup.py build_ext --inplace
<file_sep>/src/cython_files/profile_action.py
import pstats, cProfile
import cython_integrand
import pickle
with open('../../loading_data/profile.pickl', 'rb') as f:
D = pickle.load(f)
names = ('u0', 'u0_conj', 'M1', 'M2', 'Q', 'tsh', 'dt','hf', 'w_tiled', 'gam_no_aeff')
u1,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled, gam_no_aeff = D
cProfile.runctx("cython_integrand.dAdzmm_ron_s1_cython(u1,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled, gam_no_aeff)", globals(), locals(), "Profile.prof")
s = pstats.Stats("Profile.prof")
s.strip_dirs().sort_stats("time").print_stats()<file_sep>/README.md
# mm-fopo
[](https://travis-ci.com/Computational-Nonlinear-Optics-ORC/mm-fopo-1)
[](https://zenodo.org/badge/latestdoi/184894754)
Two mode Fibre Optical Patametric Oscillator (FOPO) project code.
Requirements:
* Linux system. Tested and developed on Ubuntu 16.04 LTS
* MKL libraries. Can be found [here](https://software.seek.intel.com/performance-libraries). Compiled version for Linux are in the repository.
* Python 3.6
Install:
* bash build_install.sh
|
05af67d7e3affbebdd555f95463bf5f19f570676
|
[
"Markdown",
"Python",
"Shell"
] | 20 |
Python
|
Computational-Nonlinear-Optics-ORC/mm-fopo-1
|
c423bd2c8766151360bd84b1e1ca367873b31304
|
0ea84e596ed583ca89478fe51a0afc56dff4efed
|
refs/heads/master
|
<repo_name>sirghiny/facial_recognition<file_sep>/prep_data.py
from itertools import combinations
from math import sqrt
from os import getcwd, listdir, system
from pickle import dump, load
from sys import exit
from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imwrite
from face_recognition import face_landmarks, face_locations
from tqdm import tqdm
def euclidean_distance(point1, point2):
"""
Calculate the euclidean distance between two points.
"""
return sqrt((((point1[0] - point2[0])**2)+((point1[1] - point2[1])**2)))
def get_face_landmarks(path):
"""
Get 72 key landmarks on faces.
Return a dictionary with landmark and coordinates of points.
"""
image = imread(path)
try:
landmarks = face_landmarks(image)[0]
except IndexError:
landmarks = {}
return landmarks
def get_face_locations(path):
"""
Given an image path, return locations of faces in the image.
"""
image = imread(path)
return face_locations(image)
def store_image_paths():
"""
Get all paths of images to be used.
Return a dictionary of each unique face and its images.
{'face': [path1, path2...]}
"""
paths = {
j: [('data/faces/' + j + '/' + k)
for k in listdir('data/faces/' + j) if k.endswith('.jpg')]
for j in tqdm(
[i for i in listdir('data/faces') if i.startswith('Face')])
}
dump(paths, open('data/paths.pkl', 'wb'))
def store_image_data():
"""
Create and store pickle of image data.
Each face has an image_url, location, missing attributes and landmarks.
{'Face': {'missing': [], 'images': [{}]}, ...}
"""
data = {}
face_paths = load(open('data/paths.pkl', 'rb'))
system('rm -rf temp && mkdir temp')
for face in tqdm(face_paths):
paths = face_paths[face]
images = []
for path in paths:
image_object = {
'image_url': '',
'location': [],
'missing': [],
'landmarks': {}
}
image_object['image_url'] = path
image = imread(path)
gray_image = cvtColor(image, COLOR_BGR2GRAY)
face_loci = get_face_locations(path)
if len(face_loci) == 0:
image_object['missing'].extend(['location', 'landmarks'])
else:
top, right, bottom, left = face_loci[0]
image_object['location'] = face_loci
face_image = image[top:bottom, left:right]
imwrite('temp/current.png', face_image)
landmarks = get_face_landmarks('temp/current.png')
if not landmarks:
image_object['missing'].append('landmarks')
else:
image_object['landmarks'].update(landmarks)
system('rm temp/current.png')
images.append(image_object)
data.update({face: images})
dump(data, open('data/image_data.pkl', 'wb'))
system('rm -rf temp')
def store_distances():
"""
Create and store a pickle of distances between landmarks.
{Face: [[()...], ...], ...}
"""
landmarks_ = sorted(
['chin', 'left_eyebrow', 'right_eyebrow', 'nose_bridge',
'nose_tip', 'left_eye', 'right_eye', 'top_lip', 'bottom_lip'])
combinations_ = sorted(list(combinations(landmarks_, 2)))
data = load(open('data/image_data.pkl', 'rb'))
distances = {}
for face in tqdm(data):
faces = data[face]
face_distances = []
for i in faces:
if i['missing']:
pass
else:
i_landmarks = i['landmarks']
vectors = [
tuple([i_landmarks[pair[0]], i_landmarks[pair[1]]])
for pair in combinations_]
i_distances = []
for vector_pairs in vectors:
for j in vector_pairs[0]:
for k in vector_pairs[1]:
i_distances.append(euclidean_distance(j, k))
i_ratios = [j/i_distances[0] for j in i_distances]
face_distances.append(i_ratios)
distances.update({face: face_distances})
dump(distances, open('data/distances.pkl', 'wb'))
def store_face_locations():
"""
Store location of faces on an image.
{'Face': [{'image_url': '', 'location': ()}, ...], ...}
"""
data = load(open('data/image_data.pkl', 'rb'))
faces_locations = {}
for face in tqdm(data):
faces = data[face]
face_locations = []
for i in faces:
if i['location']:
face_locations.append(
{'image_url': i['image_url'],
'location': i['location']})
else:
pass
faces_locations.update({face: face_locations})
dump(faces_locations, open('data/face_locations.pkl', 'wb'))
def store_paths_with_landmarks():
"""
Get the paths with landmark data.
"""
data = load(open('data/image_data.pkl', 'rb'))
paths = {}
for face in tqdm(data):
faces = data[face]
face_paths = []
for i in faces:
if not i['landmarks']:
pass
face_paths.append(i['image_url'])
if not face_paths:
pass
paths.update({face: face_paths})
dump(paths, open('data/paths_with_landmarks.pkl', 'wb'))
def store_cropped_faces():
"""
Crop out and store faces.
"""
system('mkdir data/cropped')
paths = load(open('data/face_locations.pkl', 'rb'))
for face in tqdm(paths):
face_data = paths[face]
i_count = 0
system('mkdir data/cropped/' + face)
for i in face_data:
image = imread(i['image_url'])
top, right, bottom, left = i['location'][0]
face_image = image[top:bottom, left:right]
new_path = 'data/cropped/' + face + '/' + str(i_count) + '.jpg'
i_count = i_count + 1
imwrite(new_path, face_image)
return True
print('\nStoring image paths.')
store_image_paths()
print('\nStoring image data.')
store_image_data()
print('\nStoring distances.')
store_distances()
print('\nStoring face locations.')
store_face_locations()
print('\nStoring paths with landmarks.')
store_paths_with_landmarks()
print('\nStoring cropped faces.')
store_cropped_faces()
<file_sep>/.flake8
[flake8]
exclude = .git,
__pycache__,
archive/,
venv,
|
b2a7b5b11f184737e488a149fc8029eaa9abe92b
|
[
"Python",
"INI"
] | 2 |
Python
|
sirghiny/facial_recognition
|
b344c04dca9514f08d5342f1cab56b19d0e8bcda
|
b205e81299bb12db36a02177107bc43edd51e841
|
refs/heads/master
|
<file_sep>/*
Delete occurrences of an element if it occurs more than n times
Enough is enough!
Alice and Bob were on a holiday. Both of them took many pictures
of the places they've been, and now they want to show Charlie their
entire collection. However, Charlie doesn't like this sessions,
since the motive usually repeats. He isn't fond of seeing the Eiffel
tower 40 times. He tells them that he will only sit during the session
if they show the same motive at most N times. Luckily, Alice and Bob
are able to encode the motive as a number. Can you help them to remove
numbers such that their list contains each number only up to N times,
without changing the order?
Task
Given a list lst and a number N, create a new list that contains each
number of lst at most N times without reordering. For example if N = 2,
and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the
next [1,2] since this would lead to 1 and 2 being in the result 3 times,
and then take 3, which leads to [1,2,3,1,2,3].
Example
deleteNth ([1,1,1,1],2) // return [1,1]
deleteNth ([20,37,20,21],1) // return [20,37,21]
https://www.codewars.com/kata/554ca54ffa7d91b236000023/train/javascript
*/
function deleteNth(arr, n){
if (n === 0) return [];
let output = [];
let holder = {};
arr.forEach( element => {
if (!holder[element]) {
holder[element] = 1;
output.push(element);
} else {
holder[element] += 1;
if (holder[element] <= n) output.push(element);
}
})
return output;
}<file_sep>function isBalanced (str) {
// remove spaces from str
str.split(' ').join('');
// create a count for each symbol
let parenCount = 0;
let curlCount = 0;
let brackCount = 0;
// loop through str
for (let i = 0; i < str.length; i++) {
// if open and closing don't match up
// return false
if (str[i] === ')' && str[i-1] === '{') {
return false;
}
if (str[i] === ')' && str[i-1] === '[') {
return false;
}
if (str[i] === '}' && str[i-1] === '(') {
return false;
}
if (str[i] === '}' && str[i-1] === '[') {
return false;
}
if (str[i] === ']' && str[i-1] === '(') {
return false;
}
if (str[i] === ']' && str[i-1] === '{') {
return false;
}
// if element is '('
if (str[i] === '(') {
// add to parenCount
parenCount++;
}
// if element is '('
if (str[i] === ')') {
// subtract from parenCount
parenCount--;
}
// if element is '{'
if (str[i] === '{') {
// add one to curlCount
curlCount++;
}
// if element is '}'
if (str[i] === '}') {
// subtract from curlCount
curlCount--;
}
// if element is '['
if (str[i] === '[') {
// add one to brackCount
brackCount++;
}
// if element is ']'
if (str[i] === ']') {
// subtract one from brack count
brackCount--;
}
// if any count is less than 0
if (parenCount < 0 || curlCount < 0 || brackCount < 0) {
// return false
return false;
}
}
// if count is greater than 0
if (parenCount > 0 || curlCount > 0 || brackCount > 0) {
// return false
return false;
}
// return true
return true;
};
console.log(`Test1: expected false and got ${isBalanced(')(')}`);
console.log(`Test2: expected false and got ${isBalanced('()(()()()())((()(()()))')}`);
console.log(`Test3: expected true and got ${isBalanced('[[[{{{((()))}}}]]]')}`);
console.log(`Test4: expected true and got ${isBalanced('(((10 ) ()) ((?)(:)))')}`);
console.log(`Test5: expected true and got ${isBalanced('(x + y) - (4)')}`);
console.log(`Test6: expected false and got ${isBalanced('({)}')}`);
console.log(`Test7: expected false and got ${isBalanced('[]]')}`);
console.log(`Test8: expected false and got ${isBalanced('(50)(')}`);
console.log(`Test9: expected true and got ${isBalanced('{}')}`);
console.log(`Test10: expected false and got ${isBalanced('{')}`);
console.log(`Test11: expected false and got ${isBalanced('[]}{()')}`);
console.log(`Test12: expected false and got ${isBalanced(')))()(((')}`);
console.log(`Test13: expected false and got ${isBalanced('}')}`);
console.log(`Test14: expected true and got ${isBalanced('[{()}]')}`);
console.log(`Test15: expected false and got ${isBalanced('[{]}')}`);
console.log(`Test16: expected true and got ${isBalanced('[{}]')}`);<file_sep>/*
The Vowel Code
Step 1: Create a function called encode() to replace all the lowercase
vowels in a given string with numbers according to the following pattern:
a -> 1
e -> 2
i -> 3
o -> 4
u -> 5
For example, encode("hello") would return "h2ll4". There is no need
to worry about uppercase vowels in this kata.
Step 2: Now create a function called decode() to turn the numbers
back into vowels according to the same pattern shown above.
For example, decode("h3 th2r2") would return "hi there".
For the sake of simplicity, you can assume that any numbers passed
into the function will correspond to vowels.
https://www.codewars.com/kata/53697be005f803751e0015aa
*/
const helper = (string, vowels) => {
let output = "";
for (let i = 0; i < string.length; i++) {
let char = string[i];
if (vowels[char]) {
output += vowels[char];
} else {
output += char;
}
}
return output;
}
function encode(string) {
const vowels = {
a: 1, e: 2, i: 3, o: 4, u: 5
}
return helper(string, vowels);
}
function decode(string) {
const vowels = {
1: 'a', 2: 'e', 3: 'i', 4: 'o', 5: 'u'
}
return helper(string, vowels);
}<file_sep>/*
Valid Parentheses
Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
https://www.codewars.com/kata/valid-parentheses/train/javascript
*/
function validParentheses (parens) {
// create an open paren variable
const open = '(';
// create a close paren variable
const closed = ')';
// create a count
let count = 0;
// loop through parens
for (let i = 0; i < parens.length; i++) {
// if open
if (parens[i] === open) {
// add to count
count++;
}
// if closed
if (parens[i] === closed) {
// remove from count
count--;
}
// if count less than 0
if (count < 0) {
// return false
return false;
}
}
// if count is equal to 0
if (count === 0) {
// return true
return true;
// else
} else {
// return false
return false;
}
}<file_sep>/*
Given a string of words, you need to find the highest scoring word.
Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
You need to return the highest scoring word as a string.
If two words score the same, return the word that appears earliest in the original string.
All letters will be lowercase and all inputs will be valid.
https://www.codewars.com/kata/57eb8fcdf670e99d9b000272
*/
function high(x){
x = x.concat(' ');
const alphabet = {
a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7,
h: 8, i: 9, j: 10, k: 11, l: 12, m: 13, n: 14,
o: 15, p: 16, q: 17, r: 18, s: 19, t: 20, u: 21,
v: 22, w: 23, x: 24, y: 25, z: 26
}
let words = [];
let count = 0;
let singleWord = '';
for (let i = 0; i < x.length; i++) {
if (x[i] === ' ') {
words.push([singleWord, count]);
count = 0;
singleWord = '';
} else {
count += alphabet[x[i]];
singleWord = singleWord.concat(x[i]);
}
}
let result = ['', 0];
words.map(word => {
if (word[1] > result[1]) {
result = word;
}
})
return result[0];
}
<file_sep>/* Write Number in Expanded Form
You will be given a number and you will need to return it as a string in Expanded Form. For example:
expandedForm(12); // Should return '10 + 2'
expandedForm(42); // Should return '40 + 2'
expandedForm(70304); // Should return '70000 + 300 + 4'
NOTE: All numbers will be whole numbers greater than 0. */
function expandedForm(num) {
let numberString = num.toString();
let output = '';
for (let i = 0; i < numberString.length; i++) {
let realNumber = Number(numberString[i]);
let zeros = numberString.length - i;
let number = numberString[i].padEnd(zeros, 0);
if (realNumber > 0 && i > 0) {
output = output.concat(` + `);
}
if (i + 1 !== numberString.length && realNumber > 0 && numberString[i + 1] !== 0) {
output = output.concat(`${number}`);
} else if (realNumber > 0 && i + 1 == numberString.length) {
output = output.concat(number);
}
}
return output;
}
Test.assertEquals(expandedForm(12), '10 + 2');
Test.assertEquals(expandedForm(42), '40 + 2');
Test.assertEquals(expandedForm(70304), '70000 + 300 + 4');<file_sep>/**
* Create a hash table with `insert()`, `retrieve()`, and `remove()` methods.
* Be sure to handle hashing collisions correctly.
* Set your hash table up to double the storage limit as
* soon as the total number of items stored is greater than
* 3/4th of the number of slots in the storage array.
* Resize by half whenever utilization drops below 1/4.
*/
// This is a "hashing function". You don't need to worry about it, just use it
// to turn any string into an integer that is well-distributed between
// 0 and max - 1
// const getIndexBelowMaxForKey = function(str, max) {
// let hash = 0;
// for (let i = 0; i < str.length; i++) {
// hash = (hash << 5) + hash + str.charCodeAt(i);
// hash = hash & hash; // Convert to 32bit integer
// hash = Math.abs(hash);
// }
// return hash % max;
// };
// const makeHashTable = function() {
// const result = {};
// let storage = [];
// let storageLimit = 4;
// let size = 0;
// result.insert = function( ) {
// // TODO: implement `insert`
// };
// result.retrieve = function( ) {
// // TODO: implement `retrieve`
// };
// result.remove = function( ) {
// // TODO: implement `remove`
// };
// return result;
// };
var makeHashTable = function(){
var result = {};
var storage = [];
var storageLimit = 4;
var size = 0;
var resizing = false;
//***Finish This Function***//
function resize(newSize) {
// if size needs to increase
if (newSize > storageLimit) {
// double the storageLimit
storageLimit = storageLimit * 2;
} else {
// else
// decrease the storageLimit by 2
storageLimit = storageLimit / 2;
}
// loop through storage
for (var key in storage) {
// call retrieve on key and save
var val = result.retrieve(key);
// call insert on key and saved above
result.insert(key, val);
}
};
//*************************//
result.insert = function(key, value){
var index = getIndexBelowMaxForKey(key, storageLimit);
storage[index] = storage[index] || [];
var pairs = storage[index];
var pair;
var replaced = false;
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (pair[0] === key) {
pair[1] = value;
replaced = true;
}
}
if (!replaced) {
pairs.push([key, value]);
size++;
}
if(size >= storageLimit * 0.75){
// increase the size of the hash table
resize(storageLimit * 2);
}
};
result.retrieve = function(key){
var index = getIndexBelowMaxForKey(key, storageLimit);
var pairs = storage[index];
if (!pairs) { return; }
var pair;
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (pair && pair[0] === key) {
return pair[1];
}
}
};
result.remove = function(key){
var index = getIndexBelowMaxForKey(key, storageLimit);
var pairs = storage[index];
var pair;
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (pair[0] === key) {
var value = pair[1];
delete pairs[i];
size--;
if(size <= storageLimit * 0.25){
// decrease the size of the hash table
resize(storageLimit / 2);
}
return value;
}
}
};
//This next function you would never have for a hash table
//It is here merely for testing purposes. So we can check that
//you are resizing correctly
result.find = function(index){
//return the bucket at a given index
return storage[index];
};
return result;
};
// This is a "hashing function". You don't need to worry about it, just use it
// to turn any string into an integer that is well-distributed between
// 0 and max - 1
var getIndexBelowMaxForKey = function(str, max){
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = (hash<<5) + hash + str.charCodeAt(i);
hash = hash & hash; // Convert to 32bit integer
hash = Math.abs(hash);
}
return hash % max;
};
module.exports = makeHashTable<file_sep>/*
Create a function that takes in an integer array
and returns the highest product of three numbers.
Example Inputs:
-1 0 2 5 3 -4
10 10 10 10
-5 9 6 0
2 -2 4 0 -1 3
4 -2 1 -4 6 0
Outputs:
30
1000
0
24
48
*/
const threeSum = (array) => {
let sorted = array.sort();
let length = sorted.length;
let backPro = sorted[length-1] * sorted[length-2] * sorted[length-3];
let frontPro = sorted[0] * sorted[1] * sorted[length-1];
if (backPro > frontPro) return backPro;
else return frontPro;
}
const threeSum = (arr) => {
let maxProduct = 0;
for (let i=0; i<arr.length - 2; i++) {
for (let j=i+1; j<arr.length - 1; j++) {
for (let k=j+1; k<arr.length; k++) {
let product = arr[i] * arr[j] * arr[k];
if (product > maxProduct) {
maxProduct = product;
}
}
}
}
return maxProduct;
}<file_sep>/* Given a number, return a string with dash'-'marks before and after each
odd integer, but do not begin or end the string with a dash mark.
dashatize(274) -> '2-7-4'
dashatize(6815) -> '68-1-5'
*/
function dashatize(num) {
if (isNaN(num)) {
return 'NaN';
}
num = Math.abs(num);
const numString = num.toString();
let output = '';
for (let i = 0; i < numString.length; i++) {
let number = Number(numString[i]);
let oldNumber = Number(numString[i-1]);
if (oldNumber % 2 == 0 && number % 2 !== 0 && i !== numString.length) {
output = output.concat(`-`);
}
if (number % 2 !== 0 && i+1 !== numString.length) {
output = output.concat(`${numString[i]}-`);
} else {
output = output.concat(numString[i]);
}
}
return output;
};
Test.describe("Basic", function(){
Test.assertEquals(dashatize(274), "2-7-4", "Should return 2-7-4");
Test.assertEquals(dashatize(5311), "5-3-1-1", "Should return 5-3-1-1");
Test.assertEquals(dashatize(86320), "86-3-20", "Should return 86-3-20");
Test.assertEquals(dashatize(974302), "9-7-4-3-02", "Should return 9-7-4-3-02");
});
Test.describe("Weird", function(){
Test.assertEquals(dashatize(NaN), "NaN", "Should return NaN");
Test.assertEquals(dashatize(0), "0", "Should return 0");
Test.assertEquals(dashatize(-1), "1", "Should return 1");
Test.assertEquals(dashatize(-28369), "28-3-6-9", "Should return 28-3-6-9");
});<file_sep>/*
Kebabize
Modify the kebabize function so that it converts a camel case string into a kebab case.
kebabize('camelsHaveThreeHumps') // camels-have-three-humps
kebabize('camelsHave3Humps') // camels-have-humps
Notes:
the returned string should only contain lowercase letters
https://www.codewars.com/kata/57f8ff867a28db569e000c4a/train/javascript
*/
function kebabize(str) {
let output = '';
for (let i = 0; i < str.length; i++) {
if (str[i] === str[i].toLowerCase() && str[i].toLowerCase() !== str[i].toUpperCase()) {
output = output.concat(str[i]);
} else if (str[i] === str[i].toUpperCase() && str[i].toLowerCase() !== str[i].toUpperCase() && output.length !== 0) {
output = output.concat('-');
output = output.concat(str[i].toLowerCase());
} else if (str[i].toLowerCase() !== str[i].toUpperCase()) {
output = output.concat(str[i].toLowerCase());
}
}
return output;
}<file_sep>const largestProductOfThree = require('../src/largest-product-of-three')
const { expect } = require('chai')
describe('largestProductOfThree', function() {
it('should be a function', function() {
expect(largestProductOfThree).to.be.a('function')
});
it('should return an integer', function() {
var result = largestProductOfThree([1, 2, 3]);
expect(result).to.be.a('number')
});
it('should handle three positive numbers', function() {
expect(largestProductOfThree([0, 2, 3])).to.equal(0)
expect(largestProductOfThree([2, 3, 5])).to.equal(30)
expect(largestProductOfThree([7, 5, 3])).to.equal(105)
expect(largestProductOfThree([7, 5, 7])).to.equal(245)
});
it('should handle more than three positive numbers', function() {
expect(largestProductOfThree([2, 5, 3, 7])).to.equal(105)
expect(largestProductOfThree([11, 7, 5, 3, 2])).to.equal(385)
expect(largestProductOfThree([2, 13, 7, 3, 5, 11])).to.equal(1001)
expect(largestProductOfThree([2, 11, 13, 7, 13, 3, 11, 5])).to.equal(1859)
});
xit('EXTRA CREDIT: should handle negative numbers', function() {
expect(largestProductOfThree([2, 3, -11, 7, 5, -13])).to.equal(1001)
expect(largestProductOfThree([-31, 41, 34, -37, -17, 29])).to.equal(47027)
expect(largestProductOfThree([-1, -2, -3, -4, -5, -6])).to.equal(-6)
});
});<file_sep>const makeHashTable = require('../src/hash-table-resizing')
const { expect } = require('chai')
describe('makeHashTable', function() {
it('should exist', function() {
expect(makeHashTable).to.exist
});
it('should be a function', function() {
expect(makeHashTable).to.be.a('function')
});
it('should return a hash table', function() {
const hashTable = makeHashTable();
expect(hashTable).to.be.an('object')
});
it('should return different instances of hash tables each time', function() {
const hashTable1 = makeHashTable();
const hashTable2 = makeHashTable();
// `makehashTable()` should create a new hash table object instance
// everytime but it's not!
expect(hashTable1).to.not.equal(hashTable2)
});
});
describe('hashTable', function() {
describe('#insert', function() {
it('should exist as a method of hashtable instances', function() {
const hashTable = makeHashTable();
expect(hashTable).to.have.property('insert')
});
it('should take exactly two arguments. a key and a value', function() {
const hashTable = makeHashTable();
/**
A Hash Table gets its awesomeness from associating data. It wouldn't be
very useful if you just gave it data without any association.
*/
expect(hashTable.insert).to.have.length(2)
});
it('should allow keys to be reinserted with new values', function() {
const hashTable = makeHashTable();
expect(() => {
hashTable.insert('keanu reeves best movie', 'Bill & Ted\'s Excellent Adventure');
hashTable.insert('keanu reeves best movie', 'The Matrix');
}).to.not.throw()
});
});
describe('#retrieve', function() {
it('should be a method of hashTable instances', function() {
const hashTable = makeHashTable();
expect(hashTable).to.have.property('retrieve')
});
it('should be a function', function() {
const hashTable = makeHashTable();
expect(hashTable.retrieve).to.be.a('function')
});
it('should take exactly one argument', function() {
const hashTable = makeHashTable();
// the retrieve function should only take a single `key` argument
// hashTable.retrieve.length.should.equal(1);
expect(hashTable.retrieve).to.have.length(1)
});
it('should return values previously inserted', function() {
const hashTable = makeHashTable();
hashTable.insert('<NAME>\'s most well known role', '<NAME>');
const value = hashTable.retrieve('<NAME>\'s most well known role');
expect(value).to.equal('Capt<NAME>irk')
});
it('should return undefined for unknown keys', function() {
const hashTable = makeHashTable();
expect(hashTable.retrieve('echo?')).to.not.exist
});
});
describe('#insert', function() {
it('should allow values to be updated', function() {
const hashTable = makeHashTable();
hashTable.insert('Tarantino\'s best movie', '<NAME>');
hashTable.insert('Tarantino\'s best movie', 'Pulp Fiction');
const value = hashTable.retrieve('Tarantino\'s best movie');
expect(value).to.equal('Pulp Fiction')
});
});
describe('#remove', function() {
it('should exist as a method of the hashTable instance', function() {
const hashTable = makeHashTable();
expect(hashTable).to.have.property('remove')
});
it('should be a function', function() {
const hashTable = makeHashTable();
expect(hashTable.remove).to.be.a('function')
});
it('should take exactly one argument', function() {
const hashTable = makeHashTable();
// the remove function should only take a single `key` argument
// hashTable.remove.length.should.equal(1);
expect(hashTable.remove).to.have.length(1)
});
it('should allow values to be removed', function() {
const hashTable = makeHashTable();
hashTable.insert('Spielberg\'s best movie', 'Jaws');
hashTable.remove('Spielberg\'s best movie');
const value = hashTable.retrieve('Spielberg\'s best movie');
expect(value).to.not.exist;
});
});
describe('#insert', function() {
it('should handle collisions', function() {
const hashTable = makeHashTable();
expect(() => {
const n = 1000;
for (let i = 0; i < n; i++) {
hashTable.insert('userid:' + (i++), '<NAME>');
}
}).to.not.throw()
});
it('should be able to resize', function() {
// If your hashtable isn't resizing, its going to start running more
// and more slowly with a large number of inserts and retrievals.
const hashTable = makeHashTable();
const n = 10;
let id = 0;
const diffs = [];
let endTime;
let startTime;
for (let i = 0; i <= n; i++) {
startTime = new Date();
for (let j = 0; j < 1000; j++) {
hashTable.insert('userid:' + (id++), '<NAME>');
}
for (let j = 0; j < 100; j++) {
hashTable.retrieve('userid:' + Math.floor(Math.random() * i));
}
endTime = new Date();
diffs.push(endTime - startTime);
}
const sum = function(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
};
// We should expect the first iteration to take up roughly 1 / n
// of the total time. We give it some wiggle room by letting it be as
// low as a 1 / (n*2) of the total duration.
const ratio = (diffs[0] / sum(diffs));
expect(ratio).to.be.greaterThan(1 / ( n * 2 ))
});
});
});<file_sep>/*
Break camelCase
Complete the solution so that the function will break up camel casing, using a space between words.
Example
solution('camelCasing') // => should return 'camel Casing'
https://www.codewars.com/kata/5208f99aee097e6552000148/train/javascript
*/
function solution(string) {
let result = '';
for (let i = 0; i < string.length; i++) {
if (string[i] === string[i].toLowerCase()) {
result = result.concat(string[i]);
} else {
result = result.concat(` ${string[i]}`)
}
}
return result;
}
Test.assertEquals(solution('camelCasing'), 'camel Casing')<file_sep>// Write a function that takes as its input a string
// and returns an array of arrays as shown below
// sorted in descending order by frequency
// and then by ascending order by character.
// "aaabbc" => [ [ "a", 3 ], [ "b", 2 ], [ "c", 1 ] ]
// "mississippi" => [ [ "i", 4 ], [ "s", 4 ], [ "p", 2 ], [ "m", 1 ] ]
// "" => [ ]
function characterFrequency(str) {
// create a storage obj
let storage = {};
// create a result array
let result = [];
// loop through string
for (let i = 0; i < str.length; i++) {
// if object does not have letter
if (storage[str[i]]) {
// add to pair value
storage[str[i]]++
} else {
// else
// store in object with a one
storage[str[i]] = 1;
}
}
// loop through object
for (let key in storage) {
// push key pair values as tuples into result
result.push([key, storage[key]]);
}
// sort array by second index of tuple
result.sort(function(a,b) {
return b[1] - a[1];
})
// return result
return result;
}
console.log(characterFrequency('aaabbc'));
console.log(characterFrequency('mississippi'));
console.log(characterFrequency(''));<file_sep>//Find count for matching instances (amount of jewels in stones)
//If string 2 has 3 matching elements compared to string 1, count should be 3
let string1 = 'aA'
let string2 = 'aAAbbb'
let string3 = 'bZw'
let string4 = 'BbzZZwW'
function numJewelsInStones(jewels, stones) {
let count = 0;
for (let i = 0; i < stones.length; i++) {
if (jewels.includes(stones[i])) {
count++;
}
}
return count;
}
console.log(numJewelsInStones(string1, string2)); //=> 3
console.log(numJewelsInStones(string3, string4)); //=>4<file_sep>// Create a function that....
// Finds sum of string
// String letters reflects alaphabet where a=1, b=2, c=3.... z=26
function solve(string) {
let alpha = '0abcdefghijklmnopqrstuvwxyz'
let count = 0;
let result = 0;
while (count !== string.length) {
for (var i = 0; i < alpha.length; i++) {
if (string[count] === alpha[i]) {
result += alpha.indexOf(alpha[i]);
count++;
}
if (count === string.length) {
return result;
}
}
}
}
console.log(solve('zodiac')); //=> 58
console.log(solve('strength'));//=> 111
console.log(solve('chruschtschov')); //=> 167
console.log(solve('abcde')); //=> 15<file_sep>/*
Array.diff
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.
It should remove all values from list a, which are present in list b.
arrayDiff([1,2],[1]) == [2]
If a value is present in b, all of its occurrences must be removed from the other:
arrayDiff([1,2,2,2,3],[2]) == [1,3]
https://www.codewars.com/kata/523f5d21c841566fde000009/train/javascript
*/
function arrayDiff(a, b) {
const holder = {};
const results = [];
const helper = (array) => {
array.forEach((element) => {
if (array === b) {
holder[element] = 'exist';
}
if (array === a && holder[element] !== "exist") {
results.push(element);
}
})
}
helper(b);
helper(a);
return results;
}<file_sep># toy-problem.__problem_name__
## Install Node dependencies
```
npm install
```
## Run tests
```
npm test
```
Make sure that you see the tests fail, you'll passing the tests as you solve the problem
## Solve problems
* __problems_to_solve__
Run test as you are working
## When you are done
* Add, commit, and push.
* Submit your solution in **Learn**
<file_sep>/*
Highest and Lowest
In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
Example:
highAndLow("1 2 3 4 5"); // return "5 1"
highAndLow("1 2 -3 4 5"); // return "5 -3"
highAndLow("1 9 3 4 -5"); // return "9 -5"
Notes:
All numbers are valid Int32, no need to validate them.
There will always be at least one number in the input string.
Output string must be two numbers separated by a single space, and highest number is first.
https://www.codewars.com/kata/554b4ac871d6813a03000035/train/javascript
*/
function highAndLow(numbers){
let highest = Number.NEGATIVE_INFINITY;
let lowest = Infinity;
let holder = numbers.split(' ');
if (holder.length === 1) {
return `${holder[0]} ${holder[0]}`;
}
for (let i = 0; i < holder.length; i++) {
let num = parseInt(holder[i]);
if (num > highest) {
highest = num;
} else if (num < lowest) {
lowest = num;
}
}
return `${highest} ${lowest}`;
}<file_sep>/*
Sudoku Background
Sudoku is a game played on a 9x9 grid. The goal of the game is to fill all cells of the grid with digits
from 1 to 9, so that each column, each row, and each of the nine 3x3 sub-grids (also known as blocks)
contain all of the digits from 1 to 9.
(More info at: http://en.wikipedia.org/wiki/Sudoku)
Sudoku Solution Validator
Write a function validSolution/ValidateSolution/valid_solution() that accepts a 2D array representing a
Sudoku board, and returns true if it is a valid solution, or false otherwise. The cells of the sudoku
board may also contain 0's, which will represent empty cells. Boards containing one or more zeroes are
considered to be invalid solutions.
The board is always 9 cells by 9 cells, and every cell only contains integers from 0 to 9.
https://www.codewars.com/kata/529bf0e9bdf7657179000008
Examples
validSolution([
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]
]); // => true
validSolution([
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 0, 3, 4, 8],
[1, 0, 0, 3, 4, 2, 5, 6, 0],
[8, 5, 9, 7, 6, 1, 0, 2, 0],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 0, 1, 5, 3, 7, 2, 1, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 0, 0, 4, 8, 1, 1, 7, 9]
]); // => false
*/
function validSolution(board){
let answer = true;
let pointer = {};
if (board[0][0] === board[1][0] || board[0][0] === board[1][1] || board[0][0] === board[1][2]) {
return false;
}
board.map (function (element) {
let arr = [];
function helper (array, pointer) {
for (let i = 0; i < array.length; i++) {
if (!arr.includes(array[i]) && i !== pointer[array[i]]) {
arr.push(array[i])
pointer[array[i]] = i;
} else {
answer = false;
}
}
}
helper(element, pointer);
})
return answer;
}<file_sep>/*
Stop gninnipS My sdroW!
Write a function that takes in a string of one or more words, and returns the same string,
but with all five or more letter words reversed (Just like the name of this Kata). Strings
passed in will consist of only letters and spaces. Spaces will be included only when more
than one word is present.
Examples: spinWords( "Hey fellow warriors" ) => returns "Hey w<NAME>"
spinWords( "This is a test") => returns "This is a test"
spinWords( "This is another test" )=> returns "This is rehtona test"
https://www.codewars.com/kata/5264d2b162488dc400000001/train/javascript
*/
function spinWords(string){
const holder = string.split(' ');
const result = [];
holder.forEach((element) => {
if (element.length > 4) {
result.push(element.split("").reverse().join(""));
} else {
result.push(element);
}
})
return result.join(" ");
}<file_sep>/*
Persistent Bugger.
Write a function, persistence, that takes in a positive parameter
num and returns its multiplicative persistence, which is the
number of times you must multiply the digits in num until you
reach a single digit.
For example:
persistence(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) === 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) === 0 // because 4 is already a one-digit number
https://www.codewars.com/kata/55bf01e5a717a0d57e0000ec
*/
function persistence(num, result = 1) {
let string = num.toString();
let array = string.split('');
let newNum = 1;
if (array.length === 1) {
return 0;
}
for (let i = 0; i < array.length; i++) {
newNum *= array[i];
}
if (newNum >= 10) {
result++;
return persistence(newNum, result);
}
return result;
}<file_sep>// function toMilitary(time) {
// // if first index is a 0
// if (time[0] === 0) {
// // return time
// return time;
// }
// // loop through string
// for (let i = 0; i < time.length; i++) {
// // if 'a' exist,
// if (time[i] === 'a') {
// // remove am
// time[i] = '';
// time[i + 1] = '';
// // add 0 to front
// let zero = '0';
// zero.concat(time)
// }
// // if 'p' exist
// if (time[i] === 'p') {
// // add 12 to first index
// time[0] = time[0] + 12
// }
// }
// return time;
// }
// function toMilitary (time) {
// // if first index is 0
// if (time[0] === '0') {
// // return time
// return time;
// }
// // loop through time
// for (let i = 0; i < time.length; i++) {
// // if time element is equal to add
// if (time[i] === 'a' && time[0,1] < 10) {
// // add 0 to front
// let zero = '0';
// zero.concat(time);
// console.log('hey')
// }
// // if 'p' exists
// // add 12 to first index
// }
// // return time without am or pm
// return time.slice (time, time.length-2)
// }
function toMilitary (time) {
// if first index is 0
if (time[0] === '0') {
// return time
return time;
}
if (time)
let colon = ':';
let arr = time.split(':')
if (arr[0] < 10 && arr[1][2] === 'a') {
let zero = '0';
arr[0] = zero.concat(arr[0])
arr[1] = colon.concat(arr[1])
}
if (arr[0] < 12 && arr[1][2] === 'p') {
arr[0] = parseInt(arr[0] + 12);
arr[1] = colon.concat(arr[1])
}
result = arr.join('').toString()
// result = arr.toString(' ')
return result.slice (time, time.length-1)
}
console.log(`Test1 expected ${toMilitary('12:00am')} to be 00:00`);
console.log(`Test2 expected ${toMilitary('7:47pm')} to be 19:47`);
console.log(`Test3 expected ${toMilitary('12:01am')} to be 00:01`);
console.log(`Test4 expected ${toMilitary('9:15am')} to be 09:15`);
console.log(`Test5 expected ${toMilitary('1:23am')} to be 01:23`);
console.log(`Test6 expected ${toMilitary('3:00pm')} to be 15:00`);
console.log(`Test7 expected ${toMilitary('12:00pm')} to be 12:00`);
console.log(`Test8 expected ${toMilitary('04:00')} to be 04:00`);<file_sep>/*
Snail Sort
Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
For better understanding, please follow the numbers of the next array consecutively:
array = [[1,2,3],
[8,9,4],
[7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.
NOTE 2: The 0x0 (empty matrix) is represented as en empty array inside an array [[]].
https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1
*/
snail = function(array) {
var result = [];
var n=array.length;
var x=n;
var y=n;
if(n==1){
return array[0];
}
while(y>1){
for(j=0;j<y;j++){
result.push(array[0][j]);
}
array.splice(0,1);
y--;
for(j=0;j<y;j++){
result.push(array[j][y]);
array[j].splice(y);
}
x--;
for(j=x-1;j>=0;j--){
result.push(array[y-1][j]);
}
array.splice(y-1);
x--;
for(j=y-1;j>0;j--){
result.push(array[j-1][0]);
array[j-1].splice(0,1);
}
y--;
if(y==1&&x==1){
result.push(array[0][0]);
}
}
return result;
}<file_sep>const { longestRun } = require('../src/longest-run.js');
const { expect } = require('chai');
describe('longestRun', function () {
it('should exist', function () {
expect(longestRun).to.exist;
});
it('should be a function', function () {
expect(longestRun).to.be.a('function');
});
it('should return an array', function () {
expect(longestRun('abc')).to.be.an('array');
});
it('should return an array with only two elements', function () {
// the length of the result array should always have exactly two elements.
// that contain the `start` and `end` indices in the original string.
expect(longestRun('abc').length).to.equal(2);
expect(longestRun("aabbbc").length).to.equal(2);
});
it('should return an array with the `start` and `end` index', function () {
expect(longestRun("abbbcc")).to.eql([1, 3]);
expect(longestRun("aabbc")).to.eql([0, 1]);
expect(longestRun("abcd")).to.eql([0, 0]);
});
it('should work for long strings', function () {
// `repeat` returns a string with the `input` string repeated `n` times
// ie., repeat('v', 3) would return 'vvv'
var repeat = function (input, n) {
var output = '';
for (var i = 0; i < n; i++) {
output = output + input;
}
return output;
};
var aaaa = repeat('a', 342); // repeat `a` 342 times
var jjjj = repeat('j', 583); // repeat `j` 583 times
var zzzz = repeat('z', 1000); // repeat `z` 1000 times
var input = aaaa + zzzz + jjjj;
expect(longestRun(input)).to.eql([342, 1341]);
});
it('should handle the edge-case of an empty string', function () {
// watch out for edge-cases! There is no longest run of an empty string.
expect(longestRun('')).to.not.exist;
});
});
<file_sep>/*Suppose a newly-born pair of iguanas, one male, one female, are put in a large aquarium.
Iguanas are able to mate at the age of one month so that at the end of its second month a female can produce another pair of iguanas.
Suppose that our iguanas never die and that the female always produces one new pair (one male, one female) every month from the second month on.
How many pairs of iguanas will there be after `n` months?
For example, the iguana pair size for months zero through five are:
`0 1 1 2 3 5`
If `n` were 4, your function should return 3; for 5, it should return 5.
HINT: This iguana pattern is described exactly by the fibonacci sequence:
[https://en.wikipedia.org/wiki/Fibonacci_number]
Write a function that accepts a number `n` and returns the number of iguana pairs after `n` months.
DO NOT use a recursive solution to this problem. Your solution must run in linear time.
Write tests to make sure your code is working as expected.*/
function fibonacci (n) {
// create an empty array
let array = [];
// loop through array to length of n
for (let i = 0; i <= n; i++) {
// if array length is equal or greater than 2
if (array.length >= 2) {
// add current to last
// push to array
array.push(array[i-1] + array[i-2]);
} else {
// else
// push i to array
array.push(i);
}
}
// return last number in array
return array.pop();
}
console.log(fibonacci(2)) //=> 1
console.log(fibonacci(4)) //=> 3
console.log(fibonacci(5)) //=>5
console.log(fibonacci(12)) //=>144
console.log(fibonacci(14)) //=>377
<file_sep>/**MERGE SORT*
Implement a function that sorts an array of numbers using the “mergesort” algorithm.
Mergesort uses a divide-and-conquer strategy. It begins by treating the input list of
length N as a set of N “sublists” of length 1, which are considered to be sorted. Adjacent
sublists are then “merged” into sorted sublists of length 2, which are merged into sorted
sublists of length 4, and so on, until only a single sorted list remains. (Note, if N is odd,
an extra sublist of length 1 will be left
after the first merge, and so on.)
This can be implemented using either a recursive (“top-down”) or an iterative (“bottom-up”)
approach.
*Illustration of an iterative approach:*
```1.Initial step: Input array is split into "sorted" sublists
[4,7,4,3,9,1,2] -> [[4],[7],[4],[3],[9],[1],[2]]
2.Merge step: Adjacent sublists are merged into sorted sublists
[[4],[7],[4],[3],[9],[1],[2]] -> [[4,7],[3,4],[1,9],[2]]
3.Repeat merge step:
[[4,7],[3,4],[1,9],[2]] -> [[3,4,4,7], [1,2,9]]
4.Repeat merge step:
[[3,4,4,7], [1,2,9]] -> [[1,2,3,4,4,7,9]]
5.Done! Return the sorted array:
[1,2,3,4,4,7,9]```
*Illustration of a recursive approach*
```1.Split the input array in half
[4, 7, 4, 3, 9, 1, 2] -> [4, 7, 4], [3, 9, 1, 2
2.Both sides are sorted recursively:
[4, 7, 4] -> [4, 4, 7]
[3, 9, 1, 2] -> [1, 2, 3, 9]
3.Both halves are merged:
[4, 7, 4], [3, 9, 1, 2] -> [1, 2, 3, 4, 4, 7, 9]```
Step 2 might seem a bit mystical - how do we sort both sides? The
simple answer is that we use mergesort! After all, mergesort sorts
arrays, right? We can test this on [4, 7, 4] by just following the
steps above but imagining that [4, 7, 4] is the whole array, which
is what happens when you call mergesort on it.
```1.Split the input array in half
[4, 7, 4] -> [4], [7, 4]
2.Both sides are sorted recursively:
[4] -> [4]
[7, 4] -> [4, 7]
3.Both halves are merged:
[4], [4, 7] -> [4, 4, 7]```
I cheated again by going directly from [7, 4] to [4, 7], but that’s
really just:
```1.Split the input array in half
[7, 4] -> [7], [4]
2.Both sides are sorted recursively:
[7] -> [7]
[4] -> [4]
3.Both halves are merged:
[7], [4] -> [4, 7]```
As you can see, all the work actually gets done in step 3, the merge
step. Everything else is just splitting and recursing.
Mergesort is an optimized sorting algorithm which is a common choice to implement sort
methods in standard libraries as an alternative to quicksort or heapsort. (For example,
Firefox’s Array.sort method uses a tuned mergesort; the WebKit engine used by Chrome and
Safari uses quicksort for numeric arrays, and mergesort for arrays of strings.)
DO NOT USE Array.sort()!*/
// create a function called mergeSort that takes in an array
function mergeSort (array) {
// create output array
let holder = [];
// create helper function that takes an array
function helper (inputArray) {
// loop through array
for (let i = 0; i < inputArray.length; i++) {
// push each element into array as its own array
holder.push([inputArray[i]])
}
array = [];
}
// if holder is equal to array
if (output === array) {
// call helper func on array
helper (array);
} else {
// reset output as empty array
output = [];
// loop through holder array
for (let i = 0; i < holder.length; i + 2) {
// compare element at i with element at i+1
// place lesser number in front as a pair and push into output array
if (holder[i] > holder[i + 1]) {
output.push([holder[i + 1], holder[i]])
} else if (holder[i] < holder[i + 1]) {
output.push([holder[i], holder[i + 1]])
}
}
}
// return output
}
const test1 = mergeSort([8,7,3,6,9,2,4,5,1]);
console.log(`Should sort a short array of integers: expected [1,2,3,4,5,6,7,8,9] and got ${JSON.stringify(test1)}`);
const test2 = mergeSort([8,7,3,3,9,2,4,5,1]);
console.log(`Should handle duplicates: expected [1,2,3,3,4,5,7,8,9] and got ${JSON.stringify(test2)}`);
const test3 = mergeSort([9,8,7,6,5,4,3,2,1]);
console.log(`Should handle reversely sorted array: expected [1,2,3,4,5,6,7,8,9] and got ${JSON.stringify(test3)}`);
const test4 = mergeSort([]);
console.log(`Should handle empty array: expected [] and got ${JSON.stringify(test4)}`);
const test5 = mergeSort([1]);
console.log(`Should handle array with single element: expected [1] and got ${JSON.stringify(test5)}`);
function createLargeArray() {
var input = [];
var sorted;
var n = 100000;
for (var i = 0; i < n; i++) {
var number = Math.floor(Math.random() * n);
input.push(number);
}
return input;
}
const arr = createLargeArray();
const test7 = arr.slice().sort((a, b) => a - b);
const test6 = mergeSort(arr);
console.log(`Should handle large array: ${JSON.stringify(test6) === JSON.stringify(test7)}`);<file_sep>/*Postfix notation (also known as Reverse Polish notation) is an alternative way of
representing algebra expressions. For example, take the following expression:
2 + 5 * 8
This "normal" notation that we see everyday is called infix notation. Infix notation
places its math operators in-between the numbers.
Infix notation also has order of operations. The previous example will be interpreted
as 2 + (5 * 8), because multiplication comes before addition. This makes it difficult
to write a program to parse infix expressions.
In contrast, postfix notation is much easier to parse, albeit it looks weird at first.
Postfix notation places math operators after the numbers. For example, the previous
infix example can be re-written in postfix notation like this:
2 5 8 * +
This expression should be read from left to right, one number / operator at a time.
In doing so, you must keep a stack of numbers that wait to be operated on.
I attached a photo of an example that walks through this
Examples to test:
"1 5 8 * +" // expected: 41
"1 5 8 + *" // expected: 13
"100 2 / 25 +" // expected: 75*/
// create a function called calculate that takes in a string
function calculate (string) {
let array = string.split(' ')
// console.log(string)
// create stack array
let stack = [];
// create number equal to 0
let numberOne = 0;
let numberTwo = 0;
// loop through string
for (let i = 0; i < array.length; i++) {
if (array[i] === '*') {
numberOne = stack.pop();
numberTwo = stack.pop();
numberOne = numberOne * numberTwo
stack.push(numberOne);
// array.splice(i, 1)
// i -= 1;
}
if (array[i] === '+') {
numberOne = stack.pop();
numberTwo = stack.pop();
numberOne = numberOne + numberTwo
stack.push(numberOne);
}
if (array[i] === '-') {
numberOne = stack.pop();
numberTwo = stack.pop();
if (numberOne > numberTwo) {
numberOne = numberOne - numberTwo;
} else {
numberOne = numberTwo - numberTwo;
}
stack.push(numberOne);
}
if (array[i] === '/') {
numberOne = stack.pop();
numberTwo = stack.pop();
if (numberOne > numberTwo) {
stack.push(numberOne/numberTwo)
} else {
stack.push(numberTwo/numberOne)
}
// stack.push(numberOne);
}
// if element is a number
if (typeof (array[i] * 1) == 'number' && array[i] !== '*' && array[i] !== '+' && array[i] !== '-' && array[i] !== '/') {
// push into stack
stack.push(array[i] * 1);
// console.log(stack)
}
}
// return the element from the stack as a number
return stack.pop();
}
// console.log(`Test1: for input "1 5 8 * +", expected 41 and got ${calculate('1 5 8 * +')}`);
// console.log(`Test2: for input "1 5 8 + *", expected 13 and got ${calculate('1 5 8 + *')}`);
console.log(`Test3: for input "100 2 / 25 +", expected 75 and got ${calculate('100 2 / 25 +')}`);
// console.log(`Test4: for input ".5 .5 +", expected 1 and got ${calculate('.5 .5 +')}`);<file_sep>/*
Highest Scoring Word
Given a string of words, you need to find the highest scoring word.
Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
You need to return the highest scoring word as a string.
If two words score the same, return the word that appears earliest in the original string.
All letters will be lowercase and all inputs will be valid.
https://www.codewars.com/kata/57eb8fcdf670e99d9b000272/train/javascript
*/
function high(x){
const alphabet = {
a:1, b:2, c:3, d:4, e:5, f:6, g:7, h:8, i:9, j: 10, k: 11, l: 12,
m: 13, n: 14, o: 15, p: 16, q: 17, r: 18, s: 19, t: 20, u: 21,
v: 22, w: 23, x: 24, y: 25, z: 26
}
let holder = {};
let wordHolder = '';
const helper = (word) => {
let count = 0;
for (let j = 0; j < word.length; j++) {
count += alphabet[word[j]];
}
holder[word] = count;
}
for (let i = 0; i < x.length; i++) {
if (x[i] !== ' ') {
wordHolder = wordHolder.concat(x[i]);
}
if (x[i] === ' ' || i + 1 === x.length) {
helper(wordHolder);
wordHolder = '';
}
}
let output = ['', 0];
for (let key in holder) {
if (holder[key] > output[1]) {
output = [key, holder[key]];
}
}
return output[0];
}
// Faster and cleaner solution below.
function high(x){
const alphabet = {
a:1, b:2, c:3, d:4, e:5, f:6, g:7, h:8, i:9, j: 10, k: 11, l: 12,
m: 13, n: 14, o: 15, p: 16, q: 17, r: 18, s: 19, t: 20, u: 21,
v: 22, w: 23, x: 24, y: 25, z: 26
}
let wordHolder = '';
let countHolder = 0;
let result = ['', 0];
for (let i = 0; i < x.length; i++) {
if (x[i] !== ' ') {
wordHolder = wordHolder.concat(x[i]);
countHolder += alphabet[x[i]];
}
if (x[i] === ' ' || i + 1 === x.length) {
if (countHolder > result[1]) {
result = [wordHolder, countHolder];
}
countHolder = 0;
wordHolder = '';
}
}
return result[0];
}
Test.describe("Example tests",_=>{
Test.assertEquals(high('man i need a taxi up to ubud'), 'taxi');
Test.assertEquals(high('what time are we climbing up the volcano'), 'volcano');
Test.assertEquals(high('take me to semynak'), 'semynak');
});<file_sep>
/* Write a function that finds the largest possible product of any three numbers
* from an array.
*
* Example:
* largestProductOfThree([2, 1, 3, 7]) === 42
*
* Extra credit: Make your function handle negative numbers.
*/
const largestProductOfThree = (array) => {
// if (array.length === 3) {
// return array.reduce((a, b) => a * b, 1);
// }
let newArray = [];
// loop through array
for (let i = 0; i < array.length; i++) {
newArray.push([array[i], i]);
}
// create a holder array
let holder = [];
let call = 0;
// create helper function that takes in an array
function helper (helperArray) {
// loop through array
for (let i = 0; i < helperArray.length; i++) {
// create truthy check
let truth = false;
// if holder length is less than 3
if (holder.length < 3) {
// push element into array
holder.push(helperArray[i]);
} else if (call > 0) {
// if element is greater than holder[0] and truth is false
if (helperArray[i][0] > holder[0][0] && truth === false && !holder.includes(helperArray[i][1])) {
// replace the new element
holder[0] = helperArray[i];
// set truth to true
truth = true;
}
// if element is greater than holder[1] and truth is false
if (helperArray[i] > holder[1][0] && truth === false && !holder.includes(helperArray[i][1])) {
// replace the new element
holder[1] = helperArray[i];
// set truth to true
truth = true;
}
// if element is greater than holder[2] and truth is false
if (helperArray[i] > holder[2][0] && truth === false && !holder.includes(helperArray[i][1])) {
// replace the new element
holder[2] = helperArray[i];
// set truth to true
truth = true;
}
}
}
}
// if holder length is 0
if (holder.length < 1) {
// call helper on input array
helper(newArray);
}
call = 1;
helper(newArray);
console.log(holder);
let result = [];
for (let i = 0; i < holder.length; i++) {
result.push(holder[i][0]);
}
return result.reduce((a, b) => a * b, 1);
};
// console.log(largestProductOfThree([0, 2, 3]))
// console.log(largestProductOfThree([2, 3, 5]))
// console.log(largestProductOfThree([7, 5, 3]))
// console.log(largestProductOfThree([7, 5, 7]))
module.exports = largestProductOfThree<file_sep>/*
Duplicate Encoder
The goal of this exercise is to convert a string to a new string where each character
in the new string is "(" if that character appears only once in the original string,
or ")" if that character appears more than once in the original string. Ignore
capitalization when determining if a character is a duplicate.
Examples
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
https://www.codewars.com/kata/54b42f9314d9229fd6000d9c/train/javascript
*/
function duplicateEncode(string){
// make string lower case
string = string.toLowerCase();
let array = [];
for (let i = 0; i < string.length; i++) {
for (let j = 0; j < string.length;)
}
}<file_sep>/* Create a function that takes in a number and
outputs a string that represents that number's
simplified fraction.
Whole numbers & mixed fractions should be returned
as improper fractions.
examples:
input: 0.5, 3, 2.5, 2.75
output: "1/2", "3/1", "5/2", "11/4" */
/* Proper to inproper: https://www.calculatorsoup.com/calculators/math/mixed-number-to-improper-fraction.php */
/* Greatest Common Diviser: https://en.wikipedia.org/wiki/Greatest_common_divisor */
function fractionConverter (number) {
// convert number to a string
let stringNumber = number.toString();
// set truty value to keep track of numbers before or after decimal
let beforeDecimal = true;
let result = "";
let count = 0;
// if string number does not include a decimal
if (!stringNumber.include('.')) {
// return the string with a concatted forward slash and one
return stringNumber.concat('/1');
}
// while stringNumber length is less than 4
while (stringNumber.length < 4) {
// concat a 0
stringNumber.concat('0');
}
// loop through string
// for(let i = 0; i < stringNumber.length; i++) {
// // convert number string to a proper function
// // if you hit a decimal, change truthy value to false
// if(stringNumber[i] === '.') {
// beforeDecimal = false;
// }
// // if number is before decimal
// if (beforeDecimal === true) {
// // add to result
// result.concat(stringNumber[i]);
// } else if (beforeDecimal === false && count < 1) {
// count++;
// result.concat('.', stringNumber[i])
// } else {
// result.concat(stringNumber[i]);
// }
// }
stringNumber.concat('/100');
// after all this, the string number should be something like
// 2.75/100
let whole = [];
// create top of fraction holder
let top = [];
// create bottom of fraction holder
let bottom = [];
// create truthy value
let afterDecimal = false;
// create second truthy value
let topTruthy = true;
// loop through stringNumber
for (let i = 0; i < stringNumber.length; i++) {
if (afterDecimal === false) {
whole.push(stringNumber[i]);
}
if (stringNumber[i] === '.') {
afterDecimal = true;
}
// if after decimal is true and top truthy is true
if (afterDecimal === true && topTruthy === true) {
// push element to top fraction holder
top.push(stringNumber[i]);
} else {
// else
// push to bottom fraction
bottom.push(stringNumber[i]);
}
if (stringNumber[i] === '/') {
topTruthy = false;
}
}
// in example, at this point, whole should be [2], top should be [75], and bottom should be [100]
// next we need to look at top and bottom to find the greatest common divisor
// then we can create the calculations of converting from proper to improper fraction
// calculate from example above to convert to improper fraction
}<file_sep>/*
Multiplication table
Your task, is to create NxN multiplication table, of size provided in parameter.
for example, when given size is 3:
1 2 3
2 4 6
3 6 9
for given example, the return value should be: [[1,2,3],[2,4,6],[3,6,9]]
https://www.codewars.com/kata/534d2f5b5371ecf8d2000a08/train/javascript
*/
input: 3
count = 4
holder = [];
output = [[1, 2, 3,], [2, 4, 6], [3, 6, 9]];
multiplicationTable = function(size) {
const output = [];
let count = 1;
let holder = [];
const helper = () => {
for (let i = 1; i <= size; i++) {
holder.push(i * count);
}
}
while (count <= size) {
helper();
output.push(holder);
holder = [];
count++;
}
return output;
}<file_sep>/*
Count the Smiley Faces
Description:
Given an array (arr) as an argument complete the function countSmileys
that should return the total number of smiling faces.
Rules for a smiling face:
-Each smiley face must contain a valid pair of eyes. Eyes can be marked
as : or ;
-A smiley face can have a nose but it does not have to. Valid characters
for a nose are - or ~
-Every smiling face must have a smiling mouth that should be marked
with either ) or D.
No additional characters are allowed except for those mentioned.
Valid smiley face examples:
:) :D ;-D :~)
Invalid smiley faces:
;( :> :} :]
Example cases:
countSmileys([':)', ';(', ';}', ':-D']); // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']); // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;
Note: In case of an empty array return 0. You will not be tested
with invalid input (input will always be an array). Order of the face
(eyes, nose, mouth) elements will always be the same.
https://www.codewars.com/kata/count-the-smiley-faces/javascript
*/
function countSmileys(arr) {
if (arr.length == 0) {
return 0;
}
let count = 0;
for (let i = 0; i < arr.length; i++) {
let smiley = false;
if (arr[i] === ';)' || arr[i] === ':)' || arr[i] === ';D' || arr[i] === ':D' || arr[i] === ';-)'
|| arr[i] === ':-)' || arr[i] === ';-D' || arr[i] === ':-D' || arr[i] === ';~)' || arr[i] === ':~)' ||
arr[i] === ';~D' || arr[i] === ':~D') {
smiley = true;
}
if (smiley === true) {
count++;
}
}
return count;
}<file_sep>/* Build Tower
Build Tower by the following given argument:
number of floors (integer and always greater than 0).
Tower block is represented as *
JavaScript: returns an Array;
Have fun!
for example, a tower of 3 floors looks like below
[
' * ',
' *** ',
'*****'
]
and a tower of 6 floors looks like below
[
' * ',
' *** ',
' ***** ',
' ******* ',
' ********* ',
'***********'
]
https://www.codewars.com/kata/576757b1df89ecf5bd00073b/train/javascript
*/
function towerBuilder(nFloors) {
let starCount = (nFloors * 2) - 1;
let output = [];
let holder = '';
for (let i = 0; i < starCount; i++) {
holder += '*';
}
output.push(holder);
let replaceCount = 1;
while (replaceCount < nFloors) {
holder = holder.split('');
holder[replaceCount - 1] = ' ';
holder[holder.length - replaceCount] = ' ';
holder = holder.join('');
output.unshift(holder);
replaceCount++;
}
return output;
}<file_sep>/*
The Hashtag Generator
The marketing team is spending way too much time typing in hashtags.
Let's help them with our own Hashtag Generator!
Here's the deal:
It must start with a hashtag (#).
All words must have their first letter capitalized.
If the final result is longer than 140 chars it must return false.
If the input or the result is an empty string it must return false.
Examples
" Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata"
" Hello World " => "#HelloWorld"
"" => false
https://www.codewars.com/kata/52449b062fb80683ec000024/train/javascript
*/
function generateHashtag (str) {
if (str.length < 1) {
return false;
}
let array = str.split(' ');
if (array[0]) {
for (let i = 0; i < array.length; i++) {
let letter = array[i];
if (letter) {
array[i] = letter.replace(letter[0], letter[0].toUpperCase());
} else {
array.splice(i, 1);
i -= 1;
}
}
} else {
return false;
}
array.unshift('#');
if (array.join('').length > 140) {
return false;
}
return array.join('');
}
Test.assertEquals(generateHashtag(""), false, "Expected an empty string to return false")
Test.assertEquals(generateHashtag(" ".repeat(200)), false, "Still an empty string")
Test.assertEquals(generateHashtag("Do We have A Hashtag"), "#DoWeHaveAHashtag", "Expected a Hashtag (#) at the beginning.")
Test.assertEquals(generateHashtag("Codewars"), "#Codewars", "Should handle a single word.")
Test.assertEquals(generateHashtag("Codewars Is Nice"), "#CodewarsIsNice", "Should remove spaces.")
Test.assertEquals(generateHashtag("Codewars is nice"), "#CodewarsIsNice", "Should capitalize first letters of words.")
Test.assertEquals(generateHashtag("code" + " ".repeat(140) + "wars"), "#CodeWars")
Test.assertEquals(generateHashtag("Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong Cat"), false, "Should return false if the final word is longer than 140 chars.")
Test.assertEquals(generateHashtag("a".repeat(139)), "#A" + "a".repeat(138), "Should work")
Test.assertEquals(generateHashtag("a".repeat(140)), false, "Too long")<file_sep>/*
Breaking chocolate problem
Your task is to split the chocolate bar of given dimension n x m
into small squares. Each square is of size 1x1 and unbreakable.
Implement a function that will return minimum number of breaks needed.
For example if you are given a chocolate bar of size 2 x 1 you can split
it to single squares in just one break, but for size 3 x 1 you must do
two breaks.
If input data is invalid you should return 0 (as in no breaks are needed
if we do not have any chocolate to split). Input will always be a
non-negative integer.
https://www.codewars.com/kata/534ea96ebb17181947000ada/train/javascript
*/
function breakChocolate(n,m) {
return (n*m === 0) ? 0 : n * m - 1;
}<file_sep>/*Quicksort (sometimes called partition-exchange sort) is an
efficient sorting algorithm. When implemented well, it can be
about two or three times faster than its main competitors, merge
sort and heapsort.
It is a comparison sort, meaning that it can sort items of any
type for which a “less-than” relation is defined.
Quicksort uses these steps.
Choose any element of the array to be the pivot. There are
multiple ways of selecting a pivot; explore the options and note
their advantages.
Divide all other elements (except the pivot) into two partitions.
All elements less than the pivot must be in the first partition.
All elements greater than the pivot must be in the second partition.
Recursively apply the above process to the two partitions
Join the first sorted partition, the pivot, and the second sorted
partition.
The best pivot creates partitions of equal length (or lengths
differing by 1). The worst pivot creates an empty partition
(for example, if the pivot is the first or last element of a
sorted array).
Extra Credit: Perform the sort in place.*/
// create a function called quickSort
function quickSort(array, lesserArray, greaterArray) {
// create lesser than array
lesserArray = lesserArray || [];
// create greater than array
greaterArray = greaterArray || [];
// choose an element from array to pivot
let middle = array[Math.round((array.length - 1) / 2)];
// if all other elements are less than pivot
if (array[0] < middle) {
// place in lesser array
lesserArray.push(array[0])
array.shift()
}
// if all other elements are greater than pivot
if (array[0] > middle) {
// place in greater array
greaterArray.push(array[0]);
array.shift();
}
if (array.length > 1) {
// recall function on partitioned arrays
quickSort(array, lesserArray, greaterArray)
} else {
// join the arrays
lesserArray.concat(greaterArray);
// return joined array
return lesserArray;
}
}
const test1 = quickSort([8,7,3,6,9,2,4,5,1]);
console.log(`Should sort a short array of integers: expected [1,2,3,4,5,6,7,8,9] and got ${JSON.stringify(test1)}`);
const test2 = quickSort([8,7,3,3,9,2,4,5,1]);
console.log(`Should handle duplicates: expected [1,2,3,3,4,5,7,8,9] and got ${JSON.stringify(test2)}`);
const test3 = quickSort([9,8,7,6,5,4,3,2,1]);
console.log(`Should handle reversely sorted array: expected [1,2,3,4,5,6,7,8,9] and got ${JSON.stringify(test3)}`);
const test4 = quickSort([]);
console.log(`Should handle empty array: expected [] and got ${JSON.stringify(test4)}`);
const test5 = quickSort([1]);
console.log(`Should handle array with single element: expected [1] and got ${JSON.stringify(test5)}`);
// function createLargeArray() {
// var input = [];
// var sorted;
// var n = 100000;
// for (var i = 0; i < n; i++) {
// var number = Math.floor(Math.random() * n);
// input.push(number);
// }
// return input;
// }
// const arr = createLargeArray();
// const test7 = arr.slice().sort((a, b) => a - b);
// const test6 = quickSort(arr);
// console.log(`Should handle large array: ${JSON.stringify(test6) === JSON.stringify(test7)}`);<file_sep>/* Find the first case of the longest substring palindrome.
Spaces and letters from other words count as long as the rules
of a palindrome are still true.*/
/* Currently works for finding the longest word that is a palindrome
in the string. My have start from scratch to work through the problem
in a completely different way.*/
function longestPalindrome (string) {
// split string on space
let array = string.split(' ');
// set variable for longest word index and length
let longest = [0,0];
// loop through array
for (let i = 0; i < array.length; i++) {
// if element is same in reverse
if (array[i] === array[i].split('').reverse().join('')) {
// if length is greater than length in longest
if (array[i].length > longest[1]) {
// save index and length of word
longest[0] = i;
longest[1] = array[i].length;
}
}
}
// return element
return array[longest[0]];
};
console.log(`Test1: expected "aibohphobia" and got "${longestPalindrome('aibohphobia')}"`);
console.log(`Test2: expected " redivider " and got "${longestPalindrome('aaaa level eye redivider hannah')}"`);
console.log(`Test3: expected "racecar" and got "${longestPalindrome('This palindrome occurs in the last half of the string racecar')}"`);
console.log(`Test4: expected " tattarrattat " and got "${longestPalindrome('There was a tattarrattat on the racecar. It made a funny noise, gfedcbabcdefg')}"`);
console.log(`Test5: expected "a racecar a" and got "${longestPalindrome('My dad is a racecar athlete')}"`);<file_sep>/**
* Write a function that, given a string, Finds the longest run of identical
* characters and returns an array containing the start and end indices of
* that run. If there are two runs of equal length, return the first one.
* For example:
*
* longestRun("abbbcc") // [1, 3]
* longestRun("aabbc") // [0, 1]
* longestRun("abcd") // [0, 0]
* longestRun("") // null
*
* Try your function with long, random strings to make sure it handles large
* inputs well.
*/
// // inputs: string
// // outputs: array of starting and ending index of longest run
// function longestRun(string) {
// // create an array
// let holder = [];
// // create a result array
// let result = [];
// // create count equal to 1
// let count = 1;
// // loop through string
// for ( let i = 0; i < string.length; i++) {
// if (holder.length < 1) {
// holder.push([string[i], i, count]);
// } else {
// // loop through array
// for(let j = 0; j < holder.length; j++) {
// // if string element is not in array
// console.log(holder[j])
// if (!holder[j].includes(string[i]) || holder[j] === undefined) {
// // push into array as mini array with letter, index, and count
// holder.push([string[i], i, count]);
// }
// // if string element is in the array
// if (holder[j].includes(string[i])) {
// // add to count
// holder[j][2]++;
// }
// }
// }
// // if (!holder.includes(string[i])) {
// // holder.push([i, count]);
// // console.log(holder)
// // } else {
// // for (let j = 0; j < holder.length; j++) {
// // if (holder[j].includes(string[i])) {
// // holder[j][1]++;
// // }
// // }
// // }
// }
// // loop through array
// for (let i = 0; i < holder.length; i++) {
// // if result array is empty
// if (result.length < 1) {
// // push first tuple into result
// result.push(holder[i]);
// }
// // if index 1 in tuple is greater than the tuple in result
// if (holder[i][1] > result[0][1]) {
// // replace tuple in result with greater value
// result.pop();
// result.push(holder[j]);
// }
// }
// if(result.length < 1) {
// return [0,0];
// }
// // return result
// return result;
// };
// console.log(`Test1: expected [1,3] and got [${longestRun('abbbcc')}]`);
// console.log(`Test2: expected [0,1] and got [${longestRun('aabbc')}]`);
// console.log(`Test3: expected [0,0] and got [${longestRun('')}]`);
// console.log(`Test4: expected [2,3] and got [${longestRun('mississippi')}]`);
// console.log(`Test5: expected [0,0] and got [${longestRun('abcdefgh')}]`);
// console.log(`Test6: expected [2,8] and got [${longestRun('abccccccc')}]`);
// inputs: string
// outputs: array of starting and ending index of longest run
function longestRun(string) {
// create an object holder
let holder = {};
// create a count set to 1
let count = 1;
// loop through string
for (let i = 0; i < string.length; i++) {
// if holder does not have a key with the string element
if (!holder[string[i]]) {
// set key in holder with an object as its property that holds the letters index and count
holder[string[i]] = {
index: i,
counter: count,
}
} else {
// else
// increment count
holder[string[i]].counter++;
}
}
// create a result array
let result = [];
// loop through object
for (let key in holder) {
// if array is empty
if (result.length < 1) {
// place index and count into array as a tuple
result.push(key.index, key.counter)
}
// if count is greater than result index 1
if (key.counter > result[1]) {
// replace object index and count in the array
result.pop();
result.push(key.index, key.counter)
}
}
// return array
return result;
}
console.log(`Test1: expected [1,3] and got [${longestRun('abbbcc')}]`);
console.log(`Test2: expected [0,1] and got [${longestRun('aabbc')}]`);
console.log(`Test3: expected [0,0] and got [${longestRun('')}]`);
console.log(`Test4: expected [2,3] and got [${longestRun('mississippi')}]`);
console.log(`Test5: expected [0,0] and got [${longestRun('abcdefgh')}]`);
console.log(`Test6: expected [2,8] and got [${longestRun('abccccccc')}]`);
// If you need a random string generator, use this!
// (you wont need this function for your solution but it may help with testing)
var randomString = function(len) {
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < len; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
module.exports = { longestRun };
|
dc67ecfa59d7e3bc452d22dc68e9262cf44eca3f
|
[
"JavaScript",
"Markdown"
] | 40 |
JavaScript
|
clln62/toyProblems
|
d6a7813236b29d2f1ef51f0d3132eef49f220eb8
|
a080d69e401ec4bef1471d204fd69a735cf7afe2
|
refs/heads/master
|
<repo_name>Juvygelbard/3dTetris<file_sep>/tetris.py
import sys, tkinter
from time import process_time
from random import choice, shuffle
from engine import Engine, Surface, HBox, HGrid
from assets import SHAPES, COLORS
from highscore import HighScoreTable
from menu import *
from utils import *
class Game:
BORAD_SIZE = 4
BOARD_HEIGHT = 14
LEVEL_TICK_TIME = (0.7, 0.5, 0.2)
LEVEL_SCORE_FACT = (1, 2, 3)
CAM_DIST = 22
CAM_HEIGHT = 18
CAM_PITCH = 0.5
HS_FILE = "hs.csv"
MOVE_MAP = ((-1, 0), (0, -1), (1, 0), (0, 1))
PITCH_ROLL_MAP = ((1, -1), (0, -1), (1, 1), (0, 1))
def __init__(self, width, height):
self.init_screen(width, height)
self.init_control()
self.init_board()
self.init_game()
self.init_menus()
def init_screen(self, width, height):
# tkinter stuff
self._root = tkinter.Tk()
self._root.minsize(width, height)
self._root.title("Tetris, FPS: 0")
self._frame = tkinter.Frame()
self._frame.pack(fill=tkinter.BOTH, expand=True)
self._canvas = tkinter.Canvas(self._frame)
self._canvas.pack(fill=tkinter.BOTH, expand=True)
# engine stuff
self._engine = Engine(self._canvas)
# cam stuff
self._board_center_X = np.floor(Game.BORAD_SIZE * 0.5)
self._board_center_Z = np.floor(Game.BORAD_SIZE * 0.5)
self._dir = 0
self.set_cam_angle(0.15)
self._target_cam_angle = self._cam_angle
self._interactive = True
self._t = 0.0
def init_control(self):
self._mouse_x = np.nan
self._mouse_y = np.nan
self._root.bind('<B1-Motion>', self.click_motion_event)
self._root.bind('<ButtonRelease-1>', self.click_release_event)
self._root.bind('<KeyPress>', self.key_press)
self._root.bind('<KeyRelease>', self.key_release)
def init_board(self):
# build board
self._board = np.zeros((Game.BORAD_SIZE, Game.BOARD_HEIGHT, Game.BORAD_SIZE))
self._elements = list()
# build floor
color = Color(120, 120, 120)
self._floor = list()
for i in range(Game.BORAD_SIZE):
self._floor.append(list())
for j in range(Game.BORAD_SIZE):
pos = Position(i + 0.5, -0.5, j + 0.5, 0.0, 0.0, 0.0)
self._floor[i].append(Surface(pos, 1.0, 1.0, color))
# build walls
self._walls = HBox(Position(Game.BORAD_SIZE * 0.5, Game.BOARD_HEIGHT * 0.5 - 0.5, Game.BORAD_SIZE * 0.5, 0, 0, 0), Game.BORAD_SIZE, Game.BOARD_HEIGHT, Game.BORAD_SIZE)
self._ceiling = HGrid(Position(Game.BORAD_SIZE * 0.5 + 0.5, Game.BOARD_HEIGHT-0.5, Game.BORAD_SIZE * 0.5 + 0.5, 0, 0, 0), 1.0, 1.0, Game.BORAD_SIZE+1, Game.BORAD_SIZE+1)
def init_game(self):
self.set_level(1)
self._fast = False
self._running = False
self._highscore = HighScoreTable(Game.HS_FILE)
def init_menus(self):
self._pause_menu = Pause()
self._start_menu = StartGame(self)
self._hs_menu = HighScore(self._highscore, self._start_menu)
self._show_menu = True
self._menu = self._start_menu
def reset_game(self):
self._board = np.zeros((Game.BORAD_SIZE, Game.BOARD_HEIGHT, Game.BORAD_SIZE))
self._elements.clear()
self._score = 0
self.generate_shape()
self._running = True
def click_motion_event(self, event):
if not np.isnan(self._mouse_x) and not np.isnan(self._mouse_y):
dy = (self._mouse_x - event.x) * self._t * np.pi * 0.02
dp = (self._mouse_y - event.y) * self._t * np.pi * 0.02
self._engine.move_cam(0.0, 0.0, 0.0, dy, dp, 0.0)
self._mouse_x = event.x
self._mouse_y = event.y
def click_release_event(self, event):
self._mouse_x = np.nan
self._mouse_y = np.nan
def key_press(self, key):
# menu keys
if self._show_menu:
self._menu = self._menu.key_press(key.char)
self._show_menu = self._menu is not None
return
# show menu keys
if key.char == 'p':
self._menu = self._pause_menu
self._show_menu = True
# cam keys
if key.char == 'z':
self.rotate_cam(-1)
elif key.char == 'c':
self.rotate_cam(1)
if not self._interactive:
return
# game translation keys
if key.keysym == "space":
self._fast = True
if key.keysym == "Left":
dX, dZ = Game.MOVE_MAP[(self._dir + 0) % 4]
self.move(dX, 0, dZ)
if key.keysym == "Down":
dX, dZ = Game.MOVE_MAP[(self._dir + 1) % 4]
self.move(dX, 0, dZ)
if key.keysym == "Right":
dX, dZ = Game.MOVE_MAP[(self._dir + 2) % 4]
self.move(dX, 0, dZ)
if key.keysym == "Up":
dX, dZ = Game.MOVE_MAP[(self._dir + 3) % 4]
self.move(dX, 0, dZ)
# game rotation keys
elif key.char == 's':
ax, dr = Game.PITCH_ROLL_MAP[(self._dir + 0) % 4]
self.rotate(ax, dr)
if key.char == 'w':
ax, dr = Game.PITCH_ROLL_MAP[(self._dir + 2) % 4]
self.rotate(ax, dr)
elif key.char == 'a':
self.rotate(2, -1)
elif key.char == 'd':
self.rotate(2, 1)
if key.char == 'q':
ax, dr = Game.PITCH_ROLL_MAP[(self._dir + 3) % 4]
self.rotate(ax, dr)
elif key.char == 'e':
ax, dr = Game.PITCH_ROLL_MAP[(self._dir + 1) % 4]
self.rotate(ax, dr)
# if key.char == 'w':
# self._engine.move_cam_relative(0.0, 0.0, 0.2)
# elif key.char == 's':
# self._engine.move_cam_relative(0.0, 0.0, -0.2)
# elif key.char == 'a':
# self._engine.move_cam_relative(-0.2, 0.0, 0.0)
# elif key.char == 'd':
# self._engine.move_cam_relative(0.2, 0.0, 0.0)
def key_release(self, key):
if key.keysym == "space":
self._fast = False
def set_cam_angle(self, a):
cam_X = Game.CAM_DIST * np.cos(a - 0.5 * np.pi) + self._board_center_X
cam_Z = Game.CAM_DIST * np.sin(a - 0.5 * np.pi) + self._board_center_Z
self._engine.set_cam(cam_X, Game.CAM_HEIGHT, cam_Z, -a, Game.CAM_PITCH, 0.0)
self._cam_angle = a
def animate_cam(self, t):
if abs(self._cam_angle - self._target_cam_angle) < 0.05:
self._dir %= 4
final_angle = self._dir * np.pi * 0.5 + 0.1
self._cam_angle = final_angle
self._target_cam_angle = final_angle
self._interactive = True
else:
temp_angle = self._cam_angle + (self._target_cam_angle - self._cam_angle) * t * np.pi * 1.0
self.set_cam_angle(temp_angle)
def rotate_cam(self, diff_idx):
self._interactive = False
self._dir += diff_idx
self._target_cam_angle = self._dir * np.pi * 0.5 + 0.1
def set_level(self, level):
self._level = level
self._tick_time = Game.LEVEL_TICK_TIME[self._level]
self._score_fact = Game.LEVEL_SCORE_FACT[self._level]
def level(self):
return self._level
def render_elements(self):
for e in self._elements:
# render only visible sides
D = e.Y > 0 and self._board[e.X, e.Y - 1, e.Z] == 0
U = e.Y == Game.BOARD_HEIGHT - 1 or self._board[e.X, e.Y + 1, e.Z] == 0
N = e.Z == Game.BORAD_SIZE - 1 or self._board[e.X, e.Y, e.Z + 1] == 0
S = e.Z == 0 or self._board[e.X, e.Y, e.Z - 1] == 0
E = e.X == Game.BORAD_SIZE - 1 or self._board[e.X + 1, e.Y, e.Z] == 0
W = e.X == 0 or self._board[e.X - 1, e.Y, e.Z] == 0
# shade shape projection on floor
shadow = 1.0
for x, y, z in self._shape.iterate():
if x == e.X and z == e.Z:
shadow = 0.5
break
self._engine.render(e.box, DOWN=D, UP=U, NORTH=N, SOUTH=S, EAST=E, WEST=W, SUP=shadow)
def render_floor(self):
for i in range(Game.BORAD_SIZE):
for j in range(Game.BORAD_SIZE):
shadow = 1.0
if self._running:
for x, y, z in self._shape.iterate():
if x == i and z == j:
shadow = 0.5
break
self._engine.render(self._floor[i][j], S=shadow)
self._engine.render(self._walls)
self._engine.render(self._ceiling)
def render_gui(self):
# display score
if self._running:
frame = GUIRect(50, 35, 100, 30, Color(200, 200, 200))
self._engine.render_gui(frame)
text = GUIText("Score: %d" % self._score, 100, 50, 14, Color(0, 0, 0))
self._engine.render_gui(text)
# display menus
if self._show_menu:
self._engine.render_gui(self._menu)
def rotate(self, axis, n):
self.remove_shape()
self._shape.rotate(axis, n)
can = True
for x, y, z in self._shape.iterate():
if not Game.in_board(x, y, z) or self._board[x, y, z] == 1:
self._shape.rotate(axis, -n)
can = False
break
self.add_shape()
return can
@staticmethod
def in_board(x, y, z):
return 0 <= x < Game.BORAD_SIZE and \
0 <= y < Game.BOARD_HEIGHT and \
0 <= z < Game.BORAD_SIZE
def move(self, dX, dY, dZ):
self.remove_shape()
self._shape.move(dX, dY, dZ)
can = True
for x, y, z in self._shape.iterate():
if not Game.in_board(x, y, z) or self._board[x, y, z] == 1:
self._shape.move(-dX, -dY, -dZ)
can = False
break
self.add_shape()
return can
def add_shape(self):
for x, y, z in self._shape.iterate():
if Game.in_board(x, y, z):
self._board[x, y, z] = 1
def remove_shape(self):
for x, y, z in self._shape.iterate():
if Game.in_board(x, y, z):
self._board[x, y, z] = 0
def update_score(self):
# find which surfaces we should remove
remove = list()
surface = Game.BORAD_SIZE * Game.BORAD_SIZE
for s in range(Game.BOARD_HEIGHT):
if np.sum(self._board[:, s, :]) == surface:
remove.append(s)
# update score
n = len(remove)
self._score += self._score_fact * n * n
# remove surfaces
while remove:
s = remove.pop(0)
for x, y, z in product_idx((Game.BORAD_SIZE, Game.BOARD_HEIGHT - s - 1, Game.BORAD_SIZE)):
self._board[x, s + y, z] = self._board[x, s + y + 1, z]
self._board[:, Game.BOARD_HEIGHT - 1, :] = np.zeros((Game.BORAD_SIZE, Game.BORAD_SIZE))
n_elements = list()
for e in self._elements:
if e.Y != s:
if e.Y > s:
e.move(0, -1, 0)
n_elements.append(e)
self._elements = n_elements
for i in range(len(remove)):
remove[i] -= 1
# find a shape that can fit current head space
def generate_shape(self):
color = choice(COLORS)
shapes = list(SHAPES)
shuffle(shapes)
while shapes:
s = shapes.pop()
s_y = Game.BOARD_HEIGHT - s.shape[1]
self._shape = Shape(s, color, 1, s_y, 1)
collision = False
for x, y, z in self._shape.iterate():
if not Game.in_board(x, y, z) or self._board[x, y, z] == 1:
collision = True
break
if collision:
continue
self.add_shape()
self._elements += self._shape.elements()
return True
return False
def tick(self):
if not self.move(0, -1, 0):
self.update_score()
if not self.generate_shape():
next_menu = NewHighScore(self._hs_menu, self._score, self._highscore) \
if self._highscore.is_high_score(self._score) \
else self._hs_menu
self._menu = GameOver(next_menu)
self._show_menu = True
self._running = False
def start(self):
fps = 0
t_acc = 0.0
t_tick = 0.0
t_p = process_time()
while True:
# handle timing
t_c = process_time()
self._t = t_c - t_p
t_p = t_c
# frame count
t_tick += self._t
if t_acc >= 1.0:
self._root.title("Tetris, FPS: %d" % fps)
t_acc = 0.0
fps = 0
# tick count
t_acc += self._t
tt_fact = 0.1 if self._fast else 1
if t_tick >= self._tick_time * tt_fact:
if not self._show_menu:
self.tick()
t_tick = 0.0
# draw stuff
try:
self.render_elements()
self.render_floor()
self.render_gui()
self.animate_cam(self._t)
self._engine.draw()
self._root.update()
except tkinter.TclError:
break
fps += 1
def run():
game = Game(550, 700)
game.start()
return 0
if __name__ == "__main__":
sys.exit(run())
<file_sep>/highscore.py
from csv import DictReader, DictWriter
from datetime import datetime
class HighScoreTable:
def __init__(self, path):
self._path = path
self.read()
def is_high_score(self, score):
return self._table[-1]["score"] < score
def read(self):
# load raw table
f = open(self._path, "r")
raw = DictReader(f)
# parse scores
self._table = list()
for r in raw:
r["score"] = int(r["score"])
self._table.append(r)
f.close()
# sort table
self._table.sort(key=lambda r: r["score"], reverse=True)
def write(self):
f = open(self._path, "w")
w = DictWriter(f, ("name", "time", "score"))
w.writeheader()
w.writerows(self._table)
f.close()
def add_score(self, score, name):
self._table.append({"name": name,
"time": datetime.now().strftime("%x"),
"score": score})
self._table.sort(key=lambda x: int(x["score"]), reverse=True)
self._table.pop(-1)
self.write()
def names(self):
for r in self._table:
yield r["name"]
def times(self):
for r in self._table:
yield r["time"]
def scores(self):
for r in self._table:
yield r["score"]<file_sep>/menu.py
from engine import GUI, GUIText, GUIRect, Color
class Menu(GUI):
# returns next menu or None for no menu
def key_press(self, key):
raise NotImplementedError
class Pause(Menu):
def draw(self, canvas, **kwargs):
w, h = canvas.winfo_width(), canvas.winfo_height()
wf, hf = 240, 80
frame = GUIRect((w - wf) * 0.5, (h - hf) * 0.5, wf, hf, Color(250, 150, 150))
frame.draw(canvas, **kwargs)
text = GUIText("Pause", w * 0.5, h * 0.5, 50, Color(100, 100, 100))
text.draw(canvas, **kwargs)
def key_press(self, key):
if key == 'p':
return None
else:
return self
class GameOver(Menu):
def __init__(self, next_menu):
self._next_menu = next_menu
def draw(self, canvas, **kwargs):
w, h = canvas.winfo_width(), canvas.winfo_height()
wf, hf = 450, 110
frame = GUIRect((w - wf) * 0.5, (h - hf) * 0.5, wf, hf, Color(250, 150, 150))
frame.draw(canvas, **kwargs)
head = GUIText("Game Over", w * 0.5, (h - hf) * 0.5 + 35, 40, Color(100, 100, 100))
head.draw(canvas, **kwargs)
cont = GUIText("<ENTER> to continue...", w * 0.5, (h - hf) * 0.5 + 85, 15, Color(100, 100, 100))
cont.draw(canvas, **kwargs)
def key_press(self, key):
if ord(key) == 13:
return self._next_menu
return self
class NewHighScore(Menu):
def __init__(self, hs_menu, score, table):
self._score = score
self._table = table
self._next_menu = hs_menu
self._text = ""
def draw(self, canvas, **kwargs):
w, h = canvas.winfo_width(), canvas.winfo_height()
fw, fh = 500, 200
frame = GUIRect((w - fw) * 0.5, (h - fh) * 0.5, fw, fh, Color(250, 150, 150))
frame.draw(canvas, **kwargs)
head_space = 35
head = GUIText("New High Score!", w * 0.5, (h - fh) * 0.5 + head_space, 30, Color(100, 100, 100))
head.draw(canvas, **kwargs)
time_l = GUIText(self._text, w * 0.5, h * 0.5, 20, Color(100, 100, 100), GUIText.CENTER)
time_l.draw(canvas, **kwargs)
cont_space = 35
cont = GUIText("Enter your name and then <ENTER> to continue...", w * 0.5, (h + fh) * 0.5 - cont_space, 15, Color(100, 100, 100))
cont.draw(canvas, **kwargs)
def key_press(self, key):
if ord(key) == 13:
print("ENTER")
self._table.add_score(self._score, self._text)
return self._next_menu
if ('A' <= key <= 'Z' or
'a' <= key <= 'z' or
'0' <= key <= '9' or
key == " ") and len(self._text) <= 10:
self._text += key
if key == '\b':
self._text = self._text[:-1]
return self
class HighScore(Menu):
def __init__(self, table, next_menu):
self._next_menu = next_menu
self._table = table
def draw(self, canvas, **kwargs):
w, h = canvas.winfo_width(), canvas.winfo_height()
fw, fh = 500, 400
frame = GUIRect((w - fw) * 0.5, (h - fh) * 0.5, fw, fh, Color(250, 150, 150))
frame.draw(canvas, **kwargs)
head_space = 35
head = GUIText("High Scores", w * 0.5, (h - fh) * 0.5 + head_space, 30, Color(100, 100, 100))
head.draw(canvas, **kwargs)
table_space = 205
rank = "\n".join(str(i) for i in range(1, 11))
names = "\n".join(self._table.names())
time = "\n".join(self._table.times())
score = "\n".join(str(s) for s in self._table.scores())
rank_l = GUIText(rank, (w - fw) * 0.5 + 30, (h - fh) * 0.5 + table_space, 18, Color(100, 100, 100), GUIText.RIGHT)
names_l = GUIText(names, (w - fw) * 0.5 + 115, (h - fh) * 0.5 + table_space, 18, Color(100, 100, 100), GUIText.LEFT)
time_l = GUIText(time, w * 0.5, (h - fh) * 0.5 + table_space, 18, Color(100, 100, 100), GUIText.CENTER)
score_l = GUIText(score, (w + fw) * 0.5 - 30, (h - fh) * 0.5 + table_space, 18, Color(100, 100, 100), GUIText.RIGHT)
rank_l.draw(canvas, **kwargs)
names_l.draw(canvas, **kwargs)
time_l.draw(canvas, **kwargs)
score_l.draw(canvas, **kwargs)
cont_space = 35
cont = GUIText("<ENTER> to continue...", w * 0.5, (h + fh) * 0.5 - cont_space, 15, Color(100, 100, 100))
cont.draw(canvas, **kwargs)
def key_press(self, key):
if ord(key) == 13:
return self._next_menu
return self
class StartGame(Menu):
LEVEL_STR = ("easy", "medium", "hard")
def __init__(self, game):
self._game = game
self._help = Help(self)
def draw(self, canvas, **kwargs):
w, h = canvas.winfo_width(), canvas.winfo_height()
fw, fh = 440, 305
frame = GUIRect((w - fw) * 0.5, (h - fh) * 0.5, fw, fh, Color(250, 150, 150))
frame.draw(canvas, **kwargs)
head = GUIText("Welcome to 3d Tetris!", w * 0.5, (h - fh) * 0.5 + 30, 30, Color(100, 100, 100))
head.draw(canvas, **kwargs)
text = GUIText("Current game level is %d (%s).\n\n"
"<S> Start the game\n"
"<1> Change game level to 1\n"
"<2> Change game level to 2\n"
"<3> Change game level to 3\n"
"<H> Display help (please read if\n"
" it's your first time playing!)"
% (self._game.level()+1, StartGame.LEVEL_STR[self._game.level()])
,w * 0.5, (h - fh) * 0.5 + 180, 18, Color(100, 100, 100))
text.draw(canvas, **kwargs)
def key_press(self, key):
if key == 's':
self._game.reset_game()
return None
if key == '1':
self._game.set_level(0)
if key == '2':
self._game.set_level(1)
if key == '3':
self._game.set_level(2)
if key == 'h':
return self._help
return self
class Help(Menu):
def __init__(self, next_menu):
self._next_menu = next_menu
def draw(self, canvas, **kwargs):
w, h = canvas.winfo_width(), canvas.winfo_height()
fw, fh = 500, 650
frame = GUIRect((w - fw) * 0.5, (h - fh) * 0.5, fw, fh, Color(250, 150, 150))
frame.draw(canvas, **kwargs)
head = GUIText("Help", w * 0.5, (h - fh) * 0.5 + 30, 30, Color(100, 100, 100))
head.draw(canvas, **kwargs)
text = GUIText("Welcome to 3d Tetris! This game is all about\n"
"procrastination, so please don't play it if there is\n"
"something you really needs to get done.\n\n"
"If somehow this is your first Tetris experience\n"
"then you're probably an alien, so welcome to earth!\n"
"The game rules are simple: you earn points by filling\n"
"up surfaces. When a surface is completely full, the\n"
"blocks of this surface will disappear, and you will earn\n"
"points. If you fill up 2 or more surfaces with a single\n"
"block, you'll get even more points. The game difficulty\n"
"level also affects the amount of points you'll get.\n\n"
"> Use the arrow keys to move blocks around.\n"
"> Use the w, s keys to rotate blocks in the pitch axis.\n"
"> Use the a, d keys to rotate blocks in the yaw axis.\n"
"> Use the q, e keys to rotate blocks in the roll axis.\n"
"> Use the z, x keys to rotate the cameras.\n"
"> Use the space key to speed up the falling blocks\n"
"> Use the p key to pause the game.\n\n"
"TIP1: motion and rotation are always relative to\n"
"current camera angle.\n"
"TIP2: rotate the camera A LOT, it's really useful!\n\n"
"<ENTER> to return..."
, w * 0.5, (h + fh) * 0.5 - 300, 14, Color(100, 100, 100))
text.draw(canvas, **kwargs)
def key_press(self, key):
if ord(key) == 13:
return self._next_menu
return self<file_sep>/engine.py
import numpy as np
from itertools import product
import tkinter
class VecUtil:
@staticmethod
def project(v):
norm = 1.0 / v[-1]
return norm * v[:-1]
@staticmethod
def l2sq(v1, v2=None):
v = v1 if v2 is None else v2 - v1
return np.sum(np.square(v))
@staticmethod
def l2(v1, v2=None):
return np.sqrt(VecUtil.l2sq(v1, v2))
@staticmethod
def norm(p1, p2, p3):
v12 = p2 - p1
v13 = p3 - p1
vn = np.cross(v12, v13)
inv_n = 1.0 / VecUtil.l2(vn)
return inv_n * vn
class GUI:
def draw(self, canvas, **kwargs):
raise NotImplementedError
class GUIRect(GUI):
def __init__(self, l, t, w, h, color):
self._l = l
self._t = t
self._r = l + w
self._b = t + h
self._color = color.toHTML()
def draw(self, canvas, **kwargs):
canvas.create_rectangle(self._l, self._t, self._r, self._b, fill=self._color, width=2)
class GUIText(GUI):
LEFT = tkinter.LEFT
CENTER = tkinter.CENTER
RIGHT = tkinter.RIGHT
def __init__(self, text, x, y, size, color, align=tkinter.LEFT):
self._text = text
self._x = x
self._y = y
self._size = size
self._color = color.toHTML()
self._align = align
def draw(self, canvas, **kwargs):
canvas.create_text(self._x, self._y, text=self._text, fill=self._color, justify=self._align, font=('Ariel', self._size))
class Position:
"""
params: X, Y, Z are real-world coordinates [pixels]
y, p, r are euler angles [radians]
"""
def __init__(self, X, Y, Z, y, p, r):
self.set_position(X, Y, Z, y, p, r)
def set_position(self, X, Y, Z, y, p, r):
self._loc = np.array((X, Y, Z), dtype=np.float64)
self._ori = np.array((y, p, r), dtype=np.float64)
self.build_tf()
def move(self, dX, dY, dZ, dy, dp, dr):
self._loc += np.array((dX, dY, dZ), dtype=np.float64)
self._ori += np.array((dy, dp, dr), dtype=np.float64)
self.build_tf()
def tf(self):
return self._tf_mat
def inv_tf(self):
return self._inv_tf
def build_tf(self):
tr = Position.tr4_mat(*self._loc)
rt = Position.rt4_mat(*self._ori)
self._tf_mat = np.dot(tr, rt)
inv_tr = Position.tr4_mat(*(-self._loc))
inv_rt = np.transpose(rt)
self._inv_tf = np.dot(inv_rt, inv_tr)
@staticmethod
def tr4_mat(X, Y, Z):
tr4 = np.eye(4)
tr4[0:3, 3] = X, Y, Z
return tr4
@staticmethod
def rt4_mat(y, p, r):
sinp = np.sin(p)
cosp = np.cos(p)
r_x = np.array(((1.0, 0.0, 0.0),
(0.0, cosp, -sinp),
(0.0, sinp, cosp)))
siny = np.sin(y)
cosy = np.cos(y)
r_y = np.array(((cosy, 0.0, siny),
(0.0, 1.0, 0.0),
(-siny, 0.0, cosy)))
sinr = np.sin(r)
cosr = np.cos(r)
r_z = np.array(((cosr, -sinr, 0.0),
(sinr, cosr, 0.0),
(0.0, 0.0, 1.0)))
rt3 = np.dot(r_z, np.dot(r_y, r_x))
rt4 = np.eye(4)
rt4[0:3, 0:3] = rt3
return rt4
def location_vec(self):
return self._loc
def orientation_vec(self):
return self._ori
class Color:
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def toHTML(self, fact=1.0):
r = min(255, int(fact * self.r))
g = min(255, int(fact * self.g))
b = min(255, int(fact * self.b))
html = "#%0.2x%0.2x%0.2x" % (r, g, b)
return html
class Cam:
def __init__(self, focal_length, position):
self._pos = position
self.build_k_mat(focal_length)
def set_position(self, X, Y, Z, y, p, r):
self._pos.set_position(X, Y, Z, y, p, r)
def move(self, dX, dY, dZ, dy, dp, dr):
self._pos.move(dX, dY, dZ, dy, dp, dr)
def build_k_mat(self, fl):
self._k = np.eye(3)
self._k[0, 0] = fl
self._k[1, 1] = fl
def extrinsic_tf(self, v):
p_ext = np.dot(self._pos.inv_tf(), v)
return VecUtil.project(p_ext)
def intrinsic_tf(self, v):
p_int = np.dot(self._k, v)
return VecUtil.project(p_int)
def tf_mat(self):
return self._pos.tf()
def inv_tf_mat(self):
return self._pos.inv_tf()
class Renderable:
def render(self, cam, light, screen_w, screen_h, **kwargs):
raise NotImplementedError
class Rendered:
def Z(self):
raise NotImplementedError
def draw(self, canvas):
raise NotImplementedError
class Polygon(Rendered):
def __init__(self, img_cord, Z, color):
self._img_cord = img_cord
self._Z = Z
self._color = color
def Z(self):
return self._Z
def draw(self, canvas):
cord = list()
for x, y in self._img_cord:
cord.append(x)
cord.append(y)
canvas.create_polygon(cord, fill=self._color, outline='black', width=2)
class Line(Rendered):
def __init__(self, p1, p2, Z, width=1, dashed=False):
self._p1 = p1
self._p2 = p2
self._Z = Z
self._width = width
self._dash = (2, 2) if dashed else None
def Z(self):
return self._Z
def draw(self, canvas):
canvas.create_line(self._p1[0], self._p1[1], self._p2[0], self._p2[1], width=self._width, dash=self._dash)
class HGrid(Renderable):
# tile_w, tile_h are floats
# grid_w, grid_h are integers
def __init__(self, position, tile_w, tile_h, grid_w, grid_h):
self._pos = position
w_edge = tile_w * grid_w * 0.5
h_edge = tile_h * grid_h * 0.5
self._grid_h = grid_h
self._grid_w = grid_w
w_diff = np.linspace(-w_edge, w_edge, grid_w + 1)
h_diff = np.linspace(-h_edge, h_edge, grid_h + 1)
self._v_diff = np.empty((self._grid_h, self._grid_w, 4))
for i in range(self._grid_h):
for j in range(self._grid_w):
self._v_diff[i][j] = w_diff[j], 0.0, h_diff[i], 1.0
def render(self, cam, light, screen_w, screen_h, **kwargs):
cx, cy = 0.5 * screen_w, 0.5 * screen_h
v_wld, v_cam, v_img = self.calc_vertices(cam, cx, cy)
for i in range(self._grid_h-1):
for j in range(self._grid_w):
# line behind camera
if min(v_cam[i][j][2], v_cam[i+1][j][2]) < 0.2:
continue
# line is outside of frame borders
if max(v_img[i][j][0], v_img[i+1][j][0]) < 0 or min(v_img[i][j][0], v_img[i+1][j][0]) >= screen_w:
continue
if max(v_img[i][j][1], v_img[i+1][j][1]) < 0 or min(v_img[i][j][1], v_img[i+1][j][1]) >= screen_h:
continue
len_ray = min(VecUtil.l2(v_cam[i][j]), VecUtil.l2(v_cam[i+1][j]))
yield Line(v_img[i][j], v_img[i+1][j], len_ray)
for i in range(self._grid_h):
for j in range(self._grid_w-1):
# line behind camera
if min(v_cam[i][j][2], v_cam[i][j+1][2]) < 0.2:
continue
# line is outside of frame borders
if max(v_img[i][j][0], v_img[i][j+1][0]) < 0 or min(v_img[i][j][0], v_img[i][j+1][0]) >= screen_w:
continue
if max(v_img[i][j][1], v_img[i][j+1][1]) < 0 or min(v_img[i][j][1], v_img[i][j+1][1]) >= screen_h:
continue
len_ray = min(VecUtil.l2(v_cam[i][j]), VecUtil.l2(v_cam[i][j+1]))
yield Line(v_img[i][j], v_img[i][j+1], len_ray)
def calc_vertices(self, cam, cx, cy):
v_wld = np.empty((self._grid_h, self._grid_w, 3))
v_cam = np.empty((self._grid_h, self._grid_w, 3))
v_img = np.empty((self._grid_h, self._grid_w, 2))
for i in range(self._grid_h):
for j in range(self._grid_w):
v_rw = np.dot(self._pos.tf(), self._v_diff[i][j])
v_wld[i][j] = VecUtil.project(v_rw)
v_ex = cam.extrinsic_tf(v_rw)
v_cam[i][j] = v_ex
v_in = cam.intrinsic_tf(v_ex)
v_img[i][j] = cx + v_in[0], cy - v_in[1]
return v_wld, v_cam, v_img
class FracLine(Renderable):
# p1, p2 are 3d vectors, res is an integer
def __init__(self, p1, p2, res):
assert(res > 0)
self._raw_pt = list()
for i in range(res + 1):
p3 = p1 * (i / res) + p2 * ((res - i) / res)
p4 = np.array((p3[0], p3[1], p3[2], 1.0))
self._raw_pt.append(p4)
def render(self, cam, light, screen_w, screen_h, **kwargs):
cx, cy = 0.5 * screen_w, 0.5 * screen_h
cam1, int1, img1 = None, None, None
first = True
for pt2 in self._raw_pt:
cam2 = cam.extrinsic_tf(pt2)
int2 = cam.intrinsic_tf(cam2)
img2 = cx + int2[0], cy - int2[1]
if not first:
# line behind camera
if min(cam1[2], cam2[2]) < 0.2:
cam1 = cam2
img1 = img2
continue
# line is outside of frame borders
if max(img1[0], img2[0]) < 0 or min(img1[0], img2[0]) >= screen_w:
cam1 = cam2
img1 = img2
continue
if max(img1[1], img2[1]) < 0 or min(img1[1], img2[1]) >= screen_h:
cam1 = cam2
img1 = img2
continue
len_ray = min(VecUtil.l2(cam1), VecUtil.l2(cam2))
yield Line(img1, img2, len_ray, width=2)
cam1 = cam2
img1 = img2
first = False
class HBox(Renderable):
LINES = ((0, 1, 2), (1, 3, 1), (3, 2, 2), (2, 0, 1),
(4, 5, 2), (5, 7, 1), (7, 6, 2), (6, 4, 1),
(2, 6, 0), (3, 7, 0), (0, 4, 0), (1, 5, 0))
def __init__(self, position, w, h, d):
self._pos = position
self._wbase = (0.5 * w, -0.5 * w)
self._hbase = (0.5 * h, -0.5 * h)
self._dbase = (0.5 * d, -0.5 * d)
self._ones = (1,)
self._dim = (w, h, d)
def render(self, cam, light, screen_w, screen_h, **kwargs):
v_wld = self.calc_vertices()
for p1, p2, l in HBox.LINES:
fl = FracLine(v_wld[p1], v_wld[p2], int(self._dim[l]))
for f in fl.render(cam, light, screen_w, screen_h, **kwargs):
yield f
def calc_vertices(self):
v_wld = list()
for v in product(self._wbase, self._hbase, self._dbase, self._ones):
v_rw = np.dot(self._pos.tf(), np.array(v))
v_wld.append(VecUtil.project(v_rw))
return v_wld
class Cube(Renderable):
SIDES = ((0, 2, 3, 1, 'EAST'),
(5, 7, 6, 4, 'WEST'),
(0, 1, 5, 4, 'UP'),
(6, 7, 3, 2, 'DOWN'),
(4, 6, 2, 0, 'NORTH'),
(1, 3, 7, 5, 'SOUTH'))
H_PI = 0.5 * np.pi
def __init__(self, position, length, color):
self._pos = position
self._len = length
self._color = color
self._base = (0.5 * self._len, -0.5 * self._len)
self._ones = (1,)
def render(self, cam, light, screen_w, screen_h, **kwargs):
cx, cy = 0.5 * screen_w, 0.5 * screen_h
v_wld, v_cam, v_img = self.calc_vertices(cam, cx, cy)
for p1, p2, p3, p4, side in Cube.SIDES:
render = kwargs.get(side, True)
if not render:
continue
# polygon behind camera
if min(v_cam[p1][2], v_cam[p2][2], v_cam[p3][2], v_cam[p4][2]) < 0.2:
continue
# polygon is outside of frame borders
img_cord = v_img[p1], v_img[p2], v_img[p3], v_img[p4]
img_x = [x for x, y in img_cord]
if max(img_x) < 0 or min(img_x) >= screen_w:
continue
img_y = [y for x, y in img_cord]
if max(img_y) < 0 or min(img_y) >= screen_h:
continue
# cube face is not visible
mid_cam = (v_cam[p1] + v_cam[p3]) * 0.5
nrm_cam = VecUtil.norm(v_cam[p1], v_cam[p2], v_cam[p3])
len_ray = VecUtil.l2(mid_cam)
nrm_ray = mid_cam / len_ray
cosa = np.dot(nrm_cam, nrm_ray)
theta = np.arccos(cosa)
if abs(theta) <= Cube.H_PI:
continue
# get color
mid_wld = (v_wld[p1] + v_wld[p3]) * 0.5
nrm_wld = VecUtil.norm(v_wld[p1], v_wld[p2], v_wld[p3])
shadow = kwargs.get("S" + side, 1.0)
fact = light.position2factor(mid_wld, nrm_wld) * shadow
color = self._color.toHTML(fact)
yield Polygon(img_cord, len_ray, color)
def calc_vertices(self, cam, cx, cy):
v_wld, v_cam, v_img = list(), list(), list()
for v in product(self._base, self._base, self._base, self._ones):
v_rw = np.dot(self._pos.tf(), np.array(v))
v_wld.append(VecUtil.project(v_rw))
v_ex = cam.extrinsic_tf(v_rw)
v_cam.append(v_ex)
v_in = cam.intrinsic_tf(v_ex)
v_sc = cx + v_in[0], cy - v_in[1]
v_img.append(v_sc)
return v_wld, v_cam, v_img
def set_position(self, X, Y, Z, y, p, r):
self._pos.set_position(X, Y, Z, y, p, r)
def move(self, dX, dY, dZ, dy, dp, dr):
self._pos.move(dX, dY, dZ, dy, dp, dr)
class Surface(Renderable):
def __init__(self, position, w, h, color):
self._pos = position
self._color = color
hw, hh = 0.5 * w, 0.5 * h
self._raw_pt = [(hw, 0.0, -hh, 1.0),
(hw, 0.0, hh, 1.0),
(-hw, 0.0, hh, 1.0),
(-hw, 0.0, -hh, 1.0)]
def render(self, cam, light, screen_w, screen_h, **kwargs):
wld_pt4 = [np.dot(self._pos.tf(), pt) for pt in self._raw_pt]
wld_pt3 = [VecUtil.project(pt) for pt in wld_pt4]
ext_pt = [cam.extrinsic_tf(pt) for pt in wld_pt4]
if min(map(lambda p: p[2], ext_pt)) < 0.1:
return []
int_pt = [cam.intrinsic_tf(pt) for pt in ext_pt]
cx, cy = 0.5 * screen_w, 0.5 * screen_h
img_pt = [(cx + x, cy - y) for x, y in int_pt]
mid_cam = 0.5 * (ext_pt[0] + ext_pt[2])
Z = VecUtil.l2(mid_cam)
mid_wld = 0.5 * (wld_pt3[0] + wld_pt3[2])
nrm_wld = VecUtil.norm(wld_pt3[0], wld_pt3[1], wld_pt3[2])
shadow = kwargs.get("S", 1.0)
fact = light.position2factor(mid_wld, nrm_wld) * shadow
color = self._color.toHTML(fact)
return [Polygon(img_pt, Z, color)]
class Light:
MID_RANGE = 15
def __init__(self, intensity, position):
self._int = intensity
self._loc = position.location_vec()
self._norm = Light.euler2unit(position)
@staticmethod
def euler2unit(pos):
rt = pos.tf()[0:3, 0:3]
v = np.array((0.0, 0.0, 1.0))
u = np.dot(rt, v)
return u
def position2factor(self, location, norm):
d = VecUtil.l2(self._loc, location)
i = Light.MID_RANGE / (d ** (2.0 * (1.0 - self._int)))
cost = np.dot(self._norm, norm)
t = np.arccos(cost)
return i * t / np.pi
class Engine:
def __init__(self, canvas):
self._canvas = canvas
self._cam = Cam(1000, Position(0.0, 0.0, 0.0, 0.0, 0.0, 0.0))
self._light = Light(0.5, Position(0.0, 2.0, -6.0, 0.0, np.pi * -0.1, 0.0))
self._polygons = list()
self._gui = list()
def render(self, item, **kwargs):
screen_w, screen_h = self._canvas.winfo_width(), self._canvas.winfo_height()
for p in item.render(self._cam, self._light, screen_w, screen_h, **kwargs):
self._polygons.append(p)
def render_gui(self, item):
self._gui.append(item)
def draw(self):
self._canvas.delete(tkinter.ALL)
self._polygons.sort(key=lambda p: p.Z(), reverse=True)
for p in self._polygons:
p.draw(self._canvas)
for g in self._gui:
g.draw(self._canvas)
self._polygons.clear()
self._gui.clear()
def set_cam(self, X, Y, Z, y, p, r):
self._cam.set_position(X, Y, Z, y, p, r)
def move_cam(self, dX, dY, dZ, dy, dp, dr):
self._cam.move(dX, dY, dZ, dy, dp, dr)
def move_cam_relative(self, dX, dY, dZ):
v = np.array((dX, dY, dZ))
tf = self._cam.tf_mat()
rt = tf[0:3, 0:3]
v_rt = np.dot(rt, v)
self._cam.move(v_rt[0], v_rt[1], v_rt[2], 0.0, 0.0, 0.0)<file_sep>/utils.py
import numpy as np
from itertools import product
from engine import Position, Cube
def product_idx(idx):
l = [list(range(i)) for i in idx]
for p in product(*l):
yield p
class Element:
def __init__(self, X, Y, Z, color):
self.X, self.Y, self.Z = X, Y, Z
self.box = Cube(Position(X + 0.5, Y, Z + 0.5, 0, 0, 0), 1, color)
def set_position(self, X, Y, Z):
self.X, self.Y, self.Z = X, Y, Z
self.box.set_position(X + 0.5, Y, Z + 0.5, 0, 0, 0)
def move(self, dX, dY, dZ):
self.X += dX
self.Y += dY
self.Z += dZ
self.box.move(dX, dY, dZ, 0, 0, 0)
class Shape:
AXIS = ((0, 1),
(1, 2),
(0, 2))
def __init__(self, src, color, X, Y, Z):
self.X, self.Y, self.Z = X, Y, Z
self._shape = np.shape(src)
self._map = np.full(self._shape, -1, dtype=np.int8)
self._elements = list()
idx = 0
for i, j, k in product_idx(self._shape):
if src[i, j, k] != 0:
self._map[i, j, k] = idx
idx += 1
self._elements.append(Element(i + X, j + Y, k + Z, color))
def elements(self):
return self._elements
def iterate(self):
for i, j, k in product_idx(self._shape):
idx = self._map[i, j, k]
if idx >= 0:
yield self._elements[idx].X, self._elements[idx].Y, self._elements[idx].Z
def rotate(self, axis, n):
self._map = np.rot90(self._map, n, Shape.AXIS[axis])
for i, j, k in product_idx(self._shape):
idx = self._map[i, j, k]
if idx >= 0:
self._elements[idx].set_position(i + self.X, j + self.Y, k + self.Z)
def move(self, dX, dY, dZ):
self.X += dX
self.Y += dY
self.Z += dZ
for e in self._elements:
e.move(dX, dY, dZ)<file_sep>/README.md
# 3d Tetris
<img src="tetris.gif" width=200px>
#### What is this?
A 3d Tetris game made using only numpy and simple tkinter 2d drawing routines.
#### Why is this?
Because I had a very important thing to do and I was eager to procrastinate.
#### How to run?
0. You need Python3 with numpy installed
1. Clone this repository
2. Run `tetris.py`
3. Profit!
#### How to play?
Full game rules and instructions are included in the help menu.
To reach the help menu, run the game and press *h*.
|
008d81bf4b4f42e75c3969b9f49082c3546a8a06
|
[
"Markdown",
"Python"
] | 6 |
Python
|
Juvygelbard/3dTetris
|
e746e2efcc383c16c9af10d0a2d6376ba69330fa
|
8a856b93d246d321a8263e1fad9aea8a38bb04f0
|
refs/heads/master
|
<repo_name>dakillon/SP<file_sep>/src/Subcapitol.java
import java.util.ArrayList;
public class Subcapitol {
String titlu;
ArrayList<Element>continut=new ArrayList<Element>();
public Subcapitol(String titlu){
this.titlu=titlu;
}
public void addElement(Element e){
this.continut.add(e);
}
public void print(){
System.out.println("Subcapitolul "+titlu);
for(Element e:continut){
}
}
}
<file_sep>/src/Element.java
public interface Element {
public static void addElement(){
}
public static void removeElement(){
}
public static void getElement(){
}
public static void print(){
}
}
<file_sep>/src/Paragraf.java
public class Paragraf implements Element {
String text;
Paragraf(String t){
this.text=t;
}
public void print(){
System.out.println(text);
}
}
|
b2e8bb51902e5a1e78664af9da67f3a6ea868556
|
[
"Java"
] | 3 |
Java
|
dakillon/SP
|
3ae4ec849930f52b21e08c91c481fd641fdfdd87
|
f2fa8bf1b7fdd5f38e44dd2faaae2cfcce199e51
|
refs/heads/master
|
<repo_name>amerlin/excel-parser<file_sep>/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using OfficeOpenXml;
namespace excel_parser
{
class Program
{
static void Main(string[] args)
{
var filePath = @"./data/data.xlsx";
FileInfo file = new FileInfo(filePath);
var exportList = new List<ExportClass>();
using (var package = new ExcelPackage(file))
{
var worksheet = package.Workbook.Worksheets[1];
var rowCount = worksheet.Dimension.Rows;
var ColCount = worksheet.Dimension.Columns;
var rawText = string.Empty;
for (int row = 1; row <= rowCount; row++)
{
for (var col = 1; col <= ColCount; col++)
{
rawText += worksheet.Cells[row, col].Value.ToString(); //+ "\t";
}
// rawText += "\r\n";
exportList.Add(new ExportClass(){Name = rawText});
}
// Console.WriteLine(rawText);
}
var export = JsonConvert.SerializeObject(exportList);
Console.WriteLine(export);
}
}
}
<file_sep>/ExportClass.cs
public class ExportClass {
public string Name {get;set;}
}<file_sep>/Readme.md
Simple console application, to parse EXCEL file, in .NET Core 2.0
|
6f1a0da1e5ef83655f28bfe1f4fa38c77d2cd751
|
[
"Markdown",
"C#"
] | 3 |
C#
|
amerlin/excel-parser
|
0eddc01c5a22493502cfd1ed16630619c5d0628a
|
b569910f153e22a30785cc2196c99fadff7c0c24
|
refs/heads/master
|
<file_sep># machineLearning
In this repository I deal with various machine learning algorithms on real world data set obtained from Kaggle
<file_sep>Algotrithm to predict the insurance charges for an individual based on various features.
We train the model,and save the top 2 best fit model.
<file_sep>import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import pickle
df=pd.read_csv('train.csv')
df2=pd.read_csv('predict.csv')
df.drop(columns=['PassengerId','Name','Ticket','Cabin'],inplace=True)
df2.drop(columns=['PassengerId','Name','Ticket','Cabin'],inplace=True)
# Encoding the data into arbitrary numbers
df['Sex']=df['Sex'].astype("category").cat.codes
df['Embarked']=df['Embarked'].astype("category").cat.codes
df2['Sex']=df2['Sex'].astype("category").cat.codes
df2['Embarked']=df2['Embarked'].astype("category").cat.codes
# preprocessing the data
df.Age.fillna(df.Age.mean(),inplace=True)
df.Fare.fillna(df.Fare.mean(),inplace=True)
df2.Age.fillna(df2.Age.mean(),inplace=True)
df2.Fare.fillna(df2.Fare.mean(),inplace=True)
X=df.drop("Survived", axis=1)
y=df.Survived
# Training and testing
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)
clf=LogisticRegression()
clf.fit(X_train,y_train)
clf.score(X_test,y_test)
# Saving the best fit model
with open('model','wb') as f:
pickle.dump(clf,f)
clf.predict(df2)
<file_sep>#!/usr/bin/env python
# coding: utf-8
# In[16]:
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import pickle
df=pd.read_csv("Admission_Predict.csv")
df=df.drop("Serial No.",axis=1)
df.head()
# In[17]:
X=df.drop("Chance of Admit",axis=1)
y=df["Chance of Admit"]
# In[18]:
X=X.values
y=y.values
# In[32]:
X_train,X_test,y_train,y_test =train_test_split(X,y,test_size=0.2)
clf=LinearRegression()
clf.fit(X_train,y_train)
clf.score(X_test,y_test)
# In[33]:
with open('model','wb') as f:
pickle.dump('model',f)
# In[ ]:
<file_sep>#predicting whether a person will click on a ad or not
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import pickle
df=pd.read_csv('advertising.csv')
df.head()
# Separating features and Target variable
X=df.drop(['Clicked on Ad','Ad Topic Line','Timestamp','Country','City'],axis=1)
y=df['Clicked on Ad']
#converting dataset into array
X=X.values
y=y.values
#Training and testing
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.25)
clf=LogisticRegression()
clf.fit(X_train,y_train)
clf.score(X_test,y_test)
#Saving the model
with open('model','wb') as f:
pickle.dump('model',f)
|
7953e6311633e88c9ba0eed4210dd52b4ff2adc8
|
[
"Markdown",
"Python",
"Text"
] | 5 |
Markdown
|
nikhil2195/machineLearning
|
3bd539e2c68595f94d3af04d3263b8393ed06719
|
cbf623d05bfe1ec72e43f8345daa6c4b5d74bf73
|
refs/heads/master
|
<file_sep>"use strict";
var path = require('path');
var fs = require('fs-extra');
var byline = require('byline');
var util = require('util');
var stream = require('stream');
var Transform = stream.Transform;
var trim = function(str) {
if (!str) {
return str;
}
return str.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '');
};
var parseColorFunction = function(colorFunc, result) {
var startIdx = colorFunc.indexOf('(');
var endIdx = colorFunc.lastIndexOf(')');
var funcName = trim(colorFunc.substring(0, startIdx));
var funcParams = trim(colorFunc.substring(startIdx + 1, endIdx));
var lastComma = funcParams.lastIndexOf(',');
var colorParam = funcParams.substring(0, lastComma);
var valueParam = funcParams.substring(lastComma + 1, funcParams.length);
colorParam = trim(colorParam);
valueParam = trim(valueParam);
if (colorParam.indexOf('lighten') >= 0 ||
colorParam.indexOf('darken') >= 0 ||
colorParam.indexOf('adjust-hue') >= 0) {
parseColorFunction(funcParams, result);
result.func.push({name: funcName, value: valueParam});
} else {
result.color = colorParam;
result.func.push({name: funcName, value: valueParam});
}
};
var isValidOperand = function(operand) {
return operand[0] === '$' || !isNaN(parseFloat(operand, 10));
};
var processCalcExpression = function(line) {
var openIdx = line.indexOf('(');
var closeIdx = line.lastIndexOf(')');
if (openIdx >= 0 && closeIdx > 0) {
var firstLinePart = line.substring(0, openIdx + 1);
var secondLinePart = line.substring(closeIdx, line.length);
var exp = line.substring(openIdx + 1, closeIdx);
var addOperatorIdx = exp.lastIndexOf('+');
var subOperatorIdx = exp.lastIndexOf('-');
var multOperatorIdx = exp.lastIndexOf('*');
var divOperatorIdx = exp.lastIndexOf('/');
var operatorIdx = Math.max(addOperatorIdx, subOperatorIdx, multOperatorIdx, divOperatorIdx);
console.log('Check if we have a calc value for line : ' + line);
console.log('firstLinePart: ' + firstLinePart);
console.log('secondLinePart: ' + secondLinePart);
console.log('exp: ' + exp);
console.log('operatorIdx: ' + operatorIdx);
if (operatorIdx > 0) {
var operator = exp[operatorIdx];
var operand1 = trim(exp.substr(0, operatorIdx));
var operand2 = trim(exp.substr(operatorIdx + 1, exp.length));
// Check operand is number or variable
if (!isValidOperand(operand1) || operand1.indexOf(' ') > 0 || operand1.indexOf(',') >= 0 || operand1.indexOf('(') >= 0
|| !isValidOperand(operand2) || operand2.indexOf(' ') > 0 || operand2.indexOf(',') >= 0 || operand2.indexOf('(') >= 0) {
// ignore
//console.log('ignore line: ' + line);
} else {
console.log('operator: ' + operator);
console.log('operand1: ' + operand1);
console.log('operand2: ' + operand2);
if (operand1 && operand2 && operand1.length > 0 && operand2.length > 0) {
line = firstLinePart + 'calc(' + operand1 + ' ' + operator + ' ' + operand2 + ')' + secondLinePart;
console.log('line: ' + line);
}
}
}
}
return line;
};
var ConvertToPostCSS = function(options) {
// allow use without new
if (!(this instanceof ConvertToPostCSS)) {
return new ConvertToPostCSS(options);
}
// init Transform
Transform.call(this, options);
};
util.inherits(ConvertToPostCSS, Transform);
ConvertToPostCSS.prototype._transform = function(chunk, encoding, callback) {
// TODO: fixme @fonf-face in glyphicons.css (remove manually to test)
var firstLinePart, secondLinePart;
var line = chunk.toString();
//var trimmedLine = trim(line);
// Remove inline comment
var commentIdx = line.indexOf('//');
if (commentIdx>= 0) {
line = line.substring(0, commentIdx);
}
// Fix icon-font-path (yes this is ugly)
if (line === '$icon-font-path: if($bootstrap-sass-asset-helper, "bootstrap/", "../fonts/bootstrap/") !default;') {
line = '$icon-font-path: "../fonts/bootstrap/");';
}
// Remove !default
line = line.replace('!default', '');
// Replace "@mixin mixin-name($var1, $var2: default) {"
// by "@define-mixin mixin-name $var1, $var2: default {"
if (line.indexOf('@mixin ') >= 0) {
line = line.replace('@mixin ', '@define-mixin ');
line = line.replace('...', '');
line = line.replace('(', ' ');
line = line.replace(')', '');
}
//@include gradient-vertical($start-color: $btn-color, $end-color: darken($btn-color, 12%));
//@include alert-variant($alert-success-bg, $alert-success-border, $alert-success-text);
// Replace @include mixin-name($var1, $var2);
// by @mixin mixin-name var1, var2 {}
if (line.indexOf('@include ') >= 0) {
line = line.replace('@include ', '@mixin ');
line = line.replace(/'/g, '');
line = line.replace('(', ' ');
line = line.replace(')', '');
line = line.replace(';', ' {}');
}
// Remove @extend (FIXME)
if (line.indexOf('@extend ') >= 0) {
line = '';
}
// Replace #{$var} by $(var)
line = line.replace(/\#\{\$([a-z]+)\}/ig, '$($1)');
// Special case of import deps (yes this is ugly)
if (line === '@import "mixins/vendor-prefixes";') {
line = '@import "mixins/border-radius";\n' + line;
} else if (line === '@import "mixins/progress-bar";') {
line = '@import "mixins/gradients";\n' + line;
} else if (line === '@import "mixins/border-radius";') {
line = '';
} else if (line === '@import "mixins/gradients";') {
line = '';
}
// Color
var lightenIdx = line.indexOf('lighten');
var darkenIdx = line.indexOf('darken');
// TODO: adjust-hue
var minIdx = lightenIdx;
//var indexLength = 'lighten'.length;
if (darkenIdx >= 0 && (minIdx < 0 || darkenIdx < minIdx)) {
minIdx = darkenIdx;
//indexLength = 'darken'.length;
}
if (minIdx >= 0) {
firstLinePart = line.substring(0, minIdx);
secondLinePart = line.substring(minIdx, line.length);
//console.log('firstLinePart: ' + firstLinePart);
//console.log('secondLinePart: ' + secondLinePart);
var result = {
color: null,
func: []
};
parseColorFunction(secondLinePart, result);
var color = 'color(' + result.color;
result.func.forEach(function(func) {
var value = func.value;
if (value[0] !== '-' || value[0] !== '+') {
value = '+' + value;
}
if (func.name === 'lighten') {
color += ' lightness(' + value + ')';
} else if (func.name === 'darken') {
color += ' blackness(' + value + ')';
} else if (func.name === 'adjust-hue') {
color += ' hue(' + value + ')';
} else {
console.error('color func ' + func.name + ' not supported');
//throw new Error('color func ' + func.name + ' not supported');
}
});
color += ');';
line = firstLinePart + color;
//console.log('result: ' + line);
}
// Calc
line = processCalcExpression(line);
if (line !== '') {
this.push(line + '\n');
}
callback();
};
var cleanFiles = function(directory) {
fs.readdirSync(directory).forEach(function(fileName) {
var file = path.join(directory, fileName);
var stat = fs.statSync(file);
if (stat.isDirectory()) {
// Recursive call
cleanFiles(file);
} else {
var cleanFileName;
var extIndex = fileName.lastIndexOf('.');
if (extIndex < 0) {
cleanFileName = fileName;
} else {
cleanFileName = fileName.substring(0, extIndex);
}
if (cleanFileName[0] === '_') {
cleanFileName = cleanFileName.substring(1, cleanFileName.length);
}
var newFile = path.join(directory, cleanFileName + '.css');
var convertToPostCSS = new ConvertToPostCSS();
byline(fs.createReadStream(file))
.pipe(convertToPostCSS)
.pipe(fs.createWriteStream(newFile));
fs.unlink(file);
}
});
};
var line = ' font-size: ($font-size-base - 1); ';
console.log(processCalcExpression(line));
var bootstrapSassModule = path.join(process.cwd(), 'node_modules/bootstrap-sass');
if (!fs.existsSync(bootstrapSassModule)) {
throw new Error('bootstrap-sass module not found, missing npm install?');
}
var bootstrapAssets = path.join(bootstrapSassModule, 'assets');
if (!fs.existsSync(bootstrapAssets)) {
throw new Error('assets directory not found, bootstrap-sass version not supported. Try downgrade');
}
var copyAssets = path.join(process.cwd(), 'assets');
fs.emptyDirSync(copyAssets);
fs.copySync(bootstrapAssets, copyAssets);
var styles = path.join(copyAssets, 'stylesheets');
cleanFiles(styles);
<file_sep># Bootstap PostCSS
The boostrap PostCSS version
# Why
* Hangs issue with webpack and sass
https://github.com/webpack/webpack-dev-server/issues/128
* "Bootstrap 5 will likely be in PostCSS", but when?
http://www.reddit.com/r/webdev/comments/33pnod/oh_btwbootstrap_4_will_be_in_scss_and_if_you_care/
* PostCSS sounds cool
# Usage
Current bootstrap SASS version converted to PostCSS is a vailable in /assets
To convert a new version, update the bootstrap-sass version and run npm start
# PostCSS required plugins
Some plugins will be required to use boostrap-postcss:
* postcss-import
* postcss-mixins
* postcss-nested
* postcss-simple-vars
* postcss-color-function
Don't forget adding them
# Work in progress
This project is work in progress and not all boostrap sass usage supported (@extend, if, twbs-font-path)
For example, you should remove the @at-root and @font-face directives of glyphicons.css to don't have error. Of cours Glyphicons don't works.
```css
@at-root {
@font-face {
font-family: 'Glyphicons Halflings';
src: url(if($bootstrap-sass-asset-helper, twbs-font-path('#{$icon-font-path}#{$icon-font-name}.eot'), '#{$icon-font-path}#{$icon-font-name}.eot'));
src: url(if($bootstrap-sass-asset-helper, twbs-font-path('#{$icon-font-path}#{$icon-font-name}.eot?#iefix'), '#{$icon-font-path}#{$icon-font-name}.eot?#iefix')) format('embedded-opentype'),
url(if($bootstrap-sass-asset-helper, twbs-font-path('#{$icon-font-path}#{$icon-font-name}.woff2'), '#{$icon-font-path}#{$icon-font-name}.woff2')) format('woff2'),
url(if($bootstrap-sass-asset-helper, twbs-font-path('#{$icon-font-path}#{$icon-font-name}.woff'), '#{$icon-font-path}#{$icon-font-name}.woff')) format('woff'),
url(if($bootstrap-sass-asset-helper, twbs-font-path('#{$icon-font-path}#{$icon-font-name}.ttf'), '#{$icon-font-path}#{$icon-font-name}.ttf')) format('truetype'),
url(if($bootstrap-sass-asset-helper, twbs-font-path('#{$icon-font-path}#{$icon-font-name}.svg##{$icon-font-svg-id}'), '#{$icon-font-path}#{$icon-font-name}.svg##{$icon-font-svg-id}')) format('svg');
}
}
```
# TODO
* @extend .className
* @at-root
* twbs-font-path
* format
* math expression (14px * 1.5), floor(14px * 1.5), (floor(ceil((14px * 0.85)) * 1.5 ) + (5px * 2) + 2)
* if
* ...
|
010ce879ddf54e85d3c45660cc7375864f096798
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
lowik/bootstrap-postcss
|
fa31ac92ac73468e975f1028033ec358ae3ae292
|
962a79fde0dbb50cc5018836e8350eafff6caad1
|
refs/heads/master
|
<repo_name>ziggity/hairsalon<file_sep>/tests/ClientTest.php
<?php
/**
* @backupGlobals disabled
* @backupStaticAttributes disabled
*/
$DB = new PDO('mysql:host=localhost:8889;dbname=test_hairsalon', "root", "root");
require_once "src/Stylist.php";
require_once "src/Client.php";
class ClientTest extends PHPUnit_Framework_TestCase
{
protected function tearDown()
{
Stylist::deleteAll();
Client::deleteAll();
}
function test_save()
{
//Arrangeit
$name = "Eliot";
$stylist_id = 8;
$client = new Client($name, $stylist_id);
//Actonit
$executed =$client->save();
// AssertEquals
$this->assertTrue($executed, "Client not saved to database");
}
function test_deleteAll()
{
$newClient = new Client ("max","blue");
$newClient->save();
Client::deleteAll();
$result = Client::getAll();
$this->assertEquals($result, []);
}
function test_getAll()
{
$newClient = new Client ('max', 8);
$newClient->save();
$newClient2 = new Client ('jack', 9);
$newClient2->save();
$result = Client::getAll();
$this->assertEquals([$newClient, $newClient2], $result);
}
}
?>
<file_sep>/tests/StylistTest.php
<?php
/**
* @backupGlobals disabled
* @backupStaticAttributes disabled
*/
$DB = new PDO('mysql:host=localhost:8889;dbname=test_hairsalon', "root", "root");
require_once "src/Stylist.php";
require_once "src/Client.php";
class StylistTest extends PHPUnit_Framework_TestCase
{
protected function tearDown()
{
Stylist::deleteAll();
}
function test_save()
{
//Arrangeit
$input_name = "Zak";
$stylist = new Stylist($input_name);
//Actonit
$stylist->save();
$result = Stylist::getAll();
//AssertEquals
$this->assertEquals([$stylist], $result);
}
function test_deleteAll()
{
//Arrangeit
$newStlyist = new Stylist ("max","blue");
//Actonit
$newStlyist->save();
Stylist::deleteAll();
$result = Stylist::getAll();
//AssertEquals
$this->assertEquals($result, []);
}
function test_getAll()
{
//Arrangeit
$newStlyist = new Stylist ('Joe', 'blue');
$newStlyist2 = new Stylist ('jack', "black");
//Actonit
$newStlyist->save();
$newStlyist2->save();
$result = Stylist::getAll();
//AssertEquals
$this->assertEquals($result, [$newStlyist, $newStlyist2] );
}
}
?>
<file_sep>/src/Stylist.php
<?php
class Stylist
{
private $name;
private $id;
function __construct($name, $id=null)
{
$this->name =$name;
$this->id = $id;
}
function getName()
{
return $this->name;
}
function setName($new_name)
{
$this->name = $new_name;
}
function getId()
{
return $this->id;
}
function save()
{
$executed = $GLOBALS['DB']->exec("INSERT INTO stylists (name) VALUES ('{$this->getName()}'); ");
if($executed){
$this->id = $GLOBALS['DB']->lastInsertId();
return true;
}else{
return false;
}
}
static function getAll()
{
$stylists = array();
$returned_stylists = $GLOBALS['DB']->query('SELECT * FROM stylists;');
foreach($returned_stylists as $stylist)
{
$newStylist = new Stylist($stylist['name'], $stylist["id"]);
array_push($stylists, $newStylist);
}
return $stylists;
}
static function deleteAll()
{
$deleteAll = $GLOBALS['DB']->exec("DELETE FROM stylists;");
if ($deleteAll)
{
return true;
}else {
return false;
}
}
}
?>
|
28632649ab2cd60c283ade9224a1c7b496d9a549
|
[
"PHP"
] | 3 |
PHP
|
ziggity/hairsalon
|
d8ce01f0ac45ba94fa60910d329b381fe78cb231
|
31a7de3715f1fea9f8a216858a7e4f1e77065071
|
refs/heads/master
|
<file_sep># WP1-14
úplně jsem na tenhle úkol zapomněl, dopsal jsem
<file_sep><?php
$submit = filter_input(INPUT_POST, 'submit');
$gender = filter_input(INPUT_POST, 'gender');
$email = filter_input(INPUT_POST, 'email');
?>
<!DOCTYPE html>
<html lang="cs">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WP1-14</title>
</head>
<body>
<form action="formular.php" method="post">
<?php
if ((isset($submit))) { ?>
<p>Formulář byl odeslán</p>
<p>Email : <?=$email?></p>
<p>pohlaví : <?=$gender?></p> <?php }
else { ?>
<p>stránka byla načtena bez odeslaného formuláře</p>
<label for="email">E-mail</label>
<input type="email" name="email" id="email">
<h2>Pohlaví</h2>
<label for="gender">Gender :</label>
<label for="gender-male">Muž</label>
<input type="radio" name="gender" value="male" id="gender-male">
<label for="gender-female">Žena</label>
<input type="radio" name="gender" value="female" id="gender-female">
<label for="gender-none">non-specific</label>
<input type="radio" name="gender" value="none" id="gender-none">
<input type="submit" name="submit" value="Přidat do databáze">
<?php }; ?>
</form>
</body>
</html>
|
b31b306ad8a1000ace68b6d10f807506feb2f320
|
[
"Markdown",
"PHP"
] | 2 |
Markdown
|
MartinL3dl/WP1-14
|
6112857ecf91738bdc27a0ab188d9f5d872623ed
|
a93c855c175000cb805f8de1b5fcd0c881231bc5
|
refs/heads/master
|
<repo_name>Anyju/Mcpec1<file_sep>/clase1.Rmd
---
title: "Curso de R"
author: <NAME>
date: 25 de enero de 2017
output:
---
## Introducci?n {.flexbox .vcenter}
R es un software para el an?lisis estad?stico de datos considerado como uno de los m?s interesantes.
Beneficios de R:
- Almacenamiento y manipulaci?n efectiva de datos.
- Operadores para c?lculo sobre variables indexadas.
- Amplia colecci?n de herramientas para an?lisis de datos.
- Posibilidades gr?ficas para an?lisis de datos
## Ayuda sobre funciones y capacidades
Para recibir ayuda sobre una funci?n o un
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
#help(solve) o ?solve
#help("[[") o #help.start()
```
Para almacenar objetos se usa $<-$ o $=$ (asignaci?n) de la siguiente manera
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
a<-2
b<-rnorm(5,0,1)
```
Para presentar los valores almacenados se escribe de nuevo el nombre de la variable
```{r ,warning=F,eval=T,message=F,comment=" ",echo=F,error=F,results='markup'}
a<-2
a
b<-rnorm(5,0,1)
b
```
##Estructura de datos
Los tipos de datos que R tiene son:
- Vectores
- Factores
- Matrices
- Data.frame
- Listas
## Vectores
Existen clases de vectores: num?ricos o caracteres.
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
##Creando vectores
a<-c(1,5,6,8,4); a
b<-runif(n = 5,min = 0,max = 100);b
b<-round(b,2);b
```
##
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
c<-c("Quito","Ambato","Guayaquil","Cuenca");c
d<-seq(1,100,1);d
e<-rep("No Informa",10);e
```
## Seleccionar un elemento de un vector
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
x = c(18,11,12,10,7,6,17)
x[c(1,3,6)]
x[-3]
x[-c(1,2)]
```
##
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
#Especificar una condici?n l?gica. En el caso del vector x creado arriba:
x>10
x[x>10]
s <- "<NAME>";s
```
##
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
class(s)
length(s)
nchar(s)
substr(s, 5, 10)
```
##
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
substring(s, 1, 5)
substr(s, 5, rep(8, 3))
substring(s, 5, rep(8, 3))
substr(s, 5, 8) <- "-";s
```
##
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
a<-"Ecuador"
b<-"Quito"
c
paste(a,b)
match("Cuenca",c)
pmatch("Cue",c)
```
##
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
texto <- c("Handel", "Haendel","H?andel","Handemore","Mendel","Handle")
patron <- "H[a|?a](e)?ndel"
musicos <- grep(patron, texto)
texto[musicos]
```
## Factores
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
estudiantes.origen<-c("getafe","mostoles","madrid","madrid","mostoles",
"leganes","getafe","leganes","madrid","mostoles",
"parla","alcorcon","mostoles","getafe","leganes")
festudiantes<-as.factor(estudiantes.origen)
levels(festudiantes)
summary(festudiantes)
estudiantes.estaturas <- c(1.83, 1.71, 1.79, 1.64, 1.74,
1.81, 1.62, 1.84, 1.68, 1.81,
1.82, 1.74, 1.84, 1.61, 1.84)
```
##Matrices
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
t(matrix(1:6))
matrix(1:6,nrow=2)
matrix(1:6,nrow=2,byrow=T)
```
##Data Frame
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
data<-data.frame(iris)
summary(cars)
```
##
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
str(iris)
iris[1,]
```
##
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
iris[2, 5]
(x <- cbind(iris[1:5,], nuevaCol=1:5))
```
##
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
head(x)
```
##
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
plot(iris)
```
## Funciones
```{r ,warning=F,eval=T,message=F,comment=" ",echo=T,error=F,results='markup'}
f <- function(v) {
v <- v[!is.na(v)]
p <- sum(v) / length(v)
p
}
x<-c(5,12,35,489,132,NA,132,12,NA)
f(x)
```
<file_sep>/script1.R
setwd("C://Users//<NAME>//Documents//Ministerio de competitividad//curso")
getwd()
dir()
#Ayuda sobre funci?n o capacidad
help(solve)
help(mean)
?solve
help("[[")
help.start()
help(rnorm)
####Asiganar
a<-2
set.seed(12456)
b<-rnorm(5,25,2)
a
b
##Creando vectores
a<-c(1,5,6,8,4);a
b<-runif(n = 5,min = 0,max = 100);b
b1<-round(b,4);b
##vector caracter
c<-c("Quito","Ambato","Guayaquil","Cuenca");c
d<-seq(1,100,0.5);d
e<-rep("No Informa",10);e
###Extraer una o m?s componentes del vector
x = c(18,11,12,10,7,6,17)
x[c(1,3,6)]
x[-3]
x[-c(1,2)]
#Especificar una condici?n l?gica. En el caso del vector x creado arriba:
x>10
x[x>10]
###Uso de variables de tipo caracter
nim1<-numeric(456)
s <-"<NAME>";s
num<-165465
num<-as.character(num)
class(num)
##Retorna la clase de s
class(s)
###Tama?o de s
length(s)
##N?mero de caracteres que tiene s
nchar(s)
#####Seleciona desde la posici?n 5 a la 10
substr(s, 5, 10)
substring(s, 1, 5)
substr(s, 5, rep(8, 3))
substring(s, 5, rep(8, 3))
substr(s, 5, 8)<-"-";s
a<-"Ecuador"
b<-"Quito"
#Une las dos variables
paste(a,b,collapse="-")
c
##b?squeda de caracteres iguales
##Exactamente igual
match("Cuenca",c)
##parcialmente
pmatch("Cue",c)
####Funci?n grep
texto <- c("Handel", "Haendel","H?andel","Handemore","Mendel","Handle")
patron <- "H[a|?a](e)?ndel"
musicos <- grep(patron, texto)
texto[musicos]
## Factores
estudiantes.origen<-c("getafe","mostoles","madrid","madrid","mostoles",
"leganes","getafe","leganes","madrid","mostoles",
"parla","alcorcon","mostoles","getafe","leganes")
festudiantes<-as.factor(estudiantes.origen)
levels(festudiantes)
summary(festudiantes)
estudiantes.estaturas <- c(1.83, 1.71, 1.79, 1.64, 1.74,
1.81, 1.62, 1.84, 1.68, 1.81,
1.82, 1.74, 1.84, 1.61, 1.84)
tapply(estudiantes.estaturas,festudiantes,mean)
t(matrix(1:6))
matrix(1:6,nrow=2)
matrix(1:6,nrow=2,byrow=T)
data<-data.frame(iris)
View(data)
summary(iris)
str(iris)
data[1,]
data[2, 5]
data$Sepal.Length
data$media<-mean(data$Sepal.Length)
x <- cbind(iris[1:5,], nuevaCol=1:5)
boxplot(iris$Sepal.Length)
head(iris,10)
tabla<-table(iris$Species)
f<- function(v){
v <- v[!is.na(v)]
p <- sum(v) / length(v)
p
}
x<-c(5,12,35,489,132,NA,132,12,NA)
f(x)
#####Ejemplo
attributes(iris)
summary(iris)
names(iris)
table(iris$Species)
setosa<-subset(iris,iris$Species=="setosa")
largo<-iris[which(iris$Sepal.Length==min(iris$Sepal.Length)),]
asd<-iris[1:5,]
asd
asd[-1,]
apply(iris[,1:4],2,mean)
apply(iris[,1:4],2,sum)
by(iris$Sepal.Length,iris$Species,summary)
<file_sep>/script2.R
##SEteamos informaci?n
setwd("~/Ministerio de competitividad/curso")
##cargamos librerias
library("openxlsx")
library(dplyr)
library(openxlsx)
library(plotly)
###leCTURA DE DATA
dir()
data<-read.xlsx("bank-additional-full.xlsx",sheet = 1)
# Descripci?n de variables
# Age: Edad del cliente (Num?rica)
# Job: Ocupaci?n del cliente (Categ?rica)
# Marital: Estado civil (Categ?rica)
# Education: Nivel de eduaci?n del cliente (Categ?rica)
# Default: Indicador de si un cliente tiene un cr?dito por defecto (categ?rica)
# Housing: Indicador de si un cliente tiene un cr?dito hipotecario (Categ?rica)
# Loan: Indicador de si un cliente tiene un cr?dito personal(Categ?rica)
# Contact: Medio por el que se le contacta a un cliente (Categ?rica)
# Month: Mes del ?ltimo contacto (Categ?rica)
# Day_of_week: D?a de la semana del ?ltimo contacto (Categ?rica)
# Duration: Duraci?n del ?ltimo contacto en segundos (Num?rica) [Tiene alto impacto sobre la variable de decisi?n]
# Campaign: N?mero de contactos hechos durante la campa?a para este cliente (Num?rica)
# Pdays: N?mero de d?as desde que se contacto por ?ltima vez en la campa?a anterior (Num?rica)
# Previous: N?mero de contactos hechas antes de esta campa?a (Num?rica)
# Poutcome: Resultado de de la campa?a de marketing previa (Categ?rica)
# Empvarrate: Variaci?n de la tasa de empleo [Indicador de cuartiles] (Num?rica)
# Conspriceidx: Indice de precios al consumidor [Indicador mensual] (Num?rica) (3616 valores perdidos)
# Consconfidx: Indice de confianza del consumidor [Indicador mensual] (Num?rica)
# Euribor3m: Tasa de inter?s bancos europeos [Indicador diario] (Num?rica) (8041 valores perdidos)
# Nremployed: N?mero de empleados[Indicador cuartiles] (Num?rica) (33425 valores perdidos)
#####Variables desconocido
table(data$default)
names(data)
def_desconocida<-sum(as.numeric(data$default=="unknown"))/nrow(data)*100
# Convertimos los datos desconocidos en "yes"
data$default[which(data$default=="unknown")]<-"yes"
str(data)
# Transformaci?n de la naturaleza de las variables
data$cons.price.idx<-as.numeric(data$cons.price.idx)
data$euribor3m<-as.numeric(data$euribor3m)
data$nr.employed<-as.numeric(data$nr.employed)
data$emp.var.rate<-as.numeric(data$emp.var.rate)
data$cons.conf.idx<-as.numeric(data$cons.conf.idx)
summary(data$cons.price.idx)
data$cons.price.idx[which(data$cons.price.idx==min(data$cons.price.idx))]<-min(data$cons.price.idx)*100
data$cons.price.idx[which(data$cons.price.idx==max(data$cons.price.idx))]<-max(data$cons.price.idx)/100
#####Valores at?picos
plot_ly(ggplot2::diamonds, y = data$age,name = "Edad", type = "box",line = list(color = 'rgba(113, 108, 235, 0.7)'))
plot_ly(ggplot2::diamonds, y = data$cons.conf.idx,name = "Cons.conf", type = "box",line = list(color = 'rgba(113, 108, 235, 0.7)'))
q<-quantile(data$age,0.75)-quantile(data$age,0.25)
data$age[which(data$age>quantile(data$age,0.75)+1.5*q)]<-median(data$age)
q<-quantile(data$cons.conf.idx,0.75)-quantile(data$cons.conf.idx,0.25)
data$cons.conf.idx[which(data$cons.conf.idx>quantile(data$cons.conf.idx,0.75)+1.5*q)]<-median(data$cons.conf.idx)
####Concatenar
grep("month",names(data))
data$fecha<-do.call(paste, c(data[c(10,11)], sep = "/"))
fecha1<-"2016-04-16"
class(fec)
fec<-as.Date(fecha1,format = '%Y-%m-%d')
#####Ejemplo Valores perdidos
na_count <- sapply(data2, function(y) sum(length(which(is.na(y)))))
na_count
###Leyendo la data para valores perdidos
data2<-read.csv("adult.csv",sep = ",")
###IDENTIFICAMOS LOS NA
is.na(data2) <- data2=='?'
is.na(data2) <- data2==' ?'
#######UNA TABLA DE LOS NA EXISTENTES
na_count <- sapply(data, function(y) sum(length(which(is.na(y)))))
na_count
###vISUALIZACIN DE DATOS PERDIDOS
library(VIM)
aggr_plot <- aggr(data2, col=c('navyblue','red'), numbers=TRUE,
sortVars=TRUE, labels=names(data),
cex.axis=.7, gap=3,
ylab=c("Histograma de datos perdidos ","Patrones"))
####cAMBIAMOS POR LA MEDIA
### Con valores perdidos
mean(data2$age)
## Sin valores perdidos
m <- floor(mean(na.omit(data2$age)))
data2$age[which(is.na(data2$age))]<-m
###Metodos del paquete mice
write.csv(data2,"basefinal.csv")
library(xlsx)
write.xlsx(data2, "base.xlsx")
#####imputación de valores perdidos. ejemplo
library(mice)
library(lattice)
library(dplyr)
####Crgando base:Ejemplo datos se simula en base a la Fase 1 de la Tercera Encuesta Nacional
#de Examen de Salud y Nutrición (NHANES) por el Centro Nacional de Estadísticas de Salud
data(nhanes)
###ESTUDIANDO LA VARIABLE EDAD
table(nhanes$age)
class(nhanes$age)
####Está agrupada en 3 grupos 20-39,40-59,60+
### Se transforma a factor para tener una variable categórica
nhanes$age = factor(nhanes$age)
##Se observa los patrones de los datos perdidos
md.pattern(nhanes)
####Dibujando la base de datos perida
nhanes_aggr = aggr(nhanes, col=mdc(1:2), numbers=TRUE, sortVars=TRUE,
labels=names(nhanes), cex.axis=.7, gap=3,
ylab=c("Proportion of missingness","Missingness Pattern"))
#####Margin plot
marginplot(nhanes[, c("chl", "bmi")], col = mdc(1:2), cex.numbers = 1.2, pch = 19)
# Estamos interesados en la regresión lineal simple de chl en edad y bmi
# Eliminar casos con valores perdidos (análisis de caso completo),
#y ajustar un modelo lineal,
fit.cc = lm(chl ~ age + bmi, data=nhanes)
summary(fit.cc)
###Qué hace la librería mice
#mice()imputa cada valor que falta con un valor plausibles (simula un valor de relleno en la que se perdió) hasta que todos los valores que faltan se imputan y se completa el conjunto de datos. Repite el proceso varias veces para, dicen m veces y tiendas de todo el m completa (d) / conjuntos de datos imputados.
#with()analiza cada uno de los conjuntos de datos basados m completado por separado en el modelo de análisis que desee.
#pool()combina (agrupaciones) todos los resultados juntos sobre la base de reglas de Rubin (Rubin, 1987).
#Para la imputación de los datos usa el método de cadenas de Markov monte carlo
#usa la corrlación de la estructura de la base con los datos perdidos
# es un proceso iterativo se la realiza m veces
imp = mice(nhanes, m=5, printFlag=FALSE, maxit = 40, seed=2525)
#la salida de mice contiene m = 5 conjuntos de datos completados. Cada conjunto de datos puede ser analizado
# Usando la función with(), e incluyendo una expresión para el enfoque de análisis estadístico
fit.mi = with(data=imp, exp = lm(chl ~ age + bmi))
#Combina los valores de los 5 dataset con la función pool
combFit = pool(fit.mi)
##Resultado de la regresión
round(summary(combFit),2)
##Para revisar el ajuste se estudia el r cuadrado
pool.r.squared(fit.mi)
#ver más información
#http://web.maths.unsw.edu.au/~dwarton/missingDataLab.html
#####Análisis de
library(tm)
library(slam)
library(wordcloud)
# lee el documento UTF-8 y lo convierte a ASCII
file.choose()
dir()
txt <- readLines("discurso 2013.txt" ,encoding="UTF-8")
txt = iconv(txt, to="ASCII//TRANSLIT")
# construye un corpus
corpus = Corpus(VectorSource(txt))
# convierte a min?sculas
corpus = tm_map(corpus, PlainTextDocument)
##
# quita espacios en blanco
d <- tm_map(corpus, stripWhitespace)
# remueve la puntuaci?n
d <- tm_map(d, removePunctuation)
##
sw <- readLines("stopwords.es.txt",encoding="UTF-8")
sw = iconv(sw, to="ASCII//TRANSLIT")
# remueve palabras vac?as personalizada
corpus = tm_map(corpus, removeWords, sw)
# remove espacios en blanco extras
corpus = tm_map(corpus, stripWhitespace)
# remueve palabras vacías genéricas
d <- tm_map(d, removeWords, stopwords("spanish"))
# remueve palabras vacías personalizadas
d <- tm_map(d, removeWords, sw)
# crea matriz de terminos
tdm <- TermDocumentMatrix(d)
#####Presenta las palabras con frecuencia mínima de 20
findFreqTerms(tdm, lowfreq=20)
####Convirtiendo en matriz
m <- as.matrix(tdm)
#####ordenando las palabras
v <- sort(rowSums(m),decreasing=TRUE)
####Cambiando a data.frame
df <- data.frame(word = names(v),freq=v)
###Esto es para borrar palabras que no fueron filtradas
df <- df[c(-7,-29,-35,-49),]
####Dibujar la nube de palabras
wordcloud(df$word, df$freq, random.order=FALSE, min.freq=8,colors=brewer.pal(4, "Dark2"))
|
6b1f25c919a7f774220b9a7d09b7286eb6f2e0f9
|
[
"R",
"RMarkdown"
] | 3 |
RMarkdown
|
Anyju/Mcpec1
|
bae59244c5c7c6fcb5ed7c4f902bed307b6e8aa1
|
cacee286ada740f1b89a60cd2090ceec6fd50a0b
|
refs/heads/master
|
<repo_name>jojello/repo<file_sep>/src/Search.js
import React, { Component } from "react";
import searchImg from "./images/search.png";
import classnames from "classnames/bind";
import App from "./css/App.css";
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchActive: false
};
this.addActiveClass = this.addActiveClass.bind(this);
}
addActiveClass() {
const currentState = this.state.searchActive;
this.setState({
searchActive: !currentState
});
}
render() {
return (
<header>
<section className="container">
<section id="search">
<div className={this.state.searchActive ? "activeclass" : null}>
<input type="text" name="name" />
</div>
<a href="#" onClick={this.addActiveClass}>
<img src={searchImg} alt="" />
</a>
</section>
<div className="clearfix" />
</section>
</header>
);
}
}
export default Search;
<file_sep>/src/Article.js
import React, { Component } from "react";
import PropTypes from "prop-types";
import ajaxloader from "./images/ajax_loader.gif";
class Article extends Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.onPopup(this.props.title, this.props.category, this.props.url);
}
render() {
return (
<article className="article">
<section className="featuredImage">
<img src={this.props.urlImage} alt="" />
</section>
<section className="articleContent">
<a onClick={this.handleClick}>
<h3>{this.props.title}</h3>
</a>
<h6>{this.props.category}</h6>
</section>
<section className="impressions">{this.props.score}</section>
<div className="clearfix" />
</article>
);
}
}
Article.PropTypes = {
title: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
category: PropTypes.string,
impressions: PropTypes.number,
urlImage: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
};
export default Article;
<file_sep>/src/Popup.js
import React, { Component } from "react";
import PropTypes from "prop-types";
import Article from "./Article";
class Popup extends Component {
constructor(props) {
super(props);
this.state = {
title: "",
category: "",
url: ""
};
this.getPopupInfo = this.getPopupInfo.bind(this);
this.handleClosePopup = this.handleClosePopup.bind(this);
this.handleClickthroughURL = this.handleClickthroughURL.bind(this);
}
getPopupInfo(title, description, url) {
this.setState({
title: title,
category: description,
url: url
});
}
handleClosePopup(e) {
e.preventDefault();
if (this.props.onClose) {
this.props.onClose();
}
}
handleClickthroughURL(e) {
e.preventDefault();
}
render() {
if (this.props.isOpen === false) {
return null;
}
return (
<div className="popUp">
<a
href="#"
className="closePopUp"
onClick={e => this.handleClosePopup(e)}
>
X
</a>
<div className="container" getPopupInfo={this.getPopupInfo}>
<h2>title</h2>
<h4>{this.props.category}</h4>
<a href={this.props.url} className="popUpAction" target="_blank">
Read More
</a>
</div>
</div>
);
}
}
Popup.PropTypes = {
onClose: PropTypes.func.isRequired,
title: PropTypes.string,
showPopup: PropTypes.bool,
href: PropTypes.string.isRequired
};
export default Popup;
<file_sep>/src/Fetchapi.js
const fetchDigg = () => {
return fetch(
"https://accesscontrolalloworiginall.herokuapp.com/http://digg.com/api/news/popular.json"
)
.then(results => results.json())
.then(results => {
let diggArticles = results.data.feed.map(article => {
return {
title: article.content.title_alt,
description: article.content.description,
url: article.content.original_url,
score: article.dig_score,
image: article.content.media.images[0].image_url,
category: article.content.tags[0].name,
source: "digg"
};
});
return diggArticles;
});
};
// function fetchMash (){} - means the same thing
const fetchMash = () => {
return fetch(
"https://accesscontrolalloworiginall.herokuapp.com/https://newsapi.org/v2/everything?sources=mashable&apiKey=48117437669b4c599e55ad484c86d8e6"
)
.then(results => results.json())
.then(results => {
let mashArticles = results.articles.map(article => {
return {
title: article.title,
description: article.description,
url: article.url,
score: article.publishedAt,
image: article.urlToImage,
category: article.description,
source: "mash"
};
});
return mashArticles;
});
};
const fetchABC = () => {
return fetch(
"https://accesscontrolalloworiginall.herokuapp.com/https://newsapi.org/v2/top-headlines?sources=abc-news-au&apiKey=48117437669b4c599e55ad484c86d8e6"
)
.then(results => results.json())
.then(results => {
let abcArticles = results.articles.map(article => {
return {
title: article.title,
description: article.description,
url: article.url,
score: article.publishedAt,
image: article.urlToImage,
category: article.description,
source: "abc"
};
});
return abcArticles;
});
};
export { fetchABC, fetchMash, fetchDigg };
|
fe4c6ff33e86d339ff7407cc6cb2619523ada6ff
|
[
"JavaScript"
] | 4 |
JavaScript
|
jojello/repo
|
4db1f76b0cef9cd1eec56e6fc62059820665c013
|
a519fe3b6471458aa6c9139b48113148e3bc075e
|
refs/heads/master
|
<repo_name>Daniil-Kuchuk/C_public<file_sep>/prgrm_2.c
// ЗАДАЧА 1
#include <stdio.h>
#include <math.h>
int main()
{
int x, y, z;
float b;
printf("x = "); scanf("%d", &x);
printf("y = "); scanf("%d", &y);
printf("z = "); scanf("%d", &z);
b = ( 1 + pow( cos(y - x), 3 ) ) / ( pow(x, 2) / 2 + pow( sin(z), 2) );// ---проверить все степени---
printf("ответ: %f\n", b);
//----------------------------------------
// ЗАДАЧА 2
int n, count;
printf("n = "); scanf("%d", &n);
for (int i = 1; i <= n; i++)
if (i % 11 == 0 || i % 5 == 0)
count++;
printf("%d", n - count);
//----------------------------------
return 0;
}
<file_sep>/prgrm5.c
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
int pop(int [], int*);
void push(int [], int*);
int main(int argc, char const *argv[])
{
int *arr, x, n;
printf("Введите кол-во элементов: ");
scanf("%d", &n);
arr = (int*)malloc( n * sizeof(int) );
for (int i = 0; i < n; i++)
{
printf("arr[%d] = ", i);
scanf("%d", &arr[i]);
}
x = pop(arr, &n);
printf("\nx = %d\n", x);
// for (int i = 0; i < n; i++)
// printf("arr[%d] = %d ", i, arr[i]);
printf("\n");
push(arr, &n);
// for (int i = 0; i < n; i++)
// printf("arr[%d] = %d ", i, arr[i]);
return 0;
}
int pop(int arr[], int* size)
{
if (!*size)
{
printf("В массиве отстутствуют элементы!");
return NULL;
}
*size -= 1;
int end_element = arr[*size];
arr = (int*)realloc( arr, *size * sizeof(int) );
return end_element;
}
void push(int arr[], int* size)
{
int add_element;
printf("new element: ");
scanf("%d", &add_element);
*size += 1;
arr = (int*)realloc( arr, *size * sizeof(int) );
arr[*size] = add_element;
}<file_sep>/prgrm_4.c
#include <stdio.h>
#include <stdlib.h>
main()
{
int n;
printf("Введите ков-во элементов = ");
scanf("%d",&n);
int *arr;
arr = (int*) malloc(n * sizeof(int) );
for(int i = 0; i < n; i++)
arr[i] = i;
arr[1] = 0;
for(int i = 2; i < n; i++)
if( arr[i] )
for(int j = i * 2; j < n; j += i)
arr[j] = 0;
for(int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
int count = 0;
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
if ( arr[j] )
{
arr[i] = arr[j];
arr[j] = 0;
count++;
break;
}
arr = (int*) realloc( arr, count * sizeof(int) );
for(int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}<file_sep>/prgrm.c
#include <stdio.h>
#include <math.h>
int main()
{
int x = 2;
float z = 1, y;
for (int i = 0; i < 100; i++)
{
y = 1.5 * z - 0.5 * x * pow(z, 3);
z = y;
printf("1 - %.5f\n", y);
}
return 0;
}<file_sep>/kr_v1_z2.c
#include <stdio.h>
#define ARR_1_SIZE 5
#define ARR_2_SIZE 3
void f2(int [][ARR_2_SIZE], int);
void f(int [][ARR_1_SIZE], int);
int main()
{
int arr1[ARR_1_SIZE][ARR_1_SIZE] = {{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}, {16,17,18,19,20},{21,22,23,24,25}};
int arr2[ARR_2_SIZE][ARR_2_SIZE] = {{5, 3, 7}, {-1, -3, -5}, {4, 7, 9}};
// for (int i = 0; i < ARR_1_SIZE; i++)
// for (int j = 0; j < ARR_2_SIZE; j++)
// {
// printf("arr[%d][%d] = ", i, j);
// scanf("%d", &arr1[i][j]);
// }
for (int i = 0; i < ARR_1_SIZE; i++)
for (int j = 0; j < ARR_1_SIZE; j++)
printf("arr[%d][%d] = %d \n", i, j, arr1[i][j]);
printf("\n");
f(arr1, ARR_1_SIZE);
f2(arr2, ARR_2_SIZE);
for (int i = 0; i < ARR_1_SIZE; i++)
for (int j = 0; j < ARR_1_SIZE; j++)
printf("arr[%d][%d] = %d \n", i, j, arr1[i][j]);
printf("\n");
for (int i = 0; i < ARR_2_SIZE; i++)
for (int j = 0; j < ARR_2_SIZE; j++)
printf("arr2[%d][%d] = %d \n", i, j, arr2[i][j]);
}
void f(int arr[][ARR_1_SIZE], int size)
{
int val;
int i = 0;
for (int j = 0; j < size; j++)
{
val = arr[i][j];
arr[i][j] = arr[size - 1 - j][size - 1 - i];
arr[size - 1 - j][size - 1 - i] = val;
}
}
void f2(int arr[][ARR_2_SIZE], int size)
{
int val;
int i = 0;
for (int j = 0; j < size; j++)
{
val = arr[i][j];
arr[i][j] = arr[size - 1 - j][size - 1 - i];
arr[size - 1 - j][size - 1 - i] = val;
}
}
<file_sep>/valInput.h
int getInt();
int getInt()
{
int val;
while (scanf("%d", &val) == 0)
{
rewind(stdin);
continue;
}
return val;
}
float getFloat()
{
float val;
while (scanf("%f", &val) == 0)
{
rewind(stdin);
continue;
}
return val;
}<file_sep>/calcE.c
#include <stdio.h>
#include "valInput.h"
double calcE(int iter);
int fact(int val);
int main()
{
int n;
printf("Введите кол-во знаков: ");
n = getInt();
double result = calcE(n);
printf("%.7f", result);
return 0;
}
double calcE(int iter)
{
double e = 2;
for (int i = 2; i <= iter; i++)
{
int f = fact(i);
e += (double)1 / f;
}
return e;
}
int fact(int val)
{
int factorial = 1;
int count = val;
while (count)
{
factorial *= count;
count--;
}
return factorial;
}<file_sep>/array.c
#include <stdio.h>
#include <math.h>
#define SIZE 10
int maximum(int arr[], int size);
int main()
{
int arr[SIZE] = {12, 5, 700, -18, 9, 100, 8, 11, -2300, 15};
int max;
max = maximum(arr, SIZE);
printf("%d", max);
return 0;
}
int maximum(int arr[], int size)
{
int max = arr[0];
int index = 0;
while (index < SIZE)
{
if (abs(max) < abs( arr[index] ))
{
max = arr[index];
}
index++;
}
return max;
}<file_sep>/random.c
#include <stdio.h>
#include <math.h>
int main()
{
int rand;
rand = random( time(20) );
printf("%d", rand);
}<file_sep>/calcE_alg_2.c
#include <stdio.h>
double calcE();
double calculate(double, int);
int main()
{
double result = calcE();
printf("%.11f", result);
return 0;
}
double calcE()
{
double e = 0;
double result = 1;
int count = 0;
result += 1 / calculate(e, count);
return result;
}
double calculate(double e, int count)
{
if (count < 11)
{
count++;
if (count % 2)
e += count - 1 / calculate(e, count);
else
e += count + 1 / calculate(e, count);
}
return e;
}<file_sep>/kr_v1_z1.c
#include <stdio.h>
#define SIZE 10
void strToInt(char [], int);
int main(int argc, char const *argv[])
{
char arr[] = {'a', '9', 'w', '5', '7', '8', 'e', 'd', '1', 'h'};
for (int i = 0; i < SIZE; i++)
printf("%c ", arr[i]);
printf("\n");
strToInt(arr, SIZE);
for (int i = 0; i < SIZE; i++)
printf("%c ", arr[i]);
return 0;
}
void strToInt(char arr[], int size)
{
for (int i = 0; i < size; i++)
switch (arr[i])
{
case 0x30:
arr[i] = '#'; break;
case 0x31:
arr[i] = '#'; break;
case 0x32:
arr[i] = '#'; break;
case 0x33:
arr[i] = '#'; break;
case 0x34:
arr[i] = '#'; break;
case 0x35:
arr[i] = '#'; break;
case 0x36:
arr[i] = '#'; break;
case 0x37:
arr[i] = '#'; break;
case 0x38:
arr[i] = '#'; break;
case 0x39:
arr[i] = '#'; break;
}
}
|
22a31a33beedf4033724501f13ebb62249621b39
|
[
"C"
] | 11 |
C
|
Daniil-Kuchuk/C_public
|
b7a0598e41264c1b5258417c3839ac2e0e771ff3
|
f825855fb3ab53e0c5b2e5cb684e3b7fe01b973d
|
refs/heads/master
|
<file_sep>//pm2
// pm2 start main.js
// pm2 stop main.js
// pm2 monit
// pm2 list
// --use--
// pm2 start main.js --watch
// pm2 log
// pm2 kill
// pm2 start main.js --watch --ignore-watch="data/*" --no-daemon //pm2 + log<file_sep>var args = process.argv[2];
//2번째 자리 출력
console.log(args);<file_sep>var name = 'eging';
var letter = 'abc' + name + 'def';
console.log(letter);<file_sep>while(true){
console.log('C1');
}<file_sep>console.log('1+1'.length);<file_sep>// array, object
var f = function f1(){ //함수는 값이 될 수 있다.
console.log(1+1);
console.log(1+2);
}
console.log(f);
f();
var a = [f];
a[0](); //배열의 원소로서 함수가 가능
var o = {
func:f
}
o.func();
|
4bf2f2712db569fc3dbf99b1f90d7eb721b238a0
|
[
"JavaScript"
] | 6 |
JavaScript
|
pgshoot13/nodelogin_ex
|
23ac86692c4b7599f074ec5436585c359ca599c3
|
0f9f0ceacfe8d1736230d516000ac475771e8b21
|
refs/heads/master
|
<file_sep><?php
namespace Tests\Grid;
use ArrayAccess;
use QueryGrid\QueryGrid\Columns\Column;
use QueryGrid\QueryGrid\Columns\ColumnCollection;
use QueryGrid\QueryGrid\Columns\Formatters\Date;
use QueryGrid\QueryGrid\GridResult;
use QueryGrid\QueryGrid\RowCollection;
use Tests\Fixtures\UserEntity;
class GridResultTest extends \Tests\TestCase
{
/** @test */
public function itGetsColumns()
{
$columns = new ColumnCollection();
$result = new GridResult($columns);
$resultColumns = $result->getColumns();
$this->assertEquals($columns, $resultColumns);
}
/** @test */
public function itGetsRows()
{
$columns = new ColumnCollection();
$columns->add(new Column('name', 'Name'));
$result = new GridResult($columns);
$result->setRows([
[
'name' => 'Andrew',
'email' => '<EMAIL>',
'created_at' => '1920-05-20',
],
[
'name' => 'Rachel',
'email' => '<EMAIL>',
'created_at' => '1940-05-20',
],
]);
$this->assertInstanceOf(RowCollection::class, $result->getRows());
$this->assertCount(2, $result->getRows());
$this->assertEquals([
[
'name' => 'Andrew',
],
[
'name' => 'Rachel'
]
], $result->getRows()->all());
}
/** @test */
public function itFormatsRows()
{
$columns = new ColumnCollection();
$column = new Column('name', 'Name');
$column->withFormat(function ($value) {
return 'NAME.' . $value;
});
$columns->add($column);
$column = new Column('startedOn', 'Name');
$column->fromField('created_at');
$column->withFormat(new Date('Y-m-d', 'd/m/Y'));
$columns->add($column);
$result = new GridResult($columns);
$result->setRows([
[
'name' => 'Andrew',
'email' => '<EMAIL>',
'created_at' => '1920-05-20',
],
[
'name' => 'Rachel',
'email' => '<EMAIL>',
'created_at' => '1940-05-20',
],
]);
$this->assertInstanceOf(RowCollection::class, $result->getRows());
$this->assertCount(2, $result->getRows());
$this->assertEquals([
[
'name' => 'NAME.Andrew',
'startedOn' => '20/05/1920',
],
[
'name' => 'NAME.Rachel',
'startedOn' => '20/05/1940',
]
], $result->getRows()->all());
}
/** @test */
public function itParsesArrayAccessableObjects()
{
$columns = new ColumnCollection();
$column = new Column('name', 'Name');
$column->withFormat(function ($value) {
return 'NAME.' . $value;
});
$columns->add($column);
$column = new Column('startedOn', 'Name');
$column->fromField('created_at');
$column->withFormat(new Date('Y-m-d', 'd/m/Y'));
$columns->add($column);
$result = new GridResult($columns);
$result->setRows([
new UserEntity('Andrew', '<EMAIL>', '1920-05-20'),
new UserEntity('Rachel', '<EMAIL>', '1940-05-20'),
]);
$this->assertInstanceOf(RowCollection::class, $result->getRows());
$this->assertCount(2, $result->getRows());
$this->assertEquals([
[
'name' => 'NAME.Andrew',
'startedOn' => '20/05/1920',
],
[
'name' => 'NAME.Rachel',
'startedOn' => '20/05/1940',
]
], $result->getRows()->all());
}
/** @test */
public function itParsesNestedValues()
{
$columns = new ColumnCollection();
$column = new Column('name', 'Name');
$column->fromField('name.first');
$columns->add($column);
$result = new GridResult($columns);
$result->setRows([
[
'name' => [
'first' => 'Andrew',
],
],
[
'name' => [
'first' => 'Rachel',
],
],
]);
$this->assertInstanceOf(RowCollection::class, $result->getRows());
$this->assertCount(2, $result->getRows());
$this->assertEquals([
[
'name' => 'Andrew',
],
[
'name' => 'Rachel',
]
], $result->getRows()->all());
}
/** @test */
public function itFailsQuietlyForMissingValues()
{
$columns = new ColumnCollection();
$column = new Column('name', 'Name');
$column->fromField('name.last');
$columns->add($column);
$result = new GridResult($columns);
$result->setRows([
[
'name' => [
'first' => 'Andrew',
],
],
[
'name' => [
'first' => 'Rachel',
],
],
]);
$this->assertInstanceOf(RowCollection::class, $result->getRows());
$this->assertCount(2, $result->getRows());
$this->assertEquals([
[
'name' => '',
],
[
'name' => '',
]
], $result->getRows()->all());
}
/** @test */
public function itHandlesMissingRows()
{
$columns = new ColumnCollection();
$column = new Column('name', 'Name');
$column->withFormat(function ($value) {
return 'NAME.' . $value;
});
$columns->add($column);
$result = new GridResult($columns);
$result->setRows([['name' => null]]);
$rows = $result->getRows();
$this->assertInstanceOf(RowCollection::class, $result->getRows());
$this->assertEquals([
[
'name' => null,
]
], $rows->all());
}
}
<file_sep><?php
namespace Tests\Fixtures;
use QueryGrid\QueryGrid\Columns\OrderBy;
use QueryGrid\QueryGrid\Contracts\DataProvider;
use QueryGrid\QueryGrid\Query;
class DataProviderSpy implements DataProvider
{
private $resource;
public $values = [];
private $filters = [];
private $query;
private $orderBy = [];
public function getResource(): string
{
return $this->resource;
}
public function setResource(string $resource)
{
$this->resource = $resource;
}
public function setValues($data)
{
$this->values = $data;
}
public function get(): array
{
return $this->values;
}
public function setFilters(array $filters)
{
$this->filters = $filters;
}
public function getFilters()
{
return $this->filters;
}
public function setQuery(Query $query)
{
$this->query = $query;
}
public function getQuery(): ?Query
{
return $this->query;
}
public function getOrderBy()
{
return $this->orderBy;
}
public function addOrderBy(OrderBy $orderBy)
{
$this->orderBy[] = $orderBy;
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Columns\Formatters;
class Date
{
/** @var string */
private $from;
/** @var string */
private $to;
/**
* Date constructor.
* @param string $from
* @param string $to
*/
public function __construct(string $from, string $to)
{
$this->from = $from;
$this->to = $to;
}
/**
* @param string $date
* @return string
*/
public function __invoke(string $date): string
{
$dateTime = \DateTime::createFromFormat($this->from, $date);
if ($dateTime !== false) {
return $dateTime->format($this->to);
}
return '';
}
}
<file_sep><?php
namespace Tests\Columns\Formatters;
use Tests\TestCase;
use QueryGrid\QueryGrid\Columns\Formatters\DateDiff;
class DateDiffTest extends TestCase
{
/** @test */
public function itIsCreatable()
{
$dateDiff = new DateDiff('Y-m-d', '%y');
$this->assertEquals(5, $dateDiff->withFromDate('2000-01-01')('2005-01-01'));
}
/** @test */
public function itReturnsEmptyStringForInvalidDates()
{
$dateDiff = new DateDiff('Y-m-d', '%y');
$this->assertEquals('', $dateDiff->withFromDate('342')('2005-01-01'));
$this->assertEquals('', $dateDiff->withFromDate('2000-01-01')('fnbr'));
}
}
<file_sep><?php
namespace Tests;
use QueryGrid\QueryGrid\RowCollection;
class RowCollectionTest extends TestCase
{
/** @test */
public function itIsPopulated()
{
$collection = new RowCollection();
$rows = [
['salutation' => 'Hello'],
['salutation' => 'Hey'],
['salutation' => 'Hi'],
['salutation' => 'Howdy'],
];
$collection->populate($rows);
$this->assertEquals($rows, $collection->all());
}
public function itIsMapped()
{
$collection = new RowCollection();
$rows = [
['salutation' => 'Hello'],
['salutation' => 'Hey'],
['salutation' => 'Hi'],
['salutation' => 'Howdy'],
];
$collection->populate($rows);
$mapped = $collection->map(function ($row) {
$row['test'] = 1;
return $row;
});
$this->assertEquals([
[
'salutation' => 'Hello',
'test' => 1,
],
[
'salutation' => 'Hey',
'test' => 1,
],
[
'salutation' => 'Hi',
'test' => 1,
],
[
'salutation' => 'Howdy',
'test' => 1,
],
], $mapped->all());
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Contracts;
use Closure;
interface Collection extends \ArrayAccess, \Countable, Arrayable, \Iterator
{
/**
* @param Closure $callable
* @return Collection
*/
public function map(Closure $callable): Collection;
/**
* @param Closure $callable
* @return Collection
*/
public function filter(Closure $callable): Collection;
/**
* @return Collection
*/
public function unique(): Collection;
/**
* @return array
*/
public function all(): array;
/**
* @param mixed $index
* @return mixed
*/
public function get($index);
/**
* @param Closure $key
* @param Closure|null $value
* @return array
*/
public function keyBy(Closure $key, Closure $value = null): array;
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Collections;
class Collection extends CollectionAbstract
{
/**
* @param mixed $value
* @return void
*/
public function add($value)
{
$this->append($value);
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Columns;
class FilterException extends \RuntimeException
{
/**
* @param string $type
* @return FilterException
*/
public static function unknownFilterType(string $type)
{
return new static("Trying to set an unknown filter type: {$type}");
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Columns;
class OrderBy
{
/** @var string */
private $field;
/** @var bool */
private $descending = false;
/**
* OrderBy constructor.
* @param string $field
*/
public function __construct(string $field)
{
$this->field = $field;
}
/**
* @return string
* @return void
*/
public function getField(): string
{
return $this->field;
}
/**
* @return bool
*/
public function isDescending(): bool
{
return $this->descending;
}
/**
* @param bool $descending
* @return void
*/
public function setDescending($descending = false)
{
$this->descending = $descending;
}
}
<file_sep><?php
namespace Tests\Columns;
use Tests\TestCase;
use QueryGrid\QueryGrid\Columns\OrderBy;
class OrderByTest extends TestCase
{
/** @test */
public function itCanParseOrderByString()
{
$orderBy = new OrderBy('name');
$this->assertEquals('name', $orderBy->getField());
$this->assertFalse($orderBy->isDescending());
}
/** @test */
public function itCanCreateADescendingOrderBy()
{
$orderBy = new OrderBy('name');
$orderBy->setDescending(true);
$this->assertEquals('name', $orderBy->getField());
$this->assertTrue($orderBy->isDescending());
}
}
<file_sep><?php
namespace Tests\Grid;
use Tests\Fixtures\DataProviderSpy;
use Tests\TestCase as BaseTestCase;
use QueryGrid\QueryGrid\Grid;
class TestCase extends BaseTestCase
{
/**
* @var DataProviderSpy
*/
protected $dataProvider;
public function setUp()
{
$this->dataProvider = new DataProviderSpy();
}
/**
* @param array $queryParams
* @return Grid
*/
protected function itHasAGridInstance(): Grid
{
return new Grid($this->dataProvider);
}
}
<file_sep>Query Grid
----------
Framework Agnostic DataGrid / Query Builder implementation.
_Everybody loves badges, check ours out:_
[](https://travis-ci.org/query-grid/query-grid)
[](https://scrutinizer-ci.com/g/query-grid/query-grid/?branch=master)
[](https://scrutinizer-ci.com/g/query-grid/query-grid/?branch=master)
[](https://styleci.io/repos/151885472)
## Installation
`composer require query-grid/query-grid`
## Usage
_You'll need to create an implementation of the `QueryGrid\QueryGrid\Contracts\DataProvider` interface in order to query the data._
```php
$grid = new \QueryGrid\QueryGrid\Grid($dataProvider);
$grid->setResource('users'); // The resource sent to the data provider for the query.
$grid->addColumn('id', '#');
$grid->addColumn('name', 'Name');
$grid->addColumn('started', 'Start Date');
$result = $grid->getResult();
```
if you need to do more with columns, the `addColumn` method returns the column, so you can set the field mapping,
filters, formatting, mark as sortable or queryable:
```php
$column = $grid->addColumn('age', 'Age');
$column->fromField('dob');
$column->sortable();
$column->addFilter(Filter::LESS_THAN);
$column->formatter(new DateDiff('Y-m-d', '%y'));
```
## Filters and queries
What are filters and what are queries?
In this package, a filter is a field which, when set, it's value MUST match, so if you have 5 filters, and they've all
been provided, all 5 of the filters must match.
A query is one string which can match many fields, but only one of the fields need to match.
For example, if you have a user with 'hobbies' and 'work_history' fields, you could mark them both as queryable, then
provide a query string which will search both fields return the row if either field matches.
If the user also as `date_of_birth`, `role`, and `name` fields, and you apply filters to them, if the filter is provided,
it `MUST` match.
You can provide a query and filters in the same request too.
_Just because this is how I say that they should work in the package, unless you're using an officially supported
`DataProvider` then I can not guarantee this be the case, in fact, if you would rather it worked a different way,
I recommend creating your own data provider to treat filters, sorting and queries any way you want._
## Using queries, filters and sorting
when you call `$grid->getResult()` you can optionally pass through an array represending the
query. The array can have four optional params:
- filters
- query
- sort
- page
Of these, page is related to pagination, telling the grid the current page for data.
### Filters
Filters are a `key:value` representation of a filter query.
The filter key is defined automatically when you add a filter to the grid column.
```php
$column = $grid->addColumn('name', 'Full Name');
$column->fromField('full_name');
$column->addFilter(Filter::CONTAINS);
$column->addFilter(Filter::STARTS_WITH);
$column->addFilter(Filter::ENDS_WITH);
```
This definition does three things:
- Defines a grid column with the key `name` and label `Full Name`
- Defines a field `full_name` which we map the field from
- adds a `CONTAINS` filter to the query.
when you call `$grid->getResult()`, if you pass the following array:
```php
$grid->getResult([
'filters' => [
'name.con' => 'dre',
],
]);
```
This will create a `Filter::CONTAINS` query on the `full_name` field with the value `dre`.
```php
$grid->getResult([
'filters' => [
'name.st' => 'and',
],
]);
```
Will create a `Filter::STARTS_WITH` query.
The dot syntax for keys, as you probably can tell, follows a `{key}.{filter}` syntax.
When converting the columns to arrays, it includes an array of filters on the fields:
```php
[
[
'key' => 'name',
'label' => '<NAME>',
'sortable' => false,
'queryable' => false,
'filterable' => true,
'filters' => [
'name.con' => [
'type' => 'con', // Filter::CONTAINS
'name' => '',
],
'name.st' => [
'type' => 'st', // Filter::STARTS_WITH
'name' => '',
],
'name.enw' => [
'type' => 'enw', // Filter::ENDS_WITH
'name' => '',
],
],
],
];
```
if your filters have options, they will be present too:
```php
'name.enw' => [
'type' => 'm1', // Filter::MATCH_ONE
'name' => '',
'options' => [
[
'value' => '',
'label' => ''
],
...
],
],
```
This enables you to create the UI for the grid based on a filters type and options.
<file_sep><?php
namespace QueryGrid\QueryGrid;
use ArrayAccess;
use QueryGrid\QueryGrid\Contracts\Collection as CollectionContract;
use QueryGrid\QueryGrid\Columns\Column;
use QueryGrid\QueryGrid\Columns\ColumnCollection;
class GridResult
{
/** @var ColumnCollection */
private $columns;
/** @var RowCollection */
private $rows;
/**
* GridResult constructor.
* @param ColumnCollection $columns
*/
public function __construct(ColumnCollection $columns)
{
$this->columns = $columns;
$this->rows = new RowCollection();
}
/**
* @return ColumnCollection
*/
public function getColumns(): ColumnCollection
{
return $this->columns;
}
/**
* @param array $rows
* @return void
*/
public function setRows(array $rows)
{
$this->rows->populate($rows);
}
/**
* @return CollectionContract|RowCollection
*/
public function getRows(): CollectionContract
{
return $this->rows->map(function ($row) {
return $this->columns->keyBy(function (Column $column) {
return $column->getKey();
}, function (Column $column) use ($row) {
return $this->getValue($column, $row);
});
});
}
/**
* @param Column $column
* @param mixed $value
* @return mixed|string
*/
private function getValue(Column $column, $value)
{
$field = $column->getField();
if (isset($value[$field])) {
$value = $value[$field];
} else {
foreach (explode('.', $field) as $part) {
if (($value instanceof ArrayAccess || is_array($value)) && isset($value[$part])) {
$value = $value[$part];
} else {
return '';
}
}
}
return $column->format($value);
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Columns;
class Column
{
/** @var string */
private $key;
/** @var string */
private $label;
/** @var string */
private $field;
/** @var callable|null */
private $formatter;
/** @var array */
private $filters = [];
/** @var bool */
private $sortable = false;
/** @var bool */
private $queryable = false;
/** @var OrderBy|null */
private $orderBy;
/**
* Column constructor.
* @param string $key
* @param string $label
*/
public function __construct(string $key, string $label)
{
$this->key = $key;
$this->field = $key;
$this->label = $label;
}
/**
* @return string
*/
public function getKey(): string
{
return $this->key;
}
/**
* @return string
*/
public function getLabel(): string
{
return $this->label;
}
/**
* @param string $field
* @return Column
*/
public function fromField(string $field): self
{
$this->field = $field;
array_walk($this->filters, function (Filter $filter) {
$filter->setField($this->field);
});
return $this;
}
/**
* @return string
*/
public function getField(): string
{
return $this->field;
}
/**
* @param callable $callable
* @return Column
*/
public function withFormat(callable $callable): self
{
$this->formatter = $callable;
return $this;
}
/**
* @param mixed $value
* @return mixed
*/
public function format($value)
{
if (is_callable($this->formatter)) {
$value = ($this->formatter)($value);
}
return $value;
}
/**
* @return bool
*/
public function hasFormat()
{
return isset($this->formatter);
}
/**
* @param string $type
* @param string $name
* @return Filter
*/
public function addFilter(string $type, string $name = ''): Filter
{
$key = $this->getKey() . '.' . $type;
if (array_key_exists($key, $this->filters)) {
throw ColumnException::canNotAddFilterWithDuplicateType();
}
$filter = new Filter($type);
$filter->setName($name);
$filter->setField($this->field);
$this->filters[$key] = $filter;
return $filter;
}
/**
* @return array
*/
public function toArray(): array
{
$filters = [];
foreach ($this->filters as $key => $filter) {
$filters[$key] = $filter->toArray();
}
$result = [
'key' => $this->getKey(),
'label' => $this->getLabel(),
'sortable' => $this->isSortable(),
'queryable' => $this->isQueryable(),
'filterable' => $this->isFilterable(),
];
if (count($filters) > 0) {
$result['filters'] = $filters;
}
return $result;
}
/**
* @return array
*/
public function getFilters(): array
{
return $this->filters;
}
/**
* @return void
*/
public function sortable()
{
$this->sortable = true;
}
/**
* @return bool
*/
public function isSortable(): bool
{
return $this->sortable;
}
/**
* @return void
*/
public function queryable()
{
$this->queryable = true;
}
/**
* @return bool
*/
public function isQueryable(): bool
{
return $this->queryable;
}
/**
* @return bool
*/
public function isFilterable(): bool
{
return count($this->filters) > 0;
}
/**
* @param bool $descending
* @return void
*/
public function setOrderBy($descending = false)
{
$this->orderBy = new OrderBy($this->getField());
$this->orderBy->setDescending($descending);
}
/**
* @return null|OrderBy
*/
public function getOrderBy(): ?OrderBy
{
return $this->orderBy;
}
}
<file_sep><?php
namespace Tests\Grid;
use QueryGrid\QueryGrid\Columns\Filter;
class GridQueryTest extends TestCase
{
/** @test */
public function itParsesFilters()
{
$grid = $this->itHasAGridInstance();
$grid->addColumn('name', 'Name')
->addFilter(Filter::CONTAINS);
$column = $grid->addColumn('birthday', 'Date of Birth')
->fromField('dob');
$column->addFilter(Filter::GREATER_THAN);
$column->addFilter(Filter::LESS_THAN);
$grid->getResult([
'filters' => [
'name.con' => 'ndr',
'birthday.gt' => '1980-01-01',
'birthday.lt' => '2000-01-01',
],
]);
$this->assertEquals([
'name' => [
[
'type' => Filter::CONTAINS,
'value' => 'ndr',
],
],
'dob' => [
[
'type' => Filter::GREATER_THAN,
'value' => '1980-01-01',
],
[
'type' => Filter::LESS_THAN,
'value' => '2000-01-01',
]
],
], $this->dataProvider->getFilters());
}
/** @test */
public function itIgnoresInvalidFilters()
{
$grid = $this->itHasAGridInstance();
$grid->addColumn('name', 'Name')
->addFilter(Filter::CONTAINS);
$column = $grid->addColumn('birthday', 'Date of Birth')
->fromField('dob');
$column->addFilter(Filter::GREATER_THAN);
$column->addFilter(Filter::LESS_THAN);
$grid->getResult([
'filters' => [
'name.con' => 'ndr',
'birthday.gt' => '1980-01-01',
'birthday.lt' => '2000-01-01',
'orange' => 'red',
],
]);
$this->assertEquals([
'name' => [
[
'type' => Filter::CONTAINS,
'value' => 'ndr',
],
],
'dob' => [
[
'type' => Filter::GREATER_THAN,
'value' => '1980-01-01',
],
[
'type' => Filter::LESS_THAN,
'value' => '2000-01-01',
]
],
], $this->dataProvider->getFilters());
}
/** @test */
public function iSetsAQuery()
{
$grid = $this->itHasAGridInstance();
$grid->addColumn('name', 'Name')->queryable();
$grid->addColumn('birthday', 'Date of Birth');
$grid->addColumn('about', 'about')->queryable();
$grid->getResult([
'query' => 'and',
]);
$query = $this->dataProvider->getQuery();
$this->assertEquals('and', $query->getQuery());
$this->assertEquals(['name', 'about'], $query->getFields());
}
/** @test */
public function itAddsSortingAscending()
{
$grid = $this->itHasAGridInstance();
$grid->addColumn('name', 'Name')->sortable();
$grid->addColumn('birthday', 'Date of Birth');
$grid->getResult([
'sort' => 'name',
]);
$orderBy = $this->dataProvider->getOrderBy();
$this->assertCount(1, $orderBy);
$this->assertFalse($orderBy[0]->isDescending());
$this->assertEquals('name', $orderBy[0]->getField());
}
/** @test */
public function itAddsSortingDescending()
{
$grid = $this->itHasAGridInstance();
$grid->addColumn('name', 'Name')->sortable();
$grid->addColumn('birthday', 'Date of Birth');
$grid->getResult([
'sort' => '-name',
]);
$orderBy = $this->dataProvider->getOrderBy();
$this->assertCount(1, $orderBy);
$this->assertTrue($orderBy[0]->isDescending());
$this->assertEquals('name', $orderBy[0]->getField());
}
/** @test */
public function itAddsMultipleSorting()
{
$grid = $this->itHasAGridInstance();
$grid->addColumn('name', 'Name')->sortable();
$grid->addColumn('birthday', 'Date of Birth')->sortable();
$grid->getResult([
'sort' => '-name,birthday',
]);
$orderBy = $this->dataProvider->getOrderBy();
$this->assertCount(2, $orderBy);
$this->assertTrue($orderBy[0]->isDescending());
$this->assertEquals('name', $orderBy[0]->getField());
$this->assertFalse($orderBy[1]->isDescending());
$this->assertEquals('birthday', $orderBy[1]->getField());
}
/** @test */
public function itSortsOnFieldNotString()
{
$grid = $this->itHasAGridInstance();
$grid->addColumn('name', 'Name')
->fromField('full_name')
->sortable();
$grid->addColumn('birthday', 'Date of Birth')->sortable();
$grid->getResult([
'sort' => 'name,birthday',
]);
$orderBy = $this->dataProvider->getOrderBy();
$this->assertEquals('full_name', $orderBy[0]->getField());
}
/** @test */
public function itSetsAQueryAndSortAndFilter()
{
$grid = $this->itHasAGridInstance();
$columnName = $grid->addColumn('name', 'Name')
->fromField('full_name');
$columnName->sortable();
$columnName->queryable();
$columnName->addFilter(Filter::CONTAINS);
$columnBirthday = $grid->addColumn('birthday', 'Date of Birth');
$columnBirthday->sortable();
$columnBirthday->addFilter(Filter::LESS_THAN);
$columnAbout = $grid->addColumn('about', 'About Me');
$columnAbout->queryable();
$grid->getResult([
'sort' => 'name,-birthday',
'filters' => [
'name.con' => 'an',
'birthday.lt' => '1999-12-31',
],
'query' => 'and',
]);
$filters = $this->dataProvider->getFilters();
$query = $this->dataProvider->getQuery();
$orderBy = $this->dataProvider->getOrderBy();
$this->assertEquals([
'full_name' => [
[
'type' => Filter::CONTAINS,
'value' => 'an',
],
],
'birthday' => [
[
'type' => Filter::LESS_THAN,
'value' => '1999-12-31',
],
],
], $filters);
$this->assertEquals('and', $query->getQuery());
$this->assertEquals(['full_name', 'about'], $query->getFields());
$this->assertCount(2, $orderBy);
$this->assertFalse($orderBy[0]->isDescending());
$this->assertEquals('full_name', $orderBy[0]->getField());
$this->assertTrue($orderBy[1]->isDescending());
$this->assertEquals('birthday', $orderBy[1]->getField());
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Columns;
class Filter
{
const STARTS_WITH = 'st';
const ENDS_WITH = 'enw';
const CONTAINS = 'con';
const EXACT = 'exa';
const LESS_THAN = 'lt';
const LESS_THAN_OR_EQUAL = 'lte';
const GREATER_THAN = 'gt';
const GREATER_THAN_OR_EQUAL = 'gte';
const MATCH_ONE_OPTION = 'm1';
const MATCH_MANY_OPTIONS = 'mn';
/** @var string */
private $type;
/** @var array */
private $options = [];
/** @var string */
private $name = '';
/** @var mixed */
private $field;
/**
* Filter constructor.
* @param string $type
* @throws FilterException
* @return void
*/
public function __construct(string $type)
{
if (!in_array($type, self::getTypes(), true)) {
throw FilterException::unknownFilterType($type);
}
$this->type = $type;
}
/**
* @return array
*/
public function toArray(): array
{
$result = [
'type' => $this->type,
'name' => $this->name,
];
if (count($this->options) > 0) {
$result['options'] = $this->options;
}
return $result;
}
/**
* @return array
*/
public static function getTypes(): array
{
return [
static::STARTS_WITH,
static::ENDS_WITH,
static::CONTAINS,
static::EXACT,
static::LESS_THAN,
static::LESS_THAN_OR_EQUAL,
static::GREATER_THAN,
static::GREATER_THAN_OR_EQUAL,
static::MATCH_ONE_OPTION,
static::MATCH_MANY_OPTIONS,
];
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @param string $value
* @param string|null $label
* @return void
*/
public function addOption(string $value, string $label = null)
{
$label = $label ?? $value;
$this->options[] = compact('value', 'label');
}
/**
* @return array
*/
public function getOptions(): array
{
return $this->options;
}
/**
* @param string $name
* @return void
*/
public function setName(string $name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $field
* @return void
*/
public function setField(string $field)
{
$this->field = $field;
}
/**
* @return string
*/
public function getField(): string
{
return $this->field;
}
}
<file_sep><?php
namespace Tests\Collections;
use Tests\TestCase;
use QueryGrid\QueryGrid\Collections\Collection;
class CollectionTest extends TestCase
{
/** @test */
public function itIsAccessible()
{
$collection = new Collection();
$collection->add(1);
$collection->add(2);
$collection->add(3);
$this->assertTrue(isset($collection[0]));
$this->assertTrue(isset($collection[1]));
$this->assertTrue(isset($collection[2]));
$this->assertFalse(isset($collection[3]));
$this->assertEquals(1, $collection[0]);
$this->assertEquals(2, $collection[1]);
$this->assertEquals(3, $collection[2]);
}
/**
* @test
* @expectedException \QueryGrid\QueryGrid\Collections\CollectionException
* @expectedExceptionMessage You can not change a collection value that way.
*/
public function itBlocksSetting()
{
$collection = new Collection();
$collection[0] = 1;
}
/**
* @test
* @expectedException \QueryGrid\QueryGrid\Collections\CollectionException
* @expectedExceptionMessage You can not unset a collection value that way.
*/
public function itBlocksUnsetting()
{
$collection = new Collection();
unset($collection[0]);
}
/** @test */
public function itIsCountable()
{
$collection = new Collection();
$this->assertCount(0, $collection);
$collection->add(1);
$this->assertCount(1, $collection);
$collection->add(1);
$this->assertCount(2, $collection);
}
/** @test */
public function itRetrievesByOffset()
{
$collection = new Collection();
$collection->add(1);
$collection->add(2);
$collection->add(3);
$this->assertEquals(1, $collection->get(0));
$this->assertEquals(2, $collection->get(1));
$this->assertEquals(3, $collection->get(2));
}
/** @test */
public function itRetrievesFirstItem()
{
$collection = new Collection();
$collection->add(1);
$collection->add(2);
$collection->add(3);
$this->assertEquals(1, $collection->first());
}
/** @test */
public function itRetrievesLastItem()
{
$collection = new Collection();
$collection->add(1);
$collection->add(2);
$collection->add(3);
$this->assertEquals(3, $collection->last());
}
/** @test */
public function itIsImmutableAndMappable()
{
$collection = new Collection();
$collection->add(1);
$collection->add(2);
$collection->add(3);
$mapped = $collection->map(function ($i) {
return $i * 2;
});
$this->assertEquals(1, $collection->get(0));
$this->assertEquals(2, $collection->get(1));
$this->assertEquals(3, $collection->get(2));
$this->assertEquals(2, $mapped->get(0));
$this->assertEquals(4, $mapped->get(1));
$this->assertEquals(6, $mapped->get(2));
}
/** @test */
public function itReturnsAnArray()
{
$collection = new Collection();
$collection->add(1);
$collection->add(2);
$collection->add(3);
$this->assertEquals([1, 2, 3], $collection->all());
}
/** @test */
public function itIsImmutableAndFilterable()
{
$collection = new Collection();
$collection->add(1);
$collection->add(2);
$collection->add(3);
$filtered = $collection->filter(function ($i) {
return $i > 1;
});
$this->assertCount(3, $collection);
$this->assertCount(2, $filtered);
$this->assertEquals(1, $collection->get(0));
$this->assertEquals(2, $collection->get(1));
$this->assertEquals(3, $collection->get(2));
$this->assertEquals(2, $filtered->get(0));
$this->assertEquals(3, $filtered->get(1));
}
/** @test */
public function itKeysResultsByCallable()
{
$collection = new Collection();
$collection->add(['k' => 'one', 'value' => 1]);
$collection->add(['k' => 'two', 'value' => 2]);
$collection->add(['k' => 'three', 'value' => 3]);
$keyed = $collection->keyBy(function ($item) {
return $item['k'];
});
$this->assertArrayHasKey('one', $keyed);
$this->assertArrayHasKey('two', $keyed);
$this->assertArrayHasKey('three', $keyed);
$this->assertEquals(['k' => 'one', 'value' => 1], $keyed['one']);
$this->assertEquals(['k' => 'two', 'value' => 2], $keyed['two']);
$this->assertEquals(['k' => 'three', 'value' => 3], $keyed['three']);
}
/** @test */
public function itKeysResultsAndValuesByCallable()
{
$collection = new Collection();
$collection->add(['k' => 'one', 'value' => 1]);
$collection->add(['k' => 'two', 'value' => 2]);
$collection->add(['k' => 'three', 'value' => 3]);
$keyed = $collection->keyBy(function ($item) {
return $item['k'];
}, function ($item) {
return $item['value'];
});
$this->assertArrayHasKey('one', $keyed);
$this->assertArrayHasKey('two', $keyed);
$this->assertArrayHasKey('three', $keyed);
$this->assertEquals(1, $keyed['one']);
$this->assertEquals(2, $keyed['two']);
$this->assertEquals(3, $keyed['three']);
}
/** @test */
public function itIsArrayable()
{
$collection = new Collection();
$collection->add('a');
$collection->add('b');
$collection->add([
'c' => 'd',
]);
$this->assertEquals(['a', 'b', ['c' => 'd',]], $collection->toArray());
}
/** @test */
public function itFiltersUnique()
{
$collection = new Collection();
$collection->add('a');
$collection->add('b');
$collection->add('b');
$collection->add('c');
$collection->add('c');
$collection->add('c');
$this->assertEquals(['a', 'b', 'c'], $collection->unique()->toArray());
}
/** @test */
public function itImplementsIteratorInterfaceCorrectly()
{
$collection = new Collection();
$collection->add(100);
$collection->add(101);
$collection->add(102);
$this->assertEquals(0, $collection->key());
$this->assertTrue($collection->valid());
$this->assertEquals(100, $collection->current());
$collection->next();
$this->assertEquals(1, $collection->key());
$this->assertTrue($collection->valid());
$this->assertEquals(101, $collection->current());
$collection->next();
$this->assertEquals(2, $collection->key());
$this->assertTrue($collection->valid());
$this->assertEquals(102, $collection->current());
$collection->next();
$this->assertFalse($collection->valid());
$collection->rewind();
$this->assertTrue($collection->valid());
$this->assertEquals(0, $collection->key());
$this->assertEquals(100, $collection->current());
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid;
use QueryGrid\QueryGrid\Contracts\Arrayable;
class PaginationData implements Arrayable
{
/** @var int */
private $perPage;
/** @var int */
private $itemCount = 0;
/** @var int|null */
private $totalItems;
/** @var int */
private $currentPage = 1;
/**
* PaginationData constructor.
* @param int $perPage
*/
public function __construct(int $perPage)
{
$this->perPage = $perPage;
}
/**
* @return int
*/
public function getPerPage(): int
{
return $this->perPage;
}
/**
* @return int
*/
public function getItemCount(): int
{
$totalItems = $this->getTotalItems();
if (is_null($totalItems)) {
return $this->itemCount;
}
return $this->getLastPage() === $this->getCurrentPage()
? $totalItems % $this->getPerPage()
: $this->getPerPage();
}
/**
* @return int|null
*/
public function getTotalItems(): ?int
{
return $this->totalItems;
}
/**
* @return int
*/
public function getCurrentPage(): int
{
return $this->currentPage;
}
/**
* @return int|null
*/
public function getLastPage(): ?int
{
if (is_null($this->totalItems)) {
return null;
}
return intval(ceil($this->totalItems / $this->perPage), 10);
}
/**
* @param int $itemCount
* @return void
*/
public function setItemCount(int $itemCount)
{
$this->itemCount = $itemCount;
}
/**
* @param int $totalItems
* @return void
*/
public function setTotalItems(int $totalItems)
{
$this->totalItems = $totalItems;
}
/**
* @param int $currentPage
* @return void
*/
public function setCurrentPage(int $currentPage)
{
$this->currentPage = $currentPage;
}
/**
* @return array
*/
public function toArray(): array
{
return [
'perPage' => $this->getPerPage(),
'itemCount' =>$this->getItemCount(),
'currentPage' =>$this->getCurrentPage(),
'totalItems' => $this->getTotalItems(),
'lastPage' =>$this->getLastPage(),
];
}
}
<file_sep><?php
namespace Tests\Columns\Formatters;
use Tests\TestCase;
use QueryGrid\QueryGrid\Columns\Formatters\Date;
class DateTest extends TestCase
{
/** @test */
public function itIsCreatable()
{
$date = new Date('Y-m-d', 'd/m/Y');
$this->assertEquals('12/12/2019', $date('2019-12-12'));
}
/** @test */
public function itReturnsEmptyStringForNonDate()
{
$date = new Date('Y-m-d', 'd/m/Y');
$this->assertEquals('', $date('231ev'));
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid;
use QueryGrid\QueryGrid\Columns\Column;
use QueryGrid\QueryGrid\Columns\ColumnCollection;
use QueryGrid\QueryGrid\Columns\Filter;
use QueryGrid\QueryGrid\Contracts\DataProvider;
class Grid
{
/**
* @var DataProvider
*/
private $dataProvider;
/**
* @var ColumnCollection
*/
private $columns;
/**
* Grid constructor.
* @param DataProvider $dataProvider
*/
public function __construct(DataProvider $dataProvider)
{
$this->dataProvider = $dataProvider;
$this->columns = new ColumnCollection();
}
/**
* @return DataProvider
*/
public function getDataProvider(): DataProvider
{
return $this->dataProvider;
}
/**
* @param string $key
* @param string $label
* @return Column
*/
public function addColumn(string $key, string $label): Column
{
$column = new Column($key, $label);
$this->columns->add($column);
return $column;
}
/**
* @return ColumnCollection
*/
public function getColumns(): ColumnCollection
{
return $this->columns;
}
/**
* @param string $resource
* @return void
*/
public function setResource(string $resource)
{
$this->dataProvider->setResource($resource);
}
/**
* @param array $params
* @return GridResult
*/
public function getResult($params = []): GridResult
{
if (array_key_exists('filters', $params)) {
$this->setFilters($params['filters']);
}
if (array_key_exists('query', $params)) {
$this->setQuery($params['query']);
}
if (array_key_exists('sort', $params)) {
$this->setOrderBy($params['sort']);
}
$result = new GridResult($this->columns);
$result->setRows($this->dataProvider->get());
return $result;
}
/**
* @param Filter[] $filters
* @return void
*/
private function setFilters($filters)
{
$newFilters = [];
/** @var Filter[] $allFilters */
$allFilters = $this->columns->getAllFilters();
foreach ($filters as $key => $value) {
if (!array_key_exists($key, $allFilters)) {
continue;
}
$filter = $allFilters[$key];
if (!array_key_exists($filter->getField(), $newFilters)) {
$newFilters[$filter->getField()] = [];
}
$newFilters[$filter->getField()][] = [
'type' => $filter->getType(),
'value' => $value,
];
}
$this->dataProvider->setFilters($newFilters);
}
/**
* @param mixed $query
* @return void
*/
private function setQuery($query)
{
$columns = $this->columns->getQueryableColumns()
->map(function (Column $column) {
return $column->getField();
})->unique();
$this->dataProvider->setQuery(new Query($query, $columns->all()));
}
/**
* @param string $orderByQuery
* @return void
*/
private function setOrderBy(string $orderByQuery)
{
$orderByList = explode(',', $orderByQuery);
$descending = [];
foreach ($orderByList as $orderBy) {
$key = ltrim($orderBy, '-');
$descending[$key] = $orderBy !== $key;
}
$sortableColumns = $this->columns->filter(function (Column $column) use ($descending) {
return array_key_exists($column->getKey(), $descending);
});
foreach ($sortableColumns as $column) {
/** @var Column $column */
$column->setOrderBy($descending[$column->getKey()]);
$this->dataProvider->addOrderBy($column->getOrderBy());
}
}
}
<file_sep><?php
namespace Tests;
use QueryGrid\QueryGrid\Contracts\Arrayable;
use QueryGrid\QueryGrid\PaginationData;
class PaginationDataTest extends TestCase
{
/** @test */
public function itIsCreatable()
{
$paginationData = new PaginationData(25);
$this->assertEquals(25, $paginationData->getPerPage());
$this->assertEquals(0, $paginationData->getItemCount());
$this->assertEquals(1, $paginationData->getCurrentPage());
$this->assertEquals(null, $paginationData->getTotalItems());
$this->assertEquals(null, $paginationData->getLastPage());
}
/** @test */
public function itSetsItemCount()
{
$paginationData = new PaginationData(25);
$paginationData->setItemCount(10);
$this->assertEquals(25, $paginationData->getPerPage());
$this->assertEquals(10, $paginationData->getItemCount());
$this->assertEquals(1, $paginationData->getCurrentPage());
$this->assertEquals(null, $paginationData->getTotalItems());
$this->assertEquals(null, $paginationData->getLastPage());
}
/** @test */
public function itSetsTotalItems()
{
$paginationData = new PaginationData(10);
$paginationData->setTotalItems(100);
$this->assertEquals(10, $paginationData->getPerPage());
$this->assertEquals(10, $paginationData->getItemCount());
$this->assertEquals(1, $paginationData->getCurrentPage());
$this->assertEquals(100, $paginationData->getTotalItems());
$this->assertEquals(10, $paginationData->getLastPage());
}
/** @test */
public function itGetsCorrectItemCountForCurrentPage()
{
$paginationData = new PaginationData(10);
$paginationData->setTotalItems(64);
$paginationData->setCurrentPage(7);
$this->assertEquals(10, $paginationData->getPerPage());
$this->assertEquals(4, $paginationData->getItemCount());
$this->assertEquals(7, $paginationData->getCurrentPage());
$this->assertEquals(64, $paginationData->getTotalItems());
$this->assertEquals(7, $paginationData->getLastPage());
}
/** @test */
public function itIsArrayable()
{
$paginationData = new PaginationData(10);
$paginationData->setTotalItems(64);
$paginationData->setCurrentPage(7);
$this->assertInstanceOf(Arrayable::class, $paginationData);
$this->assertEquals([
'perPage' => 10,
'itemCount' => 4,
'currentPage' => 7,
'totalItems' => 64,
'lastPage' => 7,
], $paginationData->toArray());
}
}
<file_sep><?php
namespace Tests\Columns;
use Tests\TestCase;
use QueryGrid\QueryGrid\Columns\Column;
use QueryGrid\QueryGrid\Columns\Filter;
class ColumnTest extends TestCase
{
/** @test */
public function itIsCreatable()
{
$column = new Column('key', 'label');
$this->assertEquals('key', $column->getKey());
$this->assertEquals('key', $column->getField());
$this->assertEquals('label', $column->getLabel());
}
/** @test */
public function itChangesTheFromField()
{
$column = new Column('key', 'label');
$response = $column->fromField('field');
$this->assertEquals('key', $column->getKey());
$this->assertEquals('field', $column->getField());
$this->assertEquals('label', $column->getLabel());
$this->assertSame($response, $column);
}
/** @test */
public function itFormatsValues()
{
$column = new Column('key', 'label');
$response = $column->withFormat(function ($value) {
return 'all_' . $value;
});
$this->assertTrue($column->hasFormat());
$this->assertEquals('all_of', $column->format('of'));
$this->assertSame($response, $column);
}
/** @test */
public function itReturnsAValueWhenThereIsNoFormat()
{
$column = new Column('key', 'label');
$this->assertFalse($column->hasFormat());
$this->assertEquals('of', $column->format('of'));
}
/** @test */
public function itAddsAFilter()
{
$column = new Column('k', 'l');
$filter = $column->addFilter(Filter::CONTAINS, 'Contains String');
$filters = $column->getFilters();
$this->assertArrayHasKey('k.' . Filter::CONTAINS, $filters);
$this->assertEquals($filter, $filters['k.' . Filter::CONTAINS]);
}
/** @test */
public function itAddsManyFilters()
{
$column = new Column('k', 'l');
$filterContains = $column->addFilter(Filter::CONTAINS, 'Contains String');
$filterStarts = $column->addFilter(Filter::STARTS_WITH, 'Starts with');
$filters = $column->getFilters();
$this->assertArrayHasKey('k.' . Filter::CONTAINS, $filters);
$this->assertArrayHasKey('k.' . Filter::STARTS_WITH, $filters);
$this->assertEquals($filterContains, $filters['k.' . Filter::CONTAINS]);
$this->assertEquals($filterStarts, $filters['k.' . Filter::STARTS_WITH]);
$this->assertEquals('k', $filterContains->getField());
$this->assertEquals('k', $filterStarts->getField());
$column->fromField('other');
$this->assertEquals('other', $filterContains->getField());
$this->assertEquals('other', $filterStarts->getField());
}
/**
* @test
* @expectedException \QueryGrid\QueryGrid\Columns\ColumnException
* @expectedExceptionMessage You can only add one of each filter type to a column.
*/
public function itRejectsDuplicateFilterTypes()
{
$column = new Column('k', 'l');
$column->addFilter(Filter::CONTAINS, 'Contains String');
$column->addFilter(Filter::CONTAINS, 'Whoops');
}
/** @test */
public function itSetsSortable()
{
$column = new Column('k', 'l');
$this->assertFalse($column->isSortable());
$column->sortable();
$this->assertTrue($column->isSortable());
}
/** @test */
public function itSetsQueryable()
{
$column = new Column('k', 'l');
$this->assertFalse($column->isQueryable());
$column->queryable();
$this->assertTrue($column->isQueryable());
}
/** @test */
public function itDetectsFilterable()
{
$column = new Column('k', 'l');
$this->assertFalse($column->isFilterable());
$column->addFilter(Filter::CONTAINS, 'Contains String');
$this->assertTrue($column->isFilterable());
}
/** @test */
public function itReturnsAnArray()
{
$column = new Column('k', 'l');
$this->assertEquals([
'key' => 'k',
'label' => 'l',
'sortable' => false,
'queryable' => false,
'filterable' => false,
], $column->toArray());
$column = new Column('k', 'l');
$column->sortable();
$this->assertEquals([
'key' => 'k',
'label' => 'l',
'sortable' => true,
'queryable' => false,
'filterable' => false,
], $column->toArray());
$column = new Column('k', 'l');
$column->queryable();
$this->assertEquals([
'key' => 'k',
'label' => 'l',
'sortable' => false,
'queryable' => true,
'filterable' => false,
], $column->toArray());
$column = new Column('k', 'l');
$filterContains = $column->addFilter(Filter::CONTAINS, 'Contains String');
$this->assertEquals([
'key' => 'k',
'label' => 'l',
'sortable' => false,
'queryable' => false,
'filterable' => true,
'filters' => [
'k.' . Filter::CONTAINS => $filterContains->toArray(),
],
], $column->toArray());
$column = new Column('k', 'l');
$filterContains = $column->addFilter(Filter::CONTAINS, 'Contains String');
$filterStarts = $column->addFilter(Filter::STARTS_WITH, 'Starts with String');
$this->assertEquals([
'key' => 'k',
'label' => 'l',
'sortable' => false,
'queryable' => false,
'filterable' => true,
'filters' => [
'k.' . Filter::CONTAINS => $filterContains->toArray(),
'k.' . Filter::STARTS_WITH => $filterStarts->toArray(),
],
], $column->toArray());
}
/** @test */
public function itCanAddOrderBy()
{
$column = new Column('k', 'l');
$column->setOrderBy();
$orderBy = $column->getOrderBy();
$this->assertFalse($orderBy->isDescending());
$this->assertEquals('k', $orderBy->getField());
}
/** @test */
public function itCanAddOrderByDescending()
{
$column = new Column('k', 'l');
$column->setOrderBy(true);
$orderBy = $column->getOrderBy();
$this->assertTrue($orderBy->isDescending());
$this->assertEquals('k', $orderBy->getField());
}
/** @test */
public function itCanAddOrderByWithCustomField()
{
$column = new Column('k', 'l');
$column->fromField('boo');
$column->setOrderBy();
$orderBy = $column->getOrderBy();
$this->assertFalse($orderBy->isDescending());
$this->assertEquals('boo', $orderBy->getField());
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Contracts;
interface Arrayable
{
/**
* @return array
*/
public function toArray(): array;
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Columns;
use QueryGrid\QueryGrid\Contracts\Collection as CollectionContract;
use QueryGrid\QueryGrid\Collections\CollectionAbstract;
class ColumnCollection extends CollectionAbstract
{
/**
* @param Column $column
* @return void
*/
public function add(Column $column)
{
$this->append($column);
}
/**
* @return Column
*/
public function last(): Column
{
return $this->offsetGet($this->count() - 1);
}
/**
* @return Column
*/
public function first(): Column
{
return $this->offsetGet(0);
}
/**
* @return array
*/
public function toArray(): array
{
return $this->map(function (Column $column) {
return $column->toArray();
})->all();
}
/**
* @return array
*/
public function getAllFilters()
{
$filters = [];
foreach ($this->items as $item) {
$filters = array_merge($filters, $item->getFilters());
}
return $filters;
}
/**
* @return CollectionContract
*/
public function getQueryableColumns(): CollectionContract
{
return $this->filter(function (Column $column) {
return $column->isQueryable();
});
}
/**
* @return CollectionContract
*/
public function getSortableColumns()
{
return $this->filter(function (Column $column) {
return $column->isSortable();
});
}
}
<file_sep><?php
namespace Tests\Columns;
use Tests\TestCase;
use QueryGrid\QueryGrid\Collections\CollectionAbstract;
use QueryGrid\QueryGrid\Columns\Column;
use QueryGrid\QueryGrid\Columns\ColumnCollection;
use QueryGrid\QueryGrid\Columns\Filter;
class ColumnCollectionTest extends TestCase
{
/** @test */
public function itExtendsTheAbstractCollection()
{
$columnCollection = new ColumnCollection();
$this->assertInstanceOf(CollectionAbstract::class, $columnCollection);
}
/** @test */
public function itAddsAColumn()
{
$columnCollection = new ColumnCollection();
$column = new Column('k', 'l');
$columnCollection->add($column);
$this->assertCount(1, $columnCollection);
$this->assertSame($column, $columnCollection->first());
$this->assertSame($column, $columnCollection->last());
}
/** @test */
public function itAddsManyColumns()
{
$columnCollection = new ColumnCollection();
$columnFirst = new Column('first', 'First');
$columnCollection->add($columnFirst);
$columnCollection->add(new Column('second', 'Second'));
$columnLast = new Column('last', 'Last');
$columnCollection->add($columnLast);
$this->assertCount(3, $columnCollection);
$this->assertSame($columnFirst, $columnCollection->first());
$this->assertSame($columnLast, $columnCollection->last());
}
/**
* @test
* @expectedException \TypeError
*/
public function itDoesNotAddNonColumns()
{
$columnCollection = new ColumnCollection();
$columnCollection->add(1);
}
/** @test */
public function itConvertsToAnArray()
{
$columnCollection = new ColumnCollection();
$columnCollection->add(new Column('first', 'First'));
$columnCollection->add(new Column('second', 'Second'));
$this->assertEquals([
[
'key' => 'first',
'label' => 'First',
'sortable' => false,
'queryable' => false,
'filterable' => false,
],
[
'key' => 'second',
'label' => 'Second',
'sortable' => false,
'queryable' => false,
'filterable' => false,
],
], $columnCollection->toArray());
}
/** @test */
public function itGetsAllFilters()
{
$columnCollection = new ColumnCollection();
$columnName = new Column('name', 'Name');
$filterNameContains = $columnName->addFilter(Filter::CONTAINS);
$columnBirthday = new Column('birthday', 'Date of Birth');
$columnBirthday->fromField('dob');
$filterBirthdayGreaterThan = $columnBirthday->addFilter(Filter::GREATER_THAN);
$filterBirthdayLessThan = $columnBirthday->addFilter(Filter::LESS_THAN);
$columnCollection->add($columnName);
$columnCollection->add($columnBirthday);
$this->assertEquals([
'name.' . Filter::CONTAINS => $filterNameContains,
'birthday.' . Filter::GREATER_THAN => $filterBirthdayGreaterThan,
'birthday.' . Filter::LESS_THAN => $filterBirthdayLessThan
], $columnCollection->getAllFilters());
}
/** @test */
public function itGetsAllQueryableFields()
{
$columnCollection = new ColumnCollection();
$columnName = new Column('name', 'Name');
$columnName->queryable();
$columnBirthday = new Column('birthday', 'Date of Birth');
$columnAbout = new Column('about', 'about');
$columnAbout->queryable();
$columnCollection->add($columnName);
$columnCollection->add($columnBirthday);
$columnCollection->add($columnAbout);
$this->assertEquals([
$columnName,
$columnAbout,
], $columnCollection->getQueryableColumns()->all());
}
/** @test */
public function itGetsAllSortableFields()
{
$columnCollection = new ColumnCollection();
$columnName = new Column('name', 'Name');
$columnName->sortable();
$columnBirthday = new Column('birthday', 'Date of Birth');
$columnBirthday->sortable();
$columnAbout = new Column('about', 'about');
$columnCollection->add($columnName);
$columnCollection->add($columnBirthday);
$columnCollection->add($columnAbout);
$this->assertEquals([
$columnName,
$columnBirthday,
], $columnCollection->getSortableColumns()->all());
}
}
<file_sep><?php
namespace Tests\Fixtures;
use ArrayAccess;
class UserEntity implements ArrayAccess
{
private $attributes;
public function __construct($name, $email, $created_at)
{
$this->attributes = compact('name', 'email', 'created_at');
}
public function offsetExists($offset)
{
return isset($this->attributes[$offset]);
}
public function offsetGet($offset)
{
return $this->attributes[$offset];
}
public function offsetSet($offset, $value)
{
}
public function offsetUnset($offset)
{
}
}
<file_sep><?php
namespace Tests\Columns;
use Tests\TestCase;
use QueryGrid\QueryGrid\Columns\Filter;
class FilterTest extends TestCase
{
/** @test */
public function itGetsFilterTypes()
{
$types = Filter::getTypes();
$this->assertEquals([
'st',
'enw',
'con',
'exa',
'lt',
'lte',
'gt',
'gte',
'm1',
'mn',
], $types);
}
/** @test */
public function itCanBeCreated()
{
$filter = new Filter(Filter::STARTS_WITH);
$this->assertEquals(Filter::STARTS_WITH, $filter->getType());
}
/**
* @test
* @expectedException \QueryGrid\QueryGrid\Columns\FilterException
* @expectedExceptionMessage Trying to set an unknown filter type: invalidFilter
*/
public function itMustHaveAnExistingFilter()
{
new Filter('invalidFilter');
}
/** @test */
public function itAddsAnOption()
{
$filter = new Filter(Filter::MATCH_ONE_OPTION);
$filter->addOption('option', 'Option');
$this->assertEquals([
[
'value' => 'option',
'label' => 'Option',
],
], $filter->getOptions());
}
/** @test */
public function itAddsManyOptions()
{
$filter = new Filter(Filter::MATCH_ONE_OPTION);
$filter->addOption('option-1', 'Option 1');
$filter->addOption('option-2', 'Option 2');
$this->assertEquals([
[
'value' => 'option-1',
'label' => 'Option 1',
],
[
'value' => 'option-2',
'label' => 'Option 2',
],
], $filter->getOptions());
}
/** @test */
public function itSetsAFilterName()
{
$filter = new Filter(Filter::CONTAINS);
$filter->setName('Awesome Filter');
$this->assertEquals('Awesome Filter', $filter->getName());
}
/** @test */
public function itSetsAFilterField()
{
$filter = new Filter(Filter::CONTAINS);
$filter->setField('field');
$this->assertEquals('field', $filter->getField());
}
/** @test */
public function itReturnsAnArray()
{
$filter = new Filter(Filter::CONTAINS);
$this->assertEquals([
'type' => Filter::CONTAINS,
'name' => '',
], $filter->toArray());
$filter = new Filter(Filter::CONTAINS);
$filter->setName('Filter Name');
$this->assertEquals([
'type' => Filter::CONTAINS,
'name' => 'Filter Name',
], $filter->toArray());
$filter = new Filter(Filter::MATCH_ONE_OPTION);
$filter->addOption('option-1', 'Option 1');
$filter->addOption('option-2', 'Option 2');
$this->assertEquals([
'type' => Filter::MATCH_ONE_OPTION,
'name' => '',
'options' => [
[
'value' => 'option-1',
'label' => 'Option 1',
],
[
'value' => 'option-2',
'label' => 'Option 2',
],
],
], $filter->toArray());
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Columns\Formatters;
use DateTime;
class DateDiff
{
/**
* @var string
*/
private $dateFormat;
/**
* @var string
*/
private $format;
/** @var string */
private $from;
/**
* DateDiff constructor.
* @param string $dateFormat
* @param string $format
*/
public function __construct(string $dateFormat, string $format)
{
$this->dateFormat = $dateFormat;
$this->format = $format;
}
/**
* @param string $date
* @return DateDiff
*/
public function withFromDate(string $date): DateDiff
{
$this->from = $date;
return $this;
}
/**
* @param string $date
* @return string
*/
public function __invoke(string $date): string
{
$to = $this->createDate($date);
$from = $this->createDate($this->from);
if ($from instanceof DateTime && $to instanceof DateTime) {
return $from->diff($to)->format($this->format);
}
return '';
}
/**
* @param string $date
* @return bool|DateTime
*/
protected function createDate(string $date)
{
return DateTime::createFromFormat($this->dateFormat, $date);
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid;
class Query
{
/** @var string */
private $query;
/** @var array */
private $fields;
public function __construct(string $query, array $fields)
{
$this->query = $query;
$this->fields = $fields;
}
/**
* @return string
*/
public function getQuery(): string
{
return $this->query;
}
/**
* @return array
*/
public function getFields(): array
{
return $this->fields;
}
/**
* @return array
*/
public function toArray()
{
return [
'query' => $this->getQuery(),
'fields' => $this->getFields(),
];
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid;
use QueryGrid\QueryGrid\Collections\CollectionAbstract;
class RowCollection extends CollectionAbstract
{
/**
* @param array $rows
* @return void
*/
public function populate(array $rows)
{
$this->fill($rows);
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Collections;
use QueryGrid\QueryGrid\Contracts\Arrayable;
use QueryGrid\QueryGrid\Contracts\Collection as CollectionContract;
use Closure;
abstract class CollectionAbstract implements CollectionContract
{
/** @var \ArrayIterator */
protected $items;
/**
* CollectionAbstract constructor.
*/
public function __construct()
{
$this->items = new \ArrayIterator();
}
/**
* @param array $items
* @return void
*/
protected function fill(array $items)
{
$this->items = new \ArrayIterator($items);
}
/**
* @param mixed $offset
* @return mixed
*/
public function get($offset)
{
return $this->offsetGet($offset);
}
/**
* @param Closure $callable
* @return CollectionContract
*/
public function map(Closure $callable): CollectionContract
{
$collection = new static();
$collection->fill(array_map($callable, $this->all()));
return $collection;
}
/**
* @param Closure $callable
* @return CollectionContract
*/
public function filter(Closure $callable): CollectionContract
{
$collection = new static;
$collection->fill(array_values(array_filter($this->all(), $callable)));
return $collection;
}
/**
* @return array
*/
public function all(): array
{
return $this->items->getArrayCopy();
}
/**
* @param Closure $key
* @param Closure|null $value
* @return array
*/
public function keyBy(Closure $key, Closure $value = null): array
{
$items = [];
foreach ($this->items as $item) {
$itemValue = is_null($value) ? $item : $value($item);
$items[$key($item)] = $itemValue;
}
return $items;
}
/**
* @return CollectionContract
*/
public function unique(): CollectionContract
{
$collection = new static();
$collection->fill(array_values(array_unique($this->items->getArrayCopy())));
return $collection;
}
/**
* @return mixed
*/
public function first()
{
return $this->offsetGet(0);
}
/**
* @return mixed
*/
public function last()
{
return $this->offsetGet($this->count() - 1);
}
/**
* @param mixed $value
* @return void
*/
protected function append($value)
{
$this->items->append($value);
}
/**
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return $this->items->offsetExists($offset);
}
/**
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset)
{
return $this->items->offsetGet($offset);
}
/**
* @param mixed $offset
* @param mixed $value
* @throws CollectionException
* @return void
*/
public function offsetSet($offset, $value)
{
throw CollectionException::canNotSetOnACollection();
}
/**
* @param mixed $offset
* @throws CollectionException
* @return void
*/
public function offsetUnset($offset)
{
throw CollectionException::canNotUnsetOnACollection();
}
/**
* @return int
*/
public function count()
{
return $this->items->count();
}
/**
* Converts a collection to an array
*
* @return array
*/
public function toArray(): array
{
return $this->map(function ($item) {
return ($item instanceof Arrayable) ? $item->toArray() : $item;
})->all();
}
/**
* @return mixed
*/
public function current()
{
return $this->items->current();
}
/**
* @return void
*/
public function next()
{
$this->items->next();
}
/**
* @return mixed
*/
public function key()
{
return $this->items->key();
}
/**
* @return bool
*/
public function valid()
{
return $this->items->valid();
}
/**
* @return void
*/
public function rewind()
{
$this->items->rewind();
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Collections;
class CollectionException extends \RuntimeException
{
/**
* @return CollectionException
*/
public static function canNotUnsetOnACollection()
{
return new static('You can not unset a collection value that way.');
}
/**
* @return CollectionException
*/
public static function canNotSetOnACollection()
{
return new static('You can not change a collection value that way.');
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Columns;
class ColumnException extends \RuntimeException
{
/**
* @return ColumnException
*/
public static function canNotAddFilterWithDuplicateType()
{
return new static("You can only add one of each filter type to a column.");
}
}
<file_sep><?php
namespace Tests;
use QueryGrid\QueryGrid\Query;
class QueryTest extends TestCase
{
/** @test */
public function itIsCreatable()
{
$query = new Query('and', ['about', 'username']);
$this->assertEquals('and', $query->getQuery());
$this->assertEquals(['about', 'username'], $query->getFields());
}
/** @test */
public function itConvertsToAnArray()
{
$query = new Query('and', ['about', 'username']);
$this->assertEquals([
'query' => 'and',
'fields' => ['about', 'username',],
], $query->toArray());
}
}
<file_sep><?php
namespace Tests\Grid;
use DateTime;
use QueryGrid\QueryGrid\Columns\Formatters\Date;
use QueryGrid\QueryGrid\Columns\Formatters\DateDiff;
use QueryGrid\QueryGrid\GridResult;
class GridDataTest extends TestCase
{
/** @test */
public function itCanBeCreated()
{
$grid = $this->itHasAGridInstance();
$this->assertSame($this->dataProvider, $grid->getDataProvider());
}
/** @test */
public function itSetsTheResource()
{
$grid = $this->itHasAGridInstance();
$grid->setResource('resource');
$this->assertEquals('resource', $this->dataProvider->getResource());
}
/** @test */
public function itReturnsTheGridResult()
{
$grid = $this->itHasAGridInstance();
$response = $grid->getResult();
$this->assertInstanceOf(GridResult::class, $response);
}
/** @test */
public function itFormatsData()
{
$grid = $this->itHasAGridInstance();
$grid->addColumn('email_address', 'Email Address')
->fromField('email');
$grid->addColumn('dob', 'Birthday')
->fromField('birthday')
->withFormat(new Date('Y-m-d', 'd/m/Y'));
$grid->addColumn('age', 'Age')
->fromField('birthday')
->withFormat((new DateDiff('Y-m-d', '%y'))->withFromDate('2018-01-01'));
$this->dataProvider->setValues([
[
'email' => '<EMAIL>',
'birthday' => '1963-04-21'
],
[
'email' => '<EMAIL>',
'birthday' => '1973-05-24'
],
[
'email' => '<EMAIL>',
'birthday' => '1983-06-27'
],
]);
$this->assertEquals([
[
'email_address' => '<EMAIL>',
'dob' => '21/04/1963',
'age' => '54',
],
[
'email_address' => '<EMAIL>',
'dob' => '24/05/1973',
'age' => '44',
],
[
'email_address' => '<EMAIL>',
'dob' => '27/06/1983',
'age' => '34',
]
], $grid->getResult()->getRows()->all());
}
}
<file_sep><?php
namespace Tests\Grid;
use QueryGrid\QueryGrid\Columns\Column;
use QueryGrid\QueryGrid\Columns\ColumnCollection;
class GridColumnsTest extends TestCase
{
/** @test */
public function itAddsAColumn()
{
$grid = $this->itHasAGridInstance();
$column = $grid->addColumn('key', 'label');
$this->assertInstanceOf(Column::class, $column);
$this->assertInstanceOf(ColumnCollection::class, $grid->getColumns());
$this->assertCount(1, $grid->getColumns());
$this->assertSame($column, $grid->getColumns()->first());
$this->assertSame($column, $grid->getColumns()->last());
}
/** @test */
public function itAddsManyColumns()
{
$grid = $this->itHasAGridInstance();
$firstColumn = $grid->addColumn('first', 'First');
$grid->addColumn('middle', 'Middle');
$lastColumn = $grid->addColumn('last', 'Last');
$this->assertInstanceOf(ColumnCollection::class, $grid->getColumns());
$this->assertCount(3, $grid->getColumns());
$this->assertSame($firstColumn, $grid->getColumns()->first());
$this->assertSame($lastColumn, $grid->getColumns()->last());
}
}
<file_sep><?php
namespace QueryGrid\QueryGrid\Contracts;
use QueryGrid\QueryGrid\Columns\OrderBy;
use QueryGrid\QueryGrid\Query;
interface DataProvider
{
/**
* @param string $resource
* @return mixed
*/
public function setResource(string $resource);
/**
* @return array
*/
public function get(): array;
/**
* @param array $filters
* @return mixed
*/
public function setFilters(array $filters);
/**
* @param Query $query
* @return mixed
*/
public function setQuery(Query $query);
/**
* @param OrderBy $orderBy
* @return mixed
*/
public function addOrderBy(OrderBy $orderBy);
}
|
042c05896418d4f9fa12e5294cfb55dab4f2a212
|
[
"Markdown",
"PHP"
] | 37 |
PHP
|
query-grid/query-grid
|
05fe36899b9f65dd1890431b28a5d2cca5bd56c6
|
9f5876d85ff0291b3fb4084ab5957b2b3f9ca146
|
refs/heads/master
|
<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'dynamic-menu',
templateUrl: 'app/templates/dynamicmenu-template.html'
})
export class DynamicMenuComponent {
}
|
006ed4c296471d4cd8b58c044904d4c84c7210bc
|
[
"TypeScript"
] | 1 |
TypeScript
|
AbdulIfthekar/feed
|
56983d79b0efcd52c52dd4465084ed1f0a15b285
|
766602e2dfb4b22bfcbb3f72946cf06062f4983d
|
refs/heads/master
|
<file_sep>import React,{Component} from 'react';
class CountWords extends Component{
constructor(props){
super(props);
this.state={
array:[],
sentence:"",
word:'',
count:0,
counts:0
};
}
inputHandler = (e) => {
const { sentence, word, array } = this.state;
array.push(sentence);
var sen = array[Math.floor(Math.random() * array.length)];
var sSplit = sen.split(" ");
this.setState({ count: sSplit.length });
var cntr = 0;
for (let i = 0; i < sSplit.length; i++) {
if (sSplit[i] === word) {
cntr += 1;
}
}
this.setState({ occurrence: cntr });
}
render() {
const { sentence, word, count, occurrence } = this.state;
return (
<div class = "container">
<center>
<div class ="box">
<h1> Sentence: <input placeholder="input sentence here..."onChange={e => this.setState({ sentence: e.target.value })}></input></h1>
<br></br>
<h1>Words: <input placeholder="input words here..." onChange={e=> this.setState({ word: e.target.value })}></input></h1>
<div><button onClick={event => this.inputHandler(event)}>Count</button></div>
<div><h2>Inputed text: {sentence}</h2></div>
<div><h2> words: {count}</h2></div>
<div><h2>word occurrence:{word} : {occurrence}</h2></div>
</div>
</center>
</div>
);
}
}
export default CountWords;<file_sep>import React,{Component} from 'react';
import CountWords from './CountWords';
import './MyStyle.css'
class Pm_number1 extends Component {
render (){
return (
<div><CountWords/></div>
);
}
}
export default Pm_number1;
|
b5b8cf17861ba3b7fddba48e745c6126dd894730
|
[
"JavaScript"
] | 2 |
JavaScript
|
annabelle1999Belcina/pm_num1
|
4679275d153a2b7b57fa77c5e0c48429e28a3257
|
4d11d0a15214d969c4f8229659ab9a89c6dacaf6
|
refs/heads/master
|
<repo_name>vivekmore/intellij-postfix-templates<file_sep>/src/de/endrullis/idea/postfixtemplates/languages/kotlin/KotlinPostfixTemplateProvider.java
package de.endrullis.idea.postfixtemplates.languages.kotlin;
import de.endrullis.idea.postfixtemplates.templates.CustomPostfixTemplateProvider;
import org.jetbrains.annotations.NotNull;
public class KotlinPostfixTemplateProvider extends CustomPostfixTemplateProvider {
@NotNull
@Override
protected String getLanguage() {
return "kotlin";
}
@NotNull
@Override
protected CustomKotlinStringPostfixTemplate createTemplate(String matchingClass, String conditionClass, String templateName, String description, String template) {
return new CustomKotlinStringPostfixTemplate(matchingClass, conditionClass, templateName, description, template);
}
}
<file_sep>/README.md
# Custom Postfix Templates for Intellij IDEA
**Custom Postfix Templates** is an Intellij IDEA plugin that allows you to define your own custom [postfix templates](https://blog.jetbrains.com/idea/2014/03/postfix-completion/).
At the moment it supports the following programming languages with : Java, Scala, Kotlin (untyped templates), and JavaScript (untyped templates).

## Download
You can download the plugin **Custom Postfix Templates** via *Settings → Plugins → Browse Repositories*.
## Usage
The plugin comes with a predefined set of templates for Java (see below) which can be immediatly applied in a Java files.
For instance, write
"1".toInt
in a Java file. If the completion popup does not automatically show up, press *Ctrl+SPACE*.
Select the `.toInt` template and see how it is expanded.
## Preconfigured Java templates which bring a tiny bit of the Scala/Kotlin feeling to Java
The following templates are shipped with the plugin and shall provide you with a template basis and with some useful examples:
* `.toByte`, `.toShort`, `.toChar`, `.toInt`, `.toLong`, `.toFloat`, `.toDouble`, `.format` - convert strings and numbers
* `.toList`, `.toSet`, `.toMap` - convert arrays, collections, iterables, and streams to lists, sets, or maps
* `.sort`, `.sortBy` - sort arrays, lists, and streams (by attribute)
* `.minBy`, `.maxBy` - find the minimum/maximum in arrays, collections, iterables, and streams
* `.groupBy` - group arrays, collections, iterables, and streams by attribute
* `.exists`, `.forall` - test if one/all element(s) of an array, a collection, an iterable, or a stream hold(s) a given condition
* `.reverse` - reverse arrays and lists
* `.concat` - concatenate arrays, collections, and streams
* `.mkString` - join the elements (strings) of an array, a collection, an iterable, or a stream into one string by using a given separator
* `.stream` - convert iterable to stream
* `.map` - map the entries of lists, sets, and maps
* `.mapKeys` - map the keys of a map
* `.mapValues` - map the values of a map
* `.getOrElseUpdate` - return the map value of a given key or compute it and return it
* `.filter` - filter the elements of lists, sets, maps, and iterables
* `.reduce` - reduce the elements of arrays, collections, and iterables
* `.fold` - reduce the elements of arrays, collections, and iterables by using a neutral element (similar to Scala fold)
* `.find` - find an element in arrays, collections, iterables, and streams
* `.take` - take a certain number of elements from a stream
* `.drop` - skip a certain number of elements from a stream
* `.size` - get the length or an array
* `.get` - get an element of an array by index
* `.forEach` - iterate over arrays, and optionals
* `.apply` - apply a runnable, supplier, consumer, or predicate
* `.lines` - get the lines of text files, paths, input streams, and strings
* `.content` - get the text content of files, paths, input streams, and URLs
* `.inputStream` - get input stream of files, URLs, strings
* `.outputStream` - get output stream for files
* `.bufferedReader` - get buffered reader for files, input streams, and URLs
* `.bufferedWriter` - get buffered writer for files and output streams
* `.printStream` - get PrintStream for files and output streams
* `.r` - convert a string into a regular expression
* `.val` - extract the expression as value (similar to the `.var` template)
* `.new` - create a new instance of a class
The idea behind these templates is to bring a tiny bit of Scala feeling back to Java.
For Scala users there is the live template `_` which expands to `v -> v` to accelerate the creating of lambda expressions.
### Special templates for IDEA (plugin) developers
* `.toVirtualFile` - convert to virtual file
* `.toFile` - convert to file
* `.getAttributes` - get file attributes
* `.openInEditor` - open file in editor
* `.getVirtualFile` - get virtual file
* `.getDocument` - get IDEA document
* `.getPsiFile` - get PSI file
* `.getPsiJavaFile` - get PSI Java file
* `.getPsiPackage` - get PSI package
* `.getChildrenOfType` - get children of an PsiElement and of a certain type
* `.getModule` - get IDEA module
* `.getProject` - get IDEA project
* `.runReadAction` - wrap in an runWriteAction(...) block
* `.runWriteAction` - wrap in an runWriteAction(...) block
* `.invokeLater` - wrap in an invokeLater(...) block
* `.showDiff` - open a diff view
## Edit the templates
Press *Shift+Alt+P* (or go to menu *Tools → Custom Postfix Templates → Edit Templates of Current Language*)
to open the custom postfix templates for the programming language in your current editor.
Here you can easily change, remove, or add new templates matching your needs.
Note that you have to save the template file explicitly (via *Ctrl+S*) in order to update the postfix templates in the IDE.
The file may contain multiple template definitions of the form:
```
.TEMPLATE_NAME : TEMPLATE_DESCRIPTION
MATCHING_TYPE1 [REQUIRED_CLASS1] → TEMPLATE_CODE1
MATCHING_TYPE2 [REQUIRED_CLASS1] → TEMPLATE_CODE2
...
```
* The options for *MATCHING_TYPE* differ from language to language:
* Java: The *MATCHING_TYPE* can be either a Java class name or one of the following special types:
* `ANY` - any expression
* `VOID` - any void expression
* `NON_VOID` - any non-void expression
* `ARRAY` - any Java array
* `BOOLEAN` - boxed or unboxed boolean expressions
* `ITERABLE_OR_ARRAY` - any iterable or array
* `NOT_PRIMITIVE` - any non-primitive value
* `NUMBER` - any boxed or unboxed number
* `BYTE` - a boxed or unboxed byte value
* `SHORT` - a boxed or unboxed short value
* `CHAR` - a boxed or unboxed char value
* `INT` - a boxed or unboxed int value
* `LONG` - a boxed or unboxed long value
* `FLOAT` - a boxed or unboxed float value
* `DOUBLE` - a boxed or unboxed double value
* `NUMBER_LITERAL` - any number literal
* `BYTE_LITERAL` - a byte literal
* `SHORT_LITERAL` - a short literal
* `CHAR_LITERAL` - a char literal
* `INT_LITERAL` - an int literal
* `LONG_LITERAL` - a long literal
* `FLOAT_LITERAL` - a float literal
* `DOUBLE_LITERAL` - a double literal
* `STRING_LITERAL` - a String literal
* `CLASS` - any class reference
* Scala: The *MATCHING_TYPE* can be either a Java class name or one of the following special types:
* `ANY` - any expression
* `VOID` - any void (Unit) expression
* `NON_VOID` - any non-void (non-Unit) expression
* `BOOLEAN` - scala.Boolean or java.lang.Boolean
* `NUMBER` - any Scala or Java number value
* `BYTE` - scala.Byte or java.lang.Byte
* `SHORT` - scala.Short or java.lang.Short
* `CHAR` - scala.Char or java.lang.Char
* `INT` - scala.Int or java.lang.Integer
* `LONG` - scala.Long or java.lang.Long
* `FLOAT` - scala.Float or java.lang.Float
* `DOUBLE` - scala.Double or java.lang.Double
* JavaScript: The *MATCHING_TYPE* has to be `ANY`.
* Kotlin: The *MATCHING_TYPE* has to be `ANY`.
* *REQUIRED_CLASS* (optional) is a name of a class that needs to be available in the module to activate the template rule
* The *TEMPLATE_CODE* can be any text which may also contain template variables used as placeholder.
* The following template variables have a special meaning:
* `$expr$` - the expression the template shall be applied to
* `$END$` - the final cursor position after the template application
* All other variables will be replaced interactively during the template expansion.
The variables have the following format:
```
$NAME#NO:EXPRESSION:DEFAULT_VALUE$
```
* *NAME* - name of the variable; use a `*` at the end of the name to skip user interaction
* *NO* (optional) - number of the variable (defining in which order the variables are expanded)
* *EXPRESSION* (optional) - a live template macro used to generate a replacement (e.g. `suggestVariableName()`)
* *DEFAULT_VALUE* (optional) - a default value that may be used by the macro
* Template examples:
* Artificial example showing variable reordering, variable reusage, interaction skipping, macros, and default values:
```
.test : test
NON_VOID → "$user*#1:user()$: $second#3:className()$ + $first#2::"1st"$ + $first$" + $expr$
```
* Real world example: Write a variable to the debug log, including the developer name, the class name, and method name:
```
.logd : log a variable
NON_VOID → Log.d("$user*:user():"MyTag"$", "$className*:className()$ :: $methodName*:methodName()$): $expr$="+$expr$);
```
While writing the templates you can use the code completion for class names, variable names, template macros and arrows (→).
## Upgrade / reset templates and configure the plugin
Go to *Settings → Editor → Custom Postfix Templates*. Here you can chose between two different lambda styles and reset your templates to the predefined ones of the plugin. Alternatively you can also upgrade your templates file by building a diff between the predefined ones and yours.
## Roadmap
### Version X
* Support for other languages
## Contribute
Any contributions are welcome. Just fork the project, make your changes and create a pull request.
# See also
* [Feature request for custom postfix completion at jetbrains.com](https://youtrack.jetbrains.com/issue/IDEA-122443)
|
cb8c0611ee16bad1a4297d3a4022cb11f2b122d2
|
[
"Markdown",
"Java"
] | 2 |
Java
|
vivekmore/intellij-postfix-templates
|
1996079ac64d420d43ac3e92507f3ab73bd3ea94
|
145b5fc1d5000f1833897ffccf7c1803eec3c07b
|
refs/heads/master
|
<file_sep>#!/bin/bash
# $$\ $$\
# $$ | $$ |
# \$$\ $$ |$$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$\ $$$$$$\
# \$$$$ /$$ __$$\ $$ __$$\ $$ __$$\ $$ | $$ |$$ __$$\
# $$ $$< $$$$$$$$ |$$ | $$ |$$$$$$$$ |$$ | $$ |$$$$$$$$ |
# $$ /\$$\$$ ____|$$ | $$ |$$ ____|$$ | $$ |$$ ____|
# $$ / $$ \$$$$$$$\ $$ | $$ |\$$$$$$$\ \$$$$$$$ |\$$$$$$$\
# \__| \__|\_______|\__| \__| \_______| \____$$ | \_______|
# $$\ $$ |
# \$$$$$$ |
# \______/
#Adding Fastest Mirror
echo "Adding Fastest Mirror"
echo "fastestmirror=true" | sudo tee -a /etc/dnf/dnf.conf
clear
#Update and Upgrade
echo "Updating and Upgrading"
sudo dnf -y update && sudo dnf -y upgrade --refresh
clear
#Install Free & NonFree Repositories
echo "Installing Free & NonFree Repositories"
sudo dnf -y install fedora-workstation-repositories https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm https://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm && sudo rpm -ivh http://linuxdownload.adobe.com/adobe-release/adobe-release-x86_64-1.0-1.noarch.rpm && sudo rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-adobe-linux
sleep 1.5
sudo dnf -y update
clear
#Install NVIDIA Drivers, Media Codecs & Essential Extras
echo "Installing NVIDIA Drivers, Media Codecs & Essential Extras"
sudo dnf -y update && sudo dnf -y install rpmfusion-free-release-tainted && sudo dnf -y install libdvdcss && sudo dnf -y update && sudo dnf -y groupupdate core sound-and-video multimedia && sudo dnf -y install curl libcurl nano util-linux-user cabextract xorg-x11-drv-nvidia xorg-x11-drv-nvidia-cuda xorg-x11-drv-nvidia-cuda-libs akmod-nvidia vulkan vdpauinfo libva-vdpau-driver libva-utils libnfs-utils alsa-plugins-pulseaudio && sudo dnf -y install gstreamer-plugins-bad gstreamer-plugins-ugly lame faad2 && sudo dnf -y install ffmpeg ffmpeg-libs gstreamer-ffmpeg && sudo dnf -y install libaacs libbdplus gstreamer1-libav.x86_64 bash-completion kernel-modules-extra pulseaudio pulseaudio-utils pavucontrol alsa-plugins-pulseaudio
sleep 1.5
sudo dnf -y update
clear
#Install Favourite Apps
echo "Installing Favourite Apps"
sudo dnf -y install google-chrome-stable telegram-desktop discord thunderbird gnome-tweak-tool chrome-gnome-shell gnome-shell-extension-dash-to-dock gimp gimp-help-en_GB obs-studio audacity lollypop autokey-gtk ckb-next filezilla fish nano cmatrix neofetch openshot blender inkscape rdiff-backup && sudo dnf -y remove rhythmbox
sleep 1.5
sudo dnf -y update
clear
#Install Fonts
#Fira
echo "Installing Fira Fonts"
sudo dnf -y install mozilla-fira-fonts-common mozilla-fira-mono-fonts mozilla-fira-sans-fonts
fc-cache -v
#Adobe
echo "Installing Adobe Fonts"
sudo dnf -y install adobe-source-code-pro-fonts
fc-cache -v
#Microsoft
echo "Installing Microsoft Fonts"
sudo rpm -i https://downloads.sourceforge.net/project/mscorefonts2/rpms/msttcore-fonts-installer-2.6-1.noarch.rpm
fc-cache -v
#Droid
echo "Installing Droid Fonts"
sudo dnf -y install google-droid-serif-fonts google-droid-sans-mono-fonts google-droid-sans-fonts
fc-cache -v
#Google
echo "Installing Google Fonts"
sudo dnf -y install google-noto-fonts-common google-noto-emoji-fonts google-roboto-fonts google-roboto-slab-fonts google-roboto-condensed-fonts
fc-cache -v
#Bitstream Vera
echo "Installing Bitstream Vera Fonts"
sudo dnf -y install bitstream-vera-sans-fonts bitstream-vera-serif-fonts bitstream-vera-fonts-common bitstream-vera-sans-mono-fonts
fc-cache -v
#Cantarell
echo "Installing Cantarell Fonts"
sudo dnf -y install abattis-cantarell-fonts
fc-cache -v
clear
#Install Themes
echo "Installing Yaru Goodies"
sudo dnf -y install yaru-icon-theme yaru-sound-theme yaru-theme gnome-shell-theme-yaru yaru-gtk2-theme yaru-gtk3-theme
echo "Installing Arc Theme"
#Arc Theme:
sudo dnf -y install arc-theme
echo "Installing Papirus Theme"
#Papirus Theme:
sudo dnf -y install papirus-icon-theme
echo "Installing Suru++"
#Suru++ Icon Theme:
sudo wget -qO- https://raw.githubusercontent.com/gusbemacbe/suru-plus/master/install.sh | sh
echo "Installing Breeze Cursor"
#Breeze Cursor:
sudo dnf -y install breeze-cursor-theme
clear
#Install Game Apps
echo "Installing Game Apps"
sudo dnf -y install steam lutris gamemode
sleep 1.5
sudo dnf -y update
clear
#Install Plexamp
echo "Installing Plexamp"
sudo wget https://plexamp.plex.tv/plexamp.plex.tv/plexamp-1.1.0-x86_64.AppImage
sudo chmod +x plexamp-1.1.0-x86_64.AppImage
sudo cp plexamp-1.1.0-x86_64.AppImage /usr/bin/plexamp
sudo rm plexamp-1.1.0-x86_64.AppImage
sleep 1.5
clear
#Set Fish as default shell
sudo chsh -s /usr/bin/fish
clear
echo "##---------------------------------------------------------##
# Install Completed - Rebooting shortly #
##---------------------------------------------------------##"
sleep 10
sudo reboot
<file_sep># newfedg
Stuff to do after fresh Fedora Workstation (Gnome) install
|
544be9b8210c20d6ed03f25e1116994fdc7d4ec1
|
[
"Markdown",
"Shell"
] | 2 |
Shell
|
Xeneye/newfedg
|
66b02f944ff050b075d737c32c53d3a4f5f421e0
|
fab37e2a35d402bb55813f6c939a3592067e2938
|
refs/heads/master
|
<file_sep>#include "directGraph.h"
#include"gate.h"
#include"simulator.h"
#include<stdio.h>
#include<vector>
#include<stack>
#include <iostream>
using namespace std;
void initial(directGraph<gate> * circuit);
void encode(unsigned int * x, unsigned char size);
void printTrTable(unsigned int * x, unsigned char size, unsigned int z);
void printFaultList(unsigned int * x, unsigned char size, Simulator simulator, unsigned int position);
void printFaultList(unsigned int * x, unsigned char size, Simulator simulator, unsigned int position, unsigned int patten);
void printGateName(unsigned int gateid);
enum gatelist{
X1,
X2,
X3,
Y1,
Y2,
A,
B,
D
};
int main(void){
directGraph<gate> * circuit = new directGraph<gate>();
initial(circuit);
unsigned int x[3] = { 0 };
encode(x, 3);
Simulator simulator (circuit, x);
//printTrTable(x, 3, simulator.getOutput(D));
simulator.getFaultList(D);
for (int line = 0; line < 8; line++) {
printGateName(line);
printf("\n");
printFaultList(x, 3, simulator, line, 6);
}
system("pause");
return 0;
}
void initial(directGraph<gate> * circuit){
circuit->addRoot(BUFFER, X1);
circuit->addRoot(BUFFER, X2);
circuit->addRoot(BUFFER, X3);
circuit->add(BUFFER, Y1, X2);
circuit->add(BUFFER, Y2, X2);
circuit->add(NOR, A, X1);
circuit->link(Y1, A);
circuit->add(NAND, B, Y2);
circuit->link(X3, B);
circuit->add(NOR, D, A);
circuit->link(B, D);
}
void encode(unsigned int * x, unsigned char size){
int i, j;
unsigned int trigger;
for(i = 0; i < size; i++){
trigger = (1<<(1<<i)) -1;
x[i] = 0;
// 32 / (2<<i) == (1<<5)/(1<<(i+1)) == 1 << (4 - i)
for(j = 0; j < (1 << (4 - i)); j++){
x[i] = x[i] | (trigger << (j * (2<<i)));
}
}
}
void printTrTable(unsigned int * x, unsigned char size, unsigned int z){
int i, j;
unsigned int mask;
//mask = (mask << 1) | (mask >> 31) is circular shift
for (i = 0, mask = 1; i < (1 << size); i++, mask = (mask << 1) | (mask >> 31)){
for (j = 0; j < size; j++){
printf("%d ", (x[j] & mask) != 0);
}
printf("| %d\n", (z & mask) != 0);
}
}
void printFaultList(unsigned int * x, unsigned char size, Simulator simulator, unsigned int position){
unsigned int mask = 1;
vector<fault> * faultList = simulator.getFaultList(position);
//mask = (mask << 1) | (mask >> 31) is circular shift
for (int i = 0; i < (1 << size); i++, mask = (mask << 1) | (mask >> 31)) {
for (int j = 0; j < size; j++) {
printf("%d ", (x[j] & mask) != 0);
}
printf("\n-------------------\n");
printf("Stuck At One: ");
unsigned int gateName = 0;
for (auto it = faultList->begin(); it != faultList->end(); ++it, ++gateName){
if (((*it).stuckAtOne & mask) != 0){
printGateName(gateName);
}
}
printf("\n");
printf("Stuck At Zero: ");
gateName = 0;
for (auto it = faultList->begin(); it != faultList->end(); ++it, ++gateName){
if (((*it).stuckAtZero & mask) != 0){
printGateName(gateName);
}
}
printf("\n\n");
}
}
void printFaultList(unsigned int * x, unsigned char size, Simulator simulator, unsigned int position, unsigned int patten){
unsigned int mask = (0x80000000 >> patten);
vector<fault> * faultList = simulator.getFaultList(position);
for (int i = 0; i < size; i++) {
printf("%d ", (x[i] & mask) != 0);
}
printf("\n-------------------\n");
printf("Stuck At One: ");
unsigned int gateName = 0;
for (auto it = faultList->begin(); it != faultList->end(); ++it, ++gateName) {
if (((*it).stuckAtOne & mask) != 0) {
printGateName(gateName);
}
}
printf("\n");
printf("Stuck At Zero: ");
gateName = 0;
for (auto it = faultList->begin(); it != faultList->end(); ++it, ++gateName) {
if (((*it).stuckAtZero & mask) != 0) {
printGateName(gateName);
}
}
printf("\n\n");
}
void printGateName(unsigned int gateid){
switch (gateid){
case X1:printf("X1 "); break;
case X2:printf("X2 "); break;
case X3:printf("X3 "); break;
case Y1:printf("Y1 "); break;
case Y2:printf("Y2 "); break;
case A: printf("A "); break;
case B: printf("B "); break;
case D: printf("D "); break;
default: printf("what???!!!");
}
}
<file_sep>//#include <stdio.h>
//#include <forward_list>
//
//using namespace std;
//
//unsigned int circuit(unsigned int * x);
//unsigned int circuitFA0(unsigned int * x);
//unsigned int circuitFA1(unsigned int * x);
//unsigned int circuitFB0(unsigned int * x);
//unsigned int circuitFB1(unsigned int * x);
//unsigned int circuitFZ0(unsigned int * x);
//unsigned int circuitFZ1(unsigned int * x);
//void encode(unsigned int * x, unsigned char size);
//void printTrTable(unsigned int * x, unsigned char size, unsigned int z);
//forward_list<unsigned int> TPG(unsigned int * x, unsigned char size, unsigned int z, unsigned int zf);
//void printTP(forward_list<unsigned int> TP, unsigned char size);
//
//int main(void){
// unsigned int x[3] = {0};
// unsigned int z_Ffree, z_FA0, z_FA1, z_FB0, z_FB1, z_FZ0, z_FZ1;
//
// encode(x, 3);
//
// z_Ffree = circuit(x);
// z_FA0 = circuitFA0(x);
// z_FA1 = circuitFA1(x);
// z_FB0 = circuitFB0(x);
// z_FB1 = circuitFB1(x);
// z_FZ0 = circuitFZ0(x);
// z_FZ1 = circuitFZ1(x);
//
// forward_list<unsigned int> tp_FA0 = TPG(x, 3, z_Ffree, z_FA0);
// forward_list<unsigned int> tp_FA1 = TPG(x, 3, z_Ffree, z_FA1);
// forward_list<unsigned int> tp_FB0 = TPG(x, 3, z_Ffree, z_FB0);
// forward_list<unsigned int> tp_FB1 = TPG(x, 3, z_Ffree, z_FB1);
// forward_list<unsigned int> tp_FZ0 = TPG(x, 3, z_Ffree, z_FZ0);
// forward_list<unsigned int> tp_FZ1 = TPG(x, 3, z_Ffree, z_FZ1);
//
// printf("truth table\n");
// printf("------- fault free ------\n"); printTrTable(x, 3, z_Ffree); printf("-------------\n\n");
//
// printf("test patten\n");
// printf("-------A stuck at 0------\n"); printTP(tp_FA0, 3); printf("-------------\n\n");
// printf("-------A stuck at 1------\n"); printTP(tp_FA1, 3); printf("-------------\n\n");
// printf("-------B stuck at 0------\n"); printTP(tp_FB0, 3); printf("-------------\n\n");
// printf("-------B stuck at 1------\n"); printTP(tp_FB1, 3); printf("-------------\n\n");
// printf("-------Z stuck at 0------\n"); printTP(tp_FZ0, 3); printf("-------------\n\n");
// printf("-------Z stuck at 1------\n"); printTP(tp_FZ1, 3); printf("-------------\n\n");
//
// system("pause");
// return 0;
//}
//
///*********************************************
// |<- 32bit ->|
//x[0] ... 0101010101010101
//x[1] ... 0011001100110011
//x[2] ... 0000111100001111
//x[3] ... 0000000011111111
// ...
// ...
//*********************************************/
//void encode(unsigned int * x, unsigned char size){
// int i, j;
// unsigned int trigger;
// for(i = 0; i < size; i++){
// trigger = (1<<(1<<i)) -1;
// x[i] = 0;
// // 32 / (2<<i) == (1<<5)/(1<<(i+1)) == 1 << (4 - i)
// for(j = 0; j < (1 << (4 - i)); j++){
// x[i] = x[i] | (trigger << (j * (2<<i)));
// }
// }
//}
//
//void printTrTable(unsigned int * x, unsigned char size, unsigned int z){
// int i, j;
// unsigned int mask;
// //mask = (mask << 1) | (mask >> 31) is circular shift
// for(i = 0, mask = 1; i < (1<<size); i++, mask = (mask << 1) | (mask >> 31)){
// for(j = 0; j < size; j++){
// printf("%d ", (x[j] & mask) !=0);
// }
// printf("| %d\n", (z & mask) !=0);
// }
//}
//
///*********************************************
// |<- 32bit ->|
//pattern 1 ... x[4]x[3]x[2]x[1]x[0]
//pattern 2 ... x[4]x[3]x[2]x[1]x[0]
//pattern 3 ... x[4]x[3]x[2]x[1]x[0]
//pattern 4 ... x[4]x[3]x[2]x[1]x[0]
//...
//...
//*********************************************/
//forward_list<unsigned int> TPG(unsigned int * x, unsigned char size, unsigned int z, unsigned int zf){
// forward_list<unsigned int> TP = forward_list<unsigned int>();
// unsigned int feffect = z ^zf;
// unsigned int pattern_temp;
// unsigned int mask = 1;
// for (int i = 0; i < (1 << size); i++, feffect = feffect >> 1){
// if (feffect & mask){
// pattern_temp = 0;
// for (int j = 0; j < size; j++){
// pattern_temp = pattern_temp | (((x[j]>>i) & mask) << j);
// }
// TP.push_front(pattern_temp);
// }
// }
// return TP;
//}
//
//void printTP(forward_list<unsigned int> TP, unsigned char size){
// unsigned int mask = 1;
// for (auto it = TP.begin(); it != TP.end(); ++it){
// for (int j = 0; j < size; j++){
// printf("%u ", (*it >> j) & mask);
// }
// printf("\n");
// }
//}
//
//unsigned int circuit(unsigned int * x){
// unsigned int a, b, z;
// a = ~(x[0] | x[1]);
// b = ~(x[1] & x[2]);
// z = ~(a | b);
// return z;
//}
//
//unsigned int circuitFA0(unsigned int * x){
// unsigned int a, b, z;
// //a = ~(x[0] | x[1]);
// a = 0;
// b = ~(x[1] & x[2]);
// z = ~(a | b);
// return z;
//}
//
//unsigned int circuitFA1(unsigned int * x){
// unsigned int a, b, z;
// //a = ~(x[0] | x[1]);
// a = 0xffffffff;
// b = ~(x[1] & x[2]);
// z = ~(a | b);
// return z;
//}
//
//unsigned int circuitFB0(unsigned int * x){
// unsigned int a, b, z;
// a = ~(x[0] | x[1]);
// //b = ~(x[1] & x[2]);
// b = 0;
// z = ~(a | b);
// return z;
//}
//
//unsigned int circuitFB1(unsigned int * x){
// unsigned int a, b, z;
// a = ~(x[0] | x[1]);
// //b = ~(x[1] & x[2]);
// b = 0xffffffff;
// z = ~(a | b);
// return z;
//}
//
//unsigned int circuitFZ0(unsigned int * x){
// return 0;
//}
//
//unsigned int circuitFZ1(unsigned int * x){
// return 0xffffffff;
//}
<file_sep>#include "simulator.h"
#include <iostream>
Simulator::Simulator(directGraph<gate> * circuit, unsigned int * PI){
this->circuit = circuit;
this->PI = circuit->getRootList();
nodes = vector<DGNode<gate> *>(circuit->getIdVector());
isVisitedOutput = vector<bool>(nodes.size(), false);
output = vector<unsigned int>(nodes.size(), false);
faultList = vector<vector<fault>>(nodes.size(), vector<fault>(nodes.size(), fault()));
isVisitedFaultList = vector<bool>(nodes.size(), false);
unsigned int crrtId;
int i = 0;
for (auto itPI = this->PI.begin(); itPI != this->PI.end(); ++itPI){
crrtId = (*itPI)->getId();
isVisitedOutput[crrtId] = true;
output[crrtId] = PI[crrtId];
isVisitedFaultList[crrtId] = true;
faultList.at(crrtId)[crrtId] = fault(~PI[crrtId], PI[crrtId]);
}
}
unsigned int Simulator::getOutput(unsigned int id){
if (isVisitedOutput.at(id)){
return output.at(id);
}
unsigned int newOutput;
DGNode<gate> * crrntNode = nodes.at(id);
switch (crrntNode->getValue()){
case AND:
newOutput = 0xffffffff;
for (auto it = crrntNode->getIE()->begin(); it != crrntNode->getIE()->end(); ++it){
newOutput = newOutput & getOutput((*it)->getId());
}
break;
case OR:
newOutput = 0;
for (auto it = crrntNode->getIE()->begin(); it != crrntNode->getIE()->end(); ++it){
newOutput = newOutput | getOutput((*it)->getId());
}
break;
case NAND:
newOutput = 0xffffffff;
for (auto it = crrntNode->getIE()->begin(); it != crrntNode->getIE()->end(); ++it){
newOutput = newOutput & getOutput((*it)->getId());
}
newOutput = ~newOutput;
break;
case NOR:
newOutput = 0;
for (auto it = crrntNode->getIE()->begin(); it != crrntNode->getIE()->end(); ++it){
newOutput = newOutput | getOutput((*it)->getId());
}
newOutput = ~newOutput;
break;
case NOT:
if (++(crrntNode->getIE()->begin()) != crrntNode->getIE()->end()){
cout << "NOT more than one input!!" << endl;
}
newOutput = ~getOutput((*crrntNode->getIE()->begin())->getId());
break;
case BUFFER:
if (++(crrntNode->getIE()->begin()) != crrntNode->getIE()->end()){
cout << "BUFFER more than one input!!" << endl;
}
newOutput = getOutput((*crrntNode->getIE()->begin())->getId());
break;
}
isVisitedOutput[id] = true;
output[id] = newOutput;
return newOutput;
}
vector<fault> * Simulator::getFaultList(unsigned int id)
{
if (isVisitedFaultList.at(id)) {
return &faultList.at(id);
}
vector<fault> newFaultList = vector<fault>(nodes.size(), fault());
DGNode<gate> * crrntNode = nodes.at(id);
switch (crrntNode->getValue()) {
case AND:
//for AND initial to 0 if ouput = 1 (Non-controlling) (to do or), else = 0 (controlling) (to do and)
for (auto it = newFaultList.begin(); it != newFaultList.end(); ++it) {
*it = fault(~getOutput(id), ~getOutput(id));
}
for (auto itIE = crrntNode->getIE()->begin(); itIE != crrntNode->getIE()->end(); ++itIE) {
auto itIEF = getFaultList((*itIE)->getId())->begin();
auto it = newFaultList.begin();
for (;
itIEF != getFaultList((*itIE)->getId())->end(), it != newFaultList.end();
++itIEF, ++it) {
*it = (*it | *itIEF) & getOutput(id) //Non - controlling
| *it & *itIEF & (~(getOutput((*itIE)->getId()))) & (~getOutput(id)) //controlling
| *it & (~(*itIEF)) & getOutput((*itIE)->getId()) & (~getOutput(id)); //controlling
}
}
break;
case OR:
//for OR initial to 0 if ouput = 0 (Non-controlling) (to do or), else = 1 (controlling) (to do and)
for (auto it = newFaultList.begin(); it != newFaultList.end(); ++it) {
*it = fault(getOutput(id), getOutput(id));
}
for (auto itIE = crrntNode->getIE()->begin(); itIE != crrntNode->getIE()->end(); ++itIE) {
auto itIEF = getFaultList((*itIE)->getId())->begin();
auto it = newFaultList.begin();
for (;
itIEF != getFaultList((*itIE)->getId())->end(), it != newFaultList.end();
++itIEF, ++it) {
*it = (*it | *itIEF) & (~getOutput(id)) //Non - controlling
| *it & *itIEF & getOutput((*itIE)->getId()) & getOutput(id) //controlling
| *it & (~(*itIEF)) & (~(getOutput((*itIE)->getId()))) & getOutput(id); //controlling
}
}
break;
case NAND:
//for NAND initial to 0 if ouput = 0 (Non-controlling) (to do or), else = 1 (controlling) (to do and)
for (auto it = newFaultList.begin(); it != newFaultList.end(); ++it) {
*it = fault(getOutput(id), getOutput(id));
}
for (auto itIE = crrntNode->getIE()->begin(); itIE != crrntNode->getIE()->end(); ++itIE) {
auto itIEF = getFaultList((*itIE)->getId())->begin();
auto it = newFaultList.begin();
for (;
itIEF != getFaultList((*itIE)->getId())->end(), it != newFaultList.end();
++itIEF, ++it) {
*it = ((*it | *itIEF) & (~getOutput(id))) //Non - controlling
| (*it & *itIEF & (~(getOutput((*itIE)->getId()))) & getOutput(id)) //controlling
| (*it & (~(*itIEF)) & (getOutput((*itIE)->getId())) & getOutput(id)); //controlling
}
}
break;
case NOR:
//for NOR initial to 0 if ouput = 1 (Non-controlling) (to do or), else = 0 (controlling) (to do and)
for (auto it = newFaultList.begin(); it != newFaultList.end(); ++it) {
*it = fault(~getOutput(id), ~getOutput(id));
}
for (auto itIE = crrntNode->getIE()->begin(); itIE != crrntNode->getIE()->end(); ++itIE) {
auto itIEF = getFaultList((*itIE)->getId())->begin();
auto it = newFaultList.begin();
for (;
itIEF != getFaultList((*itIE)->getId())->end(), it != newFaultList.end();
++itIEF, ++it) {
*it = (*it | *itIEF) & getOutput(id) //Non - controlling
| *it & *itIEF & (getOutput((*itIE)->getId())) & (~getOutput(id)) //controlling
| *it & (~(*itIEF)) & (~(getOutput((*itIE)->getId()))) & (~getOutput(id)); //controlling
}
}
break;
case NOT:
case BUFFER:
if (++(crrntNode->getIE()->begin()) != crrntNode->getIE()->end()) {
cout << "more than one input!!" << endl;
}
newFaultList.assign(getFaultList((*(crrntNode->getIE()->begin()))->getId())->begin(),
getFaultList((*(crrntNode->getIE()->begin()))->getId())->end());
break;
}
newFaultList[id] = fault(~getOutput(id), getOutput(id)); //locally generate fault
isVisitedFaultList[id] = true;
faultList[id] = newFaultList;
return &(faultList[id]);
}
<file_sep>#include "directGraph.h"
#include "gate.h"
#include <iostream>
//***************************************** DGNode *************************************************//
DGNode<gate>::DGNode(unsigned int id){
this->id = id;
value = AND;
outEdge = forward_list<DGNode<gate> *>();
inEdge = forward_list<DGNode<gate> *>();
}
DGNode<gate>::DGNode(unsigned int id, gate value){
this->id = id;
this->value = value;
outEdge = forward_list<DGNode<gate> *>();
inEdge = forward_list<DGNode<gate> *>();
}
void DGNode<gate>::addOE(DGNode<gate> * newNode){
outEdge.push_front(newNode);
}
void DGNode<gate>::addIE(DGNode<gate> * newNode){
inEdge.push_front(newNode);
}
void DGNode<gate>::cutIE(DGNode<gate> * deletNode){
inEdge.remove(deletNode);
}
void DGNode<gate>::cutOE(DGNode<gate> * deletNode){
outEdge.remove(deletNode);
}
//***************************************** directGraph *************************************************//
directGraph<gate>::directGraph(){
}
directGraph<gate>::~directGraph(){
for (auto it = idVector.begin(); it != idVector.end(); ++it){
delete *it;
}
}
void directGraph<gate>::addRoot(gate Avalue){
DGNode<gate> * newNode = new DGNode<gate>(idVector.size() + 1, Avalue);
idVector.push_back(newNode);
rootList.push_front(newNode);
}
void directGraph<gate>::add(gate Avalue, unsigned int Tid){
DGNode<gate> * Node = idVector.at(Tid);
DGNode<gate> * newNode = new DGNode<gate>(idVector.size() + 1, Avalue);
idVector.push_back(newNode);
Node->addOE(newNode);
newNode->addIE(Node);
}
void directGraph<gate>::add(gate Avalue, gate Tvalue){
cout << "don't use this\n";
}
void directGraph<gate>::addRoot(gate Avalue, unsigned int Aid){
DGNode<gate> * newNode = new DGNode<gate>(Aid, Avalue);
if (idVector.size() > Aid){
DGNode<gate> * oldNode = idVector.at(Aid);
for (auto it = oldNode->outEdge.begin(); it != oldNode->outEdge.end(); ++it){
(*it)->cutIE(oldNode);
}
for (auto it = oldNode->inEdge.begin(); it != oldNode->inEdge.end(); ++it){
(*it)->cutOE(oldNode);
}
idVector[Aid] = newNode;
cout << "some gate has been replace!!" << '\n';
}
else{
if (Aid - idVector.size() > 1) cout << "redundant!!" << endl;
for (unsigned int i = idVector.size(); i <= Aid; i++){
idVector.push_back(newNode);
}
}
rootList.push_front(newNode);
}
//Aid is the id of new node, Tid is id of Target node. there will be an edge from Target node to new node
void directGraph<gate>::add(gate Avalue, unsigned int Aid, unsigned int Tid){
DGNode<gate> * Node = idVector.at(Tid);
DGNode<gate> * newNode = new DGNode<gate>(Aid, Avalue);
if (idVector.size() > Aid){
DGNode<gate> * oldNode = idVector.at(Aid);
for (auto it = oldNode->outEdge.begin(); it != oldNode->outEdge.end(); ++it){
(*it)->cutIE(oldNode);
}
for (auto it = oldNode->inEdge.begin(); it != oldNode->inEdge.end(); ++it){
(*it)->cutOE(oldNode);
}
idVector[Aid] = newNode;
cout << "some gate has been replace!!" << '\n';
}
else{
if (Aid - idVector.size() > 1) cout << "redundant!!" << endl;
for (unsigned int i = idVector.size(); i <= Aid; i++){
idVector.push_back(newNode);
}
}
Node->addOE(newNode);
newNode->addIE(Node);
}
void directGraph<gate>::add(gate Avalue, unsigned int Aid, gate Tvalue){
cout << "don't use this\n";
}
//edge direction is fome id1 to id2;
void directGraph<gate>::link(unsigned int id1, unsigned int id2){
DGNode<gate> * Node1 = idVector.at(id1);
DGNode<gate> * Node2 = idVector.at(id2);
Node1->addOE(Node2);
Node2->addIE(Node1);
}<file_sep>#ifndef __DIRECTGRAPH_H__
#define __DIRECTGRAPH_H__
#include <forward_list>
#include <vector>
using namespace std;
template <typename T> class DGNode{
template <typename T> friend class directGraph;
public:
DGNode<T>(unsigned int id);
DGNode<T>(unsigned int id, T value);
unsigned int getId() { return id; };
forward_list<DGNode<T> *> * getOE() { return &outEdge; };
forward_list<DGNode<T> *> * getIE() { return &inEdge; };
T getValue(){ return value; };
private:
unsigned int id;
T value;
forward_list<DGNode<T> *> outEdge;
forward_list<DGNode<T> *> inEdge;
void addOE(DGNode<T> *);
void addIE(DGNode<T> *);
void cutIE(DGNode<T> *);
void cutOE(DGNode<T> *);
};
template <typename T> class directGraph{
public:
directGraph<typename T>();
~directGraph<typename T>();
void addRoot(T Avalue);
void add(T Avalue, unsigned int Tid);
void add(T Avalue, T Tvalue);
void addRoot(T Avalue, unsigned int Aid);
void add(T Avalue, unsigned int Aid, unsigned int Tid);
void add(T Avalue, unsigned int Aid, T Tvalue);
void link(unsigned int id1, unsigned int id2);
forward_list<DGNode<T> *> getRootList() { return rootList; };
vector<DGNode<T> *> getIdVector() { return idVector; };
private:
forward_list<DGNode<T> *> rootList;
vector<DGNode<T> *> idVector;
};
#endif<file_sep>#ifndef __SIMULATOR_H__
#define __SIMULATOR_H__
#include "directGraph.h"
#include "gate.h"
#include<vector>
#include<stack>
struct fault {
unsigned int stuckAtOne;
unsigned int stuckAtZero;
fault(int stuckAtOne = 0, int stuckAtZero = 0)
: stuckAtOne(stuckAtOne), stuckAtZero(stuckAtZero)
{
}
fault operator&(const fault& f2) const {
return fault(stuckAtOne & f2.stuckAtOne, stuckAtZero & f2.stuckAtZero);
}
fault operator&(const unsigned int i) const {
return fault(stuckAtOne & i, stuckAtZero & i);
}
fault operator|(const fault& f2) const {
return fault(stuckAtOne | f2.stuckAtOne, stuckAtZero | f2.stuckAtZero);
}
fault operator|(const unsigned int i) const {
return fault(stuckAtOne | i, stuckAtZero | i);
}
fault operator~() const {
return fault(~stuckAtOne, ~stuckAtZero);
}
};
class Simulator{
public:
Simulator(directGraph<gate> * circuit, unsigned int * PI);
directGraph<gate> * circuit;
forward_list<DGNode<gate> *> PI;
vector<DGNode<gate> *> nodes;
vector<bool> isVisitedOutput;
vector<unsigned int> output;
stack<unsigned int> stackNodes;
vector<bool> isVisitedFaultList;
vector<vector<fault>> faultList; // Actually ,it's list of fault list
unsigned int getOutput(unsigned int id);
vector<fault> * getFaultList(unsigned int id);
};
#endif<file_sep>#ifndef __GATE_H__
#define __GATE_H__
enum gate{
AND,
OR,
NAND,
NOR,
NOT,
BUFFER
};
#endif
|
2801b96076a1bee03300c8f956d9d81f44bd70a6
|
[
"C",
"C++"
] | 7 |
C++
|
jason950374/VLSI-testing-hw1
|
a179692ab9e3e0608b5fb8c1165f0dac50fbdc0e
|
b12c6696619240f827e9c6dd85fd0c748d17a714
|
refs/heads/master
|
<repo_name>2691432189/vue2-responsive<file_sep>/README.md
# vue2-responsive
vue2响应式原理(对象,数组,watch)及其实现源码
<file_sep>/src/observe.js
import Observer from './Observer '
export default function (data) {
// 判断当前属性是否为对象或数组类型,如果不是,则不需要进行响应式处理
if (typeof data != 'object') return
let ob
// 判断当前属性有没有__ob__属性,并且__ob__是Observer的实例,则证明当前属性已经进行过响应式处理
if (data.__ob__ && data.__ob__ instanceof Observer) {
ob = data.__ob__
} else {
ob = new Observer(data)
}
return ob
}
<file_sep>/src/defineReactive.js
import observe from './observe'
import { Dep } from './Dep'
export default function defineReactive(data, key, val) {
const dep = new Dep()
// 正常调用这个方法只需要传data和key,val作为get()和set()的中间件使用
// 递归继续进行响应式处理
if (arguments.length == 2) val = data[key]
let childOb = observe(val)
Object.defineProperty(data, key, {
get() {
console.log('调用了' + key)
// 判断是否有订阅者,有则通过dep.depend()将新的订阅者存入subs中
if (Dep.target) {
dep.depend()
// 判断有没有子元素
if (childOb) {
// 将当前订阅者存入到子元素的Dep订阅发布器中,因为子元素发生改变也需要通知当前属性的订阅者
childOb.dep.depend()
}
}
return val
},
set(newValue) {
console.log('修改了' + key + '为' + newValue)
// 判断当前newValue与val是否完全一致,不是则递归继续进行响应式处理
if (val != newValue) {
observe(newValue)
// 通过val中间件改写get()的返回值
val = newValue
dep.notify()
}
},
})
}
<file_sep>/src/index.js
import observe from './observe'
import { Wather } from './Wather'
let obj = {
a: [10, 20, []],
b: 15,
c: {
d: {
e: 20,
},
},
}
observe(obj)
new Wather(obj, 'a', function (val, oldVal) {
console.log(val)
console.log(oldVal)
console.log('a从' + oldVal + '变成了' + val)
})
obj.a.push(40)
<file_sep>/src/Wather.js
import { Dep } from './Dep'
export class Wather {
constructor(data, expression, cd) {
this.data = data
this.expression = expression
this.cd = cd
this.value = this.get()
}
addDep(dep) {
dep.addSub(this)
}
// 获取订阅属性的值并返回
get() {
// 将当前实例绑定到Dep.target上,window.target上也可以,它是什么属性绑定到什么身上并不重要,重要的是唯一性,因为要将当前Wather实例存入Dep订阅发布器中,是从Dep.target获取到的
Dep.target = this
// getValue()很重要,因为在这个函数中会去调用当前订阅的属性,获取它的属性值,也是因为这一步,getter才会知道都有谁订阅了当前属性,并将它们存入Dep订阅发布器中
const val = parsePath(this.expression)(this.data)
// 进行到这一步,说明当前Wather实例已被存入Dep订阅发布器中,那么为了下一个Wather实例也能正常存入Dep订阅发布器中,我们应把Dep.target清空
Dep.target = null
return val
}
// 当订阅的值发生改变,则调用cd回调函数,将当前对象和新旧三个值传回,并将旧值更改为新值
upLoad() {
const oldValue = deepClone(this.value)
this.value = parsePath(this.expression)(this.data)
this.cd.call(this.data, this.value, oldValue)
}
}
// 获取当前订阅的值
function parsePath(expression) {
const segments = expression.split('.')
return function (obj) {
segments.forEach((key) => {
if (!obj) return
obj = obj[key]
})
return obj
}
}
// 深克隆
function deepClone(val) {
if (typeof val == 'object') {
return JSON.parse(JSON.stringify(val))
} else {
return val
}
}
|
3b4f3e482c611a13ce5621359591f290efeef6a2
|
[
"Markdown",
"JavaScript"
] | 5 |
Markdown
|
2691432189/vue2-responsive
|
114f84201d3980fbd458abbb1b05443232a62ad7
|
80ab5f6be729bf03a3463a4e1192cf3ae3ca51cf
|
refs/heads/master
|
<repo_name>dpalmisano/spdr<file_sep>/tests/fetcher/test_fetcher.py
# MIT License
# Copyright (c) 2020 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import pytest
from pytest import raises
from unittest.mock import patch, call
import time
from spdr.fetcher import Fetcher, PrivateUserException, UserNotFoundException
token = "test-bearer-token"
baseUrl = "https://api.twitter.com/1.1/friends/ids.json"
expected_headers = {
"authorization": f"Bearer {token}",
"content-type": "application/json",
}
class MockResponse:
def __init__(self, status_code, cursor, ids, x_rate_limit_reset=None):
self.status_code = status_code
self.cursor = cursor
self.ids = ids
self.headers = {"x-rate-limit-reset": x_rate_limit_reset}
def json(self):
return {"next_cursor": self.cursor, "ids": self.ids}
def build_url(user_id, cursor):
# fmt: off
return (
f"{baseUrl}?user_id={user_id}&count=5000&stringify_ids=true&cursor={cursor}" # noqa
)
# fmt: on
@pytest.fixture
def fetcher():
return Fetcher(token)
@patch("requests.get")
def test_build_url(mock_requests_get, fetcher):
mock_response = MockResponse(200, 0, ["user-1", "user-2"])
mock_requests_get.return_value = mock_response
actual_users = fetcher.fetch("user-id")
expected_url = build_url("user-id", -1)
mock_requests_get.assert_called_once_with(
expected_url, headers=expected_headers
) # noqa
assert actual_users == ["user-1", "user-2"]
mock_responses = [
MockResponse(200, 1, ["user-1", "user-2"]),
MockResponse(200, 0, ["user-3", "user-4"]),
]
@patch("requests.get", side_effect=mock_responses)
def test_cursor(mock_requests_get, fetcher):
actual_users = fetcher.fetch("user-id")
mock_requests_get.assert_has_calls(
[
call(build_url("user-id", -1), headers=expected_headers),
call(build_url("user-id", 1), headers=expected_headers),
]
)
assert actual_users == ["user-1", "user-2", "user-3", "user-4"]
@patch("requests.get")
def test_handle_private_user(mock_requests_get, fetcher):
mock_response = MockResponse(401, 0, ["user-1", "user-2"])
mock_requests_get.return_value = mock_response
with raises(PrivateUserException) as pue:
actual_users = fetcher.fetch("user-id")
assert pue.user_id == "user-id"
assert actual_users == ["user-1", "user-2"]
@patch("time.sleep")
@patch("requests.get")
def test_handle_too_many_requests(mock_requests_get, mock_time_sleep, fetcher):
time_until_retry = int(time.time()) + 500
mock_responses = [
MockResponse(429, 1, ["user-3"], time_until_retry),
MockResponse(200, 0, ["user-3"]),
]
mock_requests_get.side_effect = mock_responses
actual_users = fetcher.fetch("user-id")
mock_time_sleep.assert_called_once_with(500)
mock_requests_get.assert_has_calls(
[call(build_url("user-id", -1), headers=expected_headers)]
)
assert actual_users == ["user-3"]
@patch("requests.get")
def test_handle_user_not_found(mock_requests_get, fetcher):
mock_response = MockResponse(409, 0, ["user-1", "user-2"])
mock_requests_get.return_value = mock_response
with raises(UserNotFoundException) as pue:
actual_users = fetcher.fetch("user-id")
assert pue.user_id == "user-id"
assert actual_users == ["user-1", "user-2"]
<file_sep>/spdr/fetcher/fetcher.py
# MIT License
# Copyright (c) 2020 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import requests
import time
class FetcherException(Exception):
"""Base class for Fetcher exceptions."""
pass
class PrivateUserException(FetcherException):
def __init__(self, user_id):
self.user_id = user_id
class UserNotFoundException(FetcherException):
def __init__(self, user_id):
self.user_id = user_id
class Fetcher:
baseUrl = "https://api.twitter.com/1.1/friends/ids.json"
def __init__(self, bearer_token):
self.headers = {
"authorization": f"Bearer {bearer_token}",
"content-type": "application/json",
}
def __build_url(self, user_id, cursor):
return f"{Fetcher.baseUrl}?user_id={user_id}&count=5000&stringify_ids=true&cursor={cursor}" # noqa
def fetch(self, user_id):
cursor = -1
users = []
while cursor != 0:
endpointUrl = self.__build_url(user_id, cursor)
response = requests.get(endpointUrl, headers=self.headers)
status_code = response.status_code
response_json = response.json()
if status_code == 200:
cursor = response_json["next_cursor"]
users.extend(response_json["ids"])
elif status_code == 401:
raise PrivateUserException(user_id)
elif status_code == 429:
epoch_until_retry = int(response.headers["x-rate-limit-reset"])
now = int(time.time())
seconds_until_retry = epoch_until_retry - now
time.sleep(seconds_until_retry)
elif status_code == 409:
raise UserNotFoundException(user_id)
else:
raise Exception(
f"""Error while getting users followed by {user_id}
with status code {status_code}"""
)
return users
<file_sep>/spdr/writer/writer.py
# MIT License
# Copyright (c) 2020 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
class Writer:
def __init__(self, output_dir, file_prefix="following"):
self.output_dir = output_dir.rstrip("\/") # noqa
self.file_prefix = file_prefix
def write(self, user_id, user_ids):
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
filepath = f"{self.output_dir}/{self.file_prefix}-{user_id}.out"
with open(filepath, "a+") as fp:
for uid in user_ids:
fp.write(uid + "\n")
return filepath
<file_sep>/spdr/stack/stack.py
# MIT License
# Copyright (c) 2020 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from collections import deque
"""
Stack to keep ids to be explored.
"""
class Stack:
def __init__(self, initial_user_id=None):
self.cache = set()
if initial_user_id is not None:
self.stack = deque([initial_user_id])
else:
self.stack = deque()
def pop(self):
try:
user_id = self.stack.pop()
self.cache.add(user_id)
return user_id
except IndexError:
return None
def push(self, user_id):
if user_id not in self.cache:
self.stack.append(user_id)
def contains(self, user_id):
return user_id in self.stack
def is_candidate(self, user_id):
return user_id not in self.cache and self.contains(user_id) is False
<file_sep>/spdr/spdr.py
# MIT License
# Copyright (c) 2020 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from ratelimit import limits, sleep_and_retry
from spdr.fetcher import PrivateUserException, UserNotFoundException
TIME_PERIOD = 900 # 15 minutes
class Spdr:
@sleep_and_retry
@limits(calls=15, period=TIME_PERIOD)
def __fetch_following(self, current_id):
print(f"Fetching users followed by {current_id}")
try:
return self.fetcher.fetch(current_id)
except PrivateUserException as pue:
print(f"User {pue.user_id} is private. Skipping.")
return None
except UserNotFoundException as unfe:
print(f"User {unfe.user_id} is private. Skipping.")
return None
def __save(self, following, current_id):
output_file = self.writer.write(current_id, following)
print(f"Users following {current_id} written to {output_file}")
def __push_to_stack(self, following):
for user_id in following:
if self.stack.is_candidate(user_id):
self.stack.push(user_id)
def __init__(self, stack, fetcher, writer):
self.stack = stack
self.writer = writer
self.fetcher = fetcher
def start(self, max_depth=1):
current_id = self.stack.pop()
while current_id is not None:
following = self.__fetch_following(current_id)
if following is not None:
self.__save(following, current_id)
self.__push_to_stack(following)
current_id = self.stack.pop()
<file_sep>/README.rst
Spdr: a simple library to crawl the Twitter user graph
==============================================================
.. image:: https://github.com/dpalmisano/spdr/workflows/Tests/badge.svg
:target: https://github.com/dpalmisano/spdr/actions<file_sep>/tox.ini
[tox]
envlist = py35, py36, py37, py38, flake8, black
[testenv]
sitepackages = False
deps =
pytest
pytest-mock<1.12
requests_mock
ratelimit
commands = pytest {posargs}
[testenv:flake8]
skip_install = True
deps =
flake8
commands =
flake8
[testenv:black]
skip_install = True
deps =
black==18.9b0
commands =
black {posargs:--check setup.py spdr tests}
|
876785a43a2498a27812d9b924d70f8758af9829
|
[
"Python",
"reStructuredText",
"INI"
] | 7 |
Python
|
dpalmisano/spdr
|
18dcc45da9f1b4a37ffc11aa59795ed9b5091a40
|
41b95981ede41660d319d62722c34b499d0177a4
|
refs/heads/master
|
<repo_name>allisonnnnnn/lotide<file_sep>/without.js
const assertArraysEqual = require("./assertArraysEqual")
const without = function(source, remove) {
let result = source.filter(item => {
return !remove.includes(item);
});
return result;
};
// TEST
assertArraysEqual(without([1, 2, 3], [1]), [2, 3]);
<file_sep>/tail.js
const assertArraysEqual = require("./assertArraysEqual");
const tail = function(arr) {
return arr.slice(1);
};
const result = tail(["Hello", "Lighthouse", "Labs"]);
assertArraysEqual(result, ["Lighthouse", "Labs"]);
tail(["Hello", "Lighthouse", "Labs"])
module.exports = tail;
<file_sep>/test/countOnlyTest.js
const expect = require("chai").expect;
const countOnly = require("../countOnly");
const firstNames = [
"Karl",
"Salima",
"Agouhanna",
"Fang",
"Kavith",
"Jason",
"Salima",
"Fang",
"Joe"
];
describe("#countOnly", () => {
it('should be true if result1["Jason"] is 1 which occurs only once', () => {
const result1 = countOnly(firstNames, {
Jason: true
// Karima: true,
// Fang: true
});
expect(result1["Jason"]).to.equal(1);
});
it('should be true if result1["Karima"] is undefined', () => {
const result1 = countOnly(firstNames, {
// Jason: true
Karima: true
// Fang: true
});
expect(result1["Karima"]).to.equal(undefined);
});
it('should be true if result1["Fang"] is 2', () => {
const result1 = countOnly(firstNames, {
// Jason: true,
// Karima: true
Fang: true
});
expect(result1["Fang"]).to.equal(2);
});
});
<file_sep>/test/letterPositionsTest.js
const assert = require("chai").assert;
const letterPosition = require("../letterPositions");
describe("#letterPositions", () => {
it('should be true if letterPositions("hello").e is [1]', () => {
assert.deepEqual(letterPosition("hello").e, [1]);
});
});
<file_sep>/test/tailTest.js
const assert = require("chai").assert;
const tail = require("../tail");
// const eqArray = require("../eqArray");
// const assertEqual = require("../assertEqual");
// const result = tail(["Hello", "Lighthouse", "Labs"]);
// assertEqual(result.length, 2);
// assertEqual(result[0], "Lighthouse");
// assertEqual(result[1], "Labs");
// console.log(assertEqual(eqArray(result, ["Lighthouse", "Labs"]), true));
describe("#tail", () => {
it("returns true when the result.length is equal to the given value", () => {
assert.deepEqual(tail(["Hello", "Lighthouse", "Labs"]), [
"Lighthouse",
"Labs"
]);
});
});
<file_sep>/head.js
const assertEqual = require("./assertEqual");
const head = function(arr) {
return arr[0];
};
assertEqual(head([5, 6, 7]), 5);
assertEqual(head(["Hello", "Lighthouse", "Labs"]), "ello");
module.exports = head;
<file_sep>/countLetters.js
const countLetters = function(string) {
let result = {};
// Remove spaces
string = string.replace(/\s/g, "");
for (char of string) {
if (string[char]) {
result[char] += 1;
// *****string[char] = value; !!!!
} else {
result[char] = 1;
}``
}
return result;
};
console.log(countLetters("lighthouse in the house"));
<file_sep>/assertEqual.js
// FUNCTION IMPLEMENTATION
// ASSERT STRING
const assertEqual = function(actual, expected) {
let message = "";
// TEMPLATE LITERALS
actual === expected ? message = `✅Assertion Passed: ${actual} === ${expected}`: message = `🛑Assertion Failed: ${actual} !== ${expected}`
return console.log(message)
};
module.exports = assertEqual;
// TEST CODE
// assertEqual("Lighthouse Labs", "Bootcamp");
// assertEqual(1, 1);
<file_sep>/eqArray.js
// JavaScript doesn't allow the use of === or == to compare two arrays
const assertEqual = require('./assertEqual')
const eqArrays = function(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
for (let i = 0; i < arr1.length; i++) {
if (Array.isArray(arr1[i]) && Array.isArray(arr2[i])) {
if (eqArrays(arr1[i], arr2[i]) === false) {
return false;
}
} else if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
};
module.exports = eqArrays;
assertEqual(eqArrays([1, 2, 3], [1, 2, 3]), true)
<file_sep>/flatten.js
// const eqArrays = function(arr1, arr2) {
// if (arr1.length !== arr2.length) return false;
// for (let i = 0; i < arr1.length; i++) {
// if (arr1[i] !== arr2[i]) {
// return false;
// }
// }
// return true;
// };
// const eqArrays = require("./eqArray");
// const assertArraysEqual = function(arr1, arr2) {
// if (eqArrays(arr1, arr2)) {
// console.log("pass!");
// } else {
// console.log("wrong");
// }
// };
const assertArraysEqual = require("./assertArraysEqual");
const flatten = function(arrSets) {
// return arrSets.reduce((a, b) => a.concat(b), []);
let result = [];
for (let i = 0; i < arrSets.length; i++) {
if (Array.isArray(arrSets[i])) {
for (let j = 0; j < arrSets[i].length; j++) {
result.push(arrSets[i][j]);
}
} else {
result.push(arrSets[i]);
}
}
return result;
};
// const flattenRecursive = function(arrSets) {
// let result = [];
// for (let i = 0; i < arrSets.length; i++) {
// if (Array.isArray(arrSets[i])) {
// result = result.concat(flattenRecursive(arrSets[i]));
// } else {
// result.push(arrSets[i]);
// }
// }
// return result;
// };
// assertArraysEqual(flatten([1, 2, [3, 4], 5, [6]]), [1, 2, 3, 4, 5, 6]);
// assertArraysEqual(flattenRecursive([1, 2, [3, [4]]]), [1, 2, 3, 4]);
// flattenRecursive([3, [4]]);
// flattenRecursive([4]);
// console.log(flatten([1, 2, [3, 4], 5, [6]]));
module.exports = flatten;
<file_sep>/eqObjects.js
// const assertEqual = function(actual, expected) {
// if (actual === expected) {
// console.log(`✅Assertion Passed: ${actual} === ${expected}`);
// } else {
// console.log(`🛑Assertion Failed: ${actual} !== ${expected}`);
// }
// };
// const assertEqual = require("./assertEqual");
const eqArrays = require("./eqArray");
// const eqObjects = function(obj1, obj2) {
// let obj1K = Object.keys(obj1);
// let obj2K = Object.keys(obj2);
// if (obj1K.length !== obj2K.length) {
// return false;
// }
// for (let key of obj1K) {
// if (typeof obj1[key] !== typeof obj2[key]) {
// return false;
// } else if (typeof obj1[key] === typeof obj2[key]) {
// if (Array.isArray(obj1[key]) && Array.isArray(obj2[key])) {
// if (eqArrays(obj1[key], obj2[key]) === false) {
// return false;
// }
// } else {
// if (obj1[key] !== obj2[key]) {
// return false;
// }
// }
// }
// }
// return true;
// };
// Returns true if both objects have identical keys with identical values.
const eqObjects = function(obj1, obj2) {
let obj1K = Object.keys(obj1);
let obj2K = Object.keys(obj2);
if (obj1K.length !== obj2K.length) {
return false;
}
for (let key of obj1K) {
if (obj1[key].length !== obj2[key].length) {
return false;
}
if (typeof obj1[key] !== typeof obj2[key]) {
return false;
} else if (typeof obj1[key] === typeof obj2[key]) {
if (typeof obj1 === "object" && typeof obj2 === "object") {
if (eqObjects(obj1[key], obj2[key]) === false) {
return false;
}
} else if (Array.isArray(obj1[key]) && Array.isArray(obj2[key])) {
if (eqArrays(obj1[key], obj2[key]) === false) {
return false;
}
}
} else {
if (obj1[key] !== obj2[key]) {
return false;
}
}
}
return true;
};
// const ab = { a: "1", b: "2" };
// const ba = { b: "2", a: "1" };
// const abc = { a: "1", b: "2", c: "3" };
// const cba = { b: "2", c: "3", a: "1" };
// // eqObjects(ab, ba);
// assertEqual(eqObjects(ab, ba), true);
// assertEqual(eqObjects(ab, abc), false);
// assertEqual(eqObjects(abc, cba), true);
// const cd = { c: "1", d: ["2", 3] };
// const dc = { d: ["2", 3], c: "1" };
// assertEqual(eqObjects(cd, dc), true);
// const cd2 = { c: "1", d: ["2", 3, 4] };
// assertEqual(eqObjects(cd, cd2), false);
module.exports = eqObjects;
<file_sep>/letterPositions.js
// const eqArrays = function(arr1, arr2) {
// if (arr1.length !== arr2.length) return false;
// for (let i = 0; i < arr1.length; i++) {
// if (Array.isArray(arr1[i]) && Array.isArray(arr2[i])) {
// if (eqArrays(arr1[i], arr2[i]) === false) {
// return false;
// }
// } else if (arr1[i] !== arr2[i]) {
// return false;
// }
// }
// return true;
// };
// const assertArraysEqual = function(arr1, arr2) {
// if (eqArrays(arr1, arr2)) {
// console.log("pass!");
// } else {
// console.log("wrong");
// }
// };
const letterPositions = function(sentence) {
let results = {};
sentence = sentence.split(" ").join("");
for (let i = 0; i < sentence.length; i++) {
if (results[sentence[i]]) {
results[sentence[i]].push(i);
} else {
results[sentence[i]] = [i];
}
}
return results;
};
// assertArraysEqual(letterPositions("hello").e, [1]);
module.exports = letterPositions;
<file_sep>/takeUntil.js
const eqArrays = function(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
for (let i = 0; i < arr1.length; i++) {
if (Array.isArray(arr1[i]) && Array.isArray(arr2[i])) {
if (eqArrays(arr1[i], arr2[i]) === false) {
return false;
}
} else if (arr1[i] !== arr2[i]) {
return false;
}
// not array both use === compare
// one array one not, return false no need to compare
}
return true;
};
const assertArraysEqual = function(arr1, arr2) {
if (eqArrays(arr1, arr2)) {
console.log("pass!");
} else {
console.log("wrong");
}
};
const takeUntil = function(array, callback) {
let result = [];
for (let item of array) {
if (callback(item) === false) {
result.push(item);
} else {
return result;
}
}
}
//??? why we should not return result here?
// return results;
};
const data1 = [1, 2, 5, 7, 2, -1, 2, 4, 5];
const results1 = takeUntil(data1, x => x < 0);
assertArraysEqual(results1);
const data2 = [
"I've",
"been",
"to",
"Hollywood",
",",
"I've",
"been",
"to",
"Redwood"
];
// ?? what is the logic when passing this func?
const results2 = takeUntil(data2, x => x === ",");
// console.log(results2);
assertArraysEqual(results2);
<file_sep>/test/flattenTest.js
const expect = require("chai").expect;
const flatten = require("../flatten");
describe("#flatten", () => {
it("return ture if flatten ([1, 2, [3, 4], 5, [6]]) is equal to [ 1, 2, 3, 4, 5, 6 ]", () => {
expect(flatten([1, 2, [3, 4], 5, [6]])).to.deep.equal([1, 2, 3, 4, 5, 6]);
});
});
<file_sep>/map.js
const eqArrays = function(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
for (let i = 0; i < arr1.length; i++) {
if (Array.isArray(arr1[i]) && Array.isArray(arr2[i])) {
if (eqArrays(arr1[i], arr2[i]) === false) {
return false;
}
} else if (arr1[i] !== arr2[i]) {
return false;
}
// not array both use === compare
// one array one not, return false no need to compare
}
return true;
};
const assertArraysEqual = function(arr1, arr2) {
if (eqArrays(arr1, arr2)) {
console.log("pass!");
} else {
console.log("wrong");
}
};
const words = ["ground", "control", "to", "major", "tom"];
// higher-order function should define ealier
const map = function(array, callback) {
const results = [];
for (let item of array) {
console.log("item BEFORE: ", item);
console.log("item AFTER: ", callback(item));
console.log("---");
}
return results;
};
const results1 = map(words, word => word[0]);
assertArraysEqual(results1);
// const results1 = function(word) {
// return word[0];
// };
// map(words, word => word[0]);
|
1664a0530bf0863e9ca7295ae2d8462444cb0d6c
|
[
"JavaScript"
] | 15 |
JavaScript
|
allisonnnnnn/lotide
|
765e25f3a2326d042174ed16958f88b714cae977
|
41d7b53ca7bd7f7cd095bd86601c83c2788200e9
|
refs/heads/master
|
<file_sep>import hashlib
import random
import string
import json
import binascii
import numpy as np
import pandas as pd
import pylab as pl
import logging
import datetime
import collections
import Crypto
import Crypto.Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from client import *
from transaction import *
from block import *
from utils import *
transactions = []
last_block_hash = ""
TPCoins = []
# Each miner will pick up the transactions from a previously created transaction pool
# To track the number of messages already mined:
last_transaction_index = 0
def dump_blockchain (self):
print ("Number of blocks in the chain: " + str(len (self)))
for x in range (len(TPCoins)):
block_temp = TPCoins[x]
print ("block # " + str(x))
for transaction in block_temp.verified_transactions:
display_transaction (transaction)
print ('--------------')
print ('=====================================')
# mine ("test message", 2)
Dinesh = Client()
Ramesh = Client()
Seema = Client()
Vijay = Client()
t0 = Transaction(
'Genesis',
Dinesh.identity,
500.0
)
# t = Transaction(
# Dinesh,
# Ramesh.identity,
# 5.0
# )
# signature = t.sign_transaction()
# print (signature)
t1 = Transaction(
Dinesh,
Ramesh.identity,
15.0
)
t1.sign_transaction()
transactions.append(t1)
t2 = Transaction(
Dinesh,
Seema.identity,
6.0
)
t2.sign_transaction()
transactions.append(t2)
t3 = Transaction(
Ramesh,
Vijay.identity,
2.0
)
t3.sign_transaction()
transactions.append(t3)
t4 = Transaction(
Seema,
Ramesh.identity,
4.0
)
t4.sign_transaction()
transactions.append(t4)
t5 = Transaction(
Vijay,
Seema.identity,
7.0
)
t5.sign_transaction()
transactions.append(t5)
t6 = Transaction(
Ramesh,
Seema.identity,
3.0
)
t6.sign_transaction()
transactions.append(t6)
t7 = Transaction(
Seema,
Dinesh.identity,
8.0
)
t7.sign_transaction()
transactions.append(t7)
t8 = Transaction(
Seema,
Ramesh.identity,
1.0
)
t8.sign_transaction()
transactions.append(t8)
t9 = Transaction(
Vijay,
Dinesh.identity,
5.0
)
t9.sign_transaction()
transactions.append(t9)
t10 = Transaction(
Vijay,
Ramesh.identity,
3.0
)
t10.sign_transaction()
transactions.append(t10)
# block0 = Block()
# block0.previous_block_hash = None
# Nonce = None
# block0.verified_transactions.append(t0)
# digest = hash(block0)
# last_block_hash = digest
# TPCoins.append (block0)
# dump_blockchain(TPCoins)
# for transaction in transactions:
# display_transaction(transaction)
# print('--------------')
block = Block()
for i in range(3):
temp_transaction = transactions[last_transaction_index]
# validate transaction
# if valid
block.verified_transactions.append (temp_transaction)
last_transaction_index += 1
block.previous_block_hash = last_block_hash
block.Nonce = mine (block, 2)
digest = hash (block)
TPCoins.append (block)
last_block_hash = digest
# Miner 2 adds a block
block = Block()
for i in range(3):
temp_transaction = transactions[last_transaction_index]
# validate transaction
# if valid
block.verified_transactions.append (temp_transaction)
last_transaction_index += 1
block.previous_block_hash = last_block_hash
block.Nonce = mine (block, 2)
digest = hash (block)
TPCoins.append (block)
last_block_hash = digest
# Miner 3 adds a block
block = Block()
for i in range(3):
temp_transaction = transactions[last_transaction_index]
#display_transaction (temp_transaction)
# validate transaction
# if valid
block.verified_transactions.append (temp_transaction)
last_transaction_index += 1
block.previous_block_hash = last_block_hash
block.Nonce = mine (block, 2)
digest = hash (block)
TPCoins.append (block)
last_block_hash = digest
dump_blockchain(TPCoins)<file_sep>from utils import TPCoins
def display_transaction(transaction):
# for transaction in transactions:
dict = transaction.to_dict()
print("sender: " + dict['sender'])
print('-----')
print("recipient: " + dict['recipient'])
print('-----')
print("value: " + str(dict['value']))
print('-----')
print("time: " + str(dict['time']))
print('-----')
def dump_blockchain (self):
print ("Number of blocks in the chain: " + str(len (self)))
for x in range (len(TPCoins)):
block_temp = TPCoins[x]
print ("block # " + str(x))
for transaction in block_temp.verified_transactions:
display_transaction (transaction)
print ('--------------')
print ('=====================================')<file_sep>import hashlib
import random
import string
import json
import binascii
import numpy as np
import pandas as pd
import pylab as pl
import logging
import datetime
import collections
import Crypto
import Crypto.Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from client import *
from transaction import *
Dinesh = Client()
Ramesh = Client()
t = Transaction(
Dinesh,
Ramesh.identity,
5.0
)
signature = t.sign_transaction()
print (signature) <file_sep>
def display_transaction(transaction):
# for transaction in transactions:
dict = transaction.to_dict()
print("sender: " + dict['sender'])
print('-----')
print("recipient: " + dict['recipient'])
print('-----')
print("value: " + str(dict['value']))
print('-----')
print("time: " + str(dict['time']))
print('-----')
<file_sep>import hashlib
import random
import string
import json
import binascii
import numpy as np
import pandas as pd
import pylab as pl
import logging
import datetime
import collections
import Crypto
import Crypto.Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from client import *
from transaction import *
from block import *
from utils import *
transactions = []
last_block_hash = ""
TPCoins = []
def dump_blockchain (self):
print ("Number of blocks in the chain: " + str(len (self)))
for x in range (len(TPCoins)):
block_temp = TPCoins[x]
print ("block # " + str(x))
for transaction in block_temp.verified_transactions:
display_transaction (transaction)
print ('--------------')
print ('=====================================')
Dinesh = Client()
# Ramesh = Client()
# Seema = Client()
# Vijay = Client()
# t = Transaction(
# Dinesh,
# Ramesh.identity,
# 5.0
# )
# signature = t.sign_transaction()
# print (signature)
# t1 = Transaction(
# Dinesh,
# Ramesh.identity,
# 15.0
# )
# t1.sign_transaction()
# transactions.append(t1)
# t2 = Transaction(
# Dinesh,
# Seema.identity,
# 6.0
# )
# t2.sign_transaction()
# transactions.append(t2)
# t3 = Transaction(
# Ramesh,
# Vijay.identity,
# 2.0
# )
# t3.sign_transaction()
# transactions.append(t3)
# t4 = Transaction(
# Seema,
# Ramesh.identity,
# 4.0
# )
# t4.sign_transaction()
# transactions.append(t4)
# t5 = Transaction(
# Vijay,
# Seema.identity,
# 7.0
# )
# t5.sign_transaction()
# transactions.append(t5)
# t6 = Transaction(
# Ramesh,
# Seema.identity,
# 3.0
# )
# t6.sign_transaction()
# transactions.append(t6)
# t7 = Transaction(
# Seema,
# Dinesh.identity,
# 8.0
# )
# t7.sign_transaction()
# transactions.append(t7)
# t8 = Transaction(
# Seema,
# Ramesh.identity,
# 1.0
# )
# t8.sign_transaction()
# transactions.append(t8)
# t9 = Transaction(
# Vijay,
# Dinesh.identity,
# 5.0
# )
# t9.sign_transaction()
# transactions.append(t9)
# t10 = Transaction(
# Vijay,
# Ramesh.identity,
# 3.0
# )
# t10.sign_transaction()
# transactions.append(t10)
t0 = Transaction(
'Genesis',
Dinesh.identity,
500.0
)
block0 = Block()
block0.previous_block_hash = None
Nonce = None
block0.verified_transactions.append(t0)
digest = hash(block0)
last_block_hash = digest
TPCoins.append (block0)
for transaction in transactions:
display_transaction(transaction)
print('--------------')
<file_sep>
import hashlib
def display_transaction(transaction):
# for transaction in transactions:
dict = transaction.to_dict()
print("sender: " + dict['sender'])
print('-----')
print("recipient: " + dict['recipient'])
print('-----')
print("value: " + str(dict['value']))
print('-----')
print("time: " + str(dict['time']))
print('-----')
# takes a message as a parameter, encodes it to ASCII, generates a hexadecimal digest and returns the value to the caller.
def sha256(message):
return hashlib.sha256(message.encode('ascii')).hexdigest()
<file_sep>import Crypto
import Crypto.Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
import binascii
from utils import *
class Client:
def __init__(self):
random = Crypto.Random.new().read
self._private_key = RSA.generate(1024, random)
self._public_key = self._private_key.publickey()
self._signer = PKCS1_v1_5.new(self._private_key)
@property
def identity(self):
return binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')
# We now develop the mine function that implements our own mining strategy.
# Our strategy in this case would be to generate a hash on the given message that is prefixed with a given number of 1’s.
# The given number of 1’s is specified as a parameter to mine function specified as the difficulty level.
# If you specify a difficulty level of 2, the generated hash on a given message should start with two 1’s - like 11xxxxxxxx.
# If the difficulty level is 3, the generated hash should start with three 1’s - like 111xxxxxxxx.
# Note that the generated digest starts with “11”.
# If you change the difficulty level to 3, the generated digest will start with “111”, and of course, it will probably require more number of iterations.
# As you can see, a miner with more processing power will be able to mine a given message earlier.
# That’s how the miners compete with each other for earning their revenues.
def mine(message, difficulty=1):
assert difficulty >= 1
prefix = '1' * difficulty
print('entra a mine')
for i in range(1000):
# print(i)
digest = sha256(str(hash(message)) + str(i))
if digest.startswith(prefix):
print ("after " + str(i) + " iterations found nonce: "+ digest)
return digest
|
38ed88de2f17d58cb639e3f49ae105109c4f43a3
|
[
"Python"
] | 7 |
Python
|
louis97/BcVotaciones1
|
b870c35d77e7193613b8c2895e4ec09e812745b8
|
3f22ae7e27a57e25a2bc1c30cf8bc61a55103c1b
|
refs/heads/master
|
<repo_name>uyansain/gallery<file_sep>/application/views/users/register.php
<?php echo validation_errors(); ?>
<?php echo form_open('users/register'); ?>
<div class="row justify-content-center">
<div class="col-md-4 ">
<h1><?= $title; ?></h1>
<div class="form-group">
<label>Нэр</label>
<input type="text" class="form-control" name="firstname" placeholder="Нэр">
</div>
<div class="form-group">
<label>Овог</label>
<input type="text" class="form-control" name="lastname" placeholder="Овог">
</div>
<div class="form-group">
<label>Цахим шуудан</label>
<input type="text" class="form-control" name="email" placeholder="Email">
</div>
<div class="form-group">
<label>Хэрэглэгчийн нэр</label>
<input type="text" class="form-control" name="username" placeholder="<NAME>">
</div>
<div class="form-group">
<label>Нууц үг</label>
<input type="text" class="form-control" name="password" placeholder="<PASSWORD>">
</div>
<div class="form-group">
<label>Нууц үг давтан хийх</label>
<input type="text" class="form-control" name="password2" placeholder="Confirm password">
</div>
<button type="submit" class="btn btn-primary btn-block">Бүртгүүлэх</button>
</div>
</div>
<?php echo form_close(); ?><file_sep>/application/views/pages/home.php
<br>
<div class="container">
<h2 class="text-center text-primary">Миний зургийн үзэсгэлэнд тавтай морилно уу.</h2>
<br>
<div class="row">
<div class="col-md-8">
<img src="<?php echo site_url(); ?>/assets/images/home.JPG" alt="Urangoo" height="100%" width="100%">
</div>
<div class="col-md-4">
<img src="<?php echo site_url(); ?>/assets/images/posts/kitty1.jpg" alt="Muur" height="100%" width="100%">
</div>
</div>
</div>
<file_sep>/application/views/categories/index.php
<h2><?= $title?></h2>
<table class="table table-active">
<thead>
<tr>
<th scope="col"><h4 class="text-center">Төрөл</h4></th>
<th scope="col"><h4 class="text-center">Устгах</h4></th>
</tr>
</thead>
<tbody>
<?php foreach($categories as $category) : ?>
<tr class="table-primary">
<th scope="row">
<a href="<?php echo site_url('/categories/posts/'.$category['id']); ?>"><?php echo $category['name']; ?></a>
</th>
<td>
<?php if($this->session->userdata('user_id') == $category['user_id']): ?>
<form class="cat-delete" action="categories/delete/<?php echo $category['id']; ?>" method="POST">
<input type="submit" class="btn-link text-danger" value="[устгах]">
</form>
<?php endif; ?>
</td>
<?php endforeach ?>
<file_sep>/application/views/templates/header.php
<!DOCTYPE html>
<html>
<head>
<title>Урангоогийн урлан</title>
<link rel="stylesheet" href="https://bootswatch.com/4/pulse/bootstrap.min.css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/style.css">
<script src="http://cdn.ckeditor.com/4.9.2/standard/ckeditor.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="<?php echo base_url(); ?>">УРАНГОО</a>
<div class="collapse navbar-collapse" id="navbarColor01">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="<?php echo base_url(); ?>">Нүүр</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="<?php echo base_url(); ?>about">Танилцуулга</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="<?php echo base_url(); ?>posts">Галерей</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="<?php echo base_url(); ?>categories">Төрөл</a>
</li>
</ul>
<ul class="navbar-nav navbar-right" >
<?php if(!$this->session->userdata('logged_in')) : ?>
<li><a class="nav-link" href="<?php echo base_url(); ?>users/login">Нэвтрэх</a></li>
<li><a class="nav-link" href="<?php echo base_url(); ?>users/register">Бүртгүүлэх</a></li>
<?php endif; ?>
<?php if($this->session->userdata('logged_in')) : ?>
<li><a class="nav-link" href="<?php echo base_url(); ?>posts/create">Зурах нэмэх</a></li>
<li><a class="nav-link" href="<?php echo base_url(); ?>categories/create">Төрөл нэмэх</a></li>
<li><a class="nav-link" href="<?php echo base_url(); ?>users/logout">Гарах</a></li>
<?php endif ?>
</ul>
</div>
</nav>
<div class="container">
<?php if($this->session->flashdata('user_registered')) : ?>
<?php echo '<p class="alert alert-success">'.$this->session->flashdata('user_registered').'</p>'; ?>
<?php endif; ?>
<?php if($this->session->flashdata('post_created')) : ?>
<?php echo '<p class="alert alert-success">'.$this->session->flashdata('post_created').'</p>'; ?>
<?php endif; ?>
<?php if($this->session->flashdata('post_updated')) : ?>
<?php echo '<p class="alert alert-success">'.$this->session->flashdata('post_updated').'</p>'; ?>
<?php endif; ?>
<?php if($this->session->flashdata('category_created')) : ?>
<?php echo '<p class="alert alert-success">'.$this->session->flashdata('category_created').'</p>'; ?>
<?php endif; ?>
<?php if($this->session->flashdata('post_deleted')) : ?>
<?php echo '<p class="alert alert-success">'.$this->session->flashdata('post_deleted').'</p>'; ?>
<?php endif; ?>
<?php if($this->session->flashdata('login_failed')) : ?>
<?php echo '<p class="alert alert-danger">'.$this->session->flashdata('login_failed').'</p>'; ?>
<?php endif; ?>
<?php if($this->session->flashdata('user_loggedin')) : ?>
<?php echo '<p class="alert alert-success">'.$this->session->flashdata('user_loggedin').'</p>'; ?>
<?php endif; ?>
<?php if($this->session->flashdata('user_loggedout')) : ?>
<?php echo '<p class="alert alert-success">'.$this->session->flashdata('user_loggedout').'</p>'; ?>
<?php endif; ?>
<?php if($this->session->flashdata('category_deleted')) : ?>
<?php echo '<p class="alert alert-success">'.$this->session->flashdata('category_deleted').'</p>'; ?>
<?php endif; ?>
|
d39ac123b46a1b29e6250e6aee63bb5ba8938701
|
[
"PHP"
] | 4 |
PHP
|
uyansain/gallery
|
16ead65d8b86ca9e4f52400d8a6270f8a8cce020
|
b4cf0c43b49a772184ed0f870aae17ad23c99757
|
refs/heads/master
|
<repo_name>parsaha/imdb<file_sep>/README.md
# IMDb EDA
## About
The purpose of this repo is just to house Jupyter notebooks that detail my journey scraping, exploring, cleaning, and presenting IMDb data to find the average rating over all their works that IMDb has listed for any given actor.
There is a folder `imdb-EDA`, showing my process of finding and understanding the data. There is also a folder `general-imdb` which has my notebook where I create the code that actually allows for accessing the average and visalizations.
## Motivation
A general curiosity is to blame. One day I set out to find the average score for movies with <NAME> in them; a week later, the first draft of this repo is being pushed to Github.
## Further Work
In the future, the goal is to add a nicer, more interactive front end.
<file_sep>/general-imdb/actor.py
from matplotlib import pyplot as plt
import pandas as pd
from bs4 import BeautifulSoup
from statistics import mean
from requests import get
import numpy as np
#Since the data cleaning and wrangling process is unique to each `Actor`, we have to find and clean data within the initialization of the `Actor` object.
class Actor:
def __init__(self, actor_link):
# INITIAL DATA
# Finding the actor's IMDb page and getting the list of movies
url = actor_link + '#actor'
response = get(url)
html_soup = BeautifulSoup(response.text, 'html.parser')
movie_containers = html_soup.find_all('div', 'filmo-category-section')
movie_containers = movie_containers[0]
# YEARS
all_years = movie_containers.find_all('span')
self.year_list = []
# Isolating the actual years from the rest of the things in the <span> objects from the html
for year in all_years:
self.year_list.append(str(year).split('\n')[1][1:])
# If there is a range of years (for a TV show), we choose the latter year since ratings are most
# likely reflective of the most recent iteration of the show.
for index, year in enumerate(self.year_list):
if '-' in year:
self.year_list[index] = year.split('-')[1]
'''
IMDb uses roman numerals to differentiate between movies of the same name that were
made the same year; the three lines below address that issue (assuming we don't) run
into any higher numerals; to address this, one can simply manually add a couple more
and should be fine.
Note that we do the higher numerals first so that we don't pick up the '/I' from a
'/II', for example.
'''
if '/I' in year or '/II' in year:
self.year_list[index] = year.split('/II')[0]
self.year_list[index] = year.split('/I')[0]
if year == '':
self.year_list[index] = 0 #our NaN for missing years
self.year_list[index] = int(self.year_list[index])
# TITLES
movie_list = movie_containers.find_all('b')
self.title_list = []
self.tag_list = []
for item in movie_list:
# We find the movie titles...
self.title_list.append(str(item.find('a')).split('>')[-2][:-3])
# ...And the IMDb tags for each title
self.tag_list.append(str(item.find('a')).split('/')[2])
# RATINGS
self.rating_list = []
# We visit each of the actors' titles' pages to find their ratings
for tag in self.tag_list:
url = 'https://www.imdb.com/title/' + tag + '/'
response = get(url)
html_soup = BeautifulSoup(response.text, 'html.parser')
rating_containers = html_soup.find_all('div','ratingValue')
if rating_containers == []:
self.rating_list.append(-1) # our NaN for ratings is -1
continue
rating_str = str(rating_containers[0].find_all('strong')[0])
rating = float(rating_str.split(' based on ')[0][-3:])
self.rating_list.append(rating)
# AVERAGE
self.avg = mean([rating for rating in self.rating_list if rating > -1.0])
#List of attributes that Actor has (and their types):
'''
year_list (list [int])
title_list (list [str])
tag_list (list [str])
rating_list (list [float])
avg (float)
'''
# Creates a DataFrame with the Actor's info in it
def makeDf(self):
return pd.DataFrame(list(zip(self.rating_list, self.year_list, self.title_list)), columns=['Ratings', 'Year', 'Title'])
# graphType decides what type of graph the method will show (between scatter, bar, and plot)
# withMean determines whether the user wants a red horizontal line through the graph to demonstrate where the mean is
def getGraph(self, graphType='s', withMean=False):
# The two lines below ensure that we aren't including our NaN values
valid_years = [year for index,year in enumerate(self.year_list) if year > 1893 and self.rating_list[index] != -1.0]
valid_ratings = [rating for index,rating in enumerate(self.rating_list) if rating > -1.0 and self.year_list[index] != 0]
plt.xlabel('Year')
if graphType not in ['scatter', 's', 'bar', 'b', 'plot', 'p']:
print('Valid name not chosen for parameter graphType; displaying default scatterplot.')
graphType='s'
if graphType == 'scatter' or graphType == 's':
plt.ylabel('Rating')
x = valid_years
y = valid_ratings
plt.scatter(x,y)
elif graphType == 'bar' or graphType == 'b':
plt.ylabel('Average Rating')
unique_year_list = np.unique(np.array(valid_years)) # create a list of just unique years
avg_rating_list = []
for year in unique_year_list:
avg_rating_list.append(mean([rating for index,rating in enumerate(valid_ratings) if valid_years[index] == year]))
x = unique_year_list
y = avg_rating_list
plt.bar(x,y)
elif graphType == 'plot' or graphType == 'p':
plt.ylabel('Rating')
unique_year_list = np.unique(np.array(valid_years))
min_list,avg_list,max_list = [],[],[]
# For each year that the Actor had a role, we take the ratings for that year and find the min, mean, and max
for year in unique_year_list:
ratings_per_year = [rating for index,rating in enumerate(valid_ratings) if valid_years[index] == year]
min_list.append(min(ratings_per_year))
avg_list.append(mean(ratings_per_year))
max_list.append(max(ratings_per_year))
plt.plot(unique_year_list, min_list, color='b', marker='o', label='Min')
plt.plot(unique_year_list, avg_list, color='r', marker='o', label='Mean')
plt.plot(unique_year_list, max_list, color='g', marker='o',label='Max')
plt.legend()
if withMean:
if graphType not in ['plot','p']:
plt.plot([min(x)-1, max(x)+1], [self.avg, self.avg], label='Average', c='r',ls='--')
plt.legend()
else:
print('Plot already has average displayed.')
plt.tight_layout()
|
e471da123a5b6abf8eb7c7a4cf407f90747627c7
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
parsaha/imdb
|
ff0c68b868b1591dbb9447d7b7b63e14218b461c
|
49655e66495d1405e570b1dcd39c6282287f11bd
|
refs/heads/master
|
<repo_name>emisaycheese/IEEE-CIS-Fraud-Detection<file_sep>/IEEE_Fraud_v7-xgb_kfold_groupkfold.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 15:56:52 2019
@author: ruiqianyang
"""
import pandas as pd
from sklearn.model_selection import train_test_split
import lightgbm as lgb
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import LabelEncoder
import numpy as np
import gc
#%%
####data from r
train_r=pd.read_csv('train_r.csv')
test_r=pd.read_csv('test_r.csv')
#del X,test_x
X=train_r.drop(train_r.columns[0],axis=1)
test_x=test_r.drop(test_r.columns[0],axis=1)
label = pd.read_pickle('train_Basic.pkl')
y = label['isFraud']
train=pd.read_pickle('train_Basic.pkl')
test=pd.read_pickle('test_Basic.pkl')
y=y.reset_index(drop=False)
train=train.reset_index(drop=False)
test=test.reset_index(drop=False)
X['TransactionID']=train['TransactionID']
test_x['TransactionID']=test['TransactionID']
X['month']=train['month']
test_x['month']=test['month']
import datetime
startDT = datetime.datetime.strptime('2017-12-01', '%Y-%m-%d')
train['TransactionDT1']=train['TransactionDT'].apply(lambda x:(startDT+datetime.timedelta(seconds=x)))
X['DT_M'] = ((train['TransactionDT1'].dt.year-2017)*12 + train['TransactionDT1'].dt.month).astype(np.int8)
X['DT_M']
for df in [X, test_x]:
for col_1 in df.columns:
if df[col_1].dtype == 'object':
print(col_1)
le = LabelEncoder()
le.fit(list(train_r[col_1].astype(str).values) +
list(test_r[col_1].astype(str).values))
df[col_1] = le.transform(list(df[col_1].astype(str).values))
df.fillna(-999,inplace=True)
df[np.isinf(df.values)==True] = 999
#%%
###minify data
X_12=X[X['month']==12]
y_12=label[label['month']==12]['isFraud']
#%%
#############################XGBOOST kfold##################################
import xgboost as xgb
from sklearn.model_selection import KFold,GroupKFold
import time
start=time.time()
def make_predictions(tr_df, tt_df, features_columns, target,
NFOLDS=10):
#folds = GroupKFold(n_splits=NFOLDS) #GroupKFold by XX
folds = KFold(n_splits=NFOLDS, shuffle=False, random_state=42)
X,y = tr_df[features_columns], tr_df[target]
P,P_y = tt_df[features_columns], tt_df[target]
#split_groups = tr_df['DT_M'] #GroupKFold by XX
tt_df = tt_df[['TransactionID',target]]
#tt_df = tt_df[target]
predictions = np.zeros(len(tt_df))
for fold_, (trn_idx, val_idx) in enumerate(folds.split(X, y)):
# for fold_, (trn_idx, val_idx) in enumerate(folds.split(X, y, groups=split_groups)): #GroupKFold by XX
print('Fold:',fold_)
tr_x, tr_y = X.iloc[trn_idx,:], y[trn_idx]
vl_x, vl_y = X.iloc[val_idx,:], y[val_idx]
print(len(tr_x),len(vl_x))
# tr_data = xgb.DMatrix(tr_x, label=tr_y)
# vl_data = xgb.DMatrix(vl_x, label=vl_y)
# P_D = xgb.DMatrix(P)
# print('train month is '+str(tr_x['month'].unique()))
# print('test month is '+str(vl_x['month'].unique()))
# tr_data = lgb.Dataset(tr_x, label=tr_y)
# if LOCAL_TEST:
# vl_data = lgb.Dataset(P, label=P_y)
# else:
# vl_data = lgb.Dataset(vl_x, label=vl_y)
# estimator = xgb.XGBClassifier.train(
# xgb_params,
# tr_data,
# evals = [(tr_data, 'train'),(vl_data, 'valid')],
# verbose_eval = 50
# )
clf = xgb.XGBClassifier(
n_jobs=4,
n_estimators=500,
max_depth=20,
learning_rate=0.035,
subsample=0.7,
colsample_bytree=0.7463058454739352,
#tree_method='gpu_hist', # THE MAGICAL PARAMETER
reg_alpha=0.39871702770778467,
reg_lamdba=0.24309304355829786,
random_state=2019,
# gamma=0.6665437467229817,
# min_child_weight=,
# max_delta_step=,
# min_child_samples= 170
)
clf.fit(tr_x, tr_y,eval_set = [(tr_x, tr_y),(vl_x, vl_y)], eval_metric="auc",
early_stopping_rounds = 10)
print(time.time()-start)
print('ROC accuracy: {}'.format(roc_auc_score(vl_y, clf.predict_proba(vl_x)[:, 1])))
#pp_p+= clf.predict_proba(P)[:,1]
pp_p = clf.predict_proba(P)[:,1]
print(pp_p)
tt_df['fold '+str(fold_)]=pp_p
predictions += pp_p/NFOLDS #consider weighting predictions??
# print('weight is '+str(w[fold_]))
# predictions += pp_p*w[fold_]
if LOCAL_TEST:
feature_imp = pd.DataFrame(sorted(zip(estimator.feature_importance(),X.columns)),
columns=['Value','Feature'])
print(feature_imp)
del tr_x, tr_y, vl_x, vl_y
gc.collect()
tt_df['prediction'] = predictions
return tt_df
########################### Model Train
LOCAL_TEST = False
TARGET = 'isFraud'
#assign train_df and test_df:
train_df=X.iloc[:]
train_df['isFraud']=y['isFraud']
test_df=test_x.iloc[:]
test_df['isFraud']=0
#!!!if transactionID is index:
train_df=train_df.reset_index(drop=False)
test_df=test_df.reset_index(drop=False)
#make sure 'DT_M' and'TransactionID' are not in feature list
features_columns=list(set(X)-{'DT_M','TransactionID'})
print(len(features_columns))
print(len(X.columns))
test_predictions = make_predictions(train_df, test_df, features_columns, TARGET,NFOLDS=10)
####End XGB KFOLD
#%%
#XGB GROUP kfold##################################
import xgboost as xgb
from sklearn.model_selection import KFold,GroupKFold
import time
start=time.time()
def make_predictions(tr_df, tt_df, features_columns, target,
NFOLDS=7):
folds = GroupKFold(n_splits=NFOLDS) #GroupKFold by DT_M
X,y = tr_df[features_columns], tr_df[target]
P,P_y = tt_df[features_columns], tt_df[target]
split_groups = tr_df['DT_M'] #GroupKFold by XX
tt_df = tt_df[['TransactionID',target]]
predictions = np.zeros(len(tt_df))
for fold_, (trn_idx, val_idx) in enumerate(folds.split(X, y, groups=split_groups)): #GroupKFold by XX
print('Fold:',fold_)
tr_x, tr_y = X.iloc[trn_idx,:], y[trn_idx]
vl_x, vl_y = X.iloc[val_idx,:], y[val_idx]
print(len(tr_x),len(vl_x))
# tr_data = xgb.DMatrix(tr_x, label=tr_y)
# vl_data = xgb.DMatrix(vl_x, label=vl_y)
# P_D = xgb.DMatrix(P)
print('train month is '+str(tr_x['month'].unique()))
print('test month is '+str(vl_x['month'].unique()))
# tr_data = lgb.Dataset(tr_x, label=tr_y)
# if LOCAL_TEST:
# vl_data = lgb.Dataset(P, label=P_y)
# else:
# vl_data = lgb.Dataset(vl_x, label=vl_y)
clf = xgb.XGBClassifier(
n_jobs=4,
n_estimators=500,
max_depth=20,
learning_rate=0.035,
subsample=0.7,
colsample_bytree=0.7463058454739352,
#tree_method='gpu_hist', # THE MAGICAL PARAMETER
reg_alpha=0.39871702770778467,
reg_lamdba=0.24309304355829786,
random_state=2019,
# gamma=0.6665437467229817,
# min_child_weight=,
# max_delta_step=,
# min_child_samples= 170
)
clf.fit(tr_x, tr_y,eval_set = [(tr_x, tr_y),(vl_x, vl_y)], eval_metric="auc",
early_stopping_rounds = 10)
print(time.time()-start)
print('ROC accuracy: {}'.format(roc_auc_score(vl_y, clf.predict_proba(vl_x)[:, 1])))
#pp_p+= clf.predict_proba(P)[:,1]
pp_p = clf.predict_proba(P)[:,1]
print(pp_p)
tt_df['fold '+str(fold_)]=pp_p
predictions += pp_p/NFOLDS #consider weighting predictions??
# print('weight is '+str(w[fold_]))
# predictions += pp_p*w[fold_]
if LOCAL_TEST:
feature_imp = pd.DataFrame(sorted(zip(estimator.feature_importance(),X.columns)),
columns=['Value','Feature'])
print(feature_imp)
del tr_x, tr_y, vl_x, vl_y
gc.collect()
tt_df['prediction'] = predictions
return tt_df
########################### Model Train
LOCAL_TEST = False
TARGET = 'isFraud'
#assign train_df and test_df:
train_df=X.iloc[:]
train_df['isFraud']=y['isFraud']
test_df=test_x.iloc[:]
test_df['isFraud']=0
train_df=train_df.reset_index(drop=False)
test_df=test_df.reset_index(drop=False)
#make sure 'DT_M' and'TransactionID' are not in feature list
features_columns=list(set(X)-{'DT_M','TransactionID'})
print(len(features_columns))
print(len(X.columns))
test_predictions = make_predictions(train_df, test_df, features_columns, TARGET,NFOLDS=7)
####End GROUPKFOLD
#%%
#important to reset index
test_x=test_x.reset_index(drop=False)
test_predictions.to_csv("XGB_Kfold_predictions_every_fold.csv",index=False)
#for kfold/groupkfold/stratifiedkfold
test_x['isFraud']=test_predictions['prediction']
output=test_x[['TransactionID','isFraud']]
output.to_csv("output_submission_XGB_Kfold.csv",index=False)
<file_sep>/README.md
# IEEE-CIS-Fraud-Detection
Kaggle Fraud Transaction Detection competition
---

This is a **private** repo for winning the Kaggle Fraud Transaction Detection competition](https://www.kaggle.com/c/ieee-fraud-detection/) at 217 out of 6300 teams (3%) !
Screenshot place holder.
Account Id
In this repo, we organize our Kaggle core codes into 2 parts: feature engineering (data pipline) and model training.
## Feature Engineering
We did the minimal data cleaning work for this project, as LightGBM model can automatically handle quite a lot, e.g., `missing values`, `outliers`. The current optimal way would be the default choice of the model.
We have different methods for **continuous** and **categorical** data correspondingly.
### Continuous Data.
We have done a variety of mathematical transformation based on the data distributions.
### Categorical Data
We spent the majority of our time on this.
* Risk Mapping and [feature embeding](https://arxiv.org/abs/1604.06737). We understood there was a risk of overfitting but we took extra care to deal with this potential issue.
* Label Transformation. For some categorical features with unknown meanings and less than their unique values was less than a threshold, as [this](https://medium.com/data-design/visiting-categorical-features-and-encoding-in-decision-trees-53400fa65931) suggested, we used the label transformation function directly from `sklearn`. We are aware of the bad implications of this but maybe for tree model, the adversarial impacts are trivial or not significant.
Domain Knowledge: this technique incoporates the common knowledge of our daily life, like a transaction made online is more dangerous than local store, or the hours of transaction made and so on.
Interaction Terms: we used the interactions among features depending on the sole critieror that after the interaction, we could see the boundary of two classes more clearly
The most surprising features we found being useful was countings for the nulls of each row, which makes sense and simple, `"KISS"` as our law.
We used the H2O autoML tool to generate insights/reduce dimensions from some not so important features, e.g., V-type features, features with too many missing values, invarient features.
### Data Pipline
It is coming soon!
## Model Training
### Model
For lightGBM, we had to choose a booster as the core model, we chose `DART` for the following reasons:
Graph place holder (from qishi ml journal club teng)
* Combine the advantages of random forest and gradient boosting tree models
* Our first few trees are not so important thus reducing the effects of overfitting.
* But really slow to train.
(Not ready yet, T will update this)
### Model Segmentation
We have two types of modeling approaches, one is to separate the data via the most important feature - transaction product type and the other one is not. The reason we took these approaches are that we found the product type had dramatic impacts on other features' distributions, missing percentages.
Please find more visualzation evidence in [notebook]. ( T will update this notebook)
### Model Training
For both approaches, we used the CV modules to address the overfiting issues.
* **Cross-validation module** - dealing with overfitting issues
* **Time-series module** - dealing with the time problem. Remember, the train and test dataset are sequential, which test dataset comes later in time
### Hyper-Parameter Optimization
* **Grid Search module**
* **Random Search module**
* **Bayes optimization module** - dealing with high dimensional hyper-parameter space searching
#### Why do we use different methods to search parameters?
Because the search space for LightGBM is so huge and we try to use different methods to find diversified local optimal solutions. (T maybe updates this possibly)
### Model stacking
We built the models from a diversified background to reduce the results correlation and thus achieve a better performance in model stacking.
* **Model stacking module** - dealing with overfitting issues
In addition, after an in-depth research into the computational mechanisms of ROC AUC scores, we found a clever way to play with it and increase the performance.
---
## What are the differentiating factors?
**Techonology** & **Experiences**
* We utilize the cutting-edge machine learning modeling framework and tracking system to greatly increase our collaborating efficiency. Featuretools that let us to focus on the most important features. In addition, we also used `mlflow` to track our ML experiments scientifically and **control** the submissions so that we do not repeat the experiments and avoid overfiting.
* We are a diversified team of data scientist veterans from consulting, banking and hedgefund industry.
## Work for us?
Write separate functions in py file as `utils` and use notebook to call the necessary
* Model Stack module V 3
* Model Segmentation module V 2
* Parameter optimizations: 3 module E 1
* CV and times series E 1
* Data Visual T&E 1
* Show the fancy techs (gradually) T 4
<file_sep>/data_demo/data_demo.md
In this competition you are predicting the probability that an online transaction is fraudulent, as denoted by the binary target isFraud.
The data is broken into two files identity and transaction, which are joined by TransactionID. Not all transactions have corresponding identity information.
This folder has demo data. Datasets only includes 100 rows.
<file_sep>/IEEE_Fraud_gridsearchcv.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 2 17:22:29 2019
@author: ruiqianyang
"""
files=['test_identity.csv',
'test_transaction.csv',
'train_identity.csv',
'train_transaction.csv']
import pandas as pd
def load_data(file):
return pd.read_csv(file,index_col='TransactionID')
#%%
import multiprocessing
import time
with multiprocessing.Pool() as pool:
test_id,test_trans,train_id,train_trans=pool.map(load_data,files)
#%%
train=train_trans.merge(train_id,how='left',left_index=True,right_index=True)
del(train_trans)
del(train_id)
test=test_trans.merge(test_id,how='left',left_index=True,right_index=True)
del test_id, test_trans
#train=pd.merge(train_trans,train_id,on='TransactionID',how='left')
#test=pd.merge(test_trans,test_id,on='TransactionID',how='left')
#%%
import datetime
startDT = datetime.datetime.strptime('2017-12-01', '%Y-%m-%d')
startDT
#add month,day of month,day of week,hour of day
train['TransactionDT1']=train['TransactionDT'].apply(lambda x:(startDT+datetime.timedelta(seconds=x)))
train['month']=train['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%m')))
train['day']=train['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%d')))
train['dayofweek']=train['TransactionDT1'].dt.date.apply(lambda x: x.weekday())
train['hour']=train['TransactionDT1'].apply(lambda x: int(x.strftime('%H')))
train['weekofyear']=train['TransactionDT1'].apply(lambda x: int(x.strftime('%U')))
#engineer Month to start from 12 and monotonous increasing;
#seems redcuce score...
#train['month'] = (train['TransactionDT1'].dt.year-2017)*12 + train['TransactionDT1'].dt.month
test['TransactionDT1']=test['TransactionDT'].apply(lambda x:(startDT+datetime.timedelta(seconds=x)))
test['month']=test['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%m')))
test['day']=test['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%d')))
test['dayofweek']=test['TransactionDT1'].dt.date.apply(lambda x: x.weekday())
test['hour']=test['TransactionDT1'].apply(lambda x: int(x.strftime('%H')))
test['weekofyear']=test['TransactionDT1'].apply(lambda x: int(x.strftime('%U')))
#engineer Month to start from 12 and monotonous increasing;
#test['month'] = (test['TransactionDT1'].dt.year-2017)*12 + test['TransactionDT1'].dt.month
#test.head(3)
#%%
train['TransactionAmt_decimal'] = ((train['TransactionAmt'] - train['TransactionAmt'].astype(int)) * 1000).astype(int)
test['TransactionAmt_decimal'] = ((test['TransactionAmt'] - test['TransactionAmt'].astype(int)) * 1000).astype(int)
#plot_numerical1('TransactionAmt_decimal')
#creat new feature: Number of NaN's
train['nulls']=train.isnull().sum(axis=1)
test['nulls']=test.isnull().sum(axis=1)
################################################################################
#%%
from sklearn.model_selection import train_test_split
import lightgbm as lgb
from sklearn.metrics import roc_auc_score
import pickle
y = train['isFraud']
X = pd.DataFrame()
col=['TransactionDT','ProductCD','P_emaildomain','R_emaildomain','nulls','month','hour',
'TransactionAmt', 'TransactionAmt_decimal','D5','D2','D8','D9','D11','D15','C1','C4','C8','C10','C13','C2',
'V256','V13','card1','card2','card3','card4', 'card5', 'card6','addr1','M4','M5','M6','M1','DeviceType',
'DeviceInfo', 'addr2','D6','D13','C5','C9','D7','C14','V145',
'V3','V4','V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V17',
'V19', 'V20', 'V29', 'V30', 'V33', 'V34', 'V35', 'V36', 'V37', 'V38', 'V40', 'V44', 'V45', 'V46', 'V47', 'V48',
'V49', 'V51', 'V52', 'V53', 'V54', 'V56', 'V58', 'V59', 'V60', 'V61', 'V62', 'V63', 'V64', 'V69', 'V70', 'V71',
'V72', 'V73', 'V74', 'V75', 'V76', 'V78', 'V80', 'V81', 'V82', 'V83', 'V84', 'V85', 'V87', 'V90', 'V91', 'V92',
'V93', 'V94', 'V95', 'V96', 'V97', 'V99', 'V100', 'V126', 'V127', 'V128', 'V130', 'V131', 'V138', 'V139', 'V140',
'V143', 'V146', 'V147', 'V149', 'V150', 'V151', 'V152', 'V154', 'V156', 'V158', 'V159', 'V160', 'V161',
'V162', 'V163', 'V164', 'V165', 'V166', 'V167', 'V169', 'V170', 'V171', 'V172', 'V173', 'V175', 'V176', 'V177',
'V178', 'V180', 'V182', 'V184', 'V187', 'V188', 'V189', 'V195', 'V197', 'V200', 'V201', 'V202', 'V203', 'V204',
'V205', 'V206', 'V207', 'V208', 'V209', 'V210', 'V212', 'V213', 'V214', 'V215', 'V216', 'V217', 'V219', 'V220',
'V221', 'V222', 'V223', 'V224', 'V225', 'V226', 'V227', 'V228', 'V229', 'V231', 'V233', 'V234', 'V238', 'V239',
'V242', 'V243', 'V244', 'V245', 'V246', 'V247', 'V249', 'V251', 'V253', 'V257', 'V258', 'V259', 'V261',
'V262', 'V263', 'V264', 'V265', 'V266', 'V267', 'V268', 'V270', 'V271', 'V272', 'V273', 'V274', 'V275', 'V276',
'V277', 'V278', 'V279', 'V280', 'V282', 'V283', 'V285', 'V287', 'V288', 'V289', 'V291', 'V292', 'V294', 'V303',
'V304', 'V306', 'V307', 'V308', 'V310', 'V312', 'V313', 'V314', 'V315', 'V317', 'V322',
'V323','V324', 'V326','V329','V331','V332', 'V333', 'V335', 'V336',
'id_01', 'id_02', 'id_03', 'id_05', 'id_06', 'id_09',
'id_11', 'id_12', 'id_13', 'id_14', 'id_15', 'id_17', 'id_19', 'id_20', 'id_30', 'id_31', 'id_32', 'id_33',
'id_36', 'id_37', 'id_38','isFraud']
# Save to pickle
#New_DatasetName = "Basic"
#train[col].to_pickle("train_{}.pkl".format(New_DatasetName))
#test[col[:-1]].to_pickle("test_{}.pkl".format(New_DatasetName))
col.pop()
X[col] = train[col]
X['M4_count'] =X['M4'].map(pd.concat([train['M4'], test['M4']], ignore_index=True).value_counts(dropna=False))
X['M6_count'] =X['M6'].map(pd.concat([train['M6'], test['M6']], ignore_index=True).value_counts(dropna=False))
X['card1_count'] = X['card1'].map(pd.concat([train['card1'], test['card1']], ignore_index=True).value_counts(dropna=False))
X['card6_count'] =X['card6'].map(pd.concat([train['card6'], test['card6']], ignore_index=True).value_counts(dropna=False))
X['DeviceType_count'] =X['DeviceType'].map(pd.concat([train['DeviceType'], test['DeviceType']], ignore_index=True).value_counts(dropna=False))
#X['DeviceInfo_count'] =X['DeviceInfo'].map(pd.concat([train['DeviceInfo'], test['DeviceInfo']], ignore_index=True).value_counts(dropna=False))
X['ProductCD_count'] =X['ProductCD'].map(pd.concat([train['ProductCD'], test['ProductCD']], ignore_index=True).value_counts(dropna=False))
X['P_emaildomain_count'] =X['P_emaildomain'].map(pd.concat([train['P_emaildomain'], test['P_emaildomain']], ignore_index=True).value_counts(dropna=False))
#X['R_emaildomain_count'] =X['R_emaildomain'].map(pd.concat([train['R_emaildomain'], test['R_emaildomain']], ignore_index=True).value_counts(dropna=False))
X['addr1_count'] = X['addr1'].map(pd.concat([train['addr1'], test['addr1']], ignore_index=True).value_counts(dropna=False))
# Risk mapping transformation
card4_dic = {'american express':287,'discover':773,'mastercard':343,'visa':348}
X['card4_dic']=X['card4'].map(card4_dic)
ProductCD_dic = {'C':117,'H':48,'R':38,'S':59,'W':20}
X['ProductCD_dic']=X['ProductCD'].map(ProductCD_dic)
card6_dic = {'charge card':0,'credit':668,'debit':243,'debit or credit':0}
X['card6_dic']=X['card6'].map(card6_dic)
#train=train.replace({'card6':card6_dic})
#test=test.replace({'card6':card6_dic})
M1_dic={'F':0,'T':2}
X['M1_dic']=X['M1'].map(M1_dic)
M4_dic={'M0':4,'M1':3,'M2':13}
X['M4_dic']=X['M4'].map(M4_dic)
M5_dic={'F':2,'T':3}
X['M5_dic']=X['M5'].map(M5_dic)
M6_dic={'F':4,'T':3}
X['M6_dic']=X['M6'].map(M6_dic)
#DeviceInfo has many category levels
#DeviceType_dic={'desktop':3,'mobile':5}
#X['DeviceType_dic']=X['DeviceType'].map(DeviceType_dic)
P_emaildomain_dic={'protonmail.com':40,'mail.com':19,'outlook.es':13,'aim.com':12,
'outlook.com':9,'hotmail.es':7,'live.com.mx':5,'hotmail.com':5,'gmail.com':4}
X['P_emaildomain_dic']=X['P_emaildomain'].map(P_emaildomain_dic)
R_emaildomain_dic={'protonmail.com':95,'mail.com':38,'netzero.net':22,'outlook.com':17,
'outlook.es':13,'icloud.com':13,'gmail.com':12,'hotmail.com':8,
'earthlink.net':8,'earthlink.net':7,'hotmail.es':7,'live.com.mx':6,
'yahoo.com':5,'live.com':5}
X['R_emaildomain_dic']=X['R_emaildomain'].map(R_emaildomain_dic)
#New feature:C2 vs TransactionDT
def func_C2_Tran(a,b):
if a<400:
return 344
elif a>=400 and a<=651 and b<=4000000:
return 3846
elif a>=400 and a<=651 and b>10000000:
return 10000
else:
return 1082
X['C2_TransactionDT']=X.apply(lambda x:func_C2_Tran(x['C2'],x['TransactionDT']),axis=1)
for feature in ['id_30','id_02', 'id_03', 'id_06', 'id_09','id_11', 'id_14',
'id_17', 'id_19', 'id_20', 'id_32']:
# Count encoded separately for train and test,
X[feature + '_count'] = X[feature].map(pd.concat([train[feature], test[feature]], ignore_index=True).value_counts(dropna=False))
X=X.drop(columns=['ProductCD','P_emaildomain','R_emaildomain','M4','M5','M6','M1','card6', 'DeviceType','DeviceInfo','card4','id_02','id_19','id_20','id_17','C2','TransactionDT','addr2','D6','D13','C5','C9','D7','C14','id_12', 'id_15', 'id_30', 'id_31', 'id_33', 'id_36', 'id_37', 'id_38'
])
#%%
print('start fillna')
X['addr1'].fillna(0, inplace=True)
#X['addr2_dic'].fillna(3, inplace=True)
#X['addr2'].fillna(96, inplace=True)
#X['D5'].fillna(150, inplace=True)
X['D2'].fillna(10, inplace=True)
X['D11'].fillna(10, inplace=True)
X['D15'].fillna(376, inplace=True)
#X['V1'].fillna(X['V1'].mode()[0], inplace=True)
#X['V2'].fillna(3, inplace=True)
X['V13'].fillna(X['V13'].mode()[0], inplace=True)
#X['V145'].fillna(X['V145'].mode()[0], inplace=True) #fillna reduce score
#X['V263'].fillna(X['V263'].mode()[0], inplace=True)
#X['V256'].fillna(X['V256'].mode()[0], inplace=True)
X['card2'].fillna(502, inplace=True)
###X['card3'].fillna(150, inplace=True)
X['card4_dic'].fillna(X['card4_dic'].mode()[0], inplace=True)
X['M4_dic'].fillna(2, inplace=True)
X['M5_dic'].fillna(3, inplace=True) #24:18:78
X['M6_dic'].fillna(13, inplace=True) #24:18:78
X['P_emaildomain_dic'].fillna(0, inplace=True)
X['R_emaildomain_dic'].fillna(0, inplace=True)
####start GridSearchCV
#%%
#train test split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.33, random_state=47, shuffle=False)
#%%
#add grid of paramters
print('start GridSearchCV')
from sklearn.model_selection import GridSearchCV
lg = lgb.LGBMClassifier(silent=False)
param_dist = {"max_depth": [25], #<=0 means no limit
"learning_rate" : [0.05],
"num_leaves": [256],
"n_estimators": [300,1800,3000],
'min_child_samples':[20],
'bagging_fraction': [0.42],
'feature_fraction': [0.38],
'min_child_weight': [0.00298],
'min_data_in_leaf': [106],
'reg_alpha': [0.38999],
'reg_lambda': [2.0]
}
#candidates for param
# "max_depth": [5,25,-1,50],
# "learning_rate" : [0.05,0.00688,0.01],
# "num_leaves": [300, 491,382,2**8],
# "n_estimators": [300,800],
# 'min_child_samples':[20],
# 'bagging_fraction': [0.42,0.9],
# 'feature_fraction': [0.38,0.9],
# 'min_child_weight': [0.00298,0.03454],
# 'min_data_in_leaf': [20,106],
# 'reg_alpha': [1.0,0.38999],
# 'reg_lambda': [2.0,0.6485],
# 'colsample_bytree': 0.7,
# 'subsample_freq':1,
# 'subsample':0.7,
# 'max_bin':255,
# 'verbose':-1,
# 'seed': SEED,
# 'early_stopping_rounds':100,
grid_search = GridSearchCV(lg, param_grid=param_dist, cv = 3, scoring="roc_auc", verbose=5)
grid_search.fit(X_train,y_train)
print(grid_search.best_estimator_)
<file_sep>/IEEE_Fraud_timeseriessplit.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 2 17:15:26 2019
@author: ruiqianyang
"""
#
#files=['test_identity.csv',
# 'test_transaction.csv',
# 'train_identity.csv',
# 'train_transaction.csv']
#
#import pandas as pd
#def load_data(file):
# return pd.read_csv(file,index_col='TransactionID')
##%%
#import multiprocessing
#import time
#with multiprocessing.Pool() as pool:
# test_id,test_trans,train_id,train_trans=pool.map(load_data,files)
#
##%%
#train=train_trans.merge(train_id,how='left',left_index=True,right_index=True)
#test=test_trans.merge(test_id,how='left',left_index=True,right_index=True)
#
#
#import datetime
#startDT = datetime.datetime.strptime('2017-12-01', '%Y-%m-%d')
#startDT
##add month,day of month,day of week,hour of day
#train['TransactionDT1']=train['TransactionDT'].apply(lambda x:(startDT+datetime.timedelta(seconds=x)))
#train['month']=train['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%m')))
#train['day']=train['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%d')))
#train['dayofweek']=train['TransactionDT1'].dt.date.apply(lambda x: x.weekday())
#train['hour']=train['TransactionDT1'].apply(lambda x: int(x.strftime('%H')))
#train['weekofyear']=train['TransactionDT1'].apply(lambda x: int(x.strftime('%U')))
#
##engineer Month to start from 12 and monotonous increasing;
##seems redcuce score...
##train['month'] = (train['TransactionDT1'].dt.year-2017)*12 + train['TransactionDT1'].dt.month
##train.iloc[299000:299100]
#
#test['TransactionDT1']=test['TransactionDT'].apply(lambda x:(startDT+datetime.timedelta(seconds=x)))
#test['month']=test['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%m')))
#test['day']=test['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%d')))
#test['dayofweek']=test['TransactionDT1'].dt.date.apply(lambda x: x.weekday())
#test['hour']=test['TransactionDT1'].apply(lambda x: int(x.strftime('%H')))
#test['weekofyear']=test['TransactionDT1'].apply(lambda x: int(x.strftime('%U')))
#
##engineer Month to start from 12 and monotonous increasing;
##test['month'] = (test['TransactionDT1'].dt.year-2017)*12 + test['TransactionDT1'].dt.month
#
#test.head(3)
##%%
#train['TransactionAmt_decimal'] = ((train['TransactionAmt'] - train['TransactionAmt'].astype(int)) * 1000).astype(int)
#test['TransactionAmt_decimal'] = ((test['TransactionAmt'] - test['TransactionAmt'].astype(int)) * 1000).astype(int)
##plot_numerical1('TransactionAmt_decimal')
#
##creat new feature: Number of NaN's
#train['nulls']=train.isnull().sum(axis=1)
#test['nulls']=test.isnull().sum(axis=1)
#for df in [train, test, X]:
# ########################### Device info
# df['DeviceInfo'] = df['DeviceInfo'].fillna('unknown_device').str.lower()
#to be continued for filling missing data ...........................................
################################################################################
#%%
import pandas as pd
from sklearn.model_selection import train_test_split
import lightgbm as lgb
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import LabelEncoder
import numpy as np
import gc
train = pd.read_pickle('train_Basic.pkl')
test = pd.read_pickle('test_Basic.pkl')
y = train['isFraud']
X = pd.DataFrame()
#%%
emails = {'gmail': 'google', 'att.net': 'att', 'twc.com': 'spectrum', 'scranton.edu': 'other',
'optonline.net': 'other', 'hotmail.co.uk': 'microsoft', 'comcast.net': 'other', 'yahoo.com.mx': 'yahoo',
'yahoo.fr': 'yahoo', 'yahoo.es': 'yahoo', 'charter.net': 'spectrum', 'live.com': 'microsoft',
'aim.com': 'aol', 'hotmail.de': 'microsoft', 'centurylink.net': 'centurylink', 'gmail.com': 'google',
'me.com': 'apple', 'earthlink.net': 'other', 'gmx.de': 'other', 'web.de': 'other', 'cfl.rr.com': 'other',
'hotmail.com': 'microsoft', 'protonmail.com': 'other', 'hotmail.fr': 'microsoft', 'windstream.net': 'other',
'outlook.es': 'microsoft', 'yahoo.co.jp': 'yahoo', 'yahoo.de': 'yahoo', 'servicios-ta.com': 'other',
'netzero.net': 'other', 'suddenlink.net': 'other', 'roadrunner.com': 'other', 'sc.rr.com': 'other',
'live.fr': 'microsoft', 'verizon.net': 'yahoo', 'msn.com': 'microsoft', 'q.com': 'centurylink',
'prodigy.net.mx': 'att', 'frontier.com': 'yahoo', 'anonymous.com': 'other', 'rocketmail.com': 'yahoo',
'sbcglobal.net': 'att', 'frontiernet.net': 'yahoo', 'ymail.com': 'yahoo', 'outlook.com': 'microsoft',
'mail.com': 'other', 'bellsouth.net': 'other', 'embarqmail.com': 'centurylink', 'cableone.net': 'other',
'hotmail.es': 'microsoft', 'mac.com': 'apple', 'yahoo.co.uk': 'yahoo', 'netzero.com': 'other',
'yahoo.com': 'yahoo', 'live.com.mx': 'microsoft', 'ptd.net': 'other', 'cox.net': 'other', 'aol.com': 'aol',
'juno.com': 'other', 'icloud.com': 'apple'}
us_emails = ['gmail', 'net', 'edu']
#%%
def id_split(dataframe):
dataframe['device_name'] = dataframe['DeviceInfo'].str.split('/', expand=True)[0]
dataframe['device_version'] = dataframe['DeviceInfo'].str.split('/', expand=True)[1]
dataframe['OS_id_30'] = dataframe['id_30'].str.split(' ', expand=True)[0]
dataframe['version_id_30'] = dataframe['id_30'].str.split(' ', expand=True)[1]
dataframe['browser_id_31'] = dataframe['id_31'].str.split(' ', expand=True)[0]
dataframe['version_id_31'] = dataframe['id_31'].str.split(' ', expand=True)[1]
dataframe['screen_width'] = dataframe['id_33'].str.split('x', expand=True)[0]
dataframe['screen_height'] = dataframe['id_33'].str.split('x', expand=True)[1]
dataframe['id_34'] = dataframe['id_34'].str.split(':', expand=True)[1]
dataframe['id_23'] = dataframe['id_23'].str.split(':', expand=True)[1]
dataframe.loc[dataframe['device_name'].str.contains('SM', na=False), 'device_name'] = 'Samsung'
dataframe.loc[dataframe['device_name'].str.contains('SAMSUNG', na=False), 'device_name'] = 'Samsung'
dataframe.loc[dataframe['device_name'].str.contains('GT-', na=False), 'device_name'] = 'Samsung'
dataframe.loc[dataframe['device_name'].str.contains('Moto G', na=False), 'device_name'] = 'Motorola'
dataframe.loc[dataframe['device_name'].str.contains('Moto', na=False), 'device_name'] = 'Motorola'
dataframe.loc[dataframe['device_name'].str.contains('moto', na=False), 'device_name'] = 'Motorola'
dataframe.loc[dataframe['device_name'].str.contains('LG-', na=False), 'device_name'] = 'LG'
dataframe.loc[dataframe['device_name'].str.contains('rv:', na=False), 'device_name'] = 'RV'
dataframe.loc[dataframe['device_name'].str.contains('HUAWEI', na=False), 'device_name'] = 'Huawei'
dataframe.loc[dataframe['device_name'].str.contains('ALE-', na=False), 'device_name'] = 'Huawei'
dataframe.loc[dataframe['device_name'].str.contains('-L', na=False), 'device_name'] = 'Huawei'
dataframe.loc[dataframe['device_name'].str.contains('Blade', na=False), 'device_name'] = 'ZTE'
dataframe.loc[dataframe['device_name'].str.contains('BLADE', na=False), 'device_name'] = 'ZTE'
dataframe.loc[dataframe['device_name'].str.contains('Linux', na=False), 'device_name'] = 'Linux'
dataframe.loc[dataframe['device_name'].str.contains('XT', na=False), 'device_name'] = 'Sony'
dataframe.loc[dataframe['device_name'].str.contains('HTC', na=False), 'device_name'] = 'HTC'
dataframe.loc[dataframe['device_name'].str.contains('ASUS', na=False), 'device_name'] = 'Asus'
dataframe.loc[dataframe.device_name.isin(dataframe.device_name.value_counts()[dataframe.device_name.value_counts()
< 200].index), 'device_name'] = "Others"
#dataframe['had_id'] = 1
gc.collect()
return dataframe
train = id_split(train)
test= id_split(test)
#%%
#%%
col=['TransactionDT','ProductCD','P_emaildomain','R_emaildomain','nulls','month','hour',
'TransactionAmt', 'TransactionAmt_decimal','D5','D2','D8','D9','D11','D15','C1','C4','C8','C10','C13','C2',
'V256','V13','card1','card2','card3','card4', 'card5', 'card6','addr1','M4','M5','M6','M1',
'M2','M3','M7','M8','M9','DeviceType',
'DeviceInfo', 'addr2','D6','D13','C5','C9','D7','C14',
'id_01', 'id_02', 'id_03', 'id_05', 'id_06', 'id_09','id_11', 'id_12', 'id_13', 'id_14', 'id_15', 'id_17',
'id_19', 'id_20', 'id_30', 'id_31', 'id_32', 'id_33','id_36', 'id_37', 'id_38',
'V145',
'V3','V4','V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V17',
'V19', 'V20', 'V29', 'V30', 'V33', 'V34', 'V35', 'V36', 'V37', 'V38', 'V40', 'V44', 'V45', 'V46', 'V47', 'V48',
'V49', 'V51', 'V52', 'V53', 'V54', 'V56', 'V58', 'V59', 'V60', 'V61', 'V62', 'V63', 'V64', 'V69', 'V70', 'V71',
'V72', 'V73', 'V74', 'V75', 'V76', 'V78', 'V80', 'V81', 'V82', 'V83', 'V84', 'V85', 'V87', 'V90', 'V91', 'V92',
'V93', 'V94', 'V95', 'V96', 'V97', 'V99', 'V100', 'V126', 'V127', 'V128', 'V130', 'V131', 'V138', 'V139', 'V140',
'V143', 'V146', 'V147', 'V149', 'V150', 'V151', 'V152', 'V154', 'V156', 'V158', 'V159', 'V160', 'V161',
'V162', 'V163', 'V164', 'V165', 'V166', 'V167', 'V169', 'V170', 'V171', 'V172', 'V173', 'V175', 'V176', 'V177',
'V178', 'V180', 'V182', 'V184', 'V187', 'V188', 'V189', 'V195', 'V197', 'V200', 'V201', 'V202', 'V203', 'V204',
'V205', 'V206', 'V207', 'V208', 'V209', 'V210', 'V212', 'V213', 'V214', 'V215', 'V216', 'V217', 'V219', 'V220',
'V221', 'V222', 'V223', 'V224', 'V225', 'V226', 'V227', 'V228', 'V229', 'V231', 'V233', 'V234', 'V238', 'V239',
'V242', 'V243', 'V244', 'V245', 'V246', 'V247', 'V249', 'V251', 'V253', 'V257', 'V258', 'V259', 'V261',
'V262', 'V263', 'V264', 'V265', 'V266', 'V267', 'V268', 'V270', 'V271', 'V272', 'V273', 'V274', 'V275', 'V276',
'V277', 'V278', 'V279', 'V280', 'V282', 'V283', 'V285', 'V287', 'V288', 'V289', 'V291', 'V292', 'V294', 'V303',
'V304', 'V306', 'V307', 'V308', 'V310', 'V312', 'V313', 'V314', 'V315', 'V317', 'V322',
'V323','V324', 'V326','V329','V331','V332', 'V333', 'V335', 'V336',
'isFraud']
#'device_name','device_version','OS_id_30','version_id_30','browser_id_31','version_id_31','screen_width','screen_height',
# 'id_34','id_23',
# 'V145',
# 'V3','V4','V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V17',
# 'V19', 'V20', 'V29', 'V30', 'V33', 'V34', 'V35', 'V36', 'V37', 'V38', 'V40', 'V44', 'V45', 'V46', 'V47', 'V48',
# 'V49', 'V51', 'V52', 'V53', 'V54', 'V56', 'V58', 'V59', 'V60', 'V61', 'V62', 'V63', 'V64', 'V69', 'V70', 'V71',
# 'V72', 'V73', 'V74', 'V75', 'V76', 'V78', 'V80', 'V81', 'V82', 'V83', 'V84', 'V85', 'V87', 'V90', 'V91', 'V92',
# 'V93', 'V94', 'V95', 'V96', 'V97', 'V99', 'V100', 'V126', 'V127', 'V128', 'V130', 'V131', 'V138', 'V139', 'V140',
# 'V143', 'V146', 'V147', 'V149', 'V150', 'V151', 'V152', 'V154', 'V156', 'V158', 'V159', 'V160', 'V161',
# 'V162', 'V163', 'V164', 'V165', 'V166', 'V167', 'V169', 'V170', 'V171', 'V172', 'V173', 'V175', 'V176', 'V177',
# 'V178', 'V180', 'V182', 'V184', 'V187', 'V188', 'V189', 'V195', 'V197', 'V200', 'V201', 'V202', 'V203', 'V204',
# 'V205', 'V206', 'V207', 'V208', 'V209', 'V210', 'V212', 'V213', 'V214', 'V215', 'V216', 'V217', 'V219', 'V220',
# 'V221', 'V222', 'V223', 'V224', 'V225', 'V226', 'V227', 'V228', 'V229', 'V231', 'V233', 'V234', 'V238', 'V239',
# 'V242', 'V243', 'V244', 'V245', 'V246', 'V247', 'V249', 'V251', 'V253', 'V257', 'V258', 'V259', 'V261',
# 'V262', 'V263', 'V264', 'V265', 'V266', 'V267', 'V268', 'V270', 'V271', 'V272', 'V273', 'V274', 'V275', 'V276',
# 'V277', 'V278', 'V279', 'V280', 'V282', 'V283', 'V285', 'V287', 'V288', 'V289', 'V291', 'V292', 'V294', 'V303',
# 'V304', 'V306', 'V307', 'V308', 'V310', 'V312', 'V313', 'V314', 'V315', 'V317', 'V322',
# 'V323','V324', 'V326','V329','V331','V332', 'V333', 'V335', 'V336',
#'V48','V53','V96','V338'
#month is important
# Save to pickle
New_DatasetName = "Basic"
#train[col].to_pickle("train_{}.pkl".format(New_DatasetName))
#test[col[:-1]].to_pickle("test_{}.pkl".format(New_DatasetName))
col.pop()
X[col] = train[col]
X['M4_count'] =X['M4'].map(pd.concat([train['M4'], test['M4']], ignore_index=True).value_counts(dropna=False))
X['M6_count'] =X['M6'].map(pd.concat([train['M6'], test['M6']], ignore_index=True).value_counts(dropna=False))
X['card1_count'] = X['card1'].map(pd.concat([train['card1'], test['card1']], ignore_index=True).value_counts(dropna=False))
X['card6_count'] =X['card6'].map(pd.concat([train['card6'], test['card6']], ignore_index=True).value_counts(dropna=False))
# X['card2_count'] =X['card2'].map(pd.concat([train['card2'], test['card2']], ignore_index=True).value_counts(dropna=False))
# X['card3_count'] =X['card3'].map(pd.concat([train['card3'], test['card3']], ignore_index=True).value_counts(dropna=False))
# X['card4_count'] =X['card4'].map(pd.concat([train['card4'], test['card4']], ignore_index=True).value_counts(dropna=False))
# X['card5_count'] =X['card5'].map(pd.concat([train['card5'], test['card5']], ignore_index=True).value_counts(dropna=False))
# X['id_36_count'] =X['id_36'].map(pd.concat([train['id_36'], test['id_36']], ignore_index=True).value_counts(dropna=False))
# # Encoding - count encoding for both train and test
# for feature in ['card1', 'card2', 'card3', 'card4', 'card5', 'card6', 'id_36']:
# train[feature + '_count_full'] = train[feature].map(pd.concat([train[feature], test[feature]], ignore_index=True).value_counts(dropna=False))
# test[feature + '_count_full'] = test[feature].map(pd.concat([train[feature], test[feature]], ignore_index=True).value_counts(dropna=False))
# # Encoding - count encoding separately for train and test
# for feature in ['id_01', 'id_31', 'id_33', 'id_36']:
# train[feature + '_count_dist'] = train[feature].map(train[feature].value_counts(dropna=False))
# test[feature + '_count_dist'] = test[feature].map(test[feature].value_counts(dropna=False))
for feature in ['id_30','id_06']:
X[feature + '_count'] = X[feature].map(pd.concat([train[feature], test[feature]], ignore_index=True).value_counts(dropna=False))
X['DeviceType_count'] =X['DeviceType'].map(pd.concat([train['DeviceType'], test['DeviceType']], ignore_index=True).value_counts(dropna=False))
#X['DeviceInfo_count'] =X['DeviceInfo'].map(pd.concat([train['DeviceInfo'], test['DeviceInfo']], ignore_index=True).value_counts(dropna=False))
X['ProductCD_count'] =X['ProductCD'].map(pd.concat([train['ProductCD'], test['ProductCD']], ignore_index=True).value_counts(dropna=False))
X['P_emaildomain_count'] =X['P_emaildomain'].map(pd.concat([train['P_emaildomain'], test['P_emaildomain']], ignore_index=True).value_counts(dropna=False))
#X['R_emaildomain_count'] =X['R_emaildomain'].map(pd.concat([train['R_emaildomain'], test['R_emaildomain']], ignore_index=True).value_counts(dropna=False))
X['addr1_count'] = X['addr1'].map(pd.concat([train['addr1'], test['addr1']], ignore_index=True).value_counts(dropna=False))
#X['id_02_count'] = X['id_02'].map(pd.concatD.value_counts(dropna=False))
#X['id_17_count'] = X['id_17'].map(pd.concat([train['id_17'], test['id_17']], ignore_index=True).value_counts(dropna=False))
###X['id_02'].fillna(0, inplace=True)
# Risk mapping transformation
card4_dic = {'american express':287,'discover':773,'mastercard':343,'visa':348}
X['card4_dic']=X['card4'].map(card4_dic)
#train=train.replace({'card4':card4_dic})
#test=test.replace({'card4':card4_dic})
ProductCD_dic = {'C':117,'H':48,'R':38,'S':59,'W':20}
X['ProductCD_dic']=X['ProductCD'].map(ProductCD_dic)
#New feature:id risk mapping:id_12,id_15,id_16,id_27,id_28,id_29
#df['id_12'] = df['id_12'].fillna('Missing').str.lower()
# id_12_dic = {'NotFound':85,'Found':60}
# X['id_12_dic']=X['id_12'].map(id_12_dic)
#df['id_15'] = df['id_15'].fillna('Missing').str.lower()
# id_15_dic = {'Found':105,'Unknown':92,'New':49}
# X['id_15_dic']=X['id_15'].map(id_15_dic)
# df['id_16'] = df['id_16'].fillna('Missing').str.lower()
# id_16_dic = {'NotFound':48,'Found':107}
# X['id_16_dic']=X['id_16'].map(id_16_dic)
# df['id_28'] = df['id_28'].fillna('Missing').str.lower()
# id_28_dic = {'Found':103,'New':52}
# X['id_28_dic']=X['id_28'].map(id_28_dic)
#New feature:addr2 risk mapping
#addr2_dic={46:100,51:100,10:100,65:54,96:14,60:9,32:7,87:2}
#X['addr2_dic']=X['addr2'].map(addr2_dic)
#38:67,73:20,54:33,68:10,29:9,
card6_dic = {'charge card':0,'credit':668,'debit':243,'debit or credit':0}
X['card6_dic']=X['card6'].map(card6_dic)
#train=train.replace({'card6':card6_dic})
#test=test.replace({'card6':card6_dic})
M1_dic={'F':0,'T':2}
X['M1_dic']=X['M1'].map(M1_dic)
M4_dic={'M0':4,'M1':3,'M2':13}
X['M4_dic']=X['M4'].map(M4_dic)
M5_dic={'F':2,'T':3}
X['M5_dic']=X['M5'].map(M5_dic)
M6_dic={'F':4,'T':3}
X['M6_dic']=X['M6'].map(M6_dic)
#DeviceInfo has many category levels
#DeviceType_dic={'desktop':3,'mobile':5}
#X['DeviceType_dic']=X['DeviceType'].map(DeviceType_dic)
P_emaildomain_dic={'protonmail.com':40,'mail.com':19,'outlook.es':13,'aim.com':12,
'outlook.com':9,'hotmail.es':7,'live.com.mx':5,'hotmail.com':5,'gmail.com':4}
X['P_emaildomain_dic']=X['P_emaildomain'].map(P_emaildomain_dic)
R_emaildomain_dic={'protonmail.com':95,'mail.com':38,'netzero.net':22,'outlook.com':17,
'outlook.es':13,'icloud.com':13,'gmail.com':12,'hotmail.com':8,
'earthlink.net':8,'earthlink.net':7,'hotmail.es':7,'live.com.mx':6,
'yahoo.com':5,'live.com':5}
X['R_emaildomain_dic']=X['R_emaildomain'].map(R_emaildomain_dic)
#New feature:C2 vs TransactionDT
def func_C2_Tran(a,b):
if a<400:
return 344
elif a>=400 and a<=651 and b<=4000000:
return 3846
elif a>=400 and a<=651 and b>10000000:
return 10000
else:
return 1082
X['C2_TransactionDT']=X.apply(lambda x:func_C2_Tran(x['C2'],x['TransactionDT']),axis=1)
###sep 06,2019 add fill na:
X['D9'] = np.where(X['D9'].isna(),0,1)
########################### Reset values for "noise" card1
# i_cols = ['card1']
# for col in i_cols:
# valid_card = pd.concat([train[[col]], test[[col]]])
# valid_card = valid_card[col].value_counts()
# valid_card = valid_card[valid_card>2]
# valid_card = list(valid_card.index)
# X[col] = np.where(train[col].isin(test[col]), train[col], np.nan)
# X[col] = np.where(X[col].isin(valid_card), X[col], np.nan)
# # test_x[col] = np.where(test_x[col].isin(train[col]), test_x[col], np.nan)
# # test_x[col] = np.where(test_x[col].isin(valid_card), test_x[col], np.nan)
########################## M columns (except M4)
#All these columns are binary encoded 1/0
#We can have some features from it
# i_cols = ['M1','M2','M3','M5','M6','M7','M8','M9']
# X['M_sum'] = X[i_cols].sum(axis=1).astype(np.int8)
# X['M_na'] = X[i_cols].isna().sum(axis=1).astype(np.int8)
# Check if the Transaction Amount is common or not (we can use freq encoding here)
# In our dialog with a model we are telling to trust or not to these values
X['TransactionAmt_check'] = np.where(X['TransactionAmt'].isin(test['TransactionAmt']), 1, 0)
####################################Interaction term
X['uid'] = X['card1'].astype(str)+'_'+X['card2'].astype(str)
test['uid'] = test['card1'].astype(str)+'_'+test['card2'].astype(str)
X['uid2'] = X['uid'].astype(str)+'_'+X['card3'].astype(str)+'_'+X['card5'].astype(str)
test['uid2'] = test['uid'].astype(str)+'_'+test['card3'].astype(str)+'_'+test['card5'].astype(str)
X['uid3'] = X['uid2'].astype(str)+'_'+X['addr1'].astype(str)+'_'+X['addr2'].astype(str)
test['uid3'] = test['uid2'].astype(str)+'_'+test['addr1'].astype(str)+'_'+test['addr2'].astype(str)
# For our model current TransactionAmt is a noise
# https://www.kaggle.com/kyakovlev/ieee-check-noise
# (even if features importances are telling contrariwise)
# There are many unique values and model doesn't generalize well
# Lets do some aggregations
i_cols = ['card1','card2','card3','card5']
#'uid','uid2','uid3'
for col2 in i_cols:
for agg_type in ['mean','std']:
new_col_name = col2+'_TransactionAmt_'+agg_type
temp_df = pd.concat([train[[col2, 'TransactionAmt']], test[[col2,'TransactionAmt']]])
#temp_df['TransactionAmt'] = temp_df['TransactionAmt'].astype(int)
temp_df = temp_df.groupby([col2])['TransactionAmt'].agg([agg_type]).reset_index().rename(
columns={agg_type: new_col_name})
temp_df.index = list(temp_df[col2])
temp_df = temp_df[new_col_name].to_dict()
X[new_col_name] = X[col2].map(temp_df)
# i_cols2 = ['uid','uid2','uid3']
# for col3 in i_cols2:
# for agg_type in ['mean','std']:
# new_col_name = col3+'_TransactionAmt_'+agg_type
# temp_df = pd.concat([X[[col3, 'TransactionAmt']], test[[col3,'TransactionAmt']]])
# #temp_df['TransactionAmt'] = temp_df['TransactionAmt'].astype(int)
# temp_df = temp_df.groupby([col3])['TransactionAmt'].agg([agg_type]).reset_index().rename(
# columns={agg_type: new_col_name})
# temp_df.index = list(temp_df[col3])
# temp_df = temp_df[new_col_name].to_dict()
# X[new_col_name] = X[col3].map(temp_df)
# Small "hack" to transform distribution
# (doesn't affect auc much, but I like it more)
# please see how distribution transformation can boost your score
# (not our case but related)
# https://scikit-learn.org/stable/auto_examples/compose/plot_transformed_target.html
#X['TransactionAmt'] = np.log1p(X['TransactionAmt'])
# ########################### Device info
# X['DeviceInfo'] = X['DeviceInfo'].fillna('unknown_device').str.lower()
# X['DeviceInfo_device'] = X['DeviceInfo'].apply(lambda x: ''.join([i for i in x if i.isalpha()]))
# X['DeviceInfo_version'] = X['DeviceInfo'].apply(lambda x: ''.join([i for i in x if i.isnumeric()]))
########################### Device info 2
#X['id_30'] = X['id_30'].fillna('unknown_device').str.lower()
#X['id_30_device'] = X['id_30'].apply(lambda x: ''.join([i for i in x if i.isalpha()]))
#X['id_30_version'] = X['id_30'].apply(lambda x: ''.join([i for i in x if i.isnumeric()]))
########################### Browser
#X['id_31'] = X['id_31'].fillna('unknown_device').str.lower()
#X['id_31_device'] = X['id_31'].apply(lambda x: ''.join([i for i in x if i.isalpha()]))
###########
for feature in ['uid','uid2','uid3']:
# Count encoded separately for train and test,
X[feature + '_count'] = X[feature].map(X[feature].value_counts(dropna=False))
X=X.drop(columns=['ProductCD','P_emaildomain','R_emaildomain','M4','M5','M6','M1', 'M2','M3','M7','M8','M9','card6', 'DeviceType',
'card4','id_02','id_19','id_20','id_17','C2','TransactionDT','addr2','D6','D13','C5','C9','D7','C14',
'id_12', 'id_15', 'id_30', 'id_31', 'id_33', 'id_36', 'id_37', 'id_38','uid','uid2','uid3'
])
#%%
X['addr1'].fillna(0, inplace=True)
#X['addr2_dic'].fillna(3, inplace=True)
#X['addr2'].fillna(96, inplace=True)
#X['D5'].fillna(150, inplace=True)
X['D2'].fillna(10, inplace=True)
X['D11'].fillna(10, inplace=True)
X['D15'].fillna(376, inplace=True)
#X['V1'].fillna(X['V1'].mode()[0], inplace=True)
#X['V2'].fillna(3, inplace=True)
X['V13'].fillna(X['V13'].mode()[0], inplace=True)
#fillna reduce score
#X['V263'].fillna(X['V263'].mode()[0], inplace=True)
#X['V256'].fillna(X['V256'].mode()[0], inplace=True)
X['card2'].fillna(502, inplace=True)
###X['card3'].fillna(150, inplace=True)
X['card4_dic'].fillna(X['card4_dic'].mode()[0], inplace=True)
X['M4_dic'].fillna(2, inplace=True)
X['M5_dic'].fillna(3, inplace=True) #24:18:78
X['M6_dic'].fillna(13, inplace=True) #24:18:78
#X['cross'].fillna(2.6, inplace=True)
#X['id_19'].fillna(444, inplace=True)
#X['id_20'].fillna(266, inplace=True)
#X['id_17'].fillna(133, inplace=True)
X['P_emaildomain_dic'].fillna(0, inplace=True)
X['R_emaildomain_dic'].fillna(0, inplace=True)
#sep 04,2019 add fill na:
#X['V145'].fillna(0, inplace=True) #V145 has more than 80% missing
X['V19'].fillna(0, inplace=True)
X['V36'].fillna(0, inplace=True)
X['V64'].fillna(0, inplace=True)
X['V70'].fillna(0, inplace=True)
X['V80'].fillna(0, inplace=True)
X['V94'].fillna(0, inplace=True)
# X['V143'].fillna(0, inplace=True)
# X['V150'].fillna(0, inplace=True)
# X['V152'].fillna(0, inplace=True)
# X['V158'].fillna(0, inplace=True)##
# X['V163'].fillna(0, inplace=True)
# X['V165'].fillna(0, inplace=True)
# X['V177'].fillna(0, inplace=True)
# X['V204'].fillna(0, inplace=True)
# X['V207'].fillna(0, inplace=True)
# X['V209'].fillna(0, inplace=True) ##
# X['V221'].fillna(0, inplace=True)
# X['V222'].fillna(0, inplace=True)
# X['V266'].fillna(0, inplace=True)
# X['V267'].fillna(0, inplace=True)
# X['V274'].fillna(0, inplace=True)
# X['V275'].fillna(0, inplace=True)
X['V279'].fillna(0, inplace=True)
X['V283'].fillna(0, inplace=True)
#X['id_30_count'].fillna(0, inplace=True)
#%%
#train test split
#X_train, X_test, y_train, y_test = train_test_split(X,
# y, test_size=0.33, random_state=47, shuffle=False)
#
#%%
#train with lgb
#params = {'boosting_type':'gbdt', 'class_weight':None, 'colsample_bytree':0.7,
# 'importance_type':'split', 'learning_rate':0.05, 'max_depth':25,
# 'min_child_samples':20, 'min_child_weight':0.00298, 'min_split_gain':0.0,
# 'n_estimators':300, 'n_jobs':-1, 'num_leaves':2**8, 'silent':False, 'subsample':0.7,
# 'reg_alpha':0.38999, 'reg_lambda':2.0,'subsample_for_bin':200000, 'subsample_freq':1,
# 'objective': 'binary', "bagging_seed": 8, 'metric': 'auc', 'random_state': 47}
#
#clf = lgb.LGBMClassifier(**params)
#clf.fit(X_train, y_train)
#print("basic score is "+str(roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])))
#%%
# clf.fit(upsampled.drop(columns=['isFraud']),upsampled['isFraud'])
# X_test=X_test.drop(columns=['TransactionDT'])
# roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])
#%%
#def addfeature(var):
#
# y = train['isFraud']
# X = pd.DataFrame()
#
# col=['TransactionDT','ProductCD','P_emaildomain','R_emaildomain','nulls','month','hour',
# 'TransactionAmt', 'TransactionAmt_decimal','D5','D2','D8','D9','D11','D15','C1','C4','C8','C10','C13','C2',
# 'V256','V13','card1','card2','card3','card4', 'card5', 'card6','addr1','M4','M5','M6','M1','DeviceType',
# 'DeviceInfo','addr2','D6','D13','C5','C9','D7','C14','V145',
# 'id_01', 'id_02', 'id_03', 'id_05', 'id_06', 'id_09',
# 'id_11', 'id_12', 'id_13', 'id_14', 'id_15', 'id_17', 'id_19', 'id_20', 'id_30', 'id_31', 'id_32', 'id_33',
# 'id_36', 'id_37', 'id_38'
# ]+[var]
#
# X[col] = train[col]
#
# print('preprocessing including '+ var)
#
# X['M4_count'] =X['M4'].map(pd.concat([train['M4'], test['M4']], ignore_index=True).value_counts(dropna=False))
# X['M6_count'] =X['M6'].map(pd.concat([train['M6'], test['M6']], ignore_index=True).value_counts(dropna=False))
# X['card1_count'] = X['card1'].map(pd.concat([train['card1'], test['card1']], ignore_index=True).value_counts(dropna=False))
# X['card6_count'] =X['card6'].map(pd.concat([train['card6'], test['card6']], ignore_index=True).value_counts(dropna=False))
#
# X['DeviceType_count'] =X['DeviceType'].map(pd.concat([train['DeviceType'], test['DeviceType']], ignore_index=True).value_counts(dropna=False))
# #X['DeviceInfo_count'] =X['DeviceInfo'].map(pd.concat([train['DeviceInfo'], test['DeviceInfo']], ignore_index=True).value_counts(dropna=False))
# X['ProductCD_count'] =X['ProductCD'].map(pd.concat([train['ProductCD'], test['ProductCD']], ignore_index=True).value_counts(dropna=False))
# X['P_emaildomain_count'] =X['P_emaildomain'].map(pd.concat([train['P_emaildomain'], test['P_emaildomain']], ignore_index=True).value_counts(dropna=False))
# #X['R_emaildomain_count'] =X['R_emaildomain'].map(pd.concat([train['R_emaildomain'], test['R_emaildomain']], ignore_index=True).value_counts(dropna=False))
# X['addr1_count'] = X['addr1'].map(pd.concat([train['addr1'], test['addr1']], ignore_index=True).value_counts(dropna=False))
#
# # Risk mapping transformation
# card4_dic = {'american express':287,'discover':773,'mastercard':343,'visa':348}
# X['card4_dic']=X['card4'].map(card4_dic)
# #train=train.replace({'card4':card4_dic})
# #test=test.replace({'card4':card4_dic})
# ProductCD_dic = {'C':117,'H':48,'R':38,'S':59,'W':20}
# X['ProductCD_dic']=X['ProductCD'].map(ProductCD_dic)
#
#
# card6_dic = {'charge card':0,'credit':668,'debit':243,'debit or credit':0}
# X['card6_dic']=X['card6'].map(card6_dic)
# #train=train.replace({'card6':card6_dic})
# #test=test.replace({'card6':card6_dic})
#
# M1_dic={'F':0,'T':2}
# X['M1_dic']=X['M1'].map(M1_dic)
#
# M4_dic={'M0':4,'M1':3,'M2':13}
# X['M4_dic']=X['M4'].map(M4_dic)
#
# M5_dic={'F':2,'T':3}
# X['M5_dic']=X['M5'].map(M5_dic)
#
# M6_dic={'F':4,'T':3}
# X['M6_dic']=X['M6'].map(M6_dic)
#
# P_emaildomain_dic={'protonmail.com':40,'mail.com':19,'outlook.es':13,'aim.com':12,
# 'outlook.com':9,'hotmail.es':7,'live.com.mx':5,'hotmail.com':5,'gmail.com':4}
# X['P_emaildomain_dic']=X['P_emaildomain'].map(P_emaildomain_dic)
#
#
# R_emaildomain_dic={'protonmail.com':95,'mail.com':38,'netzero.net':22,'outlook.com':17,
# 'outlook.es':13,'icloud.com':13,'gmail.com':12,'hotmail.com':8,
# 'earthlink.net':8,'earthlink.net':7,'hotmail.es':7,'live.com.mx':6,
# 'yahoo.com':5,'live.com':5}
# X['R_emaildomain_dic']=X['R_emaildomain'].map(R_emaildomain_dic)
#
# #New feature:C2 vs TransactionDT
## def func_C2_Tran(a,b):
## if a<400:
## return 344
## elif a>=400 and a<=651 and b<=4000000:
## return 3846
## elif a>=400 and a<=651 and b>10000000:
## return 10000
## else:
## return 1082
## X['C2_TransactionDT']=X.apply(lambda x:func_C2_Tran(x['C2'],x['TransactionDT']),axis=1)
##
#
# X[var + '_count'] = X[var].map(pd.concat([train[var], test[var]], ignore_index=True).value_counts(dropna=False))
#
# X=X.drop(columns=['ProductCD','P_emaildomain','R_emaildomain','M4','M5','M6','M1','card6', 'DeviceType','DeviceInfo',
# 'card4','id_02','id_19','id_20','id_17','C2','TransactionDT','addr2','D6','D13','C5','C9','D7','C14',
# 'id_12', 'id_15', 'id_30', 'id_31', 'id_33', 'id_36', 'id_37', 'id_38'
# ])
#X['addr1'].fillna(0, inplace=True)
##X['addr2_dic'].fillna(3, inplace=True)
##X['addr2'].fillna(96, inplace=True)
##X['D5'].fillna(150, inplace=True)
#X['D2'].fillna(10, inplace=True)
#X['D11'].fillna(10, inplace=True)
#X['D15'].fillna(376, inplace=True)
#
##X['V1'].fillna(X['V1'].mode()[0], inplace=True)
##X['V2'].fillna(3, inplace=True)
#
#X['V13'].fillna(X['V13'].mode()[0], inplace=True)
##X['V145'].fillna(X['V145'].mode()[0], inplace=True) #fillna reduce score
##X['V263'].fillna(X['V263'].mode()[0], inplace=True)
##X['V256'].fillna(X['V256'].mode()[0], inplace=True)
#
#X['card2'].fillna(502, inplace=True)
####X['card3'].fillna(150, inplace=True)
#X['card4_dic'].fillna(X['card4_dic'].mode()[0], inplace=True)
#
#X['M4_dic'].fillna(2, inplace=True)
#X['M5_dic'].fillna(3, inplace=True) #24:18:78
#X['M6_dic'].fillna(13, inplace=True) #24:18:78
#
##X['cross'].fillna(2.6, inplace=True)
#
##X['id_19'].fillna(444, inplace=True)
##X['id_20'].fillna(266, inplace=True)
##X['id_17'].fillna(133, inplace=True)
#X['P_emaildomain_dic'].fillna(0, inplace=True)
#X['R_emaildomain_dic'].fillna(0, inplace=True)
# print('start training with '+var)
# X_train, X_test, y_train, y_test = train_test_split(X,
# y, test_size=0.33, random_state=47, shuffle=False)
#
# clf = lgb.LGBMClassifier(**params)
# clf.fit(X_train, y_train)
# score=roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])
# print(score)
# return score
#
#res=[]
##ls=['V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V17',
## 'V19', 'V20', 'V29', 'V30', 'V33', 'V34', 'V35', 'V36', 'V37', 'V38', 'V40', 'V44', 'V45', 'V46', 'V47', 'V48',
## 'V49', 'V51', 'V52', 'V53', 'V54', 'V56', 'V58', 'V59', 'V60', 'V61', 'V62', 'V63', 'V64', 'V69', 'V70', 'V71',
## 'V72', 'V73', 'V74', 'V75', 'V76', 'V78', 'V80', 'V81', 'V82', 'V83', 'V84', 'V85', 'V87', 'V90', 'V91', 'V92',
## 'V93', 'V94', 'V95', 'V96', 'V97', 'V99', 'V100', 'V126', 'V127', 'V128', 'V130', 'V131', 'V138', 'V139', 'V140',
## 'V143', 'V146', 'V147', 'V149', 'V150', 'V151', 'V152', 'V154', 'V156', 'V158', 'V159', 'V160', 'V161',
## 'V162', 'V163', 'V164', 'V165', 'V166', 'V167', 'V169', 'V170', 'V171', 'V172', 'V173', 'V175', 'V176', 'V177',
## 'V178', 'V180', 'V182', 'V184', 'V187', 'V188', 'V189', 'V195', 'V197', 'V200', 'V201', 'V202', 'V203', 'V204',
## 'V205', 'V206', 'V207', 'V208', 'V209', 'V210', 'V212', 'V213', 'V214', 'V215', 'V216', 'V217', 'V219', 'V220',
## 'V221', 'V222', 'V223', 'V224', 'V225', 'V226', 'V227', 'V228', 'V229', 'V231', 'V233', 'V234', 'V238', 'V239',
## 'V242', 'V243', 'V244', 'V245', 'V246', 'V247', 'V249', 'V251', 'V253', 'V257', 'V258', 'V259', 'V261',
## 'V262', 'V263', 'V264', 'V265', 'V266', 'V267', 'V268', 'V270', 'V271', 'V272', 'V273', 'V274', 'V275', 'V276',
## 'V277', 'V278', 'V279', 'V280', 'V282', 'V283', 'V285', 'V287', 'V288', 'V289', 'V291', 'V292', 'V294', 'V303',
## 'V304', 'V306', 'V307', 'V308', 'V310', 'V312', 'V313', 'V314', 'V315', 'V317', 'V322']
#ls=[ 'id_01', 'id_02', 'id_03', 'id_05', 'id_06', 'id_09','id_11', 'id_13', 'id_14', 'id_17', 'id_19', 'id_20', 'id_32']
#for i in ls:
# res.append(addfeature(i))
#%%
#ls1=['V323','V324', 'V326','V329','V331','V332', 'V333', 'V335', 'V336']
#for i in ls1:
# res.append(addfeature(i))
#
#%%
#def nmaxelement(ls,n):
# result=[]
# tmp=sorted(ls)[-n:]
# for i in tmp:
# result.append(ls.index(i))
# return result
#nmaxelement(res,10)
#%%
#from sklearn.model_selection import GridSearchCV
#lg = lgb.LGBMClassifier(silent=False)
#param_dist = {"max_depth": [25], #<=0 means no limit
# "learning_rate" : [0.05],
# "num_leaves": [256],
# "n_estimators": [300],
# 'min_child_samples':[20],
# 'bagging_fraction': [0.42],
# 'feature_fraction': [0.38],
# 'min_child_weight': [0.00298],
# 'min_data_in_leaf': [106],
# 'reg_alpha': [0.38999],
# 'reg_lambda': [2.0]
#
## "max_depth": [5,25,-1,50],
## "learning_rate" : [0.05,0.00688,0.01],
## "num_leaves": [300, 491,382,2**8],
## "n_estimators": [300,800],
## 'min_child_samples':[20],
## 'bagging_fraction': [0.42,0.9],
## 'feature_fraction': [0.38,0.9],
## 'min_child_weight': [0.00298,0.03454],
## 'min_data_in_leaf': [20,106],
## 'reg_alpha': [1.0,0.38999],
## 'reg_lambda': [2.0,0.6485],
#
## 'colsample_bytree': 0.7,
## 'subsample_freq':1,
## 'subsample':0.7,
## 'max_bin':255,
## 'verbose':-1,
## 'seed': SEED,
## 'early_stopping_rounds':100,
# }
#grid_search = GridSearchCV(lg, param_grid=param_dist, cv = 3, scoring="roc_auc", verbose=5)
#grid_search.fit(X_train,y_train)
#grid_search.best_estimator_
#%%
# LGB_BO.max['params']
# {'bagging_fraction': 0.8999999999997461,
# 'feature_fraction': 0.8999999999999121,
# 'max_depth': 50.0,
# 'min_child_weight': 0.0029805017044362268,
# 'min_data_in_leaf': 20.0,
# 'num_leaves': 381.85354295079446,
# 'reg_alpha': 1.0,
# 'reg_lambda': 2.0}
# params = {'num_leaves': 491,
# 'min_child_weight': 0.03454472573214212,
# 'feature_fraction': 0.3797454081646243,
# 'bagging_fraction': 0.4181193142567742,
# 'min_data_in_leaf': 106,
# 'objective': 'binary',
# 'max_depth': -1,
# 'learning_rate': 0.006883242363721497,
# "boosting_type": "gbdt",
# "bagging_seed": 11,
# "metric": 'auc',
# "verbosity": -1,
# 'reg_alpha': 0.3899927210061127,
# 'reg_lambda': 0.6485237330340494,
# 'random_state': 47
# }
#%%
#preprocessing in test data
#for prediction on test dataset
#for prediction on test dataset
test_x=pd.DataFrame()
test_x[col] = test[col]
test_x['M4_count'] =test_x['M4'].map(pd.concat([train['M4'], test['M4']], ignore_index=True).value_counts(dropna=False))
test_x['M6_count'] =test_x['M6'].map(pd.concat([train['M6'], test['M6']], ignore_index=True).value_counts(dropna=False))
test_x['card1_count'] = test_x['card1'].map(pd.concat([train['card1'], test['card1']], ignore_index=True).value_counts(dropna=False))
test_x['card6_count'] = test_x['card6'].map(pd.concat([train['card6'], test['card6']], ignore_index=True).value_counts(dropna=False))
test_x['addr1_count'] = test_x['addr1'].map(pd.concat([train['addr1'], test['addr1']], ignore_index=True).value_counts(dropna=False))
test_x['ProductCD_count'] =test_x['ProductCD'].map(pd.concat([train['ProductCD'], test['ProductCD']], ignore_index=True).value_counts(dropna=False))
test_x['P_emaildomain_count'] =test_x['P_emaildomain'].map(pd.concat([train['P_emaildomain'], test['P_emaildomain']], ignore_index=True).value_counts(dropna=False))
#test_x['R_emaildomain_count'] =test_x['R_emaildomain'].map(pd.concat([train['R_emaildomain'], test['R_emaildomain']], ignore_index=True).value_counts(dropna=False))
test_x['DeviceType_count'] =test_x['DeviceType'].map(pd.concat([train['DeviceType'], test['DeviceType']], ignore_index=True).value_counts(dropna=False))
# Risk mapping transformation
test_x['card4_dic']=test_x['card4'].map(card4_dic)
test_x['card6_dic']=test_x['card6'].map(card6_dic)
test_x['ProductCD_dic']=test_x['ProductCD'].map(ProductCD_dic)
#test_x['cross'] = test_x.apply(lambda x:func(x['card4'],x['ProductCD']),axis=1)
M1_dic={'F':0,'T':2}
test_x['M1_dic']=test_x['M1'].map(M1_dic)
M4_dic={'M0':4,'M1':3,'M2':13}
test_x['M4_dic']=test_x['M4'].map(M4_dic)
M5_dic={'F':2,'T':3}
test_x['M5_dic']=test_x['M5'].map(M5_dic)
M6_dic={'F':4,'T':3}
test_x['M6_dic']=test_x['M6'].map(M6_dic)
test_x['R_emaildomain_dic']=test_x['R_emaildomain'].map(R_emaildomain_dic)
test_x['P_emaildomain_dic']=test_x['P_emaildomain'].map(P_emaildomain_dic)
test_x['C2_TransactionDT']=test_x.apply(lambda x:func_C2_Tran(x['C2'],x['TransactionDT']),axis=1)
for feature in [ 'id_30','id_06']:
# Count encoded separately for train and test 'id_12', 'id_15','id_31', 'id_33', 'id_36', 'id_37', 'id_38'
test_x[feature + '_count'] = test_x[feature].map(pd.concat([train[feature], test[feature]], ignore_index=True).value_counts(dropna=False))
###sep 06,2019 add fill na:
test_x['D9'] = np.where(test_x['D9'].isna(),0,1)
########################### Reset values for "noise" card1
# i_cols = ['card1']
# for col in i_cols:
# valid_card = pd.concat([train[[col]], test[[col]]])
# valid_card = valid_card[col].value_counts()
# valid_card = valid_card[valid_card>2]
# valid_card = list(valid_card.index)
# test_x[col] = np.where(test_x[col].isin(train[col]), test_x[col], np.nan)
# test_x[col] = np.where(test_x[col].isin(valid_card), test_x[col], np.nan)
########################## M columns (except M4)
#All these columns are binary encoded 1/0
#We can have some features from it
# i_cols = ['M1','M2','M3','M5','M6','M7','M8','M9']
# test_x['M_sum'] = test_x[i_cols].sum(axis=1).astype(np.int8)
# test_x['M_na'] = test_x[i_cols].isna().sum(axis=1).astype(np.int8)
####################################Interaction term
test_x['uid'] = test['uid']
test_x['uid2'] = test['uid2']
test_x['uid3'] = test['uid3']
# Check if the Transaction Amount is common or not (we can use freq encoding here)
# In our dialog with a model we are telling to trust or not to these values
test_x['TransactionAmt_check'] = np.where(test_x['TransactionAmt'].isin(train['TransactionAmt']), 1, 0)
# For our model current TransactionAmt is a noise
# https://www.kaggle.com/kyakovlev/ieee-check-noise
# (even if features importances are telling contrariwise)
# There are many unique values and model doesn't generalize well
# Lets do some aggregations
i_cols = ['card1','card2','card3','card5']
for col2 in i_cols:
for agg_type in ['mean','std']:
new_col_name = col2+'_TransactionAmt_'+agg_type
temp_df = pd.concat([train[[col2, 'TransactionAmt']], test[[col2,'TransactionAmt']]])
#temp_df['TransactionAmt'] = temp_df['TransactionAmt'].astype(int)
temp_df = temp_df.groupby([col2])['TransactionAmt'].agg([agg_type]).reset_index().rename(
columns={agg_type: new_col_name})
temp_df.index = list(temp_df[col2])
temp_df = temp_df[new_col_name].to_dict()
test_x[new_col_name] = test_x[col2].map(temp_df)
i_cols2 = ['uid','uid2','uid3']
for col3 in i_cols2:
for agg_type in ['mean','std']:
new_col_name = col3+'_TransactionAmt_'+agg_type
temp_df = pd.concat([X[[col3, 'TransactionAmt']], test[[col3,'TransactionAmt']]])
#temp_df['TransactionAmt'] = temp_df['TransactionAmt'].astype(int)
temp_df = temp_df.groupby([col3])['TransactionAmt'].agg([agg_type]).reset_index().rename(
columns={agg_type: new_col_name})
temp_df.index = list(temp_df[col3])
temp_df = temp_df[new_col_name].to_dict()
test_x[new_col_name] = test_x[col3].map(temp_df)
# Small "hack" to transform distribution
# (doesn't affect auc much, but I like it more)
# please see how distribution transformation can boost your score
# (not our case but related)
# https://scikit-learn.org/stable/auto_examples/compose/plot_transformed_target.html
#test_x['TransactionAmt'] = np.log1p(test_x['TransactionAmt'])
########################### Device info
test_x['DeviceInfo'] = test_x['DeviceInfo'].fillna('unknown_device').str.lower()
test_x['DeviceInfo_device'] = test_x['DeviceInfo'].apply(lambda x: ''.join([i for i in x if i.isalpha()]))
test_x['DeviceInfo_version'] = test_x['DeviceInfo'].apply(lambda x: ''.join([i for i in x if i.isnumeric()]))
########################### Device info 2
test_x['id_30'] = test_x['id_30'].fillna('unknown_device').str.lower()
test_x['id_30_device'] = test_x['id_30'].apply(lambda x: ''.join([i for i in x if i.isalpha()]))
test_x['id_30_version'] = test_x['id_30'].apply(lambda x: ''.join([i for i in x if i.isnumeric()]))
########################### Browser
test_x['id_31'] = test_x['id_31'].fillna('unknown_device').str.lower()
test_x['id_31_device'] = test_x['id_31'].apply(lambda x: ''.join([i for i in x if i.isalpha()]))
###########
for feature in ['uid','uid2','uid3']:
# Count encoded separately for train and test,
test_x[feature + '_count'] = test_x[feature].map(X[feature].value_counts(dropna=False))
test_x=test_x.drop(columns=['ProductCD','P_emaildomain','R_emaildomain','M4','M5','M6','M1', 'M2','M3','M7','M8','M9','card6', 'DeviceType',
'card4','id_02','id_19','id_20','id_17','C2','TransactionDT','addr2','D6','D13','C5','C9','D7','C14',
'id_12', 'id_15', 'id_30', 'id_31', 'id_33', 'id_36', 'id_37', 'id_38','uid','uid2','uid3'])
#%%
#filling missing in test data
test_x['addr1'].fillna(0, inplace=True)
##test_x['D5'].fillna(150, inplace=True)
test_x['D2'].fillna(10, inplace=True)
test_x['D11'].fillna(10, inplace=True)
test_x['D15'].fillna(376, inplace=True)
#test_x['V1'].fillna(test_x['V1'].mode()[0], inplace=True)
#test_x['V2'].fillna(3, inplace=True)
test_x['V13'].fillna(test_x['V13'].mode()[0], inplace=True)
##test_x['V256'].fillna(test_x['V256'].mode()[0], inplace=True)
test_x['card2'].fillna(502, inplace=True)
test_x['card4_dic'].fillna(test_x['card4_dic'].mode()[0], inplace=True)
test_x['M4_dic'].fillna(2, inplace=True)
test_x['M5_dic'].fillna(3, inplace=True) #24:18:78
test_x['M6_dic'].fillna(13, inplace=True) #24:18:78
test_x['P_emaildomain_dic'].fillna(0, inplace=True)
test_x['R_emaildomain_dic'].fillna(0, inplace=True)
# test_x['V145'].fillna(0, inplace=True)
test_x['V19'].fillna(0, inplace=True)
test_x['V36'].fillna(0, inplace=True)
test_x['V64'].fillna(0, inplace=True)
test_x['V70'].fillna(0, inplace=True)
test_x['V80'].fillna(0, inplace=True)
test_x['V94'].fillna(0, inplace=True)
# test_x['V143'].fillna(0, inplace=True)
# test_x['V150'].fillna(0, inplace=True)
# test_x['V152'].fillna(0, inplace=True)
# test_x['V158'].fillna(0, inplace=True)##
# test_x['V163'].fillna(0, inplace=True)
# test_x['V165'].fillna(0, inplace=True)
# test_x['V177'].fillna(0, inplace=True)
# test_x['V204'].fillna(0, inplace=True)
# test_x['V207'].fillna(0, inplace=True)
# test_x['V209'].fillna(0, inplace=True) ##
# test_x['V221'].fillna(0, inplace=True)
# test_x['V222'].fillna(0, inplace=True)
# test_x['V266'].fillna(0, inplace=True)
# test_x['V267'].fillna(0, inplace=True)
# test_x['V274'].fillna(0, inplace=True)
# test_x['V275'].fillna(0, inplace=True)
test_x['V279'].fillna(0, inplace=True)
test_x['V283'].fillna(0, inplace=True)
#test_x['id_30_count'].fillna(0, inplace=True)
#%%
###KFOLD lightGBM
#from sklearn.model_selection import KFold
#
#import numpy as np
#import gc
#
#
##params for kfold CV
#params={'objective':'binary',
# 'boosting_type':'gbdt',
# 'metric':'auc',
# 'n_jobs':-1,
# 'learning_rate':0.01,
# 'num_leaves': 2**8,
# 'max_depth':-1,
# 'tree_learner':'serial',
# 'colsample_bytree': 0.7,
# 'subsample_freq':1,
# 'subsample':0.7,
# 'n_estimators':800,
# 'max_bin':255,
# 'verbose':-1,
# 'early_stopping_rounds':100 }
#
#
#def make_predictions(tr_df, tt_df, features_columns, target, lgb_params, NFOLDS=5):
# folds = KFold(n_splits=NFOLDS, shuffle=False, random_state=42)
#
# X,y = tr_df[features_columns], tr_df[target]
# P,P_y = tt_df[features_columns], tt_df[target]
#
# tt_df = tt_df[['TransactionID',target]]
# predictions = np.zeros(len(tt_df))
#
# for fold_, (trn_idx, val_idx) in enumerate(folds.split(X, y)):
# print('Fold:',fold_)
# tr_x, tr_y = X.iloc[trn_idx,:], y[trn_idx]
# vl_x, vl_y = X.iloc[val_idx,:], y[val_idx]
#
# print(len(tr_x),len(vl_x))
# tr_data = lgb.Dataset(tr_x, label=tr_y)
#
# if LOCAL_TEST:
# vl_data = lgb.Dataset(P, label=P_y)
# else:
# vl_data = lgb.Dataset(vl_x, label=vl_y)
#
# estimator = lgb.train(
# params,
# tr_data,
# valid_sets = [tr_data, vl_data],
# verbose_eval = 200,
# )
#
# pp_p = estimator.predict(P)
# predictions += pp_p/NFOLDS #consider weighting predictions??
#
# if LOCAL_TEST:
# feature_imp = pd.DataFrame(sorted(zip(estimator.feature_importance(),X.columns)),
# columns=['Value','Feature'])
# print(feature_imp)
#
# del tr_x, tr_y, vl_x, vl_y, tr_data, vl_data
# gc.collect()
#
# print('Best iteration in KFOLD CV is: '+estimator.best_iteration)
# tt_df['prediction'] = predictions
#
# return tt_df
#
############################ Model Train
#LOCAL_TEST = False
#TARGET = 'isFraud'
#
##assign train_df and test_df:
#if LOCAL_TEST:
#
# train_df=pd.concat([X,y],axis=1)
# test_df = train_df[train_df['month']==train_df['month'].max()].reset_index(drop=True) #last month data used as test
# train_df = train_df[train_df['month']<(train_df['month'].max()-1)].reset_index(drop=True)
#
#else:
# train_df=pd.concat([X,y],axis=1)
# test_df=test_x.iloc[:]
# test_df['isFraud']=0
#
#features_columns=X.columns
#
#if LOCAL_TEST:
# params['learning_rate'] = 0.01
# params['n_estimators'] = 20000
# params['early_stopping_rounds'] = 100
# test_predictions = make_predictions(train_df, test_df, features_columns, TARGET, params)
# print(roc_auc_score(test_predictions[TARGET], test_predictions['prediction']))
#else:
# params['learning_rate'] = 0.05
# params['n_estimators'] = 1800
# params['early_stopping_rounds'] = 100
# test_predictions = make_predictions(train_df, test_df, features_columns, TARGET, params, NFOLDS=10)
# #should NFOLDS=5 or 10?
#%%
test_predictions
#%%
###time series split
from sklearn.model_selection import TimeSeriesSplit
from time import time
folds = TimeSeriesSplit(n_splits=5)
aucs = list()
feature_importances = pd.DataFrame()
feature_importances['feature'] = X.columns
#params for time series split and lgb train
params = {'num_leaves': 491,
'min_child_weight': 0.03454472573214212,
'feature_fraction': 0.3797454081646243,
'bagging_fraction': 0.4181193142567742,
'min_data_in_leaf': 106,
'objective': 'binary',
'max_depth': -1,
'learning_rate': 0.006883242363721497,
"boosting_type": "gbdt",
"bagging_seed": 11,
"metric": 'auc',
"verbosity": -1,
'reg_alpha': 0.3899927210061127,
'reg_lambda': 0.6485237330340494,
'random_state': 47
}
training_start_time = time()
for fold, (trn_idx, test_idx) in enumerate(folds.split(X, y)):
start_time = time()
print('Training on fold {}'.format(fold + 1))
trn_data = lgb.Dataset(X.iloc[trn_idx], label=y.iloc[trn_idx])
val_data = lgb.Dataset(X.iloc[test_idx], label=y.iloc[test_idx])
clf = lgb.train(params, trn_data, 10000, valid_sets = [trn_data, val_data], verbose_eval=1000,
early_stopping_rounds=500)
pp_p = clf.predict(test_x)
#ensemble
predictions_tssplit += pp_p/5 #n_splits=5, consider weighting predictions??
feature_importances['fold_{}'.format(fold + 1)] = clf.feature_importance()
#consider weighting aucs??
aucs.append(clf.best_score['valid_1']['auc'])
print('Fold {} finished in {}'.format(fold + 1, str(datetime.timedelta(seconds=time() - start_time))))
print('-' * 30)
print('Training has finished.')
print('Total training time is {}'.format(str(datetime.timedelta(seconds=time() - training_start_time))))
print('Mean AUC:', np.mean(aucs))
print('-' * 30)
test_x['prediction'] = predictions_tssplit
#%%
feature_importances['average'] = feature_importances[['fold_{}'.format(fold + 1) for fold in range(folds.n_splits)]].mean(axis=1)
feature_importances.to_csv('feature_importances.csv')
plt.figure(figsize=(16, 16))
sns.barplot(data=feature_importances.sort_values(by='average', ascending=False).head(50), x='average', y='feature');
plt.title('50 TOP feature importance over {} folds average'.format(folds.n_splits));
#%%
#time series split best iteration
best_iter = clf.best_iteration
clf.best_score
#%%
clf = lgb.LGBMClassifier(**params, num_boost_round=best_iter)
clf.fit(X, y)
#%%
#important to reset index
test_x=test_x.reset_index(drop=False)
#No cross validation prediction:
#test_x['isFraud']=clf.predict_proba(test_x.drop(columns=['TransactionID']))[:,1]
#for kfold
test_x['isFraud']=test_predictions['prediction']
#for time series split
#test_x['isFraud'] = clf.predict_proba(test_x.drop(columns=['TransactionID']))[:, 1]
#%%
output=test_x[['TransactionID','isFraud']]
#%%
#test.shape
output.to_csv("output_submission_ts.csv",index=False)
<file_sep>/archive/ieee_fraud_data_v5_gridsearchcv.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 2 17:22:29 2019
@author: ruiqianyang
"""
files=['test_identity.csv',
'test_transaction.csv',
'train_identity.csv',
'train_transaction.csv']
import pandas as pd
def load_data(file):
return pd.read_csv(file,index_col='TransactionID')
#%%
#import multiprocessing
#import time
#with multiprocessing.Pool() as pool:
# test_id,test_trans,train_id,train_trans=pool.map(load_data,files)
test_id,test_trans,train_id,train_trans=load_data(files[0]),load_data(files[1]),load_data(files[2]),load_data(files[3])
#%%
train=train_trans.merge(train_id,how='left',left_index=True,right_index=True)
del(train_trans)
del(train_id)
test=test_trans.merge(test_id,how='left',left_index=True,right_index=True)
del test_id, test_trans
#train=pd.merge(train_trans,train_id,on='TransactionID',how='left')
#test=pd.merge(test_trans,test_id,on='TransactionID',how='left')
#%%
import datetime
startDT = datetime.datetime.strptime('2017-12-01', '%Y-%m-%d')
startDT
#add month,day of month,day of week,hour of day
train['TransactionDT1']=train['TransactionDT'].apply(lambda x:(startDT+datetime.timedelta(seconds=x)))
train['month']=train['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%m')))
train['day']=train['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%d')))
train['dayofweek']=train['TransactionDT1'].dt.date.apply(lambda x: x.weekday())
train['hour']=train['TransactionDT1'].apply(lambda x: int(x.strftime('%H')))
train['weekofyear']=train['TransactionDT1'].apply(lambda x: int(x.strftime('%U')))
#engineer Month to start from 12 and monotonous increasing;
#seems redcuce score...
#train['month'] = (train['TransactionDT1'].dt.year-2017)*12 + train['TransactionDT1'].dt.month
#train.iloc[299000:299100]
test['TransactionDT1']=test['TransactionDT'].apply(lambda x:(startDT+datetime.timedelta(seconds=x)))
test['month']=test['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%m')))
test['day']=test['TransactionDT1'].dt.date.apply(lambda x: int(x.strftime('%d')))
test['dayofweek']=test['TransactionDT1'].dt.date.apply(lambda x: x.weekday())
test['hour']=test['TransactionDT1'].apply(lambda x: int(x.strftime('%H')))
test['weekofyear']=test['TransactionDT1'].apply(lambda x: int(x.strftime('%U')))
#engineer Month to start from 12 and monotonous increasing;
#test['month'] = (test['TransactionDT1'].dt.year-2017)*12 + test['TransactionDT1'].dt.month
#test.head(3)
#%%
train['TransactionAmt_decimal'] = ((train['TransactionAmt'] - train['TransactionAmt'].astype(int)) * 1000).astype(int)
test['TransactionAmt_decimal'] = ((test['TransactionAmt'] - test['TransactionAmt'].astype(int)) * 1000).astype(int)
#plot_numerical1('TransactionAmt_decimal')
#creat new feature: Number of NaN's
train['nulls']=train.isnull().sum(axis=1)
test['nulls']=test.isnull().sum(axis=1)
#to be continued for filling missing data ...........................................
################################################################################
#%%
from sklearn.model_selection import train_test_split
import lightgbm as lgb
from sklearn.metrics import roc_auc_score
import pickle
y = train['isFraud']
X = pd.DataFrame()
col=['TransactionDT','ProductCD','P_emaildomain','R_emaildomain','nulls','month','hour',
'TransactionAmt', 'TransactionAmt_decimal','D5','D2','D8','D9','D11','D15','C1','C4','C8','C10','C13','C2',
'V256','V13','card1','card2','card3','card4', 'card5', 'card6','addr1','M4','M5','M6','M1','DeviceType',
'DeviceInfo', 'addr2','D6','D13','C5','C9','D7','C14','V145',
'V3','V4','V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V17',
'V19', 'V20', 'V29', 'V30', 'V33', 'V34', 'V35', 'V36', 'V37', 'V38', 'V40', 'V44', 'V45', 'V46', 'V47', 'V48',
'V49', 'V51', 'V52', 'V53', 'V54', 'V56', 'V58', 'V59', 'V60', 'V61', 'V62', 'V63', 'V64', 'V69', 'V70', 'V71',
'V72', 'V73', 'V74', 'V75', 'V76', 'V78', 'V80', 'V81', 'V82', 'V83', 'V84', 'V85', 'V87', 'V90', 'V91', 'V92',
'V93', 'V94', 'V95', 'V96', 'V97', 'V99', 'V100', 'V126', 'V127', 'V128', 'V130', 'V131', 'V138', 'V139', 'V140',
'V143', 'V146', 'V147', 'V149', 'V150', 'V151', 'V152', 'V154', 'V156', 'V158', 'V159', 'V160', 'V161',
'V162', 'V163', 'V164', 'V165', 'V166', 'V167', 'V169', 'V170', 'V171', 'V172', 'V173', 'V175', 'V176', 'V177',
'V178', 'V180', 'V182', 'V184', 'V187', 'V188', 'V189', 'V195', 'V197', 'V200', 'V201', 'V202', 'V203', 'V204',
'V205', 'V206', 'V207', 'V208', 'V209', 'V210', 'V212', 'V213', 'V214', 'V215', 'V216', 'V217', 'V219', 'V220',
'V221', 'V222', 'V223', 'V224', 'V225', 'V226', 'V227', 'V228', 'V229', 'V231', 'V233', 'V234', 'V238', 'V239',
'V242', 'V243', 'V244', 'V245', 'V246', 'V247', 'V249', 'V251', 'V253', 'V257', 'V258', 'V259', 'V261',
'V262', 'V263', 'V264', 'V265', 'V266', 'V267', 'V268', 'V270', 'V271', 'V272', 'V273', 'V274', 'V275', 'V276',
'V277', 'V278', 'V279', 'V280', 'V282', 'V283', 'V285', 'V287', 'V288', 'V289', 'V291', 'V292', 'V294', 'V303',
'V304', 'V306', 'V307', 'V308', 'V310', 'V312', 'V313', 'V314', 'V315', 'V317', 'V322',
'V323','V324', 'V326','V329','V331','V332', 'V333', 'V335', 'V336',
'id_01', 'id_02', 'id_03', 'id_05', 'id_06', 'id_09',
'id_11', 'id_12', 'id_13', 'id_14', 'id_15', 'id_17', 'id_19', 'id_20', 'id_30', 'id_31', 'id_32', 'id_33',
'id_36', 'id_37', 'id_38','isFraud']
#'V48','V53','V96'
# 'V338'
#month is important
# Save to pickle
#New_DatasetName = "Basic"
#train[col].to_pickle("train_{}.pkl".format(New_DatasetName))
#test[col[:-1]].to_pickle("test_{}.pkl".format(New_DatasetName))
col.pop()
X[col] = train[col]
X['M4_count'] =X['M4'].map(pd.concat([train['M4'], test['M4']], ignore_index=True).value_counts(dropna=False))
X['M6_count'] =X['M6'].map(pd.concat([train['M6'], test['M6']], ignore_index=True).value_counts(dropna=False))
X['card1_count'] = X['card1'].map(pd.concat([train['card1'], test['card1']], ignore_index=True).value_counts(dropna=False))
X['card6_count'] =X['card6'].map(pd.concat([train['card6'], test['card6']], ignore_index=True).value_counts(dropna=False))
X['DeviceType_count'] =X['DeviceType'].map(pd.concat([train['DeviceType'], test['DeviceType']], ignore_index=True).value_counts(dropna=False))
#X['DeviceInfo_count'] =X['DeviceInfo'].map(pd.concat([train['DeviceInfo'], test['DeviceInfo']], ignore_index=True).value_counts(dropna=False))
X['ProductCD_count'] =X['ProductCD'].map(pd.concat([train['ProductCD'], test['ProductCD']], ignore_index=True).value_counts(dropna=False))
X['P_emaildomain_count'] =X['P_emaildomain'].map(pd.concat([train['P_emaildomain'], test['P_emaildomain']], ignore_index=True).value_counts(dropna=False))
#X['R_emaildomain_count'] =X['R_emaildomain'].map(pd.concat([train['R_emaildomain'], test['R_emaildomain']], ignore_index=True).value_counts(dropna=False))
X['addr1_count'] = X['addr1'].map(pd.concat([train['addr1'], test['addr1']], ignore_index=True).value_counts(dropna=False))
###X['addr1_y'] =X['addr1'].map(train.groupby(['addr1'])['isFraud'].mean())
#X['id_02_count'] = X['id_02'].map(pd.concatD.value_counts(dropna=False))
#X['id_17_count'] = X['id_17'].map(pd.concat([train['id_17'], test['id_17']], ignore_index=True).value_counts(dropna=False))
###X['id_02'].fillna(0, inplace=True)
# Risk mapping transformation
card4_dic = {'american express':287,'discover':773,'mastercard':343,'visa':348}
X['card4_dic']=X['card4'].map(card4_dic)
#train=train.replace({'card4':card4_dic})
#test=test.replace({'card4':card4_dic})
ProductCD_dic = {'C':117,'H':48,'R':38,'S':59,'W':20}
X['ProductCD_dic']=X['ProductCD'].map(ProductCD_dic)
#New feature:addr2 risk mapping
#addr2_dic={46:100,51:100,10:100,65:54,96:14,60:9,32:7,87:2}
#X['addr2_dic']=X['addr2'].map(addr2_dic)
#38:67,73:20,54:33,68:10,29:9,
#cross risk mapping for card4 vs ProductCD:
def func(i,j):
if i=='american express' and j=='C':
return 100
elif i=='american express' and j=='H':
return 6
elif i=='american express' and j=='R':
return 2
elif i=='american express' and j=='S':
return 6
elif i=='discover' and j=='H':
return 7
elif i=='discover' and j=='R':
return 5
elif i=='discover' and j=='S':
return 13
elif i=='discover' and j=='W':
return 8
elif i=='mastercard' and j=='C':
return 11
elif i=='mastercard' and j=='H':
return 5
elif i=='mastercard' and j=='R':
return 5
elif i=='mastercard' and j=='S':
return 5
elif i=='mastercard' and j=='W':
return 2
elif i=='visa' and j=='C':
return 12
elif i=='visa' and j=='H':
return 5
elif i=='visa' and j=='R':
return 4
elif i=='visa' and j=='S':
return 6
elif i=='visa' and j=='W':
return 2
#X['cross'] = X.apply(lambda x:func(x['card4'],x['ProductCD']),axis=1)
card6_dic = {'charge card':0,'credit':668,'debit':243,'debit or credit':0}
X['card6_dic']=X['card6'].map(card6_dic)
#train=train.replace({'card6':card6_dic})
#test=test.replace({'card6':card6_dic})
M1_dic={'F':0,'T':2}
X['M1_dic']=X['M1'].map(M1_dic)
M4_dic={'M0':4,'M1':3,'M2':13}
X['M4_dic']=X['M4'].map(M4_dic)
M5_dic={'F':2,'T':3}
X['M5_dic']=X['M5'].map(M5_dic)
M6_dic={'F':4,'T':3}
X['M6_dic']=X['M6'].map(M6_dic)
#DeviceInfo has many category levels
#DeviceType_dic={'desktop':3,'mobile':5}
#X['DeviceType_dic']=X['DeviceType'].map(DeviceType_dic)
P_emaildomain_dic={'protonmail.com':40,'mail.com':19,'outlook.es':13,'aim.com':12,
'outlook.com':9,'hotmail.es':7,'live.com.mx':5,'hotmail.com':5,'gmail.com':4}
X['P_emaildomain_dic']=X['P_emaildomain'].map(P_emaildomain_dic)
R_emaildomain_dic={'protonmail.com':95,'mail.com':38,'netzero.net':22,'outlook.com':17,
'outlook.es':13,'icloud.com':13,'gmail.com':12,'hotmail.com':8,
'earthlink.net':8,'earthlink.net':7,'hotmail.es':7,'live.com.mx':6,
'yahoo.com':5,'live.com':5}
X['R_emaildomain_dic']=X['R_emaildomain'].map(R_emaildomain_dic)
#New feature:C2 vs TransactionDT
def func_C2_Tran(a,b):
if a<400:
return 344
elif a>=400 and a<=651 and b<=4000000:
return 3846
elif a>=400 and a<=651 and b>10000000:
return 10000
else:
return 1082
X['C2_TransactionDT']=X.apply(lambda x:func_C2_Tran(x['C2'],x['TransactionDT']),axis=1)
for feature in ['id_30']:
# Count encoded separately for train and test,
X[feature + '_count'] = X[feature].map(pd.concat([train[feature], test[feature]], ignore_index=True).value_counts(dropna=False))
X=X.drop(columns=['ProductCD','P_emaildomain','R_emaildomain','M4','M5','M6','M1','card6', 'DeviceType','DeviceInfo',
'card4','id_02','id_19','id_20','id_17','C2','TransactionDT','addr2','D6','D13','C5','C9','D7','C14',
'id_12', 'id_15', 'id_30', 'id_31', 'id_33', 'id_36', 'id_37', 'id_38'
])
#%%
print('start fillna')
X['addr1'].fillna(0, inplace=True)
#X['addr2_dic'].fillna(3, inplace=True)
#X['addr2'].fillna(96, inplace=True)
#X['D5'].fillna(150, inplace=True)
X['D2'].fillna(10, inplace=True)
X['D11'].fillna(10, inplace=True)
X['D15'].fillna(376, inplace=True)
#X['V1'].fillna(X['V1'].mode()[0], inplace=True)
#X['V2'].fillna(3, inplace=True)
X['V13'].fillna(X['V13'].mode()[0], inplace=True)
#X['V145'].fillna(X['V145'].mode()[0], inplace=True) #fillna reduce score
#X['V263'].fillna(X['V263'].mode()[0], inplace=True)
#X['V256'].fillna(X['V256'].mode()[0], inplace=True)
X['card2'].fillna(502, inplace=True)
###X['card3'].fillna(150, inplace=True)
X['card4_dic'].fillna(X['card4_dic'].mode()[0], inplace=True)
X['M4_dic'].fillna(2, inplace=True)
X['M5_dic'].fillna(3, inplace=True) #24:18:78
X['M6_dic'].fillna(13, inplace=True) #24:18:78
#X['cross'].fillna(2.6, inplace=True)
#X['id_19'].fillna(444, inplace=True)
#X['id_20'].fillna(266, inplace=True)
#X['id_17'].fillna(133, inplace=True)
X['P_emaildomain_dic'].fillna(0, inplace=True)
X['R_emaildomain_dic'].fillna(0, inplace=True)
#%%
#train test split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.33, random_state=47, shuffle=False)
#%%
#train with lgb
#params = {'boosting_type':'gbdt', 'class_weight':None, 'colsample_bytree':1.0,
# 'importance_type':'split', 'learning_rate':0.05, 'max_depth':20,
# 'min_child_samples':20, 'min_child_weight':0.001, 'min_split_gain':0.0,
# 'n_estimators':300, 'n_jobs':-1, 'num_leaves':300, 'silent':False, 'subsample':1,
# 'reg_alpha':0.0, 'reg_lambda':0.0,'subsample_for_bin':200000, 'subsample_freq':0,
# 'objective': 'binary', "bagging_seed": 8, 'metric': 'auc', 'random_state': 47}
#
#
#clf = lgb.LGBMClassifier(**params)
#clf.fit(X_train, y_train)
#roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])
# clf.fit(upsampled.drop(columns=['isFraud']),upsampled['isFraud'])
# X_test=X_test.drop(columns=['TransactionDT'])
# roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])
#%%
#add grid of paramters
print('start GridSearchCV')
from sklearn.model_selection import GridSearchCV
lg = lgb.LGBMClassifier(silent=False)
param_dist = {"max_depth": [25], #<=0 means no limit
"learning_rate" : [0.05],
"num_leaves": [256],
"n_estimators": [300,1800,3000],
'min_child_samples':[20],
'bagging_fraction': [0.42],
'feature_fraction': [0.38],
'min_child_weight': [0.00298],
'min_data_in_leaf': [106],
'reg_alpha': [0.38999],
'reg_lambda': [2.0]
# "max_depth": [5,25,-1,50],
# "learning_rate" : [0.05,0.00688,0.01],
# "num_leaves": [300, 491,382,2**8],
# "n_estimators": [300,800],
# 'min_child_samples':[20],
# 'bagging_fraction': [0.42,0.9],
# 'feature_fraction': [0.38,0.9],
# 'min_child_weight': [0.00298,0.03454],
# 'min_data_in_leaf': [20,106],
# 'reg_alpha': [1.0,0.38999],
# 'reg_lambda': [2.0,0.6485],
# 'colsample_bytree': 0.7,
# 'subsample_freq':1,
# 'subsample':0.7,
# 'max_bin':255,
# 'verbose':-1,
# 'seed': SEED,
# 'early_stopping_rounds':100,
}
grid_search = GridSearchCV(lg, param_grid=param_dist, cv = 3, scoring="roc_auc", verbose=5)
grid_search.fit(X_train,y_train)
print(grid_search.best_estimator_)
#%%
# LGB_BO.max['params']
# {'bagging_fraction': 0.8999999999997461,
# 'feature_fraction': 0.8999999999999121,
# 'max_depth': 50.0,
# 'min_child_weight': 0.0029805017044362268,
# 'min_data_in_leaf': 20.0,
# 'num_leaves': 381.85354295079446,
# 'reg_alpha': 1.0,
# 'reg_lambda': 2.0}
# params = {'num_leaves': 491,
# 'min_child_weight': 0.03454472573214212,
# 'feature_fraction': 0.3797454081646243,
# 'bagging_fraction': 0.4181193142567742,
# 'min_data_in_leaf': 106,
# 'objective': 'binary',
# 'max_depth': -1,
# 'learning_rate': 0.006883242363721497,
# "boosting_type": "gbdt",
# "bagging_seed": 11,
# "metric": 'auc',
# "verbosity": -1,
# 'reg_alpha': 0.3899927210061127,
# 'reg_lambda': 0.6485237330340494,
# 'random_state': 47
# }
#%%
#preprocessing in test data
#for prediction on test dataset
#test_x=pd.DataFrame()
#test_x[col] = test[col]
#
#test_x['M4_count'] =test_x['M4'].map(pd.concat([train['M4'], test['M4']], ignore_index=True).value_counts(dropna=False))
#test_x['M6_count'] =test_x['M6'].map(pd.concat([train['M6'], test['M6']], ignore_index=True).value_counts(dropna=False))
#test_x['card1_count'] = test_x['card1'].map(pd.concat([train['card1'], test['card1']], ignore_index=True).value_counts(dropna=False))
#test_x['card6_count'] = test_x['card6'].map(pd.concat([train['card6'], test['card6']], ignore_index=True).value_counts(dropna=False))
#
#test_x['addr1_count'] = test_x['addr1'].map(pd.concat([train['addr1'], test['addr1']], ignore_index=True).value_counts(dropna=False))
#test_x['ProductCD_count'] =test_x['ProductCD'].map(pd.concat([train['ProductCD'], test['ProductCD']], ignore_index=True).value_counts(dropna=False))
#test_x['P_emaildomain_count'] =test_x['P_emaildomain'].map(pd.concat([train['P_emaildomain'], test['P_emaildomain']], ignore_index=True).value_counts(dropna=False))
##test_x['R_emaildomain_count'] =test_x['R_emaildomain'].map(pd.concat([train['R_emaildomain'], test['R_emaildomain']], ignore_index=True).value_counts(dropna=False))
#test_x['DeviceType_count'] =test_x['DeviceType'].map(pd.concat([train['DeviceType'], test['DeviceType']], ignore_index=True).value_counts(dropna=False))
#
## Risk mapping transformation
#test_x['card4_dic']=test_x['card4'].map(card4_dic)
#test_x['card6_dic']=test_x['card6'].map(card6_dic)
#test_x['ProductCD_dic']=test_x['ProductCD'].map(ProductCD_dic)
##test_x['cross'] = test_x.apply(lambda x:func(x['card4'],x['ProductCD']),axis=1)
#M1_dic={'F':0,'T':2}
#test_x['M1_dic']=test_x['M1'].map(M1_dic)
#M4_dic={'M0':4,'M1':3,'M2':13}
#test_x['M4_dic']=test_x['M4'].map(M4_dic)
#M5_dic={'F':2,'T':3}
#test_x['M5_dic']=test_x['M5'].map(M5_dic)
#M6_dic={'F':4,'T':3}
#test_x['M6_dic']=test_x['M6'].map(M6_dic)
#test_x['R_emaildomain_dic']=test_x['R_emaildomain'].map(R_emaildomain_dic)
#test_x['P_emaildomain_dic']=test_x['P_emaildomain'].map(P_emaildomain_dic)
#test_x['C2_TransactionDT']=test_x.apply(lambda x:func_C2_Tran(x['C2'],x['TransactionDT']),axis=1)
#
#
#test_x=test_x.drop(columns=['ProductCD','P_emaildomain','R_emaildomain','M4','M5','M6','M1','card6', 'DeviceType',
# 'DeviceInfo','card4','id_02','id_19','id_20','id_17','C2','TransactionDT','addr2','D6','D13','C5',
# 'C9','D7','C14'])
#%%
#filling missing in test data
#test_x['addr1'].fillna(0, inplace=True)
#
#test_x['D2'].fillna(10, inplace=True)
#test_x['D11'].fillna(10, inplace=True)
#test_x['D15'].fillna(376, inplace=True)
#
#test_x['V13'].fillna(test_x['V13'].mode()[0], inplace=True)
#
#
#test_x['card2'].fillna(502, inplace=True)
#test_x['card4_dic'].fillna(test_x['card4_dic'].mode()[0], inplace=True)
#
#test_x['M4_dic'].fillna(2, inplace=True)
#test_x['M5_dic'].fillna(3, inplace=True) #24:18:78
#test_x['M6_dic'].fillna(13, inplace=True) #24:18:78
#test_x['P_emaildomain_dic'].fillna(0, inplace=True)
#test_x['R_emaildomain_dic'].fillna(0, inplace=True)
#%%
###KFOLD lightGBM
#from sklearn.model_selection import KFold
#
#import numpy as np
#import gc
#
#
##params for kfold CV
#params={'objective':'binary',
# 'boosting_type':'gbdt',
# 'metric':'auc',
# 'n_jobs':-1,
# 'learning_rate':0.01,
# 'num_leaves': 2**8,
# 'max_depth':-1,
# 'tree_learner':'serial',
# 'colsample_bytree': 0.7,
# 'subsample_freq':1,
# 'subsample':0.7,
# 'n_estimators':800,
# 'max_bin':255,
# 'verbose':-1,
# 'early_stopping_rounds':100 }
#
#
#def make_predictions(tr_df, tt_df, features_columns, target, lgb_params, NFOLDS=5):
# folds = KFold(n_splits=NFOLDS, shuffle=False, random_state=42)
#
# X,y = tr_df[features_columns], tr_df[target]
# P,P_y = tt_df[features_columns], tt_df[target]
#
# tt_df = tt_df[['TransactionID',target]]
# predictions = np.zeros(len(tt_df))
#
# for fold_, (trn_idx, val_idx) in enumerate(folds.split(X, y)):
# print('Fold:',fold_)
# tr_x, tr_y = X.iloc[trn_idx,:], y[trn_idx]
# vl_x, vl_y = X.iloc[val_idx,:], y[val_idx]
#
# print(len(tr_x),len(vl_x))
# tr_data = lgb.Dataset(tr_x, label=tr_y)
#
# if LOCAL_TEST:
# vl_data = lgb.Dataset(P, label=P_y)
# else:
# vl_data = lgb.Dataset(vl_x, label=vl_y)
#
# estimator = lgb.train(
# params,
# tr_data,
# valid_sets = [tr_data, vl_data],
# verbose_eval = 200,
# )
#
# pp_p = estimator.predict(P)
# predictions += pp_p/NFOLDS #consider weighting predictions??
#
# if LOCAL_TEST:
# feature_imp = pd.DataFrame(sorted(zip(estimator.feature_importance(),X.columns)),
# columns=['Value','Feature'])
# print(feature_imp)
#
# del tr_x, tr_y, vl_x, vl_y, tr_data, vl_data
# gc.collect()
#
# print('Best iteration in KFOLD CV is: '+estimator.best_iteration)
# tt_df['prediction'] = predictions
#
# return tt_df
#
############################ Model Train
#LOCAL_TEST = False
#TARGET = 'isFraud'
#
##assign train_df and test_df:
#if LOCAL_TEST:
#
# train_df=pd.concat([X,y],axis=1)
# test_df = train_df[train_df['month']==train_df['month'].max()].reset_index(drop=True) #last month data used as test
# train_df = train_df[train_df['month']<(train_df['month'].max()-1)].reset_index(drop=True)
#
#else:
# train_df=pd.concat([X,y],axis=1)
# test_df=test_x.iloc[:]
# test_df['isFraud']=0
#
#features_columns=X.columns
#
#if LOCAL_TEST:
# params['learning_rate'] = 0.01
# params['n_estimators'] = 20000
# params['early_stopping_rounds'] = 100
# test_predictions = make_predictions(train_df, test_df, features_columns, TARGET, params)
# print(roc_auc_score(test_predictions[TARGET], test_predictions['prediction']))
#else:
# params['learning_rate'] = 0.05
# params['n_estimators'] = 1800
# params['early_stopping_rounds'] = 100
# test_predictions = make_predictions(train_df, test_df, features_columns, TARGET, params, NFOLDS=10)
#should NFOLDS=5 or 10?
#%%
###time series split
#from sklearn.model_selection import TimeSeriesSplit
#from time import time
#folds = TimeSeriesSplit(n_splits=5)
#
#aucs = list()
#feature_importances = pd.DataFrame()
#feature_importances['feature'] = X.columns
#
#
##params for time series split and lgb train
#params = {'num_leaves': 491,
# 'min_child_weight': 0.03454472573214212,
# 'feature_fraction': 0.3797454081646243,
# 'bagging_fraction': 0.4181193142567742,
# 'min_data_in_leaf': 106,
# 'objective': 'binary',
# 'max_depth': -1,
# 'learning_rate': 0.006883242363721497,
# "boosting_type": "gbdt",
# "bagging_seed": 11,
# "metric": 'auc',
# "verbosity": -1,
# 'reg_alpha': 0.3899927210061127,
# 'reg_lambda': 0.6485237330340494,
# 'random_state': 47
# }
#
#
#training_start_time = time()
#for fold, (trn_idx, test_idx) in enumerate(folds.split(X, y)):
# start_time = time()
# print('Training on fold {}'.format(fold + 1))
#
# trn_data = lgb.Dataset(X.iloc[trn_idx], label=y.iloc[trn_idx])
# val_data = lgb.Dataset(X.iloc[test_idx], label=y.iloc[test_idx])
# clf = lgb.train(params, trn_data, 10000, valid_sets = [trn_data, val_data], verbose_eval=1000,
# early_stopping_rounds=500)
#
# pp_p = clf.predict(test_x)
# #ensemble
# predictions_tssplit += pp_p/5 #n_splits=5, consider weighting predictions??
#
#
# feature_importances['fold_{}'.format(fold + 1)] = clf.feature_importance()
# #consider weighting aucs??
# aucs.append(clf.best_score['valid_1']['auc'])
#
# print('Fold {} finished in {}'.format(fold + 1, str(datetime.timedelta(seconds=time() - start_time))))
#print('-' * 30)
#print('Training has finished.')
#print('Total training time is {}'.format(str(datetime.timedelta(seconds=time() - training_start_time))))
#print('Mean AUC:', np.mean(aucs))
#print('-' * 30)
#
#test_x['prediction'] = predictions_tssplit
#%%
#feature_importances['average'] = feature_importances[['fold_{}'.format(fold + 1) for fold in range(folds.n_splits)]].mean(axis=1)
#feature_importances.to_csv('feature_importances.csv')
#
#plt.figure(figsize=(16, 16))
#sns.barplot(data=feature_importances.sort_values(by='average', ascending=False).head(50), x='average', y='feature');
#plt.title('50 TOP feature importance over {} folds average'.format(folds.n_splits));
#%%
#time series split best iteration
#best_iter = clf.best_iteration
#clf.best_score
#%%
#clf = lgb.LGBMClassifier(**params, num_boost_round=best_iter)
#clf.fit(X, y)
#%%
#No cross validation prediction:
#test_x['isFraud']=clf.predict_proba(test_x.drop(columns=['TransactionID']))[:,1]
#for kfold
#test_x['isFraud']=test_predictions['prediction']
#for time series split
#test_x['isFraud'] = clf.predict_proba(test_x.drop(columns=['TransactionID']))[:, 1]
#%%
#output=test_x[['TransactionID','isFraud']]
#output
#%%
#output.to_csv("output_submission.csv",index=False)
<file_sep>/IEEE_Fraud_v7-xgb_kfold_test.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 15:56:54 2019
@author: ruiqianyang
"""
import pandas as pd
from sklearn.model_selection import train_test_split
import lightgbm as lgb
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import LabelEncoder
import numpy as np
import gc
#%%
####data from r
train_r=pd.read_csv('train_r.csv')
test_r=pd.read_csv('test_r.csv')
#del X,test_x
X=train_r.drop(train_r.columns[0],axis=1)
test_x=test_r.drop(test_r.columns[0],axis=1)
label = pd.read_pickle('train_Basic.pkl')
y = label['isFraud']
train=pd.read_pickle('train_Basic.pkl')
test=pd.read_pickle('test_Basic.pkl')
y=y.reset_index(drop=False)
train=train.reset_index(drop=False)
test=test.reset_index(drop=False)
X['TransactionID']=train['TransactionID']
test_x['TransactionID']=test['TransactionID']
X['month']=train['month']
test_x['month']=test['month']
import datetime
startDT = datetime.datetime.strptime('2017-12-01', '%Y-%m-%d')
train['TransactionDT1']=train['TransactionDT'].apply(lambda x:(startDT+datetime.timedelta(seconds=x)))
X['DT_M'] = ((train['TransactionDT1'].dt.year-2017)*12 + train['TransactionDT1'].dt.month).astype(np.int8)
X['DT_M']
for df in [X, test_x]:
for col_1 in df.columns:
if df[col_1].dtype == 'object':
print(col_1)
le = LabelEncoder()
le.fit(list(train_r[col_1].astype(str).values) +
list(test_r[col_1].astype(str).values))
df[col_1] = le.transform(list(df[col_1].astype(str).values))
df.fillna(-999,inplace=True)
df[np.isinf(df.values)==True] = 999
#%%
###minify data
X_12=X[X['month']==12]
y_12=label[label['month']==12]['isFraud']
#%%
X_train, X_test, y_train, y_test = train_test_split(X_xgb.drop(columns=['TransactionID','DT_M']),
y_xgb, test_size=0.33, random_state=47, shuffle=False)
import xgboost as xgb
import time
start=time.time()
clf = xgb.XGBClassifier(
n_jobs=4,
n_estimators=500,
max_depth=20,
learning_rate=0.035, #0.04,
subsample=0.7,
colsample_bytree= 0.7463058454739352,
tree_method='gpu_hist', # THE MAGICAL PARAMETER
# gamma=1,
# min_child_weight=1,
# max_delta_step=,
random_state=2019,
# max_delta_step= 4.762550705407337,
reg_alpha= 0.39871702770778467,
reg_lamdba=0.24309304355829786)
# min_child_samples= 170)
# {'target': 0.9175568588299362, 'params':
# {'colsample_bytree': 0.9285591089934457, 'gamma': 1.0, 'learning_rate': 0.026245848007381067,
# 'max_delta_step': 4.762550705407337, 'max_depth': 19.868689007456137, 'min_child_weight': 2.1576248698291813,
# 'reg_alpha': 0.2866349425015622, 'reg_lambda': 0.40562804952710174, 'subsample': 0.9301734656335603}}
clf.fit(X_train, y_train,eval_set = [(X_test, y_test)], eval_metric="auc",
early_stopping_rounds = 10)
print(time.time()-start)
roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])
<file_sep>/data/data_readme.md
In this competition you are predicting the probability that an online transaction is fraudulent, as denoted by the binary target isFraud.
The data is broken into two files identity and transaction, which are joined by TransactionID. Not all transactions have corresponding identity information.
Original files for training and testing datasets are larger than 1GB. Can't upload.
## Transaction Table
* train:590,540 rows, 394 cols
* test:507k rows, 394 cols
## Identity Table
* train: 144,233 rows, 41 cols
* test:142k rows, 41 cols
|
2c407f2edaa58007441e9a6de1eb0ff2d4e2263c
|
[
"Markdown",
"Python"
] | 8 |
Python
|
emisaycheese/IEEE-CIS-Fraud-Detection
|
81f9a693653cdba375bcea3ffb6274b9406ac93a
|
49ae105d650302d909ab623eb51e2324d364e273
|
refs/heads/master
|
<file_sep># salestax
java coding problem - calculate the sales tax for different products
# how to run
./mvnw spring-boot:run
# how to test
- use a rest client to send a POST request to http://localhost:8080/receipt
sample request 1:
```json
{
"items": [
{
"quantity": 1,
"product": {
"name": "book",
"price": 12.49,
"exempt": true
}
},
{
"quantity": 1,
"product": {
"name": "music CD",
"price": 14.99
}
},
{
"quantity": 1,
"product": {
"name": "book",
"price": 0.85,
"exempt": true
}
}
]
}
```
sample request 2:
```json
{
"items": [
{
"quantity": 1,
"product": {
"name": "box of chocolates",
"price": 10.00,
"exempt": true,
"imported": true
}
},
{
"quantity": 1,
"product": {
"name": "bottle of perfume",
"price": 47.50,
"imported": true
}
}
]
}
```
<file_sep>package adolfov.salestax.model;
import java.math.BigDecimal;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class ReceiptTest {
private ShoppingBasket basket;
private BasketItem singleImportedExemptItem;
private BasketItem multipleExemptItems;
private BasketItem singleItem;
private BasketItem multipleImportedItems;
private ShoppingBasket basket1;
@Before
public void setup() {
this.basket = new ShoppingBasket();
Product product1 = new Product();
product1.setName("Ecuatorian Chocolate Bar");
product1.setPrice(new BigDecimal(4.99));
product1.setExempt(true);
product1.setImported(true);
this.singleImportedExemptItem = new BasketItem();
this.singleImportedExemptItem.setProduct(product1);
this.singleImportedExemptItem.setQuantity(1);
Product product2 = new Product();
product2.setName("Ghirardelli Chocolate Bar");
product2.setPrice(new BigDecimal(8.99));
product2.setExempt(true);
this.multipleExemptItems = new BasketItem();
this.multipleExemptItems.setProduct(product2);
this.multipleExemptItems.setQuantity(4);
Product product3 = new Product();
product3.setName("Cuphead for Xbox One");
product3.setPrice(new BigDecimal(29.99));
this.singleItem = new BasketItem();
this.singleItem.setProduct(product3);
this.singleItem.setQuantity(1);
Product product4 = new Product();
product4.setName("Tequila Shot glasses");
product4.setPrice(new BigDecimal(1));
product4.setImported(true);
this.multipleImportedItems = new BasketItem();
this.multipleImportedItems.setProduct(product4);
this.multipleImportedItems.setQuantity(20);
}
@Test
public void testGetTotalSingleItem() {
this.basket.addItem(this.singleItem);
Receipt receipt = new Receipt(this.basket);
assertEquals(receipt.getBasketItems().size(), 1);
assertEquals(receipt.getTotal().toString(), "33");
}
@Test
public void testGetTotals0QuantityItem() {
this.singleItem.setQuantity(0);
this.basket.addItem(this.singleItem);
Receipt receipt = new Receipt(this.basket);
assertEquals(receipt.getTotal().toString(), "0");
assertEquals(receipt.getTotalTax().toString(), "0");
}
@Test
public void testGetTotalsExemptItems() {
this.basket.addItem(this.multipleExemptItems);
Receipt receipt = new Receipt(this.basket);
assertEquals(receipt.getTotal().toString(), "36");
assertEquals(receipt.getTotalTax().toString(), "0");
}
@Test
public void testGetTotalMultipleImportedItems() {
this.basket.addItem(this.multipleImportedItems);
Receipt receipt = new Receipt(this.basket);
assertEquals(receipt.getTotal().toString(), "23");
assertEquals(receipt.getTotalTax().toString(), "0");
}
@Test
public void testBasket1() {
Product book = new Product();
book.setName("book");
book.setPrice(new BigDecimal(12.49));
book.setExempt(true);
Product musicCD = new Product();
musicCD.setName("book");
musicCD.setPrice(new BigDecimal(14.99));
Product chocolateBar = new Product();
chocolateBar.setName("chocolate bar");
chocolateBar.setPrice(new BigDecimal(0.85));
BasketItem bookItem = new BasketItem();
bookItem.setProduct(book);
bookItem.setQuantity(1);
BasketItem musicCDtem = new BasketItem();
musicCDtem.setProduct(musicCD);
musicCDtem.setQuantity(1);
BasketItem chocolateBarItem = new BasketItem();
chocolateBarItem.setProduct(chocolateBar);
chocolateBarItem.setQuantity(1);
this.basket1 = new ShoppingBasket();
this.basket1.addItem(bookItem);
this.basket1.addItem(musicCDtem);
this.basket1.addItem(chocolateBarItem);
Receipt receipt = new Receipt(this.basket1);
// WHY IS THIS NOT WORKING?
//assertEquals("29.83", receipt.getTotal().toString());
//assertEquals("1.50", receipt.getTotalTax().toString());
}
}<file_sep>package adolfov.salestax.model;
import java.util.ArrayList;
import java.util.List;
public class ShoppingBasket {
private List<BasketItem> items;
public ShoppingBasket() {
this.items = new ArrayList<BasketItem>();
}
public void addItem(BasketItem item) {
this.items.add(item);
}
public List<BasketItem> getItems() {
return this.items;
}
}
<file_sep>package adolfov.salestax.model;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.math.BigDecimal;
@JsonPropertyOrder({"name","priceWithTax"})
public class Product {
public static final float BASE_SALES_TAX = .1f;
public static final float IMPORTED_TAX = .05f;
private String name;
private BigDecimal price;
private boolean exempt;
private boolean imported;
public Product() {
}
public float getTax() {
float tax = 0f;
if (!this.exempt) {
tax += Product.BASE_SALES_TAX;
}
if (this.imported) {
tax += Product.IMPORTED_TAX;
}
return tax;
}
public BigDecimal getPriceWithTax() {
return this.getPrice().add(this.getCalculatedTax()).setScale(2, BigDecimal.ROUND_HALF_UP);
}
public BigDecimal getCalculatedTax() {
return this.round(this.getPrice().multiply(new BigDecimal(this.getTax()))).setScale(2, BigDecimal.ROUND_HALF_UP);
}
private BigDecimal round(BigDecimal price) {
return new BigDecimal(Math.round(price.doubleValue() * 20) / 20.0);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public boolean isExempt() {
return exempt;
}
public void setExempt(boolean exempt) {
this.exempt = exempt;
}
public boolean isImported() {
return imported;
}
public void setImported(boolean imported) {
this.imported = imported;
}
}
|
f4346ebe80f43baa10b3294be00a0029331c4da9
|
[
"Markdown",
"Java"
] | 4 |
Markdown
|
adolfov/salestax
|
48898a7961d5842dd5384303b2f519cdb87c7454
|
3b8d58b1508869c0fa92674c529645e2c11a7cd9
|
refs/heads/master
|
<file_sep>//
// SentMemesCollectionViewController.swift
// MemeMe
//
// Created by <NAME> on 10/29/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class SentMemesCollectionViewController: UICollectionViewController {
var memes:[Meme]!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
memes = appDelegate.memes
collectionView?.reloadData()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return memes.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SentMemeCollectionViewCell", for: indexPath) as! SentMemeCollectionViewCell
let me = memes[indexPath.row]
cell.cellPhoto.image = me.memedImage
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath:IndexPath) {
let detailController = storyboard!.instantiateViewController(withIdentifier: "ViewViewController") as! ViewViewController
let me = memes[indexPath.row]
detailController.detail = me.memedImage
navigationController!.pushViewController(detailController, animated: true)
}
@IBAction func memAPhoto(_ sender: Any) {
let storyboard = UIStoryboard (name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "MemeViewController")as! MemeViewController
present(controller, animated: true, completion: nil)
}
}
<file_sep>//
// SentMemesTableViewController.swift
// MemeMe
//
// Created by <NAME> on 10/29/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class SentMemesTableViewController: UITableViewController {
var memes:[Meme]!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
memes = appDelegate.memes
if memes.isEmpty{
let storyboard = UIStoryboard (name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "MemeViewController")as! MemeViewController
present(controller, animated: true, completion: nil)
}else{
tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return memes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let me = memes[indexPath.row]
cell.imageView?.image = me.memedImage
cell.textLabel?.text = "\(me.topText) ...\(me.bottomText)"
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detailController = storyboard!.instantiateViewController(withIdentifier: "ViewViewController") as! ViewViewController
let me = memes[indexPath.row]
detailController.detail = me.memedImage
navigationController!.pushViewController(detailController, animated: true)
}
@IBAction func MemeMaker(_ sender: Any) {
let storyboard = UIStoryboard (name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "MemeViewController")as! MemeViewController
present(controller, animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
memes.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath as IndexPath], with: .automatic)
tableView.endUpdates()
tableView.reloadData()
}
}
}
<file_sep>//
// SentMemeCollectionViewCell.swift
// MemeMe
//
// Created by <NAME> on 10/30/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class SentMemeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var cellPhoto: UIImageView!
}
<file_sep># MemeMe
![alt text][ScreenShot]
[ScreenShot]: https://github.com/1ryberr/MemeMe/blob/master/IMG_0009.JPG
# What the application does.
> When the application launches it opens with a blank black background and two text fields. One text field is labeled top and it is at the top center. The other is labeled bottom and is on the bottom center. The toolbar has two buttons. One button is for going to the camera to take a photo and the other is for the photo library. After taking or choosing a photo of your liking, you may begin to make the meme. By tapping on the text field temporarily labeled top you are able to put any text onto the photo that you desire. You are able to do the same with the bottom text field. Once you’re done you are able to save it to your photo library. It also displays your photos on a table and collection view.
# How to install the application.
- OSX and Xcode
- clone the repository and set up a similator or sideload app on to a device
<file_sep>//
// MemeViewController.swift
// MemeMe
//
// Created by <NAME> on 10/27/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class MemeViewController: UIViewController {
@IBOutlet weak var cancelButton: UIBarButtonItem!
@IBOutlet weak var navBar1: UINavigationBar!
@IBOutlet weak var toBar: UIToolbar!
@IBOutlet weak var navBar: UINavigationItem!
@IBOutlet weak var shareButton: UIBarButtonItem!
@IBOutlet weak var topText: UITextField!
@IBOutlet weak var bottomText: UITextField!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var toolbar: UIToolbar!
@IBOutlet weak var cameraButton: UIBarButtonItem!
var keyboardOnScreen = false
var memes:[Meme]!
override func viewDidLoad() {
super.viewDidLoad()
textFieldFunction(textField: topText,withText: "TOP")
textFieldFunction(textField: bottomText,withText: "BOTTOM")
shareButton.isEnabled = false
}
override func viewWillAppear(_ animated: Bool) {
keyBoardHideandShow()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
memes = appDelegate.memes
if memes.isEmpty{
cancelButton.isEnabled = false
}else{
cancelButton.isEnabled = true
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromAllNotifications()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !UIImagePickerController.isSourceTypeAvailable(.camera) && cameraButton.isEnabled{
cameraButton.isEnabled = false
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func save() {
let meme = Meme(topText: topText.text!, bottomText: bottomText.text!, originalImage: imageView.image!, memedImage: generateMemedImage())
let object = UIApplication.shared.delegate
let appDelegate = object as! AppDelegate
appDelegate.memes.append(meme)
}
func generateMemedImage() -> UIImage {
UIGraphicsBeginImageContext(self.view.frame.size)
view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return memedImage
}
func alertDialog(title: String, message: String){
let controller = UIAlertController(title:title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "ok", style: UIAlertActionStyle.default) { action in self.dismiss(animated: true, completion: nil)
}
controller.addAction(okAction)
self.present(controller, animated: true, completion: nil)
}
@IBAction func sharePhoto(_ sender: UIBarButtonItem) {
self.toBar.isHidden = true
self.navBar1.isHidden = true
let image = generateMemedImage()
let controller = UIActivityViewController(activityItems: [image], applicationActivities: nil)
controller.completionWithItemsHandler = {(activity,success,items,error) in
if(success && error == nil){
self.dismiss(animated: true, completion: nil)
self.save()
self.navBar1.isHidden = false
self.toBar.isHidden = false
}else if (error != nil){
print("error")
self.alertDialog(title: "Error", message: "please try again")
}
}
present(controller, animated: true, completion: nil)
}
@IBAction func cancelButton(_ sender: Any) {
dismiss(animated: true, completion: {})
}
@IBAction func photoButton(_ sender: UIBarButtonItem) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
switch sender.tag {
case 0:
pickerController.sourceType = .camera
case 1:
pickerController.sourceType = .photoLibrary
default:
alertDialog(title: "Error", message: "please try again")
}
present(pickerController, animated: true, completion: nil)
}
}
extension MemeViewController: UITextFieldDelegate{
func textFieldFunction(textField: UITextField, withText: String){
textField.delegate = self
textField.text = withText
let memeTextAttributes:[String:Any] = [
NSAttributedStringKey.strokeColor.rawValue: UIColor.black,
NSAttributedStringKey.foregroundColor.rawValue: UIColor.white,
NSAttributedStringKey.font.rawValue: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSAttributedStringKey.strokeWidth.rawValue: -3.0]
textField.defaultTextAttributes = memeTextAttributes
textField.textAlignment = .center
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if (textField.isFirstResponder){
if bottomText.isEditing{
bottomText.text = ""
}
else if (topText.isFirstResponder) {
topText.text = ""
}
}
}
func keyBoardHideandShow(){
subscribeToNotification(.UIKeyboardWillShow, selector: #selector(keyboardWillShow))
subscribeToNotification(.UIKeyboardWillHide, selector: #selector(keyboardWillHide))
subscribeToNotification(.UIKeyboardDidShow, selector: #selector(keyboardDidShow))
subscribeToNotification(.UIKeyboardDidHide, selector: #selector(keyboardDidHide))
self.view.sendSubview(toBack: imageView)
}
@objc func keyboardWillShow(_ notification: Notification) {
if !keyboardOnScreen && bottomText.isFirstResponder {
view.frame.origin.y -= keyboardHeight(notification)
}
}
@objc func keyboardWillHide(_ notification: Notification) {
if keyboardOnScreen && bottomText.isFirstResponder{
view.frame.origin.y += keyboardHeight(notification)
}
}
@objc func keyboardDidShow(_ notification: Notification) {
keyboardOnScreen = true
}
@objc func keyboardDidHide(_ notification: Notification) {
keyboardOnScreen = false
}
func keyboardHeight(_ notification: Notification) -> CGFloat {
let userInfo = (notification as NSNotification).userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
}
struct Meme {
let topText: String
let bottomText: String
let originalImage: UIImage!
let memedImage: UIImage!
}
private extension MemeViewController {
func subscribeToNotification(_ notification: NSNotification.Name, selector: Selector) {
NotificationCenter.default.addObserver(self, selector: selector, name: notification, object: nil)
}
func unsubscribeFromAllNotifications() {
NotificationCenter.default.removeObserver(self)
}
}
extension MemeViewController: UINavigationControllerDelegate,UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.image = image
imageView.contentMode = .scaleAspectFit
dismiss(animated: true, completion: nil)
shareButton.isEnabled = true
}
}
}
<file_sep>//
// ViewViewController.swift
// MemeMe
//
// Created by <NAME> on 10/30/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class ViewViewController: UIViewController {
var detail : UIImage!
@IBOutlet weak var detailImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
detailImage.image = detail
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
2edc99d10a3d60da65e609c499d8643742689159
|
[
"Swift",
"Markdown"
] | 6 |
Swift
|
1ryberr/MemeMe
|
bba529957592e8636a9a60285b1c95efe7e78f34
|
6fbc038883b076ec1a186274e0973d469e6ae4d3
|
refs/heads/master
|
<repo_name>AMARJITVS/Flappy-Dragon<file_sep>/Assets/scripts/ScoreScript.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class ScoreScript : MonoBehaviour {
public Text myScoreGUI;
public Text myScore;
public static bool a=true;
void Start()
{
myScoreGUI = GameObject.Find("Text1").GetComponent<Text>();
myScore = GameObject.Find("Scores").GetComponent<Text>();
if (myScoreGUI.text=="")
myScoreGUI.text = "0";
myScore.text = myScoreGUI.text;
myScoreGUI.text = "0";
a = false;
myScoreGUI.enabled = false;
}
}
<file_sep>/Assets/scripts/StartScript.cs
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class StartScript : MonoBehaviour {
public Text myScore;
public void NewStartGame(string start)
{
SceneManager.LoadScene(start);
}
public void ExitGame()
{
Application.Quit();
}
}
<file_sep>/Assets/scripts/GameManagerScript.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameManagerScript : MonoBehaviour {
public int myScore;
public static Text myScoreGUI;
public GameObject a;
public Transform obstacle, obstacle1;
// Use this for initialization
void Start() {
if(ScoreScript.a==true)
{
DontDestroyOnLoad(a);
myScoreGUI = GameObject.Find("Text1").GetComponent<Text>();
}
myScore = 0;
myScoreGUI.enabled = true;
InvokeRepeating("ObstacleSpawner", .5f, 1.8f);
}
public void GmAddScore()
{
myScore++;
myScoreGUI.text = myScore.ToString();
}
void ObstacleSpawner()
{
int rand = Random.Range(0, 2);
float Obstacle1MinY = 1f,
Obstacle1MaxY= 6f,
ObstacleMinY = -6f,
ObstacleMaxY = -1f;
switch(rand)
{
case 0:
Instantiate(obstacle, new Vector2(9f, Random.Range(ObstacleMinY, ObstacleMaxY)), Quaternion.identity);
break;
case 1:
Instantiate(obstacle1, new Vector2(9f, Random.Range(Obstacle1MinY, Obstacle1MaxY)), Quaternion.identity);
break;
}
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/Assets/scripts/DragonScript.cs
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class DragonScript : MonoBehaviour
{
private AudioSource audioSource;
private Rigidbody2D myRigidBody;
private Animator myAnimator;
private float jumpforce;
public bool isAlive;
public int a;
// Use this for initialization
void Start()
{
isAlive = true;
myRigidBody = gameObject.GetComponent<Rigidbody2D>();
myAnimator = gameObject.GetComponent<Animator>();
jumpforce = 10f;
myRigidBody.gravityScale = 0f;
audioSource = gameObject.GetComponent<AudioSource>();
audioSource.Play();
}
// Update is called once per frame
void Update()
{
if (isAlive)
{
if (Input.GetMouseButton(0))
{
Flap();
}
CheckIfDragonVisibleOnScreen();
}
}
void Flap()
{
myRigidBody.gravityScale = 5f;
myRigidBody.velocity = new Vector2(0, jumpforce);
myAnimator.SetTrigger("Flap");
}
void OnCollisionEnter2D(Collision2D target)
{
if(target.gameObject.tag=="Obstacle")
{
isAlive = false;
audioSource.Stop();
SceneManager.LoadScene("ExitScene");
}
}
void CheckIfDragonVisibleOnScreen()
{
if(Mathf.Abs(gameObject.transform.position.y)> 4.84f)
{
isAlive = false;
}
if (Mathf.Abs(gameObject.transform.position.y)<-4.6f)
{
isAlive = false;
}
if (isAlive == false)
{
SceneManager.LoadScene("ExitScene");
audioSource.Stop();
}
}
}
|
e32f30957d9ceb0f4bcffcd75037af2b6aae2171
|
[
"C#"
] | 4 |
C#
|
AMARJITVS/Flappy-Dragon
|
c29655a03b50080f9cab4859b12f57a6de3b25c0
|
862c0055c8b6ac76e0320079d43080c36b6a5039
|
refs/heads/master
|
<file_sep>package com.armstyle.customchatbot.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.armstyle.customchatbot.R
import com.armstyle.customchatbot.TypePosittion
import com.armstyle.customchatbot.TypeUsers
import com.armstyle.customchatbot.vo.ChatMessage
import kotlinx.android.synthetic.main.item_bot_chat.view.*
import kotlinx.android.synthetic.main.item_user_chat.view.*
class MyAdapter (val context: Context): RecyclerView.Adapter<MyAdapter.MessageViewHolder>() {
private val TYPE_BOT = 1
private val TYPE_USER = 2
private val messages: ArrayList<ChatMessage> = ArrayList()
fun addMessage(message: ChatMessage, pos: String){
if (pos == TypePosittion.TOP.type){
messages.add(0, message)
}else{
messages.add(message)
}
}
override fun getItemViewType(position: Int): Int {
return if (messages[position].user == TypeUsers.BOT.type) {
TYPE_BOT
} else {
TYPE_USER
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder {
return when (viewType) {
TYPE_BOT-> {
BotMessageViewHolder(LayoutInflater.from(context).inflate(R.layout.item_bot_chat, parent, false))
}else -> {
UserMessageViewHolder(LayoutInflater.from(context).inflate(R.layout.item_user_chat, parent, false))
}
}
}
override fun getItemCount(): Int {
return messages.size
}
override fun onBindViewHolder(holder: MessageViewHolder, position: Int) {
val message = messages[position]
holder?.bind(message)
}
inner class BotMessageViewHolder (view: View) : MessageViewHolder(view) {
private var messageText: TextView = view.botText
override fun bind(message: ChatMessage) {
messageText.text = message.chat
}
}
inner class UserMessageViewHolder (view: View) : MessageViewHolder(view) {
private var messageText: TextView = view.userText
override fun bind(message: ChatMessage) {
messageText.text = message.chat
}
}
open class MessageViewHolder (view: View) : RecyclerView.ViewHolder(view) {
open fun bind(message:ChatMessage) {}
}
}<file_sep>package com.armstyle.customchatbot.vo
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "chat_history_table")
data class ChatMessage (
@PrimaryKey(autoGenerate = true)
var id: Long = 0,
@ColumnInfo(name="chat")
var chat: String? = "",
@ColumnInfo(name="user")
var user: String? = ""
)<file_sep>package com.armstyle.customchatbot
import ai.api.AIConfiguration
import ai.api.AIDataService
import ai.api.AIListener
import ai.api.android.AIService
import ai.api.model.AIError
import ai.api.model.AIRequest
import ai.api.model.AIResponse
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.AsyncTask
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.armstyle.customchatbot.adapter.MyAdapter
import com.armstyle.customchatbot.db.ChatDatabase
import com.armstyle.customchatbot.vo.ChatMessage
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() , AIListener {
// pref
lateinit var sharedpreferences: SharedPreferences
private lateinit var editor: SharedPreferences.Editor
// api ai
lateinit var aiService: AIService
// firebase database
private val mRootRef = FirebaseDatabase.getInstance().reference
private val mMessagesRef = mRootRef.child(FIREBASE_DB_CHILD)
private lateinit var adapter: MyAdapter
val menuChatHistory: MutableList<ChatMessage> = mutableListOf()
// scroll point
var pastVisiblesItems: Int = 0
var visibleItemCount: Int = 0
var totalItemCount: Int = 0
@SuppressLint("CommitPrefEdits")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val appDatabase = ChatDatabase.getInstance(this)
sharedpreferences = getSharedPreferences(CHAT_PREF, Context.MODE_PRIVATE)
editor = sharedpreferences.edit()
// initOldChat() // load chat history from firebase
initOldChatRoom(appDatabase) // load chat history from rom database
initScrollListener()
val config = ai.api.android.AIConfiguration(
CLIENT_ACCESS_TOKEN,
AIConfiguration.SupportedLanguages.English,
ai.api.android.AIConfiguration.RecognitionEngine.System
)
voiceButton.setOnClickListener{
aiService = AIService.getService(this, config)
aiService.setListener(this)
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
val permissions = arrayOf(android.Manifest.permission.RECORD_AUDIO, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE)
ActivityCompat.requestPermissions(this, permissions,0)
} else {
aiService.startListening()
}
}
rvChat.layoutManager = LinearLayoutManager(this)
adapter = MyAdapter(this)
rvChat.adapter = adapter
val aiDataService = AIDataService(config)
val aiRequest = AIRequest()
btnSend.setOnClickListener {
val message = edChat.text.toString()
if (message != "") {
val chatMessage = ChatMessage(0, message, TypeUsers.USER.type)
addMessageToChat(chatMessage)// เพิ่ม message ลง UI
aiRequest.setQuery(message)
// mMessagesRef.push().setValue(chatMessage) // เพิ่มลง database
addChatToRoom(appDatabase, chatMessage) // เพิ่มลง database room
AsyncTask.execute(kotlinx.coroutines.Runnable {
val aiResponse :AIResponse = aiDataService.request(aiRequest)
if (aiResponse != null) {
val chatMessage = ChatMessage(0,aiResponse.result.fulfillment.speech, TypeUsers.BOT.type)
addMessageToChat(chatMessage)// เพิ่ม message ลง UI
// mMessagesRef.push().setValue(chatMessage) // เพิ่มลง database
addChatToRoom(appDatabase, chatMessage) // เพิ่มลง database room
}
})
} else {
Toast.makeText(applicationContext, "Enter message first", Toast.LENGTH_SHORT).show()
}
}
}
///////////// ใช้ database Firebase realtime database
private fun initOldChat(){
val chatListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
menuChatHistory.clear()
dataSnapshot.children.mapNotNullTo(menuChatHistory) {
it.getValue(ChatMessage::class.java) }
menuChatHistory.forEach {
addMessageToChat(it) }
}
override fun onCancelled(databaseError: DatabaseError) {
println("loadPost:onCancelled ${databaseError.toException()}")
}
}
mMessagesRef.limitToLast(LIMIT_LOAD).addListenerForSingleValueEvent(chatListener)
}
/////////// ใช้ database room
private fun initOldChatRoom(appDatabase: ChatDatabase) {
AsyncTask.execute(kotlinx.coroutines.Runnable {
val data = appDatabase.chatDatabaseDao.getLastLoad10(LIMIT_LOAD)
data.asReversed().forEach {
addMessageToChat(ChatMessage(0,it.chat, it.user))
}
if (data.isNotEmpty()){
editor.putLong(LAST_LOAD_ID, data[data.size-1].id)
editor.apply()
}
})
}
// เพิ่มลง database room
private fun addChatToRoom(appDatabase: ChatDatabase, chatMessage: ChatMessage) {
val chatmessage2 = ChatMessage()
chatmessage2.chat = chatMessage.chat
chatmessage2.user = chatMessage.user
AsyncTask.execute(kotlinx.coroutines.Runnable { appDatabase.chatDatabaseDao.insert(chatmessage2) })
}
private fun initScrollListener(){
rvChat.addOnScrollListener(object :RecyclerView.OnScrollListener(){
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val linearLayoutManager = recyclerView.layoutManager as LinearLayoutManager
visibleItemCount = linearLayoutManager.childCount
totalItemCount = linearLayoutManager.itemCount
pastVisiblesItems = linearLayoutManager.findFirstVisibleItemPosition()
if(linearLayoutManager.findViewByPosition(pastVisiblesItems)!!.top==0 && pastVisiblesItems==0){
loadMoreOldChatRoom() // load more chat history from database
}
}
})
}
private fun loadMoreOldChatRoom(){ // load more จาก room
val appDatabase = ChatDatabase.getInstance(this)
sharedpreferences = getSharedPreferences(CHAT_PREF, Context.MODE_PRIVATE)
val editor = sharedpreferences.edit()
AsyncTask.execute(kotlinx.coroutines.Runnable {
val data = appDatabase.chatDatabaseDao.getAllChatLoadMore(sharedpreferences.getLong(LAST_LOAD_ID, 0), LIMIT_LOAD)
data.forEach {
addMessageHistoryToChat(ChatMessage(0,it.chat, it.user))
}
if (data.isNotEmpty()){
editor.putLong(LAST_LOAD_ID, data[data.size-1].id)
editor.apply()
}
})
}
private fun addMessageToChat(text: ChatMessage){
runOnUiThread {
adapter.addMessage(text, TypePosittion.BOTTOM.type)
// scroll the RecyclerView to the last added element
rvChat.scrollToPosition(adapter.itemCount - 1)
edChat.setText("")
}
}
private fun addMessageHistoryToChat(text: ChatMessage){
runOnUiThread {
adapter.addMessage(text, TypePosittion.TOP.type)
adapter.notifyItemInserted(0)
}
}
override fun onResult(result: AIResponse?) {
val appDatabase = ChatDatabase.getInstance(this)
// Show results in TextView.
if (result != null) {
// user text
val chatMessageUser = ChatMessage(0,result.result.resolvedQuery, TypeUsers.USER.type)
addMessageToChat(chatMessageUser) // เพิ่ม message ลง UI
// mMessagesRef.push().setValue(chatMessageUser) // เพิ่มลง database
addChatToRoom(appDatabase, chatMessageUser) // เพิ่มลง database room
// bot text
val chatMessageBot = ChatMessage(0,result.result.fulfillment.speech, TypeUsers.BOT.type)
addMessageToChat(chatMessageBot) // เพิ่ม message ลง UI
// mMessagesRef.push().setValue(chatMessageBot) // เพิ่มลง database
addChatToRoom(appDatabase, chatMessageBot) // เพิ่มลง database room
}
}
override fun onListeningStarted() {}
override fun onAudioLevel(level: Float) {}
override fun onError(error: AIError?) {
Log.d(TAG_CHATBOT, "query error_result : ${error.toString()}")
}
override fun onListeningCanceled() {}
override fun onListeningFinished() {}
companion object {
// database
const val LAST_LOAD_ID = "LAST_LOAD_ID"
const val CHAT_PREF = "CHAT_PREF"
const val LIMIT_LOAD = 10
// chatbot
const val CLIENT_ACCESS_TOKEN = "Your client access token"
// firebase
const val FIREBASE_DB_CHILD = "messages"
// TAG
const val TAG_CHATBOT = "TAG_chat"
}
}
<file_sep>rootProject.name='Custom chatbot'
include ':app'
<file_sep>package com.armstyle.customchatbot
enum class TypePosittion(val type:String) {
TOP(type = "top"),
BOTTOM(type = "bottom")
}<file_sep>package com.armstyle.customchatbot
enum class TypeUsers(val type:String) {
USER(type = "user"),
BOT(type = "bot")
}<file_sep>package com.armstyle.customchatbot.db
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.armstyle.customchatbot.vo.ChatMessage
@Dao
interface ChatDatabaseDao {
@Insert
fun insert(night: ChatMessage)
@Update
fun update(night: ChatMessage)
@Query("SELECT * from chat_history_table WHERE id = :key ")
fun get(key:Long):ChatMessage?
@Query("DELETE FROM chat_history_table")
fun clear()
@Query("SELECT * FROM chat_history_table ORDER BY id ASC")
fun getAllChat(): LiveData<List<ChatMessage>>
@Query("SELECT * FROM chat_history_table where id >= :key ORDER BY id ASC")
fun getAllChat10(key:Long): LiveData<List<ChatMessage>>
@Query("SELECT * FROM chat_history_table where id < :key ORDER BY id DESC limit :limit")
fun getAllChatLoadMore(key:Long, limit:Int): List<ChatMessage>
@Query("SELECT * from chat_history_table order by id desc limit :limit")
fun getLastLoadId(limit:Int): LiveData<List<ChatMessage>>
@Query("SELECT * from chat_history_table order by id desc limit :limit")
fun getLastLoad10(limit:Int): List<ChatMessage>
}
|
69cbe541302002d55f89f7ea56e7cd3a5098a929
|
[
"Kotlin",
"Gradle"
] | 7 |
Kotlin
|
armjingjai/android-simple-chatbot
|
1dad48a982ab217fc001f7253e7c739367406594
|
36911a9d3cad045744784f537e63480e422c79bc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.