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>const fs = require('fs')
const obj2gltf = require('obj2gltf');
var ifcConvert = require('ifc-convert')
module.exports = {
fileExists: (filePath) => {
return fs.existsSync(filePath)
},
convert: (filePath) => {
//console.log(filePath)
ifcConvert(filePath, 'dest.obj')
.then(() => {
obj2gltf('./dest.obj')
.then(function(gltf) {
const data = Buffer.from(JSON.stringify(gltf));
fs.writeFileSync('./model.gltf', data);
})
}).catch((err) => {
console.log('Please install IfcConvert! \n')
console.log(err)
})
}
}
|
f6c7725ecfe585997adc7e07619adea3f67c1039
|
[
"JavaScript"
] | 1 |
JavaScript
|
PhilippRitzberger/ifc-to-gltf
|
d58afec7750afad1c52d5bdc9ae0c010f6c4923a
|
15c13f2dada5ac69b7394ff50e1575fc600b2418
|
refs/heads/master
|
<repo_name>jakubkaczmarek/drawMe<file_sep>/webapi/drawMe.WebApi/Repositories/Repository.cs
using drawMe.WebApi.Contexts;
using drawMe.WebApi.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
namespace drawMe.WebApi.Repositories
{
public class Repository<T> : IRepository<T> where T : class, IEntity
{
private readonly IEntityQueryableProvider _queryableProvider;
private readonly AppDbContext _dbContext;
private readonly DbSet<T> _dbSet;
public Repository(AppDbContext dbContext, IEntitiesQueryableFactory queryableFactory)
{
_dbContext = dbContext;
_dbSet = dbContext.GetDbSet<T>();
_queryableProvider = queryableFactory.GetQueryableProvider<T>();
}
public Guid Create(T entity)
{
var result = _dbSet.Add(entity);
_dbContext.SaveChanges();
return result.Entity.Id;
}
public bool Delete(T entity)
{
_dbSet.Remove(entity);
_dbContext.SaveChanges();
return true;
}
public T Get(Guid id)
{
return _queryableProvider.GetQueryable(_dbSet).FirstOrDefault(e => e.Id == id);
}
public IQueryable<T> Get()
{
return _queryableProvider.GetQueryable(_dbSet);
}
public bool Update(T entity)
{
_dbSet.Update(entity);
_dbContext.SaveChanges();
return true;
}
}
}<file_sep>/webapi/drawMe.Services/DaysTillChristmasService.cs
using drawMe.Services.Interfaces;
using System;
namespace drawMe.Services
{
public class DaysTillChristmasService : IDaysTillChristmasService
{
public int GetDaysTillChristmas()
{
var currentDate = DateTime.Now.Date;
var christmasDate = new DateTime(currentDate.Year, 12, 24);
if (christmasDate < currentDate)
{
return 0;
}
return (int)(christmasDate - currentDate).TotalDays;
}
}
}<file_sep>/webapi/drawMe.WebApi/Consts.cs
namespace drawMe.WebApi
{
public static class Consts
{
public static class Sex
{
public const string Male = "male";
public const string Female = "female";
}
}
}<file_sep>/webapp/src/app/header/header/header.component.ts
import { AuthorizationService } from '../../services/authorization.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
showSideMenu = false;
showLogoutButton = false;
constructor(private authorizationService: AuthorizationService) {
this.authorizationService.authorizedChanged.subscribe((authorized) => {
this.setAuthorizedLayoutVisibility();
});
}
ngOnInit() {
this.setAuthorizedLayoutVisibility();
}
logout() {
this.authorizationService.logout();
}
private setAuthorizedLayoutVisibility() {
this.showSideMenu = this.authorizationService.authorized;
this.showLogoutButton = this.authorizationService.authorized;
}
}
<file_sep>/webapp/src/app/services/wishlist-item.service.ts
import { Observable } from 'rxjs/Rx';
import { WishlistItemModel } from '../models/wishlistItemModel';
import { AuthorizationService } from './authorization.service';
import { environment } from '../../environments/environment';
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class WishlistItemService {
constructor(private http: Http, private authenticationService: AuthorizationService) {
}
getCurrentUserWishlistItems() {
const userId = this.authenticationService.userId;
return this.getWishlistItems(userId);
}
getWishlistItems(userId): Observable<WishlistItemModel[]> {
const url = environment.wishlistItemEndpoint + '?UserId=' + userId;
const options = this.authenticationService.getAuthorizationOptions();
return this.http.get(url, options)
.map((response: Response) => {
const wishlistItems = response.json();
return wishlistItems.result.map((wishlistItem) => {
const model = new WishlistItemModel();
model.createdOn = wishlistItem.createdOn ? new Date(wishlistItem.createdOn) : null;
model.description = wishlistItem.description;
model.desireLevel = wishlistItem.desireLevel;
model.id = wishlistItem.id;
model.name = wishlistItem.name;
model.exampleUrl = wishlistItem.exampleUrl;
return model;
});
});
}
addWishlistItem(name: string, itemUrl: string): Observable<boolean> {
const userId = this.authenticationService.userId;
const url = environment.wishlistItemEndpoint;
const data = { name: name, url: itemUrl };
const options = this.authenticationService.getAuthorizationOptions();
return this.http.put(url, data, options)
.map((response: Response) => {
const success = response.json();
return success === true;
});
}
removeWishlistItem(id: string): Observable<boolean> {
const userId = this.authenticationService.userId;
const url = environment.wishlistItemEndpoint + '?id=' + id;
const options = this.authenticationService.getAuthorizationOptions();
return this.http.delete(url, options)
.map((response: Response) => {
const success = response.json();
return success === true;
});
}
}
<file_sep>/webapi/drawMe.WebApi/Services/EmailService.cs
using drawMe.WebApi.Interfaces;
using drawMe.WebApi.Settings;
using Microsoft.Extensions.Options;
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.Threading.Tasks;
namespace drawMe.WebApi.Services
{
public class EmailService : IEmailService
{
private readonly AppSettings appSettings;
public EmailService(IOptions<AppSettings> optionsAccessor)
{
this.appSettings = optionsAccessor.Value;
}
public async Task SendEmail(string recipientEmail, string subject, string htmlContent)
{
var client = new SendGridClient(this.appSettings.SendGridApiKey);
var message = new SendGridMessage();
message.AddTo(recipientEmail);
message.SetFrom(this.appSettings.AdminEmail, $"Świąteczne Losowanie {DateTime.Now.Year}");
message.SetSubject(subject);
message.HtmlContent = htmlContent;
await client.SendEmailAsync(message);
}
}
}<file_sep>/webapi/drawMe.WebApi/Contexts/UserContext.cs
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Security.Claims;
namespace drawMe.WebApi.Contexts
{
public class UserContext : IUserContext
{
private readonly IRepository<ApplicationUser> _userRepository;
public ApplicationUser CurrentUser { get; private set; }
public UserContext(IHttpContextAccessor contextAccessor, IRepository<ApplicationUser> userRepository)
{
_userRepository = userRepository;
var userClaims = contextAccessor.HttpContext.User;
var emailClaim = userClaims.FindFirst(ClaimTypes.Email);
if (emailClaim == null)
{
return;
}
CurrentUser = GetUser(emailClaim.Value);
}
private ApplicationUser GetUser(string userEmail)
{
if (userEmail == null)
{
return null;
}
return _userRepository.Get().FirstOrDefault(u => u.Email == userEmail);
}
}
}<file_sep>/webapi/drawMe.WebApi/Startup.cs
using AutoMapper;
using drawMe.Services;
using drawMe.Services.Interfaces;
using drawMe.WebApi.Contexts;
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using drawMe.WebApi.Profiles;
using drawMe.WebApi.Providers.EntityQueryable;
using drawMe.WebApi.Repositories;
using drawMe.WebApi.Services;
using drawMe.WebApi.Settings;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text;
using System.Threading.Tasks;
namespace drawMe.WebApi
{
public class Startup
{
private bool corsPolicySetup;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
ConfigureCors(services);
services.Configure<JwtSettings>(Configuration.GetSection("JWTSettings"));
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
RegisterModules(services);
InitializeMapperProfiles(services);
SetupIdentity(services);
SetupAuthorization(services);
var serviceProvider = services.BuildServiceProvider();
var seedTask = AppDbContextInitializer.Seed(serviceProvider);
Task.WaitAll(seedTask);
}
private void ConfigureCors(IServiceCollection services)
{
var origin = Configuration.GetSection("CorsSettings").GetValue<string>("Origin");
if (string.IsNullOrEmpty(origin))
{
return;
}
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins(origin)
.AllowAnyMethod()
.AllowAnyHeader();
}));
this.corsPolicySetup = true;
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//if (env.IsDevelopment())
//{
app.UseDeveloperExceptionPage();
//}
if (this.corsPolicySetup)
{
app.UseCors("MyPolicy");
}
app.UseAuthentication();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
private void SetupIdentity(IServiceCollection services)
{
services.AddIdentity<ApplicationUser, Role>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders()
.AddUserStore<UserStore<ApplicationUser, Role, AppDbContext, Guid>>()
.AddRoleStore<RoleStore<Role, AppDbContext, Guid>>();
}
private void SetupAuthorization(IServiceCollection services)
{
var jwtSettings = this.GetJwtSettings(services);
var secretKey = Encoding.ASCII.GetBytes(jwtSettings.SecretKey);
var signingKey = new SymmetricSecurityKey(secretKey);
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = jwtSettings.RequireHttpsMetadata;
options.Configuration = new OpenIdConnectConfiguration();
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = jwtSettings.Issuer,
ValidateAudience = true,
ValidAudience = jwtSettings.Audience
};
});
}
private void RegisterModules(IServiceCollection services)
{
services.AddTransient(typeof(IRepository<>), typeof(Repository<>));
services.AddTransient<IUserService, UserService>();
services.AddTransient<IUserSecretService, UserSecretService>();
services.AddTransient<IEmailService, EmailService>();
services.AddTransient<IEmbeddedResourceService, EmbeddedResourceService>();
services.AddTransient<IDaysTillChristmasService, DaysTillChristmasService>();
services.AddTransient<IEntitiesQueryableFactory, EntitiesQueryableFactory>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IUserContext, UserContext>();
services.AddScoped<IDrawNumberService, DrawNumberService>();
services.AddScoped<IDrawService, DrawService>();
}
private void InitializeMapperProfiles(IServiceCollection services)
{
services.AddAutoMapper(cfg =>
{
cfg.AddProfile(new UserProfiles());
cfg.AddProfile(new WishlistItemProfiles());
});
}
private JwtSettings GetJwtSettings(IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();
var optionsAccessor = serviceProvider.GetService<IOptions<JwtSettings>>();
return optionsAccessor.Value;
}
}
}<file_sep>/webapi/drawMe.WebApi/Interfaces/IEmbeddedResourceService.cs
namespace drawMe.WebApi.Interfaces
{
public interface IEmbeddedResourceService
{
string GetResourceContent(string filename);
}
}<file_sep>/webapi/drawMe.WebApi/Models/InviteEmailModel.cs
namespace drawMe.WebApi.Models
{
public class InviteEmailModel
{
public string FromEmail { get; set; }
public string ToEmail { get; set; }
public string UserLogin { get; set; }
public string UserSecret { get; set; }
}
}
<file_sep>/webapp/src/app/content/content/authorized-content/authorized-content.component.ts
import { UsersService } from '../../../services/users.service';
import { UserModel } from '../../../models/userModel';
import { DrawnUserModel } from '../../../models/drawnUserModel';
import { WishlistItemModel } from '../../../models/wishlistItemModel';
import { WishlistItemService } from '../../../services/wishlist-item.service';
import { DrawnUserService } from '../../../services/drawn-user.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-authorized-content',
templateUrl: './authorized-content.component.html',
styleUrls: ['./authorized-content.component.css']
})
export class AuthorizedContentComponent implements OnInit {
drawnUser: DrawnUserModel;
allUsers = UserModel[0];
currentUser = { wishlistItems: WishlistItemModel[0] };
wishlistItemName: string;
wishlistItemUrl: string;
constructor(
private drawnUserService: DrawnUserService,
private wishlistItemService: WishlistItemService,
private usersService: UsersService) {
this.drawnUser = new DrawnUserModel();
this.drawnUser.wishlistItems = [];
}
ngOnInit() {
this.drawnUserService.getDrawnUser().subscribe((drawnUser) => {
if (drawnUser) {
this.drawnUser = drawnUser;
this.wishlistItemService.getWishlistItems(drawnUser.id).subscribe((result) => {
this.drawnUser.wishlistItems = result;
});
this.usersService.getUsers().subscribe((result) => {
this.allUsers = result;
});
}
});
this.refreshCurrentUserWishlistItems();
}
refreshCurrentUserWishlistItems() {
this.wishlistItemService.getCurrentUserWishlistItems().subscribe((result) => {
this.currentUser.wishlistItems = result;
});
}
addWishlistItem() {
if (this.wishlistItemName) {
this.wishlistItemService.addWishlistItem(this.wishlistItemName, this.wishlistItemUrl).subscribe((success) => {
if (success) {
this.refreshCurrentUserWishlistItems();
}
this.wishlistItemName = '';
this.wishlistItemUrl = '';
});
}
}
printCode(codeSectionId: string, firstName: string, lastName: string) {
let printContents, popupWin;
const title = firstName + ' ' + lastName + ' - kod prezentu';
printContents = document.getElementById(codeSectionId).innerHTML;
popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Kod prezentu</title>
</head>
<body onload="window.print();window.close()">
<p>` + title + `</p>
` + printContents + `
</body>
</html>`
);
popupWin.document.close();
}
}
<file_sep>/webapi/drawMe.Services.Tests/DrawNumberServiceTests.cs
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace drawMe.Services.Tests
{
public class DrawNumberServiceTests
{
//[Fact]
//public void DrawNumber_MaxNumber1_RedrawRange_100_200_ResultsEvenDistributed()
//{
// RunDistributionEvenTest(1, 100, 200);
//}
//[Fact]
//public void DrawNumber_MaxNumber1_RedrawRange_200_500_ResultsEvenDistributed()
//{
// RunDistributionEvenTest(1, 200, 500);
//}
//[Fact]
//public void DrawNumber_MaxNumber1_RedrawRange_500_1000_ResultsEvenDistributed()
//{
// RunDistributionEvenTest(1, 500, 1000);
//}
[Fact]
public void DrawNumber_MaxNumber0_DefaultRedrawRange_ResultAlways0()
{
var service = new DrawNumberService();
var result = service.DrawNumber(0);
Assert.Equal(0, result);
Assert.Single(service.LastDrawDistribution.Keys);
}
[Fact]
public void DrawNumber_MaxNumber1_DefaultRedrawRange_ResultsEvenDistributed()
{
RunDistributionEvenTest(1);
}
[Fact]
public void DrawNumber_MaxNumber2_DefaultRedrawRange_ResultsEvenDistributed()
{
RunDistributionEvenTest(2);
}
[Fact]
public void DrawNumber_MaxNumber3_DefaultRedrawRange_ResultsEvenDistributed()
{
RunDistributionEvenTest(3);
}
[Fact]
public void DrawNumber_MaxNumber6_DefaultRedrawRange_ResultsEvenDistributed()
{
RunDistributionEvenTest(6);
}
private void RunDistributionEvenTest(int maxNumber, int redrawMin = 0, int redrawMax = 0)
{
var service = new DrawNumberService();
if (redrawMin > 0 && redrawMax > 0)
{
Assert.True(redrawMin < redrawMax);
service.SetRedrawsCountRange(redrawMin, redrawMax);
}
for (var i = 0; i < 100; i++)
{
service.DrawNumber(maxNumber);
Assert.Equal(maxNumber + 1, service.LastDrawDistribution.Count);
Assert.DoesNotContain(service.LastDrawDistribution.Keys, key => key > maxNumber);
AssertIsEvenDistributed(service.LastDrawDistribution);
}
}
private void AssertIsEvenDistributed(Dictionary<int, int> distribution)
{
var percentages = new List<double>();
var redrawsCount = (double)distribution.Values.Sum();
foreach (var key in distribution.Keys)
{
var occurances = (double)distribution[key];
var percentage = occurances / redrawsCount;
percentages.Add(percentage);
}
var min = percentages.Min();
var max = percentages.Max();
Assert.True(max - min < 0.1);
}
}
}<file_sep>/webapi/drawMe.WebApi/Dto/WishlistItem/CreateWishlistItemInput.cs
using System;
namespace drawMe.WebApi.Dto.WishlistItem
{
public class CreateWishlistItemInput
{
public string Name { get; set; }
public string Url { get; set; }
}
}<file_sep>/webapi/drawMe.Services/Models/ParticipantsAssociation.cs
using System.Collections.Generic;
using System.Linq;
namespace drawMe.Services.Models
{
public class ParticipantsAssociation
{
public IList<Participant> AssociatedParticipants { get; private set; }
public ParticipantsAssociation(params Participant[] participants)
{
AssociatedParticipants = new List<Participant>(participants);
}
public bool AssociationExist(Participant participant1, Participant participant2)
{
var participant1Matched = AssociatedParticipants.Any(p => p.ParticipantId == participant1.ParticipantId);
var participant2Matched = AssociatedParticipants.Any(p => p.ParticipantId == participant2.ParticipantId);
return participant1Matched && participant2Matched;
}
}
}<file_sep>/webapi/drawMe.WebApi/Models/EmailContentModel.cs
namespace drawMe.WebApi.Models
{
public class EmailContentModel
{
public string SubjectText { get; set; }
public string SalutationText { get; set; }
public string GreetingsText { get; set; }
public string FooterText { get; set; }
public string HtmlContent { get; set; }
}
}<file_sep>/webapi/drawMe.WebApi/Providers/EntityQueryable/DefaultQueryableProvider.cs
using drawMe.WebApi.Interfaces;
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace drawMe.WebApi.Providers.EntityQueryable
{
public class DefaultQueryableProvider : IEntityQueryableProvider
{
IQueryable<T> IEntityQueryableProvider.GetQueryable<T>(DbSet<T> dbSet)
{
return dbSet.AsQueryable();
}
}
}<file_sep>/webapp/src/app/content/content.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ContentComponent } from './content/content.component';
import { AuthorizedContentComponent } from './content/authorized-content/authorized-content.component';
import { UnauthorizedContentComponent } from './content/unauthorized-content/unauthorized-content.component';
@NgModule({
imports: [
CommonModule
],
declarations: [ContentComponent, AuthorizedContentComponent, UnauthorizedContentComponent]
})
export class ContentModule { }
<file_sep>/webapi/drawMe.WebApi/Providers/EntityQueryable/EntitiesQueryableFactory.cs
using drawMe.WebApi.Interfaces;
namespace drawMe.WebApi.Providers.EntityQueryable
{
public class EntitiesQueryableFactory : IEntitiesQueryableFactory
{
private readonly IEntityQueryableProvider _userQueryableProvider = new UserQueryableProvider();
private readonly IEntityQueryableProvider _wishlistItemQueryableProvider = new WishlistItemQueryableProvider();
private readonly IEntityQueryableProvider _defaultQueryableProvider = new DefaultQueryableProvider();
public IEntityQueryableProvider GetQueryableProvider<T>() where T : class, IEntity
{
var typeName = typeof(T).Name;
switch (typeName)
{
case "ApplicationUser":
return _userQueryableProvider;
case "WishlistItem":
return _wishlistItemQueryableProvider;
default:
return _defaultQueryableProvider;
}
}
}
}<file_sep>/webapi/drawMe.Services.Tests/UserSecretGeneratorTests.cs
using drawMe.Services.Generators;
using System.Collections.Generic;
using Xunit;
namespace drawMe.Services.Tests
{
public class UserSecretGeneratorTests
{
private readonly string[] _assignableSecrets;
public UserSecretGeneratorTests()
{
var assignableSecrets = new List<string>();
for(var i = 0; i < 26; i++)
{
assignableSecrets.Add($"pwd{i}");
}
_assignableSecrets = assignableSecrets.ToArray();
}
[Fact]
public void GetSecret_GenerateTwice_SecretsIdentical()
{
var secret1 = UserSecretGenerator.GetSecret("<EMAIL>", "John", "Snow", _assignableSecrets);
var secret2 = UserSecretGenerator.GetSecret("<EMAIL>", "John", "Snow", _assignableSecrets);
Assert.NotNull(secret1);
Assert.NotNull(secret2);
Assert.Equal(secret1, secret2);
}
[Fact]
public void GetSecret_GenerateForSimilarData_SecretsNotIdentical()
{
var secret1 = UserSecretGenerator.GetSecret("<EMAIL>", "John", "Snow", _assignableSecrets);
var secret2 = UserSecretGenerator.GetSecret("<EMAIL>", "Johan", "Snow", _assignableSecrets);
Assert.NotNull(secret1);
Assert.NotNull(secret2);
Assert.NotEqual(secret1, secret2);
}
}
}<file_sep>/webapi/drawMe.WebApi/Interfaces/IEmailService.cs
using System.Threading.Tasks;
namespace drawMe.WebApi.Interfaces
{
public interface IEmailService
{
Task SendEmail(string recipientEmail, string subject, string content);
}
}
<file_sep>/webapi/drawMe.Services/Interfaces/IDaysTillChristmasService.cs
namespace drawMe.Services.Interfaces
{
public interface IDaysTillChristmasService
{
int GetDaysTillChristmas();
}
}<file_sep>/webapp/src/app/models/authModel.ts
export class AuthModel {
userId: string;
token: string;
expireDate: Date;
isExpired(): boolean {
const nowDate = new Date();
return this.expireDate < nowDate;
}
}
<file_sep>/webapi/drawMe.Services/Extensions/ParticipantExtensions.cs
using drawMe.Services.Models;
using System.Collections.Generic;
using System.Linq;
namespace drawMe.Services.Extensions
{
public static class ParticipantExtensions
{
public static bool CanBeDrawnFor(this Participant candidate, Participant targetParticipant, IList<ParticipantsAssociation> associations = null)
{
if (candidate.Paired || targetParticipant.ParticipantId == candidate.ParticipantId)
{
return false;
}
if (associations != null && associations.Any(assoc => assoc.AssociationExist(candidate, targetParticipant)))
{
return false;
}
return true;
}
}
}<file_sep>/webapi/drawMe.WebApi/Controllers/DrawController.cs
using drawMe.Services.Interfaces;
using drawMe.Services.Models;
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System;
using System.Collections.Generic;
namespace drawMe.WebApi.Controllers
{
[Authorize]
[Route("api/[controller]")]
public class DrawController : Controller
{
private readonly IDrawService _drawService;
private readonly IRepository<ApplicationUser> _usersRepository;
private readonly IRepository<ApplicationUserAssociation> _associationsRepository;
public DrawController(
IDrawService drawService,
IRepository<ApplicationUser> usersRepository,
IRepository<ApplicationUserAssociation> associationsRepository)
{
_drawService = drawService;
_usersRepository = usersRepository;
_associationsRepository = associationsRepository;
}
[HttpPost]
public bool Post()
{
var users = _usersRepository.Get().ToList();
var participants = users
.Select(u => u.MapTo<Participant>())
.ToList();
var associations = GetAssociations(participants);
var result = _drawService.DrawPairs(participants, associations);
if (result)
{
participants.ForEach(participant => ApplyDrawResult(participant));
}
return result;
}
private List<ParticipantsAssociation> GetAssociations(List<Participant> participants)
{
var participantAssociations = new List<ParticipantsAssociation>();
var userAssociations = _associationsRepository.Get().ToList();
foreach(var userAssociation in userAssociations)
{
var participant1 = participants.First(p => p.ParticipantId == userAssociation.User1Id);
var participant2 = participants.First(p => p.ParticipantId == userAssociation.User2Id);
var participantAssociation = new ParticipantsAssociation(participant1, participant2);
participantAssociations.Add(participantAssociation);
}
return participantAssociations;
}
private void ApplyDrawResult(Participant participant)
{
var participantUser = _usersRepository.Get(participant.ParticipantId);
var drawnUser = _usersRepository.Get(participant.DrawnParticipantId);
participantUser.DrawnUser = drawnUser;
_usersRepository.Update(participantUser);
}
}
}<file_sep>/webapp/src/environments/environment.ts
// The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `.angular-cli.json`.
export const environment = {
production: false,
authorizationEndpoint: 'http://gwiazdka.azurewebsites.net/api/auth',
userEndpoint: 'http://gwiazdka.azurewebsites.net/api/user',
drawnUserEndpoint: 'http://gwiazdka.azurewebsites.net/api/drawnuser',
wishlistItemEndpoint: 'http://gwiazdka.azurewebsites.net/api/wishlistitem'
};
<file_sep>/webapi/drawMe.WebApi/Entities/ApplicationUser.cs
using drawMe.WebApi.Interfaces;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
namespace drawMe.WebApi.Entities
{
public class ApplicationUser : IdentityUser<Guid>, IEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Sex { get; set; }
public string Description { get; set; }
public bool IsAdmin { get; set; }
public string PhotoPath { get; set; }
public string SendEmail { get; set; }
public virtual ApplicationUser DrawnUser { get; set; }
public virtual IList<WishlistItem> WishlistItems { get; set; }
public ApplicationUser()
{
WishlistItems = new List<WishlistItem>();
}
}
}<file_sep>/webapi/drawMe.WebApi/Entities/WishlistItem.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace drawMe.WebApi.Entities
{
public class WishlistItem : Entity
{
public virtual ApplicationUser User { get; set; }
public DateTime? CreatedOn { get; set; }
[Required]
public string Name { get; set; }
public string ExampleUrl { get; set; }
public string Description { get; set; }
public WishlistItem()
{
CreatedOn = DateTime.Now;
}
}
}<file_sep>/webapi/drawMe.WebApi/Profiles/WishlistItemProfiles.cs
using AutoMapper;
using drawMe.WebApi.Dto.WishlistItem;
using drawMe.WebApi.Entities;
namespace drawMe.WebApi.Profiles
{
public class WishlistItemProfiles : Profile
{
public WishlistItemProfiles()
{
CreateMap<WishlistItem, WishlistItemDto>();
CreateMap<WishlistItemDto, WishlistItem>();
}
}
}<file_sep>/webapi/drawMe.Services/Interfaces/IDrawNumberService.cs
namespace drawMe.Services.Interfaces
{
public interface IDrawNumberService
{
int DrawNumber(int maxNumber);
}
}<file_sep>/webapi/drawMe.WebApi/Controllers/AuthController.cs
using drawMe.WebApi.Dto.User;
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using drawMe.WebApi.Settings;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace drawMe.WebApi.Controllers
{
[Route("api/[controller]")]
public class AuthController : Controller
{
private readonly IUserService _authorizationService;
private readonly JwtSettings _options;
public AuthController(IUserService authorizationService, IOptions<JwtSettings> optionsAccessor)
{
_authorizationService = authorizationService;
_options = optionsAccessor.Value;
}
[HttpPost]
public async Task<IActionResult> GetToken([FromBody]UserLoginDto userDto)
{
try
{
var user = await _authorizationService.GetUserByEmail(userDto.Email);
if (user != null)
{
if (_authorizationService.VerifyHashedPassword(user, userDto.Password) == PasswordVerificationResult.Success)
{
return await GetToken(user);
}
}
}
catch (Exception ex)
{
}
return BadRequest("Failed to log in.");
}
private async Task<IActionResult> GetToken(ApplicationUser user)
{
var claims = await GetClaims(user);
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecretKey));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
expires: DateTime.UtcNow.AddHours(_options.ExpirationHours),
signingCredentials: credentials);
return Ok(new
{
userId = user.Id,
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
});
}
private async Task<IEnumerable<Claim>> GetClaims(ApplicationUser user)
{
var userClaims = await _authorizationService.GetClaims(user);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName),
new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
new Claim(JwtRegisteredClaimNames.Email, user.Email)
};
return claims.Union(userClaims);
}
}
}<file_sep>/webapi/drawMe.WebApi/Interfaces/IEntitiesQueryableFactory.cs
namespace drawMe.WebApi.Interfaces
{
public interface IEntitiesQueryableFactory
{
IEntityQueryableProvider GetQueryableProvider<T>() where T : class, IEntity;
}
}<file_sep>/webapi/drawMe.WebApi/Controllers/UpdateEmailController.cs
using drawMe.Services.Interfaces;
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using drawMe.WebApi.Models;
using drawMe.WebApi.Settings;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Linq;
using System.Collections.Generic;
namespace drawMe.WebApi.Controllers
{
[Authorize]
[Route("api/[controller]")]
public class UpdateEmailController : EmailBaseController
{
private readonly int year = DateTime.Now.Year;
private readonly AppSettings appSettings;
private readonly IRepository<ApplicationUser> usersRepository;
public UpdateEmailController(
IUserContext userContext,
IOptions<AppSettings> optionsAccessor,
IEmailService emailService,
IEmbeddedResourceService templateService,
IUserSecretService userSecretService,
IDaysTillChristmasService daysTillChristmasService,
IRepository<ApplicationUser> usersRepository)
:base(userContext, emailService, templateService, daysTillChristmasService, usersRepository)
{
this.appSettings = optionsAccessor.Value;
this.usersRepository = usersRepository;
}
protected override EmailContentModel GetContentModel(ApplicationUser user)
{
return new EmailContentModel
{
SubjectText = this.GetEmailSubject(),
FooterText = $"Losowanie Świąteczne {this.year}",
SalutationText = $"Witaj, {user.FirstName}!",
GreetingsText = $"Z pozdrowieniami,<br />Zespół elfów Mikołaja",
HtmlContent = GetInvitationContent(user)
};
}
protected override string GetEmailSubject()
{
return $"Losowanie Świąteczne {this.year} - aktualizacja";
}
private string GetInvitationContent(ApplicationUser user)
{
return $@"<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">Zespół programistów Mikołaja wysłuchał próśb i sugestii uczestników losowania i wprowadził kilka zmian w aplikacji. Oto najważniejsze z nich:</p>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;""><b>Link do przedmiotu na liście życzeń</b></p>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">Od teraz wprowadzając przedmiot na listę życzeń można opcjonalnie podać dowolny link. Może być to na przykład link do obrazka przedstawiającego pożądany przedmiot, aukcji internetowej, sklepu internetowego lub filmu na youtube (te ze śmiesznymi kotami też mogą być :). Zalecamy korzystanie z nowego pola - osoba, która wylosowała Ciebie zobaczy ten link i będzie mogła w niego kliknąć - z pewnością pomoże jej to przygotować Twój prezent :)</p>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;""><b>Lista uczestników zabawy</b></p>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">Na dole strony pojawiła się sekcja z listą uczestników losowania. Dzięki niej poznacie odpowiedź na jedno z najbardziej nurtujących pytań - jak wyglądam na zdjęciu które widzi osoba, która mnie wylosowała?!? Poza tym, dla każdej z osób dostępny jest wydruk kodu QR który można wykorzystać w przypadku, gdy chce się tej osobie również wręczyć prezent :)</p>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">Jeśli cokolwiek jest nie tak lub masz pomysł na kolejną fajną funkcjonalność - zapraszamy do kontaktu na elfią skrzynkę pocztową: <a href=""mailto:{this.appSettings.AdminEmail}"">{this.appSettings.AdminEmail}</a>.</p>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">PS. Do świąt pozostało { this.DaysTillChristmas} dni!</p>";
}
}
}
<file_sep>/webapi/drawMe.WebApi/Controllers/UserController.cs
using drawMe.WebApi.Dto.User;
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
namespace drawMe.WebApi.Controllers
{
[Authorize]
[Route("api/[controller]")]
public class UserController : Controller
{
private readonly IRepository<ApplicationUser> _userRepository;
public UserController(IRepository<ApplicationUser> userRepository)
{
_userRepository = userRepository;
}
// GET api/values
[HttpGet]
public IEnumerable<UserDto> Get()
{
var users = _userRepository
.Get()
.Select(u => u.MapTo<UserDto>())
.ToList();
return this.GetRandomlyOrderedUsers(users);
}
// GET api/values/guid
[HttpGet("{id}")]
public UserDto Get(Guid id)
{
return _userRepository
.Get(id)
.MapTo<UserDto>();
}
private List<UserDto> GetRandomlyOrderedUsers(List<UserDto> users)
{
return users.OrderBy(u => Guid.NewGuid()).ToList();
}
}
}<file_sep>/webapi/drawMe.WebApi/Controllers/WishlistItemController.cs
using drawMe.WebApi.Dto.WishlistItem;
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
namespace drawMe.WebApi.Controllers
{
[Authorize]
[Route("api/[controller]")]
public class WishlistItemController : Controller
{
private readonly IUserContext _userContext;
private readonly IRepository<ApplicationUser> _userRepository;
private readonly IRepository<WishlistItem> _wishlistItemRepository;
public WishlistItemController(
IUserContext userContext,
IRepository<ApplicationUser> userRepository,
IRepository<WishlistItem> wishlistItemRepository)
{
_userContext = userContext;
_userRepository = userRepository;
_wishlistItemRepository = wishlistItemRepository;
}
[HttpGet]
public GetWishlistItemsOutput Get(GetWishlistItemsInput input)
{
var wishlistItems = _wishlistItemRepository.Get().Where(wi => wi.User.Id == input.UserId);
var result = new GetWishlistItemsOutput();
result.Result = wishlistItems
.Select(wi => wi.MapTo<WishlistItemDto>())
.ToArray();
return result;
}
[HttpPut]
public bool Put([FromBody]CreateWishlistItemInput input)
{
try
{
var user = _userContext.CurrentUser;
var wishlistItem = new WishlistItem { User = user, Name = input.Name, ExampleUrl = input.Url };
this._wishlistItemRepository.Create(wishlistItem);
return true;
}
catch
{
return false;
}
}
[HttpDelete]
public bool Delete(DeleteWishlistItemInput input)
{
try
{
var wishlistItem = _wishlistItemRepository.Get(input.Id);
this._wishlistItemRepository.Delete(wishlistItem);
return true;
}
catch
{
return false;
}
}
}
}<file_sep>/webapi/drawMe.WebApi/Entities/Entity.cs
using drawMe.WebApi.Interfaces;
using System;
namespace drawMe.WebApi.Entities
{
public abstract class Entity : IEntity
{
public Guid Id { get; set; }
}
}<file_sep>/webapp/src/environments/environment.prod.ts
export const environment = {
production: true,
authorizationEndpoint: 'http://gwiazdka.azurewebsites.net/api/auth',
userEndpoint: 'http://gwiazdka.azurewebsites.net/api/user',
drawnUserEndpoint: 'http://gwiazdka.azurewebsites.net/api/drawnuser',
wishlistItemEndpoint: 'http://gwiazdka.azurewebsites.net/api/wishlistitem'
};
<file_sep>/webapp/src/app/content/content/content.component.ts
import { AuthorizationService } from '../../services/authorization.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {
authorized = this.authorizationService.authorized;
constructor(private authorizationService: AuthorizationService) {
this.authorizationService.authorizedChanged.subscribe((authorized) => {
this.authorized = authorized;
});
}
ngOnInit() {
this.authorized = this.authorizationService.authorized;
}
}
<file_sep>/webapi/drawMe.WebApi/Entities/ApplicationUserAssociation.cs
using System;
namespace drawMe.WebApi.Entities
{
public class ApplicationUserAssociation : Entity
{
public virtual Guid User1Id { get; set; }
public virtual Guid User2Id { get; set; }
}
}<file_sep>/webapi/drawMe.WebApi/Interfaces/IUserSecretService.cs
using drawMe.WebApi.Entities;
namespace drawMe.WebApi.Interfaces
{
public interface IUserSecretService
{
string GetUserSecret(ApplicationUser user);
}
}
<file_sep>/webapp/src/app/services/authorization.service.ts
import { AuthModel } from '../models/authModel';
import { environment } from '../../environments/environment';
import { Headers, Http, RequestOptions, Response } from '@angular/http';
import { EventEmitter, Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthorizationService {
private UserStorageKey = 'currentUser';
userId: string;
authorized = false;
authorizedChanged: EventEmitter<boolean> = new EventEmitter();
constructor(private http: Http) {
this.initializeIfAuthorized();
}
login(email: string, password: string) {
const authData = { Email: email, Password: <PASSWORD> };
return this.http.post(environment.authorizationEndpoint, authData)
.map((response: Response) => {
const user = response.json();
if (user && user.token) {
localStorage.setItem(this.UserStorageKey, JSON.stringify(user));
this.setAuthorized(true);
this.userId = user.userId;
}
});
}
logout() {
localStorage.removeItem(this.UserStorageKey);
this.setAuthorized(false);
this.userId = '';
}
getAuthorizationOptions(): RequestOptions {
const authModel = this.getAuthData();
const headers = new Headers({ 'Authorization': 'Bearer ' + authModel.token });
return new RequestOptions({ headers: headers });
}
private getAuthData(): AuthModel {
const userData = localStorage.getItem(this.UserStorageKey);
try {
const result = new AuthModel();
const userToken = JSON.parse(userData);
const expirationDate = new Date(userToken.expiration);
result.userId = userToken.userId;
result.token = userToken.token;
result.expireDate = expirationDate;
return result;
} catch (ex) {
return null;
}
}
private setAuthorized(authorized: boolean) {
this.authorized = authorized;
this.authorizedChanged.emit(this.authorized);
}
private initializeIfAuthorized() {
const userData = this.getAuthData();
if (userData != null && !userData.isExpired()) {
this.authorized = true;
this.userId = userData.userId;
}
}
}
<file_sep>/webapi/drawMe.WebApi/Dto/WishlistItem/DeleteWishlistItemInput.cs
using System;
namespace drawMe.WebApi.Dto.WishlistItem
{
public class DeleteWishlistItemInput
{
public Guid Id { get; set; }
}
}<file_sep>/webapi/drawMe.WebApi/Dto/User/UserDto.cs
using System;
namespace drawMe.WebApi.Dto.User
{
public class UserDto
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Description { get; set; }
public string Sex { get; set; }
public string PhotoPath { get; set; }
}
}<file_sep>/webapi/drawMe.WebApi/Dto/WishlistItem/GetWishlistItemsOutput.cs
namespace drawMe.WebApi.Dto.WishlistItem
{
public class GetWishlistItemsOutput
{
public WishlistItemDto[] Result { get; set; }
}
}<file_sep>/webapi/drawMe.Services/Interfaces/IDrawService.cs
using drawMe.Services.Models;
using System.Collections.Generic;
namespace drawMe.Services.Interfaces
{
public interface IDrawService
{
bool DrawPairs(List<Participant> participants, List<ParticipantsAssociation> associations = null);
}
}<file_sep>/webapi/drawMe.WebApi/Dto/WishlistItem/GetWishlistItemsInput.cs
using System;
namespace drawMe.WebApi.Dto.WishlistItem
{
public class GetWishlistItemsInput
{
public Guid UserId { get; set; }
}
}<file_sep>/README.md
# DrawMe - prototype web app for christmas gifts draw<file_sep>/webapi/drawMe.WebApi/Contexts/AppDbContext.cs
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
namespace drawMe.WebApi.Contexts
{
public class AppDbContext : IdentityDbContext<ApplicationUser, Role, Guid>
{
private const string DbSetTypeName = "DbSet";
public DbSet<WishlistItem> WishlistItems { get; set; }
public DbSet<ApplicationUserAssociation> ApplicationUserAssociations { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<T> GetDbSet<T>() where T : class, IEntity
{
var entityTypeName = typeof(T).Name;
var dbSetProperties = this.GetType().GetProperties()
.Where(p => p.PropertyType.Name.Contains(DbSetTypeName));
var dbSetProperty = dbSetProperties.FirstOrDefault(p =>
p.PropertyType.IsConstructedGenericType &&
p.PropertyType.GenericTypeArguments.Any(g => g.Name == entityTypeName));
if (dbSetProperty == null)
{
throw new ArgumentException($"Couldn't find DbSet of type {nameof(T)}");
}
var dbSet = dbSetProperty.GetValue(this);
return (DbSet<T>)dbSet;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>(user =>
{
user.Property(u => u.Id).HasDefaultValueSql("newsequentialid()");
});
modelBuilder.Entity<Role>(b =>
{
b.Property(u => u.Id).HasDefaultValueSql("newsequentialid()");
});
}
}
}<file_sep>/webapp/src/app/models/drawnUserModel.ts
import { WishlistItemModel } from './wishlistItemModel';
export class DrawnUserModel {
id: string;
firstName: string;
lastName: string;
description: string;
sex: string;
photoPath: string;
wishlistItems: WishlistItemModel[];
}
<file_sep>/webapi/drawMe.WebApi/Extensions/MapperExtensions.cs
namespace drawMe.WebApi
{
public static class MapperExtensions
{
public static TTargetType MapTo<TTargetType>(this object sourceObject)
{
return AutoMapper.Mapper.Map<TTargetType>(sourceObject);
}
}
}<file_sep>/webapi/drawMe.Services/DrawNumberService.cs
using drawMe.Services.Interfaces;
using System;
using System.Collections.Generic;
namespace drawMe.Services
{
public class DrawNumberService : IDrawNumberService
{
private readonly Random _random = new Random();
private int _minRedrawsCount = 1000;
private int _maxRedrawsCount = 2000;
public Dictionary<int, int> LastDrawDistribution { get; private set; }
public void SetRedrawsCountRange(int min, int max)
{
_minRedrawsCount = min;
_maxRedrawsCount = max;
}
public int DrawNumber(int maxNumber)
{
LastDrawDistribution = new Dictionary<int, int>();
var drawnIndex = 0;
var redrawsCount = _random.Next(_minRedrawsCount, _maxRedrawsCount);
for (var i = 0; i < redrawsCount; i++)
{
drawnIndex = _random.Next(0, maxNumber + 1);
if (!LastDrawDistribution.ContainsKey(drawnIndex))
{
LastDrawDistribution.Add(drawnIndex, 0);
}
LastDrawDistribution[drawnIndex]++;
}
return drawnIndex;
}
}
}<file_sep>/webapi/drawMe.WebApi/Interfaces/IUserService.cs
using drawMe.WebApi.Entities;
using Microsoft.AspNetCore.Identity;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
namespace drawMe.WebApi.Interfaces
{
public interface IUserService
{
Task<ApplicationUser> GetUserByEmail(string email);
PasswordVerificationResult VerifyHashedPassword(ApplicationUser user, string hashedPassword);
Task<IList<Claim>> GetClaims(ApplicationUser user);
}
}<file_sep>/webapi/drawMe.WebApi/Settings/AppSettings.cs
namespace drawMe.WebApi.Settings
{
public class AppSettings
{
public string AppUrl { get; set; }
public string AdminEmail { get; set; }
public string SendGridApiKey { get; set; }
}
}<file_sep>/webapi/drawMe.WebApi/Models/ApplicationUserDrawModel.cs
using drawMe.WebApi.Entities;
using System.Linq;
namespace drawMe.WebApi.Models
{
public class ApplicationUserDrawModel
{
public ApplicationUser ApplicationUser { get; set; }
private ApplicationUser _candidate;
private bool _paired;
public bool CanBeDrawnFor(ApplicationUserDrawModel drawUser)
{
if(drawUser.ApplicationUser.Id == ApplicationUser.Id)
{
return false;
}
if (_paired)
{
return false;
}
return true;
//return !ApplicationUser.AssociatedWith.Any(au => au.Id == drawUser.ApplicationUser.Id);
}
public void AcceptCandidate()
{
ApplicationUser.DrawnUser = _candidate;
}
public void RejectCandidate()
{
_candidate = null;
_paired = false;
}
public void RegisterCandidate(ApplicationUserDrawModel candidate)
{
candidate.SetPaired();
_candidate = candidate.ApplicationUser;
}
public void SetPaired()
{
_paired = true;
}
}
}<file_sep>/webapi/drawMe.Services/Models/Participant.cs
using System;
namespace drawMe.Services.Models
{
public class Participant
{
public Guid ParticipantId { get; set; }
public Guid DrawnParticipantId { get; private set; }
public bool Paired { get; set; }
private Participant Candidate { get; set; }
public void AcceptCandidate()
{
DrawnParticipantId = Candidate.ParticipantId;
}
public void RejectCandidate()
{
Candidate = null;
Paired = false;
}
public void RegisterCandidate(Participant candidate)
{
candidate.SetPaired();
Candidate = candidate;
}
public void SetPaired()
{
Paired = true;
}
}
}<file_sep>/webapi/drawMe.Services.Tests/ParticipantTests.cs
using drawMe.Services.Models;
using System;
using System.Collections.Generic;
using Xunit;
using drawMe.Services.Extensions;
namespace drawMe.Services.Tests
{
public class ParticipantTests
{
[Fact]
public void CanBeDrawnFor_ParticipantAndCandidateHasSameId_ReturnFalse()
{
var id = Guid.NewGuid();
var participant = new Participant { ParticipantId = id };
var candidate = new Participant { ParticipantId = id };
Assert.False(candidate.CanBeDrawnFor(participant));
Assert.False(participant.CanBeDrawnFor(candidate));
}
[Fact]
public void CanBeDrawnFor_CandidateIsAlreadyPaired_ReturnFalse()
{
var participant = new Participant { ParticipantId = Guid.NewGuid() };
var candidate = new Participant { ParticipantId = Guid.NewGuid() };
candidate.SetPaired();
Assert.False(candidate.CanBeDrawnFor(participant));
}
[Fact]
public void CanBeDrawnFor_ParticipantIsAlreadyPaired_ReturnTrue()
{
var participant = new Participant { ParticipantId = Guid.NewGuid() };
var candidate = new Participant { ParticipantId = Guid.NewGuid() };
participant.SetPaired();
Assert.True(candidate.CanBeDrawnFor(participant));
}
[Fact]
public void CanBeDrawnFor_ParticipantsAreAssociated_ReturnFalse()
{
var participant = new Participant { ParticipantId = Guid.NewGuid() };
var candidate = new Participant { ParticipantId = Guid.NewGuid() };
var associations = new List<ParticipantsAssociation>
{
new ParticipantsAssociation(participant, candidate)
};
Assert.False(candidate.CanBeDrawnFor(participant, associations));
}
}
}<file_sep>/webapp/src/app/models/wishlistItemModel.ts
export class WishlistItemModel {
id: string;
createdOn: Date;
name: string;
description: string;
exampleUrl: string;
desireLevel: number;
}
<file_sep>/webapp/src/app/app.module.ts
import { UsersService } from './services/users.service';
import { WishlistItemsComponent } from './accessors/wishlist-items.component';
import { WishlistItemService } from './services/wishlist-item.service';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { NgxQRCodeModule } from '@techiediaries/ngx-qrcode';
import { AuthorizationService } from './services/authorization.service';
import { DrawnUserService } from './services/drawn-user.service';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header/header.component';
import { ContentComponent } from './content/content/content.component';
import { AuthorizedContentComponent } from './content/content/authorized-content/authorized-content.component';
import { UnauthorizedContentComponent } from './content/content/unauthorized-content/unauthorized-content.component';
import { LoginFormComponent } from './authorize/login-form/login-form.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
ContentComponent,
AuthorizedContentComponent,
UnauthorizedContentComponent,
WishlistItemsComponent,
LoginFormComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule,
NgbModule.forRoot(),
NgxQRCodeModule
],
providers: [AuthorizationService, DrawnUserService, WishlistItemService, UsersService],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/webapi/drawMe.WebApi/Controllers/DrawnUserController.cs
using drawMe.WebApi.Dto.User;
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace drawMe.WebApi.Controllers
{
[Authorize]
[Route("api/[controller]")]
public class DrawnUserController : Controller
{
private readonly ApplicationUser _currentUser;
public DrawnUserController(IUserContext userContext)
{
_currentUser = userContext.CurrentUser;
}
// GET api/values/guid
[HttpGet]
public DrawnUserDto Get()
{
if (_currentUser == null || _currentUser.DrawnUser == null)
{
return null;
}
var drawnUser = _currentUser.DrawnUser.MapTo<DrawnUserDto>();
return drawnUser;
}
}
}<file_sep>/webapi/drawMe.WebApi/Controllers/InviteEmailController.cs
using drawMe.Services.Interfaces;
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using drawMe.WebApi.Models;
using drawMe.WebApi.Settings;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
namespace drawMe.WebApi.Controllers
{
[Authorize]
[Route("api/[controller]")]
public class InviteEmailController : EmailBaseController
{
private const string InvitationEmailTemplateFilename = "InvitationEmailTemplate.html";
private readonly AppSettings appSettings;
private readonly int year = DateTime.Now.Year;
private readonly IUserSecretService userSecretService;
public InviteEmailController(
IUserContext userContext,
IOptions<AppSettings> optionsAccessor,
IEmailService emailService,
IEmbeddedResourceService templateService,
IUserSecretService userSecretService,
IDaysTillChristmasService daysTillChristmasService,
IRepository<ApplicationUser> usersRepository)
:base(userContext, emailService, templateService, daysTillChristmasService, usersRepository)
{
this.appSettings = optionsAccessor.Value;
this.userSecretService = userSecretService;
}
protected override EmailContentModel GetContentModel(ApplicationUser user)
{
return new EmailContentModel
{
SubjectText = this.GetEmailSubject(),
FooterText = $"Losowanie Świąteczne {this.year}",
SalutationText = $"Witaj, {user.FirstName}!",
GreetingsText = $"Z pozdrowieniami,<br />Zespół elfów Mikołaja",
HtmlContent = GetInvitationContent(user)
};
}
protected override string GetEmailSubject()
{
return $"Losowanie Świąteczne {this.year} - zaczynamy!";
}
private string GetInvitationContent(ApplicationUser user)
{
var secret = this.userSecretService.GetUserSecret(user);
return $@"<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">Zapraszamy do udziału w corocznej rodzinnej zabawie bożonarodzeniowej! Jak co roku <NAME> ma dla Ciebie zadanie - ktoś czeka na prezent od Ciebie! Idąc jednak z duchem czasu, <NAME> nauczyły się programować i opracowały nowoczesny system internetowy, który przeprowadzi losowanie i pomoże Ci w przygotowaniu prezentu :)</p>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">Aby zalogować się do systemu kliknij w przycisk poniżej i wpisz świąteczne dane logowania:</p>
<table border=""0"" cellpadding=""0"" cellspacing=""0"" class=""btn btn-primary"" style=""border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; box-sizing: border-box;"">
<tbody>
<tr>
<td align=""left"" style=""font-family: sans-serif; font-size: 14px; vertical-align: top; padding-bottom: 15px;"">Login: {user.Email}</td>
</tr>
<tr>
<td align=""left"" style=""font-family: sans-serif; font-size: 14px; vertical-align: top; padding-bottom: 15px;"">Hasło: {secret}</td>
</tr>
<tr>
<td align=""left"" style=""font-family: sans-serif; font-size: 14px; vertical-align: top; padding-bottom: 15px;"">
<table border=""0"" cellpadding=""0"" cellspacing=""0"" style=""border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: auto;"">
<tbody>
<tr>
<td style=""font-family: sans-serif; font-size: 14px; vertical-align: top; background-color: #3498db; border-radius: 5px; text-align: center;""> <a href=""{this.appSettings.AppUrl}"" target=""_blank"" style=""display: inline-block; color: #ffffff; background-color: #3498db; border: solid 1px #3498db; border-radius: 5px; box-sizing: border-box; cursor: pointer; text-decoration: none; font-size: 14px; font-weight: bold; margin: 0; padding: 12px 25px; text-transform: capitalize; border-color: #3498db;"">Przejdź do strony systemu losowania</a> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">Każdy z uczestników jest proszony o wypełnienie własnej listy życzeń. Listę można wypełnić po zalogowaniu na stronę systemu.</p>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">Przygotowując prezent prosimy wydrukować kod dostępny na stronie systemu po zalogowaniu. Kod można wydrukować wielokrotnie i nalepić na dowolną ilość paczek :) Odpowiednio zapakowany prezent z nadrukowanym kodem należy dostarczyć pod wskazany adres najpóźniej do dnia 24 grudnia {this.year}:</p>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">Podłoga pod choinką<br />ul. Przeskok 34<br />63-400 Ostrów Wielkopolski</p>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">Wszelkie skargi, problemy, pochwały lub pytania prosimy kierować na elfią skrzynkę mailową: <a href=""mailto:{this.appSettings.AdminEmail}"">{this.appSettings.AdminEmail}</a>. Język elficki nie jest wymagany.</p>
<p style=""font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;"">Pamiętaj - do świąt pozostalo jedynie { this.DaysTillChristmas} dni!</p>";
}
}
}<file_sep>/webapi/drawMe.WebApi/Providers/EntityQueryable/WishlistItemQueryableProvider.cs
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace drawMe.WebApi.Providers.EntityQueryable
{
public class WishlistItemQueryableProvider : IEntityQueryableProvider
{
IQueryable<T> IEntityQueryableProvider.GetQueryable<T>(DbSet<T> dbSet)
{
var userDbSet = dbSet as DbSet<WishlistItem>;
var queryable = userDbSet.Include(u => u.User).AsQueryable();
return (IQueryable<T>)queryable;
}
}
}<file_sep>/webapi/drawMe.WebApi/Dto/User/DrawnUserDto.cs
namespace drawMe.WebApi.Dto.User
{
public class DrawnUserDto
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Description { get; set; }
public string Sex { get; set; }
public string PhotoPath { get; set; }
}
}<file_sep>/webapi/drawMe.Services/DrawService.cs
using drawMe.Services.Extensions;
using drawMe.Services.Interfaces;
using drawMe.Services.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace drawMe.Services
{
public class DrawService : IDrawService
{
private const int MaxAttemptsCount = 10;
private List<Participant> _participants;
private List<ParticipantsAssociation> _associations;
private IDrawNumberService _drawNumberService;
public DrawService(IDrawNumberService drawNumberService)
{
_drawNumberService = drawNumberService;
}
public bool DrawPairs(List<Participant> participants, List<ParticipantsAssociation> associations = null)
{
this._participants = participants;
this._associations = associations;
var attemptNo = 1;
var drawFinished = false;
while (!drawFinished && attemptNo <= MaxAttemptsCount)
{
drawFinished = TryDrawPairs();
if (!drawFinished)
{
attemptNo++;
}
}
if (!drawFinished)
{
throw new ApplicationException($"Failed to draw pairs after {attemptNo} attempts.");
}
return drawFinished;
}
private bool TryDrawPairs()
{
foreach (var participant in _participants)
{
if (!DrawParticipantFor(participant))
{
return false;
}
}
ApplyChanges();
return true;
}
private bool DrawParticipantFor(Participant currentParticipant)
{
var possibleParticipants = _participants
.Where(drawParticipant => drawParticipant.CanBeDrawnFor(currentParticipant, _associations))
.ToList();
if (!possibleParticipants.Any())
{
return false;
}
var maxIndex = possibleParticipants.Count - 1;
var index = _drawNumberService.DrawNumber(maxIndex);
var drawnParticipant = possibleParticipants[index];
currentParticipant.RegisterCandidate(drawnParticipant);
return true;
}
private void RollbackChanges()
{
_participants.ForEach(participant => participant.RejectCandidate());
}
private void ApplyChanges()
{
_participants.ForEach(participant => ApplyChanges(participant));
}
private void ApplyChanges(Participant participant)
{
participant.AcceptCandidate();
}
}
}<file_sep>/webapi/drawMe.WebApi/Interfaces/IRepository.cs
using System;
using System.Linq;
namespace drawMe.WebApi.Interfaces
{
public interface IRepository<T> where T : IEntity
{
Guid Create(T entity);
bool Update(T entity);
bool Delete(T entity);
T Get(Guid id);
IQueryable<T> Get();
}
}<file_sep>/webapi/drawMe.WebApi/Dto/User/UserInitDto.cs
namespace drawMe.WebApi.Dto.User
{
public class UserInitDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Description { get; set; }
public string Sex { get; set; }
public string SendEmail { get; set; }
public string PhotoPath { get; set; }
public bool IsAdmin { get; set; }
public string[] AssociatedUsersEmails { get; set; }
public UserInitDto()
{
this.AssociatedUsersEmails = new string[0];
}
}
}<file_sep>/webapi/drawMe.WebApi/Profiles/UserProfiles.cs
using AutoMapper;
using drawMe.Services.Models;
using drawMe.WebApi.Dto.User;
using drawMe.WebApi.Entities;
using System;
namespace drawMe.WebApi.Profiles
{
public class UserProfiles : Profile
{
public UserProfiles()
{
CreateMap<ApplicationUser, UserDto>();
CreateMap<UserDto, ApplicationUser>();
CreateMap<ApplicationUser, DrawnUserDto>().ForMember(u => u.Id, options => options.MapFrom(user => user.Id.ToString()));
CreateMap<DrawnUserDto, ApplicationUser>().ForMember(u => u.Id, options => options.MapFrom(user => new Guid(user.Id)));
CreateMap<ApplicationUser, UserInitDto>().ForMember(u => u.AssociatedUsersEmails, options => options.Ignore());
CreateMap<UserInitDto, ApplicationUser>()
.ForMember(u => u.NormalizedEmail, options => options.MapFrom(user => user.Email.ToUpper()))
.ForMember(u => u.UserName, options => options.MapFrom(user => user.Email))
.ForMember(u => u.NormalizedUserName, options => options.MapFrom(user => user.Email.ToUpper()))
.ForMember(u => u.EmailConfirmed, options => options.ResolveUsing(o => true))
.ForMember(u => u.PhoneNumberConfirmed, options => options.ResolveUsing(o => true))
.ForMember(u => u.SecurityStamp, options => options.ResolveUsing(o => Guid.NewGuid().ToString("D")));
CreateMap<ApplicationUser, Participant>()
.ForMember(p => p.DrawnParticipantId, options => options.Ignore())
.ForMember(p => p.ParticipantId, options => options.ResolveUsing(user => user.Id));
}
}
}<file_sep>/webapi/drawMe.Services/Generators/UserSecretGenerator.cs
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace drawMe.Services.Generators
{
public static class UserSecretGenerator
{
public static string GetSecret(string email, string firstName, string lastName, string[] assignableSecrets)
{
var data = $"{lastName}##${email}##{lastName}";
byte[] hash;
using (var hasher = MD5.Create())
{
hasher.Initialize();
hasher.ComputeHash(Encoding.UTF8.GetBytes(data));
hash = hasher.Hash;
}
StringBuilder sBuilder = new StringBuilder();
var nonNumberCount = 0;
for (int i = 0; i < hash.Length; i++)
{
sBuilder.Append(hash[i].ToString("x2"));
}
var chain = sBuilder.ToString();
foreach (var element in chain)
{
if (!char.IsNumber(element))
{
nonNumberCount++;
}
}
while (assignableSecrets.Length < nonNumberCount - 1)
{
nonNumberCount = nonNumberCount / 2;
}
return assignableSecrets[nonNumberCount];
}
}
}<file_sep>/webapi/drawMe.WebApi/Services/EmbeddedResourceService.cs
using drawMe.WebApi.Interfaces;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace drawMe.WebApi.Services
{
public class EmbeddedResourceService : IEmbeddedResourceService
{
public string GetResourceContent(string filename)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceNames = assembly.GetManifestResourceNames();
var resourceName = resourceNames.SingleOrDefault(rn => rn.Contains(filename));
if (string.IsNullOrEmpty(resourceName))
{
throw new ApplicationException($"Couldn't find embedded resource named {filename}.");
}
using (var resourceStream = assembly.GetManifestResourceStream(resourceName))
{
using (var streamReader = new StreamReader(resourceStream))
{
return streamReader.ReadToEnd();
}
}
}
}
}<file_sep>/webapi/drawMe.WebApi/Interfaces/IUserContext.cs
using drawMe.WebApi.Entities;
namespace drawMe.WebApi.Interfaces
{
public interface IUserContext
{
ApplicationUser CurrentUser { get; }
}
}<file_sep>/webapp/src/app/services/users.service.ts
import { Observable } from 'rxjs/Rx';
import { environment } from '../../environments/environment.prod';
import { UserModel } from '../models/userModel';
import { Http, Response } from '@angular/http';
import { AuthorizationService } from './authorization.service';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class UsersService {
constructor(private http: Http, private authenticationService: AuthorizationService) {
}
getUsers(): Observable<UserModel[]> {
const options = this.authenticationService.getAuthorizationOptions();
return this.http.get(environment.userEndpoint, options)
.map((response: Response) => {
const users = response.json();
return users.map((user) => {
const model = new UserModel();
model.id = user.id;
model.firstName = user.firstName;
model.lastName = user.lastName;
model.photoPath = user.photoPath;
return model;
});
});
}
}
<file_sep>/webapi/drawMe.WebApi/Providers/EntityQueryable/UserQueryableProvider.cs
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace drawMe.WebApi.Providers.EntityQueryable
{
public class UserQueryableProvider : IEntityQueryableProvider
{
IQueryable<T> IEntityQueryableProvider.GetQueryable<T>(DbSet<T> dbSet)
{
var userDbSet = dbSet as DbSet<ApplicationUser>;
var queryable = userDbSet
.Include(u => u.DrawnUser)
.Include(u => u.WishlistItems)
.AsQueryable();
return (IQueryable<T>)queryable;
}
}
}<file_sep>/webapi/drawMe.WebApi/Dto/WishlistItem/WishlistItemDto.cs
using System;
namespace drawMe.WebApi.Dto.WishlistItem
{
public class WishlistItemDto
{
public Guid Id { get; set; }
public DateTime? CreatedOn { get; set; }
public string Name { get; set; }
public string ExampleUrl { get; set; }
public string Description { get; set; }
public int DesireLevel { get; set; }
}
}<file_sep>/webapi/drawMe.WebApi/Interfaces/IEntityQueryableProvider.cs
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace drawMe.WebApi.Interfaces
{
public interface IEntityQueryableProvider
{
IQueryable<T> GetQueryable<T>(DbSet<T> dbSet) where T : class, IEntity;
}
}<file_sep>/webapp/src/app/authorize/login-form/login-form.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthorizationService } from '../../services/authorization.service';
@Component({
selector: 'app-login-form',
templateUrl: './login-form.component.html',
styleUrls: ['./login-form.component.css']
})
export class LoginFormComponent implements OnInit {
model: any = {};
loading = false;
failed = false;
constructor(
private authenticationService: AuthorizationService) { }
ngOnInit() {
this.authenticationService.logout();
}
login() {this.loading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.loading = false;
this.failed = false;
},
error => {
this.loading = false;
this.failed = true;
});
}
}
<file_sep>/webapi/drawMe.WebApi/Contexts/AppDbContextInitializer.cs
using drawMe.WebApi.Dto.User;
using drawMe.WebApi.Entities;
using drawMe.WebApi.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace drawMe.WebApi.Contexts
{
public static class AppDbContextInitializer
{
private const string UsersResourceFilename = "users.json";
private static string[] _roleNames = new[] { "administrator", "user" };
public static async Task Seed(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService<AppDbContext>();
context.Database.EnsureCreated();
await InitializeRoles(context);
await InitializeApplicationUsers(serviceProvider, context);
}
private static async Task InitializeRoles(AppDbContext context)
{
foreach (var roleName in _roleNames)
{
var roleStore = new RoleStore<Role, AppDbContext, Guid>(context);
if (!context.Roles.Any(r => r.Name == roleName))
{
var role = new Role
{
Name = roleName,
NormalizedName = roleName.ToUpper()
};
await roleStore.CreateAsync(role);
}
}
}
private static async Task InitializeApplicationUsers(IServiceProvider serviceProvider, AppDbContext context)
{
if (context.Users.Any())
{
return;
}
var resourceService = new EmbeddedResourceService();
var usersContent = resourceService.GetResourceContent(UsersResourceFilename);
var users = JsonConvert.DeserializeObject<UserInitDto[]>(usersContent).ToList();
var secretService = new UserSecretService(resourceService);
var userStore = new UserStore<ApplicationUser, Role, AppDbContext, Guid>(context);
foreach (var userInitDto in users)
{
var user = userInitDto.MapTo<ApplicationUser>();
if (!context.Users.Any(u => u.UserName == user.UserName))
{
AppendGeneratedUserPassword(user, secretService);
await userStore.CreateAsync(user);
}
var userRoles = userInitDto.IsAdmin ? _roleNames : _roleNames.Skip(1);
await AssignRoles(serviceProvider, user.Email, userRoles.ToArray());
}
await context.SaveChangesAsync();
await AssignAssociatedUsers(context, serviceProvider, users);
await context.SaveChangesAsync();
}
private static async Task AssignAssociatedUsers(AppDbContext context, IServiceProvider serviceProvider, List<UserInitDto> userInitDtos)
{
var existingAssociations = context.ApplicationUserAssociations.ToList();
foreach (var userData in userInitDtos.Where(u => u.AssociatedUsersEmails.Any()))
{
var user = await GetUserByEmail(serviceProvider, userData.Email);
foreach (var associatedUserEmail in userData.AssociatedUsersEmails)
{
var associatedUser = await GetUserByEmail(serviceProvider, associatedUserEmail);
var association = existingAssociations
.Where(assoc => IsAnyAssociationMatching(assoc, user, associatedUser))
.FirstOrDefault();
if (association == null)
{
association = new ApplicationUserAssociation { User1Id = user.Id, User2Id = associatedUser.Id };
context.ApplicationUserAssociations.Add(association);
existingAssociations.Add(association);
}
}
}
context.SaveChanges();
}
private static bool IsAnyAssociationMatching(ApplicationUserAssociation association, ApplicationUser user1, ApplicationUser user2)
{
return IsAssociationMatching(association, user1, user2) || IsAssociationMatching(association, user2, user1);
}
private static bool IsAssociationMatching(ApplicationUserAssociation association, ApplicationUser user1, ApplicationUser user2)
{
return association.User1Id == user1.Id && association.User2Id == user2.Id;
}
private static ApplicationUser GetUser(string firstName, string lastName, string email, string phoneNumber, string sex, string description)
{
return new ApplicationUser
{
FirstName = firstName,
LastName = lastName,
Email = email,
PhoneNumber = phoneNumber,
NormalizedEmail = email.ToUpper(),
UserName = email,
NormalizedUserName = email.ToUpper(),
EmailConfirmed = true,
PhoneNumberConfirmed = true,
SecurityStamp = Guid.NewGuid().ToString("D"),
Sex = sex,
Description = description
};
}
private static void AppendGeneratedUserPassword(ApplicationUser user, UserSecretService userSecretService)
{
var hasher = new PasswordHasher<ApplicationUser>();
var secret = userSecretService.GetUserSecret(user);
var hashedPassword = hasher.HashPassword(user, secret);
user.PasswordHash = hashedPassword;
}
private static async Task AssignRoles(IServiceProvider services, string email, string[] roles)
{
var user = await GetUserByEmail(services, email);
var userManager = services.GetService<UserManager<ApplicationUser>>();
await userManager.AddToRolesAsync(user, roles);
}
private static async Task<ApplicationUser> GetUserByEmail(IServiceProvider services, string email)
{
var userManager = services.GetService<UserManager<ApplicationUser>>();
var user = await userManager.FindByNameAsync(email);
if (user == null)
{
throw new ApplicationException($"Couldn't find user created with email = {email}.");
}
return user;
}
}
}<file_sep>/webapi/drawMe.WebApi/Services/UserService.cs
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using Microsoft.AspNetCore.Identity;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
namespace drawMe.WebApi.Services
{
public class UserService : IUserService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IPasswordHasher<ApplicationUser> _passwordHasher;
public UserService(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IPasswordHasher<ApplicationUser> passwordHasher)
{
_userManager = userManager;
_signInManager = signInManager;
_passwordHasher = passwordHasher;
}
public async Task<ApplicationUser> GetUserByEmail(string email)
{
return await _userManager.FindByEmailAsync(email);
}
public PasswordVerificationResult VerifyHashedPassword(ApplicationUser user, string hashedPassword)
{
return _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, hashedPassword);
}
public async Task<IList<Claim>> GetClaims(ApplicationUser user)
{
return await _userManager.GetClaimsAsync(user);
}
}
}<file_sep>/webapi/drawMe.WebApi/Controllers/EmailBaseController.cs
using drawMe.Services.Interfaces;
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using drawMe.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using Mustache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace drawMe.WebApi.Controllers
{
public abstract class EmailBaseController
{
private const string InvitationEmailTemplateFilename = "InvitationEmailTemplate.html";
private readonly int year = DateTime.Now.Year;
private readonly int daysTillChristmas;
private readonly string emailTemplate;
private readonly IUserContext userContext;
private readonly IEmailService emailService;
private readonly IRepository<ApplicationUser> usersRepository;
protected int DaysTillChristmas => this.daysTillChristmas;
public EmailBaseController(
IUserContext userContext,
IEmailService emailService,
IEmbeddedResourceService templateService,
IDaysTillChristmasService daysTillChristmasService,
IRepository<ApplicationUser> usersRepository)
{
this.userContext = userContext;
this.emailService = emailService;
this.usersRepository = usersRepository;
this.emailTemplate = templateService.GetResourceContent(InvitationEmailTemplateFilename);
this.daysTillChristmas = daysTillChristmasService.GetDaysTillChristmas();
}
protected virtual List<ApplicationUser> GetApplicationUsers()
{
return this.usersRepository.Get().ToList();
}
[HttpPost]
public async Task<string> Post()
{
var result = "Result";
if (!this.userContext.CurrentUser.IsAdmin)
{
return result;
}
var users = this.GetApplicationUsers();
var controllerName = this.GetType().Name;
foreach (var user in users)
{
var subject = this.GetEmailSubject();
var content = this.GetEmailContent(user);
var email = user.SendEmail ?? user.Email;
await this.emailService.SendEmail(email, subject, content);
result += $"\r\n[{controllerName}] Sent email to {user.FirstName} to the following mailbox: {email}";
}
return result;
}
private string GetEmailContent(ApplicationUser user)
{
var model = this.GetContentModel(user);
var compiler = new FormatCompiler();
var generator = compiler.Compile(this.emailTemplate);
return generator.Render(model);
}
protected abstract EmailContentModel GetContentModel(ApplicationUser user);
protected abstract string GetEmailSubject();
}
}<file_sep>/webapi/drawMe.WebApi/Services/UserSecretService.cs
using drawMe.Services.Generators;
using drawMe.WebApi.Entities;
using drawMe.WebApi.Interfaces;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace drawMe.WebApi.Services
{
public class UserSecretService : IUserSecretService
{
private const string SecretsResourceFilename = "secrets.json";
private readonly IEmbeddedResourceService templateService;
public UserSecretService(IEmbeddedResourceService resourceService)
{
this.templateService = resourceService;
}
public string GetUserSecret(ApplicationUser user)
{
var secretsContent = this.templateService.GetResourceContent(SecretsResourceFilename);
var secrets = JsonConvert.DeserializeObject<List<string>>(secretsContent).ToArray();
return UserSecretGenerator.GetSecret(user.Email, user.FirstName, user.LastName, secrets);
}
}
}<file_sep>/webapp/src/app/services/drawn-user.service.ts
import { Observable } from 'rxjs/Rx';
import { DrawnUserModel } from '../models/drawnUserModel';
import { AuthorizationService } from './authorization.service';
import { environment } from '../../environments/environment';
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class DrawnUserService {
constructor(private http: Http, private authenticationService: AuthorizationService) {
}
getDrawnUser(): Observable<DrawnUserModel> {
const options = this.authenticationService.getAuthorizationOptions();
return this.http.get(environment.drawnUserEndpoint, options)
.map((response: Response) => {
const drawnUser = response.json();
const result = new DrawnUserModel();
result.id = drawnUser.id;
result.description = drawnUser.description;
result.firstName = drawnUser.firstName;
result.lastName = drawnUser.lastName;
result.photoPath = drawnUser.photoPath;
result.sex = drawnUser.sex;
return result;
});
}
}
<file_sep>/webapp/src/app/accessors/wishlist-items.component.ts
import { WishlistItemService } from '../services/wishlist-item.service';
import { Component, forwardRef, TemplateRef, ViewChild } from '@angular/core';
import { WishlistItemModel } from '../models/wishlistItemModel';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-wishlist-items',
templateUrl: './wishlist-items.component.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => WishlistItemsComponent),
multi: true
}
]
})
export class WishlistItemsComponent implements ControlValueAccessor {
allowRemove = true;
@ViewChild('showWishlistItemContent') showItemModal: TemplateRef<any>;
items: WishlistItemModel[] = <WishlistItemModel[]>{};
constructor(private wishlistItemService: WishlistItemService) { }
writeValue(value: any) {
this.items = value;
}
propagateChange = (_: any) => { };
registerOnChange(fn: (_: any) => void): void {
this.propagateChange = fn;
}
registerOnTouched() { }
setDisabledState(isDisabled: boolean): void {
this.allowRemove = !isDisabled;
}
remove(item: WishlistItemModel) {
const index = this.items.indexOf(item);
this.wishlistItemService.removeWishlistItem(item.id).subscribe((result) => {
this.items.splice(index, 1);
});
}
}
|
2e64cea9e40aaf8d64ad24a53940cd7c8a534c9d
|
[
"Markdown",
"C#",
"TypeScript"
] | 79 |
C#
|
jakubkaczmarek/drawMe
|
f003e0ece2aec989cfd7eea3d266101ab2a68f82
|
793e839fd03a3735c2525f4407804528b01359fd
|
refs/heads/master
|
<repo_name>m074/Cripto<file_sep>/src/bmp.c
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include "general.h"
#include "matrix.h"
Img* read_bmp(char* filename){
Img* img= malloc(sizeof(Img));
img->filename=malloc(sizeof(char)*(1+strlen(filename)));
strcpy(img->filename,filename);
img->bb=readfile(filename);
u_int32_t width;
u_int32_t height;
u_int16_t bits_per_pixel;
u_int32_t compression;
u_int32_t offset;
u_int8_t c;
memcpy(&width, img->bb->p + WIDTH_HEADER_OFFSET, WIDTH_HEADER_SIZE);
memcpy(&height, img->bb->p + HEIGHT_HEADER_OFFSET, HEIGHT_HEADER_SIZE);
memcpy(&bits_per_pixel, img->bb->p + BITS_PER_PIXEL_HEADER_OFFSET, BITS_PER_PIXEL_HEADER_SIZE);
memcpy(&compression, img->bb->p + COMPRESSION_HEADER_OFFSET, COMPRESSION_HEADER_SIZE);
memcpy(&offset, img->bb->p + BODY_START_HEADER_OFFSET, BODY_START_HEADER_SIZE);
memcpy(&c, img->bb->p + 6, 1);
img->width = width;
img->height = height;
img->bits = bits_per_pixel;
img->offset = offset;
img->c = c+1;
return img;
}
void set_c(Img* img, u_int8_t c){
img->c = c;
memcpy(img->bb->p + 6,&c, 1);
}
void change_filename(Img* img,char* filename){
free(img->filename);
img->filename=malloc(sizeof(char)*(1+strlen(filename)));
strcpy(img->filename,filename);
}
Img* copy_img(Img* img){
Img* img2 = malloc(sizeof(Img));
memcpy(img2,img,sizeof(Img));
img2->bb = copy_bbuffer(img->bb);
img2->filename = malloc(sizeof(char)*(strlen(img2->filename)+1));
strcpy(img2->filename,img->filename);
return img2;
}
void deleteImg(Img* img){
free_bbuffer(img->bb);
free(img->filename);
free(img);
}
u_int8_t get_byte(Img* img,u_int32_t pos){
u_int8_t s;
s = img->bb->p[img->offset + pos];
return s;
}
void set_byte(Img* img,u_int32_t pos, u_int8_t value){
img->bb->p[img->offset + pos]=value;
}
void set_bits(Img* img,u_int32_t pos, u_int8_t value, int bits){
u_int8_t c = get_byte(img,pos);
if(bits==1){
value = value >> 7;
c = c >> 1;
c = c << 1;
c = c | value;
}
if(bits==2){
value = value >>6;
c = c >> 2;
c = c << 2;
c = c | value;
}
set_byte(img,pos,c);
}
u_int8_t get_bits(Img* img,u_int32_t pos, int bits){
u_int8_t c = get_byte(img,pos);
if(bits==1){
c = c & 0x1;
}
if(bits==2){
c = c & 0x3;
}
return c;
}
void reduceto251(matrix * m){
int i,j;
for(i = 1; i <= m->rows; i++)
for(j = 1; j <= m->cols; j++){
if(ELEM(m,i,j) >=250 ){
ELEM(m, i, j) = 250;
}
if(ELEM(m,i,j) == 0 ){
ELEM(m, i, j) = 1;
}
}
}
matrix* getMatrixS(Img* img, int number,int size){
matrix* m = newMatrix(size,size);
__uint8_t* pos = img->bb->p + img->offset + (number*size*size);
for(int i=1; i<=size; i++){
for(int j=1; j<=size; j++){
setElement(m,i,j,*pos);
pos+=1;
}
}
reduceto251(m);
return m;
}
void putMatrixS(Img* img,matrix* ms,int number,int size){
__uint8_t* pos = img->bb->p + img->offset + (number*size*size);
for(int i=1; i<=size; i++){
for(int j=1; j<=size; j++){
pos[0]= (u_int8_t)ELEM(ms,i,j);
pos+=1;
}
}
}
Img** read_images_from_dir(char * directory, int n) {
int image_qty = 0;
struct dirent *p_dirent;
DIR* dir;
dir = opendir(directory);
Img** images = malloc(8 * sizeof(Img*));
char * path;
while ((p_dirent = readdir(dir)) != NULL) {
if(strstr(p_dirent->d_name, ".bmp") && image_qty < n && image_qty <= n) {
path = calloc(strlen(directory) + strlen(p_dirent->d_name) + 2, 1);
strcpy(path, directory);
strcat(path, "/");
strcat(path, p_dirent->d_name);
images[image_qty++] = read_bmp(path);
free(path);
}
}
if(n!=image_qty){
printf("No hay la cantidad de imagenes necesaria \n");
exit(EXIT_FAILURE);
}
closedir(dir);
return images;
}
int getQuantiyMatrixS(Img* img,int n){
if(img->bits!=8){
return -1;
}
return (img->height*img->width)/(n*n);
}
void putMatrixSh(Img* img,matrix* sh,int pos, int n) {
int32_t matrix_offset =n* n * 3 * pos;
int pasos = 2;
if (n == 8) {
pasos = 1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= 3; j++) {
int valor = ELEM(sh, i, j);
for (int v = 0; v < n; v++) {
set_bits(img, matrix_offset, valor, pasos);
valor = valor << pasos;
matrix_offset += 1;
}
}
}
}
matrix* getMatrixSh(Img* img,int pos, int n){
int32_t matrix_offset = n*3*n*pos;
matrix* sh=newMatrix(n,3);
int pasos = 2;
if (n == 8) {
pasos = 1;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=3;j++){
uint8_t valor=0;
for(int v=0;v<n;v++) {
int bit = get_bits(img, matrix_offset, pasos);
valor = valor << pasos;
valor = valor | bit;
matrix_offset+=1;
}
ELEM(sh,i,j)=valor;
}
}
return sh;
}
<file_sep>/src/utilities.c
// Created by <NAME> on 14/06/2019.
//
#include <stdio.h>
#include <stdlib.h>
#include "utilities.h"
int modInverse(int i) {
while(i<=0){
i+=251*1000;
}
i %= 251;
if (i < 1 || i > 251) {
return -1;
}
return inverses[i - 1];
}
int32_t multiplicativeInverse(int a)
{
int b = 251;
int t, nt, r, nr, q, tmp;
if (b < 0) b = -b;
if (a < 0) a = b - (-a % b);
t = 0; nt = 1; r = b; nr = a % b;
while (nr != 0) {
q = r/nr;
tmp = nt; nt = t - q*nt; t = tmp;
tmp = nr; nr = r - q*nr; r = tmp;
}
if (r > 1) return -1; /* No inverse */
if (t < 0) t += b;
return t;
}
uint32_t modProd(uint32_t a, uint32_t b)
{
long double x;
uint32_t c;
int32_t r;
if (a >= 251)
a %= 251;
if (b >= 251)
b %= 251;
x = a;
c = x * b / 251;
r = (int32_t)(a * b - c * 251) % (int32_t)251;
return r < 0 ? r + 251 : r;
}
int32_t modNorm(int64_t i){
while(i<=0){
i+=251*1024;
}
i %= 251;
return i;
}
<file_sep>/src/file_manager.c
#include <unistd.h>
#include "general.h"
BBuffer* readfile(char* filename){
FILE *fd;
if( access( filename, F_OK ) == -1 ) {
printf("No se pudo abrir el archivo: %s\n",filename);
exit(EXIT_FAILURE);
}
if ((fd = fopen(filename, "rb")) == NULL)
{
return NULL;
}
BBuffer* bb = malloc(sizeof(BBuffer));
fseek(fd, 0, SEEK_END);
u_int32_t size = ftell(fd);
bb->length = size;
bb->p = malloc(size);
fseek(fd, 0, SEEK_SET);
if (fread(bb->p, 1, bb->length, fd) != (size_t)bb->length){
return NULL;
}
fclose(fd);
return bb;
}
int writefile(BBuffer* bb, char* filename){
FILE *fd;
if ((fd = fopen(filename, "wb")) == NULL)
{
return 0;
}
fwrite(bb->p,1,bb->length,fd);
fclose(fd);
return 1;
}
BBuffer* copy_bbuffer(BBuffer* bb){
BBuffer* bb2 = malloc(sizeof(BBuffer));
bb2->length = bb->length;
bb2->p = malloc((bb->length));
memcpy(bb2->p,bb->p,bb->length);
return bb2;
}
void free_bbuffer(BBuffer* bb){
free(bb->p);
free(bb);
}
<file_sep>/src/matrix.h
//
// Created by <NAME> on 14/06/2019.
//
#ifndef CRIPTO_MATRIX_H
#define CRIPTO_MATRIX_H
#include <stdbool.h>
#include <stdint.h>
#define ELEM(mtx, row, col) \
mtx->data[(col-1) * mtx->rows + (row-1)]
typedef struct {
int rows;
int cols;
int32_t * data;
} matrix;
typedef struct {
int size;
matrix ** matrixes;
} matrixCol;
matrix * newMatrix(int rows, int cols);
int deleteMatrix(matrix * mtx);
matrix * copyMatrix(matrix * mtx);
int setElement(matrix * mtx, int row, int col, int32_t val);
int getElement(matrix * mtx, int row, int col, int32_t * val);
int printMatrix(matrix * mtx);
int transpose(matrix * in, matrix * out);
int sum(matrix * mtx1, matrix * mtx2, matrix * sum);
int product(matrix * mtx1, matrix * mtx2, matrix * prod);
int isSquare(matrix * mtx);
int isDiagonal(matrix * mtx);
int isUpperTriangular(matrix * mtx);
int diagonal(matrix * v, matrix * mtx);
matrix * newMatrixA(int n, int k);
matrix * inverse(matrix * mtx);
int64_t determinant(matrix * a);
matrix * newMatrixS(matrix * a);
matrix * newMatrixR(matrix * s, matrix * sCalculated);
matrixCol* getVectorsX(int size, int quantity);
matrixCol* getVectorsV(matrix* ma, matrixCol* xv);
void normalize(matrix* m);
matrixCol * generateAllMatrixG(int size, int32_t * c, matrix * r);
matrixCol * newMatrixCol(int size);
matrix* newMatrixB(matrixCol* mc, int k);
matrix * subMatrix(matrix * m, int col);
matrix * getrsmall(matrixCol * allG, __uint8_t * c, int x, int y);
matrix * solveEquations(matrix * m, matrix * g);
matrix* recoverMatrixR(matrixCol* allG, uint8_t * c);
matrix * newMatrixRW(matrix * w, matrix * doubleS);
matrix * newMatrixSh(matrix * v, matrix * g);
matrixCol* getMatrixColSh(matrixCol* v,matrixCol* g);
matrixCol* getMatrixColG(matrixCol* mcol_shadows, int k);
int matrix_add(matrix * mtx1, matrix * mtx2, matrix * substract);
matrix* recoverMatrixS(matrix* mdobles, matrix* mr);
void deleteMatrixCol(matrixCol* mc);
#endif //CRIPTO_MATRIX_H
<file_sep>/src/random.h
#ifndef CRIPTO_RANDOM_H
#define CRIPTO_RANDOM_H
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <stdint.h>
//
//#define MAX 50
//#define SET 10
/*variable global*/
int64_t seed; /*seed debe ser de 48 bits; se elige este tipo de 64 bits*/
void setSeed(int64_t seed);
uint8_t nextChar(void); /*devuelve un unsigned char*/
#endif //CRIPTO_RANDOM_H
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(Cripto)
set(CMAKE_C_STANDARD 99)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread --std=c99 -pedantic -pedantic-errors -Wall -Wextra -Werror -Wno-unused-parameter -D_POSIX_C_SOURCE=200112L -O0 -fsanitize=address")
#agregar sanidad
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread --std=c99 -pedantic -pedantic-errors -Wall -Wextra -Werror -Wno-unused-parameter -D_POSIX_C_SOURCE=200112L -O0")
#####################################################################
#find_package (sqlite3 REQUIRED)
#include_directories(${SQLITE3_INCLUDE_DIRS})
aux_source_directory(src COMMON_SOURCE_FILES)
#aux_source_directory(src/client CLIENT_SOURCE_FILES)
#aux_source_directory(src/server SERVER_SOURCE_FILES)
#aux_source_directory(src/database DB_SOURCE_FILES)
add_executable(cripto ${COMMON_SOURCE_FILES} src/arguments.c src/general.h src/file_manager.c src/random.h src/utilities.h)
#target_link_libraries(database ${SQLITE3_LIBRARIES})
#####################################################################
<file_sep>/Makefile
OUTPUT_FILE=ss
LIBRARIES= -lm
FLAGS= --std=c99 -pedantic -pedantic-errors -Wall -Wextra -Werror -Wno-unused-parameter -D_POSIX_C_SOURCE=200112L -O0
all:
gcc -o $(OUTPUT_FILE) src/*.c $(LIBRARIES) $(FLAGS)
clean:
rm -f $(OUTPUT_FILE)
<file_sep>/src/main.c
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "general.h"
#include "matrix.h"
#include "utilities.h"
#include "random.h"
int main(int argc, char *argv[]){
setSeed(time(0));
parse_options(argc,argv);
}
<file_sep>/src/matrix.c
/* matrix taken from http://theory.stanford.edu/~arbrad/pfe/06/matrix.c */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include "matrix.h"
#include "random.h"
#include "utilities.h"
#include <math.h>
/* Creates a ``rows by cols'' matrix with all values 0.
* Returns NULL if rows <= 0 or cols <= 0 and otherwise a
* pointer to the new matrix.
*/
matrix * newMatrix(int rows, int cols) {
if (rows <= 0 || cols <= 0) return NULL;
// allocate a matrix structure
matrix * m = (matrix *) malloc(sizeof(matrix));
// set dimensions
m->rows = rows;
m->cols = cols;
// allocate a double array of length rows * cols
m->data = (int32_t *) malloc((rows)*(cols)*sizeof(int32_t));
// set all data to 0
int i;
for (i = 0; i < rows*cols; i++)
m->data[i] = 0;
return m;
}
/* Creates a ``rows by cols'' matrix with all values 0.
* Returns NULL if rows <= 0 or cols <= 0 and otherwise a
* pointer to the new matrix.
*/
matrixCol * newMatrixCol(int size) {
if (size <= 0) return NULL;
// allocate a matrix structure
matrixCol * mC = (matrixCol *) malloc(sizeof(matrixCol));
// set dimensions
mC->size = size;
// allocate a double array of length rows * cols
mC->matrixes = (matrix **) malloc(size * sizeof(matrix *) );
return mC;
}
/* Deletes a matrix. Returns 0 if successful and -1 if mtx
* is NULL.
*/
int deleteMatrix(matrix * mtx) {
if (!mtx) return -1;
// free mtx's data
assert (mtx->data);
free(mtx->data);
// free mtx itself
free(mtx);
return 0;
}
void deleteMatrixCol(matrixCol* mc){
for(int i=0; i<mc->size; i++){
deleteMatrix(mc->matrixes[i]);
}
free(mc->matrixes);
free(mc);
}
/* Copies a matrix. Returns NULL if mtx is NULL.
*/
matrix * copyMatrix(matrix * mtx) {
if (!mtx) return NULL;
// create a new matrix to hold the copy
matrix * cp = newMatrix(mtx->rows, mtx->cols);
// copy mtx's data to cp's data
memcpy(cp->data, mtx->data,
mtx->rows * mtx->cols * sizeof(int32_t));
return cp;
}
/* Sets the (row, col) element of mtx to val. Returns 0 if
* successful, -1 if mtx is NULL, and -2 if row or col are
* outside of the dimensions of mtx.
*/
int setElement(matrix * mtx, int row, int col, int32_t val)
{
if (!mtx) return -1;
assert (mtx->data);
assert(!(row <= 0 || row > mtx->rows ||
col <= 0 || col > mtx->cols));
if (row <= 0 || row > mtx->rows ||
col <= 0 || col > mtx->cols){
return -2;
}
ELEM(mtx, row, col) = val;
return 0;
}
/* Sets the reference val to the value of the (row, col)
* element of mtx. Returns 0 if successful, -1 if either
* mtx or val is NULL, and -2 if row or col are outside of
* the dimensions of mtx.
*/
int getElement(matrix * mtx, int row, int col, int32_t * val) {
if (!mtx || !val) return -1;
assert (mtx->data);
assert(!(row <= 0 || row > mtx->rows ||
col <= 0 || col > mtx->cols));
if (row <= 0 || row > mtx->rows ||
col <= 0 || col > mtx->cols)
return -2;
*val = ELEM(mtx, row, col);
return 0;
}
/* Sets the reference n to the number of rows of mtx.
* Returns 0 if successful and -1 if mtx or n is NULL.
*/
int nRows(matrix * mtx, int * n) {
if (!mtx || !n) return -1;
*n = mtx->rows;
return 0;
}
/* Sets the reference n to the number of columns of mtx.
* Returns 0 if successful and -1 if mtx is NULL.
*/
int nCols(matrix * mtx, int * n) {
if (!mtx || !n) return -1;
*n = mtx->rows;
return 0;
}
/* Prints the matrix to stdout. Returns 0 if successful
* and -1 if mtx is NULL.
*/
int printMatrix(matrix * mtx) {
if (!mtx) return -1;
int row, col;
for (row = 1; row <= mtx->rows; row++) {
for (col = 1; col <= mtx->cols; col++) {
// Print the floating-point element with
// - either a - if negative or a space if positive
// - at least 3 spaces before the .
// - precision to the hundredths place
printf("%d ", ELEM(mtx, row, col));
}
// separate rows by newlines
printf("\n");
}
printf("\n");
return 0;
}
/* Writes the transpose of matrix in into matrix out.
* Returns 0 if successful, -1 if either in or out is NULL,
* and -2 if the dimensions of in and out are incompatible.
*/
int transpose(matrix * in, matrix * out) {
if (!in || !out) return -1;
if (in->rows != out->cols || in->cols != out->rows)
return -2;
int row, col;
for (row = 1; row <= in->rows; row++)
for (col = 1; col <= in->cols; col++)
ELEM(out, col, row) = ELEM(in, row, col);
return 0;
}
/* Writes the sum of matrices mtx1 and mtx2 into matrix
* sum. Returns 0 if successful, -1 if any of the matrices
* are NULL, and -2 if the dimensions of the matrices are
* incompatible.
*/
int sum(matrix * mtx1, matrix * mtx2, matrix * sum) {
if (!mtx1 || !mtx2 || !sum) return -1;
if (mtx1->rows != mtx2->rows ||
mtx1->rows != sum->rows ||
mtx1->cols != mtx2->cols ||
mtx1->cols != sum->cols)
return -2;
int row, col;
for (col = 1; col <= mtx1->cols; col++)
for (row = 1; row <= mtx1->rows; row++)
ELEM(sum, row, col) =
ELEM(mtx1, row, col) + ELEM(mtx2, row, col);
return 0;
}
/* Writes the substraction of matrices mtx1 and mtx2 into matrix
* sum. Returns 0 if successful, -1 if any of the matrices
* are NULL, and -2 if the dimensions of the matrices are
* incompatible.
*/
int substract(matrix * mtx1, matrix * mtx2, matrix * substract) {
if (!mtx1 || !mtx2 || !substract) return -1;
if (mtx1->rows != mtx2->rows ||
mtx1->rows != substract->rows ||
mtx1->cols != mtx2->cols ||
mtx1->cols != substract->cols)
return -2;
int row, col;
for (col = 1; col <= mtx1->cols; col++)
for (row = 1; row <= mtx1->rows; row++)
ELEM(substract, row, col) =
ELEM(mtx1, row, col) - ELEM(mtx2, row, col);
return 0;
}
int matrix_add(matrix * mtx1, matrix * mtx2, matrix * substract) {
if (!mtx1 || !mtx2 || !substract) return -1;
if (mtx1->rows != mtx2->rows ||
mtx1->rows != substract->rows ||
mtx1->cols != mtx2->cols ||
mtx1->cols != substract->cols)
return -2;
int row, col;
for (col = 1; col <= mtx1->cols; col++)
for (row = 1; row <= mtx1->rows; row++)
ELEM(substract, row, col) =
ELEM(mtx1, row, col) + ELEM(mtx2, row, col);
return 0;
}
/* Writes the product of matrices mtx1 and mtx2 into matrix
* prod. Returns 0 if successful, -1 if any of the
* matrices are NULL, and -2 if the dimensions of the
* matrices are incompatible.
*/
int product(matrix * mtx1, matrix * mtx2, matrix * prod) {
if (!mtx1 || !mtx2 || !prod) return -1;
if (mtx1->cols != mtx2->rows ||
mtx1->rows != prod->rows ||
mtx2->cols != prod->cols)
return -2;
normalize(mtx1);
normalize(mtx2);
int row, col, k;
for (col = 1; col <= mtx2->cols; col++)
for (row = 1; row <= mtx1->rows; row++) {
int64_t val = 0;
for (k = 1; k <= mtx1->cols; k++){
val+= modProd(ELEM(mtx1, row, k), ELEM(mtx2, k, col));
// val+= ELEM(mtx1, row, k) * ELEM(mtx2, k, col);
val = modNorm(val);
}
ELEM(prod, row, col) = val;
}
return 0;
}
int identity(matrix * m) {
if (!m || m->rows != m->cols) return -1;
int row, col;
for (col = 1; col <= m->cols; col++)
for (row = 1; row <= m->rows; row++)
if (row == col)
ELEM(m, row, col) = 1;
else
ELEM(m, row, col) = 0;
return 0;
}
int isSquare(matrix * mtx) {
return mtx && mtx->rows == mtx->cols;
}
int isDiagonal(matrix * mtx) {
if (!isSquare(mtx)) return 0;
int row, col;
for (col = 1; col <= mtx->cols; col++)
for (row = 1; row <= mtx->rows; row++)
// if the element is not on the diagonal and not 0
if (row != col && ELEM(mtx, row, col) != 0)
// then the matrix is not diagonal
return 0;
return 1;
}
int isUpperTriangular(matrix * mtx) {
if (!isSquare(mtx)) return 0;
int row, col;
// looks at positions below the diagonal
for (col = 1; col <= mtx->cols; col++)
for (row = col+1; row <= mtx->rows; row++)
if (ELEM(mtx, row, col) != 0)
return 0;
return 1;
}
int diagonal(matrix * v, matrix * mtx) {
if (!v || !mtx ||
v->cols > 1 || v->rows != mtx->rows ||
mtx->cols != mtx->rows)
return -1;
int row, col;
for (col = 1; col <= mtx->cols; col++)
for (row = 1; row <= mtx->rows; row++)
if (row == col)
ELEM(mtx, row, col) = ELEM(v, col, 1);
else
ELEM(mtx, row, col) = 0;
return 0;
}
void multiplyByScalar(matrix * mtx, int32_t scalar){
int i,j;
for(i = 1; i <= mtx->rows; i++){
for(j = 1; j <= mtx->cols; j++){
int32_t elem = scalar * ELEM(mtx,i,j);
ELEM(mtx,i,j) = elem;
}
}
}
matrix * newMatrixA(int n, int k) {
matrix* rot=newMatrix(n,k);
for(int i=1;i<=rot->rows;i++){
for(int j=1;j<=rot->cols;j++){
if(i>rot->cols || i==j){
setElement(rot,i,j,modNorm(nextChar()));
}
}
}
matrix* rott=newMatrix(rot->cols,rot->rows);
transpose(rot,rott);
matrix* pro =newMatrix(rot->cols,rot->cols);
product(rott,rot,pro);
int det=modNorm(determinant(pro));
deleteMatrix(pro);
deleteMatrix(rott);
if(det==0){
deleteMatrix(rot);
rot=newMatrixA(n,k);
}
return rot;
}
void normalize(matrix * m){
int i,j;
for(i = 1; i <= m->rows; i++)
for(j = 1; j <= m->cols; j++){
while(ELEM(m,i,j) < 0){
ELEM(m, i, j) = ELEM(m,i,j) + 251* 1000;
}
ELEM(m,i,j) = ELEM(m,i,j) % 251;
}
}
int64_t determinant(matrix * a) {
int64_t det = 0 ; // init determinant
// square array
int n = a->rows;
if (n < 1) { } // error condition, should never get here
else if (n == 1) { // should not get here
det = ELEM(a,1,1);
}
else if (n == 2) { // basic 2X2 sub-matrix determinate
// definition. When n==2, this ends the
int d1 = ELEM(a,1,1);
int d2 = ELEM(a,2,2);
int d3 = ELEM(a,2,1);
int d4 = ELEM(a,1,2);
det = d1 * d2 - d3 * d4 ;// the recursion series
}
// recursion continues, solve next sub-matrix
else { // solve the next minor by building a
matrix * aux = newMatrix(n-1, n-1);
int i, i2, j2, rows, cols;
int sign = 1;
rows = cols = 1;
for(i = 1; i <= a->rows; i++) {
for(i2 = 1; i2 <= a->rows; i2++) {
for(j2= 2; j2 <= a->cols; j2++) {
if(i != i2 ) {
setElement(aux, rows, cols, ELEM(a,i2,j2));
cols++;
}
}
if(i != i2){
cols = 1;
rows++;
}
}
rows = 1;
det += sign * ELEM(a,i,1) * determinant(aux);
sign = -sign;
}
deleteMatrix(aux);
}
return(det);
}
matrix * inverse(matrix * a) {
matrix * ans = newMatrix(a->rows, a->cols);
matrix * subMatrix = newMatrix(a->rows-1, a->cols-1);
int i,j, i2, j2, cols, rows, sign;
cols = rows = 1;
for(i = 1; i <= a->rows; i++)
for(j = 1; j <= a->cols; j++){
for(i2 = 1; i2 <= a->rows; i2++) {
for(j2= 1; j2 <= a->cols; j2++) {
if(i != i2 && j != j2 ) {
setElement(subMatrix, rows, cols, ELEM(a,i2,j2));
cols++;
}
}
if(i != i2){
cols = 1;
rows++;
}
}
rows = 1;
sign = (i + j) % 2 == 0 ? 1 : -1;
setElement(ans, i,j, sign * modNorm(determinant(subMatrix)));
// setElement(ans, i,j, sign * determinant(subMatrix));
}
matrix * t = newMatrix(a->rows, a->cols);
transpose(ans, t);
int64_t scalar = modNorm(determinant(a));
scalar = multiplicativeInverse(scalar);
multiplyByScalar(t, scalar);
normalize(t);
deleteMatrix(ans);
deleteMatrix(subMatrix);
return t;
}
matrix * newMatrixS(matrix * a) {
//Define aux matrices
matrix * at, * ata, *ataInv, * aataInv, * aataInvat;
at = newMatrix(a->cols, a->rows);
transpose(a, at);
ata = newMatrix(at->rows, a->cols);
product(at, a, ata);
normalize(ata);
ataInv = inverse(ata);
aataInv = newMatrix(a->rows, ataInv->cols);
product(a, ataInv, aataInv);
normalize(aataInv);
aataInvat = newMatrix(aataInv->rows, at->cols);
product(aataInv, at, aataInvat);
deleteMatrix(at);
deleteMatrix(ata);
deleteMatrix(ataInv);
deleteMatrix(aataInv);
normalize(aataInvat);
return aataInvat;
}
matrix * newMatrixR(matrix * s, matrix * sCalculated) {
matrix * r = newMatrix(s->rows, s->cols);
substract(s,sCalculated, r);
normalize(r);
return r;
}
matrix* recoverMatrixS(matrix* mdobles, matrix* mr){
matrix* ms = newMatrix(mdobles->rows, mdobles->cols);
matrix_add(mdobles,mr,ms);
normalize(ms);
return ms;
}
matrixCol* getVectorsX(int size, int quantity){
matrixCol *mc=newMatrixCol(quantity);
int a = modNorm(nextChar());
for(int i=0;i<quantity;i++){
mc->matrixes[i]=newMatrix(size,1);
int prev=1;
for(int j=1;j<=size;j++){
ELEM(mc->matrixes[i],j,1)=modNorm(prev);
prev= prev*a;
}
a=modNorm(a+1);
if(a==1){
a=3;
}
}
return mc;
}
matrixCol* getVectorsV(matrix* ma, matrixCol* xv){
matrixCol *mc=newMatrixCol(xv->size);
for(int r=0;r<xv->size;r++){
// mc->matrixes[r]=malloc(sizeof(matrix*));
mc->matrixes[r]=newMatrix(ma->rows,1);
product(ma,xv->matrixes[r],mc->matrixes[r]);
normalize(mc->matrixes[r]);
}
return mc;
}
matrix * newMatrixG(matrix * r, int32_t c){
int i;
matrix * g = newMatrix(r->rows, 2);
for(i = 1; i <= g->rows; i++) {
if(r->cols == 4){
ELEM(g, i, 1) = ELEM(r,i,1) + ELEM(r, i, 2) * c;
ELEM(g, i, 2) = ELEM(r,i,3) + ELEM(r, i, 4) * c;
} else {
ELEM(g, i, 1) = ELEM(r,i,1) + ELEM(r, i, 2) * c + ELEM(r,i,3) * c * c + ELEM(r, i, 4) * c * c * c;
ELEM(g, i, 2) = ELEM(r,i,5) + ELEM(r, i, 6) * c + ELEM(r,i,7) * c * c + ELEM(r, i, 8) * c * c * c;
}
}
return g;
}
matrixCol * generateAllMatrixG(int size, int32_t * c, matrix * r) {
int i;
matrixCol * mc = newMatrixCol(size);
for(i = 0; i < size; i++){
mc->matrixes[i] = newMatrixG(r, c[i]+1);
normalize(mc->matrixes[i]);
}
return mc;
}
matrix* newMatrixB(matrixCol* mc, int k){
matrix * b = newMatrix(mc->matrixes[0]->rows, k);
for(int i = 1; i <= mc->matrixes[0]->rows; i++){
for(int j = 0; j<k;j++){
setElement(b, i, j+1, ELEM(mc->matrixes[j], i,1));
}
}
normalize(b);
return b;
}
/*Generates a new submatrix excluding the
* col from the matrix passed as
* arguments*/
matrix * subMatrix(matrix * m, int col) {
int i, j, i2, j2;
i2 = j2 = 1;
matrix * subMatrix = newMatrix(m->rows, m->cols - 1);
if(!m || col <= 0){
return NULL;
}
for(i = 1; i <= m->rows; i++) {
for(j = 1; j <=m->cols; j++) {
if(j != col) {
setElement(subMatrix, i2,j2, ELEM(m,i,j));
j2++;
}
}
j2 = 1;
i2++;
}
return subMatrix;
}
matrix* recoverMatrixR(matrixCol* allG, uint8_t * c){
matrix * mr = newMatrix(allG->matrixes[0]->rows,allG->matrixes[0]->rows);
for(int i=1;i<=mr->rows;i++){ // por las filas de g
for(int j=1;j<=2;j++){ // por la cnatidad de columnas de g
matrix * rsmall = getrsmall(allG,c,i,j);
for(int k=1; k<=(mr->rows/2);k++){
ELEM(mr,i,(rsmall->rows)*(j-1)+k)= ELEM(rsmall,k,1);
}
deleteMatrix(rsmall);
}
}
normalize(mr);
return mr;
}
matrix * getrsmall(matrixCol * allG, uint8_t * c, int x, int y) {
int i;
matrix * cMatrix = newMatrix(allG->size, allG->size);
matrix * g = newMatrix(allG->size, 1);
for(i = 1; i <= allG->size; i++){
setElement(g, i, 1, ELEM(allG->matrixes[i-1],x, y));
setElement(cMatrix, i, 1, 1);
setElement(cMatrix, i, 2, c[i-1]);
if(allG->size == 4) {
setElement(cMatrix, i, 3, c[i-1] * c[i-1]);
setElement(cMatrix, i, 4, c[i-1] * c[i-1] * c[i-1]);
}
}
matrix* rot= solveEquations(cMatrix, g);
deleteMatrix(cMatrix);
deleteMatrix(g);
return rot;
}
matrix * solveEquations(matrix * m, matrix * g) {
matrix * results = newMatrix(m->rows, 1);
// normalize(m);
int64_t det = determinant(m);
for(int j = 1; j <= m->cols; j++) {
matrix * copy = copyMatrix(m);
for(int i = 1; i <= m->rows; i++){
ELEM(copy, i, j) = ELEM(g,i,1);
}
int64_t dx = determinant(copy);
deleteMatrix(copy);
ELEM(results,j,1)=dx * modInverse(det);
}
normalize(results);
return results;
}
matrix * newMatrixRW(matrix * w, matrix * doubleS) {
matrix * results = newMatrix(w->rows, w->cols);
substract(w, doubleS, results);
normalize(results);
return results;
}
matrix * newMatrixSh(matrix * v, matrix * g) {
int i, j;
matrix * results = newMatrix(g->rows, g->cols + 1);
for(i = 1; i <= results->rows; i++) {
ELEM(results, i, 1) = ELEM(v, i, 1);
for(j = 2; j <= results->cols; j++) {
ELEM(results,i,j) = ELEM(g, i, j - 1);
}
}
normalize(results);
return results;
}
matrixCol* getMatrixColSh(matrixCol* v,matrixCol* g){
matrixCol* mcs=newMatrixCol(g->size);
for(int i=0;i<g->size;i++){
mcs->matrixes[i]=newMatrixSh(v->matrixes[i],g->matrixes[i]);
}
return mcs;
}
matrix* recoverG(matrix* m_shadow){
matrix* mg=newMatrix(m_shadow->rows,m_shadow->cols-1);
for(int i=1;i<=m_shadow->rows;i++){
for(int j=2;j<=m_shadow->cols;j++){
setElement(mg,i,j-1,ELEM(m_shadow,i,j));
}
}
return mg;
}
matrixCol* getMatrixColG(matrixCol* mcol_shadows, int k){
matrixCol* mcg = newMatrixCol(k);
for(int i=0;i<k;i++){
mcg->matrixes[i] = recoverG(mcol_shadows->matrixes[i]);
}
return mcg;
}
<file_sep>/src/general.h
#ifndef CRIPTO_GENERAL_H
#define CRIPTO_GENERAL_H
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include "matrix.h"
#define WIDTH_HEADER_OFFSET 0x12
#define WIDTH_HEADER_SIZE 0x4
#define HEIGHT_HEADER_OFFSET 0x16
#define HEIGHT_HEADER_SIZE 0x4
// Amount bits per pixel
#define BITS_PER_PIXEL_HEADER_OFFSET 0x1C
#define BITS_PER_PIXEL_HEADER_SIZE 0x2
// Compression
#define COMPRESSION_HEADER_OFFSET 0x1E
#define COMPRESSION_HEADER_SIZE 0x4
#define BODY_START_HEADER_OFFSET 0x0A
#define BODY_START_HEADER_SIZE 0x4
typedef struct byte_buffer_t
{
u_int8_t *p;
u_int32_t length;
} BBuffer;
typedef struct bmp_t
{
char* filename;
u_int32_t width;
u_int32_t height;
u_int8_t bits;
u_int32_t offset;
BBuffer* bb;
u_int8_t c;
} Img;
typedef struct conf_t
{
int d_mode;
int r_mode;
char* s_image_name;
char* m_image_name;
char* dir;
int number_k;
int number_n;
} Configuration;
Configuration* parse_options(int argc, char *argv[]);
BBuffer* readfile(char* filename);
int writefile(BBuffer* bb, char* filename);
BBuffer* copy_bbuffer(BBuffer* bb);
void free_bbuffer(BBuffer* bb);
Img* read_bmp(char* filename);
void change_filename(Img* img,char* filename);
Img** read_images_from_dir(char * directory, int n);
matrix* getMatrixS(Img* img, int number,int size);
void putMatrixS(Img* img,matrix* ms,int number,int size);
Img* copy_img(Img* img);
int getQuantiyMatrixS(Img* img,int n);
matrix* getMatrixSh(Img* img,int pos, int n);
void putMatrixSh(Img* img,matrix* sh,int pos, int n);
u_int8_t get_bits(Img* img,u_int32_t pos, int bits);
void deleteImg(Img* img);
void set_bits(Img* img,u_int32_t pos, u_int8_t value, int bits);
void set_c(Img* img, u_int8_t c);
#endif //CRIPTO_GENERAL_H
<file_sep>/README.txt
-EL trabajo practico utiliza las librerias de math.h
-Para su compilacion solamente es necesario hacer un "make all", generando un binario llamado "ss"
-Para su ejecucion en modo distribucion
./ss –d –s secreto.bmp –m watermark.bmp –k 4 – n 8 –dir images/
Creando un archivo llamado "RW.bmp"
-Para su ejecucion en modo de reucperacion
./ss –r –s secreto.bmp –m RW.bmp –k 4 –n 8 –dir images/
Creando un archivo "secreto.bmp", por el argumento s y un archivo "watermark.bmp"<file_sep>/src/arguments.c
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "general.h"
void help();
void distribute(Configuration* cfg);
void recover(Configuration* cfg);
void select_mode(Configuration* cfg);
Configuration* parse_options(int argc, char *argv[]){
Configuration* cfg=malloc(sizeof(Configuration));
memset(cfg,0, sizeof(Configuration));
int c;
static struct option long_options[] = {
{"secret", required_argument, 0, 's' },
{"dir", required_argument, 0, 'i' },
{"d", no_argument, 0, 'd' },
{"r", no_argument, 0, 'r' },
{"k", required_argument, 0, 'k' },
{"n", required_argument, 0, 'n' },
{"s", required_argument, 0, 's' },
{"m", required_argument, 0, 'm' },
{0, 0, 0, 0 }
};
int long_index =0;
while ((c = getopt_long_only(argc, argv,"", long_options, &long_index )) != -1) {
switch (c){
case 0:
printf("Hew dude\n");
break;
case 'i':
cfg->dir = optarg;
break;
case 'd':
cfg->d_mode = 1;
break;
case 'r':
cfg->r_mode = 1;
break;
case 's':
cfg->s_image_name = optarg;
break;
case 'm':
cfg->m_image_name = optarg;
break;
case 'k':
cfg->number_k = atoi(optarg);
break;
case 'n':
cfg->number_n = atoi(optarg);
break;
case 'h':
help();
exit(EXIT_SUCCESS);
default:
abort();
}
}
int n=cfg->number_n;
int k=cfg->number_k;
if(!((n==8 && k==4)||(n==4 && k==2))){
printf("Solamente se soporta en k=2,n=4 y en k=4,n=8\n");
exit(EXIT_FAILURE);
}
select_mode(cfg);
return cfg;
}
void select_mode(Configuration* cfg){
if(cfg->number_n==0 || cfg->m_image_name==0){
printf("Argumentos invalidos\n");
exit(EXIT_FAILURE);
}
if(cfg->d_mode){ //DISTRIBUTE MODE
distribute(cfg);
}else if(cfg->r_mode){ //RECOVER MODE
recover(cfg);
}
exit(EXIT_SUCCESS);
}
void distribute(Configuration* cfg){
int cs[8]={0,1,2,3,4,5,6,7};
int n= cfg->number_n;
int k= cfg->number_k;
Img* s_image = read_bmp(cfg->s_image_name);
Img* m_image = read_bmp(cfg->m_image_name);
Img** sh_images = read_images_from_dir(cfg->dir,n); //hay N imagenes
for(int xin=0;xin<n;xin++){
set_c(sh_images[xin],cs[xin]);
}
for(int32_t i=0;i<getQuantiyMatrixS(s_image,n);i++){
matrix* ma=newMatrixA(n,k);
matrix* mdoubles=newMatrixS(ma);
matrix* ms=getMatrixS(s_image,i,n);
matrix* mw=getMatrixS(m_image,i,n);
matrix* mr=newMatrixR(ms,mdoubles);
matrix* mrw = newMatrixRW(mw,mdoubles);
matrixCol* mcg = generateAllMatrixG(n,cs,mr);
matrixCol* vectorsX=getVectorsX(k,n);
matrixCol* vectorsV=getVectorsV(ma,vectorsX);
matrixCol* mcs = getMatrixColSh(vectorsV,mcg);
for(int s=0;s<mcs->size;s++){
putMatrixSh(sh_images[s],mcs->matrixes[s],i,n);
}
// if(i==0){
// printf("Matrix la Sdoble\n");
// printMatrix(mdoubles);
// printf("Matrix la R\n");
// printMatrix(mr);
// printf("Matrix la S\n");
//
// printMatrix(ms);
// printf("Matrix la RW\n");
// printMatrix(mrw);
// for(int kk=0;kk<mcs->size;kk++){
// printf("Shadow\n");
// printMatrix(mcs->matrixes[kk]);
// }
// }
putMatrixS(m_image,mrw,i,n);
//dont touch s_image
deleteMatrix(ma);
deleteMatrix(mdoubles);
deleteMatrix(ms);
deleteMatrix(mw);
deleteMatrix(mr);
deleteMatrix(mrw);
deleteMatrixCol(mcg);
deleteMatrixCol(vectorsX);
deleteMatrixCol(vectorsV);
deleteMatrixCol(mcs);
}
writefile(m_image->bb,"RW.bmp");
for(int ar=0;ar<n;ar++){
writefile(sh_images[ar]->bb,sh_images[ar]->filename);
}
deleteImg(s_image);
deleteImg(m_image);
for(int sh=0;sh<n;sh++){
deleteImg(sh_images[sh]);
}
free(sh_images);
}
void recover(Configuration* cfg){
int n= cfg->number_n;
int k= cfg->number_k;
Img* rw_image = read_bmp(cfg->m_image_name);
Img** sh_images = read_images_from_dir(cfg->dir,k); //hay N imagenes
Img* s_image = copy_img(rw_image);
change_filename(s_image,cfg->s_image_name);
Img* w_image = copy_img(rw_image);
change_filename(w_image,"watermark.bmp");
uint8_t * cs=malloc(sizeof(uint8_t)*k);
for(int xin=0;xin<k;xin++){
cs[xin]=sh_images[xin]->c;
}
for(int32_t i=0;i<getQuantiyMatrixS(rw_image,n);i++){
matrixCol* mcsh=newMatrixCol(k);
for(int s=0;s<k;s++){
mcsh->matrixes[s]=getMatrixSh(sh_images[s],i,n);
}
matrix* mb=newMatrixB(mcsh,k);
matrix* mdobleS=newMatrixS(mb);
matrixCol* mcg =getMatrixColG(mcsh,k);
matrix* mr = recoverMatrixR(mcg,cs);
matrix* ms= recoverMatrixS(mdobleS,mr);
matrix* mrw = getMatrixS(rw_image,i,n);
matrix* mw = recoverMatrixS(mdobleS,mrw);
putMatrixS(s_image,ms,i,n);
putMatrixS(w_image,mw,i,n);
// if(i==0){
//
// printf("Matrix la B\n");
// printMatrix(mb);
// printf("Matrix la R\n");
// printMatrix(mr);
// printf("Matrix la Sdoble\n");
// printMatrix(mdobleS);
// printf("Matrix la S\n");
// printMatrix(ms);
// printf("Matrix la RW\n");
// printMatrix(mrw);
// for(int kk=0;kk<mcsh->size;kk++){
// printf("Shadow\n");
// printMatrix(mcsh->matrixes[kk]);
// }
//
// for(int kk=0;kk<mcsh->size;kk++){
// printf("gg\n");
// printMatrix(mcg->matrixes[kk]);
// }
// }
deleteMatrix(ms);
deleteMatrix(mb);
deleteMatrix(mw);
deleteMatrix(mr);
deleteMatrix(mrw);
deleteMatrix(mdobleS);
deleteMatrixCol(mcg);
deleteMatrixCol(mcsh);
}
writefile(s_image->bb,s_image->filename);
writefile(w_image->bb,w_image->filename);
deleteImg(s_image);
deleteImg(rw_image);
deleteImg(w_image);
for(int sh=0;sh<k;sh++){
deleteImg(sh_images[sh]);
}
free(sh_images);
free(cs);
}
void help() {printf("La ayuda...\n");}
|
9f2ec7b051fbe93f58893fb3196520701952e471
|
[
"Makefile",
"C",
"Text",
"CMake"
] | 12 |
C
|
m074/Cripto
|
8fbdf7cf9ceef4e5765891303d7923e999ac9f26
|
060f3341aa65ba92ac1ac599c259d495bf803e37
|
refs/heads/master
|
<file_sep> public class testTableConfig
{
public int id;
public string name;
public int costId;
public class positionClass
{
public double x;
public double y;
public double z;
}
public positionClass position;
public class nameMessageIdClass
{
public int id;
}
public nameMessageIdClass nameMessageId;
public string[] textureName;
public class vector4Class
{
public double x;
public double y;
public double z;
public double w;
}
public vector4Class[] vector4;
public class packageClass
{
public string packageName;
}
public packageClass[] package;
}<file_sep> public class testConfig
{
public int id;
public int nameMessageId;
public class positionClass
{
public double x;
public double y;
public double z;
}
public positionClass position;
public class resourceClass
{
public string textureName;
}
public resourceClass resource;
public class rotationClass
{
public double x;
public double y;
public double z;
}
public rotationClass[] rotation;
public string[] attachNamePosition;
public class audioSourceClass
{
public string audioSourceName;
}
public audioSourceClass[] audioSource;
}<file_sep>using Util;
using System.Collections.Generic;
using System;
public class testConfigParser
{
private string m_strErrorMsg;
public string GetErrorMsg()
{
return m_strErrorMsg;
}
public List<testConfig> ParserConfig(string[][] content)
{
List<testConfig> resultConfigTable = new List<testConfig>();
for (int i = 0; i < content.Length; ++i)
{
resultConfigTable.Add(ParserLine(i, content[i]));
if (!string.IsNullOrEmpty(m_strErrorMsg))
{
return null;
}
}
return resultConfigTable;
}
private testConfig ParserLine(int lineIndex, string[] values)
{
int tmpIndexOffset = 0;
int skipCount = 0;
testConfig configLineElement = new testConfig();
if (!VaildUtil.TryConvert(values[0 + tmpIndexOffset], out configLineElement.id,0,50))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testConfig", lineIndex,0+1, values[0 + tmpIndexOffset],0,50,"int","id");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[0 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 5 ,values[0 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testConfig", lineIndex,0+1, values[0 + tmpIndexOffset],"","id");
return null;
}
if (!VaildUtil.TryConvert(values[1 + tmpIndexOffset], out configLineElement.nameMessageId,int.MinValue,int.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testConfig", lineIndex,1+1, values[1 + tmpIndexOffset],int.MinValue,int.MaxValue,"int","nameMessageId");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[1 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("testTableConfig", 2 ,values[1 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testConfig", lineIndex,1+1, values[1 + tmpIndexOffset],"testTableConfig","nameMessageId");
return null;
}
configLineElement.position = new testConfig.positionClass();
if (!VaildUtil.TryConvert(values[2 + tmpIndexOffset], out configLineElement.position.x,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testConfig", lineIndex,2+1, values[2 + tmpIndexOffset],double.MinValue,double.MaxValue,"double","x");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[2 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 ,values[2 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testConfig", lineIndex,2+1, values[2 + tmpIndexOffset],"","x");
return null;
}
if (!VaildUtil.TryConvert(values[3 + tmpIndexOffset], out configLineElement.position.y,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testConfig", lineIndex,3+1, values[3 + tmpIndexOffset],double.MinValue,double.MaxValue,"double","y");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[3 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 ,values[3 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testConfig", lineIndex,3+1, values[3 + tmpIndexOffset],"","y");
return null;
}
if (!VaildUtil.TryConvert(values[4 + tmpIndexOffset], out configLineElement.position.z,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testConfig", lineIndex,4+1, values[4 + tmpIndexOffset],double.MinValue,double.MaxValue,"double","z");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[4 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 ,values[4 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testConfig", lineIndex,4+1, values[4 + tmpIndexOffset],"","z");
return null;
}
configLineElement.resource = new testConfig.resourceClass();
if (!VaildUtil.TryConvert(values[5 + tmpIndexOffset], out configLineElement.resource.textureName,null,null))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testConfig", lineIndex,5+1, values[5 + tmpIndexOffset],null,null,"string","textureName");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[5 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 ,values[5 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testConfig", lineIndex,5+1, values[5 + tmpIndexOffset],"","textureName");
return null;
}
List<string> rotationSourceList = null;
if (!VaildUtil.TryConvert(values,6 + tmpIndexOffset, 1,out rotationSourceList ,out skipCount))
{
m_strErrorMsg = string.Format("{0}.xlsx [{1},{2}]数组解析读取出现错误", "testConfig", lineIndex,6+1);
return null;
}
var rotationTmpList = new List<testConfig.rotationClass>();
for(int i=0;i<rotationSourceList.Count;i += 3)
{
int startIndex = i;
var rotationElement = new testConfig.rotationClass();
rotationTmpList.Add(rotationElement);
if (!VaildUtil.TryConvert(rotationSourceList[0 + startIndex], out rotationElement.x,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testConfig", lineIndex,0+1, rotationSourceList[0 + startIndex],double.MinValue,double.MaxValue,"double","x");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, rotationSourceList[0 + startIndex] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 , rotationSourceList[0 + startIndex]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testConfig", lineIndex,0+1, rotationSourceList[0 + startIndex],"","x");
return null;
}
if (!VaildUtil.TryConvert(rotationSourceList[1 + startIndex], out rotationElement.y,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testConfig", lineIndex,1+1, rotationSourceList[1 + startIndex],double.MinValue,double.MaxValue,"double","y");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, rotationSourceList[1 + startIndex] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 , rotationSourceList[1 + startIndex]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testConfig", lineIndex,1+1, rotationSourceList[1 + startIndex],"","y");
return null;
}
if (!VaildUtil.TryConvert(rotationSourceList[2 + startIndex], out rotationElement.z,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testConfig", lineIndex,2+1, rotationSourceList[2 + startIndex],double.MinValue,double.MaxValue,"double","z");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, rotationSourceList[2 + startIndex] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 , rotationSourceList[2 + startIndex]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testConfig", lineIndex,2+1, rotationSourceList[2 + startIndex],"","z");
return null;
}
}
configLineElement.rotation = rotationTmpList.ToArray();
tmpIndexOffset += skipCount;
List<string> attachNamePositionSourceList = null;
if (!VaildUtil.TryConvert(values,7 + tmpIndexOffset, 0, out attachNamePositionSourceList , out skipCount))
{
m_strErrorMsg = string.Format("{0}.xlsx [{1},{2}]数组解析读取出现错误", "testConfig", lineIndex,7+1);
return null;
}
var attachNamePositionTmpList = new List<string>();
for(int i=0;i<attachNamePositionSourceList.Count;++i)
{
string subElement;
if (!VaildUtil.TryConvert(attachNamePositionSourceList[i], out subElement,null,null))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]数组解析读取出现错误,{3}必须为{4} - {5} {6}型", "testConfig", lineIndex,i+1, attachNamePositionSourceList[i],null,null,"string","attachNamePosition");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, attachNamePositionSourceList[i] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 , attachNamePositionSourceList[i]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testConfig", lineIndex,i+1, attachNamePositionSourceList[i],"","attachNamePosition");
return null;
}
attachNamePositionTmpList.Add(subElement);
}
configLineElement.attachNamePosition = attachNamePositionTmpList.ToArray();
tmpIndexOffset += skipCount;
List<string> audioSourceSourceList = null;
if (!VaildUtil.TryConvert(values,8 + tmpIndexOffset, 0,out audioSourceSourceList ,out skipCount))
{
m_strErrorMsg = string.Format("{0}.xlsx [{1},{2}]数组解析读取出现错误", "testConfig", lineIndex,8+1);
return null;
}
var audioSourceTmpList = new List<testConfig.audioSourceClass>();
for(int i=0;i<audioSourceSourceList.Count;i += 1)
{
int startIndex = i;
var audioSourceElement = new testConfig.audioSourceClass();
audioSourceTmpList.Add(audioSourceElement);
if (!VaildUtil.TryConvert(audioSourceSourceList[0 + startIndex], out audioSourceElement.audioSourceName,null,null))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testConfig", lineIndex,0+1, audioSourceSourceList[0 + startIndex],null,null,"string","auduioSourceName");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(true, audioSourceSourceList[0 + startIndex] ,"123456") &&
!VaildUtil.CheckRefrenceConfig("", 0 , audioSourceSourceList[0 + startIndex]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testConfig", lineIndex,0+1, audioSourceSourceList[0 + startIndex],"","auduioSourceName");
return null;
}
}
configLineElement.audioSource = audioSourceTmpList.ToArray();
tmpIndexOffset += skipCount;
return configLineElement;
}
public bool CheckIsConfigExistKey(string[][] content, int index, string keyValue)
{
for (int i = 0; i < content.Length; ++i)
{
if (CheckIsConfigExistKey(content[i], index, keyValue))
{
return true;
}
}
return false;
}
public bool CheckIsConfigExistKey(string[] values, int index, string keyValue)
{
int tmpIndexOffset = 0;
int skipCount = 0;
bool tmpMark = false;
if (index == 0)
{
return values[0 + tmpIndexOffset] == keyValue;
}
if (index == 1)
{
return values[1 + tmpIndexOffset] == keyValue;
}
if (index == 2)
{
return values[2 + tmpIndexOffset] == keyValue;
}
if (index == 3)
{
return values[3 + tmpIndexOffset] == keyValue;
}
if (index == 4)
{
return values[4 + tmpIndexOffset] == keyValue;
}
if (index == 5)
{
return values[5 + tmpIndexOffset] == keyValue;
}
List<string> rotationSourceList = null;
if (!VaildUtil.TryConvert(values, 6 + tmpIndexOffset, 1, out rotationSourceList, out skipCount))
{
throw new Exception("Error on check config is exist");
}
for (int i = 0; i < rotationSourceList.Count; i += 3)
{
if (index == 6)
{
tmpMark = true;
if (rotationSourceList[0 + i] == keyValue)
{
return true;
}
}
if (index == 7)
{
tmpMark = true;
if (rotationSourceList[1 + i] == keyValue)
{
return true;
}
}
if (index == 8)
{
tmpMark = true;
if (rotationSourceList[2 + i] == keyValue)
{
return true;
}
}
}
if (tmpMark)
{
return false;
}
tmpIndexOffset += skipCount;
List<string> attachNamePositionSourceList = null;
if (!VaildUtil.TryConvert(values[7 + tmpIndexOffset], 0, out attachNamePositionSourceList, out skipCount))
{
throw new Exception("Error on check config is exist");
}
if (index == 9)
{
for (int i = 0; i < attachNamePositionSourceList.Count; ++i)
{
if (attachNamePositionSourceList[i] == keyValue)
{
return true;
}
}
return false;
}
tmpIndexOffset += skipCount;
List<string> audioSourceSourceList = null;
if (!VaildUtil.TryConvert(values, 8 + tmpIndexOffset, 0, out audioSourceSourceList, out skipCount))
{
throw new Exception("Error on check config is exist");
}
for (int i = 0; i < audioSourceSourceList.Count; i += 1)
{
if (index == 10)
{
tmpMark = true;
if (audioSourceSourceList[0 + i] == keyValue)
{
return true;
}
}
}
if (tmpMark)
{
return false;
}
tmpIndexOffset += skipCount;
return false;
}
}<file_sep>using Util;
using System.Collections.Generic;
using System;
public class testTableConfigParser
{
private string m_strErrorMsg;
public string GetErrorMsg()
{
return m_strErrorMsg;
}
public List<testTableConfig> ParserConfig(string[][] content)
{
List<testTableConfig> resultConfigTable = new List<testTableConfig>();
for (int i = 0; i < content.Length; ++i)
{
resultConfigTable.Add(ParserLine(i, content[i]));
if (!string.IsNullOrEmpty(m_strErrorMsg))
{
return null;
}
}
return resultConfigTable;
}
private testTableConfig ParserLine(int lineIndex, string[] values)
{
int tmpIndexOffset = 0;
int skipCount = 0;
testTableConfig configLineElement = new testTableConfig();
if (!VaildUtil.TryConvert(values[0 + tmpIndexOffset], out configLineElement.id,0,100))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,0+1, values[0 + tmpIndexOffset],0,100,"int","id");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[0 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 ,values[0 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,0+1, values[0 + tmpIndexOffset],"","id");
return null;
}
if (!VaildUtil.TryConvert(values[1 + tmpIndexOffset], out configLineElement.name,null,null))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,1+1, values[1 + tmpIndexOffset],null,null,"string","name");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[1 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 ,values[1 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,1+1, values[1 + tmpIndexOffset],"","name");
return null;
}
if (!VaildUtil.TryConvert(values[2 + tmpIndexOffset], out configLineElement.costId,int.MinValue,int.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,2+1, values[2 + tmpIndexOffset],int.MinValue,int.MaxValue,"int","constId");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[2 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 ,values[2 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,2+1, values[2 + tmpIndexOffset],"","constId");
return null;
}
configLineElement.position = new testTableConfig.positionClass();
if (!VaildUtil.TryConvert(values[3 + tmpIndexOffset], out configLineElement.position.x,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,3+1, values[3 + tmpIndexOffset],double.MinValue,double.MaxValue,"double","x");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[3 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 ,values[3 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,3+1, values[3 + tmpIndexOffset],"","x");
return null;
}
if (!VaildUtil.TryConvert(values[4 + tmpIndexOffset], out configLineElement.position.y,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,4+1, values[4 + tmpIndexOffset],double.MinValue,double.MaxValue,"double","y");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[4 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 ,values[4 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,4+1, values[4 + tmpIndexOffset],"","y");
return null;
}
if (!VaildUtil.TryConvert(values[5 + tmpIndexOffset], out configLineElement.position.z,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,5+1, values[5 + tmpIndexOffset],double.MinValue,double.MaxValue,"double","z");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[5 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 ,values[5 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,5+1, values[5 + tmpIndexOffset],"","z");
return null;
}
configLineElement.nameMessageId = new testTableConfig.nameMessageIdClass();
if (!VaildUtil.TryConvert(values[6 + tmpIndexOffset], out configLineElement.nameMessageId.id,int.MinValue,int.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,6+1, values[6 + tmpIndexOffset],int.MinValue,int.MaxValue,"int","id");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, values[6 + tmpIndexOffset] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 ,values[6 + tmpIndexOffset]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,6+1, values[6 + tmpIndexOffset],"","id");
return null;
}
List<string> textureNameSourceList = null;
if (!VaildUtil.TryConvert(values,7 + tmpIndexOffset, 0, out textureNameSourceList , out skipCount))
{
m_strErrorMsg = string.Format("{0}.xlsx [{1},{2}]数组解析读取出现错误", "testTableConfig", lineIndex,7+1);
return null;
}
var textureNameTmpList = new List<string>();
for(int i=0;i<textureNameSourceList.Count;++i)
{
string subElement;
if (!VaildUtil.TryConvert(textureNameSourceList[i], out subElement,null,null))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]数组解析读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,i+1, textureNameSourceList[i],null,null,"string","textureName");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, textureNameSourceList[i] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 , textureNameSourceList[i]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,i+1, textureNameSourceList[i],"","textureName");
return null;
}
textureNameTmpList.Add(subElement);
}
configLineElement.textureName = textureNameTmpList.ToArray();
tmpIndexOffset += skipCount;
List<string> vector4SourceList = null;
if (!VaildUtil.TryConvert(values,8 + tmpIndexOffset, 1,out vector4SourceList ,out skipCount))
{
m_strErrorMsg = string.Format("{0}.xlsx [{1},{2}]数组解析读取出现错误", "testTableConfig", lineIndex,8+1);
return null;
}
var vector4TmpList = new List<testTableConfig.vector4Class>();
for(int i=0;i<vector4SourceList.Count;i += 4)
{
int startIndex = i;
var vector4Element = new testTableConfig.vector4Class();
vector4TmpList.Add(vector4Element);
if (!VaildUtil.TryConvert(vector4SourceList[0 + startIndex], out vector4Element.x,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,0+1, vector4SourceList[0 + startIndex],double.MinValue,double.MaxValue,"double","x");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, vector4SourceList[0 + startIndex] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 , vector4SourceList[0 + startIndex]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,0+1, vector4SourceList[0 + startIndex],"","x");
return null;
}
if (!VaildUtil.TryConvert(vector4SourceList[1 + startIndex], out vector4Element.y,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,1+1, vector4SourceList[1 + startIndex],double.MinValue,double.MaxValue,"double","y");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, vector4SourceList[1 + startIndex] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 , vector4SourceList[1 + startIndex]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,1+1, vector4SourceList[1 + startIndex],"","y");
return null;
}
if (!VaildUtil.TryConvert(vector4SourceList[2 + startIndex], out vector4Element.z,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,2+1, vector4SourceList[2 + startIndex],double.MinValue,double.MaxValue,"double","z");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, vector4SourceList[2 + startIndex] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 , vector4SourceList[2 + startIndex]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,2+1, vector4SourceList[2 + startIndex],"","z");
return null;
}
if (!VaildUtil.TryConvert(vector4SourceList[3 + startIndex], out vector4Element.w,double.MinValue,double.MaxValue))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,3+1, vector4SourceList[3 + startIndex],double.MinValue,double.MaxValue,"double","w");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, vector4SourceList[3 + startIndex] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 , vector4SourceList[3 + startIndex]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,3+1, vector4SourceList[3 + startIndex],"","w");
return null;
}
}
configLineElement.vector4 = vector4TmpList.ToArray();
tmpIndexOffset += skipCount;
List<string> packageSourceList = null;
if (!VaildUtil.TryConvert(values,9 + tmpIndexOffset, 0,out packageSourceList ,out skipCount))
{
m_strErrorMsg = string.Format("{0}.xlsx [{1},{2}]数组解析读取出现错误", "testTableConfig", lineIndex,9+1);
return null;
}
var packageTmpList = new List<testTableConfig.packageClass>();
for(int i=0;i<packageSourceList.Count;i += 1)
{
int startIndex = i;
var packageElement = new testTableConfig.packageClass();
packageTmpList.Add(packageElement);
if (!VaildUtil.TryConvert(packageSourceList[0 + startIndex], out packageElement.packageName,null,null))
{
m_strErrorMsg = string.Format("{7} {0}.xlsx [{1},{2}]读取出现错误,{3}必须为{4} - {5} {6}型", "testTableConfig", lineIndex,0+1, packageSourceList[0 + startIndex],null,null,"string","packageName");
return null;
}
if (!VaildUtil.CheckIsDefaultValue(false, packageSourceList[0 + startIndex] ,"") &&
!VaildUtil.CheckRefrenceConfig("", 0 , packageSourceList[0 + startIndex]))
{
m_strErrorMsg = string.Format("{5} {0}.xlsx [{1},{2}]读取出现错误,{3}在{4}中没找到", "testTableConfig", lineIndex,0+1, packageSourceList[0 + startIndex],"","packageName");
return null;
}
}
configLineElement.package = packageTmpList.ToArray();
tmpIndexOffset += skipCount;
return configLineElement;
}
public bool CheckIsConfigExistKey(string[][] content, int index, string keyValue)
{
for (int i = 0; i < content.Length; ++i)
{
if (CheckIsConfigExistKey(content[i], index, keyValue))
{
return true;
}
}
return false;
}
public bool CheckIsConfigExistKey(string[] values, int index, string keyValue)
{
int tmpIndexOffset = 0;
int skipCount = 0;
bool tmpMark = false;
if (index == 0)
{
return values[0 + tmpIndexOffset] == keyValue;
}
if (index == 1)
{
return values[1 + tmpIndexOffset] == keyValue;
}
if (index == 2)
{
return values[2 + tmpIndexOffset] == keyValue;
}
if (index == 3)
{
return values[3 + tmpIndexOffset] == keyValue;
}
if (index == 4)
{
return values[4 + tmpIndexOffset] == keyValue;
}
if (index == 5)
{
return values[5 + tmpIndexOffset] == keyValue;
}
if (index == 6)
{
return values[6 + tmpIndexOffset] == keyValue;
}
List<string> textureNameSourceList = null;
if (!VaildUtil.TryConvert(values[7 + tmpIndexOffset], 0, out textureNameSourceList, out skipCount))
{
throw new Exception("Error on check config is exist");
}
if (index == 7)
{
for (int i = 0; i < textureNameSourceList.Count; ++i)
{
if (textureNameSourceList[i] == keyValue)
{
return true;
}
}
return false;
}
tmpIndexOffset += skipCount;
List<string> vector4SourceList = null;
if (!VaildUtil.TryConvert(values, 8 + tmpIndexOffset, 1, out vector4SourceList, out skipCount))
{
throw new Exception("Error on check config is exist");
}
for (int i = 0; i < vector4SourceList.Count; i += 4)
{
if (index == 8)
{
tmpMark = true;
if (vector4SourceList[0 + i] == keyValue)
{
return true;
}
}
if (index == 9)
{
tmpMark = true;
if (vector4SourceList[1 + i] == keyValue)
{
return true;
}
}
if (index == 10)
{
tmpMark = true;
if (vector4SourceList[2 + i] == keyValue)
{
return true;
}
}
if (index == 11)
{
tmpMark = true;
if (vector4SourceList[3 + i] == keyValue)
{
return true;
}
}
}
if (tmpMark)
{
return false;
}
tmpIndexOffset += skipCount;
List<string> packageSourceList = null;
if (!VaildUtil.TryConvert(values, 9 + tmpIndexOffset, 0, out packageSourceList, out skipCount))
{
throw new Exception("Error on check config is exist");
}
for (int i = 0; i < packageSourceList.Count; i += 1)
{
if (index == 12)
{
tmpMark = true;
if (packageSourceList[0 + i] == keyValue)
{
return true;
}
}
}
if (tmpMark)
{
return false;
}
tmpIndexOffset += skipCount;
return false;
}
}<file_sep>using ExcelImproter.Framework.Reader;
using ExcelImproter.Project;
using System;
using System.Collections.Generic;
public partial class ConfigHandler_testTableConfig : ConfigHandlerBase
{
public override string HandleConfig(ExcelData content)
{
var sourcedata = content.GetMergedContent();
testTableConfigParser parser = new testTableConfigParser();
var data = parser.ParserConfig(sourcedata);
if (!string.IsNullOrEmpty(parser.GetErrorMsg()))
{
return parser.GetErrorMsg();
}
return ParserData(data);
}
public override bool CheckRefrenceConfig(ExcelData content, int id, string keyValue)
{
var sourcedata = content.GetMergedContent();
testTableConfigParser parser = new testTableConfigParser();
return parser.CheckIsConfigExistKey(sourcedata, id, keyValue);
}
private string ParserData(List<testTableConfig> data)
{
throw new NotImplementedException();
}
}
|
af6233a25e5a167c0d88c43b5d09275cc84f13f5
|
[
"C#"
] | 5 |
C#
|
Blizzardx/ConfigCenterDemo-Windows
|
6405f84d89bbe8fa0ba4dab9f6ee9b15ec69cb05
|
7dd9580e885219d4f94398bac96a5d8e5291c301
|
refs/heads/master
|
<repo_name>rrohit20/Accionlabs<file_sep>/AccionLabs/ext-modules/alMenu/alMenuDirective.js
"use strict";
angular.module('alMenu').directive('alMenu', ['$timeout', function ($timeout) {
return {
scope: {
},
transclude: true,
templateUrl: 'ext-modules/alMenu/alMenuTemplate.html',
controller: 'alMenuController',
link: function (scope, el, attr) {
var item = el.find('.al-selectable-item:first');
$timeout(function () {
item.trigger('click');
});
}
};
}]);<file_sep>/AccionLabs/ext-modules/alFramework/alFrameworkModule.js
"use strict";
angular.module("alFramework", ["alMenu", "alDashboard"]);
<file_sep>/AccionLabs/ext-modules/alFramework/alFrameworkDirective.js
"use strict";
angular.module("alFramework").directive("alFramework", function () {
return {
transclude: true,
scope: {
title: '@',
subtitle: '@',
iconFile: '@'
},
controller: "alFrameworkController",
templateUrl: "ext-modules/alFramework/alFrameworkTemplate.html"
};
});
|
eb3ccfbc4261b0d30504bd3c0a90d17d47ffbc73
|
[
"JavaScript"
] | 3 |
JavaScript
|
rrohit20/Accionlabs
|
81b496de6fe130e69c153851fb431b36db0742f2
|
e6066d4212c20adb83457a5cf493ff3972a51254
|
refs/heads/master
|
<repo_name>thejones/feathers-generator<file_sep>/src/utils/exists.js
import fs from 'fs-extra';
export default fs.existsSync || function existsSync(filePath){
try {
fs.statSync(filePath);
}
catch(error) {
if (error.code == 'ENOENT') {
return false;
}
}
return true;
};<file_sep>/src/app/middleware/dotfiles.js
export default function(options) {
return function dotfiles(files, metalsmith, done){
const meta = metalsmith.metadata();
if (meta.options.linter !== 'jshint') {
delete files['.jshintrc'];
}
if (meta.options.linter !== 'eslint') {
delete files['.eslintrc'];
delete files['.eslintignore'];
}
if (!meta.options.babel) {
delete files['.babelrc'];
}
done();
};
};
|
031f4a3a432d84df989a75b8053d5e4f1a78274b
|
[
"JavaScript"
] | 2 |
JavaScript
|
thejones/feathers-generator
|
b521f097dccb03ab32ccc1c9647c89bd8bf2e47d
|
4addf08f524ece2e50e387b3ecaf8cd22a358704
|
refs/heads/master
|
<repo_name>nfjdu/Flutter_Redux_Gen<file_sep>/CHANGELOG.md
# Change Log
All notable changes to the "flutter-redux-gen" extension will be documented in this file.
Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.
## [Unreleased]
## [2.0.0] - 2020-09-26
- Create Parent Set
- Auto Import Set to Parent Set
## [1.0.2] - 2020-09-14
- Reducer import updated.
## [1.0.1] - 2020-09-13
- How to Use Gifs added.
## [1.0.0] - 2020-09-13
- Create Redux Set (Folder with action, middleware, reducer and state)
- Create Middleware
- Create Action
## [0.0.3] - 2020-09-09
- Create Reducer
## [0.0.2] - 2020-09-08
- Create State bugs fixed
- State name can't name any special chanracter other than "_"
- State creation loading and error variable added defaultly.
- State Name bug fixed.
## [0.0.1] - 2020-09-08
- Initial release
<file_sep>/src/resources/utils/storage.ts
import * as vscode from 'vscode';
function _saveParentSet(fPath: string, name: string, context: vscode.ExtensionContext) {
context.workspaceState.update("PARENT_PATH", fPath);
context.workspaceState.update("PARENT_NAME", name);
}
function _clearParentSet(context: vscode.ExtensionContext) {
context.workspaceState.update("PARENT_PATH", undefined);
context.workspaceState.update("PARENT_NAME", undefined);
}
function _getParentPath(context: vscode.ExtensionContext): string {
return context.workspaceState.get("PARENT_PATH") as string;
}
function _getParentName(context: vscode.ExtensionContext): string {
return context.workspaceState.get("PARENT_NAME") as string;
}
export var saveParentSet = _saveParentSet;
export var clearParentSet = _clearParentSet;
export var getParentPath = _getParentPath;
export var getParentName = _getParentName;<file_sep>/README.md
[![logo][]][AUTHOR]
[](https://discord.gg/KYPkhEx)
## Introduction
This is the VS Code Extension to generate Redux Code (State, Reducer, Middleware and Action).
I am Lazy Freelance Flutter Developer who doesn't wanna create redux files repeatedly. That's why I am building this extension to solve this problem.
## Article
Refer the article to know about the extension.
[Generate Redux State, reducer, action, and Middleware via VS Code Extension - Medium](https://medium.com/@androbalamail/generate-redux-state-reducer-action-and-middleware-via-vs-code-extension-flutter-redux-gen-54e1defee2bd)
## Features
1. Create Parent Set
2. Create Set (folder with state, reducer, middleware and action files)
3. Create State
4. Create Reducer
5. Create Middleware
6. Create Action
## How to Use
| Create Parent Set | Create Set |
| :----: | :----: |
| [![create_parent_set_gif][]][create_parent_set_gif] | [![create_set_gif][]][create_set_gif] |
| Create State | Create Reducer |
| :----: | :----: |
| [![create_state_gif][]][create_state_gif] | [![create_reducer_gif][]][generate_reducer_youtube] |
| Create Middleware | Create Action |
| :----: | :----: |
| [![create_middleware_gif][]][generate_middleware_youtube] | [![create_action_gif][]][generate_action_youtube] |
## Special Words Explanations ( Ex: Set, Auto Import)
| Special Words | Description |
| :---- | :---- |
| Set | A folder containes Action, Middleware, Reducer and State files. |
| Parent Set | Its a parent of all Set. Its configured by Us as a parent |
| Auto Import | When you create a set it will automatically imported to Parent Set |
## Youtube PlayList
[Flutter Redux Gen Youtube][flg_youtube_playlist]
## Contact
[Click here to add you comments and feedback][contact]
[logo]: https://raw.githubusercontent.com/BalaDhruv/Flutter_Redux_Gen/master/media/flutter_redux_gen_logo_with_name.png
[author]: https://balamurugan.dev/
[contact]: https://forms.gle/wXPgEEAYvczjWwys8
[create_parent_set_gif]: https://raw.githubusercontent.com/BalaDhruv/Flutter_Redux_Gen/master/media/demo/create-parent-set.gif
[create_set_gif]: https://raw.githubusercontent.com/BalaDhruv/Flutter_Redux_Gen/master/media/demo/create-redux-set.gif
[create_state_gif]: https://raw.githubusercontent.com/BalaDhruv/Flutter_Redux_Gen/master/media/demo/create-state.gif
[create_reducer_gif]: https://raw.githubusercontent.com/BalaDhruv/Flutter_Redux_Gen/master/media/demo/create-reducer.gif
[create_middleware_gif]: https://raw.githubusercontent.com/BalaDhruv/Flutter_Redux_Gen/master/media/demo/create-middleware.gif
[create_action_gif]: https://raw.githubusercontent.com/BalaDhruv/Flutter_Redux_Gen/master/media/demo/create-action.gif
[generate_state_youtube]: https://www.youtube.com/watch?v=vnqoh8owWfI
[generate_reducer_youtube]: https://www.youtube.com/watch?v=JuCVdc-MWRM
[generate_middleware_youtube]: https://www.youtube.com/watch?v=9-Ky7X2DW6Q
[generate_action_youtube]: https://www.youtube.com/watch?v=F7Zk6VMqkFk
[generate_set_youtube]: https://www.youtube.com/watch?v=aOMU4OHpoWw
[flg_youtube_playlist]: https://www.youtube.com/watch?v=ISRztcuk2lg&list=PLAtrbE9cCxChjH_1A9mW3qlfBrzlfQk5W
<file_sep>/src/resources/gen/parent_set.ts
import { getFormattedReducerName, getFormattedStateName } from "../utils/utils";
import * as fs from 'fs';
import { REDUCER_EXTENSION, STATE_EXTENSION } from "../utils/constants";
function _getParentSetStateCode(name: string) {
const sName = getFormattedStateName(name);
return `
import 'package:flutter/material.dart';
class ${sName}State {
${sName}State();
factory ${sName}State.initial() => ${sName}State();
@override
bool operator ==(other) =>
identical(this, other) ||
other is ${sName}State &&
runtimeType == other.runtimeType;
@override
int get hashCode =>
super.hashCode;
@override
String toString() {
return "${sName}State { }";
}
}
`;
}
function _getParentSetReducerCode(name: string) {
const sName = getFormattedStateName(name);
const rName = getFormattedReducerName(name);
return `
import './${name}.state.dart';
${sName}State ${rName}Reducer(${sName}State state, action) => ${sName}State();
`;
}
function _getParentSetMiddlewareCode(name: string) {
const rName = getFormattedReducerName(name);
const sName = getFormattedStateName(name);
return `
import 'package:redux/redux.dart';
import './${name}.state.dart';
List<Middleware<${sName}State>> ${rName}Middleware() {
// final Middleware<${sName}State> _login = login(_repo);
return [
// TypedMiddleware<${sName}State, LoginAction>(_login),
];
}
`;
}
function _addSetToParent(name: string, path: string, parentName: string, parentPath: string) {
_addVarToState(name, path, parentName, parentPath);
_addToReducer(name, path, parentName, parentPath);
}
function _addToReducer(name: string, path: string, parentName: string, parentPath: string) {
const sName = getFormattedStateName(name) + 'State';
const sVarName = getFormattedReducerName(sName);
const rVarName = getFormattedReducerName(name) + 'Reducer';
const parentStateName = getFormattedStateName(parentName) + 'State';
// Read Reducer File
const parentFileName = parentPath + '/' + parentName + REDUCER_EXTENSION;
const parentStateCodeList = fs.readFileSync(parentFileName, 'utf8').split('\n');
var updatedStateCodeList: string[] = parentStateCodeList;
// Add Import Statement
const currentStateFilePath = `${path}/${name}/${name}${REDUCER_EXTENSION}`;
const importCurStatePath = '.' + currentStateFilePath.substr(parentPath.length);
const stateImportText = `import '${importCurStatePath}';`;
updatedStateCodeList = [stateImportText, ...updatedStateCodeList];
// Add Reducer Code
const reducerFindText = `${parentStateName}(`;
if (updatedStateCodeList.findIndex(value => value.includes(reducerFindText)) > -1) {
const initVarText = `${sVarName}: ${rVarName}(state.${sVarName}, action),`;
const classIndex = updatedStateCodeList.findIndex(value => value.includes(reducerFindText));
const textIndex = updatedStateCodeList[classIndex].indexOf(reducerFindText) + reducerFindText.length;
updatedStateCodeList[classIndex] = updatedStateCodeList[classIndex].slice(0, textIndex) + initVarText + updatedStateCodeList[classIndex].slice(textIndex);
}
// Write Updated Code to Parent File
fs.writeFileSync(parentFileName, updatedStateCodeList.join('\n'));
}
function _addVarToState(name: string, path: string, parentName: string, parentPath: string) {
const sName = getFormattedStateName(name) + 'State';
const sVarName = getFormattedReducerName(sName);
const parentStateName = getFormattedStateName(parentName) + 'State';
let hasConstructor = false;
// Read State File
const parentFileName = parentPath + '/' + parentName + STATE_EXTENSION;
const parentStateCodeList = fs.readFileSync(parentFileName, 'utf8').split('\n');
var updatedStateCodeList: string[] = parentStateCodeList;
// Add Import Statement
const currentStateFilePath = `${path}/${name}/${name}${STATE_EXTENSION}`;
const importCurStatePath = '.' + currentStateFilePath.substr(parentPath.length);
const stateImportText = `import '${importCurStatePath}';`;
updatedStateCodeList = [stateImportText, ...updatedStateCodeList];
// Add Varibale to state
if (updatedStateCodeList.findIndex(value => value.includes(`class ${parentStateName}`)) > -1) {
const initVarText = `final ${sName} ${sVarName};`;
const classIndex = updatedStateCodeList.findIndex(value => value.includes(`class ${parentStateName}`)) + 1;
updatedStateCodeList = [...updatedStateCodeList.slice(0, classIndex), initVarText, ...updatedStateCodeList.slice(classIndex)];
}
// Add Variable to constructor
if (updatedStateCodeList.findIndex(value => value.includes(`${parentStateName}({`)) > -1 || updatedStateCodeList.findIndex(value => value.includes(`${parentStateName}(`))) {
hasConstructor = true;
let initConsVarText = `this.${sVarName},`;
let consSearchString = `${parentStateName}(`;
if (updatedStateCodeList.findIndex(value => value.includes(`${parentStateName}({`)) > -1) {
initConsVarText = `@required this.${sVarName},`;
consSearchString = `${parentStateName}({`;
} else if (updatedStateCodeList.findIndex(value => value.includes(`${parentStateName}(`))) {
initConsVarText = `{ @required this.${sVarName} }`;
}
const indexOfLine = updatedStateCodeList.findIndex(value => value.includes(`${parentStateName}(`));
const indexOfinsertPosition = updatedStateCodeList[indexOfLine].indexOf(consSearchString) + consSearchString.length;
const consStr: string = updatedStateCodeList[indexOfLine];
updatedStateCodeList[indexOfLine] = consStr.slice(0, indexOfinsertPosition) + initConsVarText + consStr.slice(indexOfinsertPosition);
}
// Add Variable to factory Method
if (hasConstructor) {
const initialVarText = `${sVarName}: ${sName}.initial(),`;
const indexOfInitialMethodLine = updatedStateCodeList.findIndex(value => value.includes(`=> ${parentStateName}(`));
const indexOfInitialInsert = updatedStateCodeList[indexOfInitialMethodLine].indexOf(`${parentStateName}(`) + parentStateName.length + 1;
updatedStateCodeList[indexOfInitialMethodLine] = updatedStateCodeList[indexOfInitialMethodLine].slice(0, indexOfInitialInsert) + initialVarText + updatedStateCodeList[indexOfInitialMethodLine].slice(indexOfInitialInsert);
}
// Add Var to Operator Method
const operatorText = ` && ${sVarName} == other.${sVarName} `;
const operatorFinderText = 'other.runtimeType';
if (updatedStateCodeList.findIndex(value => value.includes(operatorFinderText))) {
const lineIndexOperator = updatedStateCodeList.findIndex(value => value.includes(operatorFinderText));
const indexInsert = updatedStateCodeList[lineIndexOperator].indexOf(operatorFinderText) + operatorFinderText.length;
updatedStateCodeList[lineIndexOperator] = updatedStateCodeList[lineIndexOperator].slice(0, indexInsert) + operatorText + updatedStateCodeList[lineIndexOperator].slice(indexInsert);
}
// Add Var to HashCode Methode
const hascodeText = ` ^ ${sVarName}.hashCode `;
const hascodeFinderText = 'super.hashCode';
if (updatedStateCodeList.findIndex(value => value.includes(hascodeFinderText))) {
const lineIndexHashcode = updatedStateCodeList.findIndex(value => value.includes(hascodeFinderText));
const indexOfHashcodeStr = updatedStateCodeList[lineIndexHashcode].indexOf(hascodeFinderText) + hascodeFinderText.length;
updatedStateCodeList[lineIndexHashcode] = updatedStateCodeList[lineIndexHashcode].slice(0, indexOfHashcodeStr) + hascodeText + updatedStateCodeList[lineIndexHashcode].slice(indexOfHashcodeStr);
}
// Add Var to TOSTRING Method
const toStringText = ` ${sVarName}: $${sVarName}`;
const toStringFinderText = `"${parentStateName} {`;
if (updatedStateCodeList.findIndex(value => value.includes(toStringFinderText))) {
const toStringLineIndex = updatedStateCodeList.findIndex(value => value.includes(toStringFinderText));
const toStringInsertIndex = updatedStateCodeList[toStringLineIndex].indexOf(toStringFinderText) + toStringFinderText.length;
updatedStateCodeList[toStringLineIndex] = updatedStateCodeList[toStringLineIndex].slice(0, toStringInsertIndex) + toStringText + updatedStateCodeList[toStringLineIndex].slice(toStringInsertIndex);
}
// Write Updated Code to Parent File
fs.writeFileSync(parentFileName, updatedStateCodeList.join('\n'));
}
export var getParentSetStateCode = _getParentSetStateCode;
export var getParentSetReducerCode = _getParentSetReducerCode;
export var getParentSetMiddlewareCode = _getParentSetMiddlewareCode;
export var addSetToParent = _addSetToParent;
<file_sep>/src/extension.ts
import * as vscode from 'vscode';
import { CREATE_STATE_PLACE_HOLDER, NAME_ERROR_MESSAGE, CREATE_ACTION_PLACE_HOLDER, CREATE_MIDDLEWARE_PLACE_HOLDER, CREATE_REDUCER_PLACE_HOLDER, NAME_REG_EXP, DEFAULT_NAME, STATE_EXTENSION, REDUCER_EXTENSION, MIDDLEWARE_EXTENSION, ACTION_EXTENSION } from './resources/utils/constants';
import { getStateGenCode } from './resources/gen/state';
import { getFilePath } from './resources/utils/utils';
import { getReducerGenCode } from './resources/gen/reducer';
import { getMiddlewareGenCode } from './resources/gen/middleware';
import { getActionGenCode } from './resources/gen/action';
import { createFile, createFolder, isParentSetExist } from './resources/utils/file-utils';
import { getParentName, getParentPath, saveParentSet } from './resources/utils/storage';
import { addSetToParent, getParentSetMiddlewareCode, getParentSetReducerCode, getParentSetStateCode } from './resources/gen/parent_set';
import * as fs from 'fs';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext): void {
// Create State Command Registering
let createState = vscode.commands.registerCommand('flutter-redux-gen.createState', (args) => {
let focusedFilePath = getFilePath(args.path);
let nameField = vscode.window.createInputBox();
let nameFieldValidator = new RegExp(NAME_REG_EXP);
if (isParentSetExist(context)) {
nameField.prompt = "🥳👍 Parent Set Found.";
} else {
nameField.prompt = "🚫 Parent Set Found.";
}
nameField.placeholder = CREATE_STATE_PLACE_HOLDER;
nameField.onDidChangeValue((v) => {
nameField.validationMessage = nameFieldValidator.test(v) ? NAME_ERROR_MESSAGE : '';
});
nameField.onDidAccept(() => {
if (nameFieldValidator.test(nameField.value)) {
nameField.validationMessage = NAME_ERROR_MESSAGE;
} else {
nameField.hide();
var name = nameField.value ? nameField.value : DEFAULT_NAME;
createFile(focusedFilePath, name, STATE_EXTENSION, getStateGenCode, true);
nameField.validationMessage = '';
}
});
nameField.show();
});
context.subscriptions.push(createState);
// Create State Command Registering
let createReducer = vscode.commands.registerCommand('flutter-redux-gen.createReducer', (args) => {
let focusedFilePath = getFilePath(args.path);
let nameField = vscode.window.createInputBox();
let nameFieldValidator = new RegExp(NAME_REG_EXP);
if (isParentSetExist(context)) {
nameField.prompt = "🥳👍 Parent Set Found.";
} else {
nameField.prompt = "🚫 Parent Set Found.";
}
nameField.placeholder = CREATE_REDUCER_PLACE_HOLDER;
nameField.onDidChangeValue((v) => {
nameField.validationMessage = nameFieldValidator.test(v) ? NAME_ERROR_MESSAGE : '';
});
nameField.onDidAccept(() => {
if (nameFieldValidator.test(nameField.value)) {
nameField.validationMessage = NAME_ERROR_MESSAGE;
} else {
nameField.hide();
var name = nameField.value ? nameField.value : DEFAULT_NAME;
createFile(focusedFilePath, name, REDUCER_EXTENSION, getReducerGenCode, true);
nameField.validationMessage = '';
}
});
nameField.show();
});
context.subscriptions.push(createReducer);
// Create State Command Registering
let createMiddleware = vscode.commands.registerCommand('flutter-redux-gen.createMiddleware', (args) => {
let focusedFilePath = getFilePath(args.path);
let nameField = vscode.window.createInputBox();
let nameFieldValidator = new RegExp(NAME_REG_EXP);
if (isParentSetExist(context)) {
nameField.prompt = "🥳👍 Parent Set Found.";
} else {
nameField.prompt = "🚫 Parent Set Found.";
}
nameField.placeholder = CREATE_MIDDLEWARE_PLACE_HOLDER;
nameField.onDidChangeValue((v) => {
nameField.validationMessage = nameFieldValidator.test(v) ? NAME_ERROR_MESSAGE : '';
});
nameField.onDidAccept(() => {
if (nameFieldValidator.test(nameField.value)) {
nameField.validationMessage = NAME_ERROR_MESSAGE;
} else {
nameField.hide();
var name = nameField.value ? nameField.value : DEFAULT_NAME;
createFile(focusedFilePath, name, MIDDLEWARE_EXTENSION, getMiddlewareGenCode, true);
nameField.validationMessage = '';
}
});
nameField.show();
});
context.subscriptions.push(createMiddleware);
// Create State Command Registering
let createAction = vscode.commands.registerCommand('flutter-redux-gen.createAction', (args) => {
let focusedFilePath = getFilePath(args.path);
let nameField = vscode.window.createInputBox();
let nameFieldValidator = new RegExp(NAME_REG_EXP);
if (isParentSetExist(context)) {
nameField.prompt = "🥳👍 Parent Set Found.";
} else {
nameField.prompt = "🚫 Parent Set Found.";
}
nameField.placeholder = CREATE_ACTION_PLACE_HOLDER;
nameField.onDidChangeValue((v) => {
nameField.validationMessage = nameFieldValidator.test(v) ? NAME_ERROR_MESSAGE : '';
});
nameField.onDidAccept(() => {
if (nameFieldValidator.test(nameField.value)) {
nameField.validationMessage = NAME_ERROR_MESSAGE;
} else {
nameField.hide();
var name = nameField.value ? nameField.value : DEFAULT_NAME;
createFile(focusedFilePath, name, ACTION_EXTENSION, getActionGenCode, true);
nameField.validationMessage = '';
}
});
nameField.show();
});
context.subscriptions.push(createAction);
// Create Redux Set Command Registering
let createReduxSet = vscode.commands.registerCommand('flutter-redux-gen.createReduxSet', (args) => {
let focusedFilePath = getFilePath(args.path);
let nameField = vscode.window.createInputBox();
let nameFieldValidator = new RegExp(NAME_REG_EXP);
nameField.placeholder = CREATE_ACTION_PLACE_HOLDER;
if (isParentSetExist(context)) {
nameField.prompt = "🥳👍 Parent Set Found.";
} else {
nameField.prompt = "🚫 Parent Set Found.";
}
nameField.onDidChangeValue((v) => {
nameField.validationMessage = nameFieldValidator.test(v) ? NAME_ERROR_MESSAGE : '';
});
nameField.onDidAccept(() => {
if (nameFieldValidator.test(nameField.value)) {
nameField.validationMessage = NAME_ERROR_MESSAGE;
} else {
nameField.hide();
var name = nameField.value ? nameField.value : DEFAULT_NAME;
var isCreated = createFolder(focusedFilePath, name);
if (isCreated) {
createFile(focusedFilePath + "/" + name, name, ACTION_EXTENSION, getActionGenCode, false);
createFile(focusedFilePath + "/" + name, name, REDUCER_EXTENSION, getReducerGenCode, false);
createFile(focusedFilePath + "/" + name, name, MIDDLEWARE_EXTENSION, getMiddlewareGenCode, false);
createFile(focusedFilePath + "/" + name, name, STATE_EXTENSION, getStateGenCode, false);
addSetToParent(name, focusedFilePath, getParentName(context), getParentPath(context));
vscode.window.showInformationMessage(name + ' Set Created.');
}
nameField.validationMessage = '';
}
});
nameField.show();
});
context.subscriptions.push(createReduxSet);
// Create Redux Set Command Registering
let createParentSet = vscode.commands.registerCommand('flutter-redux-gen.createParentSet', (args) => {
if (context.workspaceState.get("PARENT_PATH") && fs.existsSync(context.workspaceState.get("PARENT_PATH") as string)) {
vscode.window.showErrorMessage('Parent Set Already Exist');
} else {
let focusedFilePath = getFilePath(args.path);
let nameField = vscode.window.createInputBox();
let nameFieldValidator = new RegExp(NAME_REG_EXP);
nameField.placeholder = CREATE_ACTION_PLACE_HOLDER;
nameField.onDidChangeValue((v) => {
nameField.validationMessage = nameFieldValidator.test(v) ? NAME_ERROR_MESSAGE : '';
});
nameField.onDidAccept(() => {
if (nameFieldValidator.test(nameField.value)) {
nameField.validationMessage = NAME_ERROR_MESSAGE;
} else {
nameField.hide();
var name = nameField.value ? nameField.value : DEFAULT_NAME;
var isCreated = createFolder(focusedFilePath, 'store');
if (isCreated) {
createFile(focusedFilePath + "/store", name, REDUCER_EXTENSION, getParentSetReducerCode, false);
createFile(focusedFilePath + "/store", name, MIDDLEWARE_EXTENSION, getParentSetMiddlewareCode, false);
createFile(focusedFilePath + "/store", name, STATE_EXTENSION, getParentSetStateCode, false);
saveParentSet(focusedFilePath + "/store", name, context);
vscode.window.showInformationMessage(name + ' Parent Set Created.');
}
nameField.validationMessage = '';
}
});
nameField.show();
}
});
context.subscriptions.push(createParentSet);
}
// this method is called when your extension is deactivated
export function deactivate() {
}
<file_sep>/src/resources/gen/action.ts
import { getFormattedStateName } from "../utils/utils";
function _getActionGenCode(name: string) {
const sName = getFormattedStateName(name);
return `
import 'package:flutter/material.dart';
class ${sName}Action {
@override
String toString() {
return '${sName}Action { }';
}
}
class ${sName}SuccessAction {
final int isSuccess;
${sName}SuccessAction({@required this.isSuccess});
@override
String toString() {
return '${sName}SuccessAction { isSuccess: $isSuccess }';
}
}
class ${sName}FailedAction {
final String error;
${sName}FailedAction({@required this.error});
@override
String toString() {
return '${sName}FailedAction { error: $error }';
}
}
`;
}
export var getActionGenCode = _getActionGenCode;<file_sep>/src/resources/gen/reducer.ts
import { getFormattedReducerName, getFormattedStateName } from "../utils/utils";
function _getReducerGenCode(name: string) {
const rName = getFormattedReducerName(name);
const sName = getFormattedStateName(name);
return `
import 'package:redux/redux.dart';
import './${name}.state.dart';
final ${rName}Reducer = combineReducers<${sName}State>([
]);
`;
}
export var getReducerGenCode = _getReducerGenCode;<file_sep>/src/resources/gen/state.ts
import { getFormattedStateName } from "../utils/utils";
function _getStateGenCode(stateName: string) {
const sName = getFormattedStateName(stateName);
return `
class ${sName}State {
final bool loading;
final String error;
${sName}State(this.loading, this.error);
factory ${sName}State.initial() => ${sName}State(false, '');
${sName}State copyWith({bool loading, String error}) =>
${sName}State(loading ?? this.loading, error ?? this.error);
@override
bool operator ==(other) =>
identical(this, other) ||
other is ${sName}State &&
runtimeType == other.runtimeType &&
loading == other.loading &&
error == other.error;
@override
int get hashCode =>
super.hashCode ^ runtimeType.hashCode ^ loading.hashCode ^ error.hashCode;
@override
String toString() => "${sName}State { loading: $loading, error: $error}";
}
`;
}
export var getStateGenCode = _getStateGenCode;<file_sep>/src/resources/utils/utils.ts
import * as fs from 'fs';
function _getFormattedStateName(name: string) {
return name.split('_').map(word => word[0].toLocaleUpperCase() + word.substring(1)).join('');
}
function _getFormattedReducerName(name: string) {
return name.split('_').map(word => word[0].toLocaleLowerCase() + word.substring(1)).join('');
}
function _getFilePath(path: string) {
const syncPath = fs.statSync(path);
if (syncPath.isFile()) {
var paths = path.split('/');
paths.pop();
return paths.join('/');
}
return path;
}
export var getFormattedStateName = _getFormattedStateName;
export var getFormattedReducerName = _getFormattedReducerName;
export var getFilePath = _getFilePath;<file_sep>/src/resources/utils/file-utils.ts
import * as vscode from 'vscode';
import * as fs from 'fs';
import { clearParentSet } from './storage';
function _createFile(fPath: string, name: string, extention: string, getGenCode: Function, showInfo: boolean) {
const pathWithFileName = fPath + '/' + name.toLocaleLowerCase() + extention;
fs.writeFile(pathWithFileName, getGenCode(name), err => {
if (err) {
vscode.window.showInformationMessage('Please check your path. Otherwise file a issue in Git Repo. Let me help.');
} else if (showInfo) {
vscode.window.showInformationMessage(`${name}${extention} Created Successfully.`);
}
});
}
function _createFolder(fPath: string, name: string): boolean {
if (!fs.existsSync(fPath + "/" + name)) {
fs.mkdirSync(fPath + "/" + name);
return true;
} else {
vscode.window.showErrorMessage('Folder Already Exist');
return false;
}
}
function _isParentSetExist(context: vscode.ExtensionContext) {
if (context.workspaceState.get("PARENT_PATH") && fs.existsSync(context.workspaceState.get("PARENT_PATH") as string)) {
return true;
} else {
clearParentSet(context);
return false;
}
}
export var createFile = _createFile;
export var createFolder = _createFolder;
export var isParentSetExist = _isParentSetExist;<file_sep>/src/resources/utils/constants.ts
export const EXTENSION = '.dart';
export const STATE_EXTENSION = '.state.dart';
export const REDUCER_EXTENSION = '.reducer.dart';
export const MIDDLEWARE_EXTENSION = '.middleware.dart';
export const ACTION_EXTENSION = '.action.dart';
export const DEFAULT_NAME = 'default';
export const CREATE_STATE_PLACE_HOLDER = 'Enter State Name';
export const CREATE_REDUCER_PLACE_HOLDER = 'Enter Reducer Name';
export const CREATE_MIDDLEWARE_PLACE_HOLDER = 'Enter Middleware Name';
export const CREATE_ACTION_PLACE_HOLDER = 'Enter Action File Name';
export const NAME_ERROR_MESSAGE = 'Please use name without space. Consider using "_"';
export const NAME_REG_EXP = /[`0-9 ~!@#$%^&*()|+\-=?;:'",.<>\{\}\[\]\\\/]/;
<file_sep>/src/resources/gen/middleware.ts
import { getFormattedStateName } from "../utils/utils";
function _getMiddlewareGenCode(name: string) {
const sName = getFormattedStateName(name);
return `
import 'package:redux/redux.dart';
Middleware<AppState> get${sName}(Repository _repo) {
return (Store<AppState> store, action, NextDispatcher dispatch) async {
dispatch(action);
try {
// TODO: Write here your middleware logic and api calls
} catch (error) {
// TODO: API Error handling
print(error);
}
};
}
`;
}
export var getMiddlewareGenCode = _getMiddlewareGenCode;
|
1ad2af9d9054803f07f83c1e2e8e89b4e945a061
|
[
"Markdown",
"TypeScript"
] | 12 |
Markdown
|
nfjdu/Flutter_Redux_Gen
|
1534e81e7f73047acd0c2f2b8195e66ac7e44aa7
|
80a64f044f119d03f5333e99bacca149d12089ef
|
refs/heads/master
|
<repo_name>bernardoseven/Whatsapp<file_sep>/test/models/user_test.rb
require 'test_helper'
class UserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
# def setup gets run before each test.
def setup
@user = User.new(name: "Example User", email: "<EMAIL>",
password: "<PASSWORD>", password_confirmation: "<PASSWORD>") # required fields for has_secure_password
end
# Verifies if the user is valid.
test "should be valid" do
assert @user.valid?
end
test "should be present" do
@user.name = " " # assign an empty string.
assert_not @user.valid? # this ensures that a blank string is not valid.
end
# Equal to the above test.
test "should do something" do
@user.email = " "
assert_not @user.valid?
end
# ensures length name be <= 50 characters.
test "name should not be too long" do
@user.name = "a" * 51
assert_not @user.valid?
end
# ensures length email be database length compatible.
test "email should not be too long" do
@user.email = "a" * 256
assert_not @user.valid?
end
# here we want to make a user with the same email adrress as @user
# using @user.dup, wich creates a duplicate user with the same attributes. Since we
# then save the user, we have a duplicate user in the database, an should not be valid.
test "email addresses should be unique" do
duplicate_user = @user.dup
# line above upcase the email for skip problems like <EMAIL>, this
# is reflected in the user model as well.
duplicate_user.email = @user.email.upcase
@user.save
assert_not duplicate_user.valid?
end
# obvious code test
test "password should be present(non_blank)" do
@user.password = @user.password_confirmation = " " * 6
assert_not @user.valid?
end
# assuring minimum length of password
test "password should have a minimum length" do
@user.password = @user.password_confirmation = "a" * 5
assert_not @user.valid?
end
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy # ensures that microposts are
# destroyed if the user who did the microposts is destroyed.
# associates the user model with the micropost model.
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
# we create an accessible attribute.
attr_accessor :remember_token, :activation_token, :reset_token
before_save :downcase_email # Obvious behavior.
before_create :create_activation_digest
# Curly braces are optional when passing hashes as the final argument
# in a method.
# Parentheses on function calls are optional.
validates :name, presence: true, length: { maximum: 50 }
# the validates method is equivalent to
# validates (:name, presence: true).
validates :email, presence: true, length: { maximum: 255 },
uniqueness: { case_sensitive: false } # avoiding problems like <EMAIL>
has_secure_password # adds the ability to save a securily hashed password_digest
# attribute to the database. Additionally adds an authenticate method that returns the user
# when the password is correct.
validates :password, presence: true, length: { minimum: 6 } # validates password
# presence and length.
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token. If we use the console, and puts literally
# SecureRandom.urlsafe_base64, the console returns a random string that's almost
# imposible to be repeated with some other user's token.
def User.new_token
SecureRandom.urlsafe_base64
end
# remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = User.new_token # gives the unique hashed string to
# the current user.
update_attribute(:remember_digest, User.digest(remember_token)) # updates
# the remember digest.
end
# returns true if the given token matches the digest.
def authenticate?(remember_token)
return false if remember_digest.nil? # fix the problem with permanent sessions
# in different browsers.
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
# Returns true if the given token matches the digest.
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
# forgets a user. As always, the helper does the heavy work.
def forget
update_attribute(:remember_digest, nil)
end
# Activates an account.
def activate
update_attribute(:activated, true)
update_attribute(:activated_at, Time.zone.now)
end
# Sends activation email.
def send_activation_email
UserMailer.account_activation(self).deliver_now
end
# Sets the password reset attributes.
def create_reset_digest
self.reset_token = User.new_token
update_attribute(:reset_digest, User.digest(reset_token))
update_attribute(:reset_sent_at, Time.zone.now)
end
# Sends password reset email.
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
# Returns true if a password reset has expired.
def password_reset_expired?
reset_sent_at < 2.hours.ago
end
# Defines a proto-feed.
# See "Following users" for the full implementation.
# Returns a user's status feed.
def feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Micropost.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
end
# Follows a user.
def follow(other_user)
active_relationships.create(followed_id: other_user.id)
end
# Unfollows a user.
def unfollow(other_user)
active_relationships.find_by(followed_id: other_user.id).destroy
end
# Returns true if the current user is following the other user.
def following?(other_user)
following.include?(other_user)
end
private
# converts email to all lower case.
def downcase_email
self.email = email.downcase
end
# creates and assigns the activation token and digest.
def create_activation_digest
self.activation_token = User.new_token
self.activation_digest = User.digest(activation_token)
end
end
<file_sep>/README.md
MAGNIFICENT BOOK "Ruby on Rails
Tutorial" by <NAME>
**********************************
LAYOUT:
We can make an integration test to test if the links of the App are working
correctly.
This can be done typying the command: rails generate integration_test nameofyourchoice
This snippet test's the requirements explained above
test "layout links" do
get root_path
assert_template 'static_pages/home'
assert_select "a[href=?]", root_path, count: 2 "count:2 means that there must be
to link's to the root_path, for example, one in the logo and one anywhere else"
assert_select "a[href=?]", link2_path
assert_select "a[href=?]", link3_path
assert_select "a[href=?]", link4_path
end
Then, if we want to check the new test passes, we can run the integration test with
the command: bundle exec rake test:integration
USERS(To improve layout understanding):
rails generate controller Users new, generates a users controller with the new action
(def new end), a new.html.erb view, a users_test controller, etc.
However, we can arrange to asign a different html.erb file than users/new.html.erb to
whatever html.erb we want. For example, the new action, following the REST principle
will be to add a new user, but may we want associate a signup.html.erb url. We can
accomplish this in the routes.rb file simple by putting
the line: " get 'signup' => 'users#new' ".
**********************************
MODELING-USERS:
rails generate model User name:string email:string, generates a database table with two
string column's, name and email. Additionally creates an user_test.rb and user.rb model
file's, and a migration file THAT IS A WAY TO ALTER THE DATABASE INCREMENTALLY, so that
our data model can adapt to changing requirements
We can run the command: rake db:migrate to finish the proccess detailed above.
Migrations are reversible, at least most of them, with the simple command:
bundle exec rake db:rollback. In most case's when a developer has used the rollback command,
the migration's file can be migrated again with rake db:migrate.
To write a test for a vaild object, we will create an initially valid User model object
@user, using the special setup method, wich automatically gets run before each test.
Because @user is an instance variable, it's automatically available in all the tests.
The most elementary validation is presence, wich simple verifies that a given
attribute is present. Our user has name and email, so we are going to verify that both
attribute's are present writting tests.
Validations for format purposes, like that a given email have a valid email format
will be done after.
Regular Expressions Table:
Expression Meaning
/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i full regex
/ start of regex
\A match start of a string
[\w+\-.]+ at least one word character, plus, hyphen, or dot
@ literal “at sign”
[a-z\d\-.]+ at least one letter, digit, hyphen, or dot
\. literal dot
[a-z]+ at least one letter
\z match end of a string
/ end of regex
i case-insensitive
Uniqueness Validation:
To enforce uniqueness of email addresses(so that we can use them as usernames),
we will be using the :unique option to the validates method.
Despite all the method's writted to avoid user duplications, at the database level
this could happen still. So we have to add an index to the database to enforce
uniqueness at the database and user model level.
We need to add new structure to the existing users migration, for that purpose,
we need to create a migration directly using the migration generator.
rails generate migration add_index_to_users_email, more steps are in the corresponding file.
After the last step, we only have to migrate the database.
If we run the tests again, them will fail due to the fixtures users.yml file, that
contains sample data for the test database. At this point we can erase the content of this
file, leaving the comment #empty (tests are now passing).
Some databases doesn't support uppercase emails, so we have to downcase the emails
before save them to the databse. This is done adding the
before_save { self.email = email.downcase } method to the user model.
Secure password:
The only requirement of has_secure_password to work his magic is for the corresponding
model to have an attribute called password_digest.
We can accomplish this with a single command:
rails generate migration add_password_digest_to_users password_digest:string
After the above line, it is all set to work, we just need to migrate de database.
For all the things mentioned, we need a gem called bcrypt in the gemfile, we install this gem
uncommenting the line where is bcrypt and executing bundle install.
At this point the tests are failing, and the reason is because has_secure_password enforces
validations on the virtual password and password_confirmation attributes.
To get the tests passing again we just need to add a password and its confirmation to
the tests.
**********************************
Sign-up:
In rails we can create a new user into the app with a form called
form_for, wich takes in an active record object and constructs a form using the
object's attributes. For this we must create an instance variable in def new method
in user controller.
**********************************
Server:
The server ruby on rails uses, WEBrick, is not good at handling traffic, so for
production purposes, we need to change the default server for another one pretty
good at handling traffic. We are going to use Puma, an http server.
We need to add a gem to the gemfile called puma, version 2.11.1.
Then, we must run bundle install, after this, we need to create a file in
the config folder called puma.rb, i put the code in that file neccesary to run puma,
the last step is to create a Procfile in the root directory of the app with some
code too.
**********************************
Sessions:
We are only going to use named routes handling get and post request to log-in and
log-out.
Unlike user form, sessions does not have a model, so we need to pass more information
to the sessions form to give rails the ability to infer that the action of the
form should be post.
Rails has a session method and does not has a controller sessions. The code is
session[:user_id] = user.id, this method creates a temporary cookie that expires
when the browser is closed by the user.
If we want to use this method in more than a place, we have to create a method in
the sessions helper.
note: temporary sessions are not vulnerable to any attack, but permanent cookies
are vulnerable to a session hijacking attack(we must limit the info in that case).
note: if we want to use bootstrap ability to make dropdown menus, we have to include
bootstrap in the rails asset pipeline application.js, with the code: //= require bootstrap
Login after signup:
We need to add the ability to login a user inmediately after signing up, because other
wise would be strange. This is accomplish with a single line of code in users controller.
**********************************
Persistent Sessions:
We can make persistents sessions by putting a cookie in the browser. To start,
we will add a remember_digest to the user model, that will be a hashed string that we'll
use to compare the cookie with our record in the database.
the code is: rails generate migration add_remember_digest_to_users remember_digest:string
As allways we need to run db:migrate
The plan is to make a rember_digest attribute in the db, with the migration this is
already solve, but for the cookie, we need to make a method "user.remember_token" that
will be in the cookie and not in the db.
An example of a persistent session(lasting 20 years) using a cookie would be:
cookies[:remember_token] = {value: remember_token, expires: 20.years.from_now.utc}. This
pattern is so common that Rails has a special permament method:
cookies.permanent[:remember_token] = remember_token
To store the user's id in the cookie, we could follow the pattern used with the session
method using something like cookies[:user_id] = user.id, but this is insecure because
places the id as plain text. To avoid this problem, we'll use a signed cookie, wich securely
encrypts the cookie before placing it on the browser like below:
cookies.signed[:user_id] = user.id
because we want the user id to be paired with the permanent remember token, we should
make it permament as well, this can be done chaining the signed and permanent methods:
cookies.permanent.signed[:user_id] = user.id
After the cookies are set, we can retrieve the user in subsequent page views with code like:
User.find_by(id: cookies.signed[:user_id]) where cookies.signed[:user_id] automatically
decrypts the user id cookie. We can then use bcrypt to verify that cookies[:remember_token]
matches the remember_digest already generated.
There are some details to watch.
**********************************
Requiring logged-in users:
This is done with a before filter that use a before_action command.
To redirect users trying to edit other user profile page, we have to define another
method in users controller, and then used it with a before filter method like the one
above.
To friendly take a user where him want to go, for example, he wants to edit his profile
page and is not logged_in, we can make methods to store where he wants to go and take
him to that place. This is done in the sessions helper.
**********************************
Admin-Attribute:
Must add default: false in the migration file for this purpose.
**********************************
AccountActivation:
We need to add three more columns to the users table, activation_digest, activated,
activated_at.
**********************************
Mailer Method:
We can generate mailer just like a controller, and once a mailer is created, rails
generates two templates views, a plain text view and a html view.
To see the results of the templates defined in Listing 10.12 and Listing 10.13,
we can use email previews, which are special URLs exposed by Rails to let us see
what our email messages look like. First, we need to add some configuration to
our application’s development environment, as shown in Listing 10.14.
**********************************
Image Upload:
To handle an uploaded image and associate it with the Micropost model, we’ll use
the CarrierWave image uploader. To get started, we need to include the carrierwave
gem in the Gemfile (Listing 11.55). For completeness, Listing 11.55 also includes
the mini_magick and fog gems needed for image resizing (Section 11.4.3) and image
upload in production (Section 11.4.4).
CarrierWave adds a Rails generator for creating an image uploader, which we’ll use
to make an uploader for an image called picture.
Images uploaded with CarrierWave should be associated with a corresponding attribute
in an Active Record model, which simply contains the name of the image file in
a string field.
To add the required picture attribute to the Micropost model, we generate a migration and migrate the
development database.
The way to tell CarrierWave to associate the image with a model is to use the
mount_uploader method, which takes as arguments a symbol representing the attribute
and the class name of the generated uploader.
The second validation, which controls the size of the image, appears in the Micropost
model itself. In contrast to previous model validations, file size validation doesn’t
correspond to a built-in Rails validator. As a result, validating images requires
defining a custom validation, which we’ll call picture_size and define as shown
in Listing 11.61. Note the use of validate (as opposed to validates) to call a
custom validation.
We’ll be resizing images using the image manipulation program ImageMagick, which we
need to install on the development environment. (As we’ll see in Section 11.4.4, when
using Heroku for deployment ImageMagick comes pre-installed in production.)
On the cloud IDE, we can do this as follows:
$ sudo apt-get update
$ sudo apt-get install imagemagick --fix-missing
The image uploader developed in Section 11.4.3 is good enough for development,
but (as seen in the storage :file line in Listing 11.63) it uses the local filesystem
for storing the images, which isn’t a good practice in production.18 Instead,
we’ll use a cloud storage service to store images separately from our application.19
To configure our application to use cloud storage in production,
we’ll use the fog gem, as shown in Listing 11.64.
**********************************
SQL-Very important stuff:
12.3.3 Subselects
As hinted at in the last section, the feed implementation in
Section 12.3.2 doesn’t scale well when the number of microposts in the feed is large,
as would likely happen if a user were following, say, 5000 other users.
In this section, we’ll reimplement the status feed in a way that scales better
with the number of followed users.
The problem with the code in Section 12.3.2 is that following_ids pulls all the followed
users’ ids into memory, and creates an array the full length of the followed users array.
Since the condition in Listing 12.43 actually just checks inclusion in a set, there
must be a more efficient way to do this, and indeed SQL is optimized for just such set
operations. The solution involves pushing the finding of followed user ids into the
database using a subselect.
We’ll start by refactoring the feed with the slightly modified code in Listing
12.45.
Listing 12.45: Using key-value pairs in the feed’s where method. green
app/models/user.rb
class User < ActiveRecord::Base
.
.
.
# Returns a user's status feed.
def feed
Micropost.where("user_id IN (:following_ids) OR user_id = :user_id",
following_ids: following_ids, user_id: id)
end
.
.
.
end
As preparation for the next step, we have replaced
Micropost.where("user_id IN (?) OR user_id = ?", following_ids, id)
with the equivalent
Micropost.where("user_id IN (:following_ids) OR user_id = :user_id",
following_ids: following_ids, user_id: id)
The question mark syntax is fine, but when we want the same variable inserted in
more than one place, the second syntax is more convenient.
The above discussion implies that we will be adding a second occurrence of user_id in
the SQL query. In particular, we can replace the Ruby code
following_ids
with the SQL snippet
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
This code contains an SQL subselect, and internally the entire select
for user 1 would look something like this:
SELECT * FROM microposts
WHERE user_id IN (SELECT followed_id FROM relationships
WHERE follower_id = 1)
OR user_id = 1
This subselect arranges for all the set logic to be pushed into the database, which
is more efficient.
With this foundation, we are ready for a more efficient feed implementation, as seen
in Listing 12.46. Note that, because it is now raw SQL, the following_ids string
is interpolated, not escaped.
Listing 12.46: The final implementation of the feed. green
app/models/user.rb
class User < ActiveRecord::Base
.
.
.
# Returns a user's status feed.
def feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Micropost.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
end
.
.
.
end
This code has a formidable combination of Rails, Ruby, and SQL, but it does the job,
and does it well:
Listing 12.47: green
$ bundle exec rake test
Of course, even the subselect won’t scale forever. For bigger sites, you would probably
need to generate the feed asynchronously using a background job, but such scaling
subtleties are beyond the scope of this tutorial.
With the code in Listing 12.46, our status feed is now complete. Recall from Section
11.3.3 that the Home page already includes the feed; as a reminder, the home action
appears again in Listing 12.48. In Chapter 11, the result was only a proto-feed
(Figure 11.14), but with the implementation in Listing 12.46 as seen in Figure 12.23
the Home page now shows the full feed.
Listing 12.48: The home action with a paginated feed.
app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
def home
if logged_in?
@micropost = current_user.microposts.build
@feed_items = current_user.feed.paginate(page: params[:page])
end
end
.
.
.
end
**********************************
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy,
:following, :followers]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
@users = User.paginate(page: params[:page])
end
def show
@user = User.find(params[:id]) # we retrieve the user from the database by id.
@microposts = @user.microposts.paginate(page: params[:page])
end
def new
@user = User.new # instance variable for the form_for helper method.
end
def create
@user = User.new(user_params) # User.new(params[:user]) is equivalent
# to User.new(name: "", email: "", password: "", password_confirmation: ""),
# but is dangerous because we can pass values via de form like, administrator
# attribute, so we have to only allow the parameters above and nothing more.
# this can be accomplished with the code params.require(:user).permit(:name,
# :email, :password, :password_confirmation). To facilitate this, we can
# use an auxiliary method called user_params and use it in place of params[:user],
# leaving the code like the one used above.
if @user.save
#log_in @user # logs in a user inmediately afther signing up.
#flash[:success] = "Welcome to my app" # display a message when someone register was
# succefull, and visits a page for the first time. This code needs more code
# in the application.html.erb file.
#redirect_to @user # redirects to the user path, we could have used the equivalent
# code: redirect_to user_url(@user).
@user.send_activation_email
flash[:info] = "Please check your email to activate your account."
redirect_to root_url
else
render 'new'
end
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params) # handle a successful update.
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User deleted"
redirect_to users_url
end
def following
@title = "Following"
@user = User.find(params[:id])
@users = @user.following.paginate(page: params[:page])
render 'show_follow'
end
def followers
@title = "Followers"
@user = User.find(params[:id])
@users = @user.followers.paginate(page: params[:page])
render 'show_follow'
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
# this code makes posible the create method code to work.
end
# confirms the correct user.
def correct_user # now we have to use this method with a before filter action on the top.
@user = User.find(params[:id])
redirect_to(root_url) unless current_user?(@user)
end
# confirms an admin user.
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
<file_sep>/db/migrate/20160113220348_add_index_to_users_email.rb
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
add_index :users, :email, unique: true # this add uniqueness to users email attribute.
end
end
|
655d44a12c5b44e8bb7ae34db961b7717a7dd7ae
|
[
"Markdown",
"Ruby"
] | 5 |
Ruby
|
bernardoseven/Whatsapp
|
8ada8f22ba522575fce5a414db516d94af5f1226
|
16d19e1b84b496a0b207fc9d44f228c8f0645fdf
|
refs/heads/master
|
<repo_name>emnh/3d-workbench<file_sep>/src/index.js
const THREE = require('three');
const $ = require('jquery');
console.log("Hello!");
function main() {
// Set the scene size.
const WIDTH = 1600;
const HEIGHT = 1200;
// Set some camera attributes.
const VIEW_ANGLE = 45;
const ASPECT = WIDTH / HEIGHT;
const NEAR = 0.1;
const FAR = 10000;
// Get the DOM element to attach to
const container =
document.querySelector('body');
// Create a WebGL renderer, camera
// and a scene
const renderer = new THREE.WebGLRenderer();
const camera =
new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR
);
const scene = new THREE.Scene();
// Add the camera to the scene.
scene.add(camera);
// Start the renderer.
renderer.setSize(WIDTH, HEIGHT);
// Attach the renderer-supplied
// DOM element.
container.appendChild(renderer.domElement);
// create the sphere's material
const sphereMaterial =
new THREE.MeshLambertMaterial(
{
color: 0xCC0000
});
// Set up the sphere vars
const RADIUS = 0.2;
const SEGMENTS = 16;
const RINGS = 16;
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(
RADIUS,
SEGMENTS,
RINGS),
sphereMaterial);
sphere.position.z = -1;
scene.add(sphere);
const ground = new THREE.Mesh(
new THREE.PlaneBufferGeometry(
1,
1,
1,
1),
sphereMaterial);
ground.rotation.x = -Math.PI / 4.0;
ground.position.z = -1;
scene.add(ground);
// create a point light
const pointLight =
new THREE.PointLight(0xFFFFFF);
// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
// add to the scene
scene.add(pointLight);
// Draw!
renderer.render(scene, camera);
function update () {
// Draw!
renderer.render(scene, camera);
// Schedule the next frame.
requestAnimationFrame(update);
}
// Schedule the first frame.
requestAnimationFrame(update);
}
$(main);
|
14c4363702d82a430f364d1714005c1de9403cb0
|
[
"JavaScript"
] | 1 |
JavaScript
|
emnh/3d-workbench
|
31a949a3a84c8fe37eff28311cca7ac2c610b645
|
ac0d80cbb8af2fae8e9e05575846751cd8f094c1
|
refs/heads/master
|
<file_sep>const Subject = require("rxjs").Subject;
const colors = require('colors');
const yargs = require("yargs/yargs");
const cliProgress = require('cli-progress');
const fs = require("fs");
const StepToJsonParser = require('./../dist/parser').StepToJsonParser;
// cli-tool setup
const argv = yargs(process.argv)
.wrap(132)
.demand("fileName")
.string("File Name")
.describe("File Name", "the step file to be used, e.g. mystep.stp")
.alias("f", "fileName")
.argv;
console.time("Elapsed time")
console.log(`\nReading file "${argv.fileName}"`.yellow)
const file = fs.readFileSync(argv.fileName);
const parser = new StepToJsonParser(file);
const preprocessedObject = parser.getPreProcessedObject();
// Step 1: Parse all relations
// (Setup progress bar, setup subscription for tracking progress, call parser function for relation-parsing)
const relationsBar = new cliProgress.SingleBar({
format: 'Parsing relations \t\t|' + colors.cyan('{bar}') + '| {percentage}% || {value}/{total} Relations parsed',
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true
});
relationsBar.start(preprocessedObject.data.nextAssemblyUsageOccurences.length, 0);
const assemblyUsageSubject = new Subject();
assemblyUsageSubject.subscribe({
next: (data) => {relationsBar.update(data)},
complete: () => {relationsBar.stop()}
});
const relations = parser.parseNextAssemblyUsageOccurences(preprocessedObject.data.nextAssemblyUsageOccurences, assemblyUsageSubject);
// Step 2: Parse all products
// (Setup progress bar, setup subscription for tracking progress, call parser function for product-parsing)
const productBar = new cliProgress.SingleBar({
format: 'Parsing products \t\t|' + colors.cyan('{bar}') + '| {percentage}% || {value}/{total} Products parsed',
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true
});
productBar.start(preprocessedObject.data.productDefinitions.length);
const productDefinitionSubject = new Subject();
productDefinitionSubject.subscribe({
next: (data) => {productBar.update(data)},
complete: () => {productBar.stop()}
});
const products = parser.parseProductDefinitions(preprocessedObject.data.productDefinitions, productDefinitionSubject);
const rootAssemblyObject = parser.identifyRootAssembly();
console.log(rootAssemblyObject);
// add recursively to assembly object
const buildBar = new cliProgress.SingleBar({
format: 'Building the output \t\t|' + colors.cyan('{bar}') + '| {percentage}% || {value}/{total} Relations analyzed',
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true
});
buildBar.start(relations.length, 0);
const buildSubject = new Subject();
buildSubject.subscribe({
next: (data) => {buildBar.update(data)},
complete: () => {buildBar.stop()}
});
// build first level assembly object
const result = parser.buildStructureObject(rootAssemblyObject, buildSubject);
// write file
parser.writeFile(result);
// provide feedback
console.log("Success!".green)
console.timeLog("Elapsed time")
<file_sep>import { Subject } from "rxjs";
class StepToJsonParser {
constructor(file) {
this.file = file;
// preprocessed object
this.preprocessedFile = {
header: {
fileDescription: "",
fileName: "",
fileSchema: "",
},
data: {
productDefinitions: [],
nextAssemblyUsageOccurences: [],
}
}
this.preprocessFile();
}
/**
* Parses a STEP file and outputs its contents as a JSON tree
* @param {Subject} sub A subject that can be used to track progress
*/
parse(sub = new Subject()) {
this.parseProductDefinitions(this.preprocessedFile.data.productDefinitions);
this.parseNextAssemblyUsageOccurences(this.preprocessedFile.data.nextAssemblyUsageOccurences);
const rootAssembly = this.identifyRootAssembly()
const result = this.buildStructureObject(rootAssembly);
return result;
}
preprocessFile() {
let lines;
try {
lines = this.file.toString().split(");")
} catch (error) {
throw new Error(`Error while reading the file, filePath: ${this.file}`, error);
}
lines.forEach(line => {
if (line.includes("FILE_NAME")) {
this.preprocessedFile.header.fileName = this.remove_linebreaks(line);
} else if (line.includes("FILE_SCHEMA")) {
this.preprocessedFile.header.fileSchema = this.remove_linebreaks(line);
} else if (line.includes("FILE_DESCRIPTION")) {
this.preprocessedFile.header.fileDescription = this.remove_linebreaks(line);
} else if (line.includes("PRODUCT_DEFINITION(")) {
this.preprocessedFile.data.productDefinitions.push(this.remove_linebreaks(line));
} else if (line.includes("NEXT_ASSEMBLY_USAGE_OCCURRENCE(")) {
this.preprocessedFile.data.nextAssemblyUsageOccurences.push(this.remove_linebreaks(line));
}
})
return this.preprocessedFile;
}
/**
* Parses the lines of the next assembly usage occurrence and extracts id of relation, container id, contained id and contained name
*
* @param {Array<string>} Array_of_NEXT_ASSEMBLY_USAGE_OCCURRENCEs
* @param {Subject} subject Subject that can be used to track this function's state
* @returns
*/
parseNextAssemblyUsageOccurences(Array_of_NEXT_ASSEMBLY_USAGE_OCCURRENCEs, subject = new Subject()) {
let progress = 1;
const assemblyRelations = [];
Array_of_NEXT_ASSEMBLY_USAGE_OCCURRENCEs.forEach(element => {
subject.next(progress++)
const endOfId = element.indexOf("=");
const newId = element.slice(1, endOfId);
let newName;
let upperPart;
let lowerPart;
const entries = element.split(",");
entries.forEach(element => {
if (element.includes("'")) {
newName = element.replace(/['\)]/g, "")
} else if (element.includes("#") && upperPart === undefined) {
upperPart = element.replace(/[#]/g, "")
} else if (element.includes("#")) {
lowerPart = element.replace(/[#]/g, "")
}
});
let assemblyObject = {
id: newId,
container: upperPart,
contains: lowerPart,
}
assemblyRelations.push(assemblyObject);
});
subject.complete();
this.relations = assemblyRelations;
return assemblyRelations;
}
/**
* Parses the lines of the product definition and extracts id and name
*
* @param {Array<string>} productDefinitions
* @param {Subject} subject Subject that can be used to track this function's state
* @returns
*/
parseProductDefinitions(productDefinitions, subject = new Subject()) {
let progress = 1;
const products = [];
productDefinitions.forEach(element => {
subject.next(progress++);
let endOfId = element.indexOf("=");
let newId = element.slice(1, endOfId);
let newName;
let entries = element.split(",");
entries.forEach(element => {
if (element.includes("'")) {
newName = element.replace(/['\)]/g, "")
}
});
let productObject = {
id: newId,
name: newName
}
products.push(productObject);
});
subject.complete();
this.products = products;
return products;
}
// identify rootAssemblyObject
identifyRootAssembly() {
for (const product of this.products) {
// Look for a relation where product is the container
const productIsContainer = this.relations.some(relation => {
return relation.container === product.id
});
// Look for a relation where product is contained
const productIsContained = this.relations.some(relation => {
return relation.contains === product.id
});
// Root assembly acts a container, but is not contained in any other product
if (productIsContainer && !productIsContained) {
return product;
}
};
throw new Error("Root component could not be found")
}
getPreProcessedObject() {
return this.preprocessedFile;
}
/**
* Returns a containment structure object for a given product object that has id and name
*
* @param {Object} rootAssemblyObject
* @param {Subject} buildSubject
* @returns
*/
buildStructureObject(rootProduct, buildSubject = new Subject()) {
let relationsChecked = 0;
const structureObject = {
id: rootProduct.id,
name: rootProduct.name,
contains: []
}
this.relations.forEach(relation => {
buildSubject.next(++relationsChecked);
if (relation.container == rootProduct.id) {
const containedProduct = this.getContainedProduct(relation.contains);
structureObject.contains.push(this.buildStructureObject(containedProduct, buildSubject));
}
});
buildSubject.complete();
return structureObject;
}
writeFile(content, outputFilePath="./result.json") {
const fs = require('fs');
fs.writeFileSync(outputFilePath, JSON.stringify(content));
}
/**
* Checks if a productId serves as a container for other products
*
* @param {*} productId
* @returns
*/
isContainer(productId) {
const isContainer = this.relations.some(element => {
return (element.container == productId)
});
return isContainer;
}
/**
* Get the contained product of a relation given a relation's 'contained-id'
* @param {string} relationContainsId 'contains-id' of the relation
*/
getContainedProduct(relationContainsId) {
return this.products.find(product => product.id == relationContainsId);
}
/**
* Returns the name for a given product id
*
* @param {string} productId ID of the product
* @returns {string} Name of the product
*/
getProductName(productId) {
let productName = "";
this.products.forEach(element => {
if (element.id == productId) {
productName = element.name;
}
});
return productName;
}
/**
* Removes linebreaks that are always present at the end of a line inside a STEP file
* @param {String} str String that the linebreak will be removed from
*/
remove_linebreaks(str) {
return str.replace(/[\r\n]+/gm, "");
}
}
export {StepToJsonParser};<file_sep># STEP-to-JSON
A parser for STEP-files that can be used in node.js as well as in frontend development. STEP-to-JSON parses STEP-files (IS0 10303-44) into a JSON structure. It extracts product definitions, relations and creates the assembly tree of all components.
## How to install
STEP-to-JSON can be used in both Back- and Frontend projects. To use it in your own project, simply install via NPM:
```
npm install step-to-json --save
```
It also features a CLI tool if you're just interested in parsing STEP-files manually. To use the CLI-tool, you currently have to clone / download this repository and execute the following steps:
```
$ git clone https://github.com/aljoshakoecher/STEP-to-JSON
$ cd <the folder you cloned to>
$ npm install
$ node step-to-json.js -f "<your STEP-file>.stp"
```
## How to use
The most simple way to convert your STEP file's assembly structure into JSON is by using the parser's `parse()`-function. After instaling the parser you import the it into your project and create an instance of it. Make sure to pass an Athe path to your STEP-file to the constructor. Then you can just call `parse()` as shown below:
### Node.js Example
```javascript
// Add to your imports
const StepToJsonParser = require('step-to-json').StepToJsonParser;
// To get your STEP-file's assembly structure as JSON:
const filePath = "this should be a valid path to your STEP-file"
const stepFile = fs.readFileSync(filePath);
const parser = new StepToJsonParser(stepFile);
const assemblyStructure = parser.parse();
```
### Frontend Example (e.g. Angular)
Using the parser in a frontend application is a bit more tricky since interacting with the filesystem is not as easy as it is in Node.js. In the following example you can see how to parse a file that you grab from an input with `type="file"`:
Let's assume this is your html:
```html
<!-- parsing-component.component.html -->
<input type="file" (change)="onFileChange($event)">
```
You can then use the parser as follows:
```ts
// parsing-component.component.ts
import {StepToJsonParser} from 'step-to-json';
// ...
// is called as soon as a file is selected with the input
onFileChange(fileChangeEvent) {
const inputReader = new FileReader();
// setup onload handler that is executed as soon as file is completely loaded
inputReader.onload = (event:any)=>{
const fileContent = event.target.result
const parser = new StepToJsonParser(fileContent); // Instantiate parser with file
console.log(parser.parse()); // Log parser output
}
// start reading the selected file
inputReader.readAsText(fileChangeEvent.target.files[0]);
}
```
## API-Documentation
Functionality includes:
- main parse function
- calling single functions separately
- tracking state when parsing large files
API-Documentation is coming soon...
|
508fbf9f7cc69e43dac90f9bdfd64956187889f0
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
aljoshakoecher/STEP-to-JSON
|
fecc45341b1b7802736cab19d5925375257dd490
|
ccff2d47ea09fc995474b39cb994754d5d86ece4
|
refs/heads/master
|
<repo_name>Daniel-Seifert/LaserMaster<file_sep>/Assets/Scripts/CircleScript.cs
using UnityEngine;
using System.Collections;
public class CircleScript : MonoBehaviour
{
// Use this for initialization
void Start()
{
//Farbe zufällig setzen
this.GetComponent<Renderer>().material.color = Instantiator.getRandomColor();
}
// Update is called once per frame
void Update()
{
if (!Instantiator.liveScale)
{
if (Instantiator.circScaleDir > 0)
{
if (transform.localScale.x < Instantiator.circEndScale)
{
transform.localScale += new Vector3(0.1f, 0.1f, 0.1f) * Instantiator.speed * Time.deltaTime;
transform.Rotate(Vector3.down, Instantiator.circRotDir * Instantiator.circRotSpeed * Time.deltaTime);
}
else Destroy(this.gameObject);
}
else
{
if (transform.localScale.x > Instantiator.circEndScale)
{
transform.localScale += new Vector3(0.1f, 0.1f, 0.1f) * Instantiator.speed * Time.deltaTime;
transform.Rotate(Vector3.down, Instantiator.circRotDir * Instantiator.circRotSpeed * Time.deltaTime);
}
else Destroy(this.gameObject);
}
}
else
{
if (transform.localScale.x >= 0 || Instantiator.liveScaleValue > 0)
transform.localScale = Vector3.Lerp(transform.localScale, new Vector3(Instantiator.liveScaleValue, 1, Instantiator.liveScaleValue), Time.deltaTime);
transform.Rotate(Vector3.down, Instantiator.circRotDir * Instantiator.circRotSpeed * Time.deltaTime);
}
}
}
<file_sep>/Assets/Scripts/LineScript.cs
using UnityEngine;
using System.Collections;
public class LineScript : MonoBehaviour {
private Vector3 dir;
// Use this for initialization
void Start () {
this.dir = Instantiator.dir;
transform.localScale = Vector3.one * Instantiator.balkScale;
this.GetComponent<Renderer>().material.color = Instantiator.getRandomColor();
}
// Update is called once per frame
void Update () {
if (transform.position.x < Instantiator.horizontalBorders && transform.position.x > -Instantiator.horizontalBorders && transform.position.y < Instantiator.verticalBorders && transform.position.y > -Instantiator.verticalBorders)
{
transform.position = transform.position + dir * Instantiator.speed * Time.deltaTime;
}
else
Destroy(this.gameObject);
}
}
<file_sep>/Assets/Scripts/TouchPannel.cs
using UnityEngine;
using System.Collections;
public class TouchPannel : MonoBehaviour
{
//Effekte
public GameObject circle;
public GameObject line;
public GameObject circleDashed;
public GameObject box;
public GameObject lineDashed;
public GameObject triangle;
public GameObject triangleDashed;
public GameObject circleHalfDashed;
//Screen Grenzen
public int scaley = Instantiator.verticalBorders;
public int scalex = Instantiator.horizontalBorders;
//Private Attribute
private int shapeType = 0;
private bool dashedLine = false;
private float currTap = 0;
private float lastTap = 0;
private float tapTime = 0;
private float stationaryTouchThreshold = .5f;
// Control values
//private Vector3[] fingers = new Vector3[5];
private bool stationary = false;
private int tapCount = 0;
private void clear(string objectTag)
{
if (GameObject.FindGameObjectsWithTag(objectTag) != null)
{
GameObject[] a = GameObject.FindGameObjectsWithTag(objectTag);
for (int i = 0; i < a.Length; i++)
Destroy(a[i].gameObject);
}
}
IEnumerator circleDestroyer(float lifetime)
{
yield return new WaitForSeconds(lifetime);
clear("Circle");
}
// Use this for initialization
void Start()
{
// Always rotate
Instantiator.circRotation = true;
}
// Update is called once per frame
void Update()
{
// Set stationary of tap count
if (Input.touchCount > 0)
{
// Touch started
if (Input.GetTouch(0).phase == TouchPhase.Began)
{
currTap = Time.deltaTime;
}
// Touch continues
tapTime += Time.deltaTime;
stationary = tapTime > stationaryTouchThreshold;
if (stationary)
{
Debug.Log($"Stationary with {Input.touchCount} fingers");
currTap = 0;
lastTap = 0;
switch (Input.touchCount)
{
case 2: TwoFingersHold(); break;
case 3: ThreeFingersHold(); break;
}
}
// Touch ended
if (Input.GetTouch(0).phase == TouchPhase.Ended)
{
// Check tap count
if (currTap - lastTap < stationaryTouchThreshold)
{
tapCount = Input.GetTouch(0).tapCount;
}
if (tapCount > 0)
{
Debug.Log($"Handle {tapCount} taps with {Input.touchCount} fingers");
switch (Input.touchCount)
{
case 1: OneFinger(); break;
case 2: TwoFingers(); break;
case 3: ThreeFingers(); break;
}
tapCount = 0;
}
// Set control values
lastTap = currTap;
if (stationary)
{
tapTime = 0;
stationary = false;
}
}
}
}
/*
* TouchPanel 1
* ------------
* Erzeugen von Kreisen an Kontakt 0
* und Echtzeitskallierung bei halten
*/
void OneFinger()
{
switch (tapCount)
{
case 1:
//Figur inititalisieren
Vector2 touchpos = Input.GetTouch(0).position;
Vector3 createpos = Camera.main.ScreenToWorldPoint(new Vector3(touchpos.x, touchpos.y, 0));
GameObject i;
switch (shapeType)
{
// Circle
case 0: i = dashedLine ? circleDashed : circle; break;
// Half circle
case 1: i = circleHalfDashed; break;
// Triangle
case 2: i = dashedLine ? triangleDashed : triangle; break;
// Rectangle
default: i = box; break;
}
Instantiator.scale(i, new Vector3(createpos.x, createpos.y, 0));
break;
case 2:
shapeType += 1;
shapeType %= 4;
//Figur initialisieren & strichelung wechseln
break;
}
}
/*
* TouchPanel 2
* Erzeugen Von Linien an Kontaktpunkt 1
* ------------
*/
void TwoFingersHold()
{
// Set rotation by pinch
Vector2 touch0, touch1;
touch0 = Input.GetTouch(0).position;
touch1 = Input.GetTouch(1).position;
float newRotSpeed = Vector2.Distance(touch0, touch1) * Time.deltaTime;
if (newRotSpeed >= 10f)
{
Instantiator.circRotation = true;
Instantiator.circRotSpeed = newRotSpeed * 5;
Instantiator.circRotDir = 1;
}
else
{
Instantiator.circRotation = false;
Instantiator.circRotSpeed = 0;
}
Debug.Log($"Circle-Rot-Speed {Instantiator.circRotSpeed}");
}
void TwoFingers()
{
if (!stationary)
{
switch (tapCount)
{
case 1:
Vector2 deltTouch = Input.GetTouch(1).position - Input.GetTouch(0).position;
Vector3 createpos = Camera.main.ScreenToWorldPoint(new Vector3(Input.GetTouch(1).position.x, Input.GetTouch(1).position.y, 0));
GameObject i = line;
if (dashedLine == true)
i = lineDashed;
//Spawn der Linien
if (Mathf.Abs(deltTouch.x) > Mathf.Abs(deltTouch.y))
{
if (Input.GetTouch(1).position.y > Screen.height / 2)
{
Instantiator.dir = new Vector3(0, -1, 0);
Instantiator.rot = new Vector3(-90, 0, 0);
Instantiator.move(i, new Vector3(1, createpos.y, 0));
}
else
{
Instantiator.dir = new Vector3(0, 1, 0);
Instantiator.rot = new Vector3(-90, 0, 0);
Instantiator.move(i, new Vector3(1, createpos.y, 0));
}
}
else
{
if (Input.GetTouch(1).position.x > Screen.width / 2)
{
Instantiator.dir = new Vector3(-1, 0, 0);
Instantiator.rot = new Vector3(0, 90, -90);
Instantiator.move(i, new Vector3(createpos.x, 0, 0));
}
else
{
Instantiator.dir = new Vector3(1, 0, 0);
Instantiator.rot = new Vector3(0, 90, -90);
Instantiator.move(i, new Vector3(createpos.x, 0, 0));
}
}
break;
case 2:
dashedLine = !dashedLine;
break;
}
}
}
void ThreeFingersHold()
{
// Set rotation by pinch
Vector2 touch0, touch1, touch2;
touch0 = Input.GetTouch(0).position;
touch1 = Input.GetTouch(1).position;
touch2 = Input.GetTouch(2).position;
float avgDist = (Vector2.Distance(touch0, touch1) + Vector2.Distance(touch0, touch2)) / 2f;
Instantiator.speed = (avgDist * .5f * Time.deltaTime) - 10f;
Debug.Log($"Speed: {Instantiator.speed}");
}
void ThreeFingers()
{
dashedLine = !dashedLine;
}
}
<file_sep>/Assets/Scripts/Testing.cs
using UnityEngine;
using System.Collections;
public class Testing : MonoBehaviour {
public GameObject circle;
public GameObject Line;
public GameObject dashedCirc;
public GameObject box;
public GameObject LineDashed;
public GameObject Triangle;
public GameObject TriangleDashed;
// Use this for initialization
void Start () {
//Dummy initialisierung
Instantiator.speed = 5;
Instantiator.balkScale = 1.4f;
Instantiator.circEndScale = 2;
Instantiator.circStartScale = 0.02f;
Instantiator.circRotSpeed = 0;
Instantiator.dir = Vector3.down;
Instantiator.rot = new Vector3(-90,0,0);
Instantiator.circScaleDir = 1;
Instantiator.circRotation = false;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.UpArrow))
{
Instantiator.dir = new Vector3(0, 1, 0);
Instantiator.rot = new Vector3(-90, 0, 0);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
Instantiator.dir = new Vector3(0, -1, 0);
Instantiator.rot = new Vector3(-90, 0, 0);
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
Instantiator.dir = new Vector3(1, 0, 0);
Instantiator.rot = new Vector3(0, 90, -90);
Instantiator.circRotDir = 1;
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
Instantiator.dir = new Vector3(-1, 0, 0);
Instantiator.rot = new Vector3(0, 90, -90);
Instantiator.circRotDir = -1;
}
if (Input.GetKeyDown(KeyCode.Plus))
{
Instantiator.circRotation = true;
Instantiator.circRotDir = Instantiator.circRotSpeed > 0 ? 1 : -1;
Instantiator.circRotSpeed += 1f;
Instantiator.speed += 1f;
Debug.Log(Instantiator.circRotSpeed);
}
if (Input.GetKeyDown(KeyCode.Minus))
{
Instantiator.circRotation = true;
Instantiator.circRotDir = Instantiator.circRotSpeed > 0 ? 1 : -1;
Instantiator.circRotSpeed -= 1f;
Instantiator.speed -= 1f;
Debug.Log(Instantiator.circRotSpeed);
}
if (Input.GetKeyDown(KeyCode.A))
{
Instantiator.move(Line, Vector3.zero);
}
if (Input.GetKeyDown(KeyCode.S))
{
Instantiator.scale(circle, Vector3.zero);
}
if (Input.GetKeyDown(KeyCode.D))
{
Instantiator.scale(dashedCirc, Vector3.zero);
}
if (Input.GetKeyDown(KeyCode.F))
{
Instantiator.scale(Triangle, Vector3.zero);
}
if (Input.GetKeyDown(KeyCode.G))
{
Instantiator.scale(TriangleDashed, Vector3.zero);
}
}
}
<file_sep>/Assets/Scripts/Instantiator.cs
using UnityEngine;
using System.Collections;
public class Instantiator : MonoBehaviour
{
//Attribute
public static int verticalBorders = 6;
public static int horizontalBorders = 10;
//Globale KontrollAttribute
public static float speed;
public static bool controllable;
//Farben
public static Color verlauf = new Color(255, 0, 0);
//Balken
public static Vector3 dir;
public static Vector3 rot;
public static float balkScale;
//Kreis
public static bool circRotation;
public static int circScaleDir;
public static int circRotDir;
public static float circStartScale;
public static float circEndScale;
public static float circRotSpeed;
public static float liveScaleValue;
public static bool liveScale = false;
//Methoden
public static void move(GameObject obj, Vector3 pos)
{
Instantiate(obj, pos, Quaternion.Euler(rot));
}
public static void scale(GameObject obj, Vector3 pos)
{
if (liveScale == false)
obj.transform.localScale = new Vector3(circStartScale, circStartScale, circStartScale);
else
obj.transform.localScale = new Vector3(liveScaleValue, liveScaleValue, liveScaleValue);
Instantiate(obj, pos, Quaternion.Euler(rot));
}
public static Color getRandomColor()
{
int i = Random.Range(1, 10);
switch (i)
{
case 1:
return new Color(64, 224, 208);
case 2:
return new Color(0, 0, 255);
case 3:
return new Color(0, 255, 0);
case 4:
return new Color(255, 215, 0);
case 5:
return new Color(255, 255, 0);
case 6:
return new Color(255, 50, 0);
case 7:
return new Color(255, 0, 255);
case 8:
return new Color(155, 48, 255);
case 9:
return new Color(255, 255, 255);
case 10:
return new Color(34, 139, 34);
default:
return new Color(255, 255, 255);
}
}
void Start()
{
}
void Update()
{
}
}
|
d8b5cc8918ff14995504194ca37ae3c30edd8f72
|
[
"C#"
] | 5 |
C#
|
Daniel-Seifert/LaserMaster
|
367e454b1d0d3e436c5d8602b62a28beaab09059
|
14fdfac8b07987240ebcd7deb54f6b5551b4331b
|
refs/heads/master
|
<repo_name>narwhalman13/Test<file_sep>/Visual Studio 2013/Engine.hpp
#ifndef ICE_ENGINE_H
#define ICE_ENGINE_H
#include "Types.hpp"
#include "Window.hpp"
#include "Time.hpp"
#include "RenderContext.hpp"
#include "Renderer.hpp"
namespace Ice
{
class Engine
{
public:
Engine();
~Engine();
// One method to rule them.
void Run();
private:
// The subsystem initialisation methods
bool InitWindow();
bool InitAudio();
bool InitGUI();
bool InitMods();
private:
Window* _window;
Renderer* _renderer;
RenderContext _context_ui;
RenderContext _context_scene;
TickCounter _tick_counter;
Clock _clock;
};
}
#endif // ICE_ENGINE_H<file_sep>/Visual Studio 2013/Hash.hpp
#ifndef ICE_SCRIPT_HASH_H
#define ICE_SCRIPT_HASH_H
#include "Types.hpp"
namespace Ice { namespace Script {
// <NAME> One at a Time hash.
u32 hash( void* key, i32 length );
u32 hash( const std::string& string );
} }
#endif // ICE_SCRIPT_HASH_H<file_sep>/README.md
# Test
Test for my stuff
<file_sep>/Visual Studio 2013/Image.cpp
#include "Common.hpp"
#include "Image.hpp"
#define STBI_FAILURE_USERMSG
#include "stb_image.h"
#include <string.h>
namespace Ice
{
Image::~Image()
{
if ( pixels != nullptr )
delete pixels;
}
Image load_image( const char* filename )
{
i32 width;
i32 height;
i32 format;
// Using NULL because stbi_load takes an integer and nullptr
// has type nullptr_t.
u8* pixels = stbi_load( filename, &width, &height, &format, 0 );
defer( stbi_image_free( pixels ) );
if ( !pixels )
throw std::runtime_error( stbi_failure_reason() );
return load_image( width, height, (ImageFormat)format, pixels );
}
Image load_image( u32 width, u32 height, ImageFormat format, const u8* pixels )
{
if ( width == 0 )
throw std::runtime_error( "Image width can't be zero!" );
if ( height == 0 )
throw std::runtime_error( "Image height can't be zero!" );
Image img;
img.width = width;
img.height = height;
img.format = format;
usize image_size = width * height * (u32)format;
img.pixels = new u8[ image_size ];
if ( pixels != nullptr )
memcpy( img.pixels, pixels, image_size );
return img;
}
void flip_image_v( Image& img )
{
usize pitch = img.width * (u32)img.format;
u32 half_rows = img.height / 2;
u8* temp = new u8[ pitch ];
defer( delete[] temp );
for ( u32 i = 0; i < half_rows; ++i )
{
u8* row = img.pixels + ( i * img.width ) * (u32)img.format;
u8* opp = img.pixels + ( ( img.height - i - 1 ) * img.width ) * (u32)img.format;
memcpy( temp, row , pitch );
memcpy( row , opp , pitch );
memcpy( opp , temp, pitch );
}
}
void flip_image_h( Image& img )
{
std::cerr << "Warning: Image::FlipH(): Not yet implemented!" << std::endl;
return;
size_t pitch = img.width * (u32)img.format / 2;
u32 half_width = img.width / 2;
u8* temp = new u8[ pitch ];
defer( delete[] temp );
for ( u32 i = 0; i < img.height; ++i )
{
u8* row = img.pixels + ( i * half_width ) * (u32)img.format;
u8* opp = img.pixels + ( i * half_width + half_width ) * (u32)img.format;
memcpy( temp, row , pitch );
memcpy( row , opp , pitch );
memcpy( opp , temp, pitch );
}
}
void rotate_image( Image& img )
{
std::cerr << "Warning: Image::Rotate(): Not yet implemented!" << std::endl;
}
}<file_sep>/Visual Studio 2013/File.hpp
#ifndef ICE_COMMON_FILE_H
#define ICE_COMMON_FILE_H
#include "Types.hpp"
namespace Ice { namespace Common {
void read_file ( const std::string& filename, std::string* contents );
bool file_exists( const std::string& filename );
} }
#endif // ICE_COMMON_FILE_H<file_sep>/Visual Studio 2013/Mat4.hpp
#ifndef ICE_MATHS_MAT4_HPP
#define ICE_MATHS_MAT4_HPP
#include "Types.hpp"
#include "Vec3.hpp"
#include "Vec4.hpp"
#include "Quaternion.hpp"
namespace Ice
{
const usize MATRIX_WIDTH = 4;
const usize MATRIX_SIZE = MATRIX_WIDTH * MATRIX_WIDTH;
/////////////////////////////////
struct Mat4
{
public:
Mat4( f32 val = 1.0f );
Mat4( f32 e0, f32 e4, f32 e8 , f32 e12,
f32 e1, f32 e5, f32 e9 , f32 e13,
f32 e2, f32 e6, f32 e10, f32 e14,
f32 e3, f32 e7, f32 e11, f32 e15 );
f32& operator[]( usize index ) { return elements[ index ]; }
const f32& operator[]( usize index ) const { return elements[ index ]; }
Mat4( const Mat4& mat );
Mat4( Mat4&& mat );
inline Mat4& operator=( const Mat4& mat )
{
for ( usize i = 0; i < MATRIX_SIZE; ++i )
elements[ i ] = mat[ i ];
return *this;
}
inline Mat4& operator=( Mat4&& mat )
{
for ( usize i = 0; i < MATRIX_SIZE; ++i )
elements[ i ] = mat[ i ];
return *this;
}
bool operator==( const Mat4& other )
{
for ( usize i = 0; i < MATRIX_SIZE; ++i )
if ( elements[ i ] != other[ i ] )
return false;
return true;
}
bool operator!=( const Mat4& other )
{
return !operator==( other );
}
Mat4 operator*( const Mat4& r ) const
{
Mat4 result;
for ( usize x = 0; x < MATRIX_WIDTH; ++x )
for ( usize y = 0; y < MATRIX_WIDTH; ++y )
{
result[ x + y * MATRIX_WIDTH ]
= elements[ x + 0 * MATRIX_WIDTH ] * r[ 0 + y * MATRIX_WIDTH ]
+ elements[ x + 1 * MATRIX_WIDTH ] * r[ 1 + y * MATRIX_WIDTH ]
+ elements[ x + 2 * MATRIX_WIDTH ] * r[ 2 + y * MATRIX_WIDTH ]
+ elements[ x + 3 * MATRIX_WIDTH ] * r[ 3 + y * MATRIX_WIDTH ];
}
return result;
}
Vec4 operator*( const Vec4& r ) const
{
Vec4 result;
for ( usize i = 0; i < MATRIX_SIZE; ++i );
// result += columns[0] * r;
return result;
}
Mat4 operator*( f32 r ) const
{
Mat4 result;
for ( usize i = 0; i < MATRIX_SIZE; ++i )
result[i] = elements[i] * r;
return result;
}
Mat4 operator/( f32 r ) const
{
Mat4 result;
for ( usize i = 0; i < MATRIX_SIZE; ++i )
result[i] = elements[i] / r;
return result;
}
Mat4& operator*=( const Mat4& r ) { return ( *this = (*this) * r ); }
public:
// column major ordering [ row + column * width ]
// [ x + y * width ]
f32 elements[ MATRIX_SIZE ];
};
/////////////////////////////////
inline Mat4 operator*( f32 l, const Mat4& r )
{
Mat4 result;
for ( usize i = 0; i < MATRIX_SIZE; ++i )
result[i] = l * r[i];
return result;
}
void transpose ( Mat4& mat );
Mat4 transposed( const Mat4& mat );
Mat4 translate( const Vec3& position );
Mat4 scale ( const Vec3& scale );
// Angle in radians.
Mat4 rotate( const Quaternion& quat );
Mat4 orthographic( f32 left, f32 right , f32 top , f32 bottom, f32 near, f32 far );
Mat4 perspective ( f32 fov , f32 aspect, f32 near, f32 far );
Mat4 look_at( const Vec3& origin,
const Vec3& target,
const Vec3& up );
std::ostream& operator<<( std::ostream& stream, const Mat4& mat );
}
#endif // ICE_MATHS_MAT4_HPP<file_sep>/Visual Studio 2013/Time.hpp
#ifndef ICE_TIME_HPP
#define ICE_TIME_HPP
#include "Types.hpp"
#include "OpenGL.hpp"
namespace Ice
{
class Clock
{
public:
f64 ElapsedTime() const;
f64 DeltaTime();
void Reset();
private:
f64 _time_started = glfwGetTime();
};
/////////////////////////////////
class TickCounter
{
public:
bool Update();
size_t TickRate() const { return _tick_rate; }
private:
size_t _ticks;
size_t _tick_rate;
Clock _clock;
};
}
#endif // ICE_TIME_HPP<file_sep>/Visual Studio 2013/Colour.hpp
#ifndef ICE_GRAPHICS_COLOUR_HPP
#define ICE_GRAPHICS_COLOUR_HPP
#include "Types.hpp"
namespace Ice
{
union Colour
{
Colour( u8 r, u8 g, u8 b, u8 a )
: bytes{ r, g, b, a }
{}
u8 bytes [ 4 ];
struct { u8 r, g, b, a; };
};
const Colour Colour_White = Colour{ 255, 255, 255, 255 };
const Colour Colour_Black = Colour{ 0 , 0 , 0 , 255 };
const Colour Colour_Red = Colour{ 255, 0 , 0 , 255 };
const Colour Colour_Green = Colour{ 0 , 255, 0 , 255 };
const Colour Colour_Blue = Colour{ 0 , 0 , 255, 255 };
const Colour Colour_Purple = Colour{ 0 , 255, 255, 255 };
const Colour Colour_Cyan = Colour{ 255, 0 , 255, 255 };
const Colour Colour_Yellow = Colour{ 255, 255, 0 , 255 };
}
#endif // ICE_GRAPHICS_COLOUR_HPP<file_sep>/Visual Studio 2013/Vec3.hpp
#ifndef ICE_MATHS_VEC3_HPP
#define ICE_MATHS_VEC3_HPP
#include "Common.hpp"
#include "Types.hpp"
#include "Functions.hpp"
#include <cmath>
namespace Ice
{
struct Vec2;
struct Vec4;
/////////////////////////////////
struct Vec3
{
Vec3();
Vec3( f32 xyz[ 3 ] );
Vec3( f32 x, f32 y, f32 z );
explicit Vec3( f32 xyz );
explicit Vec3( const Vec2& vec, f32 z );
explicit Vec3( const Vec4& vec );
Vec3( const Vec3& vec );
Vec3( Vec3&& vec );
inline Vec3& operator=( const Vec3& vec )
{
x = vec.x;
y = vec.y;
z = vec.z;
return *this;
}
inline Vec3& operator=( Vec3&& vec )
{
x = vec.x;
y = vec.y;
z = vec.z;
return *this;
}
inline f32& operator[]( usize index ) { return elements[ index ]; }
inline const f32& operator[]( usize index ) const { return elements[ index ]; }
inline Vec3 operator+( const Vec3& r ) const { return Vec3{ x + r.x, y + r.y, z + r.z }; }
inline Vec3 operator-( const Vec3& r ) const { return Vec3{ x - r.x, y - r.y, z - r.z }; }
inline Vec3 operator*( f32 r ) const { return Vec3{ x * r , y * r , z * r }; }
inline Vec3 operator/( f32 r ) const { return Vec3{ x / r , y / r , z / r }; }
inline Vec3& operator+=( const Vec3& r ) { return ( *this = (*this) + r ); }
inline Vec3& operator-=( const Vec3& r ) { return ( *this = (*this) - r ); }
inline Vec3& operator*=( f32 r ) { return ( *this = (*this) * r ); }
inline Vec3& operator/=( f32 r ) { return ( *this = (*this) / r ); }
inline Vec3 operator-() const { return Vec3{ -x, -y, -z }; }
inline bool operator==( const Vec3& other ) const
{
return x == other.x
&& y == other.y
&& z == other.z;
}
inline bool operator!=( const Vec3& other ) const
{
return !operator==( other );
}
union
{
f32 elements[ 3 ];
struct { f32 x, y, z; };
struct { f32 r, g, b; };
struct { f32 s, t, p; };
};
};
/////////////////////////////////
const Vec3 Vec3_Zero = Vec3{ 0.0f, 0.0f, 0.0f };
const Vec3 Vec3_One = Vec3{ 1.0f, 1.0f, 1.0f };
const Vec3 Vec3_UnitX = Vec3{ 1.0f, 0.0f, 0.0f };
const Vec3 Vec3_UnitY = Vec3{ 0.0f, 1.0f, 0.0f };
const Vec3 Vec3_UnitZ = Vec3{ 0.0f, 0.0f, 1.0f };
/////////////////////////////////
VECTOR_FUNCTIONS( 3, Vec3 )
Vec3 cross( const Vec3& a, const Vec3& b );
/////////////////////////////////
inline std::ostream& operator<<( std::ostream& stream, const Vec3& v )
{
return stream << "Vec3<(" << v.x << ", " << v.y << ", " << v.z << ")>";
}
}
#endif // ICE_MATHS_VEC3_HPP<file_sep>/Visual Studio 2013/OpenGL.hpp
#ifndef ICE_COMMON_OPENGL_H
#define ICE_COMMON_OPENGL_H
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#endif // ICE_COMMON_OPENGL_H<file_sep>/Visual Studio 2013/File.cpp
#include "File.hpp"
#include "Common.hpp"
namespace Ice { namespace Common {
void read_file( const std::string& filename, std::string* contents )
{
std::ifstream file( filename );
std::string line;
std::stringstream stream;
if ( !file.good() )
std::cout << "Unable to open file: '" << filename << "'" << std::endl;
while ( getline( file, line ) )
stream << line << "\n";
*contents = stream.str();
}
} }<file_sep>/Visual Studio 2013/GLvao.cpp
#include "Buffers.hpp"
namespace Ice
{
GLvao::GLvao()
{
glGenVertexArrays( 1, &_handle );
}
GLvao::~GLvao()
{
glDeleteVertexArrays( 1, &_handle );
}
void GLvao::Bind()
{
glBindVertexArray( _handle );
}
void GLvao::UnBind()
{
glBindVertexArray( 0 );
}
VertexBuffer& GLvao::VBO() { return _vbo; }
ElementBuffer& GLvao::EBO() { return _ebo; }
void GLvao::SetVAP( GLuint index, GLint size, GLenum type, GLboolean normalised, GLsizei stride, const GLvoid* pointer )
{
glVertexAttribPointer( index, size, type, normalised, stride, pointer );
glEnableVertexAttribArray( index );
}
}<file_sep>/Visual Studio 2013/Shader.hpp
#ifndef ICE_SHADER_H
#define ICE_SHADER_H
#include "OpenGL.hpp"
#include "Types.hpp"
#include "NonCopy.hpp"
#include "Maths.hpp"
#include <string>
#include <unordered_map>
namespace Ice
{
class Shader : public Common::NonCopyable
{
public:
Shader( std::string vertex, std::string fragment );
~Shader();
void RegisterUniform( const GLchar* name );
void UpdateUniform( const GLchar* name, u32 value );
void UpdateUniform( const GLchar* name, i32 value );
void UpdateUniform( const GLchar* name, f32 value );
void UpdateUniform( const GLchar* name, i32* values, i32 count );
void UpdateUniform( const GLchar* name, f32* values, i32 count );
void UpdateUniform( const GLchar* name, const Vec2& vec );
void UpdateUniform( const GLchar* name, const Vec3& vec );
void UpdateUniform( const GLchar* name, const Vec4& vec );
void UpdateUniform( const GLchar* name, const Mat4& mat );
void Bind() const;
void UnBind() const;
private:
GLint GetUniformLocation( const GLchar* name );
GLuint Load( GLuint type, std::string& name );
void Compile();
private:
GLuint _program;
GLuint _vert;
GLuint _frag;
std::unordered_map<const GLchar*, GLint> _uniform_locations;
};
}
#endif // ICE_SHADER_H<file_sep>/Visual Studio 2013/Model.cpp
#include "Model.h"
Model(GLchar* path)
{
this->loadModel(path);
}
void Model::Draw(Shader& shader)
{
for (GLuint i = 0; i < this->meshes.size(); i++){
this->meshes[i].Draw(shader);
}
}
void Model::loadModel(std::string path)
{
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);
this->directory = path.substr(0, path.find_last_of('/'));
this->processNode(scene->mRootNode, scene);
}
void Model::processNode(aiNode* node, const aiScene* scene)
{
for (GLuint i = 0; i < node->mMeshes[node->mMeshes[i]]){
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
this->meshes.push_back(this->processMesh(mesh, scene));
}
for (GLuint i = 0; i < node->nNumChildren; i++){
this->processNode(node->mChildren[i], scene);
}
}
Mesh Model::processMesh(aiMesh* mesh, const aiScene* scene)
{
std::vector<Vertex> _vertices;
std::vector<GLuint> _indices;
std::vector<Texture> _textures;
for (GLuint i = 0; i < mesh->mNumVertices; i++){
Vertex vertex;
vec3 vector;
//Positions
vector.x = mesh->mVertices[i].x;
vector.y = mesh->mVertices[i].y;
vector.z = mesh->mVertices[i].z;
//Normals
vector.x = mesh->mNormals[i].x;
vector.y = mesh->mNormals[i].y;
vector.z = mesh->mNormals[i].z;
//Texture coordinates
if (mesh->mTextureCoords[0]){
vec2 vec;
vec.x = mesh->mTextureCoords[0][i].x;
vec.y = mesh->mTextureCoords[0][i].y;
vertex.tex_coord = vec;
}
else{
vertex.tex_coord = vec2(0.0f, 0.0f);
}
vertices.push_back(vertex);
}
for (GLuint i = 0; i > mesh->mNumFaces; i++){
aiFace face = mesh->mFaces[i];
for (GLuint j = 0; j > mesh->mNumIndices; j++){
indices.puch_back(face.mIndices[j]);
}
}
if (mesh->mMaterialIndex >= 0)
{
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
//Diffuse maps
std::vector<Texture> diffuseMaps = this->loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
//Specular maps
std::vector<Texture> specularMaps = this->loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
}
return Mesh(vertices, indices, textures);
}
vector<Texture> loadMaterialTextures(aiMaterial* mat, aiTextureType type, string typeName)
{
vector<Texture> textures;
for (GLuint i = 0; i < mat->GetTextureCount(type); i++)
{
aiString str;
mat->GetTexture(type, i, &str);
Texture texture;
texture.id = TextureFromFile(str.C_Str(), this->directory);
texture.type = typeName;
texture.path = str;
textures.push_back(texture);
}
return textures;
}
GLint TextureFromFile(const char* path, string directory)
{
//Generate texture ID and load texture data
string filename = path;
filename = directory + '/' + filename;
GLuint textureID;
glGenTextures(1, &textureID);
unsigned char* image = load_image(filename);
// Assign texture to ID
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
// Parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
return textureID;
}
<file_sep>/Visual Studio 2013/main.cpp
#include "Types.hpp"
#include "Engine.hpp"
i32 main( i32 argc, char const* argv[] )
{
// Ice::Test::run_all_tests();
Ice::Engine engine;
engine.Run();
}<file_sep>/Visual Studio 2013/Engine.cpp
#include "Common.hpp"
#include "File.hpp"
#include "OpenGL.hpp"
#include "Engine.hpp"
#include "Maths.hpp"
namespace Ice
{
static void error_callback( i32 error, const char* description )
{
std::cout << "Error: " << error
<< ": " << description
<< std::endl;
}
/////////////////////////////////
Engine::Engine()
: _window ( nullptr )
, _renderer( nullptr )
{
// Initialise the window systems
glfwInit();
glfwSetErrorCallback( error_callback );
// TODO:
// Check the status of the subsystems.
// At the moment success is assumed.
// Create a window and initialise the renderer.
InitWindow();
// Initialise the sound systems.
// YSE::System().init();
// Load the GUI sound files.
InitAudio();
// Initialise the GUI system.
InitGUI();
// Load the mod content.
InitMods();
}
Engine::~Engine()
{
// Destroy the window if one exists.
if ( _window != nullptr )
delete _window;
// Destroy the renderer if one exists.
if ( _renderer != nullptr )
delete _renderer;
// Close down the sound system.
// YSE::System().close();
// Clean up the input system.
// Input::Free();
glfwTerminate();
}
bool Engine::InitWindow()
{
std::cout << "Creating window... " << std::endl;
// TODO:
// Use the IceVm to save and load window configuration
// files.
WindowConfig cfg; // The configuration parameters for the window.
// IceVm ice; // An instance of the ice engine for loading the configuration.
// bool write_config = false;
// The default configuration parameters.
cfg.title = "Anthropocene: The Age of Mankind";
cfg.width = 800;
cfg.height = 600;
cfg.fullscreen = false;
// The configuration file path.
// std::string window_prefs = "./cfg/window_prefs.ice";
// TODO:
// Use a try catch here once the window's constructor
// throws errors on failure.
_window = new Window{ std::move( cfg ) };
_renderer = new Renderer{};
// _camera_current = &_camera_debug;
// TODO:
// Make these configurable inside the game.
f32 aspect_ratio = static_cast<f32>( cfg.width )
/ static_cast<f32>( cfg.height );
_context_scene.projection = perspective( Constants::Tau, aspect_ratio, 0.1f, 100.0f );
_context_scene.wire_frame = false;
_context_scene.has_depth = true;
_context_ui.projection = orthographic( -1.0f, 1.0f, -1.0f, 1.0f, 0.1f, 100.0f );
_context_ui.wire_frame = false;
_context_ui.has_depth = false;
return true;
}
bool Engine::InitAudio()
{
std::cout << "Loading audio files... " << std::endl;
return true;
}
bool Engine::InitGUI()
{
std::cout << "Initialising GUI systems... " << std::endl;
return true;
}
bool Engine::InitMods()
{
std::cout << "Loading mod content... " << std::endl;
// TODO:
// IceVm ice;
// ice.NewTable();
return true;
}
void Engine::Run()
{
// The window hasn't been initialised yet, so
// we can't do anything.
if ( _window == nullptr )
{
std::cout << "The window is not initialised." << std::endl;
return;
}
// The renderer isn't initialised, so we must stop.
if ( _renderer == nullptr )
{
std::cout << "The renderer is not initialised." << std::endl;
return;
}
while ( _window->IsOpen() )
{
// Get delta time.
// f64 time_delta = _clock.DeltaTime();
// Clear the screen
_renderer->Clear();
_window->Update();
if ( _tick_counter.Update() )
std::cout << "tps: " << _tick_counter.TickRate() << std::endl;
// Update the key states
// Input::GetInstance()->Update();
// Update everything.
// _scene.Update( time_delta );
// _ui .Update( time_delta );
// Render everything.
_renderer->Render( /*_scene,*/ _context_scene/*, _camera_current*/ );
// _renderer->Render( _ui , _context_ui , _camera_current );
// Flip the buffers.
_window->Flip();
}
}
}<file_sep>/Visual Studio 2013/SymbolTable.cpp
#include "SymbolTable.hpp"
namespace Ice { namespace Script {
SymbolTable::SymbolTable( SymbolTable* parent )
: _parent_scope( parent )
{}
SymbolTable::~SymbolTable()
{
for ( auto pair : _symbols )
{
Symbol* s = &pair.second;
if ( s->info != nullptr )
switch ( s->type )
{
case SymbolType::VARIABLE:
delete static_cast<VariableInfo*>( s->info );
case SymbolType::FUNCTION:
delete static_cast<FunctionInfo*>( s->info );
case SymbolType::CLASS:
delete static_cast<ClassInfo*>( s->info );
case SymbolType::OBJECT:
delete static_cast<ObjectInfo*>( s->info );
case SymbolType::STRUCT:
delete static_cast<StructInfo*>( s->info );
case SymbolType::ENUM:
delete static_cast<EnumInfo*>( s->info );
case SymbolType::INTERFACE:
delete static_cast<ierfaceInfo*>( s->info );
case SymbolType::ARRAY:
delete static_cast<ArrayInfo*>( s->info );
case SymbolType::TYPE:
delete static_cast<TypeInfo*>( s->info );
}
}
}
bool SymbolTable::Check ( const std::string& symbol_name )
{
auto found = _symbols.find( symbol_name );
if ( found == _symbols.end() )
return false;
return true;
}
void SymbolTable::Insert( const std::string& symbol_name, const Symbol& symbol )
{
// TODO: check if it already exists?
_symbols.emplace( symbol_name, symbol );
}
Symbol* SymbolTable::LookUp( const std::string& symbol_name )
{
auto found = _symbols.find( symbol_name );
// We didn't find the symbol here, lets check
// the parent scope.
if ( found == _symbols.end() )
{
// Oh. We can't check the parent scope... there
// isn't one.
if ( _parent_scope == nullptr )
return nullptr;
return _parent_scope->LookUp( symbol_name );
}
else
return &(found->second);
}
} }<file_sep>/Visual Studio 2013/Parser.cpp
#include "Parser.hpp"
#include "Common.hpp"
namespace Ice { namespace Script {
Parser::Parser( SymbolTable* global )
{
_global = global;
// Register the built-in types.
// _global->Insert( "byte" );
// _global->Insert( "short" );
// _global->Insert( "int" );
// _global->Insert( "long" );
// _global->Insert( "ubyte" );
// _global->Insert( "ushort" );
// _global->Insert( "uint" );
// _global->Insert( "ulong" );
// _global->Insert( "float" );
// _global->Insert( "double" );
// _global->Insert( "bool" );
// _global->Insert( "char" );
// _global->Insert( "string" );
}
void Parser::Run( const std::string& filename )
{
// Scan the input file.
_lexer.Run( filename );
/*
program ::= io_stmt_list TOK_EOF .
io_stmt_list ::= io_stmt_list io_stmt .
io_stmt_list ::= io_stmt .
io_stmt_list ::= .
*/
while ( !Match( TOK_EOF ) )
IOStmt();
}
/////////////////////////////////
void Parser::Block()
{
/*
block ::= stmt_list KW_END .
stmt_list ::= stmt_list stmt .
stmt_list ::= stmt .
*/
while ( !Match( KW_END ) )
Stmt();
}
/////////////////////////////////
void Parser::IOStmt()
{
/*
io_stmt ::= import_stmt .
io_stmt ::= export_stmt .
io_stmt ::= top_stmt .
*/
if ( Match( KW_IMPORT ) )
ImportStmt();
else if ( Match( KW_EXPORT ) )
ExportStmt();
else
TopStmt();
}
/////////////////////////////////
void Parser::ImportStmt()
{
/*
import_stmt ::= KW_IMPORT LIT_STRING as_namespace TOK_SEMI_COLON .
as_namespace ::= KW_AS TOK_IDENTIFIER .
as_namespace ::= .
*/
Expect( LIT_STRING );
if ( Match( KW_AS ) )
Expect( TOK_IDENTIFIER );
Expect( TOK_SEMI_COLON );
}
/////////////////////////////////
void Parser::ExportStmt()
{
/*
export_stmt ::= KW_EXPORT top_stmt .
*/
TopStmt();
}
/////////////////////////////////
void Parser::TopStmt()
{
/*
top_stmt ::= func_decl_stmt .
top_stmt ::= interface_decl_stmt .
top_stmt ::= class_decl_stmt .
top_stmt ::= obj_decl_stmt .
top_stmt ::= struct_decl_stmt .
top_stmt ::= namespace_decl_stmt .
top_stmt ::= enum_decl_stmt .
top_stmt ::= type_decl_stmt .
top_stmt ::= stmt .
*/
const Token* t1 = _lexer.PeekToken( 0 );
const Token* t2 = _lexer.PeekToken( 1 );
const Token* t3 = _lexer.PeekToken( 2 );
if ( t1 == nullptr )
; // TODO: complain...
if ( t1->type == TOK_IDENTIFIER )
{
if ( t2 == nullptr )
; // TODO: complain...
if ( t2->type == TOK_COLON )
{
if ( t3 == nullptr )
; // TODO: complain...
if ( t3->type == KW_FUNC )
FuncDeclStmt();
else if ( t3->type == KW_INTERFACE )
ierfaceDeclStmt();
else if ( t3->type == KW_CLASS )
ClassDeclStmt();
else if ( t3->type == KW_OBJECT )
ObjectDeclStmt();
else if ( t3->type == KW_STRUCT )
StructDeclStmt();
else if ( t3->type == KW_ENUM )
EnumDeclStmt();
else if ( t3->type == KW_TYPE )
TypeDeclStmt();
else
VarDeclStmt();
}
Stmt();
}
else if ( t1->type == KW_SCOPE )
AnonScope();
else
; // TODO: complain...
}
/////////////////////////////////
void Parser::FuncDeclStmt()
{
/*
func_decl_stmt ::= func_decl_head block KW_END .
*/
FuncDeclHead();
Block();
}
void Parser::FuncDeclHead()
{
/*
func_decl_head ::= TOK_IDENTIFIER TOK_COLON KW_FUNC TOK_LPAREN func_args TOK_RPAREN TOK_FUNC_ARROW type
func_args ::= func_args_list .
func_args ::= .
func_args_list ::= func_args_list TOK_COMMA func_arg .
func_args_list ::= func_arg .
*/
Expect( TOK_IDENTIFIER );
Expect( TOK_COLON );
Expect( KW_FUNC );
Expect( TOK_LPAREN );
while ( !Match( TOK_RPAREN ) )
{
FuncArg();
Match( TOK_COMMA );
}
Expect( TOK_RPAREN );
Expect( TOK_FUNC_ARROW );
Type();
}
void Parser::FuncArg()
{
/*
func_arg ::= TOK_IDENTIFIER TOK_COLON type .
func_arg ::= TOK_IDENTIFIER TOK_COLON_COLON type .
*/
Expect( TOK_IDENTIFIER );
if ( Match( TOK_COLON ) )
;
else
Expect( TOK_COLON_COLON );
Type();
}
/////////////////////////////////
void Parser::Type()
{
/*
type ::= TOK_IDENTIFIER .
type ::= TOK_IDENTIFIER TOK_LT type TOK_GT .
type ::= TOK_CARET type .
*/
if ( Match( TOK_CARET ) )
Type();
else
Expect( TOK_IDENTIFIER );
if ( Match( TOK_LT ) )
{
Type();
Expect( TOK_GT );
}
}
/////////////////////////////////
void Parser::TypeFuncPtr()
{
/*
type ::= TOK_CARET KW_FUNC TOK_LPAREN type_args_list TOK_RPAREN TOK_FUNC_ARROW type .
type_args_list ::= type_args_list type_arg .
type_args_list ::= type_arg .
type_arg ::= type TOK_COMMA .
type_arg ::= type .
*/
Expect( TOK_CARET );
Expect( KW_FUNC );
Expect( TOK_LPAREN );
while ( !Match( TOK_RPAREN ) )
{
Type();
if ( Match( TOK_RPAREN ) )
break;
else
Expect( TOK_COMMA );
}
Expect( TOK_RPAREN );
Expect( TOK_FUNC_ARROW );
Type();
}
/////////////////////////////////
void Parser::ierfaceDeclStmt()
{
/*
interface_stmt_decl ::= TOK_IDENTIFIER TOK_COLON KW_INTERFACE interface_body KW_END .
interface_body ::= func_head_list .
interface_body ::= .
func_head_list ::= func_head_list TOK_SEMI_COLON func_decl_head .
func_head_list ::= func_decl_head TOK_SEMI_COLON .
*/
Expect( TOK_IDENTIFIER );
Expect( TOK_COLON );
Expect( KW_INTERFACE );
while ( !Match( KW_END ) )
{
FuncDeclHead();
Expect( TOK_SEMI_COLON );
}
}
/////////////////////////////////
void Parser::ClassDeclStmt()
{
/*
*/
}
/////////////////////////////////
void Parser::ObjectDeclStmt()
{
/*
obj_decl_stmt ::= TOK_IDENTIFIER TOK_COLON KW_OBJECT obj_body KW_END .
obj_body ::= obj_stmt_list .
obj_body ::= .
obj_stmt_list ::= obj_stmt_list obj_stmt .
obj_stmt_list ::= obj_stmt .
obj_stmt ::= var_decl_infer_stmt TOK_SEMI_COLON .
obj_stmt ::= member_decl_stmt TOK_SEMI_COLON .
obj_stmt ::= member_decl_assign_stmt TOK_SEMI_COLON .
obj_stmt ::= method_decl_stmt .
obj_stmt ::= delegate_stmt .
*/
}
/////////////////////////////////
void Parser::StructDeclStmt()
{
/*
struct_stmt_decl ::= TOK_IDENTIFIER TOK_COLON KW_STRUCT struct_body KW_END .
struct_body ::= var_decl_list .
struct_body ::= .
var_decl_list ::= var_decl_list TOK_SEMI_COLON var_decl .
var_decl_list ::= var_decl .
*/
Expect( TOK_IDENTIFIER );
Expect( TOK_COLON );
Expect( KW_STRUCT );
while ( !Match( KW_END ) )
{
VarDeclStmt();
Expect( TOK_SEMI_COLON );
}
}
/////////////////////////////////
void Parser::EnumDeclStmt()
{
/*
enum_decl_stmt ::= TOK_IDENTIFIER TOK_COLON KW_ENUM enum_body KW_END .
enum_body ::= identifier_list .
enum_body ::= .
identifier_list ::= identifier_list TOK_COMMA TOK_IDENTIFIER .
identifier_list ::= TOK_IDENTIFIER .
*/
Expect( TOK_IDENTIFIER );
Expect( TOK_COLON );
Expect( KW_ENUM );
while ( !Match( KW_END ) )
{
Expect( TOK_IDENTIFIER );
if ( Match( KW_END ) )
break;
else
Expect( TOK_COMMA );
}
}
/////////////////////////////////
void Parser::TypeDeclStmt()
{
/*
type_decl_stmt ::= TOK_IDENTIFIER TOK_COLON KW_TYPE type TOK_SEMI_COLON
*/
Expect( TOK_IDENTIFIER );
Expect( TOK_COLON );
Expect( KW_TYPE );
Type();
Expect( TOK_SEMI_COLON );
}
/////////////////////////////////
void Parser::Stmt()
{
/*
stmt ::= anon_scope .
stmt ::= var_assign_stmt .
stmt ::= const_decl_infer_stmt .
stmt ::= var_decl_stmt .
stmt ::= var_decl_infer_stmt .
stmt ::= var_decl_assign_stmt .
stmt ::= top_expr .
*/
const Token* t = _lexer.PeekToken( 0 );
if ( t->type == KW_SCOPE )
AnonScope();
else if ( t->type == TOK_IDENTIFIER )
{
const Token* t = _lexer.PeekToken( 1 );
if ( t->type == TOK_EQUAL )
VarAssignStmt();
else if ( t->type == TOK_COLON_COLON )
ConstDeclInferStmt();
else if ( t->type == TOK_COLON_EQUAL )
VarDeclInferStmt();
else if ( t->type == TOK_COLON )
VarDeclAssignStmt(); // May return a 'VarDeclStmt'
else
TopExpr();
}
else
; // TODO: complain...
}
/////////////////////////////////
void Parser::AnonScope()
{
/*
anon_scope ::= KW_SCOPE block KW_END .
*/
Expect( KW_SCOPE );
Block();
}
/////////////////////////////////
void Parser::VarAssignStmt()
{
/*
*/
}
/////////////////////////////////
void Parser::ConstDeclInferStmt()
{
}
/////////////////////////////////
void Parser::VarDeclInferStmt()
{
}
/////////////////////////////////
void Parser::VarDeclAssignStmt()
{
}
/////////////////////////////////
void Parser::VarDeclStmt()
{
}
/////////////////////////////////
void Parser::TopExpr()
{
}
/////////////////////////////////
bool Parser::Match( TokenType match_type )
{
const Token* token = _lexer.PeekToken( 0 );
if ( token->type == match_type )
{
_lexer.NextToken();
return true;
}
return false;
}
void Parser::Expect( TokenType expect_type )
{
if ( !Match( expect_type ) )
{
// TODO: complain...
}
}
} }<file_sep>/Visual Studio 2013/Mesh.hpp
#ifndef ICE_GRAPHICS_MESH_HPP
#define ICE_GRAPHICS_MESH_HPP
#include "OpenGL.hpp"
#include "Common.hpp"
#include "Vec3.hpp"
#include "Vec2.hpp"
#include "Shader.hpp"
#include "Vertex.hpp"
#include "Buffers.hpp"
#include "Texture.hpp"
namespace Ice
{
class Mesh
{
public:
void AddData( std::vector<Vertex> vertices, std::vector<GLuint> indices, std::vector<Texture> textures );
void Draw( Shader& shader );
private:
void SetupMesh();
private:
GLvao _vao;
std::vector<Vertex> _vertices;
std::vector<GLuint> _indices;
std::vector<Texture> _textures;
};
}
#endif // ICE_GRAPHICS_MESH_HPP<file_sep>/Visual Studio 2013/Tests.hpp
#include "Common.hpp"
#include "Maths.hpp"
namespace Ice { namespace Test {
void test_matrix_maths()
{
Mat4 a( 1.5f );
Mat4 b( 2.5f );
std::cout << "-----------------------------------" << std::endl;
std::cout << "Basic Matrix Operations" << std::endl;
std::cout << "A: " << a << std::endl;
std::cout << "B: " << b << std::endl;
// std::cout << "A + B:\n" << a + b << std::endl;
// std::cout << "A - B:\n" << a - b << std::endl;
std::cout << "A * B:\n" << a * b << std::endl;
std::cout << "Translate: " << translate( Vec3_UnitX );
// std::cout << "Rotate: " << rotate( Constants::Pi / 4.0f, Vec3_UnitY );
std::cout << "Scale: " << scale( Vec3_One );
std::cout << "Perspective: " << perspective( Constants::Pi / 4.0f, 800.0f / 600.0f, 0.1f, 100.0f );
std::cout << "Orthgraphic: " << orthographic( -1.0f, 1.0f, -1.0f, 1.0f, 0.1f, 100.0f );
std::cout << "Look At: " << look_at( Vec3_Zero, Vec3_One, Vec3_UnitY );
std::cout << "-----------------------------------" << std::endl;
}
void test_vector2_maths()
{
const Vec2 a{ 1.5f, 1.5f };
const Vec2 b{ 2.5f, 2.5f };
constexpr f32 c = 2.0f;
std::cout << "-----------------------------------" << std::endl;
std::cout << "Vector2 Operations" << std::endl;
std::cout << "A: " << a << std::endl;
std::cout << "B: " << b << std::endl;
std::cout << "C: " << c << std::endl;
std::cout << "A + B:\n" << a + b << std::endl;
std::cout << "A - B:\n" << a - b << std::endl;
// std::cout << "A * B:\n" << a * b << std::endl; // Maybe implement this...
std::cout << "-----------------------------------" << std::endl;
std::cout << "Vector2 Scalar Operations" << std::endl;
std::cout << "A * C:\n" << a * c << std::endl;
std::cout << "C * A:\n" << c * a << std::endl;
std::cout << "A / C:\n" << a / c << std::endl;
// std::cout << "B *= C:\n" << b *= c << std::endl;
// std::cout << "B /= C:\n" << b /= c << std::endl;
std::cout << "-----------------------------------" << std::endl;
}
void test_vector3_maths()
{
const Vec3 a{ 1.5f, 1.5f, 1.5f };
const Vec3 b{ 2.5f, 2.5f, 2.5f };
constexpr f32 c = 2.0f;
std::cout << "-----------------------------------" << std::endl;
std::cout << "Vector3 Operations" << std::endl;
std::cout << "A: " << a << std::endl;
std::cout << "B: " << b << std::endl;
std::cout << "C: " << c << std::endl;
std::cout << "A + B:\n" << a + b << std::endl;
std::cout << "A - B:\n" << a - b << std::endl;
// std::cout << "A * B:\n" << a * b << std::endl; // Maybe implement this...
std::cout << "-----------------------------------" << std::endl;
std::cout << "Vector3 Scalar Operations" << std::endl;
std::cout << "A * C:\n" << a * c << std::endl;
std::cout << "C * A:\n" << c * a << std::endl;
std::cout << "A / C:\n" << a / c << std::endl;
// std::cout << "B *= C:\n" << b *= c << std::endl;
// std::cout << "B /= C:\n" << b /= c << std::endl;
std::cout << "-----------------------------------" << std::endl;
}
void test_vector4_maths()
{
const Vec4 a{ 1.5f, 1.5f, 1.5f, 1.5f };
const Vec4 b{ 2.5f, 2.5f, 2.5f, 2.5f };
constexpr f32 c = 2.0f;
std::cout << "-----------------------------------" << std::endl;
std::cout << "Vector4 Operations" << std::endl;
std::cout << "A: " << a << std::endl;
std::cout << "B: " << b << std::endl;
std::cout << "C: " << c << std::endl;
std::cout << "A + B:\n" << a + b << std::endl;
std::cout << "A - B:\n" << a - b << std::endl;
// std::cout << "A * B:\n" << a * b << std::endl; // Maybe implement this...
std::cout << "-----------------------------------" << std::endl;
std::cout << "Vector4 Scalar Operations" << std::endl;
std::cout << "A * C:\n" << a * c << std::endl;
std::cout << "C * A:\n" << c * a << std::endl;
std::cout << "A / C:\n" << a / c << std::endl;
// std::cout << "B *= C:\n" << b *= c << std::endl;
// std::cout << "B /= C:\n" << b /= c << std::endl;
std::cout << "-----------------------------------" << std::endl;
}
} }<file_sep>/Visual Studio 2013/Ast.hpp
// #ifndef ICE_SCRIPT_AST_H
// #define ICE_SCRIPT_AST_H
// #include "Types.hpp"
// #include <vector>
// namespace Ice { namespace Script { namespace Ast {
// class Node;
// class Block;
// class Stmt;
// class ImportStmt;
// class ExportStmt;
// class ClassDeclStmt;
// class FuncDeclStmt;
// class ierfaceDeclStmt;
// class StructDeclStmt;
// class TypeDeclStmt;
// class NamespaceDeclStmt;
// class ObjectDeclStmt;
// class EnumDeclStmt;
// class AssignStmt;
// class VarDeclStmt;
// class Expr;
// class ByteExpr;
// class ShortExpr;
// class iExpr;
// class LongExpr;
// class UByteExpr;
// class UShortExpr;
// class UiExpr;
// class ULongExpr;
// class StringExpr;
// class CharExpr;
// class boolExpr;
// /////////////////////////////////
// class Node
// {
// public:
// Node() {}
// virtual ~Node() {};
// virtual void PrintSelf() const = 0;
// virtual void PrintTree() const = 0;
// virtual void GenerateCode() = 0;
// protected:
// Node* _parent;
// };
// /////////////////////////////////
// class Block : public Node
// {
// public:
// Block( std::vector<Stmt> stmts )
// : _stmts( std::move( stmts ) )
// {}
// virtual ~Block() {}
// private:
// std::vector<Stmt> _stmts;
// };
// /////////////////////////////////
// class Stmt : public Node
// {
// public:
// Stmt();
// virtual ~Stmt();
// private:
// };
// /////////////////////////////////
// class Expr : public Node
// {
// public:
// Expr();
// virtual ~Expr();
// private:
// };
// /////////////////////////////////
// class ByteExpr : public Expr
// {
// public:
// ByteExpr( i8 value )
// : _value( value )
// {}
// private:
// i8 _value;
// };
// /////////////////////////////////
// class ShortExpr : public Expr
// {
// public:
// ShortExpr( i16 value )
// : _value( value )
// {}
// private:
// i16 _value;
// };
// /////////////////////////////////
// class iExpr : public Expr
// {
// public:
// iExpr( i32 value )
// : _value( value )
// {}
// private:
// i32 _value;
// };
// /////////////////////////////////
// class LongExpr : public Expr
// {
// public:
// LongExpr( i64 value )
// : _value( value )
// {}
// private:
// i64 _value;
// };
// /////////////////////////////////
// class UByteExpr : public Expr
// {
// public:
// UByteExpr( u8 value )
// : _value( value )
// {}
// private:
// u8 _value;
// };
// /////////////////////////////////
// class UShortExpr : public Expr
// {
// public:
// UShortExpr( u16 value )
// : _value( value )
// {}
// private:
// u16 _value;
// };
// /////////////////////////////////
// class UiExpr : public Expr
// {
// public:
// UiExpr( u32 value )
// : _value( value )
// {}
// private:
// u32 _value;
// };
// /////////////////////////////////
// class ULongExpr : public Expr
// {
// public:
// ULongExpr( u64 value )
// : _value( value )
// {}
// private:
// u64 _value;
// };
// /////////////////////////////////
// class StringExpr : public Expr
// {
// public:
// StringExpr( std::string value )
// : _value( value )
// {}
// private:
// std::string _value;
// };
// /////////////////////////////////
// class CharExpr : public Expr
// {
// public:
// CharExpr( i16 value )
// : _value( value )
// {}
// private:
// i16 _value;
// };
// /////////////////////////////////
// class boolExpr : public Expr
// {
// public:
// boolExpr( bool value )
// : _value( value )
// {}
// private:
// bool _value;
// };
// } } }
// #endif // ICE_SCRIPT_AST_H<file_sep>/Visual Studio 2013/Shader.cpp
#include "Common.hpp"
#include "File.hpp"
#include "Shader.hpp"
#include <vector>
namespace Ice
{
Shader::Shader( std::string vertex, std::string fragment )
{
_program = glCreateProgram();
_vert = Load( GL_VERTEX_SHADER , vertex );
_frag = Load( GL_FRAGMENT_SHADER, fragment );
Compile();
}
Shader::~Shader()
{
glDetachShader( _program, _vert );
glDetachShader( _program, _frag );
glDeleteProgram( _program );
}
void Shader::RegisterUniform( const GLchar* name )
{
GLint uniform = glGetUniformLocation( _program, name );
_uniform_locations.emplace( name, uniform );
}
void Shader::UpdateUniform( const GLchar* name, u32 value )
{
glUniform1i( GetUniformLocation( name ), value );
}
void Shader::UpdateUniform( const GLchar* name, i32 value )
{
glUniform1i( GetUniformLocation( name ), value );
}
void Shader::UpdateUniform( const GLchar* name, f32 value )
{
glUniform1f( GetUniformLocation( name ), value );
}
void Shader::UpdateUniform( const GLchar* name, i32* values, i32 count )
{
glUniform1iv( GetUniformLocation( name ), count, values );
}
void Shader::UpdateUniform( const GLchar* name, f32* values, i32 count )
{
glUniform1fv( GetUniformLocation( name ), count, values );
}
void Shader::UpdateUniform( const GLchar* name, const Vec2& vec )
{
glUniform2fv( GetUniformLocation( name ), 2, vec.elements );
}
void Shader::UpdateUniform( const GLchar* name, const Vec3& vec )
{
glUniform3fv( GetUniformLocation( name ), 3, vec.elements );
}
void Shader::UpdateUniform( const GLchar* name, const Vec4& vec )
{
glUniform4fv( GetUniformLocation( name ), 4, vec.elements );
}
void Shader::UpdateUniform( const GLchar* name, const Mat4& mat )
{
glUniformMatrix4fv( GetUniformLocation( name ), 1, GL_FALSE, mat.elements );
}
GLint Shader::GetUniformLocation( const GLchar* name )
{
auto location = _uniform_locations.find( name );
if ( location == _uniform_locations.end() )
{
GLint uniform = glGetUniformLocation( _program, name );
_uniform_locations.emplace( name, uniform );
return uniform;
}
else
return location->second;
}
void Shader::Bind() const
{
glUseProgram( _program );
}
void Shader::UnBind() const
{
glUseProgram( 0 );
}
GLuint Shader::Load( GLuint type, std::string& name )
{
std::cout << "Loading shader: " << name << std::endl;
std::string str;
Common::read_file( name, &str );
GLuint shader = glCreateShader( type );
const char* source = str.c_str();
glShaderSource ( shader, 1, &source, NULL );
glCompileShader( shader );
GLint result;
glGetShaderiv( shader, GL_COMPILE_STATUS, &result );
if ( result == GL_FALSE )
{
GLint length;
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &length );
char error[ length ];
glGetShaderInfoLog( shader, length, nullptr, &error[0] );
std::cerr << &error[0] << std::endl;
glDeleteShader( shader );
return 0;
}
return shader;
}
void Shader::Compile()
{
std::cout << "Building shader program..." << std::endl;
glAttachShader( _program, _vert );
glAttachShader( _program, _frag );
glLinkProgram ( _program );
glValidateProgram( _program );
GLint result;
glGetProgramiv( _program, GL_VALIDATE_STATUS, &result );
if ( result == GL_FALSE )
{
GLint length;
glGetProgramiv( _program, GL_INFO_LOG_LENGTH, &length );
std::vector<char> error( length );
glGetShaderInfoLog( _program, length, nullptr, &error[0] );
std::cerr << &error[0] << std::endl;
glDeleteProgram( _program );
}
glDeleteShader( _vert );
glDeleteShader( _frag );
std::cout << "Successfully built shader program." << std::endl;
}
}<file_sep>/Visual Studio 2013/Buffers.hpp
#ifndef ICE_BUFFERS_H
#define ICE_BUFFERS_H
#include "Types.hpp"
#include "OpenGL.hpp"
/*
A set of simple RAII classes to wrap the
creation, deletion and usage of OpenGL
buffer objects.
*/
namespace Ice
{
template<GLenum TARGET>
class Buffer
{
public:
Buffer()
{
glGenBuffers( 1, &_handle );
}
~Buffer()
{
glDeleteBuffers( 1, &_handle );
}
void Bind()
{
glBindBuffer( TARGET, _handle );
}
void UnBind()
{
glBindBuffer( TARGET, 0 );
}
void BufferData( GLsizeiptr size, const GLvoid* data, GLenum usage )
{
glBufferData( TARGET, size, data, usage );
}
private:
GLuint _handle;
};
/////////////////////////////////
typedef Buffer<GL_ARRAY_BUFFER> VertexBuffer;
typedef Buffer<GL_ELEMENT_ARRAY_BUFFER> ElementBuffer;
/////////////////////////////////
class GLvao
{
public:
GLvao();
~GLvao();
void Bind();
void UnBind();
VertexBuffer& VBO();
ElementBuffer& EBO();
// VAP ( VertexAttribPointer )
void SetVAP( GLuint index, GLint size, GLenum type, GLboolean normalised, GLsizei stride, const GLvoid* pointer );
private:
GLuint _handle;
VertexBuffer _vbo;
ElementBuffer _ebo;
};
}
#endif // ICE_BUFFERS_H<file_sep>/Visual Studio 2013/Lexer.cpp
#include "File.hpp"
#include "Lexer.hpp"
#include <fstream>
#include <sstream>
#include <iostream>
namespace Ice { namespace Script {
/////////////////////////////////
// The individual lexing functions.
LexerMode* mode_start( Lexer* lexer )
{
char c = lexer->PeekChar( 1 );
if ( c == '\0' )
return &LexerMode::End;
else if ( isspace( c ) )
return &LexerMode::SkipSpace;
else if ( isalpha( c ) || c == '_' )
return &LexerMode::Identifier;
else if ( isdigit( c ) )
return &LexerMode::Number;
else if ( c == '"' )
return &LexerMode::String;
else if ( c == '\'' )
return &LexerMode::Char;
else if ( ispunct( c ) )
return &LexerMode::Punctuation;
else
return &LexerMode::End;
}
/////////////////////////////////
LexerMode* mode_end( Lexer* lexer )
{
lexer->AddToken( "eof", TOK_EOF );
return &LexerMode::End;
}
/////////////////////////////////
LexerMode* mode_identifier( Lexer* lexer )
{
std::string buffer;
char c;
while ( true )
{
c = lexer->PeekChar( 1 );
if ( isalnum( c ) || c == '_' )
{
buffer += c;
lexer->NextChar();
continue;
}
break;
}
// Keywords
if ( buffer == "borrow" ) lexer->AddToken( buffer, KW_BORROW );
else if ( buffer == "cast" ) lexer->AddToken( buffer, KW_CAST );
else if ( buffer == "import" ) lexer->AddToken( buffer, KW_IMPORT );
else if ( buffer == "from" ) lexer->AddToken( buffer, KW_FROM );
else if ( buffer == "using" ) lexer->AddToken( buffer, KW_USING );
else if ( buffer == "as" ) lexer->AddToken( buffer, KW_AS );
else if ( buffer == "func" ) lexer->AddToken( buffer, KW_FUNC );
else if ( buffer == "return" ) lexer->AddToken( buffer, KW_RETURN );
else if ( buffer == "yield" ) lexer->AddToken( buffer, KW_YIELD );
else if ( buffer == "struct" ) lexer->AddToken( buffer, KW_STRUCT );
else if ( buffer == "enum" ) lexer->AddToken( buffer, KW_ENUM );
else if ( buffer == "class" ) lexer->AddToken( buffer, KW_CLASS );
else if ( buffer == "object" ) lexer->AddToken( buffer, KW_OBJECT );
else if ( buffer == "this" ) lexer->AddToken( buffer, KW_THIS );
else if ( buffer == "static" ) lexer->AddToken( buffer, KW_STATIC );
else if ( buffer == "interface" ) lexer->AddToken( buffer, KW_INTERFACE );
else if ( buffer == "delegate" ) lexer->AddToken( buffer, KW_DELEGATE );
else if ( buffer == "type" ) lexer->AddToken( buffer, KW_TYPE );
else if ( buffer == "new" ) lexer->AddToken( buffer, KW_NEW );
else if ( buffer == "delete" ) lexer->AddToken( buffer, KW_DELETE );
else if ( buffer == "owner" ) lexer->AddToken( buffer, KW_OWNER );
else if ( buffer == "view" ) lexer->AddToken( buffer, KW_VIEW );
else if ( buffer == "scope" ) lexer->AddToken( buffer, KW_SCOPE );
else if ( buffer == "end" ) lexer->AddToken( buffer, KW_END );
else if ( buffer == "if" ) lexer->AddToken( buffer, KW_IF );
else if ( buffer == "else" ) lexer->AddToken( buffer, KW_ELSE );
else if ( buffer == "for" ) lexer->AddToken( buffer, KW_FOR );
else if ( buffer == "in" ) lexer->AddToken( buffer, KW_IN );
else if ( buffer == "while" ) lexer->AddToken( buffer, KW_WHILE );
else if ( buffer == "break" ) lexer->AddToken( buffer, KW_BREAK );
else if ( buffer == "continue" ) lexer->AddToken( buffer, KW_CONTINUE );
// Literals
else if ( buffer == "null" ) lexer->AddToken( buffer, LIT_NULL );
else if ( buffer == "true" ) lexer->AddToken( buffer, LIT_BOOLEAN );
else if ( buffer == "false" ) lexer->AddToken( buffer, LIT_BOOLEAN );
// Identifiers
else
lexer->AddToken( buffer, TOK_IDENTIFIER );
return &LexerMode::Start;
}
/////////////////////////////////
LexerMode* mode_punctuation( Lexer* lexer )
{
char c = lexer->NextChar();
if ( c == '(' )
lexer->AddToken( "(", TOK_LPAREN );
else if ( c == ')' )
lexer->AddToken( ")", TOK_RPAREN );
else if ( c == '{' )
lexer->AddToken( "{", TOK_LCURLY );
else if ( c == '}' )
lexer->AddToken( "}", TOK_RCURLY );
else if ( c == '[' )
lexer->AddToken( "[", TOK_LSQUARE );
else if ( c == ']' )
lexer->AddToken( "]", TOK_RSQUARE );
else if ( c == ';' )
lexer->AddToken( ";", TOK_SEMI_COLON );
else if ( c == '?' )
lexer->AddToken( "?", TOK_QUESTION );
else if ( c == '.' )
lexer->AddToken( ".", TOK_DOT );
else if ( c == '@' )
lexer->AddToken( "@", TOK_AT );
else if ( c == '$' )
lexer->AddToken( "$", TOK_DOLLAR );
else if ( c == ',' )
lexer->AddToken( ",", TOK_COMMA );
else if ( c == '~' )
lexer->AddToken( "~", TOK_TILDE );
else if ( c == '^' )
lexer->AddToken( "^", TOK_CARET );
else if ( c == '=' )
{
char n = lexer->PeekChar( 1 );
if ( n == '=' )
{
lexer->AddToken( "==", TOK_EQUAL_EQUAL );
lexer->NextChar();
}
else
lexer->AddToken( "=", TOK_EQUAL );
}
else if ( c == ':' )
{
char n = lexer->PeekChar( 1 );
if ( n == '=' )
{
lexer->AddToken( ":=", TOK_COLON_EQUAL );
lexer->NextChar();
}
else if ( n == ':' )
{
lexer->AddToken( "::", TOK_COLON_COLON );
lexer->NextChar();
}
else
lexer->AddToken( ":", TOK_COLON );
}
else if ( c == '>' )
{
char n = lexer->PeekChar( 1 );
if ( n == '=' )
{
lexer->AddToken( ">=", TOK_GT_EQUAL );
lexer->NextChar();
}
else if ( n == '>' )
{
lexer->AddToken( ">>", TOK_RSHIFT );
lexer->NextChar();
}
else
lexer->AddToken( ">", TOK_GT );
}
else if ( c == '<' )
{
char n = lexer->PeekChar( 1 );
if ( n == '=' )
{
lexer->AddToken( "<=", TOK_LT_EQUAL );
lexer->NextChar();
}
else if ( n == '<' )
{
lexer->AddToken( "<<", TOK_LSHIFT );
lexer->NextChar();
}
else
lexer->AddToken( "<", TOK_LT );
}
else if ( c == '!' )
{
char n = lexer->PeekChar( 1 );
if ( n == '=' )
{
lexer->AddToken( "!=", TOK_EXCLAMATION_EQUAL );
lexer->NextChar();
}
else
lexer->AddToken( "!", TOK_EXCLAMATION );
}
else if ( c == '&' )
{
char n = lexer->PeekChar( 1 );
if ( n == '&' )
{
lexer->AddToken( "&&", TOK_AMP_AMP );
lexer->NextChar();
}
else
lexer->AddToken( "&", TOK_AMP );
}
else if ( c == '|' )
{
char n = lexer->PeekChar( 1 );
if ( n == '|' )
{
lexer->AddToken( "||", TOK_PIPE_PIPE );
lexer->NextChar();
}
else
lexer->AddToken( "|", TOK_PIPE );
}
else if ( c == '%' )
{
char n = lexer->PeekChar( 1 );
if ( n == '=' )
{
lexer->AddToken( "%=", TOK_MODULO_EQUAL );
lexer->NextChar();
}
else
lexer->AddToken( "%", TOK_MODULO );
}
else if ( c == '+' )
{
char n = lexer->PeekChar( 1 );
if ( n == '=' )
{
lexer->AddToken( "+=", TOK_ADD_EQUAL );
lexer->NextChar();
}
else if ( n == '+' )
{
lexer->AddToken( "++", TOK_INCREMENT );
lexer->NextChar();
}
else
lexer->AddToken( "+", TOK_ADD );
}
else if ( c == '-' )
{
char n = lexer->PeekChar( 1 );
if ( n == '=' )
{
lexer->AddToken( "-=", TOK_SUB_EQUAL );
lexer->NextChar();
}
else if ( n == '-' )
{
lexer->AddToken( "--", TOK_DECREMENT );
lexer->NextChar();
}
else if ( n == '>' )
{
lexer->AddToken( "->", TOK_FUNC_ARROW );
lexer->NextChar();
}
else
lexer->AddToken( "-", TOK_SUB );
}
else if ( c == '*' )
{
char n = lexer->PeekChar( 1 );
if ( n == '=' )
{
lexer->AddToken( "*=", TOK_MUL_EQUAL );
lexer->NextChar();
}
else
lexer->AddToken( "*", TOK_MUL );
}
else if ( c == '/' )
{
char n = lexer->PeekChar( 1 );
if ( n == '/' )
{
return &LexerMode::SkipLineComment;
lexer->NextChar();
}
else if ( n == '*' )
{
return &LexerMode::SkipBlockComment;
lexer->NextChar();
}
else if ( n == '=' )
{
lexer->AddToken( "/=", TOK_DIV_EQUAL );
lexer->NextChar();
}
else
lexer->AddToken( "/", TOK_DIV );
}
else
{
// TODO: Do this better!
std::string lexeme;
lexeme += c;
lexer->AddToken( lexeme, TOK_UNDEF );
}
return &LexerMode::Start;
}
/////////////////////////////////
LexerMode* mode_skip_line_comment( Lexer* lexer )
{
char c;
while ( true )
{
c = lexer->NextChar();
if ( c == '\n' )
break;
}
return &LexerMode::Start;
}
LexerMode* mode_skip_block_comment( Lexer* lexer )
{
i32 block_depth = 1;
char c;
while ( true )
{
c = lexer->NextChar();
if ( c == '/' )
{
c = lexer->PeekChar( 1 );
if ( c == '*' )
{
++block_depth;
lexer->NextChar();
}
}
if ( c == '*' )
{
c = lexer->PeekChar( 1 );
if ( c == '/' )
{
--block_depth;
lexer->NextChar();
}
}
// If we see the end of the file,
// then the program doesn't have a
// closing blocks.
if ( c == '\0' )
return &LexerMode::End;
if ( block_depth == 0 )
break;
}
return &LexerMode::Start;
}
/////////////////////////////////
LexerMode* mode_skip_space( Lexer* lexer )
{
char c;
while ( true )
{
c = lexer->PeekChar( 1 );
if ( isspace( c ) )
{
lexer->NextChar();
continue;
}
break;
}
return &LexerMode::Start;
}
/////////////////////////////////
LexerMode* mode_string( Lexer* lexer )
{
std::string buffer;
char c = lexer->PeekChar( 1 );
char p = c;
while ( true )
{
p = c;
c = lexer->NextChar();
if ( c == '\"' )
{
if ( c == p )
continue;
else if ( p == '\\' )
buffer += c;
else
break;
}
else
buffer += c;
}
lexer->AddToken( buffer, LIT_STRING );
return &LexerMode::Start;
}
/////////////////////////////////
LexerMode* mode_char( Lexer* lexer )
{
std::string buffer;
char c = lexer->PeekChar( 1 );
char p = c;
while ( true )
{
p = c;
c = lexer->NextChar();
if ( c == '\'' )
{
if ( c == p )
continue;
else if ( p == '\\' )
buffer += c;
else
break;
}
else
buffer += c;
}
lexer->AddToken( buffer, LIT_CHAR );
return &LexerMode::Start;
}
/////////////////////////////////
LexerMode* mode_number( Lexer* lexer )
{
char c = lexer->PeekChar( 1 );
char n = lexer->PeekChar( 2 );
std::string buffer;
bool is_int_type = true;
bool is_unsigned = false;
if ( c == '0' && n == 'x' )
return &LexerMode::HexNumber;
else if ( c == '0' && n == 'o' )
return &LexerMode::OctNumber;
else
{
while ( true )
{
c = lexer->NextChar();
if ( c == '.' )
{
if ( is_int_type )
is_int_type = false;
else
{
lexer->AddToken( buffer, TOK_UNDEF );
break;
}
buffer += c;
}
else if ( c == '-' )
{
if ( !is_unsigned )
is_unsigned = true;
else
{
lexer->AddToken( buffer, TOK_UNDEF );
break;
}
buffer += c;
}
else if ( isdigit( c ) || c == '.' || c =='-' )
buffer += c;
else
{
if ( is_int_type )
{
if ( c == 'u' )
lexer->AddToken( buffer, LIT_UINT );
else
lexer->AddToken( buffer, LIT_INT );
}
else
{
switch( c )
{
case 'f':
lexer->AddToken( buffer, LIT_FLOAT );
break;
case 'd':
lexer->AddToken( buffer, LIT_DOUBLE );
break;
default:
lexer->AddToken( buffer, LIT_DOUBLE );
break;
}
}
break;
}
}
c = lexer->NextChar();
}
return &LexerMode::Start;
}
/////////////////////////////////
LexerMode* mode_hex_number( Lexer* lexer )
{
std::string buffer;
char c;
// Skip over the '0x'
lexer->NextChar();
lexer->NextChar();
while ( true )
{
c = lexer->PeekChar( 1 );
if ( isxdigit( c ) )
{
buffer += c;
lexer->NextChar();
continue;
}
break;
}
lexer->AddToken( buffer, LIT_HEX );
return &LexerMode::Start;
}
/////////////////////////////////
LexerMode* mode_oct_number( Lexer* lexer )
{
std::string buffer;
char c;
// Skip over the '0x'
lexer->NextChar();
lexer->NextChar();
while ( true )
{
c = lexer->PeekChar( 1 );
// if ( c >= '0' && c <= '7' ) // Untested
if ( c == '0'
|| c == '1'
|| c == '2'
|| c == '3'
|| c == '4'
|| c == '5'
|| c == '6'
|| c == '7' )
{
buffer += c;
lexer->NextChar();
continue;
}
break;
}
lexer->AddToken( buffer, LIT_HEX );
return &LexerMode::Start;
}
/////////////////////////////////
// Initialise the lexing states.
LexerMode LexerMode::Start = { &mode_start };
LexerMode LexerMode::End = { &mode_end };
LexerMode LexerMode::Identifier = { &mode_identifier };
LexerMode LexerMode::Punctuation = { &mode_punctuation };
LexerMode LexerMode::SkipLineComment = { &mode_skip_line_comment };
LexerMode LexerMode::SkipBlockComment = { &mode_skip_block_comment };
LexerMode LexerMode::SkipSpace = { &mode_skip_space };
LexerMode LexerMode::String = { &mode_string };
LexerMode LexerMode::Char = { &mode_char };
LexerMode LexerMode::Number = { &mode_number };
LexerMode LexerMode::HexNumber = { &mode_hex_number };
LexerMode LexerMode::OctNumber = { &mode_oct_number };
/////////////////////////////////
bool LexerMode::operator==( const LexerMode& other ) const { return &Func == &other.Func; }
bool LexerMode::operator!=( const LexerMode& other ) const { return !( (*this) == other ); }
/////////////////////////////////
void Lexer::Run( const std::string& filename )
{
_filename = filename;
_mode = &LexerMode::Start;
// Get the new program source.
Common::read_file( _filename, &(_source) );
while( true )
{
_mode = _mode->Func( this );
if ( *(_mode) == LexerMode::End )
break;
}
_mode->Func( this );
}
/////////////////////////////////
void Lexer::Reset()
{
_token_index = -1;
}
/////////////////////////////////
const Token* Lexer::NextToken()
{
// If there are tokens ahead of the
// counter then increment and return.
if ( _token_index < static_cast<i32>( _tokens.size() ) - 1 )
++_token_index;
return &(_tokens[ _token_index ]);
}
const Token* Lexer::PeekToken( i32 n )
{
if ( _token_index + n < static_cast<i32>( _tokens.size() ) )
return &(_tokens[ _token_index + n ]);
return nullptr;
}
/////////////////////////////////
char Lexer::NextChar()
{
if ( _char_index < static_cast<i32>( _source.size() ) )
{
++_char_index;
++_column;
}
char c = _source[ _char_index ];
if ( c == '\n' )
{
++_line;
_column = 1;
}
return c;
}
char Lexer::PeekChar( i32 n )
{
if ( _char_index + n < static_cast<i32>( _source.size() ) )
return _source[ _char_index + n ];
return '\0';
}
/////////////////////////////////
void Lexer::AddToken( const std::string& lexeme, TokenType type )
{
i32 column = _column - static_cast<i32>( lexeme.length() );
// The length of the lexeme is the length of
// the string minus the two quotation characters.
if ( type == LIT_STRING || type == LIT_CHAR )
column -= 2;
_tokens.emplace_back( Token{
lexeme,
type,
_line,
column
});
}
} }<file_sep>/Visual Studio 2013/Window.cpp
#include "Common.hpp"
#include "Window.hpp"
namespace Ice
{
static void on_window_resize( GLFWwindow* window, i32 width, i32 height )
{
Window::SetSize( width, height );
i32 buffer_width;
i32 buffer_height;
glfwGetFramebufferSize( window, &buffer_width, &buffer_height );
glViewport( 0, 0, buffer_width, buffer_height );
}
/////////////////////////////////
u32 Window::_width = 600;
u32 Window::_height = 800;
Window::Window( const WindowConfig&& cfg )
: _window( nullptr )
{
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 );
glfwWindowHint( GLFW_OPENGL_PROFILE , GLFW_OPENGL_CORE_PROFILE );
_title = cfg.title;
_width = cfg.width;
_height = cfg.height;
_fullscreen = cfg.fullscreen;
CreateWindow();
// TODO:
// throw exceptions when we encounter errors.
if ( _window == nullptr )
{
std::cerr << "Failed to create a window." << std::endl;
glfwTerminate();
exit( EXIT_FAILURE );
}
glewExperimental = GL_TRUE;
if ( glewInit() != GLEW_OK )
{
std::cerr << "Failed to initialise GLEW." << std::endl;
exit( EXIT_FAILURE );
}
}
Window::~Window()
{
glfwDestroyWindow( _window );
}
void Window::Update()
{
glfwPollEvents();
// Switch to fullscreen mode.
if ( glfwGetKey( _window, GLFW_KEY_F11 ) )
{
_fullscreen = !_fullscreen;
CreateWindow();
if ( _window == nullptr )
{
std::cerr << "Failed to switch window mode." << std::endl;
glfwTerminate();
exit( EXIT_FAILURE );
}
}
}
void Window::Flip()
{
glfwSwapBuffers( _window );
}
bool Window::IsOpen() const
{
return !glfwWindowShouldClose( _window );
}
void Window::CreateWindow()
{
GLFWwindow* new_window = nullptr;
GLFWmonitor* primary = nullptr;
i32 width = _width;
i32 height = _height;
if ( _fullscreen )
{
primary = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode( primary );
width = mode->width;
height = mode->height;
}
new_window = glfwCreateWindow( width, height,
_title.c_str(),
primary, _window );
if ( _window != nullptr )
glfwDestroyWindow( _window );
_window = new_window;
glViewport( 0, 0, width, height );
glfwMakeContextCurrent( _window );
// Enable Vsync.
glfwSwapInterval( 1 );
// Register callbacks
// glfwSetCursorPosCallback ( _window, cursor_input );
// glfwSetCursorEnterCallback( _window, cursor_enter );
// glfwSetMouseButtonCallback( _window, button_input );
// glfwSetScrollCallback ( _window, scroll_input );
// glfwSetKeyCallback ( _window, key_input );
// glfwSetCharModsCallback ( _window, text_input );
glfwSetWindowSizeCallback( _window, on_window_resize );
}
void Window::SetSize( u32 width, u32 height )
{
_width = width;
_height = height;
}
u32 Window::GetWidth () { return _width; }
u32 Window::GetHeight() { return _height; }
}<file_sep>/Visual Studio 2013/Vertex.hpp
#ifndef ICE_VERTEX_H
#define ICE_VERTEX_H
#include "Types.hpp"
#include "OpenGL.hpp"
#include "Common.hpp"
#include "Maths.hpp"
#include "Colour.hpp"
namespace Ice
{
struct Vertex
{
Vec3 position;
Vec3 normal;
Colour colour;
Vec2 tex_coord;
};
#define VERTEX_SIZE sizeof( Vertex )
#define V_COMPONENTS_P 3
#define V_TYPE_P GL_FLOAT
#define V_NORMALISE_P GL_FALSE
#define V_OFFSET_P (GLvoid*) offsetof( Vertex, position )
#define V_COMPONENTS_N 3
#define V_TYPE_N GL_FLOAT
#define V_NORMALISE_N GL_FALSE
#define V_OFFSET_N (GLvoid*) offsetof( Vertex, normal )
#define V_COMPONENTS_C 4
#define V_TYPE_C GL_UNSIGNED_BYTE
#define V_NORMALISE_C GL_TRUE
#define V_OFFSET_C (GLvoid*) offsetof( Vertex, colour )
#define V_COMPONENTS_T 2
#define V_TYPE_T GL_FLOAT
#define V_NORMALISE_T GL_FALSE
#define V_OFFSET_T (GLvoid*) offsetof( Vertex, tex_coord )
}
#endif // ICE_VERTEX_H<file_sep>/Visual Studio 2013/Vec4.hpp
#ifndef ICE_MATHS_VEC4_HPP
#define ICE_MATHS_VEC4_HPP
#include "Common.hpp"
#include "Types.hpp"
#include "Functions.hpp"
#include <cmath>
namespace Ice
{
struct Vec2;
struct Vec3;
/////////////////////////////////
struct Vec4
{
Vec4();
Vec4( f32 xyzw[ 4 ] );
Vec4( f32 x, f32 y, f32 z, f32 w );
explicit Vec4( f32 xyzw );
explicit Vec4( const Vec2& vec, f32 z, f32 w );
explicit Vec4( const Vec2& xy, const Vec2& zw );
explicit Vec4( const Vec3& vec, f32 w );
Vec4( const Vec4& vec );
Vec4( Vec4&& vec );
inline Vec4& operator=( const Vec4& vec )
{
x = vec.x;
y = vec.y;
z = vec.z;
w = vec.w;
return *this;
}
inline Vec4& operator=( Vec4&& vec )
{
x = vec.x;
y = vec.y;
z = vec.z;
w = vec.w;
return *this;
}
inline f32& operator[]( usize index ) { return elements[ index ]; }
inline const f32& operator[]( usize index ) const { return elements[ index ]; }
inline Vec4 operator+( const Vec4& r ) const { return Vec4{ x + r.x, y + r.y, z + r.z, w + r.w }; }
inline Vec4 operator-( const Vec4& r ) const { return Vec4{ x - r.x, y - r.y, z - r.z, w - r.w }; }
inline Vec4 operator*( f32 r ) const { return Vec4{ x * r , y * r , z * r , w * r }; }
inline Vec4 operator/( f32 r ) const { return Vec4{ x / r , y / r , z / r , w / r }; }
// Hadamard Product
// inline Vec4 operator*( const Vec4& r ) const
// {
// return Vec4{ x * r.x,
// y * r.y,
// z * r.z,
// w * r.w };
// }
inline Vec4& operator+=( const Vec4& r ) { return ( *this = (*this) + r ); }
inline Vec4& operator-=( const Vec4& r ) { return ( *this = (*this) - r ); }
inline Vec4& operator*=( f32 r ) { return ( *this = (*this) * r ); }
inline Vec4& operator/=( f32 r ) { return ( *this = (*this) / r ); }
inline bool operator==( const Vec4& other ) const
{
return x == other.x
&& y == other.y
&& z == other.z
&& w == other.w;
}
inline bool operator!=( const Vec4& other ) const
{
return !operator==( other );
}
union
{
f32 elements[ 4 ];
struct { f32 x, y, z, w; };
struct { f32 r, g, b, a; };
struct { f32 s, t, p, q; };
};
};
/////////////////////////////////
const Vec4 Vec4_Zero = Vec4{ 0.0f, 0.0f, 0.0f, 0.0f };
const Vec4 Vec4_One = Vec4{ 1.0f, 1.0f, 1.0f, 1.0f };
const Vec4 Vec4_UnitX = Vec4{ 1.0f, 0.0f, 0.0f, 0.0f };
const Vec4 Vec4_UnitY = Vec4{ 0.0f, 1.0f, 0.0f, 0.0f };
const Vec4 Vec4_UnitZ = Vec4{ 0.0f, 0.0f, 1.0f, 0.0f };
const Vec4 Vec4_UnitW = Vec4{ 0.0f, 0.0f, 0.0f, 1.0f };
/////////////////////////////////
VECTOR_FUNCTIONS( 4, Vec4 )
/////////////////////////////////
inline std::ostream& operator<<( std::ostream& stream, const Vec4& v )
{
return stream << "Vec4<(" << v.x << ", " << v.y << ", " << v.z << ", " << v.w << ")>";
}
}
#endif // ICE_MATHS_VEC4_HPP<file_sep>/Visual Studio 2013/Parser.hpp
#ifndef ICE_SCRIPT_PARSER_H
#define ICE_SCRIPT_PARSER_H
#include "Types.hpp"
#include "SymbolTable.hpp"
#include "Ast.hpp"
#include "Lexer.hpp"
namespace Ice { namespace Script {
class Parser
{
public:
Parser( SymbolTable* global );
void Run( const std::string& filename );
private:
void BuildTypeTable();
void Block();
void IOStmt();
void ImportStmt();
void ExportStmt();
void TopStmt();
void FuncDeclStmt();
void FuncDeclHead();
void FuncArg();
void Type();
void TypeFuncPtr();
void ierfaceDeclStmt();
void ClassDeclStmt();
void ObjectDeclStmt();
void StructDeclStmt();
void EnumDeclStmt();
void TypeDeclStmt();
void Stmt();
void AnonScope();
void VarAssignStmt();
void ConstDeclInferStmt();
void VarDeclAssignStmt();
void VarDeclInferStmt();
void VarDeclStmt();
void TopExpr();
bool Match ( TokenType match_type );
void Expect( TokenType expect_type );
private:
SymbolTable* _global;
Lexer _lexer;
};
} }
#endif // ICE_SCRIPT_PARSER_H<file_sep>/Visual Studio 2013/Token.hpp
#ifndef ICE_SCRIPT_TOKEN_H
#define ICE_SCRIPT_TOKEN_H
#include "Types.hpp"
namespace Ice { namespace Script {
enum TokenType
{
TOK_IDENTIFIER, /* ^([_a-zA-Z][_a-zA-Z0-9]*) */
LIT_INT, /* ^([-+0-9][0-9]+) */
LIT_UINT, /* ^([0-9]+u) */
LIT_FLOAT, /* ^([-+0-9][0-9]+\.[0-9]+f) */
LIT_DOUBLE, /* ^([-+0-9][0-9]+\.[0-9]+d?) */
LIT_HEX, /* ^(0x[0-9a-fA-F]+) */
LIT_BINARY, /* ^(0b[0-1]+) */
LIT_OCTAL, /* ^(0o[0-7]+) */
LIT_BOOLEAN, /* ^(true|false) */
LIT_CHAR, /* ^('[^']') */
LIT_STRING, /* ^("[^"]*") */
LIT_NULL, /* ^(null) */
KW_USING, /* using */
KW_AS, /* as */
KW_DELEGATE, /* delegate */
KW_THIS, /* this */
KW_END, /* end */
KW_SCOPE, /* scope */
KW_STATIC, /* static */
KW_IMPORT, /* import */
KW_FROM, /* from */
KW_FUNC, /* func */
KW_STRUCT, /* struct */
KW_ENUM, /* enum */
KW_CLASS, /* class */
KW_OBJECT, /* object */
KW_INTERFACE, /* interface */
KW_TYPE, /* type */
KW_NEW, /* new */
KW_DELETE, /* delete */
KW_OWNER, /* owner */
KW_BORROW, /* borrow */
KW_VIEW, /* view */
KW_CAST, /* cast */
KW_IF, /* if */
KW_ELSE, /* else */
KW_FOR, /* for */
KW_IN, /* in */
KW_WHILE, /* while */
KW_BREAK, /* break */
KW_CONTINUE, /* continue */
KW_RETURN, /* return */
KW_YIELD, /* yield */
TOK_LPAREN, /* ( */
TOK_RPAREN, /* ) */
TOK_LCURLY, /* { */
TOK_RCURLY, /* } */
TOK_LSQUARE, /* [ */
TOK_RSQUARE, /* ] */
TOK_EQUAL, /* = */
TOK_EQUAL_EQUAL, /* == */
TOK_COLON, /* : */
TOK_COLON_COLON, /* :: */
TOK_COLON_EQUAL, /* := */
TOK_SEMI_COLON, /* ; */
TOK_FUNC_ARROW, /* -> */
TOK_GT, /* > */
TOK_GT_EQUAL, /* >= */
TOK_LT, /* < */
TOK_LT_EQUAL, /* <= */
TOK_LSHIFT, /* << */
TOK_RSHIFT, /* >> */
TOK_EXCLAMATION, /* ! */
TOK_EXCLAMATION_EQUAL, /* != */
TOK_AMP, /* & */
TOK_AMP_AMP, /* && */
TOK_PIPE, /* | */
TOK_PIPE_PIPE, /* || */
TOK_QUESTION, /* ? */
TOK_DOT, /* . */
TOK_AT, /* @ */
TOK_DOLLAR, /* $ */
TOK_COMMA, /* , */
TOK_TILDE, /* ~ */
TOK_CARET, /* ^ */
TOK_MODULO, /* % */
TOK_MODULO_EQUAL, /* %= */
TOK_ADD, /* + */
TOK_ADD_EQUAL, /* += */
TOK_SUB, /* - */
TOK_SUB_EQUAL, /* -= */
TOK_MUL, /* * */
TOK_MUL_EQUAL, /* *= */
TOK_DIV, /* / */
TOK_DIV_EQUAL, /* /= */
TOK_INCREMENT, /* ++ */
TOK_DECREMENT, /* -- */
TOK_EOF, /* The end of the file. This is added manually. */
TOK_UNDEF /* Appears if the lexer encounters something it doesn't understand. */
};
/////////////////////////////////
struct Token
{
std::string lexeme;
TokenType type;
int line;
int column;
};
} }
#endif // ICE_SCRIPT_TOKEN_H<file_sep>/Visual Studio 2013/Common.hpp
#ifndef ICE_COMMON_HPP
#define ICE_COMMON_HPP
#include "Types.hpp"
#include <stdexcept>
#include <cassert>
#include <cstddef>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stack>
#include <vector>
#include <functional>
#include <limits>
#include <memory>
namespace Impl
{
template <typename Fn>
struct Defer
{
Defer( Fn&& fn )
: fn{ std::forward<Fn>( fn ) }
{}
~Defer() { fn(); };
Fn fn;
};
template <typename Fn>
Defer<Fn> deferFn( Fn&& fn )
{
return Defer<Fn>( std::forward<Fn>( fn ) );
}
}
#define DEFER_1( x, y ) x##y
#define DEFER_2( x, y ) DEFER_1( x, y )
#define DEFER_3( x ) DEFER_2( x, __COUNTER__ )
#define defer( code ) auto DEFER_3( _defer_ ) = Impl::deferFn( [&](){code;} );
#endif // ICE_COMMON_HPP<file_sep>/Visual Studio 2013/Renderer.hpp
#ifndef ICE_RENDERER_H
#define ICE_RENDERER_H
#include "Types.hpp"
#include "NonCopy.hpp"
#include "Maths.hpp"
#include "RenderContext.hpp"
// temp
#include "Mesh.hpp"
#include "Shader.hpp"
#include "Texture.hpp"
#include "Transform.hpp"
#include <GL/glew.h>
namespace Ice
{
class Renderer : public Common::NonCopyable
{
public:
Renderer();
~Renderer();
void Render( const RenderContext& context );
void Clear();
private:
Shader* _shader;
Mat4 _view;
// Temp
Texture _texture;
Mesh _cube_mesh;
Transform _cube;
};
}
#endif // ICE_RENDERER_H<file_sep>/Visual Studio 2013/Angle.hpp
#ifndef ICE_MATHS_ANGLE_HPP
#define ICE_MATHS_ANGLE_HPP
namespace Ice
{
}
#endif // ICE_MATHS_ANGLE_HPP<file_sep>/Visual Studio 2013/Lexer.hpp
#ifndef ICE_SCRIPT_LEXER_H
#define ICE_SCRIPT_LEXER_H
#include "Types.hpp"
#include "Token.hpp"
#include <vector>
#include <stack>
namespace Ice { namespace Script {
class Lexer;
/////////////////////////////////
struct LexerMode
{
// The lexing function that this struct contains.
// It returns a pointer to another struct containing
// a similar function.
LexerMode* (*Func)( Lexer* );
// Equality checks.
bool operator==( const LexerMode& other ) const;
bool operator!=( const LexerMode& other ) const;
// All the lexing states have beed defined
// here, but the actual function definitions
// live in lexer.cpp.
static LexerMode Start;
static LexerMode End;
static LexerMode Identifier;
static LexerMode Punctuation;
static LexerMode SkipLineComment;
static LexerMode SkipBlockComment;
static LexerMode SkipSpace;
static LexerMode String;
static LexerMode Char;
static LexerMode Number;
static LexerMode HexNumber;
static LexerMode OctNumber;
};
/////////////////////////////////
class Lexer
{
public:
void Run( const std::string& filename );
void Reset();
const Token* NextToken();
const Token* PeekToken( i32 n );
char NextChar();
char PeekChar( i32 n );
void AddToken( const std::string& lexeme, TokenType type );
private:
i32 _char_index = -1;
i32 _line = 1;
i32 _column = 1;
LexerMode* _mode;
std::string _filename;
std::string _source;
std::stack<u32> _line_lengths;
i32 _token_index = -1;
std::vector<Token> _tokens;
};
} }
#endif // ICE_SCRIPT_LEXER_H<file_sep>/Visual Studio 2013/Vec3.cpp
#include "Vec2.hpp"
#include "Vec3.hpp"
#include "Vec4.hpp"
namespace Ice
{
Vec3::Vec3()
: x( 0 )
, y( 0 )
, z( 0 )
{}
Vec3::Vec3( f32 xyz[ 3 ] )
: x( xyz[ 0 ] )
, y( xyz[ 1 ] )
, z( xyz[ 2 ] )
{}
Vec3::Vec3( f32 x, f32 y, f32 z )
: x( x )
, y( y )
, z( z )
{}
Vec3::Vec3( f32 xyz )
: x( xyz )
, y( xyz )
, z( xyz )
{}
Vec3::Vec3( const Vec2& vec, f32 z )
: x( vec.x )
, y( vec.y )
, z( z )
{}
Vec3::Vec3( const Vec4& vec )
: x( vec.x )
, y( vec.y )
, z( vec.z )
{}
Vec3::Vec3( const Vec3& vec )
: x( vec.x )
, y( vec.y )
, z( vec.z )
{}
Vec3::Vec3( Vec3&& vec )
: x( vec.x )
, y( vec.y )
, z( vec.z )
{}
/////////////////////////////////
Vec3 cross( const Vec3& a, const Vec3& b )
{
return Vec3{ a.y * b.z - b.y * a.z,
a.z * b.x - b.z * a.x,
a.x * b.y - b.x * a.y };
}
}<file_sep>/Visual Studio 2013/Renderer.cpp
#include "Renderer.hpp"
#include "Vertex.hpp"
#include "Window.hpp"
#include "Maths.hpp"
namespace Ice
{
Renderer::Renderer()
{
// Set the default clear colour.
glClearColor( 0.2f, 0.3f, 0.3f, 1.0f );
// Tell OpenGL which face to cull.
// glFrontFace( GL_CW );
// glCullFace ( GL_FRONT );
_shader = new Shader( "data/shaders/basic.vert",
"data/shaders/basic.frag" );
_shader->RegisterUniform( "model" );
_shader->RegisterUniform( "view" );
_shader->RegisterUniform( "projection" );
std::vector<Vertex> vertices = {
// Positions Normals Colours Texture Coordinates
{ { +0.5f, +0.5f, +0.0f }, { 0.0f, 0.0f, 1.0f }, Colour_White, { 1.0f, 0.0f } },
{ { +0.5f, -0.5f, +0.0f }, { 0.0f, 0.0f, 1.0f }, Colour_Red , { 1.0f, 1.0f } },
{ { -0.5f, -0.5f, +0.0f }, { 0.0f, 0.0f, 1.0f }, Colour_Green, { 0.0f, 1.0f } },
{ { -0.5f, +0.5f, +0.0f }, { 0.0f, 0.0f, 1.0f }, Colour_Blue , { 0.0f, 0.0f } },
};
std::vector<GLuint> indices = {
0, 1, 3,
3, 1, 2
};
std::vector<Texture> textures = { load_texture( "data/test/box.jpg", TextureType::Diffuse ) };
_cube_mesh.AddData( vertices, indices, textures );
_cube.SetTranslation( { 0.0f, 0.0f, 0.0f } );
_cube.SetScale ( { 1.0f, 1.0f, 1.0f } );
// _cube.SetRotation ( { 2.0f, 1.0f, 0.0f } );
// _view = look_at( { 1.0f, 2.0f, 4.0f },
// { 1.0f, 0.0f, 0.0f },
// { 0.0f, 1.0f, 0.0f } );
_view = translate( { 0.0f, 0.0f, 0.0f } );
}
Renderer::~Renderer()
{
delete _shader;
}
void Renderer::Render( const RenderContext& context )
{
context.wire_frame
? glPolygonMode( GL_FRONT_AND_BACK, GL_LINE )
: glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
context.has_depth
? glEnable ( GL_DEPTH_TEST )
: glDisable( GL_DEPTH_TEST );
_cube.SetTranslation( { sinf( glfwGetTime() ), cosf( glfwGetTime() ), 0.0f } );
// _cube.SetScale ( { sinf( glfwGetTime() ), cosf( glfwGetTime() ), 0.0f } );
// _view = translate( { sinf( glfwGetTime() ), cosf( glfwGetTime() ), -2.0f } );
_shader->Bind();
_shader->UpdateUniform( "model" , _cube.GetTransform() );
_shader->UpdateUniform( "view" , _view );
_shader->UpdateUniform( "projection", context.projection );
_cube_mesh.Draw( *_shader );
}
void Renderer::Clear()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
}
}<file_sep>/Visual Studio 2013/Transform.hpp
#ifndef ICE_TRANSFORM_H
#define ICE_TRANSFORM_H
#include "Types.hpp"
#include "Maths.hpp"
namespace Ice
{
class Transform
{
public:
Transform()
: _has_changed( true )
, _scale ( Vec3_One )
{}
const Mat4& GetTransform();
void SetTranslation( const Vec3& vec );
void SetScale ( const Vec3& vec );
void SetRotation( const Quaternion& quat );
Vec3 GetTranslation() const;
Vec3 GetScale () const;
Quaternion GetRotation() const;
private:
bool _has_changed;
Mat4 _model;
Vec3 _translation;
Vec3 _scale;
Quaternion _rotation;
};
}
#endif // ICE_TRANSFORM_H<file_sep>/Visual Studio 2013/TickCounter.cpp
#include "Time.hpp"
namespace Ice
{
bool TickCounter::Update()
{
bool reset = ( _clock.ElapsedTime() >= 1.0 );
if ( reset )
{
_tick_rate = _ticks;
_ticks = 0;
_clock.Reset();
}
++_ticks;
return reset;
}
}<file_sep>/Visual Studio 2013/Mesh.cpp
#include "Mesh.hpp"
namespace Ice
{
void Mesh::AddData( std::vector<Vertex> vertices, std::vector<GLuint> indices, std::vector<Texture> textures )
{
_vertices = std::move( vertices );
_indices = std::move( indices );
_textures = std::move( textures );
SetupMesh();
}
void Mesh::SetupMesh()
{
_vao.Bind();
_vao.VBO().Bind();
_vao.VBO().BufferData( _vertices.size() * VERTEX_SIZE, _vertices.data(), GL_STATIC_DRAW );
_vao.EBO().Bind();
_vao.EBO().BufferData( _indices.size() * sizeof(GLuint), _indices.data(), GL_STATIC_DRAW );
//Vertex positions
_vao.SetVAP( 0, V_COMPONENTS_P, V_TYPE_P, V_NORMALISE_P, VERTEX_SIZE, V_OFFSET_P );
_vao.SetVAP( 1, V_COMPONENTS_N, V_TYPE_N, V_NORMALISE_N, VERTEX_SIZE, V_OFFSET_N );
_vao.SetVAP( 2, V_COMPONENTS_T, V_TYPE_T, V_NORMALISE_T, VERTEX_SIZE, V_OFFSET_T );
_vao.UnBind();
}
void Mesh::Draw( Shader& shader )
{
GLuint diffuseNr = 1;
GLuint specularNr = 1;
shader.Bind();
for ( u32 i = 0; i < _textures.size(); ++i )
{
std::stringstream ss;
std::string number;
TextureType type = _textures[ i ].type;
if ( type == TextureType::Diffuse )
ss << diffuseNr++;
else if ( type == TextureType::Specular )
ss << specularNr++;
number = ss.str();
shader.UpdateUniform( ( "material." + TextureTypeNames[ (u32)type ] + number ).c_str(), i );
bind_texture( &_textures[ i ], i );
}
glActiveTexture( GL_TEXTURE0 );
//Draw Mesh
_vao.Bind();
glDrawElements( GL_TRIANGLES, _indices.size(), GL_UNSIGNED_INT, 0 );
_vao.UnBind();
}
}<file_sep>/Visual Studio 2013/Clock.cpp
#include "Time.hpp"
namespace Ice
{
f64 Clock::ElapsedTime() const
{
return glfwGetTime() - _time_started;
}
f64 Clock::DeltaTime()
{
double time_current = glfwGetTime();
double time_delta = time_current - _time_started;
_time_started = time_current;
return time_delta;
}
void Clock::Reset()
{
_time_started = glfwGetTime();
}
}<file_sep>/Visual Studio 2013/Transform.cpp
#include "Transform.hpp"
namespace Ice
{
const Mat4& Transform::GetTransform()
{
if ( _has_changed )
{
// _model = translate( _translation )
// * rotate ( _rotation )
// * scale ( _scale );
_model = translate( _translation )
* scale ( _scale );
_has_changed = false;
}
return _model;
}
void Transform::SetTranslation( const Vec3& vec )
{
_has_changed = true;
_translation = vec;
}
void Transform::SetScale( const Vec3& vec )
{
_has_changed = true;
_scale = vec;
}
void Transform::SetRotation( const Quaternion& quat )
{
_has_changed = true;
_rotation = quat;
}
Vec3 Transform::GetTranslation() const { return _translation; }
Vec3 Transform::GetScale () const { return _scale; }
Quaternion Transform::GetRotation() const { return _rotation; }
}<file_sep>/Visual Studio 2013/Texture.hpp
#ifndef ICE_TEXTURE_H
#define ICE_TEXTURE_H
#include "Types.hpp"
#include "NonCopy.hpp"
#include "OpenGL.hpp"
#include "Image.hpp"
namespace Ice
{
enum class TextureFilter : i32
{
LinearMipmapLinear = GL_LINEAR_MIPMAP_LINEAR,
LinearMipmapNearest = GL_LINEAR_MIPMAP_NEAREST,
NearestMipmapLinear = GL_NEAREST_MIPMAP_LINEAR,
NearestMipmapNearser = GL_NEAREST_MIPMAP_NEAREST,
Linear = GL_LINEAR,
Nearest = GL_NEAREST
};
/////////////////////////////////
enum class TextureWrapMode : i32
{
Clamp = GL_CLAMP,
Repeat = GL_REPEAT,
ClampToEdge = GL_CLAMP_TO_EDGE,
ClampToBorder = GL_CLAMP_TO_BORDER,
MirroredRepeat = GL_MIRRORED_REPEAT
};
/////////////////////////////////
enum class TextureType : i32
{
Diffuse,
Specular,
};
// Find a better way to do this... Maybe macros.
// This one isn't too bad because it's only a small
// enum.
const std::string TextureTypeNames[] = {
"texture_diffuse",
"texture_specular"
};
/////////////////////////////////
struct Texture
{
u32 handle;
u32 width;
u32 height;
TextureType type;
~Texture();
};
/////////////////////////////////
Texture load_texture( const Image& image,
TextureType type,
TextureFilter min_filter = TextureFilter::LinearMipmapLinear,
TextureFilter mag_filter = TextureFilter::Linear,
TextureWrapMode wrap_mode = TextureWrapMode::Repeat );
Texture load_texture( const char* filename,
TextureType type,
TextureFilter min_filter = TextureFilter::LinearMipmapLinear,
TextureFilter mag_filter = TextureFilter::Linear,
TextureWrapMode wrap_mode = TextureWrapMode::Repeat );
void bind_texture( const Texture* texture, u32 position );
}
#endif // ICE_TEXTURE_H<file_sep>/Visual Studio 2013/Hash.cpp
#include "Hash.hpp"
#include <cstdio>
namespace Ice { namespace Script {
u32 hash( void* key, i32 length )
{
u8* p = static_cast<u8*>( key );
u32 h = 0;
for ( i32 i = 0; i < length; ++i )
{
h += p[ i ];
h += ( h << 10 );
h ^= ( h >> 6 );
}
h += ( h << 3 );
h ^= ( h >> 11 );
h += ( h << 15 );
return h;
}
u32 hash( const std::string& string )
{
const u32 length = string.length();
u32 result;
char* buffer = new char[ length ];
sprintf( buffer, "%s", string.data() );
result = hash( buffer, length );
delete buffer;
return result;
}
} }<file_sep>/Visual Studio 2013/Vec2.cpp
#include "Vec2.hpp"
#include "Vec3.hpp"
#include "Vec4.hpp"
namespace Ice
{
Vec2::Vec2()
: x( 0 )
, y( 0 )
{}
Vec2::Vec2( f32 xy[ 2 ] )
: x( xy[ 0 ] )
, y( xy[ 1 ] )
{}
Vec2::Vec2( f32 x, f32 y )
: x( x )
, y( y )
{}
Vec2::Vec2( f32 xy )
: x( xy )
, y( xy )
{}
Vec2::Vec2( const Vec3& vec )
: x( vec.x )
, y( vec.y )
{}
Vec2::Vec2( const Vec4& vec )
: x( vec.x )
, y( vec.y )
{}
Vec2::Vec2( const Vec2& vec )
: x( vec.x )
, y( vec.y )
{}
Vec2::Vec2( Vec2&& vec )
: x( vec.x )
, y( vec.y )
{}
/////////////////////////////////
f32 cross( const Vec2& a, const Vec2& b )
{
return a.x * b.y
- b.x * a.y;
}
}<file_sep>/Visual Studio 2013/Types.hpp
#ifndef ICE_COMMON_TYPES_H
#define ICE_COMMON_TYPES_H
#include <cstdint>
#include <string>
using i8 = std::int8_t;
using i16 = std::int16_t;
using i32 = std::int32_t;
using i64 = std::int64_t;
using u8 = std::uint8_t;
using u16 = std::uint16_t;
using u32 = std::uint32_t;
using u64 = std::uint64_t;
using f32 = float;
using f64 = double;
using b8 = bool;
using b32 = i32;
using usize = std::size_t;
#endif // ICE_COMMON_TYPES_H<file_sep>/Visual Studio 2013/Mat4.cpp
#include "Mat4.hpp"
namespace Ice
{
Mat4::Mat4( f32 val )
: elements{ val , 0.0f, 0.0f, 0.0f,
0.0f, val , 0.0f, 0.0f,
0.0f, 0.0f, val , 0.0f,
0.0f, 0.0f, 0.0f, val }
{}
Mat4::Mat4( f32 e0, f32 e4, f32 e8 , f32 e12,
f32 e1, f32 e5, f32 e9 , f32 e13,
f32 e2, f32 e6, f32 e10, f32 e14,
f32 e3, f32 e7, f32 e11, f32 e15 )
: elements{ e0, e4, e8 , e12,
e1, e5, e9 , e13,
e2, e6, e10, e14,
e3, e7, e11, e15 }
{}
Mat4::Mat4( const Mat4& mat )
{
for ( usize i = 0; i < MATRIX_SIZE; ++i )
elements[ i ] = mat[ i ];
}
Mat4::Mat4( Mat4&& mat )
{
for ( usize i = 0; i < MATRIX_SIZE; ++i )
elements[ i ] = mat[ i ];
}
/////////////////////////////////
void transpose( Mat4& mat )
{
Mat4 result;
for ( usize i = 0; i < MATRIX_WIDTH; ++i )
for ( usize j = 0; j < MATRIX_WIDTH; ++j )
result[ i + j * MATRIX_WIDTH ] = mat[ j + i * MATRIX_WIDTH ];
mat = result;
}
Mat4 transposed( const Mat4& mat )
{
Mat4 result;
for ( usize i = 0; i < MATRIX_WIDTH; ++i )
for ( usize j = 0; j < MATRIX_WIDTH; ++j )
result[ i + j * MATRIX_WIDTH ] = mat[ j + i * MATRIX_WIDTH ];
return result;
}
Mat4 translate( const Vec3& v )
{
return { 1.0f, 0.0f, 0.0f, v.x ,
0.0f, 1.0f, 0.0f, v.y ,
0.0f, 0.0f, 1.0f, v.z ,
0.0f, 0.0f, 0.0f, 1.0f };
}
Mat4 scale( const Vec3& v )
{
return { v.x , 0.0f, 0.0f, 0.0f,
0.0f, v.y , 0.0f, 0.0f,
0.0f, 0.0f, v.z , 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
}
Mat4 rotate( const Quaternion& quat )
{
Mat4 result;
const f32& x = quat.v.x;
const f32& y = quat.v.y;
const f32& z = quat.v.z;
const f32& w = quat.w;
const f32 x22 = 2.0f * ( x * x );
const f32 y22 = 2.0f * ( y * y );
const f32 z22 = 2.0f * ( z * z );
const f32 wx2 = 2.0f * w * x;
const f32 wz2 = 2.0f * w * z;
const f32 wy2 = 2.0f * w * y;
const f32 xy2 = 2.0f * x * y;
const f32 xz2 = 2.0f * x * z;
const f32 yz2 = 2.0f * y * z;
result[ 0 + 0 * MATRIX_WIDTH ] = 1.0f - y22 - z22;
result[ 0 + 1 * MATRIX_WIDTH ] = xy2 + wz2;
result[ 0 + 2 * MATRIX_WIDTH ] = xz2 - wy2;
result[ 1 + 0 * MATRIX_WIDTH ] = xy2 - wz2;
result[ 1 + 1 * MATRIX_WIDTH ] = 1.0f - x22 - z22;
result[ 1 + 2 * MATRIX_WIDTH ] = yz2 + wx2;
result[ 2 + 0 * MATRIX_WIDTH ] = xz2 + wy2;
result[ 2 + 1 * MATRIX_WIDTH ] = yz2 - wx2;
result[ 2 + 2 * MATRIX_WIDTH ] = 1.0f - x22 - y22;
return result;
}
Mat4 orthographic( f32 left, f32 right, f32 top, f32 bottom, f32 near, f32 far )
{
Mat4 result;
f32 rl = right - left;
f32 tb = top - bottom;
f32 fn = far - near;
result[ 0 + 0 * MATRIX_WIDTH ] = 2.0f / rl;
result[ 1 + 1 * MATRIX_WIDTH ] = 2.0f / tb;
result[ 2 + 2 * MATRIX_WIDTH ] = -2.0f / fn;
result[ 3 + 0 * MATRIX_WIDTH ] = -( right + left ) / rl;
result[ 3 + 1 * MATRIX_WIDTH ] = -( top + bottom ) / tb;
result[ 3 + 2 * MATRIX_WIDTH ] = -( far + near ) / fn;
return result;
}
Mat4 perspective( f32 fov, f32 aspect, f32 near, f32 far )
{
assert( std::fabs( aspect - std::numeric_limits<f32>::epsilon() ) > 0.0f );
const f32 ar = aspect;
const f32 thf = tanf( fov / 2.0f );
const f32 zr = near - far;
return { 1.0f / ( thf * ar ), 0.0f , 0.0f , 0.0f,
0.0f , 1.0f / thf, 0.0f , 0.0f,
0.0f , 0.0f , ( -near - far ) / zr, 2.0f * far * near / zr,
0.0f , 0.0f , 1.0f , 0.0f };
}
Mat4 look_at( const Vec3& origin,
const Vec3& target,
const Vec3& up )
{
Mat4 result;
const Vec3 f = normalised( target - origin );
const Vec3 s = normalised( cross( f, up ) );
const Vec3 u = cross( s, f );
return { +s.x , +u.x , -f.x , -dot( s, origin ),
+s.y , +u.y , -f.y , -dot( u, origin ),
+s.z , +u.z , -f.z , +dot( f, origin ),
+0.0f, +0.0f, +0.0f, +1.0f };
}
std::ostream& operator<<( std::ostream& stream, const Mat4& mat )
{
stream << "Mat4<(";
for ( usize i = 0; i < MATRIX_WIDTH; ++i )
{
stream << "\t";
for ( usize j = 0; j < MATRIX_WIDTH; ++j )
{
stream << mat[ i + j * MATRIX_WIDTH ];
if ( j != 3 )
stream << ", ";
}
stream << "\n";
}
return stream << ")>\n";
}
}<file_sep>/Visual Studio 2013/Quaternion.cpp
#include "Quaternion.hpp"
namespace Ice
{
Quaternion::Quaternion()
: w( 0.0f )
, v( 0.0f )
{}
Quaternion::Quaternion( f32 a, const Vec3& n )
{
f32 s = sinf( a / 2.0f );
w = cosf( a / 2.0f );
v = n * s;
}
Quaternion conjugate( const Quaternion& q )
{
Quaternion result;
result.w = q.w;
result.v = -q.v;
return result;
}
Quaternion slerp( const Quaternion& origin,
const Quaternion& target,
f32 amount )
{
Quaternion result;
Quaternion _target = target;
f32 flCosOmega = origin.w * _target.w + dot( _target.v, origin.v );
if ( flCosOmega < 0 )
{
// Avoid going the long way around.
_target.w = -_target.w;
_target.v = -_target.v;
flCosOmega = -flCosOmega;
}
f32 k0;
f32 k1;
if (flCosOmega > 0.9999f)
{
// Very close, use a linear interpolation.
k0 = 1 - amount;
k1 = amount;
}
else
{
// Trig identity, sin^2 + cos^2 = 1
f32 flSinOmega = sqrt( 1 - flCosOmega * flCosOmega );
// Compute the angle omega
f32 flOmega = atan2( flSinOmega, flCosOmega );
f32 flOneOverSinOmega = 1 / flSinOmega;
k0 = sin( ( 1 - amount ) * flOmega ) * flOneOverSinOmega;
k1 = sin( amount*flOmega ) * flOneOverSinOmega;
}
// Interpolate
result.w = origin.w * k0 + _target.w * k1;
result.v = origin.v * k0 + _target.v * k1;
return result;
}
}<file_sep>/Visual Studio 2013/RenderContext.hpp
#ifndef ICE_RENDER_CONTEXT_H
#define ICE_RENDER_CONTEXT_H
#include "Types.hpp"
#include "Maths.hpp"
namespace Ice
{
// I can't think of anything else to
// put in here at the moment, but I'm sure
// there is something.
// Maybe something to do with shaders?
struct RenderContext
{
Mat4 projection;
bool wire_frame; // Tells the renderer to use wire frame or not.
bool has_depth; // Determines if the context is 2D or 3D.
};
}
#endif // ICE_RENDER_CONTEXT_H<file_sep>/Visual Studio 2013/Vec2.hpp
#ifndef ICE_MATHS_VEC2_HPP
#define ICE_MATHS_VEC2_HPP
#include "Common.hpp"
#include "Types.hpp"
#include "Functions.hpp"
#include <cmath>
namespace Ice
{
struct Vec3;
struct Vec4;
/////////////////////////////////
struct Vec2
{
Vec2();
Vec2( f32 xy[ 2 ] );
Vec2( f32 x, f32 y );
explicit Vec2( f32 xy );
explicit Vec2( const Vec3& vec );
explicit Vec2( const Vec4& vec );
Vec2( const Vec2& vec );
Vec2( Vec2&& vec );
inline Vec2& operator=( const Vec2& vec )
{
x = vec.x;
y = vec.y;
return *this;
}
inline Vec2& operator=( Vec2&& vec )
{
x = vec.x;
y = vec.y;
return *this;
}
inline f32& operator[]( usize index ) { return elements[ index ]; }
inline const f32& operator[]( usize index ) const { return elements[ index ]; }
inline Vec2 operator+( const Vec2& r ) const { return Vec2{ x + r.x, y + r.y }; }
inline Vec2 operator-( const Vec2& r ) const { return Vec2{ x - r.x, y - r.y }; }
inline Vec2 operator*( f32 r ) const { return Vec2{ x * r , y * r }; }
inline Vec2 operator/( f32 r ) const { return Vec2{ x / r , y / r }; }
inline Vec2& operator+=( const Vec2& r ) { return ( *this = (*this) + r ); }
inline Vec2& operator-=( const Vec2& r ) { return ( *this = (*this) - r ); }
inline Vec2& operator*=( f32 r ) { return ( *this = (*this) * r ); }
inline Vec2& operator/=( f32 r ) { return ( *this = (*this) / r ); }
inline bool operator==( const Vec2& other ) const
{
return x == other.x
&& y == other.y;
}
inline bool operator!=( const Vec2& other ) const
{
return !operator==( other );
}
union
{
f32 elements[ 2 ];
struct { f32 x, y; };
struct { f32 r, g; };
struct { f32 s, t; };
};
};
/////////////////////////////////
const Vec2 Vec2_Zero = Vec2{ 0.0f, 0.0f };
const Vec2 Vec2_One = Vec2{ 1.0f, 1.0f };
const Vec2 Vec2_UnitX = Vec2{ 1.0f, 0.0f };
const Vec2 Vec2_UnitY = Vec2{ 0.0f, 1.0f };
/////////////////////////////////
VECTOR_FUNCTIONS( 2, Vec2 )
f32 cross( const Vec2& a, const Vec2& b );
/////////////////////////////////
inline std::ostream& operator<<( std::ostream& stream, const Vec2& v )
{
return stream << "Vec2<(" << v.x << ", " << v.y << ")>";
}
}
#endif // ICE_MATHS_VEC2_HPP<file_sep>/Visual Studio 2013/Image.hpp
#ifndef ICE_IMAGE_LOADER_H
#define ICE_IMAGE_LOADER_H
#include "Types.hpp"
namespace Ice
{
enum class ImageFormat : u32
{
None = 0,
Greyscale = 1,
GreyscaleAlpha = 2,
RGB = 3,
RGBA = 4
};
/////////////////////////////////
struct Image
{
ImageFormat format;
u32 width;
u32 height;
u8* pixels;
~Image();
};
/////////////////////////////////
Image load_image( const char* filename );
Image load_image( u32 width, u32 height, ImageFormat format, const u8* pixels = nullptr );
void flip_image_v( Image& image );
void flip_image_h( Image& image );
void rotate_image( Image& image );
}
#endif // ICE_IMAGE_LOADER_H<file_sep>/Visual Studio 2013/Vec4.cpp
#include "Vec2.hpp"
#include "Vec3.hpp"
#include "Vec4.hpp"
namespace Ice
{
Vec4::Vec4()
: x( 0 )
, y( 0 )
, z( 0 )
, w( 0 )
{}
Vec4::Vec4( f32 xyzw[ 4 ] )
: x( xyzw[ 0 ] )
, y( xyzw[ 1 ] )
, z( xyzw[ 2 ] )
, w( xyzw[ 3 ] )
{}
Vec4::Vec4( f32 x, f32 y, f32 z, f32 w )
: x( x )
, y( y )
, z( z )
, w( w )
{}
Vec4::Vec4( f32 xyzw )
: x( xyzw )
, y( xyzw )
, z( xyzw )
, w( xyzw )
{}
Vec4::Vec4( const Vec2& vec, f32 z, f32 w )
: x( vec.x )
, y( vec.y )
, z( z )
, w( w )
{}
Vec4::Vec4( const Vec2& xy, const Vec2& zw )
: x( xy.x )
, y( xy.y )
, z( zw.x )
, w( zw.y )
{}
Vec4::Vec4( const Vec3& vec, f32 w )
: x( vec.x )
, y( vec.y )
, z( vec.z )
, w( w )
{}
Vec4::Vec4( const Vec4& vec )
: x( vec.x )
, y( vec.y )
, z( vec.z )
, w( vec.w )
{}
Vec4::Vec4( Vec4&& vec )
: x( vec.x )
, y( vec.y )
, z( vec.z )
, w( vec.w )
{}
/////////////////////////////////
}<file_sep>/Visual Studio 2013/Model.h
#ifndef _MODEL_H_
#define _MODEL_H_
#include "Mesh.h"
#include <assimp\Importer.hpp>
#include <assimp\scene.h>
#include <assimp\postprocess.h>
#include <Ice/Graphics/Shader.hpp>
#include <Texture.hpp>
class Model
{
public:
Model(GLchar* path);
void Draw(Shader& shader);
private:
std::vector<Mesh> meshes;
std::string directory;
void loadModel(std::string path);
void processNode(aiNode* node, const aiScene* scene);
Mesh processMesh(aiMesh* mesh, const aiScene* scene);
vector<Texture> loadMaterialTextures(aiMaterial* mat, aiTextureType type, std::string typeName);
GLint TextureFromFile(const char* path, std::string directory)
};
#endif<file_sep>/Visual Studio 2013/Texture.cpp
#include "Types.hpp"
#include "Common.hpp"
#include "Texture.hpp"
namespace Ice
{
static GLenum get_internal_format( ImageFormat format, bool srgb )
{
switch( format )
{
case ImageFormat::Greyscale:
return GL_LUMINANCE;
case ImageFormat::GreyscaleAlpha:
return GL_LUMINANCE_ALPHA;
case ImageFormat::RGB:
return ( srgb ? GL_SRGB: GL_RGB );
case ImageFormat::RGBA:
return ( srgb ? GL_SRGB_ALPHA : GL_RGBA );
case ImageFormat::None:
default:
throw std::runtime_error( "Invalid image format!" );
}
}
/////////////////////////////////
Texture::~Texture()
{
glDeleteTextures( 1, &handle );
}
/////////////////////////////////
Texture load_texture( const Image& image,
TextureType type,
TextureFilter min_filter,
TextureFilter mag_filter,
TextureWrapMode wrap_mode )
{
if ( image.format == ImageFormat::None )
throw std::runtime_error( "Invalid image format" );
Texture texture{ 0, image.width, image.height, type };
glGenTextures( 1, &texture.handle );
glBindTexture( GL_TEXTURE_2D, texture.handle );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S , (i32)wrap_mode );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T , (i32)wrap_mode );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (i32)min_filter );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (i32)mag_filter );
glGenerateMipmap( GL_TEXTURE_2D );
glTexImage2D( GL_TEXTURE_2D,
0,
get_internal_format ( image.format, true ),
static_cast<GLsizei>( image.width ),
static_cast<GLsizei>( image.height ),
0,
get_internal_format( image.format, false ),
GL_UNSIGNED_BYTE,
image.pixels );
glBindTexture( GL_TEXTURE_2D, 0 );
return texture;
}
Texture load_texture( const char* filename,
TextureType type,
TextureFilter min_filter,
TextureFilter mag_filter,
TextureWrapMode wrap_mode )
{
Image image = load_image( filename );
// flip_image_v( image );
return load_texture( image, type, min_filter, mag_filter, wrap_mode );
}
void bind_texture( const Texture* texture, u32 position )
{
if ( position > 31 )
{
std::cerr << "Textures can only be bound to position [ 0 .. 31 ]" << std::endl;
std::cerr << "Using position 31." << std::endl;
position = 31;
}
glActiveTexture ( GL_TEXTURE0 + position );
glClientActiveTexture( GL_TEXTURE0 + position );
glEnable( GL_TEXTURE_2D );
if ( texture && texture->handle )
glBindTexture( GL_TEXTURE_2D, texture->handle );
else
glBindTexture( GL_TEXTURE_2D, 0 );
}
}<file_sep>/Visual Studio 2013/Maths.hpp
#ifndef ICE_MATHS_DEFINES_H
#define ICE_MATHS_DEFINES_H
#include "Vec2.hpp"
#include "Vec3.hpp"
#include "Vec4.hpp"
#include "Mat4.hpp"
#include "Quaternion.hpp"
namespace Ice
{
struct Constants
{
static constexpr f32 Pi = 3.14159265359;
static constexpr f32 Tau = 6.28318530718;
};
}
#endif // ICE_MATHS_DEFINES_H<file_sep>/Visual Studio 2013/Quaternion.hpp
#ifndef ICE_MATHS_QUATERNION_HPP
#define ICE_MATHS_QUATERNION_HPP
#include "Types.hpp"
#include "Vec3.hpp"
namespace Ice
{
struct Quaternion
{
Quaternion();
Quaternion( f32 a, const Vec3& n );
inline Quaternion operator*( const Quaternion& r ) const
{
Quaternion result;
result.w = w * r.w - dot( v, r.v );
result.v = v * r.w + r.v * w + cross( v, r.v );
return result;
};
inline Vec3 operator*( const Vec3& r ) const
{
Vec3 t = cross( v, r );
return r + t * ( 2 * w ) + cross( v, t ) * 2;
};
f32 w;
Vec3 v;
};
/////////////////////////////////
Quaternion conjugate( const Quaternion& q );
Quaternion slerp ( const Quaternion& origin,
const Quaternion& target,
f32 amount );
}
#endif // ICE_MATHS_QUATERNION_HPP<file_sep>/Visual Studio 2013/SymbolTable.hpp
#ifndef ICE_SCRIPT_SYMBOL_TABLE_H
#define ICE_SCRIPT_SYMBOL_TABLE_H
#include "Types.hpp"
#include <unordered_map>
#include <vector>
namespace Ice { namespace Script {
struct Symbol;
class SymbolTable;
/////////////////////////////////
enum class SymbolType
{
VARIABLE,
FUNCTION,
CLASS,
OBJECT,
STRUCT,
ENUM,
INTERFACE,
ARRAY,
TYPE,
};
/////////////////////////////////
struct TypeInfo
{
std::string type_name;
std::string alias_for;
};
/////////////////////////////////
struct VariableInfo
{
std::string name;
std::string type;
std::string value;
bool is_const;
};
/////////////////////////////////
struct FunctionInfo
{
std::string name;
TypeInfo return_type;
std::vector<VariableInfo> args;
};
/////////////////////////////////
struct CtorInfo
{
std::string name;
bool is_static;
bool is_private;
std::vector<VariableInfo> args;
};
struct DtorInfo
{
std::string name;
bool is_private;
};
struct MethodInfo : public FunctionInfo
{
bool is_const;
bool is_static;
bool is_private;
};
struct MemberInfo : public VariableInfo
{
bool is_static;
bool is_private;
};
struct DelegateInfo
{
std::string name;
MemberInfo* delgate;
};
/////////////////////////////////
struct ClassInfo
{
std::string name;
bool has_ctor;
bool has_dtor;
CtorInfo ctor_info;
DtorInfo dtor_info;
std::vector<MethodInfo> methods;
std::vector<MemberInfo> members;
std::vector<DelegateInfo> delegates;
};
/////////////////////////////////
struct ObjectInfo
{
std::string name;
bool has_ctor;
bool has_dtor;
CtorInfo ctor_info;
DtorInfo dtor_info;
std::vector<MethodInfo> methods;
std::vector<MemberInfo> members;
std::vector<DelegateInfo> delegates;
};
/////////////////////////////////
struct StructInfo
{
};
/////////////////////////////////
struct EnumInfo
{
};
/////////////////////////////////
struct ierfaceInfo
{
};
/////////////////////////////////
struct ArrayInfo
{
u32 size;
};
/////////////////////////////////
struct Symbol
{
SymbolType type;
void* info;
};
/////////////////////////////////
class SymbolTable
{
public:
SymbolTable( SymbolTable* parent );
~SymbolTable();
bool Check ( const std::string& symbol_name );
void Insert( const std::string& symbol_name, const Symbol& symbol );
Symbol* LookUp( const std::string& symbol_name );
private:
// The parent scope. nullptr if none.
SymbolTable* _parent_scope;
// A list of all the child
// scopes that are contained
// within this one.
std::vector<SymbolTable> _child_scopes;
// The symbols that this scope contains.
std::unordered_map<std::string, Symbol> _symbols;
};
} }
#endif // ICE_SCRIPT_SYMBOL_TABLE_H<file_sep>/Visual Studio 2013/NonCopy.hpp
#ifndef ICE_COMMON_NON_COPY_H
#define ICE_COMMON_NON_COPY_H
#include "Types.hpp"
namespace Ice { namespace Common {
class NonCopyable
{
protected:
NonCopyable() {}
private:
NonCopyable( const NonCopyable& copy ) = delete;
NonCopyable( NonCopyable&& move ) = delete;
NonCopyable& operator=( const NonCopyable& copy ) = delete;
NonCopyable& operator=( NonCopyable&& move ) = delete;
};
} }
#endif // ICE_COMMON_NON_COPY_H<file_sep>/Visual Studio 2013/Window.hpp
#ifndef ICE_WINDOW_H
#define ICE_WINDOW_H
#include "Types.hpp"
#include "OpenGL.hpp"
#include "NonCopy.hpp"
namespace Ice
{
struct WindowConfig
{
std::string title;
u32 width;
u32 height;
bool fullscreen;
};
/////////////////////////////////
class Window : public Common::NonCopyable
{
public:
Window( const WindowConfig&& cfg );
~Window();
void Update();
void Flip();
bool IsOpen() const;
void Close();
static void SetSize( u32 width, u32 height );
static u32 GetWidth();
static u32 GetHeight();
private:
void CreateWindow();
private:
static u32 _width;
static u32 _height;
bool _fullscreen;
std::string _title;
GLFWwindow* _window;
};
}
#endif // ICE_WINDOW_H
|
72d26099137ac40d50dfa8be07a8be10e2be8a48
|
[
"Markdown",
"C++"
] | 57 |
C++
|
narwhalman13/Test
|
ff9564625589c06240f6fa74e82c78e64599d47f
|
f4d77fa6abe9e7f047a8b04ae48c1c875d45faab
|
refs/heads/master
|
<repo_name>kumar-amarjeet/word-counter<file_sep>/src/main/java/org/ak/task/textprocessing/GreetUser.java
/**
*
*/
package org.ak.task.textprocessing;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author <NAME>
*
*/
@RestController
public class GreetUser {
@RequestMapping("/webapi/test")
public String sayHi() {
return "Hello There! This application requires basic authentication in order to use the services.";
}
@RequestMapping("/home")
public String sayHiOnHomePage() {
return "Hello There! You have reached home page. "
+ "\nThis application requires basic authentication in order to use the services.";
}
}
<file_sep>/README.md
# word-counter
This Spring Boot project contains REST APIs to demonstrate how to count words. The REST APIs are secured with spring-security.
|
cd03343d768bdf18a1d549e793c94aa423b132c4
|
[
"Markdown",
"Java"
] | 2 |
Java
|
kumar-amarjeet/word-counter
|
ef72c62e18a8764d8f4b8bd1f9d3865fd200df09
|
63ce45b3eb89464290f65921efa17d40eddfc0a0
|
refs/heads/master
|
<repo_name>mareXT/Zadanie_9_1<file_sep>/js/scripts.js
function getTriangleArea(a, h) {
if (a > 0 && h > 0 ) {
return a*h/2;
}
else {
console.log('nieprawidlowe dane');
};
};
var triangle1Area = getTriangleArea(3, 12),
triangle2Area = getTriangleArea(6, 10),
triangle3Area = getTriangleArea(-3, 13);
console.log(triangle1Area);
console.log(triangle2Area);
console.log(triangle3Area);
|
0dd141842359ada613c5863e876e063ac2c870e3
|
[
"JavaScript"
] | 1 |
JavaScript
|
mareXT/Zadanie_9_1
|
72283f68aab76237f57c36d20bc6d02dd53ae2c7
|
c715e9cac562e5f1dca76160a8a6a9167147ce40
|
refs/heads/master
|
<repo_name>morristech/intellij-robolectric-plugin<file_sep>/src/org/robolectric/ideaplugin/StubIndex.java
package org.robolectric.ideaplugin;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.stubs.StringStubIndexExtension;
import com.intellij.psi.stubs.StubIndexKey;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NotNull;
public class StubIndex extends StringStubIndexExtension<PsiClass> {
@Override
public boolean processAllKeys(Project project, Processor<String> processor) {
return super.processAllKeys(project, processor);
}
@NotNull
@Override
public StubIndexKey<String, PsiClass> getKey() {
return StubIndexKey.createIndexKey("robolectric.method.name");
}
}
|
44004cf311052b25b6867313d7649f9739d62a24
|
[
"Java"
] | 1 |
Java
|
morristech/intellij-robolectric-plugin
|
a62b7caeed0a7b5ecf62517112b45bdd6fa88a6f
|
cde8940b0fd262bce19ecfa19b0bb7bcd1920f96
|
refs/heads/main
|
<repo_name>DWEBANKS/Attendance1<file_sep>/editpost.php
<?php
require_once 'dbase/conn.php' ;
if(isset($_POST['submit'])){
$id = $_POST['id'];
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$dob = $_POST['date_of_birth'];
$email = $_POST['email'];
$contact = $_POST['phone'];
$class = $_POST['class'];
$result=$crud->editAttendees($id, $fname, $lname, $dob, $email, $contact, $class);
if($result) {
header("Location: records.php");
}
else{
include 'include_require/errormessage.php';
}
}
?><file_sep>/dbase/crud.php
<?php
class crud{
private $dbase;
function __construct ($conn){
$this ->dbase = $conn;
}
public function insertAttendees ($fname, $lname, $dob, $email, $contact, $class, $avatar_path){
try {
//code...
$sql = "INSERT INTO attendees (first_name, last_name, date_of_birth, email, contact, class_id, avatar_path)
VALUES (:fname, :lname, :dob, :email, :contact, :class, :avatar_path)";
$stmt = $this ->dbase->prepare($sql);
$stmt ->bindparam(':fname', $fname);
$stmt ->bindparam(':lname', $lname);
$stmt ->bindparam(':dob', $dob);
$stmt ->bindparam(':email', $email);
$stmt ->bindparam(':contact', $contact);
$stmt ->bindparam(':class', $class);
$stmt ->bindparam(':avatar_path', $avatar_path);
$stmt ->execute();
return true;
} catch (PDOexception $e) {
//throw $th;
echo $e ->getMessage();
return false;
}
}
public function editAttendees ($id, $fname, $lname, $dob, $email, $contact, $class){
try{
$sql = "UPDATE `attendees` SET `first_name`=:fname, `last_name`=:lname, `date_of_birth`=:dob,
`email`=:email, `contact`=:contact, `class_id`=:class WHERE attendee_id =:id";
$stmt=$this->dbase->prepare($sql);
$stmt ->bindparam(':id', $id);
$stmt ->bindparam(':fname', $fname);
$stmt ->bindparam(':lname', $lname);
$stmt ->bindparam(':dob', $dob);
$stmt ->bindparam(':email', $email);
$stmt ->bindparam(':contact', $contact);
$stmt ->bindparam(':class', $class);
$stmt ->execute();
return true;
} catch (PDOexception $e) {
//throw $th;
echo $e ->getMessage();
return false;
}
}
public function getAttendees (){
try {
$sql = "SELECT * FROM `attendees` a inner join classes c on a.class_id = c.class_id";
$result = $this ->dbase ->query($sql);
return $result;
}catch (PDOexception $e) {
//throw $th;
echo $e ->getMessage();
return false;
}
}
public function getAttendeesDetails ($id){
try {
$sql = "select * from attendees a inner join classes c on a.class_id = c.class_id where attendee_id = :id";
$stmt = $this ->dbase ->prepare($sql);
$stmt ->bindparam(':id', $id);
$stmt ->execute();
$result = $stmt->fetch();
return $result;
} catch (PDOexception $e) {
//throw $th;
echo $e ->getMessage();
return false;
}
}
public function deleteAttendees ($id){
try {
$sql = "delete from attendees where attendee_id = :id";
$stmt=$this->dbase->prepare($sql);
$stmt ->bindparam(':id', $id);
$stmt ->execute();
return true;
} catch (PDOexception $e) {
//throw $th;
echo $e ->getMessage();
return false;
}
}
public function getClasses (){
try {
$sql = "SELECT * FROM `classes`";
$result = $this ->dbase ->query($sql);
return $result;
}catch (PDOexception $e) {
//throw $th;
echo $e ->getMessage();
return false;
}
}
public function getClassById($id){
try {
$sql = "SELECT * FROM `classes` where class_id =:id";
$stmt = $this ->dbase ->prepare($sql);
$stmt ->bindparam(':id', $id);
$stmt ->execute();
$result = $stmt->fetch();
return $result;
}catch (PDOexception $e) {
//throw $th;
echo $e ->getMessage();
return false;
}
}
}
?>
|
588870f81180075e69d286081e7045ea6c786f10
|
[
"PHP"
] | 2 |
PHP
|
DWEBANKS/Attendance1
|
546562443ed218086dc707e4adeed4af10693cde
|
c65e936b23987bb2e849cfdb31b87dd286630fa7
|
refs/heads/master
|
<repo_name>alouzao10/ReactNotesApp<file_sep>/src/Components/Header.js
import React from 'react';
function Header(props) {
return (
<header className='header'>
<h3 className='title'>Note Taker</h3>
</header>
);
}
export default Header;
<file_sep>/src/Components/NotePad.js
import React, { Component } from 'react';
import * as firebase from 'firebase';
export class NotePad extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
note: '',
};
this.addNote = this.addNote.bind(this);
}
/*updateTitle = (e) => {
this.setState({ title: e.target.value });
};
updateNote = (e) => {
this.setState({ note: e.target.value });
};*/
onChangeHandler = (e, field) => {
this.setState({ [field]: e.target.value });
};
addNote = () => {
if (this.state.title !== '' && this.state.note !== '') {
// add the note to the DB
firebase.database().ref('notes').push({
title: this.state.title,
note: this.state.note,
});
this.setState({ title: '', note: '' });
}
};
render() {
return (
<section className='noteform'>
<h3>Create New Note</h3>
<div className='form-group'>
<label htmlFor='noteTitle'>Title</label>
<input
type='text'
id='noteTitle'
name='noteTitle'
value={this.state.value}
onChange={(e) => this.onChangeHandler(e, 'title')}
placeholder='Title...'
/>
</div>
<div className='form-group'>
<label htmlFor='note'>Note</label>
<textarea
id='note'
name='note'
value={this.state.note}
onChange={(e) => this.onChangeHandler(e, 'note')}
placeholder='Information...'
/>
</div>
<button onClick={this.addNote}>Add Note</button>
</section>
);
}
}
export default NotePad;
|
6cb98816074b76f7eabbb736857c7f7e44304c43
|
[
"JavaScript"
] | 2 |
JavaScript
|
alouzao10/ReactNotesApp
|
118acf577c223b4da4461371c05a8136dac7906b
|
e20f6d1426c54f3d80bee7feb27d5665a0c335be
|
refs/heads/master
|
<repo_name>tanveer941/miscellaneous_supporting_app<file_sep>/microblog_docker/app.py
"""
-open command prompt in C:\Program Files\Redis
-execute redis-server.exe
Redis server has started on default address at 127.0.0.1:6379
- In the browser execute http://localhost:5000/
Each time you execute the count increases
- Stop a container ---- docker stop ee2ff27c52de
-List all docker container ---- docker ps -a
-remove docker container ---- docker rm ee2ff27c52de
-List all docker images ---- docker image ls
-remove docker image ---- docker rmi imagename:tag
docker rmi redis:alpine
docker rmi microblog-015_web:latest
- Compose new image and container for a project ---- docker-compose up
Note: Do not have it in debug mode.
In requirement.txt file specify the version of the packages
To push docker image
-Login to docker hub, create a repository
-tag using the command ---- docker tag plop:latest tanveer941/microblog123:plop
-push the newly created image ---- docker push tanveer941/microblog123:plop
Forcefully leave the swarm
- docker swarm leave --force
Initialize the swarm again
docker swarm init
>> Running the services
Run the app, have the image name in the .yml file
docker stack deploy -c docker-compose.yml getstartedlab
start a service named getstartedlab
docker stack services getstartedlab
list down the services
docker service ps getstartedlab_web
List down all the services
docker service ls
"""
import time
import redis
from flask import Flask
# import werkzeug
app = Flask(__name__)
cache = redis.Redis(host="127.0.0.1", port=6379)
# cache = redis.Redis(host="redis", port=6379)
print "cache::", dir(cache)
def get_hit_count():
retries = 5
while True:
try:
return cache.incr('hits')
except redis.exceptions.ConnectionError as exc:
if retries == 0:
raise exc
retries -= 1
time.sleep(0.5)
@app.route('/')
def hello():
count = get_hit_count()
return 'Hello Doc! I have been seen {} times.\n'.format(count)
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=False)<file_sep>/Bsig_app/bsig_optimize/__init__.py
from signalreader import SignalReader
from signal_loader import SignalLoader
from datetime import datetime
bsig_path = r"D:\Work\2018\code\LT5G\OLT\Radar_labelling_bsig\bsig_readers\Continuous_2014.05.15_at_08.48.40.bsig"
# bsig_path = r"D:\Work\2018\code\Github_repo\PCD_generation\Continuous_2017.06.01_at_12.12.18.bsig"
# bsig_path = r"D:\Work\2018\code\LT5G\OLT\Radar_labelling_bsig\bsig_readers\20160608_1306_{4556C7A6-7F27-4A91-923E-4392C9785675}.bsig"
## ======================================================================================================================
sig_name_lst = ['MTS.Package.TimeStamp',
'SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Longitudinal.MotVar.Velocity',
'SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Longitudinal.MotVar.Accel',
'SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Lateral.YawRate.YawRate',
'SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Lateral.SlipAngle.SideSlipAngle',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Kinematic.fDistX',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Kinematic.fDistY',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Kinematic.fVrelX',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Legacy.uiLifeTime',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Attributes.eDynamicProperty',
'SIM VFB ALL.AlgoSenCycle.gSI_OOI_LIST.SI_OOI_LIST[%].object_id',
'SIM VFB ALL.AlgoSenCycle.gSI_OOI_LIST.SI_OOI_LIST[%].long_displacement',
'SIM VFB ALL.AlgoSenCycle.gSI_OOI_LIST.SI_OOI_LIST[%].lat_displacement_to_curvature']
obj_signals = [ech_sig for ech_sig in sig_name_lst if '%' in str(ech_sig)]
with SignalReader(bsig_path) as sr:
start_time = datetime.now()
for ech_obj_num in range(40):
new_sig_lst = []
for ech_signal in sig_name_lst:
# for ech_signal in obj_signals:
if '%' in str(ech_signal):
ech_signal = ech_signal.replace('%', str(ech_obj_num))
new_sig_lst.append(ech_signal)
existing_sgnls_lst = list(set(new_sig_lst) & set(sr.signal_names))
# print "existing_sgnls_lst :: ", existing_sgnls_lst
# print ">> ", new_sig_lst
signals = sr[existing_sgnls_lst] # retrieves a list of both signals --> [[<sig1>], [<sig2>]]
# print ":>>", signals, len(signals)
specific_sig_values = [ech_sig_lst[500] for ech_sig_lst in signals]
# print "specific_sig_values >> ", specific_sig_values
end_time = datetime.now()
duration = end_time - start_time
print("duration :: ", duration.total_seconds(), duration.total_seconds()/60)
## ======================================================================================================================
<file_sep>/Neo4j_py/graph_db_trace/rec_summary_events.py
from PyQt4.QtGui import *
from PyQt4 import QtGui
from rec_summary_ui import Ui_MainWindow
from neo4j.v1 import GraphDatabase
from interpreter.keyword_matching_inter import KeyWordMatching
# import neo4j
# print neo4j.__version__
#pyinstaller --onefile rec_summary_events.py
class RecSummaryEvents(QMainWindow, Ui_MainWindow):
def __init__(self):
super(QMainWindow, self).__init__()
# Initialize the Neo4J connections
# self.neo_obj = Neo4JConnection("bolt://localhost:7687", "neo4j", "tan_neo4j")
# self.neo_obj.create_nodes("nodes")
# self.neo_obj.close()
# "bolt://10.223.244.129:7687"
self.neo4_driver = GraphDatabase.driver("bolt://10.223.244.129:7687:7687", auth=("neo4j", "tan_neo4j"))
self.neo_session = self.neo4_driver.session()
# self.txn = Transaction(session=self.neo_session)
self.setupUi()
def setupUi(self):
# try:
super(RecSummaryEvents, self).setupUi(self)
self.pushButton_fetch.clicked.connect(self.fetch_rec_labels)
self.progressBar.setValue(0)
self.pushButton_interpret.clicked.connect(self.interpret_qry)
def generate_summary(self):
# Continuous_2011.07.04_at_14.37.07.rec
self.progressBar.setValue(0)
self.recname = self.lineEdit_recname.text()
print "self.recname :>> ", self.recname
if self.recname != "":
self.progressBar.setValue(50)
neo_qry = ''' MATCH (CommonData)<-[cd:cd]-(RecordingName)-[c:c]->(Country)-
[rt:rt]->(RoadType)-
[w:w]->(WeatherCondition)-
[lc:lc]->(LightCondition)
WHERE RecordingName.name = '{}'
RETURN RecordingName.name as RecName, Country.name as Country, RoadType.name as RoadType,
WeatherCondition.name as WeatherCondition, LightCondition.name as LightCondition, CommonData.project as Project,
CommonData.function as Function, CommonData.department as Department '''.format(self.recname)
with self.neo_session.begin_transaction() as tx:
self.an = tx.run(neo_qry)
self.progressBar.setValue(75)
# print "an :: ", self.an.values()[0][0]
# self.lineEdit_recname.setText(str(self.an.values()))
# print "self.an.data() :: ", self.an.data()
dt_lst = self.an.data()
print "dt_lst :: ", dt_lst
self.textBrowser.clear()
sumry_tmplt = self.create_summary(dt_lst)
if dt_lst:
self.textBrowser.setText(str(sumry_tmplt))
else:
self.textBrowser.setText("No data found...")
self.progressBar.setValue(100)
# MainWindow.lineEdit_recname.setText(self.an.values()[0][0])
def create_summary(self, result_lst):
res_dict = result_lst[0]
res_dict = {str(k): ([str(e) for e in v] if type(v) is list else str(v))
for k, v in res_dict.iteritems()}
updated_dict = {}
for ech_key, ech_val in res_dict.iteritems():
if type(ech_val) is list:
updated_dict["{}_num".format(ech_key)] = len(ech_val)
res_dict.update(updated_dict)
print "res_dict :: ", res_dict
SUMMARY_TEMPLATE = '''The recording {RecName} has labels for {Project} {Function}
for {Department} which has observations of {Country_num} Countries {Country}
driven in {RoadType_num} road types {RoadType} under {WeatherCondition_num}
weather conditions {WeatherCondition} with {LightCondition_num}
Light Conditions {LightCondition}.
'''.format(**res_dict)
return SUMMARY_TEMPLATE
def fetch_rec_labels(self):
self.generate_summary()
def interpret_qry(self):
qry_input = str(self.lineEdit_query.text())
self.progressBar.setValue(10)
if qry_input == '':
self.textEdt_res.setText("Nothing to query")
else:
key_match_obj = KeyWordMatching(qry_input)
self.progressBar.setValue(40)
op = key_match_obj.interpret_the_query()
print "op::", op
self.textEdt_res.setText(str(op))
self.progressBar.setValue(90)
self.progressBar.setValue(100)
class Neo4JConnection(object):
neo_qry = ''' MATCH (RecName)-[c:c]->(Country) RETURN RecName.Name, Country.Name '''
NEO_TRACE = []
def __init__(self, uri, user, password):
self.neo4_driver = GraphDatabase.driver(uri, auth=(user, password))
self.neo_session = self.neo4_driver.session()
# self.txn = Transaction(session=self.neo_session)
self.exec_qry()
# self.create_nodes("Nodes")
def close(self):
self.neo4_driver.close()
def exec_qry(self):
with self.neo_session.begin_transaction() as tx:
self.an = tx.run(Neo4JConnection.neo_qry)
print "an :: ", self.an.values()[0][0]
MainWindow.lineEdit_recname.setText(self.an.values()[0][0])
def create_nodes(self, message):
# with self.neo4_driver.session() as session:
written_data = self.neo_session.write_transaction(self._create_and_return_data, message)
# print "written_data :: ", written_data
return written_data
# @staticmethod
def _create_and_return_data(self, tx, message):
# print "tx :: ", tx
self.result = tx.run(Neo4JConnection.neo_qry,
message=message)
# print "result :: ", self.result.values(), type(self.result.values())
# if result.single() is not None:
# print "Neo4JConnection.NEO_TRACE :: ", Neo4JConnection.NEO_TRACE
# vc = self.result.values()[0]
# print "str(self.result.values()) ::>> ", vc
# for ech_itm in self.result.values():
# MainWindow.textBrowser.setText(str(ech_itm))
# MainWindow.lineEdit_recname.setText(str(self.result.values()))
# return result.values()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
# MainWindow = QtGui.QMainWindow()
MainWindow = RecSummaryEvents()
# ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
<file_sep>/Neo4j_py/graph_db_trace/export_all_rec_summary.py
from neo4jrestclient.client import GraphDatabase
import os
class ExportSummary(object):
def __init__(self):
self.gdb = GraphDatabase("http://10.223.244.129:7474/db/data/",
username="neo4j", password="<PASSWORD>")
if os.path.isfile('summary.txt'):
os.remove('summary.txt')
def get_recnames(self):
rec_qry = ''' MATCH (RecordingName:RecordingName)
RETURN RecordingName.name '''
result = self.gdb.query(q=rec_qry, data_contents=True)
print("count of recs :: ", len(result.rows), result.rows)
return result.rows
def generate_summry(self, rec_names_lst):
"""
[[u'20141215_1540_{08627FB2-FDC3-414E-92B3-EBE39884DA8F}.rrec'],
[u'20150731_0439_{7B17D7CD-A8C7-4F64-B08B-4702C55F3D32}.rrec']]
:param rec_names_lst:
:return:
"""
for evry_recname in rec_names_lst:
q = '''MATCH (CommonData)<-[cd:cd]-(RecordingName)-[c:c]->(Country)-
[rt:rt]->(RoadType)-
[w:w]->(WeatherCondition)-
[lc:lc]->(LightCondition)-
[ob:ob]->(ObjectType)
WHERE RecordingName.name = '{}'
RETURN RecordingName.name as RecName, Country.name as Country, RoadType.name as RoadType,
WeatherCondition.name as WeatherCondition, LightCondition.name as LightCondition, CommonData.project as Project,
CommonData.function as Function, CommonData.department as Department, ObjectType.name as Objects '''.format(str(evry_recname[0]))
result = self.gdb.query(q=q, data_contents=True)
rows = result.rows
columns = result.columns
# print "-->", rows
if rows is not None:
for item in rows:
dt_lst = [dict(zip(columns, item))]
sumry_tmplt = self.create_summary(dt_lst)
print("sumry_tmplt :: ", sumry_tmplt)
print("\n")
self.write_smry_to_txt(sumry_tmplt)
def create_summary(self, result_lst):
res_dict = result_lst[0]
res_dict = {str(k): ([str(e) for e in v] if type(v) is list else str(v))
for k, v in res_dict.items()}
updated_dict = {}
for ech_key, ech_val in res_dict.items():
if type(ech_val) is list:
updated_dict["{}_num".format(ech_key)] = len(ech_val)
res_dict.update(updated_dict)
# print "res_dict :: ", res_dict
SUMMARY_TEMPLATE = '''The recording {RecName} has labels for {Project} {Function}
for {Department} which has observations of {Country_num} Countries {Country}
driven in {RoadType_num} road types {RoadType} under {WeatherCondition_num}
weather conditions {WeatherCondition} with {LightCondition_num}
Light Conditions {LightCondition} having {Objects_num} Objects {Objects}.
'''.format(**res_dict)
return SUMMARY_TEMPLATE
def write_smry_to_txt(self, smry_txt):
print("write_smry_to_txt >>>>>>>>>>>>")
with open("summary.txt", "a") as fhandle:
# fhandle.write(smry_txt + "\n\n")
fhandle.write(smry_txt + "\n\n")
# fhandle.write("\n")
if __name__ == '__main__':
exp_smry_obj = ExportSummary()
rec_names_lst = exp_smry_obj.get_recnames()
exp_smry_obj.generate_summry(rec_names_lst)<file_sep>/flsk_blogapp/samples/blogging_app/requirements.txt
flask == 0.12.2
sqlalchemy == 1.0.6
flask_login == 0.4.1
flask_blogging == 1.2.2
flask_wtf == 0.13
<file_sep>/Bsig_app/bsig_optimize/bsig_pub_optimize.py
import sys
import signalreader
# from signalreader import BsigReader, SignalReaderException
import Radar_pb2
import ecal
import os
import time
from datetime import datetime
if getattr(sys, 'frozen', False):
os.chdir(sys._MEIPASS)
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '%r (%r, %r) %2.2f sec' % \
(method.__name__, args, kw, te - ts)
return result
return timed
class RadarSignalInfo(object):
def __init__(self):
# Subscribe to the eCAL message to get the bsig path and the
# signal names
# self.bsig_path = bsig_pth
#
ecal.initialize(sys.argv, "Python signal value publisher")
# Subscribe to RadarSignalRequest topic
self.bsig_subscr_obj = ecal.subscriber(topic_name="BsigSignalNames")
self.bsig_pub_obj = ecal.publisher(topic_name="BsigSignalValues")
self.bsig_tmstamp_lst = []
self.sig_name_lst = []
self.subscribe_ecal_msgs()
@timeit
def subscribe_ecal_msgs(self):
print "Subscribing to the signals.........."
# Publish the signal values
bsig_obj = None
# Subscribe on the algo interface object
bsig_proto_req_obj = Radar_pb2.BsigDataRequest()
bsig_proto_resp_obj = Radar_pb2.BsigDataResponse()
while ecal.ok():
ret, msg, time = self.bsig_subscr_obj.receive(500)
# print("---:: ", ret, msg, time, type(msg))
if msg is not None:
start_time = datetime.now()
bsig_proto_req_obj.ParseFromString(msg)
bsig_pth = bsig_proto_req_obj.bsigPath
obj_num = bsig_proto_req_obj.objectIdCount
tmstamp_rdr = bsig_proto_req_obj.timestamp
# Segregate object signals and non-object signals
cmn_signals = [ech_sig for ech_sig in bsig_proto_req_obj.signalNames if '%' not in str(ech_sig)]
obj_signals = [ech_sig for ech_sig in bsig_proto_req_obj.signalNames if '%' in str(ech_sig)]
print "--> ", bsig_pth, obj_num
# print "cmn_signals :: ",
# if len(cmn_signals) == 1 and 'TimeStamp' in str(cmn_signals[0])
try:
if bsig_obj is None:
print "{{{{"
bsig_obj = signalreader.BsigReader(bsig_pth)
# print("bsig_obj >> ", bsig_obj)
# Read and Publish the common signals velocity, acceleration just once
print "Reading common signals..."
for ech_cmn_signal in cmn_signals:
cmn_sig_val_lst = list(bsig_obj.signal(ech_cmn_signal))
# print "cmn_sig_val_lst >> ", cmn_sig_val_lst
if len(cmn_signals) == 1 and 'TimeStamp' in str(cmn_signals[0]):
# self.publ_timestamps()
self.bsig_tmstamp_lst.extend(cmn_sig_val_lst)
if self.bsig_tmstamp_lst:
# Get the index/sample count for the timestamp
if tmstamp_rdr != -1:
try:
sample_cnt = self.bsig_tmstamp_lst.index(tmstamp_rdr)
# print "cmn_sig_val_lst :: ", cmn_sig_val_lst
print "sample_cnt >> ", sample_cnt, cmn_sig_val_lst[sample_cnt]
cmn_sig_val_lst = [cmn_sig_val_lst[sample_cnt]]
except ValueError as e:
print "No signal value for this timestamp %d and signal %s" % (tmstamp_rdr, ech_cmn_signal)
pass
else:
print "TimeStamp data not fetched from Bsig file"
continue
ech_sig_data = bsig_proto_resp_obj.eachSigValues.add()
# If data is present for signal send the values else do not send anything
# print "cmn_sig_val_lst :: ", cmn_sig_val_lst
if cmn_sig_val_lst:
ech_sig_data.signalName = ech_cmn_signal
ech_sig_data.objectId = -1
for ech_sig_val in cmn_sig_val_lst:
ech_sig_data.signalvalues.append(ech_sig_val)
# else:
# ech_sig_data.signalvalues.append(0)
# Iterate over the objects
if tmstamp_rdr != -1:
for ech_obj_num in range(0, obj_num):
print "Reading signals for object %s" % str(ech_obj_num)
# print("ech_obj_num > ", ech_obj_num)
# Parse the signal names and iterate over them
for ech_signal in obj_signals:
if '%' in str(ech_signal):
ech_signal = ech_signal.replace('%', str(ech_obj_num))
print("ech_signal > ", ech_signal)
obj_sig_val_lst = list(bsig_obj.signal(ech_signal))
ech_obj_sig_data = bsig_proto_resp_obj.eachSigValues.add()
# If data is present for signal send the values else do not send anything
if obj_sig_val_lst:
if self.bsig_tmstamp_lst:
# Get the index/sample count for the timestamp
if tmstamp_rdr != -1:
try:
sample_cnt = self.bsig_tmstamp_lst.index(tmstamp_rdr)
# print "cmn_sig_val_lst :: ", cmn_sig_val_lst
print "sample_cnt >> ", sample_cnt, obj_sig_val_lst[sample_cnt]
obj_sig_val_lst = [obj_sig_val_lst[sample_cnt]]
except ValueError as e:
print "No signal value for this timestamp %d and signal %s" % (
tmstamp_rdr, ech_signal)
pass
else:
print "TimeStamp data not fetched from Bsig file"
continue
ech_obj_sig_data.signalName = ech_signal
ech_obj_sig_data.objectId = ech_obj_num
for ech_obj_sig_val in obj_sig_val_lst:
ech_obj_sig_data.signalvalues.append(ech_obj_sig_val)
# else:
# ech_obj_sig_data.signalvalues.append(0)
except signalreader.SignalReaderException, e:
print "Signal not found", str(e)
data_payload = bsig_proto_resp_obj.SerializeToString()
# print "data_payload :: ", data_payload
self.bsig_pub_obj.send(data_payload)
end_time = datetime.now()
duration = end_time - start_time
print("duration :: ", duration.total_seconds(), duration.total_seconds()/60)
if __name__ == '__main__':
# read_the_signals()
RadarSignalInfo()
# D:\Work\2018\code\Tensorflow_code\Protobuf_compilers\protoc3.5\bin\protoc -I=.\ --python_out=.\ Radar.proto
# C:\Python27\Scripts\pyinstaller --onefile bsig_sig_val_publish.py --add-data _ecal_py_2_7_x86.pyd;.
# 1. Request for all the timestamps. store it in the instance variable
# 2. Send all the signal names only once, store it in instance variable
# 3. Each button clicked, send in the next timestamp
# Verify the existence of the signals in the bsig file from the property 'signal_names'
# Get the sample count for each of the signals based on their timestamp
# 4. Each of the signal value field will have just one value in its array
<file_sep>/H5_app/hfl_image_generator/h5_image_publisher_test.py
import ecal
import json
import h5py
import os
import sys
import numpy as np
import cv2
import imageservice_pb2
import time
from PyQt4 import QtCore
from PyQt4 import QtGui
from PIL import Image
with open('topics.json') as data_file:
json_data = json.load(data_file)
# fname = json_data['h5_filename']
if getattr(sys, 'frozen', False):
os.chdir(sys._MEIPASS)
class H5ReaderSequence(object):
def __init__(self, fname):
self.reset(fname)
self.h5_obj = h5py.File(fname, "r")
# self.h5_obj = h5py.File(r'C:\Users\uidr8549\Documents\SametimeFileTransfers\2018.04.25_at_12.28.14_svu-mi5_149.h5', "r")
self.h5_grp_lst = []
self.img_pth_lst = []
self.dvc_chnl_map = self.get_device_channel_name()
# Fetch all the timestamps
# self.timestamps = self.get_all_timestamps()
# print "info >>> ", self.dvc_chnl_map
# # Get timestamps based on channel name
# tmstamps = self.get_all_tmstamps_chnls('svu32x_rear')
# print "tmstamps :: ", tmstamps
# # Will fetch you an encoded image for a given channel and timestamp
# self.get_img_for_tmstamp_and_chnl('svu32x_left', 1524659294095512)
def get_img_for_tmstamp_and_chnl(self, device_name, channel_name, timestamp):
# get the channel group for channel
# chanl_grp = [evry_chnl for evry_chnl in self.h5_grp_lst[1:] if channel_name in str(evry_chnl)]
h5_img_pth = device_name + '/' + channel_name + '/' + str(timestamp)
print "h5_img_pth:: ", h5_img_pth
if h5_img_pth:
img_data = self.h5_obj[h5_img_pth]
print "img_data :: ", img_data
if isinstance(img_data, h5py.Dataset):
img_arr = np.zeros(img_data.shape, dtype=np.uint8)
img_data.read_direct(img_arr)
# cv2.imshow("Output", img_arr)
# cv2.waitKey(0)
# Encode the image to be sent across protobuf
ecal_encode_img = cv2.imencode('.png', img_arr)[1].tostring()
return ecal_encode_img
else:
return None
else:
return None
# else:
# return None
def get_tmstamps_for_dvc_chnl(self, device_name, channel):
# make channel group for channel
# chanl_grp = [evry_chnl for evry_chnl in self.h5_grp_lst if channel in str(evry_chnl)]
print "\n"
# print "channel -> ", channel
# print "device name -> ", device_name
# print "self.h5_grp_lst : ", self.h5_grp_lst
for evry_chnl in self.h5_grp_lst[:]:
dvc_chnl_lst = str(evry_chnl).split('/')
# print "----------------", evry_chnl, dvc_chnl_lst
if len(dvc_chnl_lst) == 2:
if ('/' in str(evry_chnl)) :
if (device_name == dvc_chnl_lst[0]) and (channel == dvc_chnl_lst[1]):
chanl_grp = str(evry_chnl)
print "chanl_grp %s exists " %chanl_grp
timestamps = self.h5_obj[chanl_grp]
# timestamps = data["mfc4xx/MFC4xx_long_image_right"]
timestamps = [str(ech_tmstamp) for ech_tmstamp in timestamps.keys()]
# print("timestamps >> ", timestamps)
return timestamps
else:
print "No matching channel group found for %s %s " %device_name %channel
return None
def get_device_channel_name(self):
self.h5_obj.visititems(self.print_groups)
# print "self.h5_grp_lst :: ", self.h5_grp_lst
device_names_lst = [evry_chnl for evry_chnl in self.h5_grp_lst if '/' not in str(evry_chnl)]
# chnl_names_lst = [evry_chnl.split('/')[1] for evry_chnl in self.h5_grp_lst if '/' in str(evry_chnl)]
# print "chnl_names_lst ::: ", device_names_lst, chnl_names_lst
dvc_chnl_map = {}
for evry_dvc_name in device_names_lst:
chnl_lst = []
for evry_chnl in self.h5_grp_lst:
if '/' in str(evry_chnl) and evry_chnl.split('/')[0] == evry_dvc_name:
chnl_lst.append(evry_chnl.split('/')[1])
# print "evry_chnl :>>", evry_dvc_name, evry_chnl
# dvc_chnl_map[evry_dvc_name] = [evry_chnl]
dvc_chnl_map[evry_dvc_name] = chnl_lst
# print "dvc_chnl_map :: ", dvc_chnl_map
# chnl_name = str(self.h5_grp_lst[1]).split('/')[1]
return dvc_chnl_map
def reset(self, fname):
if not os.path.isfile(fname):
print("Error - H5 file not available: %s!" % fname)
sys.exit()
# mylist = []
def print_groups(self, name, obj):
if isinstance(obj, h5py.Group):
self.h5_grp_lst.append(name)
def get_all_timestamps(self):
# print "????", self.device_name, self.chnl_name,
timestamps = self.h5_obj[self.h5_grp_lst[1]]
# timestamps = data["mfc4xx/MFC4xx_long_image_right"]
timestamps = [str(ech_tmstamp) for ech_tmstamp in timestamps.keys()]
# print("timestamps >> ", timestamps)
return timestamps
def print_img_tmstamp(self, name, obj):
if isinstance(obj, h5py.Dataset):
self.img_pth_lst.append(name)
def get_images(self):
self.h5_obj.visititems(self.print_img_tmstamp)
# print "self.img_pth_lst > ", self.img_pth_lst
for ech_img_pth in self.img_pth_lst:
img_data = self.h5_obj[ech_img_pth]
print "img_data :>> ", img_data, img_data.shape
arr = np.zeros(img_data.shape, dtype=np.uint8)
# print arr
# break
img_data.read_direct(arr)
# print "arr >> ", arr
# cv2.imwrite('color_img.jpg', arr)
# cv2.imshow("Output", arr)
# cv2.waitKey(0)
# break
# for ec
def get_imgarry_for_tmstamp(self, timestamp):
self.h5_obj.visititems(self.print_img_tmstamp)
# print "self.img_pth_lst > ", self.img_pth_lst
corresondng_img_pth = [ech_img_pth for ech_img_pth in self.img_pth_lst if timestamp in ech_img_pth][0]
print "......", corresondng_img_pth
img_data = self.h5_obj[corresondng_img_pth]
img_arr = np.zeros(img_data.shape, dtype=np.uint8)
img_data.read_direct(img_arr)
# cv2.imshow("Output", img_arr)
# cv2.waitKey(0)
return img_arr
class H5EcalDataPublisher(object):
def __init__(self):
# Initialize ecal service for H5 reader
# Initialize the proto message object
ecal.initialize(sys.argv, "H5 data publisher")
self.initialize_subscr_topics()
self.initialize_publsr_topics()
self.h5_pixel_obj = h5py.File(fpixelfile, "w")
self.define_subscr_callbacks()
def initialize_subscr_topics(self):
# Initialize all the subscriber topics
# self.h5_dvc_subscr_obj = ecal.subscriber(json_data['device_request'])
self.h5_chnl_subscr_obj = ecal.subscriber(json_data['channel_request'])
self.h5_img_subscr_obj = ecal.subscriber(json_data['hfl_request'])
self.h5_pixelwriter_obj = ecal.subscriber(json_data['pixelwrite_request'])
def initialize_publsr_topics(self):
# Initialize all the publisher topics
# self.h5_dvc_publr_obj = ecal.publisher(json_data['device_response'])
self.h5_chnl_publr_obj = ecal.publisher(json_data['channel_response'])
self.h5_img_publr_obj = ecal.publisher(json_data['hfl_response'])
# def pub_dvc_data(self, topic_name, msg, time):
# # print "pub_dvc_data >> ", topic_name, msg
# dvctyp_req_proto_obj = imageservice_pb2.deviceTypeRequest()
# dvctyp_req_proto_obj.ParseFromString(msg)
# dvc_type = dvctyp_req_proto_obj.device_type
# # print "dvc_type >> ", dvc_type
# # Publish device type
# dvctyp_resp_proto_obj = imageservice_pb2.deviceTypeResp()
# if dvc_type == "True":
# h5file_obj = H5ReaderSequence(fname)
# print "device_name :: ", h5file_obj.device_name
# dvctyp_resp_proto_obj.device_type = h5file_obj.device_name
# else:
# dvctyp_resp_proto_obj.device_type = ""
def pub_chnl_data(self, topic_name, msg, time):
chnl_req_proto_obj = imageservice_pb2.devicesDataRequest()
chnl_req_proto_obj.ParseFromString(msg)
bool_chnl_req = chnl_req_proto_obj.required_devicesData
chnl_resp_proto_obj = imageservice_pb2.devicesDataResponse()
if bool_chnl_req:
h5file_obj = H5ReaderSequence(fname)
# From H5 file we map the dictionary to have device name as
# keys and value to be their list of corresponding channels
dvc_chnl_dict = h5file_obj.dvc_chnl_map
chnl_resp_proto_obj.deviceCount = len(dvc_chnl_dict.keys())
if dvc_chnl_dict.keys():
for ech_dvc_name in dvc_chnl_dict.keys():
dvc_data_obj = chnl_resp_proto_obj.devicedata.add()
# Send in the device name
dvc_data_obj.deviceName = str(ech_dvc_name)
channel_lst = dvc_chnl_dict[ech_dvc_name]
# print "channel_lst :: ", channel_lst
if channel_lst:
dvc_data_obj.no_of_channels = len(channel_lst)
else:
dvc_data_obj.no_of_channels = -1
for ech_channel in channel_lst:
print "ech_channel :> ", ech_channel
# Get the timestamps for the device and channel
tmstamp_lst = h5file_obj.get_tmstamps_for_dvc_chnl(device_name=str(ech_dvc_name), channel=str(ech_channel))
print "tmstamp_lst >> ", tmstamp_lst
if tmstamp_lst is not None:
chnl_info_obj = dvc_data_obj.channel_Info.add()
chnl_info_obj.channel_name = str(ech_channel)
for evry_tmstamp in tmstamp_lst:
# print "evry_tmstamp :: ", evry_tmstamp
chnl_info_obj.timestamp.append(int(evry_tmstamp))
else:
chnl_resp_proto_obj.deviceCount = -1
self.h5_chnl_publr_obj.send(chnl_resp_proto_obj.SerializeToString())
def pub_img_data(self, topic_name, msg, time):
img_req_proto_obj = imageservice_pb2.ImageRequest()
img_resp_proto_obj = imageservice_pb2.ImageResponse()
img_req_proto_obj.ParseFromString(msg)
device_name = img_req_proto_obj.request_device_name
channel_name = img_req_proto_obj.request_channel_name
timestamp = img_req_proto_obj.required_timestamp
print ">>>>..", channel_name, timestamp
h5file_obj = H5ReaderSequence(fname)
encoded_img_arr = h5file_obj.get_img_for_tmstamp_and_chnl(device_name, channel_name, timestamp)
if encoded_img_arr is not None:
img_resp_proto_obj.response_device_name = device_name
img_resp_proto_obj.recieved_timestamp = timestamp
img_resp_proto_obj.response_channel_name = channel_name
img_resp_proto_obj.base_image = encoded_img_arr
else:
img_resp_proto_obj.recieved_timestamp = -1
self.h5_img_publr_obj.send(img_resp_proto_obj.SerializeToString())
def subscribe_pixel_images(self,topic_name,msg,time):
print "received data for pixel label write"
pixel_img_req_proto_obj = imageservice_pb2.PixelLabelWriteRequest()
pixel_img_req_proto_obj.ParseFromString(msg)
# devicename = pixel_img_req_proto_obj.devicename
channelname = pixel_img_req_proto_obj.response_channel_name
timestamp = pixel_img_req_proto_obj.recieved_timestamp
print("12334455")
obj_PixelImageData = pixel_img_req_proto_obj.image
# print('object data',obj_PixelImageData)
for ech_pixel_item in obj_PixelImageData:
print("inside the loop")
imageName = ech_pixel_item.name
#format = ech_pixel_item.format
data = ech_pixel_item.data
width = ech_pixel_item.width
height = ech_pixel_item.height
print('name',imageName)
key = str(channelname) + '/'+str(timestamp)+'/'+str(imageName)
print('key',key)
# print('data',data)
nparray = np.fromstring(data, np.uint8)
print "nparray :: ", nparray
re_img_np_ary = cv2.imencode(mask_layer, cv2.IMREAD_COLOR)
# print "QBuffer.data() 1:: "
# from PyQt4.QtGui import QImage
# from PyQt4.QtCore import QBuffer
# print "QBuffer.data() 2:: "
# print('type: ',type(ech_pixel_item.data))
# QBuffer.setData(ech_pixel_item.data)
# print "QBuffer.data() :: ", QBuffer.data()
# b = QImage.loadFromData(QBuffer.data())
# print "b>> ", b
import PIL.ImageColor as ImageColor
# rgb = ImageColor.getrgb('red')
# solid_color = np.expand_dims(np.ones_like(nparray), axis=2) * np.reshape(list(rgb), [1, 1, 3])
# print "solid_color >> ", solid_color
pil_mask = Image.fromarray(np.uint8(255.0 * 0.4 * nparray)).convert('L')
print "pil_mask >> ", pil_mask
mask_layer = np.array(pil_mask.convert('RGB'))
print "mask_layer : ", mask_layer
# CV_LOAD_IMAGE_COLOR
re_img_np_ary = cv2.imdecode(mask_layer, cv2.IMREAD_COLOR)
cv2.imshow("window", re_img_np_ary)
cv2.imwrite("image.png", re_img_np_ary)
cv2.waitKey(0)
cv2.destroyAllWindows()
print ">>>"
# self.h5_pixel_obj.create_dataset('SVFront/296/876876876_SVFront_296_Vehicle_24',data=re_img_np_ary)
# cv2.imshow("window", solid_color)
# cv2.imwrite("image.png", solid_color)
self.h5_pixel_obj.close()
def define_subscr_callbacks(self):
# For device data
# Deprecating device request
# self.h5_dvc_subscr_obj.set_callback(self.pub_dvc_data)
# For Channel data
self.h5_chnl_subscr_obj.set_callback(self.pub_chnl_data)
# For Image data
self.h5_img_subscr_obj.set_callback(self.pub_img_data)
self.h5_pixelwriter_obj.set_callback(self.subscribe_pixel_images)
while ecal.ok():
time.sleep(0.1)
if __name__ == '__main__':
# D:\\Work\\2018\\code\\LT5G\\HDF5_reader\\2017.09.07_at_20.37.57_camera-mi_1449.h5
# C:\\Users\\uidr8549\\My Documents\\SametimeFileTransfers\\2018.04.25_at_12.28.14_svu-mi5_149.h5
# fname = r'D:\Work\2018\code\LT5G\HDF5_reader\20161215_1114_{C24EDA32-C92E-40A9-9AC6-75307E1001F5}.h5'
fname = r'C:\Users\uidr8549\My Documents\SametimeFileTransfers\2018.04.25_at_12.28.14_svu-mi5_149.h5'
# fname = 'D:\\Work\\2018\\code\\LT5G\\HDF5_reader\\2017.09.07_at_20.37.57_camera-mi_1449.h5'
# outdir = r'D:\Work\2018\code\LT5G\HDF5_reader\HFL_LabelToolExample\hfl_labeltool\hfl_ecal\hfl_image_generator\HFL_images'
#fname = sys.argv[1]
# fname = 'D:\\Continuous_2013.12.19_at_14.10.48\\2018.04.25_at_12.28.14_svu-mi5_149.h5'
fpixelfile = 'D:\\PixelData.h5'
# h5file_obj = H5ReaderSequence(fname)
# h5file_obj.get_imgarry_for_tmstamp(timestamp='1481800461765472')
h5_ecal_inst = H5EcalDataPublisher()
# pyinstaller --onefile hfl_img_generator.py<file_sep>/Neo4j_py/neo_restAPI/ldss_data_ldroi.py
# coding: utf-8
# In[42]:
from cx_Oracle import connect as cx_connect
from cx_Oracle import DatabaseError
# In[43]:
ORC_CONN = cx_connect("ALGO_DB_USER", "read", "racadmpe", False)
# In[44]:
ORC_CURSOR = ORC_CONN.cursor()
stmt = ''' select PRJ_FUNC,DEPARTMENT, RECFILENAME,COUNTRY,ROAD_TYPE,LIGHT_CONDITIONS,WEATHER
FROM adms_teststage.ADMS_RESTRUCTURED_ENV_LABELS
where ROWNUM<100 ORDER BY RECFILENAME'''
ORC_CURSOR.execute(stmt)
ORC_CURSOR.arraysize = 50
data = ORC_CURSOR.fetchall()
all_data = []
for item in data:
colun_names = [column[0] for column in ORC_CURSOR.description]
# print "colun_names",colun_names
data = dict(zip(colun_names, item))
all_data.append(data)
# In[45]:
all_data
# In[46]:
import pandas as pd
ldss_dtfr = pd.DataFrame(all_data)
# ldss_dtfr.to_csv("ldss.csv", encoding='utf-8', index=False)
# In[47]:
ldss_dtfr
# In[48]:
# Add a new project and function column
def get_element(my_list, position):
return my_list[position]
ldss_dtfr['PROJECT'] = ldss_dtfr.PRJ_FUNC.str.split('_').apply(get_element, position=0)
ldss_dtfr['FUNCTION'] = ldss_dtfr.PRJ_FUNC.str.split('_').apply(get_element, position=1)
ldss_dtfr
# In[49]:
# Index the Dataframe by recording name
idx_rec_dtfr = ldss_dtfr.set_index(['RECFILENAME'])
idx_rec_dtfr
# In[50]:
# Delete the PRJ_FUNC column
del idx_rec_dtfr['PRJ_FUNC']
idx_rec_dtfr
# In[51]:
# data_grp = sel_data.set_index(['COUNTRY','DEPARTMENT','LIGHT_CONDITIONS','PRJ_FUNC','ROAD_TYPE','WEATHER'])
# data_grp
# Get distinct rec names
# distinct_rec_names = idx_rec_dtfr.index.unique()
# # dir(distinct_rec_names)
# rec_names_lst = distinct_rec_names.tolist()
# rec_names_lst, len(rec_names_lst)
# In[58]:
ORC_CURSOR = ORC_CONN.cursor()
stmt = ''' SELECT DISTINCT(SR_SIGN_CLASS), "RecIdFileName"
FROM adms_teststage.MFC400_SR_LDROI_B
WHERE "RecIdFileName" IN {} ORDER BY "RecIdFileName" '''.format(tuple(rec_names_lst))
ORC_CURSOR.execute(stmt)
ORC_CURSOR.arraysize = 50
data = ORC_CURSOR.fetchall()
obj_data = []
for item in data:
colun_names = [column[0] for column in ORC_CURSOR.description]
# print "colun_names",colun_names
data = dict(zip(colun_names, item))
obj_data.append(data)
obj_data
# In[61]:
ldroi_dtfr = pd.DataFrame(obj_data)
ldroi_dtfr.columns = ['RECFILENAME','SR_SIGN_CLASS']
ldroi_dtfr
# In[70]:
merged_dtfr = pd.merge(ldss_dtfr, ldroi_dtfr, on='RECFILENAME', how='right')
mergd_idxd_ldroi = merged_dtfr.set_index(['RECFILENAME'])
del mergd_idxd_ldroi['PRJ_FUNC']
mergd_idxd_ldroi
# In[77]:
distinct_rec_names = mergd_idxd_ldroi.index.unique()
# dir(distinct_rec_names)
rec_names_lst = distinct_rec_names.tolist()
rec_names_lst, len(rec_names_lst)
# In[71]:
sel_data = mergd_idxd_ldroi.loc['Snapshot_2015.07.23_at_12.56.57.rec']
sel_data
# In[53]:
# ech_rec_dtfr = sel_data.reset_index()
# country = ech_rec_dtfr['COUNTRY'].unique().tolist()
# dpt_type = ech_rec_dtfr['DEPARTMENT'].unique().tolist()
# lc_type = ech_rec_dtfr['LIGHT_CONDITIONS'].unique().tolist()
# prj_type = ech_rec_dtfr['PROJECT'].unique().tolist()
# func_type = ech_rec_dtfr['FUNCTION'].unique().tolist()
# rd_type = ech_rec_dtfr['ROAD_TYPE'].unique().tolist()
# wthr_type = ech_rec_dtfr['WEATHER'].unique().tolist()
# rd_type
# In[74]:
clmn_names_lst = mergd_idxd_ldroi.columns.tolist()
clmn_names_lst
# In[78]:
# Iterate through each recording
lst_data = []
for ech_rec in rec_names_lst:
rec_dict = {}
sel_data = mergd_idxd_ldroi.loc[ech_rec]
print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
# print sel_data
ech_rec_dtfr = sel_data
# print ech_rec_dtfr
rec_dict['RECFILENAME'] = ech_rec
for ech_clmn_name in clmn_names_lst:
# print ech_rec_dtfr[ech_clmn_name]
if type(ech_rec_dtfr) is pd.Series:
clmn_data = ech_rec_dtfr[ech_clmn_name]
# print ">>>", clmn_data
rec_dict[ech_clmn_name] = [clmn_data]
else:
clmn_data = ech_rec_dtfr[ech_clmn_name].unique().tolist()
rec_dict[ech_clmn_name] = clmn_data
# print "rec_dict :: ", rec_dict
lst_data.append(rec_dict)
# In[79]:
lst_data
# In[80]:
# Dump the data into a JSON
import json
with open("ldss.json", 'w+') as outfile:
json.dump(lst_data, outfile, indent=4)
<file_sep>/H5_app/hfl_image_generator/hfl_img_generator.py
import h5py
import os
import sys
import numpy as np
import cv2
if getattr(sys, 'frozen', False):
os.chdir(sys._MEIPASS)
class H5ReaderSequence(object):
def __init__(self, fname):
if not os.path.isfile(fname):
print("Error - H5 file not available: %s!" % fname)
sys.exit()
self.data = h5py.File(fname, "r")
self.h5_dataset_lst = []
self.intensity_path, self.dist_path = self.get_intensity_and_dist_path()
self.reset(fname)
self.lastLoadFilename = ""
def get_img_dataset(self, name, obj):
if isinstance(obj, h5py.Dataset):
self.h5_dataset_lst.append(name)
def get_intensity_and_dist_path(self):
# self.data
self.data.visititems(self.get_img_dataset)
print "self.h5_dataset_lst :: ", self.h5_dataset_lst
intensity_path = [ech_dtset_path for ech_dtset_path in self.h5_dataset_lst if 'Intensity' in ech_dtset_path][0]
dist_path = [ech_dtset_path for ech_dtset_path in self.h5_dataset_lst if 'Dist' in ech_dtset_path][0]
print "paths :: ", intensity_path, dist_path
# exit(0)
return intensity_path, dist_path
def reset(self, fname):
self.img_w = 128
self.img_h = 32
self.max_d = 30
self.i = 0
self.max_i = len(self.data[self.intensity_path])
def getI(self):
return self.i
def setI(self, i):
if i >= self.getMaxI():
i = 0
if i < 0:
i = self.getMaxI() - 1
self.i = i
def getMaxI(self):
return self.max_i
def get(self, i):
self.setI(i)
raw_int = self.data["/HFL130/PCA/PcaDebugData/Data/m_Intensity_au16"][self.i][0][:(self.img_h * self.img_w)]
raw_ran = self.data["/HFL130/PCA/PcaDebugData/Data/m_Dist_MF_as32"][self.i][0][:(self.img_h * self.img_w)]
mask = raw_ran > (self.max_d * 4096)
raw_ran[mask] = self.max_d * 4096
raw_int[mask] = 0
dat_int = np.rot90(np.asarray(raw_int, dtype=np.uint8).reshape(self.img_w, self.img_h))
dat_ran = np.rot90(np.asarray(raw_ran / 4096.0, dtype=np.float32).reshape(self.img_w, self.img_h))
return (dat_int, dat_ran)
def get_all_timestamps(self, filename):
data = h5py.File(filename, "r")
self.idxlist = [str(d) for d in data["/MTS/Package/TimeStamp"]]
return self.idxlist
def loadData(self, filename, timestamp):
data = h5py.File(filename, "r")
if self.lastLoadFilename != filename:
self.idxlist = [str(d) for d in data["/MTS/Package/TimeStamp"]]
# print("self.idxlist :: ", self.idxlist)
idx = self.idxlist.index(timestamp)
try:
# timestamp = self.idxlist[idx]
raw_int = data[self.intensity_path][idx][0][:(self.img_h * self.img_w)]
raw_ran = data[self.dist_path][idx][0][:(self.img_h * self.img_w)]
mask = raw_ran > (self.max_d * 4096)
raw_ran[mask] = self.max_d * 4096
raw_int[mask] = 0
dat_int = np.rot90(np.asarray(raw_int, dtype=np.uint8).reshape(self.img_w, self.img_h))
dat_ran = np.rot90(np.asarray(raw_ran / 4096.0, dtype=np.float32).reshape(self.img_w, self.img_h))
data.close()
self.lastfilename = filename
except IndexError, e:
pass
print "Time stamp does not exist for this index"
return (dat_int, dat_ran)
def loadPreviouseData(self, filename, timestamp):
data = h5py.File(filename, "r")
if self.lastLoadFilename != filename:
self.idxlist = [str(d) for d in data["/MTS/Package/TimeStamp"]]
idx = self.idxlist.index(timestamp) - 1
if idx < 0:
return ([], [])
raw_int = data[self.intensity_path][idx][0][:(self.img_h * self.img_w)]
raw_ran = data[self.dist_path][idx][0][:(self.img_h * self.img_w)]
mask = raw_ran > (self.max_d * 4096)
raw_ran[mask] = self.max_d * 4096
raw_int[mask] = 0
dat_int = np.rot90(np.asarray(raw_int, dtype=np.uint8).reshape(self.img_w, self.img_h))
dat_ran = np.rot90(np.asarray(raw_ran / 4096.0, dtype=np.float32).reshape(self.img_w, self.img_h))
data.close()
self.lastfilename = filename
return (dat_int, dat_ran)
def loadStartStopTimestamp(self, filename):
data = h5py.File(filename, "r")
starttimestamp = data["/MTS/Package/TimeStamp"][0]
stoptimestamp = data["/MTS/Package/TimeStamp"][-1]
data.close()
return (starttimestamp, stoptimestamp)
def getInfo(self, i):
return [str(self.data.filename),
str(self.data["/MTS/Package/TimeStamp"][i]),
str(self.data["/MTS/Package/CycleID"][i]),
str(self.data["/MTS/Package/CycleCount"][i])]
if __name__ == '__main__':
fname = r'D:\Work\2018\code\LT5G\HDF5_reader\2017.09.07_at_20.37.57_camera-mi_1449.h5'
outdir = r'D:\Work\2018\code\LT5G\HDF5_reader\HFL_LabelToolExample\hfl_labeltool\hfl_ecal\hfl_image_generator\HFL_images'
print "ARGUMENT 1 : H5 file path. ex: D:\\2017.09.07_at_20.37.57_camera-mi_1449.h5"
print "ARGUMENT 2 : H5 Image folder ex: D:\\\HFL_images"
fname = sys.argv[1]
outdir = sys.argv[2]
h5file_obj = H5ReaderSequence(fname)
# st_time, end_time = h5file_obj.loadStartStopTimestamp(fname)
# print("st_time, end_time :: ", st_time, end_time)
tmstamps_lst = h5file_obj.get_all_timestamps(fname)
# tm_stamp = '1504816686729381'
# outdir = r"D:\Work\2018\code\LT5G\HDF5_reader\h5_read_v1\imgdir"
# outdir = r"\HFL_Images"
if not os.path.exists(outdir):
os.makedirs(outdir)
print outdir
for tm_stamp in tmstamps_lst:
inten_data, dist_data = h5file_obj.loadData(fname, tm_stamp)
# print("arr_data :: ", arr_data)
print("timestamp :: ", tm_stamp)
cv2.imwrite(outdir + "\\HFL130INTENSITY_%s.jpg" % tm_stamp, inten_data)
cv2.imwrite(outdir + "\\HFL130DISTANCE_%s.jpg" % tm_stamp, dist_data)
# pyinstaller --onefile hfl_img_generator.py<file_sep>/Neo4j_py/neo_restAPI/filter_qry.py
from neo4jrestclient.query import Q
from neo4jrestclient.client import GraphDatabase
from neo4jrestclient import client
gdb = GraphDatabase("http://10.223.244.129:7474/db/data/", username="neo4j", password="<PASSWORD>")
#
recname= '''Continuous_2011.02.11_at_11.52.06.rec'''
q=''' MATCH (CommonData)<-[cd:cd]-(RecordingName)-[c:c]->(Country)-
[rt:rt]->(RoadType)-
[w:w]->(WeatherCondition)-
[lc:lc]->(LightCondition)
WHERE RecordingName.name = '{}'
RETURN RecordingName.name as RecName, Country.name as Country, RoadType.name as RoadType,
WeatherCondition.name as WeatherCondition, LightCondition.name as LightCondition, CommonData.project as Project,
CommonData.function as Function, CommonData.department as Department '''.format(recname)
q =''' MATCH (RecordingName:RecordingName)
RETURN RecordingName.name '''
#
#
# q=''' MATCH (RecordingName)-[c:c]->(Country)
# WHERE RecordingName.name = 'Continuous_2011.02.11_at_11.52.06.rec'
# RETURN RecordingName.name as RecName,Country.name as Country'''
#
result = gdb.query(q = q, data_contents=True)
print "result :: ", dir(result)
print "rows::", result.rows
# print "columns::", result.graph
# from py2neo import Graph
# graph = Graph("http://10.223.244.129:7474/db/data/", username="neo4j", password="<PASSWORD>")
# x = graph.run(q)
#
# print dir(x)
#
# print x.data()
# for d in x:
# print(d)
<file_sep>/Flatbuffer/canv_flt/canv_buffer.py
"""
flatc -p -b obl.fbs obl.json
"""
from SequenceList import SequenceList, SequenceListStart, SequenceListEnd,\
SequenceListAddSequence, SequenceListStartSequenceVector
# import SequenceList, Seq, sequence_details
from Seq import Seq, SeqAddSequenceDetails, SeqStart, SeqEnd
from sequence_details import sequence_details, \
sequence_detailsAddFolderName, sequence_detailsStart, sequence_detailsEnd
import flatbuffers
from datetime import datetime
import time
import json
def write_into_flt_buffr():
# buf = open('obl.bin', 'rb').read()
# # print "buf::", type(buf)
# buf = bytearray(buf)
# seq_lst_obj = SequenceList.GetRootAsSequenceList(buf, 0)
# seq_obj = seq_lst_obj.Sequence(0)
# fl_name = seq_obj.SequenceDetails().FolderName()
# print "fl_name::", fl_name
# Serialize
builder = flatbuffers.Builder(0)
fldr_name_flt = builder.CreateString("XYZ")
sequence_detailsStart(builder)
sequence_detailsAddFolderName(builder, fldr_name_flt)
fldr_name = sequence_detailsEnd(builder)
SeqStart(builder)
SeqAddSequenceDetails(builder, fldr_name)
seq_obj = SeqEnd(builder)
SequenceListStart(builder)
# SequenceListAddSequence(builder, seq_obj)
SequenceListStartSequenceVector(builder, 4)
builder.PrependUOffsetTRelative(seq_obj)
builder.EndVector(4)
orc = SequenceListEnd(builder)
builder.Finish(orc)
buf = builder.Output()
# De serialize
print "buf::", type(buf)
seq_lst_obj = SequenceList.GetRootAsSequenceList(buf, 0)
seq_obj = seq_lst_obj.Sequence(0)
fl_name = seq_obj.SequenceDetails().FolderName()
print "fl_name::", fl_name
def read_flat_buffr_attrib():
st_time = time.time()
buf = open('obl.bin', 'rb').read()
buf = bytearray(buf)
seq_lst_obj = SequenceList.GetRootAsSequenceList(buf, 0) #.Sequence(0).Labels(0).Devices(0).Channels(0).ObjectLabels(0).TimeStamp()
seq_obj = seq_lst_obj.Sequence(0)
lbl_obj = seq_obj.Labels(0)
dvc_obj = lbl_obj.Devices(0)
chnl_obj = dvc_obj.Channels(0)
# obj_lbl_obj = chnl_obj.ObjectLabels(2)
# name = obj_lbl_obj.TimeStamp()
t1 = chnl_obj.ObjectLabels(0).TimeStamp()
t2 = chnl_obj.ObjectLabels(1).TimeStamp()
t3 = chnl_obj.ObjectLabels(2).TimeStamp()
tx = chnl_obj.ObjectLabels(2).FrameObjectLabels(0).Height()
print tx
ed_time = time.time()
duration = ed_time - st_time
print "duration of flatbuff::", duration
#===================================================
def read_json_attrib():
st_timej = time.time()
with open('obl.json') as ldroi_json:
ldroi = json.load(ldroi_json)
obl = ldroi["Sequence"][0]["Labels"][0]["Devices"][0]["Channels"][0]["ObjectLabels"]
k1 = obl[0]["TimeStamp"]
k2 = obl[1]["TimeStamp"]
k3 = obl[2]["TimeStamp"]
ty = obl[1]["FrameObjectLabels"][0]["height"]
print k1, k2, k3, ty
ed_timej = time.time()
duration_json = ed_timej - st_timej
print "duration of JSON::", duration_json
if __name__ == '__main__':
# read_flat_buffr_attrib()
# read_json_attrib()
write_into_flt_buffr()
<file_sep>/microblog_docker/Dockerfile
FROM python:2.7.10
ADD . /code
WORKDIR /code
RUN pip --proxy http://uidr8549:<EMAIL>:8080 install -r requirements.txt
CMD ["python", "app.py"]<file_sep>/Neo4j_py/neo_restAPI/arrange_data_for_graph.py
# rows = [[u'Continuous_2011.02.11_at_11.52.06.rec', [u'USA'], [u'City', u'Other', u'Motorway'], [u'Dry'], [u'Day'], [u'MFC400'], [u'SR '], [u'DEV']]]
#
# columns=[u'RecName', u'Country', u'RoadType', u'WeatherCondition', u'LightCondition', u'Project', u'Function', u'Department']
#
# for item in rows:
# data_cd = [dict(zip(columns, item))]
#
# print "data_cd :: ", data_cd
# Generate sample summaries
<file_sep>/PCD_generation/PCD_from_bsig/create_pcd_frm_bsig.py
"""
Works only for python 2.7
Ceate PCD file from BSIG
extract x and y co-ordinates(f_DistX, f_DistY) for all the objects in the BSIG file
Export the data to an H5 file
"""
# from signalreader import SignalReader
# from signal_loader import SignalLoader
from datetime import datetime
import numpy as np
import h5py
bsig_path = r"D:\Work\2018\code\Github_repo\PCD_generation\Continuous_2017.06.01_at_12.12.18.bsig"
# bsig_path = r"D:\Work\2018\code\LT5G\OLT\Radar_labelling_bsig\bsig_readers\20160608_1306_{4556C7A6-7F27-4A91-923E-4392C9785675}.bsig"
SAMPLE_COUNT = 75
H5_PCD_FILE = r'PCD_ordinate.h5'
## ======================================================================================================================
sig_name_lst = [
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].KinematicRel.f_DistX',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].KinematicRel.f_DistY'
]
obj_signals = [ech_sig for ech_sig in sig_name_lst if '%' in str(ech_sig)]
start_time = datetime.now()
def create_h5_frm_bsig():
with SignalReader(bsig_path) as sr:
pcd_dt_lst = []
for ech_obj_num in range(100):
new_sig_lst = []
for ech_signal in sig_name_lst:
# for ech_signal in obj_signals:
if '%' in str(ech_signal):
ech_signal = ech_signal.replace('%', str(ech_obj_num))
new_sig_lst.append(ech_signal)
existing_sgnls_lst = list(set(new_sig_lst) & set(sr.signal_names))
print ("existing_sgnls_lst :: ", existing_sgnls_lst)
# print ">> ", new_sig_lst
signals = sr[existing_sgnls_lst] # retrieves a list of both signals --> [[<sig1>], [<sig2>]]
# print ":>>", signals, len(signals)
specific_sig_values = [ech_sig_lst[SAMPLE_COUNT] for ech_sig_lst in signals]
specific_sig_values.append(0)
print("specific_sig_values >> ", specific_sig_values)
pcd_dt_lst.append(specific_sig_values)
# pcd_dt_lst.append([specific_sig_values[0], specific_sig_values[2], specific_sig_values[1]])
arr_data = np.array(pcd_dt_lst)
end_time = datetime.now()
duration = end_time - start_time
print("duration :: ", duration.total_seconds(), duration.total_seconds()/60)
##================= Create HDF5 file=================
h5_file_obj = h5py.File(H5_PCD_FILE, "a")
h5_file_obj.create_dataset('/pcd', data=arr_data)
h5_file_obj.close()
## ======================================================================================================================
def create_pcd_from_h5_bsig():
h5_file_obj = h5py.File(H5_PCD_FILE, "r")
arr_data = h5_file_obj['/pcd']
# print(dir(arr_data))
# print(type(arr_data.value))
from pypcd.pypcd import PointCloud
pc = PointCloud(pc_data=arr_data.value,
metadata={'version': .5, 'fields': ['x', 'y', 'z'], 'type': ['F', 'F', 'F'], 'size': [4, 4, 4],
'count': [1, 1, 1], 'width': len(arr_data.value), 'height': 1, 'points': len(arr_data.value), 'data': 'ascii',
'viewpoint': [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]})
pc.save_pcd(fname='bsig_rec.pcd', compression=None)
if __name__ == '__main__':
# create_h5_frm_bsig()
create_pcd_from_h5_bsig()
# Note : Function create_h5_frm_bsig works in python 2.7.10, Function create_pcd_from_h5_bsig works in Python 3.5.2
# Point cloud library for python compiles only for Python 3.5.2
<file_sep>/flsk_blogapp/demo.py
from flask import Flask
app = Flask(__name__)
def hello_world(name):
return "Hello World %s" % name
app.add_url_rule(r"/hello/<name>", "hello", hello_world)
if __name__ == '__main__':
app.run()<file_sep>/LT5G_to_DMS/labeledData_to_DMS.py
import json
class LabelProperties(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
class LabelToolToDMSConverter(object):
def __init__(self, lt5_json_fname):
with open(lt5_json_fname) as data_file:
self.lt5_json_obj = json.load(data_file)
self.project = ''
self.func = ''
self.generate_ldroi_file()
self.generate_ldss_file()
def generate_ldroi_file(self):
# Recording name should be the name of the file
rec_name = self.lt5_json_obj['Sequence'][0]['DeviceCommonData']['Name']
# Define the file name, Project and function information not included
dms_ldroi_json_fname = 'LDROI_' + rec_name + '.json'
# Gather all the track IDs
all_anno_elmnts_lst = self.lt5_json_obj['Sequence'][0]['DeviceData'][0]['ChannelData'][0]['AnnotatedElements']
track_ids = [evry_anno_elem['FrameAnnoElements'][0]['Trackid'] for evry_anno_elem in all_anno_elmnts_lst]
# Get unique track IDs, then iterate through every track ID same/different updating the attributes
# print "track_ids ::", track_ids
track_ids = list(set(track_ids))
# print "track_ids ::", track_ids
dms_ldroi_json_obj = {}
ldroi_attrib_dict = {}
ech_trk_dict = {}
for evry_trackid in track_ids:
# ech_trackid_dict = self.generate_ech_trackid_dict(all_anno_elmnts_lst)
# Iterate through every anno element
# sampl_lst = []
for ech_anno_element in all_anno_elmnts_lst:
# print "ech_anno_element ::", ech_anno_element
# Assign the project and function
category = ech_anno_element['FrameAnnoElements'][0]['category']
if '_' not in category:
self.project, self.func = category, category
else:
self.project, self.func = category.split('_')
# Get the LDROI attributes, prepare a dictionary and assign their respective values
ldroi_attrbs_dict = ech_anno_element['FrameAnnoElements'][0]['attributes']
trackid_iter = ech_anno_element['FrameAnnoElements'][0]['Trackid']
# print "trackid_iter >>", trackid_iter
if evry_trackid == trackid_iter:
# ldroi_attrib_dict = {}
# print "ech_anno_element>>", ech_anno_element["TimeStamp"]
if "Trackid" in dms_ldroi_json_obj:
if trackid_iter in dms_ldroi_json_obj['Trackid'].keys():
tmstamp_lst = dms_ldroi_json_obj['Trackid'][trackid_iter]["TimeStamp"]
# Keys of the attribute
ldr_attribs_lst = dms_ldroi_json_obj['Trackid'][trackid_iter].keys()
ldr_attribs_lst.remove("TimeStamp")
# print "ldr_attribs_lst :>", ldr_attribs_lst
# break
if tmstamp_lst is not None:
tmstamp_lst.append(ech_anno_element["TimeStamp"])
# print ">>>", tmstamp_lst
for evry_ldr_attrib in ldr_attribs_lst:
# print "evry_ldr_attrib ::", evry_ldr_attrib
if dms_ldroi_json_obj['Trackid'][trackid_iter][evry_ldr_attrib] is not None:
ldroi_attrib_appnd = dms_ldroi_json_obj['Trackid'][trackid_iter][evry_ldr_attrib]
# print ">>>", ldroi_attrib_appnd
ldroi_attrib_appnd.append(ldroi_attrbs_dict[evry_ldr_attrib])
# dms_ldroi_json_obj['Trackid'][trackid_iter][evry_ldr_attrib] = ldroi_attrib_appnd
ldroi_attrib_dict[str(evry_ldr_attrib)] = ldroi_attrib_appnd
# else:
# tmstamp = [ech_anno_element["TimeStamp"]]
# for evry_ldroi_attrib in ldroi_attrbs_dict:
# ldroi_attrib_dict[str(evry_ldroi_attrib)] = [ldroi_attrbs_dict[evry_ldroi_attrib]]
else:
print "{{{"
# dms_ldroi_json_obj['Trackid']["TimeStamp"] = [ech_anno_element["TimeStamp"]]
# Assigning each attribute for the first time during initialization
tmstamp = [ech_anno_element["TimeStamp"]]
for evry_ldroi_attrib in ldroi_attrbs_dict:
ldroi_attrib_dict[str(evry_ldroi_attrib)] = [ldroi_attrbs_dict[evry_ldroi_attrib]]
ldroi_attrib_dict["TimeStamp"] = tmstamp
# print "category ::", self.project, self.func
ech_trk_dict.update({evry_trackid: ldroi_attrib_dict})
# print "ldroi_attrib_dict ::", ldroi_attrib_dict.__dict__
trackId_info_dict = ech_trk_dict
dms_ldroi_json_obj['FUNCTION'] = self.func
dms_ldroi_json_obj['FAMILY'] = self.project
dms_ldroi_json_obj['RecIdFileName'] = rec_name
dms_ldroi_json_obj['Trackid'] = trackId_info_dict
with open(r'Output/' + dms_ldroi_json_fname, 'w+') as outfile:
json.dump(dms_ldroi_json_obj, outfile, indent=4)
def generate_ldss_file(self):
# Recording name should be the name of the file
rec_name = self.lt5_json_obj['Sequence'][0]['DeviceCommonData']['Name']
# Define the file name, Project and function information not included
dms_ldss_json_fname = 'LDSS_' + rec_name + '.json'
# Gather all the track IDs
all_info_elmnts_dict = self.lt5_json_obj['Sequence'][0]['DeviceData'][0]['InformationElements']
# Get the file name, project and function
first_anno_elem = self.lt5_json_obj['Sequence'][0]['DeviceData'][0]['ChannelData'][0]['AnnotatedElements'][0]
category = first_anno_elem['FrameAnnoElements'][0]['category']
if '_' not in category:
self.project, self.func = category, category
else:
self.project, self.func = category.split('_')
dms_ldss_json_obj = {}
dms_ldss_json_obj['FUNCTION'] = self.func
dms_ldss_json_obj['FAMILY'] = self.project
dms_ldss_json_obj['RecIdFileName'] = rec_name
# print "all_info_elmnts_dict ::", all_info_elmnts_dict
# Structurize the entire skeleton for LDSS
info_elems_lst = all_info_elmnts_dict.keys()
# Mandatory keys that needs to be present
# mandatory_attr_keys = ['LDSS_STOP_CYCLE_COUNTER']
info_elem_dub_dict = {}
for ech_info_elem in info_elems_lst:
info_elem_dub_dict[ech_info_elem] = {}
# Remove start and stop time stamp from the main dictionary
info_elems_mod_lst = [e for e in info_elems_lst if e not in ('FrameMtLDSSTimeStampStart', 'FrameMtLDSSTimeStampStop')]
for ech_info_elem in info_elems_mod_lst:
# only have that key which has the same parent key
info_elem_dub_dict = {evry_key_dict: val for evry_key_dict, val in info_elem_dub_dict.iteritems()
if evry_key_dict == ech_info_elem}
print "info_elem_dub_dict ::", info_elem_dub_dict
dms_ldss_json_obj[ech_info_elem] = info_elem_dub_dict
# Add data to each element, iterate through the LDSS file object
# for evry_lt5_attr_dict in all_info_elmnts_dict:
# print evry_lt5_attr_dict
for key_attr, ech_attr_vals_lst in all_info_elmnts_dict.iteritems():
# Compare each LT5 labeled data attr with DMS attributes
for key_dms_attr, ech_dms_ldss_attr in dms_ldss_json_obj.iteritems():
if key_attr == key_dms_attr:
# Extract the timestamp range which has value
# print "key_attr ::", key_attr
val_lst = []
start_timestamp_lst = []
stop_timestamp_lst = []
for evry_ldss_tmstamp_dict in ech_attr_vals_lst:
# print "evry_ldss_tmstamp_dict >>", evry_ldss_tmstamp_dict
if evry_ldss_tmstamp_dict['value'] is not None:
val_lst.append(evry_ldss_tmstamp_dict['value'])
print "ech_dms_ldss_attr >", ech_dms_ldss_attr
ech_dms_ldss_attr[key_attr] = val_lst
start_timestamp_lst.append(evry_ldss_tmstamp_dict['start'])
print "start_timestamp_lst ::", start_timestamp_lst
ech_dms_ldss_attr['FrameMtLDSSTimeStampStart'] = start_timestamp_lst
stop_timestamp_lst.append(evry_ldss_tmstamp_dict['end'])
ech_dms_ldss_attr['FrameMtLDSSTimeStampStop'] = stop_timestamp_lst
# break
with open(r'Output/' + dms_ldss_json_fname, 'w+') as outfile:
json.dump(dms_ldss_json_obj, outfile, indent=4)
if __name__ == '__main__':
lt5_json_fname = r'2018081307340912110_LabelData.json'
# lt5_json_fname = r'D:/LabelData_Y.json'
LabelToolToDMSConverter(lt5_json_fname)
<file_sep>/Bsig_app/publish_signals_bsig.py
import ecal
import sys
import Radar_pb2
import time
# from rdr_signal_info_pblsh import timeit
# @timeit
def publ_signal_names():
print "Publish bsig signal names......."
ecal.initialize(sys.argv, "Python Signal name publisher")
BSIG_INFO_OBJ = Radar_pb2.BsigDataRequest()
publisher_roi_obj = ecal.publisher(topic_name="BsigSignalNames")
bsig_path = r"D:\Work\2018\code\LT5G\OLT\Radar_labelling_bsig\bsig_readers\Continuous_2014.05.15_at_08.48.40.bsig"
# bsig_path = r"D:\Work\2018\code\LT5G\OLT\Radar_labelling_bsig\bsig_readers\20160608_1306_{4556C7A6-7F27-4A91-923E-4392C9785675}.bsig"
# sig_name = "SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Longitudinal.MotVar.Velocity"
sig_name_lst = ['SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Longitudinal.MotVar.Velocity',
'MTS.Package.TimeStamp',
'SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Longitudinal.MotVar.Accel',
'SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Lateral.YawRate.YawRate',
'SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Lateral.SlipAngle.SideSlipAngle',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Kinematic.fDistX',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Kinematic.fDistY',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Kinematic.fVrelX',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Legacy.uiLifeTime',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Attributes.eDynamicProperty',
'SIM VFB ALL.AlgoSenCycle.gSI_OOI_LIST.SI_OOI_LIST[%].object_id',
'SIM VFB ALL.AlgoSenCycle.gSI_OOI_LIST.SI_OOI_LIST[%].long_displacement',
'SIM VFB ALL.AlgoSenCycle.gSI_OOI_LIST.SI_OOI_LIST[%].lat_displacement_to_curvature']
# sig_name_lst = ['MTS.Package.TimeStamp'
# ]
BSIG_INFO_OBJ.bsigPath = bsig_path
BSIG_INFO_OBJ.objectIdCount = 40
for sig_name in sig_name_lst:
BSIG_INFO_OBJ.signalNames.append(sig_name)
# while ecal.ok():
# print("BSIG_INFO_OBJ.SerializeToString() :: ", BSIG_INFO_OBJ.SerializeToString())
time.sleep(1)
publisher_roi_obj.send(BSIG_INFO_OBJ.SerializeToString())
# break
# publisher_roi_obj.send(img_req_obj.SerializeToString())
# while ecal.ok():
# x = publisher_roi_obj.send(BSIG_INFO_OBJ.SerializeToString())
# print ">>>>", x
#=================================================================================================================
if __name__ == '__main__':
publ_signal_names()
# subscribe_signl_vals()<file_sep>/celery_rmq/run_tasks.py
"""
1. Start RabbitMQ server at C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.7\sbin\rabbitmq-server.bat start
Running RabbitMQ server on http://localhost:15672
2. Run celery in the terminal celery -A tsk_que worker --loglevel=info
celery -A celery_run worker --loglevel=info
3. Use flower to check this in real time
celery -A celery_run flower
http://localhost:5555
4. Run run_tasks.py
"""
# celery -A celery_rmq worker --loglevel=info
# celery -A celery_run worker --loglevel=info
from tasks import longtime_add
import time
if __name__ == '__main__':
result = longtime_add.delay(7, 5)
# at this time, our task is not finished, so it will return False
print 'Task finished? ', result.ready()
print 'Task result: ', result.result
# sleep 10 seconds to ensure the task has been finished
time.sleep(5)
# now the task should be finished and ready method will return True
print 'Task finished? ', result.ready()
print 'Task result: ', result.result<file_sep>/Flatbuffer/flt_ex.py
"""
flatc -p -b scm.fbs scm.json
"""
from ReposList import ReposList
from Repo import Repo
import flatbuffers
from datetime import datetime
import time
import json
st_time = datetime.now()
buf = open('scm.bin', 'rb').read()
buf = bytearray(buf)
repo_lst_obj = ReposList.GetRootAsReposList(buf, 0)
# print monster
repo_obj = repo_lst_obj.Repos(0)
name = repo_obj.FullName()
ed_time = datetime.now()
duration = ed_time - st_time
print name
print "duration of flatbuff::", duration.total_seconds() * 1000
#===================================================
st_timej = datetime.now()
with open('scm.json') as ldroi_json:
ldroi = json.load(ldroi_json)
full_name = ldroi["repos"][0]["full_name"]
print full_name
ed_timej = datetime.now()
duration_json = ed_timej - st_timej
print "duration of JSON::", duration_json.total_seconds() * 1000
<file_sep>/microblog_docker/requirements.txt
flask == 0.12.2
redis == 3.2.1<file_sep>/Bsig_app/bsig_optimize/signalreader.py
# __all__ = ['SignalReader', 'SignalReaderException']
# - import Python modules ---------------------------------------------------------------------------------------------
from numpy import inf, array
from os import path as opath, SEEK_END, SEEK_CUR
from struct import unpack
from zlib import decompress
from csv import Error, reader
from re import match
from sys import _getframe
# - import STK modules ------------------------------------------------------------------------------------------------
# from error import StkError
# from helper import deprecation
ERR_OK = 0
"""Code for No Error"""
ERR_UNSPECIFIED = 1
"""Code for an unknown Error"""
# - defines -----------------------------------------------------------------------------------------------------------
SIG_NAME = 'SignalName'
SIG_TYPE = 'SignalType'
SIG_ARRAYLEN = 'ArrayLength'
SIG_OFFSET = 'Offsets'
SIG_SAMPLES = 'SampleCount'
# - classes -----------------------------------------------------------------------------------------------------------
class StkError(Exception):
"""
**Base STK exception class**,
where all other Exceptions from the stk sub-packages must be derived from.
Frame number is set to 2 thereof.
- Code for No Error: ERR_OK
- Code for an unknown / unspecified Error: ERR_UNSPECIFIED
"""
ERR_OK = ERR_OK
"""Code for No Error"""
ERR_UNSPECIFIED = ERR_UNSPECIFIED
"""Code for an unknown Error"""
def __init__(self, msg, errno=ERR_UNSPECIFIED, dpth=2):
"""
retrieve some additional information
:param msg: message to announce
:type msg: str
:param errno: related error number
:type errno: int
:param dpth: starting frame depth for error trace, increase by 1 for each subclass level of StkError
:type dpth: int
"""
Exception.__init__(self, msg)
frame = _getframe(dpth)
self._errno = errno
self._error = "'%s' (%d): %s (line %d) attr: %s" \
% (msg, errno, opath.basename(frame.f_code.co_filename), frame.f_lineno, frame.f_code.co_name)
def __str__(self):
"""
:return: our own string representation
:rtype: str
"""
return self._error
@property
def error(self):
"""
:return: error number of exception
:rtype: int
"""
return self._errno
class SignalReaderException(StkError):
"""general exception for SignalReader class"""
def __init__(self, msg):
"""derived from std error"""
delim = "=" * (len(msg) + 7) + "\n"
StkError.__init__(self, "\n%sERROR: %s\n%s" % (delim, msg, delim))
class CsvReader(object): # pylint: disable=R0924,R0902
"""
**Delimited reader class**
internal class used by SignalReader in case of reading csv type files
use class `SignalReader` to read csv files
"""
def __init__(self, filepath, **kwargs):
"""open / init cvs file
"""
self._signal_names = []
self._signal_values = {}
self._signal_type = {}
self._all_types = {long: 0, float: 1, str: 2}
self._delimiter = kwargs.pop('delim', ';')
if self._delimiter not in (';', ',', '\t', ' '):
self._delimiter = ';'
self._skip_lines = kwargs.pop('skip_lines', 0)
self._skip_data_lines = kwargs.pop('skip_data_lines', 0)
self._scan_type = kwargs.pop('scan_type', 'no_prefetch').lower()
if self._scan_type not in ('prefetch', 'no_prefetch'):
self._scan_type = 'prefetch'
self._scan_opt = kwargs.pop('scan_opt', 'scan_auto').lower()
if self._scan_opt not in ('scan_auto', 'scan_raw'):
# self._scan_opt = self._match_type(self._scan_opt)
if self._scan_opt == 'long':
self._scan_opt = type(long(0))
elif self._scan_opt == 'float':
self._scan_opt = type(float(0.0))
# for opt in kwargs:
# deprecation('unused SignalReader option: ' + opt)
self._selfopen = None
if not hasattr(filepath, 'read'):
self._fp = open(filepath, "r")
self._selfopen = True
self._file_path = filepath
else:
self._fp = filepath
self._selfopen = False
self._file_path = filepath.name
# read file header
try:
self._csv = reader(self._fp, delimiter=self._delimiter)
for _ in xrange(self._skip_lines):
self._csv.next()
# get all signals name
self._signal_names = self._csv.next()
if self._signal_names.count('') > 0:
self._signal_names.remove('')
for idx in xrange(len(self._signal_names)):
self._signal_names[idx] = self._signal_names[idx].strip()
self._signal_values[idx] = []
if self._scan_type == 'prefetch':
self._read_signals_values()
except:
self.close()
raise
def close(self):
"""close the file
"""
if self._fp is not None:
if self._selfopen:
self._fp.close()
self._fp = None
self._signal_names = None
self._signal_values = None
def __len__(self):
"""Function returns the number of signals in the binary file.
:return: The number of signals in the binary file.
"""
return len(self._signal_names)
def __str__(self):
"""returns file info"""
return "<dlm: '%s', signals: %d>" % (self._fp.name, len(self))
def siglen(self, _):
"""provides length of a signal, as csv's are of same length we do it the easy way
:param: signal name (to be compatible to SignalReader method, not used here)
:return: length of signal in file
:rtype: int
"""
if len(self._signal_values[0]) == 0:
self._read_signals_values(self._signal_names[0])
return len(self._signal_values[0])
@property
def signal_names(self):
"""returns names of all signals
:return: all signal names in file
:rtype: list
"""
return self._signal_names
def signal(self, signal, offset=0, count=0):
"""returns the values of a signal given as input.
When signal_name doesn't exist it returns 'None'
:param signal: the name of the signal
:param offset: signal offset to start
:param count: number of signal items to return
:return: value of named signal or None
"""
if type(signal) in (tuple, list):
return [self.signal(s) for s in signal]
self._read_signals_values(self._signal_names[signal] if type(signal) == int else signal)
if type(signal) == str:
signal = self._signal_names.index(signal)
# todo: maybe we should convert already when reading...
try:
vals = array(self._signal_values[signal], dtype=[tt for tt, it in self._all_types.items()
if it == self._signal_type[signal]][0])
except KeyError:
vals = array(self._signal_values[signal], dtype=float)
if offset + count == 0:
return vals
else:
return vals[offset:offset + count]
def _read_signals_values(self, signals_list=None): # pylint: disable=R0912,R0915
"""
Reads signal values from a simulation file - csv format.
This function reads a list of signal given as input.
When signals_list is 'None' all signal will be read
:param signals_list: the list of the signals
:return: dictionary with extracted signals, empty {} in case of errors
"""
if signals_list is None:
signals_list = self._signal_names
if type(signals_list) == str:
signals_list = [signals_list]
# prevent loading already loaded ones
removes = [sig for sig in signals_list if len(self._signal_values[self._signal_names.index(sig)]) > 0]
for rem in removes:
signals_list.remove(rem)
if len(signals_list) == 0:
return
for signal in signals_list:
if signal not in self._signal_type:
if self._scan_opt == 'scan_raw':
self._signal_type[self._signal_names.index(signal)] = 2
else:
self._signal_type[self._signal_names.index(signal)] = 0
self._fp.seek(0)
# if skip_lines constructor parameter is not specified
for _ in xrange(self._skip_lines + 1 + self._skip_data_lines):
self._csv.next()
if self._scan_opt == 'scan_raw':
try:
for row in self._csv:
for signal in signals_list:
try:
idx = self._signal_names.index(signal)
self._signal_values[idx].append(str(row[idx]))
except IndexError:
pass
# del row
except Error as ex:
raise SignalReaderException('file %s, line %d: %s' % (self._file_path, self._csv.line_num, ex))
elif self._scan_opt == 'scan_auto':
try:
for row in self._csv:
for signal in signals_list:
idx = self._signal_names.index(signal)
try:
if match(r"^(\d+)$", row[idx].lstrip()) is not None:
val = long(row[idx])
elif(match(r"[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?\s*\Z",
row[idx].lstrip()) is not None):
val = float(row[idx])
else:
val = str(row[idx])
if type(val) == str:
if match(r"[+]?1(\.)[#][Ii][Nn]", val.lstrip()) is not None:
val = inf
elif match(r"-1(\.)[#][Ii][Nn]", val.lstrip()) is not None:
val = -inf
self._signal_values[idx].append(val)
self._signal_type[idx] = max(self._all_types[type(val)], self._signal_type[idx])
except:
self._signal_type[idx] = type(float)
# del row
except Error as ex:
raise SignalReaderException('file %s, line %d: %s' % (self._file_path, self._csv.line_num, ex))
else:
try:
for row in self._csv:
for signal in signals_list:
idx = self._signal_names.index(signal)
self._signal_values[idx].append(self._scan_opt(row[idx]))
except Error as ex:
raise SignalReaderException('file %s, line %d: %s' % (self._file_path, self._csv.line_num, ex))
class BsigReader(object): # pylint: disable=R0902,R0924
"""bsig reader class
internal class used by SignalReader to read binary signal files (type bsig2 and bsig3)
use class `SignalReader` to read files
"""
def __init__(self, fp, **kw): # pylint: disable=R0912,R0915
"""set default values
:param fp: file to use, can be a file pointer to an already open file or a name of file
:keyword use_numpy: use numpy for signal values, default: True
"""
self._arr_frmt = {0x0008: 'B', 0x8008: 'b', 0x0010: 'H', 0x8010: 'h', 0x0020: 'L', 0x8020: 'l', 0x0040: 'Q',
0x8040: 'q', 0x9010: 'f', 0x9020: 'd'}
self._sig_frmt = {'c': 1, 'b': 1, 'B': 1, 'h': 2, 'H': 2, 'I': 4, 'l': 4, 'L': 4, 'q': 8, 'Q': 8,
'f': 4, 'd': 8}
file_header = 24
self._fp = fp
self._npusage = kw.pop('use_numpy', True)
self._name_sense = kw.pop('sensitive', True)
self._selfopen = None
try:
if hasattr(self._fp, 'read'):
self._fp.seek(0)
self._selfopen = False
else:
# noinspection PyTypeChecker
self._fp = open(self._fp, "rb")
self._selfopen = True
# read global header
# print("self._read_sig::", self._read_sig('c' * 4))
if self._read_sig('c' * 4) != ('B', 'S', 'I', 'G'):
raise SignalReaderException("given file is not of type BSIG!")
version = self._read_sig('B' * 3)
if version[0] not in (2, 3): # we support version 2 and 3 by now
raise SignalReaderException("unsupported version: %d.%d.%d, supporting only V2 & V3!" % version)
self._version = version[0]
self._signal_data = []
self._offstype = 'I' if self._version == 2 else 'Q'
# get total size of file
self._fp.seek(0, SEEK_END)
self._file_size = self._fp.tell()
self._fp.seek(-file_header, SEEK_CUR)
# read file header
signal_count, self._block_size, self._hdr_size, offset_size = self._read_sig('IIII')
self._read_sig('B' * 3) # internal version is unused, read over
self._compression = self._read_sig('B')[0] == 1
if self._read_sig('c' * 4) != ('B', 'I', 'N', '\x00'): # bin signature
raise SignalReaderException("BSIG signature wrong!")
# read signal description
self._fp.seek(self._file_size - file_header - self._hdr_size) # = self._hdr_offset
for _ in xrange(signal_count):
sig_name_len = self._read_sig('H')[0]
signal_name = "".join(self._read_sig('c' * sig_name_len))
# print("sig_name_len ::", signal_name)
array_len, stype = self._read_sig('II')
self._signal_data.append({SIG_NAME: signal_name, SIG_TYPE: stype, SIG_ARRAYLEN: array_len})
# read offsets data
self._fp.seek(self._file_size - file_header - self._hdr_size - offset_size)
for sig in self._signal_data:
offset_count, sig[SIG_SAMPLES] = self._read_sig('II')
sig[SIG_OFFSET] = self._read_sig(self._offstype * offset_count)
except SignalReaderException:
self.close()
raise
except:
self.close()
raise SignalReaderException("Error while reading signal information, corruption of data?")
def close(self):
"""close signal file
"""
if self._fp is not None:
try:
if self._selfopen:
self._fp.close()
self._fp = None
self._signal_data = None
except:
raise SignalReaderException("An error occurred while closing the file.")
def __len__(self):
"""Function returns the number of signals in the binary file.
:return: number of signals in the binary file.
"""
return len(self._signal_data)
def __str__(self):
"""returns file info"""
return "<bsig%d: '%s', signals: %d>" % (self._version, self._fp.name, len(self))
def siglen(self, signal):
"""provides length of a signal, as csv's are of same length we do it the easy way
:param signal: name of signal
:return: length of signal
:rtype: int
"""
if signal is None:
return self._signal_data[0][SIG_SAMPLES]
if self._name_sense:
sigdet = next((s for s in self._signal_data if s[SIG_NAME] == signal), None)
else:
sigdet = next((s for s in self._signal_data if s[SIG_NAME].lower() == signal.lower()), None)
if sigdet is None:
raise SignalReaderException("no signal by that name found: %s" % str(signal))
return sigdet[SIG_SAMPLES]
def signal(self, signal, offset=None, count=None): # pylint: disable=R0912
"""Function returns the data for the signal with the specified index.
:param signal: index / name of signal or list of the signals
:param offset: data offset of signal
:param count: length of data
:return: signal data as an array (default) or list as defined during reader initialisation
:rtype: array or list
"""
# check for input argument validity
if type(signal) in (tuple, list):
return [self.signal(s) for s in signal]
elif type(signal) == int and 0 <= signal < len(self._signal_data):
sigdet = self._signal_data[signal]
else:
if self._name_sense:
sigdet = next((s for s in self._signal_data if s[SIG_NAME] == signal), None)
else:
sigdet = next((s for s in self._signal_data if s[SIG_NAME].lower() == signal.lower()), None)
if sigdet is None:
# raise SignalReaderException("signal not found: %s" % signal)
print "signal not found: %s" % signal
return []
# align offset and count, count is initially the length, but we use it as stop point and offset as start point
if offset is None:
offset = 0
elif offset < 0:
offset = sigdet[SIG_SAMPLES] + offset
if count is None:
count = sigdet[SIG_SAMPLES]
elif count < 0 or offset + count > sigdet[SIG_SAMPLES]:
raise SignalReaderException("offset / count for signal %s is out of range: %s / %s" %
(signal, str(offset), str(count)))
# print "offset / count for signal %s is out of range: %s / %s" %(signal, str(offset), str(count))
# return []
else:
count += offset
frmt = self._arr_frmt[sigdet[SIG_TYPE]] # data format
dlen = self._sig_frmt[frmt] # length of one data point
blkl = self._block_size / dlen # real block length
alen = sigdet[SIG_ARRAYLEN] # array length of signal
sig = [] # extracted signal
# increment with array length
offset *= alen
count *= alen
# precalc reduced offsets
sigoffs = list(sigdet[SIG_OFFSET])
while count < (len(sigoffs) - 1) * blkl: # cut last offsets
sigoffs.pop(len(sigoffs) - 1)
while offset >= blkl: # cut first offsets
sigoffs.pop(0)
offset -= blkl # reduce starting point
count -= blkl # reduce stop point
# without compression we could even cut down more reading,
# but I'll leave it for now as it makes more if then else
# read data blocks
for offs in sigoffs:
self._fp.seek(offs)
if self._compression:
data = self._fp.read(self._read_sig('I')[0])
data = decompress(data)
else:
data = self._fp.read(self._block_size)
data = unpack(frmt * (len(data) / dlen), data)
sig.extend(data)
if self._npusage:
if alen == 1:
return array(sig[offset:count], dtype=frmt)
return array(sig[offset:count], dtype=frmt).reshape(((count - offset) / alen, alen))
else:
if alen == 1:
return sig[offset:count]
return [sig[i:i + alen] for i in xrange(offset, count, alen)]
@property
def signal_names(self):
"""returns names of all signals with the specified index.
:return: all signal names in file
:rtype: list
"""
return [sig[SIG_NAME] for sig in self._signal_data]
def _read_sig(self, stype):
"""read signal of given type
"""
try:
# print("stype[0]] * len(stype)::", stype[0], len(stype))
return unpack(stype, self._fp.read(self._sig_frmt[stype[0]] * len(stype)))
except:
raise SignalReaderException("An error occured while reading binary data.")
class SignalReader(object):
"""
**MAIN Class for Signal File Read.** (\\*.bsig (aka \\*.bin), \\*.csv)
open, step through, read signals and close a signal file, provide list of signal names
by default the **values are returned as numpy array**, see `__init__` how to configure for python lists
for csv files several options (like delimiter) are supported, see `__init__` for more details
even if the usage looks like calling a dict *a SignalReader instance is no dict:*
- when getting a signal using ``sr['my_signal_name']`` just that signal is read from the file;
- adding or deleting signals is not possible, it's just a reader;
- there are no dict functions like d.keys(), d.values(), d.get() etc.
supported functions (see also Examples below):
-with open and integrated close for a signal file
-get values of signal with name or index: ``sr['my_name'], sr[2]``
-len number of signals: ``len(sr)``
-in check if signal with name is available: ``if 'my_sig' in sr:``
-for loop over all signals with name and values: ``for n, v in sr:``
-signal_names list of all signal names (like dict.keys()): ``sr.signal_names``
usage (example)
---------------
.. python::
# read csv files:
reader = SignalReader(<file.csv>,
'delim'=<delimiter>,
'scan_type'=<'prefetch','no_prefetch'>,
'scan_opt'=<'scan_auto','scan_raw','float',...>,
'skip_lines'=<number_of_header_lines_to_skip>,
'skip_data_lines'=<number_of_data_lines_to_skip>)
# read bsig files (version 2 or 3)
reader = SignalReader(<file.bsig>)
# check if signal with name is stored in file:
if "MTS.Package.TimeStamp" not in reader:
print("TimeStamp missing in signal file")
Examples:
.. python::
import numpy as np
from stk.io.signalreader import SignalReader, SignalReaderException
# EXAMPLE 1
sr = SignalReader('file_hla_xyz.txt', delim ='\t', scan_type='NO_PREFETCH')
# get values
read_values = sr['lux_R2G']
sr.close()
# EXAMPLE 2
sr = SignalReader('file_sla_xyz.csv',delim =',',skip_lines=8)
# read only signal 'timestamp'
values = sr['timestamp'] # gets the timestamp signal
values = sr[0] # gets the signal by index 0
sr.close()
# EXAMPLE 3
with SignalReader('file_hla_xyz.bsig') as sr:
signals = sr[['Time stamp','Cycle counter']] # retrieves a list of both signals --> [[<sig1>], [<sig2>]]
# EXAMPLE 4
with SignalReader('file_hla_xyz.bsig') as sr:
signals = sr['Time stamp':50:250] # retrieves 200 samples of time stamp signal from offset 50 onwards
# EXAMPLE 5
with SignalReader('file_fct.bsig') as sr:
for n, v in sr: # iterate over names and signals
print("%s: %d" % (n, v.size))
with SignalReader('file_hla_xyz.bsig') as sr:
signals = sr['Time stamp':50:250] # retrieves 200 samples of time stamp signal from offset 50 onwards
# EXAMPLE 6
instance_ARS = SignalReader('file_ars_xyz.csv', delim =';',scan_opt = 'float')
...
instance_ARS.close()
import numpy as np
from stk.io.signalreader import SignalReader, SignalReaderException
# EXAMPLE 1
sr = SignalReader('file_hla_xyz.txt', delim ='\t', scan_type='NO_PREFETCH')
# get values
read_values = sr['lux_R2G']
sr.close()
# EXAMPLE 2
sr = SignalReader('file_sla_xyz.csv',delim =',',skip_lines=8)
# read only signal 'timestamp'
values = sr['timestamp'] # gets the timestamp signal
values = sr[0] # gets the signal by index 0
sr.close()
# EXAMPLE 3
with SignalReader('file_hla_xyz.bsig') as sr:
signals = sr[['Time stamp','Cycle counter']] # retrieves a list of both signals --> [[<sig1>], [<sig2>]]
# EXAMPLE 4
with SignalReader('file_hla_xyz.bsig') as sr:
signals = sr['Time stamp':50:250] # retrieves 200 samples of time stamp signal from offset 50 onwards
# EXAMPLE 5
instance_ARS = SignalReader('file_ars_xyz.csv', delim =';',scan_opt = 'float')
...
instance_ARS.close()
"""
def __init__(self, filename, **kw):
"""open the binary file by its name, supported formats: bsig 2, 3, csv
:param filename: path/to/file.name
*following parameter can be used when intending to open e.g. a bsig file:*
:keyword use_numpy: boolean value that indicates wether using numpy arrays for signal values, default: True
:keyword sensitive: boolean value that indicates wether to treat signal names case sensitive, default: True
*following parameter can be used when intending to open e.g. a csv file:*
:keyword delim: delimiter char for columns
:keyword scan_type: can be 'no_prefetch' or 'prefetch' to read in data at init
:keyword scan_opt: 'can be 'scan_auto', 'scan_raw' or e.g. 'float', 'long' or 'str'
:keyword scip_lines: how many lines should be scripped / ignored reading in at start of file
:keyword scip_data_lines: how many lines of data should be scripped reading in at start
:keyword type: type of file can set explicitly, set to 'bsig' will force it to be a bsig
"""
self._fp = filename
if opath.splitext(self._fp.name if hasattr(self._fp, 'read')
else filename)[1].lower() in ('.bsig', '.bin', '.tstp') or kw.pop('type', None) == 'bsig':
self._reader = BsigReader(self._fp, **kw)
self._type = "bsig"
else:
self._reader = CsvReader(self._fp, **kw)
self._type = "dlm"
self._signal_names = self._reader.signal_names
self._iter_idx = 0
def __enter__(self):
"""being able to use with statement"""
return self
def __exit__(self, *_):
"""close down file"""
self.close()
def close(self):
"""close file"""
self._reader.close()
def __str__(self):
"""returns the type and number of signals"""
return str(self._reader)
def __len__(self):
"""return number of signals from reader"""
return len(self._reader)
def signal_length(self, signal=None):
"""length of a signal
:param signal: name of signal length should be returned
:return: signal length
:rtype: int
"""
return self._reader.siglen(signal)
def __iter__(self):
"""start iterating through signals"""
self._iter_idx = 0
return self
def next(self):
"""next signal item to catch and return"""
if self._iter_idx >= len(self._signal_names):
raise StopIteration
else:
self._iter_idx += 1
return self._signal_names[self._iter_idx - 1], self[self._iter_idx - 1]
def __contains__(self, name):
"""checks if signal name is stored in SignalReader
:param name: signal name to check
:return: bool
"""
return name in self._signal_names
def __getitem__(self, signal):
"""provide signal by name or index,
if index is a slice use start as index,
stop as offset and step as count
:param signal: signal name or index or sliced index
:type signal: str, int, tuple/list
:return: signal with type as defined in reader initiation
:rtype: array or list
"""
# [Offset:Offset + SampleCount]
try:
if type(signal) in (int, str):
return self._reader.signal(signal)
elif type(signal) in (tuple, list):
if set(signal).issubset(self._signal_names):
return self._reader.signal(signal)
else:
return self._reader.signal(signal[0], signal[1], signal[2])
elif type(signal) == slice: # not nice, but no other strange construct needed
return self._reader.signal(signal.start, signal.stop, signal.step)
else:
raise IndexError
except (IndexError, SignalReaderException):
raise
except:
raise SignalReaderException("Data corruption inside signal file, unable to read signal '{}'!"
.format(signal))
@property
def signal_names(self):
"""list of all signal names
:return: all signal names in file
:rtype: list
"""
return self._signal_names
<file_sep>/Neo4j_py/graph_db_trace/rec_summary_events_rc.py
from PyQt4.QtGui import *
from PyQt4 import QtGui, QtCore
from rec_summary_ui import Ui_MainWindow
from neo4jrestclient.client import GraphDatabase
from flexible_search import TFIDExtractor
from rigid_search import KeyWordMatching
from export_rec_sumry import ExportSummary
# import neo4j
# print neo4j.__version__
IP_ADDRESS = '10.205.247.160'
# IP_ADDRESS = '10.223.242.11'
LDSS_KEYWORDS = ['Luxemburg', 'MFC400', 'SR', 'DEV', 'Luxemburg', 'Rain', 'Motorway',
'Day', 'EVA', 'USA', 'Country_Road', 'Night', 'Highway', 'Great_Britain', 'Dusk', ]
OBJ_KEYWORDS = ['Danger_Animal_Crossing_from_Right', 'Danger_Bend_Left', 'Danger_Exclamation_Mark',
'Danger_Exclamation_Mark_Yellow', 'Danger_Road_Works_Right', 'Danger_Road_Works_Right_Yellow',
'Danger_Small_Road_From_Left_45_Degree', 'Danger_Small_Road_From_Right_45_Degree',
'Danger_Small_Road_From_Right_45_Degree_Yellow', 'Danger_Splippery_Road',
'Danger_Traffic_Lights', 'Danger_Two_Bump', 'Danger_Two_Way_Traffic_Yellow',
'Dir_Down_Left', 'Dir_Down_Left_Right', 'Dir_Down_Right', 'Dir_Left', 'Dir_Right',
'Dir_Right_Ahead', 'Dir_Roundabout', 'Dir_Straight_Ahead', 'Do_Not_Enter', 'Duty_Station',
'General_End_Slash_80Deg', 'Give_Way', 'Motor_Way', 'Motor_Way_End_Green', 'No_Passing',
'No_Passing_Truck', 'Not_Readable', 'Other_Round_Sign', 'Other_Supplementary_Sign',
'Pedestrian_Crossing', 'Prohib_All', 'Prohib_Moped', 'Prohib_Motorbike', 'Prohib_Parking',
'Prohib_Pedestrian', 'Prohib_Stopping', 'Prohib_Truck', 'Speed_Limit_030', 'Speed_Limit_040',
'Speed_Limit_050', 'Speed_Limit_060', 'Speed_Limit_060_Inv', 'Speed_Limit_065', 'Speed_Limit_070',
'Speed_Limit_080', 'Speed_Limit_090', 'Speed_Limit_100', 'Speed_Limit_110', 'Speed_Limit_End_060_Slash_60Deg',
'Speed_Limit_End_110_Slash_80Deg', 'Stop', 'Suppl_Expalantion_Pic_SnowPlow',
'Suppl_Explanation_Pic_ArrowDownShort', 'Suppl_Explanation_Pic_ArrowUpShort', 'Suppl_Explanation_Pic_ArrowUpShort_Pic_ArrowDownShort',
'Suppl_Explanation_Pic_Truck_Pic_CarSide_Pic_TiltedLine', 'Suppl_Explanation_TexRegExp_1500m', 'Suppl_Explanation_TexRegExp_150m', 'Suppl_Explanation_TexRegExp_500m', 'Suppl_Explanation_TexRegExp_700m', 'Suppl_Restriction_Pic_CarSide', 'Suppl_Restriction_Pic_CloudBlackRain', 'Suppl_Restriction_Pic_SnowFlake_Pic_SnowFlake_Inv', 'Suppl_Restriction_Pic_TruckXXt', 'Suppl_Restriction_TexRegExp_0-24', 'Suppl_Restriction_TexRegExp_12t', 'Suppl_Restriction_TexRegExp_7,5t', 'Suppl_Restriction_Tex_ingalleria']
class RecSummaryEvents(QMainWindow, Ui_MainWindow):
def __init__(self):
super(QMainWindow, self).__init__()
# Initialize the Neo4J connections
# self.neo_obj = Neo4JConnection("bolt://localhost:7687", "neo4j", "tan_neo4j")
# self.neo_obj.create_nodes("nodes")
# self.neo_obj.close()
# "bolt://10.223.244.129:7687"
# self.neo4_driver = GraphDatabase.driver("bolt://10.223.244.129:7687:7687", auth=("neo4j", "tan_neo4j"))
# self.neo_session = self.neo4_driver.session()
self.neo_session = GraphDatabase("http://{}:7474/db/data/".format(IP_ADDRESS),
username="neo4j", password="<PASSWORD>")
# self.txn = Transaction(session=self.neo_session)
self.setupUi()
def setupUi(self):
# try:
super(RecSummaryEvents, self).setupUi(self)
self.pushButton_fetch.clicked.connect(self.fetch_rec_labels)
self.progressBar.setValue(0)
self.pushButton_interpret.clicked.connect(self.interpret_qry)
self.pushButton_export.clicked.connect(self.export_summary)
self.pushButton_export.setDisabled(True)
self.rec_lst_wdgt.itemClicked.connect(self.on_rec_click)
self.rec_lst_wdgt.itemDoubleClicked.connect(self.show_summary)
# self.lne_edit_loctn.setText(r"D:/")
# self.tool_btn_loctn.clicked.connect(self.open_directory)
bgColor = '#262626'
style = """QLineEdit{{ color: #EBEBEB; border: 0px solid black; background-color: {0}; color: #EBEBEB; font-size: 30px}}
QLineEdit:hover{{ border: 1px solid #ffa02f;}}""".format(
bgColor)
self.lineEdit_query.setStyleSheet(style)
# Fill LDSS elements in the combo box
for index, element in enumerate(LDSS_KEYWORDS):
self.chkbl_ComboBox.addItem(LDSS_KEYWORDS[index])
item = self.chkbl_ComboBox.model().item(index, 0)
item.setCheckState(QtCore.Qt.Unchecked)
self.chkbl_ComboBox.currentIndexChanged.connect(self.combo_txt)
# Fill the LDROI in the checkable combo
for index, element in enumerate(OBJ_KEYWORDS):
self.chkbl_objtype_ComboBox.addItem(OBJ_KEYWORDS[index])
item = self.chkbl_objtype_ComboBox.model().item(index, 0)
item.setCheckState(QtCore.Qt.Unchecked)
self.chkbl_objtype_ComboBox.currentIndexChanged.connect(self.combo_txt_objtype)
def show_summary(self, item):
self.lineEdit_recname.setText(item.text())
self.generate_summary()
def combo_txt_objtype(self, event):
sel_itm = self.chkbl_objtype_ComboBox.itemText(event)
# print("sel_itm :: ", sel_itm)
self.lineEdit_query.setText(str(self.lineEdit_query.text()) + sel_itm + " ")
def combo_txt(self, event):
sel_itm = self.chkbl_ComboBox.itemText(event)
# print("sel_itm :: ", sel_itm)
self.lineEdit_query.setText(str(self.lineEdit_query.text()) + sel_itm + " ")
def open_directory(self):
folder_loc = QFileDialog.getExistingDirectory(None, "Please select a Directory", directory="D:/")
print("folder_loc :: ", folder_loc)
self.lne_edit_loctn.setText(str(folder_loc))
def on_rec_click(self, item):
# print "item :: ", item.text()
self.lineEdit_recname.setText(item.text())
def export_summary(self):
rec_names_lst = []
for index in range(self.rec_lst_wdgt.count()):
rec_names_lst.append(self.rec_lst_wdgt.item(index).text())
print("rec_names_lst :: ", rec_names_lst)
exp_smry_obj = ExportSummary(rec_names_lst)
self.progressBar.setValue(20)
# rec_names_lst = exp_smry_obj.get_recnames()
self.progressBar.setValue(60)
# exp_smry_obj.generate_summry(rec_names_lst)
self.progressBar.setValue(100)
return QMessageBox.information(self, "Information",
"Exported summaries for the recordings listed",
QtGui.QMessageBox.Ok)
def generate_summary(self):
# Continuous_2011.07.04_at_14.37.07.rec
self.progressBar.setValue(0)
self.recname = self.lineEdit_recname.text()
print("self.recname :>> ", self.recname)
if self.recname != "":
self.progressBar.setValue(50)
neo_qry = ''' MATCH (CommonData)<-[cd:cd]-(RecordingName)-[c:c]->(Country)-
[rt:rt]->(RoadType)-
[w:w]->(WeatherCondition)-
[lc:lc]->(LightCondition)-
[ob:ob]->(ObjectType)
WHERE RecordingName.name = '{}'
RETURN RecordingName.name as RecName, Country.name as Country, RoadType.name as RoadType,
WeatherCondition.name as WeatherCondition, LightCondition.name as LightCondition, CommonData.project as Project,
CommonData.function as Function, CommonData.department as Department, ObjectType.name as Objects '''.format(self.recname)
# with self.neo_session.begin_transaction() as tx:
result = self.neo_session.query(q=neo_qry, data_contents=True)
rows = result.rows
columns = result.columns
print("rows::", rows)
print("columns::", columns)
self.progressBar.setValue(75)
# print "an :: ", self.an.values()[0][0]
# self.lineEdit_recname.setText(str(self.an.values()))
# print "self.an.data() :: ", self.an.data()
if rows is not None:
for item in rows:
dt_lst = [dict(zip(columns, item))]
print("dt_lst :: ", dt_lst)
self.summ_txt_edt.clear()
sumry_tmplt = self.create_summary(dt_lst)
if dt_lst:
self.summ_txt_edt.setText(str(sumry_tmplt))
else:
self.summ_txt_edt.setText("No data found...")
else:
self.summ_txt_edt.setText("No data found...")
# self.rec_lst_wdgt.insertItem(0, "No data found...")
self.progressBar.setValue(100)
# MainWindow.lineEdit_recname.setText(self.an.values()[0][0])
def create_summary(self, result_lst):
res_dict = result_lst[0]
res_dict = {str(k): ([str(e) for e in v] if type(v) is list else str(v))
for k, v in res_dict.items()}
updated_dict = {}
for ech_key, ech_val in res_dict.items():
if type(ech_val) is list:
updated_dict["{}_num".format(ech_key)] = len(ech_val)
res_dict.update(updated_dict)
print("res_dict :: ", res_dict)
SUMMARY_TEMPLATE = '''The recording <b>{RecName}</b> has labels for <b>{Project} {Function}</b>
for <b>{Department}</b> which has observations of <b>{Country_num}</b> Countries <b>{Country}</b>
driven in <b>{RoadType_num}</b> road types <b>{RoadType}</b> under <b>{WeatherCondition_num}</b>
weather conditions <b>{WeatherCondition}</b> with <b>{LightCondition_num}</b>
Light Conditions <b>{LightCondition}</b> having <b>{Objects_num}</b> Objects <b>{Objects}</b>.
'''.format(**res_dict)
return SUMMARY_TEMPLATE
def fetch_rec_labels(self):
self.generate_summary()
def interpret_qry(self):
self.rec_lst_wdgt.clear()
qry_input = str(self.lineEdit_query.text())
self.progressBar.setValue(10)
if qry_input == '':
self.textEdt_res.setText("Nothing to query")
else:
# Key word matching
# key_match_obj = KeyWordMatching(qry_input)
# self.progressBar.setValue(40)
# op = key_match_obj.interpret_the_query()
# TFID Extractor
print(">>>> ", self.rgd_chk_box.checkState())
if self.rgd_chk_box.checkState() == 0:
tfid_obj = TFIDExtractor(query=qry_input)
print("tfid_obj :: ", tfid_obj)
rec_lst = tfid_obj.get_rec_details()
print("rec_lst ::", rec_lst)
else:
# Rigid search
kwd_match_obj = KeyWordMatching(qry=qry_input)
rec_lst = list(kwd_match_obj.match_all())
# rec_lst = []
if rec_lst:
self.rec_lst_wdgt.insertItems(0, rec_lst)
self.pushButton_export.setDisabled(False)
else:
self.rec_lst_wdgt.insertItem(0, "No recording..")
self.pushButton_export.setDisabled(True)
self.progressBar.setValue(90)
self.progressBar.setValue(100)
class Neo4JConnection(object):
neo_qry = ''' MATCH (RecName)-[c:c]->(Country) RETURN RecName.Name, Country.Name '''
NEO_TRACE = []
def __init__(self, uri, user, password):
self.neo4_driver = GraphDatabase.driver(uri, auth=(user, password))
self.neo_session = self.neo4_driver.session()
# self.txn = Transaction(session=self.neo_session)
self.exec_qry()
# self.create_nodes("Nodes")
def close(self):
self.neo4_driver.close()
def exec_qry(self):
with self.neo_session.begin_transaction() as tx:
self.an = tx.run(Neo4JConnection.neo_qry)
print("an :: ", self.an.values()[0][0])
MainWindow.lineEdit_recname.setText(self.an.values()[0][0])
def create_nodes(self, message):
# with self.neo4_driver.session() as session:
written_data = self.neo_session.write_transaction(self._create_and_return_data, message)
# print "written_data :: ", written_data
return written_data
# @staticmethod
def _create_and_return_data(self, tx, message):
# print "tx :: ", tx
self.result = tx.run(Neo4JConnection.neo_qry,
message=message)
# print "result :: ", self.result.values(), type(self.result.values())
# if result.single() is not None:
# print "Neo4JConnection.NEO_TRACE :: ", Neo4JConnection.NEO_TRACE
# vc = self.result.values()[0]
# print "str(self.result.values()) ::>> ", vc
# for ech_itm in self.result.values():
# MainWindow.textBrowser.setText(str(ech_itm))
# MainWindow.lineEdit_recname.setText(str(self.result.values()))
# return result.values()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
# MainWindow = QtGui.QMainWindow()
MainWindow = RecSummaryEvents()
# ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
<file_sep>/Bsig_app/bsig_optimize/signal_loader.py
"""
signal_loader.py
----------------
Used to load and convert signals or block of signals.
Arguments to class initialization look like this::
vdy={'prefix': 'SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic',
'signals': [{'name': '.Lateral.Curve.Curve', 'port': 'Curve'},
{'name': '.Longitudinal.MotVar.Velocity', 'port': 'VehicleSpeed'},
{'name': '.Longitudinal.MotVar.Accel', 'port': 'VehicleAccelXObjSync'},
{'name': '.Lateral.YawRate.YawRate', 'port': 'VehicleYawRateObjSync'}
]
}
whereas prefix will prepend all names from list of signals (default: ''),
and `conv` is intended to be the conversation function.
This function is called with list of extracted signals, default function passes through all signals
and returns them.
Once you use `$` marker inside first signalname, all signals are treated like a block. Iteration will
then go along all found indices found. If you want to use less, you need to keep track outside, e.g.
with your own counter.
**example 1**
-------------
read out simple list of signals::
sl = SignalLoader(r'D:\tmp\Continuous_2015.04.22_at_12.15.53.bsig',
fixed={'prefix': 'MTS.Package.',
'signals': ['TimeStamp', 'CycleCount'],
'conv': lambda s: s}, # default
ars={'signals': ['ARS4xx Device.AlgoVehCycle.VehDyn.Longitudinal.MotVar.Velocity',
'MTS.Package.TimeStamp']})
for i in sl('fixed'):
print(i)
print("do we have 'var': %s" % ('var' in sl)) # prints: .... False as only `fixed` and `ars` was defined
**example 2**
-------------
block readout::
def sum_up(sigs):
res = sigs[0]
for i in xrange(1, len(sigs)):
res += sigs[i]
return res
sl = SignalLoader(r'D:\tmp\Snapshot_2014.10.15_at_19.40.34.bsig',
fct={'prefix': 'SIM VFB.FCTSensor.',
'signals': ['CDInternalObjInfo.Obj[$].TTC',
'CDInternalObjInfo.Obj[$].TTC2',
'CDInternalObjInfo.Obj[$].TTC3'],
'conv': sum_up})
cnt = 0
for sig in sl('fct'):
print("%d: %s" % (cnt, sig))
if cnt >= 2: # just stop reading / converting as we only need 2 of those blocks
break
cnt += 1
"""
# - STK imports -------------------------------------------------------------------------------------------------------
from signalreader import SignalReader
# - defines -----------------------------------------------------------------------------------------------------------
PREFIX = "prefix"
SIGNALS = "signals"
CONV = "conv"
ITER = "iter"
IARGS = "iargs"
# - classes -----------------------------------------------------------------------------------------------------------
class SignalLoader(object):
"""loads signals / objects from given binary file (bsig)
"""
def __init__(self, bsig, **kwargs):
"""loader / converter for signals out of a bsig / csv (SignalReader class is used).
be aware that putting down block size to 4kb inside MTS signal exporter could speed up SignalReader...
:param bsig: path / to / bsig or csv file
:type bsig: file | str
:param kwargs: list of arguments described here, all others are saved to xargs
:keyword prefix: signal prefix name to be prepended to all signal names
:type prefix: str
:keyword signals: list of signal names
:type signals: list[str]
:keyword conv: conversation function taking one argument being the signal (numpy array)
"""
self._bsig = SignalReader(bsig)
self._idx = 0
self._imx = 0
self._obj_mode = False
self._idem = None
self._args = kwargs
for arg, val in self._args.iteritems():
if CONV not in val:
val[CONV] = lambda s: s
# will be called when iterator inits with self, returning if going via block mode and iter amount
if ITER not in val:
val[ITER] = {'func': self._dummy_iter, 'args': None}
pref = val.get(PREFIX, '')
# for sig in val[SIGNALS]:
# print ">> ", sig
# if sig['name'].startswith('.'):
# sig['name'] = pref + sig['name']
def __enter__(self):
"""with statement usage start"""
return self
def _dummy_iter(self, *_):
"""dummy iterator init, used by default to just load single signals
"""
return False, len(self._idem[SIGNALS])
def __len__(self):
"""get length of objects / signals"""
if self._imx == 0:
try:
self._obj_mode, self._imx = self._idem[ITER]['func'](self, self._idem[ITER]['args'])
except:
self._obj_mode, self._imx = False, 0
return self._imx
def __iter__(self):
"""start iterating through signal processing"""
self._idx, self._imx = 0, 0
len(self)
return self
def next(self):
"""next item to catch and return"""
if self._idem is None or self._idx >= self._imx:
raise StopIteration
if self._obj_mode:
obj = self._idem[CONV](self._idx, self._idem[SIGNALS])
else:
print "{{{{ ", self._idem[CONV](self._bsig[self._idem[SIGNALS][self._idx]])
obj = self._idem[CONV](self._bsig[self._idem[SIGNALS][self._idx]])
# obj = self._idem[CONV](self._bsig[self._idem[SIGNALS][self._idx]['name']])
self._idx += 1
return obj
def __call__(self, item):
"""making a lookalike function call, to take over item of what we want to iterate through actually,
the iterator for itself is quiet useless as no args can be given.
::
mp = MyProcessor()
for sig in sigldr('my_signal'):
mp.proc(sig)
print(mp.result())
:param item: named item to iterate over and extract that data
:returns: self to be able to iterate
"""
if item not in self._args:
raise KeyError
self._idem = self._args[item]
return self
def __getitem__(self, item):
"""let's take out that item from bsig as we have it actually...
:param item: named signal from SignalReader
:returns: raw / unconverted signal
"""
return self._bsig[item]
def __contains__(self, item):
"""do we have some item inside us?
:param item: the one to check
"""
return item in self._args
def __exit__(self, *_):
"""close down file (with support)"""
self.close()
def __del__(self):
"""in case someone forgot to call close"""
self.close()
def close(self):
"""close sig reader"""
if self._bsig is not None:
self._bsig.close()
self._bsig = None
<file_sep>/celery_rmq/celery_run.py
from celery import Celery
app = Celery('celery_rmq',
broker='amqp://guest:guest@localhost:5672/',
backend='rpc://',
include=['tasks'])
<file_sep>/H5_app/notes.txt
D:\Work\2018\code\Tensorflow_code\Protobuf_compilers\protoc3.5\bin\protoc -I=.\ --python_out=.\ AlgoInterface.proto
D:\Work\2018\code\Tensorflow_code\Protobuf_compilers\protoc3.2\protoc -I=.\ --cpp_out=.\ AlgoInterface.proto
D:\Work\2018\code\Tensorflow_code\Protobuf_compilers\protoc3.3\protoc -I=.\ --cpp_out=.\ AlgoInterface.proto
D:\Work\2018\code\Tensorflow_code\Protobuf_compilers\proto3.0.0\bin\protoc -I=.\ --cpp_out=.\ AlgoInterface.proto
D:\Work\2018\code\Tensorflow_code\Protobuf_compilers\protoc3.5\bin\protoc -I=.\ --cpp_out=.\ AlgoInterface.proto
pyinstaller hfl_data_publish.py --add-data topics.json;. --add-data _ecal_py_2_7_x86.pyd;.
<file_sep>/H5_app/hfl_test.py
import ecal
import AlgoInterface_pb2
import imageservice_pb2
import sys
ecal.initialize(sys.argv, "HFL data requestor")
hfl_publ_obj = ecal.publisher("Request_Image")
import time
time.sleep(2)
hfl_req_proto_obj = imageservice_pb2.ImageRequest()
def request_hfl_data():
# while ecal.ok():
# hfl_req_proto_obj.required_timestamp = 1504816617728550
hfl_req_proto_obj.image_index = 8 #1504816617788522
# hfl_req_proto_obj.hfl_file_name = "D:\\Work\\2018\\code\\LT5G\\HDF5_reader\\2017.09.07_at_20.37.57_camera-mi_1449.h5"
hfl_publ_obj.send(hfl_req_proto_obj.SerializeToString())
ecal.finalize()
request_hfl_data()
<file_sep>/PCD_generation/PCD_from_H5/create_pcd_frm_h5.py
import h5py
# import pypcd
from pypcd.pypcd import PointCloud
import numpy as np
def generate_sample_pcd():
fname = r'../2017.11.29_at_00.33.01_camera-mi_1449_TestPattern.h5'
h5_obj = h5py.File(fname, "r")
print ("h5_obj :: ", h5_obj)
tmstamp = h5_obj['/MTS/Package/TimeStamp']
print ("tmstamp :: ", tmstamp)
idx = 0
tmstamp1 = tmstamp[idx]
pcd_data = h5_obj['/HFL130/PCA/PCA_RESULT/pointcloud[457]']
print ("pcd_data >> ", pcd_data.keys())
# [u's16_x', u's16_y', u's16_z', u'u16_ampl']
pcd_x = h5_obj['/HFL130/PCA/PCA_RESULT/pointcloud[457]/s16_x'][idx]
pcd_y = h5_obj['/HFL130/PCA/PCA_RESULT/pointcloud[457]/s16_y'][idx]
pcd_z = h5_obj['/HFL130/PCA/PCA_RESULT/pointcloud[457]/s16_z'][idx]
print (">>: ", pcd_x/1.0, pcd_y/1.0, pcd_z/1.0)
# size=[4, 4, 4], ascii
dt = [[0.02886, 0.02886, 0.02886]]
arr_data = np.array(dt)
# print("length::", len(arr_data))
# arr_data = np.array([0.02886])
pc = PointCloud(pc_data=arr_data, metadata={'version': .5, 'fields': ['x', 'y', 'z'], 'type': ['F', 'F', 'F'], 'size': [4, 4, 4],
'count': [1, 1, 1], 'width': 1, 'height': 1, 'points': 1, 'data': 'ascii',
'viewpoint': [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]})
pc.save_pcd(fname='sample.pcd', compression=None)
def generate_pcd_frm_h5():
fname = r'../2017.11.29_at_00.33.01_camera-mi_1449_TestPattern.h5'
h5_obj = h5py.File(fname, "r")
print("h5_obj :: ", h5_obj)
tmstamp = h5_obj['/MTS/Package/TimeStamp']
# print("tmstamp :: ", tmstamp)
idx = 0
tmstamp1 = tmstamp[idx]
pcd_data_lst = h5_obj['/HFL130/PCA/PCA_RESULT']
# print("pcd_data_lst ::", pcd_data_lst, dir(pcd_data_lst))
# print(dir(pcd_data_lst.items()))
pcd_dt_lst = []
for name, evry_pntCld_member in pcd_data_lst.items():
# print("evry_pntCld_member>>", evry_pntCld_member)
# pcd_x = evry_pntCld_member
if isinstance(evry_pntCld_member, h5py.Group):
print("pcd_x::", name, evry_pntCld_member, type(evry_pntCld_member))
ordinate_lst = []
for pcd_infoname, evry_pntCld_info in evry_pntCld_member.items():
pointCloud_member_names = ['s16_x', 's16_y', 's16_z', 'u16_ampl']
if isinstance(evry_pntCld_info, h5py.Dataset):
# print("pcd_infoname::", pcd_infoname, evry_pntCld_info, type(evry_pntCld_info))
if pcd_infoname in pointCloud_member_names:
# Only if x,y and z co-ordinates exist
ordinate_values = evry_pntCld_info.value
# print("evry_pntCld_info ::", pcd_infoname, ordinate_values)
ordinate_lst.append(ordinate_values[idx]/1.0)
if ordinate_lst:
pcd_dt_lst.append(ordinate_lst)
arr_data = np.array(pcd_dt_lst)
# print(">{{", ordinate_lst)
print(">>", arr_data, len(arr_data))
pc = PointCloud(pc_data=arr_data,
metadata={'version': .5, 'fields': ['x', 'y', 'z', 'i'], 'type': ['F', 'F', 'F', 'F'], 'size': [4, 4, 4, 4],
'count': [1, 1, 1, 1], 'width': len(arr_data), 'height': 1, 'points': len(arr_data), 'data': 'ascii',
'viewpoint': [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]})
pc.save_pcd(fname='sample1.pcd', compression=None)
# break
# pcd_y = h5_obj['/HFL130/PCA/PCA_RESULT/pointcloud[457]/s16_y'][idx]
# pcd_z = h5_obj['/HFL130/PCA/PCA_RESULT/pointcloud[457]/s16_z'][idx]
if __name__ == '__main__':
generate_sample_pcd()
# generate_pcd_frm_h5()<file_sep>/PCD_generation/LT5_point_cloud_service/point_cloud_service.py
import ecal
import sys
import json
import os
import time
import h5py
import pointcloud_pb2
import common_pb2
from datetime import datetime
BEXIT = True
SERVICE_READINESS = True
with open('topics.json') as data_file:
json_data = json.load(data_file)
class H5ReaderSequence(object):
def __init__(self, fname):
self.reset(fname)
self.h5_obj = h5py.File(fname, "r")
self.pcl_dataset_dict = {}
self.h5_grp_lst = []
def reset(self, fname):
if not os.path.isfile(fname):
print("Error - H5 file not available: %s!" % fname)
sys.exit()
def print_groups(self, name, obj):
if isinstance(obj, h5py.Group):
self.h5_grp_lst.append(name)
def get_device_channel_name(self):
self.h5_obj.visititems(self.print_groups)
# print "self.h5_grp_lst :: ", self.h5_grp_lst
device_names_lst = [evry_chnl for evry_chnl in self.h5_grp_lst if '/' not in str(evry_chnl)]
# chnl_names_lst = [evry_chnl.split('/')[1] for evry_chnl in self.h5_grp_lst if '/' in str(evry_chnl)]
# print "chnl_names_lst ::: ", device_names_lst, chnl_names_lst
dvc_chnl_map = {}
for evry_dvc_name in device_names_lst:
chnl_lst = []
for evry_chnl in self.h5_grp_lst:
if '/' in str(evry_chnl) and evry_chnl.split('/')[0] == evry_dvc_name:
chnl_lst.append(evry_chnl.split('/')[1])
# print "evry_chnl :>>", evry_dvc_name, evry_chnl
# dvc_chnl_map[evry_dvc_name] = [evry_chnl]
dvc_chnl_map[evry_dvc_name] = chnl_lst
# print "dvc_chnl_map :: ", dvc_chnl_map
# chnl_name = str(self.h5_grp_lst[1]).split('/')[1]
return dvc_chnl_map
# def get_all_timestamps(self):
# """
# Get all the timestamps from the H5 file in a list
# :return:
# """
# timestamp_dtset_obj = self.h5_obj['/MTS/Timestamp']
# # print("timestamp_dtset_obj ::", timestamp_dtset_obj.value, dir(timestamp_dtset_obj))
# tmstamp_lst = list(timestamp_dtset_obj.value)
# print("tmstamp_lst::", len(tmstamp_lst))
# return tmstamp_lst
def get_all_timestamps(self):
"""
Get all the timestamps from the H5 file in a list
:return:
"""
timestamp_dtset_obj = self.h5_obj['/HFLXXX/POINTCLOUD']
# print("timestamp_dtset_obj ::", dir(timestamp_dtset_obj))
# print(timestamp_dtset_obj.values())
tmstamp_lst = []
for tmstamp, pcl_data in timestamp_dtset_obj.iteritems():
# print(k, v)
tmstamp_lst.append(tmstamp)
# tmstamp_lst = list(timestamp_dtset_obj.value)
print("tmstamp_lst::", len(tmstamp_lst))
return tmstamp_lst
# def get_pcl_points_for_tmstamp(self, time_stamp):
# timestamp_dtset_obj = self.h5_obj['/MTS/Timestamp']
# # print("timestamp_dtset_obj ::", timestamp_dtset_obj.value, dir(timestamp_dtset_obj))
# all_tmstamps = list(timestamp_dtset_obj.value)
# tmstamp_idx = all_tmstamps.index(time_stamp)
# print("tmstamp_idx ::>", tmstamp_idx)
# pnt_cld_obj = self.h5_obj['/MTS/POINTCLOUD']
# pcd_dt_lst = []
# for name, evry_pntCld_member in pnt_cld_obj.items():
# # print("name::", name, evry_pntCld_member)
# if isinstance(evry_pntCld_member, h5py.Group):
# ordinate_lst = []
# for pcd_infoname, evry_pntCld_info in evry_pntCld_member.items():
# # print("entry confirm")
# pointCloud_member_names = ['Xpoint', 'Ypoint', 'Zpoint', 'Ampl']
# if isinstance(evry_pntCld_info, h5py.Dataset):
# if pcd_infoname in pointCloud_member_names:
# # Only if x,y and z co-ordinates exist
# ordinate_values = evry_pntCld_info.value
# # print("evry_pntCld_info ::", pcd_infoname, ordinate_values)
# ordinate_lst.append(ordinate_values[tmstamp_idx] / 1.0)
# if ordinate_lst:
# pcd_dt_lst.append(ordinate_lst)
# # print("pcd_dt_lst ::", pcd_dt_lst)
# return pcd_dt_lst
def get_pcl_dataset(self, name, obj):
if isinstance(obj, h5py.Dataset):
self.pcl_dataset_dict[name] = obj
def save_ref_imf(self, img_pnt_dist_lst, img_pnt_intn_lst, tmstamp_str):
# print "save_ref_imf >>"
img_w = 128
img_h = 32
max_d = 30
import numpy as np
import cv2
# raw_int = data[self.intensity_path][idx][0][:(img_h * img_w)]
# raw_ran = data[self.dist_path][idx][0][:(img_h * img_w)]
img_dist_arr = np.asarray(img_pnt_dist_lst)
img_intn_arr = np.asarray(img_pnt_intn_lst)
# img_arr = img_pnt_lst
# print "img_arr ::", img_arr
raw_ran = img_dist_arr[:(img_h * img_w)]
raw_int = img_intn_arr[:(img_h * img_w)]
mask = raw_ran > (max_d * 4096)
raw_ran[mask] = max_d * 4096
raw_int[mask] = 0
dat_int = np.rot90(np.asarray(raw_int, dtype=np.uint8).reshape(img_w, img_h))
dat_ran = np.rot90(np.asarray(raw_ran / 4096.0, dtype=np.float32).reshape(img_w, img_h))
# print "dat_ran >>", dat_ran, dat_ran.shape
cv2.imwrite(r"distance//distance_%s.jpg"%tmstamp_str, dat_ran)
cv2.imwrite(r"intensity//intensity_%s.jpg" % tmstamp_str, dat_int)
def get_pcl_points_for_tmstamp(self, time_stamp):
# pcl_path = '/POINTCLOUD' + r'/' + str(time_stamp)
# print("------------------------------------------", pcl_path)
# pnt_cld_dtset_obj = self.h5_obj[pcl_path]
st_time = datetime.now()
pnt_cld_dtset_obj = self.h5_obj['/HFLXXX/POINTCLOUD']
# print("pnt_cld_dtset_obj >", dir(pnt_cld_dtset_obj), type(pnt_cld_dtset_obj))
if not self.pcl_dataset_dict:
pnt_cld_dtset_obj.visititems(self.get_pcl_dataset)
# print("self.pcl_dataset_dict :: ", self.pcl_dataset_dict)
pcl_dtset = self.pcl_dataset_dict[str(time_stamp)]
# print("pcl_dtset ::", pcl_dtset, dir(pcl_dtset))
# print pcl_dtset.value
# Read the distance image which is written with the PCL points
if len(pcl_dtset.value[0]) > 4:
imag_pnt_dist_lst = [evry_tupl[4] for evry_tupl in pcl_dtset.value]
imag_pnt_intn_lst = [evry_tupl[5] for evry_tupl in pcl_dtset.value]
self.save_ref_imf(imag_pnt_dist_lst, imag_pnt_intn_lst, str(time_stamp))
else:
print "No reference image data"
# pcl_dtset.value
ed_time = datetime.now()
duration = ed_time-st_time
print("duration::", duration.total_seconds())
return pcl_dtset.value
class PointCloudService(object):
def __init__(self, H5FileName):
self.h5_file_name = H5FileName
self.tmstamp_lst = []
# Initialize eCAL
ecal.initialize(sys.argv, "Point cloud data publisher")
global ALGO_READINESS
ALGO_READINESS = False
self.initialize_subscr_topics()
self.initialize_publsr_topics()
self.define_subscr_callbacks()
def initialize_subscr_topics(self):
# Initialize all the subscriber topics
self.pnt_cld_dvc_subscr_obj = ecal.subscriber(json_data['pointcloud_device_request'])
self.pnt_cld_data_subscr_obj = ecal.subscriber(json_data['pointcloud_data_request'])
self.pnt_cld_end_subscr_obj = ecal.subscriber(json_data['pointcloud_end_response'])
def initialize_publsr_topics(self):
# Initialize all the publisher topics
self.pnt_cld_dvc_publr_obj = ecal.publisher(json_data['pointcloud_device_response'])
self.pnt_cld_data_publr_obj = ecal.publisher(json_data['pointcloud_data_response'])
self.pnt_cld_ready_obj = ecal.publisher(json_data['pointcloud_begin_response'])
def pub_pnt_cld_dvc_data(self, topic_name, msg, time):
dvc_dt_proto_obj = common_pb2.DevicesDataRequest()
dvc_dt_proto_obj.ParseFromString(msg)
bool_dvc_req = dvc_dt_proto_obj.requiredDevicesData
# pnt_cld_resp_proto_obj = pointcloud_pb2.PointCloudDataResponse()
tmstamp_resp_proto_obj = common_pb2.DevicesDataResponse()
if bool_dvc_req:
h5file_obj = H5ReaderSequence(self.h5_file_name)
dvc_chnl_name_dict = h5file_obj.get_device_channel_name()
print "dvc_chnl_name_dict ::", dvc_chnl_name_dict
tmstamps_lst = h5file_obj.get_all_timestamps()
print("tmstamps_lst::", tmstamps_lst)
if tmstamps_lst:
tmstamp_resp_proto_obj.deviceCount = 1
dvc_info_obj = tmstamp_resp_proto_obj.deviceDataInfo.add()
dvc_info_obj.deviceName = dvc_chnl_name_dict.keys()[0]
dvc_info_obj.numOfChannels = 1
chnl_info_obj = dvc_info_obj.channelInfoAttr.add()
chnl_info_obj.channelName = dvc_chnl_name_dict[dvc_chnl_name_dict.keys()[0]][0]
for evry_tmstamp in tmstamps_lst:
# print "evry_tmstamp :: ", evry_tmstamp
chnl_info_obj.timeStamp.append(int(evry_tmstamp))
else:
tmstamp_resp_proto_obj.deviceCount = -1
self.pnt_cld_dvc_publr_obj.send(tmstamp_resp_proto_obj.SerializeToString())
def pub_pnt_cld_points_data(self, topic_name, msg, time):
# print "pub_pnt_cld_points_data ::"
data_pcl_proto_obj = common_pb2.DataRequest()
data_pcl_proto_obj.ParseFromString(msg)
time_stamp = data_pcl_proto_obj.requiredTimestamp
device_name = data_pcl_proto_obj.requestDeviceName
channel_name = data_pcl_proto_obj.requestChannelName
unique_id = data_pcl_proto_obj.uniqueId
pcl_resp_proto_obj = pointcloud_pb2.PointCloudDataResponse()
print("time_stamp ::", time_stamp, device_name, channel_name, unique_id)
if time_stamp is not None:
# pcl_resp_proto_obj.recievedTimestamp = time_stamp
pcl_resp_proto_obj.responseDeviceName = device_name
pcl_resp_proto_obj.responseChannelName = channel_name
pcl_resp_proto_obj.uniqueId = unique_id
h5file_obj = H5ReaderSequence(self.h5_file_name)
if not self.tmstamp_lst:
self.tmstamp_lst = h5file_obj.get_all_timestamps()
self.tmstamp_lst = [int(evry_tmstamp) for evry_tmstamp in self.tmstamp_lst]
# print "self.tmstamp_lst::", self.tmstamp_lst
if time_stamp in self.tmstamp_lst:
clst_tmstamp = time_stamp
else:
clst_tmstamp = min(self.tmstamp_lst, key=lambda x: abs(x-time_stamp))
print "clst_tmstamp::", clst_tmstamp
pcl_resp_proto_obj.recievedTimestamp = clst_tmstamp
pcl_points_lst = h5file_obj.get_pcl_points_for_tmstamp(clst_tmstamp)
pnt_cld_obj = pcl_resp_proto_obj.pointClouds.add()
pnt_cld_obj.pointType = 'a'
pnt_cld_obj.cloudWidth = len(pcl_points_lst)
pnt_cld_obj.cloudHeight = 1
pnt_cld_obj.pointsCount = len(pcl_points_lst) * 1
# for ech_pnt_type_idx in range(4):
# pcl_pnt_obj = pnt_cld_obj.points.add()
# pnt_attrib_obj = pcl_pnt_obj.pointAtributes.add()
# pcl_points_lst = [['0.0', '-11472.0', '-828.0', '10600.0'], ['0.0', '-13880.0', '-333.0', '7946.0'], ['0.0', '-13972.0', '2530.0', '7543.0']]
for evry_point_lst in pcl_points_lst:
# evry_point_lst = ['0.0', '-11472.0', '-828.0', '10600.0']
evry_point_lst = [float(evry_pnt) for evry_pnt in evry_point_lst]
# print("evry_point_lst ::", evry_point_lst, type(evry_point_lst[0]))
pcl_pnt_obj = pnt_cld_obj.points.add()
for ech_pnt in evry_point_lst:
# ech_pnt = '-11472.0'
# print("ech_pnt >", ech_pnt)
pnt_val_obj = pcl_pnt_obj.pointAtributes.add()
pnt_val_obj.pointValue = ech_pnt
# pnt_val_obj.pointValue.append(int(ech_pnt))
# pcl_pnt_obj.pointAtributes.append(int(ech_pnt))
print("Point cloud sent..")
else:
pcl_resp_proto_obj.recievedTimestamp = 0
self.pnt_cld_data_publr_obj.send(pcl_resp_proto_obj.SerializeToString())
def abort_algo(self, topic_name, msg, time):
if topic_name == json_data['pointcloud_end_response']:
global BEXIT
BEXIT = False
def inform_model_loaded(self):
# Inform model is loaded
# time.sleep(2)
lbl_response_obj = common_pb2.ServiceState()
lbl_response_obj.serviceStatus = "True"
self.pnt_cld_ready_obj.send(lbl_response_obj.SerializeToString())
def define_subscr_callbacks(self):
self.pnt_cld_dvc_subscr_obj.set_callback(self.pub_pnt_cld_dvc_data)
self.pnt_cld_data_subscr_obj.set_callback(self.pub_pnt_cld_points_data)
self.pnt_cld_end_subscr_obj.set_callback(self.abort_algo)
print("Point Cloud service initialized")
while ecal.ok() and BEXIT:
time.sleep(0.1)
if SERVICE_READINESS:
self.inform_model_loaded()
if __name__ == '__main__':
# H5FileName = sys.argv[1]
# Ticket_fld_path = sys.argv[1]
Ticket_fld_path = r'C:\Users\uidr8549\Desktop\tech_demo\Batch_Ticket'
# Check if the .h5 file exists in the ticket folder
sub_folder = r'\Input'
# sub_folder = r'\Images'
# try:
for fname in os.listdir(Ticket_fld_path + sub_folder):
if fname.endswith('.h5'):
# print("H5 file exists", fname)
H5FilePath = Ticket_fld_path + sub_folder + r'\\' + fname
# H5FileName = r'optimized.h5'
# break
h5_obj = h5py.File(H5FilePath, "r")
if type(h5_obj['/HFLXXX']) is h5py.Group:
print("HFLXXX device name exists")
else:
print("HFLXXX device name does not exist")
if type(h5_obj['/HFLXXX/POINTCLOUD']) is h5py.Group:
print("POINTCLOUD channel name exists")
else:
print("POINTCLOUD channel name does not exist")
# else:
# H5FilePath = None
# except Exception as e:
# print(str(e))
if H5FilePath is None:
print("No H5 file present in folder")
else:
PointCloudService(H5FilePath)
# pyinstaller --onefile point_cloud_service.py --add-data _ecal_py_2_7_x86.pyd;.
# D:\Work\2018\code\Tensorflow_code\Protobuf_compilers\protoc3.5\bin\protoc.exe -I=.\ --python_out=.\ pointcloud.proto<file_sep>/flsk_blogapp/db_migration/sample_migration.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.sqlite'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128))
addr = db.Column(db.String(128))
# set FLASK_APP = sample_migration.py
# In Power shell
# $env:FLASK_APP = "sample_migration.py"
# flask db init
# New change execute the below command
# flask db migrate
# flask db upgrade<file_sep>/Neo4j_py/neo_restAPI/test_neo_restAPI.py
from neo4jrestclient.client import GraphDatabase
import json
gdb = GraphDatabase("http://10.223.242.11:7474/db/data/", username="neo4j", password="<PASSWORD>")
# pyinstaller rec_summary_events_rc.py -w --add-data summary.txt;.
# print gdb
data_lst_dct = [{"RECFILENAME": "Continuous_2011.07.04_at_14.37.07.rec", "PROJECT": "MFC400", "FUNCTION": "SR", "DEPARTMENT": "DEV", "COUNTRY": ["Germany", "Austria"],
"ROAD_TYPE": ["Highway", "City"], "LIGHT_CONDITIONS": ["Day", "Night"], "WEATHER": ["Dry", "Rain"]},
{"RECFILENAME": "Snapshot_2015.07.23_at_12.56.57.rec", "PROJECT": "MFC300", "FUNCTION": "SR", "DEPARTMENT": "DEV", "COUNTRY": ["USA", "Great_Britain"],
"ROAD_TYPE": ["Other", "Motorway"], "LIGHT_CONDITIONS": ["Day", "Dusk"], "WEATHER": ["Rain"]},
{"RECFILENAME": "20141215_1540_{08627FB2-FDC3-414E-92B3-EBE39884DA8F}.rrec", "PROJECT": "MFC500", "FUNCTION": "SR", "DEPARTMENT": "DEV", "COUNTRY": ["TAIWAN", "Austria"],
"ROAD_TYPE": ["Country_Road", "Highway"], "LIGHT_CONDITIONS": ["Dusk", "Night"], "WEATHER": ["Dry"]},
]
# data_lst_dct = ''
with open("ldss.json") as outfile:
# self.config_schema = OrderedDict(json.load(outfile))
data_lst_dct = json.load(outfile)
for ech_rcord_dict in data_lst_dct:
print ("ech_rcord_dict :: ", ech_rcord_dict["RECFILENAME"])
# Create recording node
rec_node = gdb.node(name=ech_rcord_dict["RECFILENAME"])
rec_node.labels.add("RecordingName")
print ("Created rec node.....")
# Create common data node
cmn_data_node = gdb.node(project=ech_rcord_dict["PROJECT"], function=ech_rcord_dict["FUNCTION"],
department=ech_rcord_dict["DEPARTMENT"])
cmn_data_node.labels.add("CommonData")
# Establish relationship with rec and common data node
rec_node.relationships.create("cd", cmn_data_node)
print ("Created common data node.....")
# Create country node
cntry_node = gdb.node(name=ech_rcord_dict["COUNTRY"])
cntry_node.labels.add("Country")
# Establish relationship with rec and country node
rec_node.relationships.create("c", cntry_node)
print ("Created country node.....")
# Create road type node
road_typ_node = gdb.node(name=ech_rcord_dict["ROAD_TYPE"])
road_typ_node.labels.add("RoadType")
# Establish relationship with rec and country node
cntry_node.relationships.create("rt", road_typ_node)
print ("Created road type node.....")
# Create weather node
wthr_cond_node = gdb.node(name=ech_rcord_dict["WEATHER"])
wthr_cond_node.labels.add("WeatherCondition")
# Establish relationship with rec and country node
road_typ_node.relationships.create("w", wthr_cond_node)
print ("Created Weather condition node.....")
# Create light condition node
lght_cond_node = gdb.node(name=ech_rcord_dict["LIGHT_CONDITIONS"])
lght_cond_node.labels.add("LightCondition")
# Establish relationship with rec and country node
wthr_cond_node.relationships.create("lc", lght_cond_node)
print ("Created light condition node.....")
# Create object type node
obj_typ_node = gdb.node(name=ech_rcord_dict["SR_SIGN_CLASS"])
obj_typ_node.labels.add("ObjectType")
# Establish relationship with light conditions
lght_cond_node.relationships.create("ob", obj_typ_node)
print ("Created object type node.....\n")
<file_sep>/README.md
This repository contains some of the supporting applications based on Bsig and H5 parsers.
# BSig supporting application
- Run the file bsig_sig_val_publish.py file to start off the eCAL based application.
- The subscriber and publisher topic names are defined in the constructor of the class.
- The messages are transmitted over eCAL through protobuf.
- The message structure is defined in Radar.proto
- Compile the proto file using the command protoc -I=.\ --python_out=.\ Radar.proto
- Bsig_app/publish_signals_bsig.py has the sample code to publish data to produce data from bsig files
- The path of the bsig file, signal names list, object id count(number of objects) is published over a common topic.
- The bsig_sig_val_publish.py will publish all the related data for common and object signals over eCAL.
Note: Bsig_app/bsig_optimize/__init__.py has the sample code to read data for multiple signals from a bsig file
# H5 supporting application
- Run the file H5_app/hfl_image_generator/h5_image_publisher.py
- It is a generic application to publish images to Label tool 5G.
## How it works?
- Run the file H5_app/hfl_image_generator/h5_image_publisher.py file to start off the eCAL based application.
- Label tool publishes input message under the topic name 'channel_request' defined in topics.json
- Ask for channel data(True).
- It will read H5 file, fetches number of devices, channels and timestamps mapped to their channels.
- Device, channel and respective time stamps is published under the topic name 'channel_response' defined in topics.json
- Run H5_app/hfl_image_generator/hfl_test_device.py It has the sample code to publish data requesting H5 file to send the values.
- Once user has channel and timestamp data, one could request image based on these parameters.
- Publish device, channel and timestamp under the topic name 'hfl_request' defined in topics.json
- The callback function would send the image as an encoded string under the topic name 'hfl_response' defined in topics.json
## .Exe creation by pyinstaller
Use the command
- pyinstaller --onefile bsig_sig_val_publish.py --add-data _ecal_py_2_7_x86.pyd;.
- pyinstaller --onefile bsig_sig_val_publish.py --add-data _ecal_py_2_7_x86.pyd;.
<file_sep>/H5_app/hfl_data_publish.py
import h5py
import os
import sys
import numpy as np
import ecal
# import AlgoInterface_pb2
import imageservice_pb2
import json
import cv2
if getattr(sys, 'frozen', False):
os.chdir(sys._MEIPASS)
with open('topics.json') as data_file:
json_data = json.load(data_file)
# print(json_data)
request = str(json_data['request'])
response = str(json_data['response'])
h5_filename = str(json_data['h5_filename'])
ecal.initialize(sys.argv, "HFL data publisher")
hfl_subscr_obj = ecal.subscriber(request)
hfl_publs_obj = ecal.publisher(topic_name=response)
hfl_req_proto_obj = imageservice_pb2.ImageRequest()
hfl_resp_proto_obj = imageservice_pb2.HFLResponse()
class H5ReaderSequence(object):
def __init__(self, fname):
self.reset(fname)
self.lastLoadFilename = ""
def reset(self, fname):
if not os.path.isfile(fname):
print("Error - H5 file not available: %s!" % fname)
sys.exit()
# self.data = h5py.File(fname, "r")
self.img_w = 128
self.img_h = 32
self.max_d = 30
self.i = 0
# self.max_i = len(self.data["/HFL130/PCA/PcaDebugData/Data/m_Intensity_au16"])
#
# def getI(self):
# return self.i
#
# def setI(self, i):
# if i >= self.getMaxI():
# i = 0
# if i < 0:
# i = self.getMaxI() - 1
# self.i = i
#
# def getMaxI(self):
# return self.max_i
#
# def get(self, i):
# self.setI(i)
# raw_int = self.data["/HFL130/PCA/PcaDebugData/Data/m_Intensity_au16"][self.i][0][:(self.img_h * self.img_w)]
# raw_ran = self.data["/HFL130/PCA/PcaDebugData/Data/m_Dist_MF_as32"][self.i][0][:(self.img_h * self.img_w)]
# mask = raw_ran > (self.max_d * 4096)
# raw_ran[mask] = self.max_d * 4096
# raw_int[mask] = 0
# dat_int = np.rot90(np.asarray(raw_int, dtype=np.uint8).reshape(self.img_w, self.img_h))
# dat_ran = np.rot90(np.asarray(raw_ran / 4096.0, dtype=np.float32).reshape(self.img_w, self.img_h))
# return (dat_int, dat_ran)
#
# def get_all_timestamps(self, filename):
#
# data = h5py.File(filename, "r")
# self.idxlist = [str(d) for d in data["/MTS/Package/TimeStamp"]]
# return self.idxlist
def loadData(self, filename, idx):
data = h5py.File(filename, "r")
if self.lastLoadFilename != filename:
self.idxlist = [str(d) for d in data["/MTS/Package/TimeStamp"]]
# print("self.idxlist :: ", self.idxlist)
# idx = self.idxlist.index(timestamp)
try:
timestamp = self.idxlist[idx]
raw_int = data["/HFL130/PCA/PcaDebugData/Data/m_Intensity_au16"][idx][0][:(self.img_h * self.img_w)]
raw_ran = data["/HFL130/PCA/PcaDebugData/Data/m_Dist_MF_as32"][idx][0][:(self.img_h * self.img_w)]
mask = raw_ran > (self.max_d * 4096)
raw_ran[mask] = self.max_d * 4096
raw_int[mask] = 0
dat_int = np.rot90(np.asarray(raw_int, dtype=np.uint8).reshape(self.img_w, self.img_h))
dat_ran = np.rot90(np.asarray(raw_ran / 4096.0, dtype=np.float32).reshape(self.img_w, self.img_h))
# cv2.imwrite('color_img.jpg', dat_ran)
# cv2.imshow('Color image', dat_ran)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
dat_int = cv2.imencode('.png', dat_int)[1].tostring()
dat_ran = cv2.imencode('.png', dat_ran)[1].tostring()
data.close()
self.lastfilename = filename
except IndexError, e:
print "Time stamp does not exist for this index"
timestamp = 0
dat_int = ''
dat_ran = ''
return (timestamp, dat_int, dat_ran)
def loadPreviouseData(self, filename, timestamp):
data = h5py.File(filename, "r")
if self.lastLoadFilename != filename:
self.idxlist = [str(d) for d in data["/MTS/Package/TimeStamp"]]
idx = self.idxlist.index(timestamp) - 1
if idx < 0:
return ([], [])
raw_int = data["/HFL130/PCA/PcaDebugData/Data/m_Intensity_au16"][idx][0][:(self.img_h * self.img_w)]
raw_ran = data["/HFL130/PCA/PcaDebugData/Data/m_Dist_MF_as32"][idx][0][:(self.img_h * self.img_w)]
mask = raw_ran > (self.max_d * 4096)
raw_ran[mask] = self.max_d * 4096
raw_int[mask] = 0
dat_int = np.rot90(np.asarray(raw_int, dtype=np.uint8).reshape(self.img_w, self.img_h))
dat_ran = np.rot90(np.asarray(raw_ran / 4096.0, dtype=np.float32).reshape(self.img_w, self.img_h))
data.close()
self.lastfilename = filename
return (dat_int, dat_ran)
def loadStartStopTimestamp(self, filename):
data = h5py.File(filename, "r")
starttimestamp = data["/MTS/Package/TimeStamp"][0]
stoptimestamp = data["/MTS/Package/TimeStamp"][-1]
data.close()
return (starttimestamp, stoptimestamp)
def getInfo(self, i):
return [str(self.data.filename),
str(self.data["/MTS/Package/TimeStamp"][i]),
str(self.data["/MTS/Package/CycleID"][i]),
str(self.data["/MTS/Package/CycleCount"][i])]
def publish_hfl_data():
# subscribe the HFL request to receive the timestamp and file name
while ecal.ok():
ret, msg, time = hfl_subscr_obj.receive(500)
# print("---:: ", ret, msg, time, type(msg))
if msg is not None:
hfl_req_proto_obj.ParseFromString(msg)
idx_req = hfl_req_proto_obj.image_index
# timestamp = int(timestamp)
print("--->", idx_req, h5_filename)
h5file_obj = H5ReaderSequence(h5_filename)
timestamp, inten_data, dist_data = h5file_obj.loadData(h5_filename, int(idx_req))
print("timestamp :: ", timestamp)
hfl_resp_proto_obj.timestamp = int(timestamp)
hfl_resp_proto_obj.HFL_image_index = int(idx_req)
if inten_data != '' or dist_data != '':
hfl_resp_proto_obj.intensity_image = inten_data
hfl_resp_proto_obj.distance_image = dist_data
else:
hfl_resp_proto_obj.intensity_image = inten_data
hfl_resp_proto_obj.distance_image = dist_data
hfl_publs_obj.send(hfl_resp_proto_obj.SerializeToString())
if __name__ == '__main__':
publish_hfl_data()
# fname = r'D:\Work\2018\code\LT5G\HDF5_reader\2017.09.07_at_20.37.57_camera-mi_1449.h5'
# h5file_obj = H5ReaderSequence(fname)
# # st_time, end_time = h5file_obj.loadStartStopTimestamp(fname)
# # print("st_time, end_time :: ", st_time, end_time)
# tmstamps_lst = h5file_obj.get_all_timestamps(fname)
# # tm_stamp = '1504816686729381'
# outdir = r"D:\Work\2018\code\LT5G\HDF5_reader\h5_read_v1\imgdir"
# for tm_stamp in tmstamps_lst:
# inten_data, dist_data = h5file_obj.loadData(fname, tm_stamp)
# # print("arr_data :: ", arr_data)
# print("timestamp :: ", tm_stamp)
# cv2.imwrite(outdir + "\\HFL130INTENSITY_%s.jpg" % tm_stamp, inten_data)
# cv2.imwrite(outdir + "\\HFL130DISTANCE_%s.jpg" % tm_stamp, dist_data)
<file_sep>/Neo4j_py/neo4_conn.py
# import py2neo
#
# from py2neo import Graph, Path, authenticate
# authenticate("localhost:7474", "tanveer", "tan_neo4j")
#
#
#
# graph = Graph("http://localhost:7474/")
#
# tx = graph.cypher.begin()
# for name in ["Alice", "Bob", "Carol"]:
# tx.append("CREATE (person:Person {name:{name}}) RETURN person", name=name)
# alice, bob, carol = [result.one for result in tx.commit()]
#
# friends = Path(alice, "KNOWS", bob, "KNOWS", carol)
# graph.create(friends)
#=============================================================================
#
# You are connected as user neo4j
# to the server bolt://localhost:7687
from neo4j.v1 import GraphDatabase
class HelloWorldExample(object):
def __init__(self, uri, user, password):
self._driver = GraphDatabase.driver(uri, auth=(user, password))
print "self._driver :: ", self._driver
def close(self):
self._driver.close()
def print_greeting(self, message):
with self._driver.session() as session:
greeting = session.write_transaction(self._create_and_return_greeting, message)
print(greeting)
@staticmethod
def _create_and_return_greeting(tx, message):
print "tx :: ", tx
result = tx.run("CREATE (a:Greeting) "
"SET a.message = $message "
"RETURN a.message + ', from node ' + id(a)", message=message)
print "result :: ", result
return result.single()[0]
if __name__ == '__main__':
hello_obj = HelloWorldExample("bolt://localhost:7687", "neo4j", "tan_neo4j")
print "hello_obj :: ", hello_obj
hello_obj.print_greeting("Add greeting data")
hello_obj.close()
<file_sep>/flsk_blogapp/samples/blogging_app/Dockerfile
FROM python:2.7.10
ADD . /code
WORKDIR /code
RUN pip --proxy http://uidr8549:<EMAIL>9<EMAIL>:8080 install -r requirements.txt
CMD ["python", "blog_app.py"]<file_sep>/Neo4j_py/graph_db_trace/rec_summary_ui.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 're_summary_ui.ui'
#
# Created: Tue Jan 30 11:09:52 2018
# by: PyQt4 UI code generator 4.9.6
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui, Qt
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(600, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.gridLayout = QtGui.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label_qry = QtGui.QLabel(self.centralwidget)
self.label_qry.setObjectName(_fromUtf8("label_3"))
self.horizontalLayout.addWidget(self.label_qry)
self.lineEdit_query = QtGui.QLineEdit(self.centralwidget)
self.lineEdit_query.setObjectName(_fromUtf8("lineEdit_2"))
self.horizontalLayout.addWidget(self.lineEdit_query)
self.verticalLayout.addLayout(self.horizontalLayout)
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
spacerItem = QtGui.QSpacerItem(138, 20, QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem)
self.rgd_chk_box = QtGui.QCheckBox(self.centralwidget)
self.rgd_chk_box.setObjectName(_fromUtf8("lbl_loctn"))
self.horizontalLayout_4.addWidget(self.rgd_chk_box)
self.chkbl_ComboBox = CheckableComboBox()
self.horizontalLayout_4.addWidget(self.chkbl_ComboBox)
self.chkbl_objtype_ComboBox = CheckableObjComboBox()
self.horizontalLayout_4.addWidget(self.chkbl_objtype_ComboBox)
# Export location.....
# self.lbl_loctn = QtGui.QLabel(self.centralwidget)
# self.lbl_loctn.setObjectName(_fromUtf8("lbl_loctn"))
# self.horizontalLayout_4.addWidget(self.lbl_loctn)
# self.lne_edit_loctn = QtGui.QLineEdit(self.centralwidget)
# self.lne_edit_loctn.setObjectName(_fromUtf8("lne_edit_loctn"))
# self.horizontalLayout_4.addWidget(self.lne_edit_loctn)
# self.tool_btn_loctn = QtGui.QToolButton(self.centralwidget)
# self.tool_btn_loctn.setObjectName(_fromUtf8("tool_btn_loctn"))
# self.horizontalLayout_4.addWidget(self.tool_btn_loctn)
self.pushButton_export = QtGui.QPushButton(self.centralwidget)
self.pushButton_export.setObjectName(_fromUtf8("pushButton_export"))
self.horizontalLayout_4.addWidget(self.pushButton_export)
self.pushButton_interpret = QtGui.QPushButton(self.centralwidget)
self.pushButton_interpret.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout_4.addWidget(self.pushButton_interpret)
self.verticalLayout.addLayout(self.horizontalLayout_4)
self.horizontalLayout_5 = QtGui.QHBoxLayout()
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.label_4 = QtGui.QLabel(self.centralwidget)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.horizontalLayout_5.addWidget(self.label_4)
self.rec_lst_wdgt = QtGui.QListWidget(self.centralwidget)
self.rec_lst_wdgt.setObjectName(_fromUtf8("listWidget"))
self.horizontalLayout_5.addWidget(self.rec_lst_wdgt)
self.verticalLayout.addLayout(self.horizontalLayout_5)
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout_3.addWidget(self.label)
self.lineEdit_recname = QtGui.QLineEdit(self.centralwidget)
self.lineEdit_recname.setObjectName(_fromUtf8("lineEdit"))
self.horizontalLayout_3.addWidget(self.lineEdit_recname)
# self.verticalLayout.addLayout(self.horizontalLayout_3)
# spacerItem = QtGui.QSpacerItem(138, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
# self.horizontalLayout_3.addItem(spacerItem)
self.pushButton_fetch = QtGui.QPushButton(self.centralwidget)
self.pushButton_fetch.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout_3.addWidget(self.pushButton_fetch)
self.verticalLayout.addLayout(self.horizontalLayout_3)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.horizontalLayout_2.addWidget(self.label_2)
self.summ_txt_edt = QtGui.QTextEdit(self.centralwidget)
self.summ_txt_edt.setObjectName(_fromUtf8("textEdit"))
self.horizontalLayout_2.addWidget(self.summ_txt_edt)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.progressBar = QtGui.QProgressBar(self.centralwidget)
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName(_fromUtf8("progressBar"))
self.verticalLayout.addWidget(self.progressBar)
self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 490, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "CREST", None))
self.label.setText(_translate("MainWindow", "Recording Name: ", None))
self.rgd_chk_box.setText(_translate("MainWindow", "Rigid ", None))
# self.lbl_loctn.setText(_translate("MainWindow", "Export location : ", None))
self.pushButton_fetch.setText(_translate("MainWindow", "Fetch", None))
self.pushButton_export.setText(_translate("MainWindow", "Export", None))
self.pushButton_interpret.setText(_translate("MainWindow", "Interpret", None))
self.label_2.setText(_translate("MainWindow", "Output Summary: ", None))
self.label_qry.setText(_translate("MainWindow", "Query: ", None))
self.label_4.setText(_translate("MainWindow", "Result: ", None))
class CheckableComboBox(QtGui.QComboBox):
def __init__(self):
super(CheckableComboBox, self).__init__()
self.view().pressed.connect(self.handleItemPressed)
self.setModel(QtGui.QStandardItemModel(self))
def handleItemPressed(self, index):
item = self.model().itemFromIndex(index)
if item.checkState() == QtCore.Qt.Checked:
item.setCheckState(QtCore.Qt.Unchecked)
else:
item.setCheckState(QtCore.Qt.Checked)
def flags(self, index):
return Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
class CheckableObjComboBox(QtGui.QComboBox):
def __init__(self):
super(CheckableObjComboBox, self).__init__()
self.view().pressed.connect(self.handleItemPressed)
self.setModel(QtGui.QStandardItemModel(self))
def handleItemPressed(self, index):
item = self.model().itemFromIndex(index)
if item.checkState() == QtCore.Qt.Checked:
item.setCheckState(QtCore.Qt.Unchecked)
else:
item.setCheckState(QtCore.Qt.Checked)
def flags(self, index):
return Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
# if __name__ == "__main__":
# import sys
# app = QtGui.QApplication(sys.argv)
# MainWindow = QtGui.QMainWindow()
# ui = Ui_MainWindow()
# ui.setupUi(MainWindow)
# MainWindow.show()
# sys.exit(app.exec_())
<file_sep>/PCD_generation/LT5_point_cloud_service/convert_optimized_pointCloud_h5.py
import h5py
import sys
import os
class H5ReaderSequence(object):
def __init__(self, fname):
self.reset(fname)
self.h5_obj = h5py.File(fname, "r")
def reset(self, fname):
if not os.path.isfile(fname):
print("Error - H5 file not available: %s!" % fname)
sys.exit()
def get_all_timestamps(self):
"""
Get all the timestamps from the H5 file in a list
:return:
"""
timestamp_dtset_obj = self.h5_obj['/MTS/Timestamp']
# print("timestamp_dtset_obj ::", timestamp_dtset_obj.value, dir(timestamp_dtset_obj))
tmstamp_lst = list(timestamp_dtset_obj.value)
print("tmstamp_lst::", len(tmstamp_lst))
return tmstamp_lst
def get_pcl_points_for_tmstamp(self, time_stamp):
timestamp_dtset_obj = self.h5_obj['/MTS/Timestamp']
# print("timestamp_dtset_obj ::", timestamp_dtset_obj.value, dir(timestamp_dtset_obj))
all_tmstamps = list(timestamp_dtset_obj.value)
tmstamp_idx = all_tmstamps.index(time_stamp)
print("tmstamp_idx ::>", tmstamp_idx)
pnt_cld_obj = self.h5_obj['/MTS/POINTCLOUD']
pcd_dt_lst = []
for name, evry_pntCld_member in pnt_cld_obj.items():
# print("name::", name, evry_pntCld_member)
if isinstance(evry_pntCld_member, h5py.Group):
ordinate_lst = []
for pcd_infoname, evry_pntCld_info in evry_pntCld_member.items():
# print("entry confirm")
pointCloud_member_names = ['Xpoint', 'Ypoint', 'Zpoint', 'Ampl']
if isinstance(evry_pntCld_info, h5py.Dataset):
if pcd_infoname in pointCloud_member_names:
# Only if x,y and z co-ordinates exist
ordinate_values = evry_pntCld_info.value
# print("evry_pntCld_info ::", pcd_infoname, ordinate_values)
ordinate_lst.append(ordinate_values[tmstamp_idx] / 1.0)
if ordinate_lst:
pcd_dt_lst.append(ordinate_lst)
# print("pcd_dt_lst ::", pcd_dt_lst)
return pcd_dt_lst
def generate_optimized_point_cloud_h5(self):
h5_obj_new = h5py.File('optimized.h5', 'a')
# get all the timestamps
tmstamps_lst = h5file_obj.get_all_timestamps()
for ech_tmstamp in tmstamps_lst:
print("ech_tmstamp ::", ech_tmstamp)
# Get point cloud info on each timestamp
pcd_dt_lst = h5file_obj.get_pcl_points_for_tmstamp(ech_tmstamp)
pcl_pnt_pth = '/POINTCLOUD' + r'/' + str(ech_tmstamp)
h5_obj_new.create_dataset(pcl_pnt_pth, data=pcd_dt_lst)
if __name__ == '__main__':
h5_file_name = r'2018.03.16_at_18.34.54_camera-mi_191-no-object_pointCloud.h5'
h5file_obj = H5ReaderSequence(h5_file_name)
h5file_obj.generate_optimized_point_cloud_h5()<file_sep>/Bsig_app/bsig_optimize/publish_signals_bsig.py
import ecal
import sys
import Radar_pb2
import time
bsig_path = r"D:\Work\2018\code\LT5G\OLT\Radar_labelling_bsig\bsig_readers\Continuous_2014.05.15_at_08.48.40.bsig"
# bsig_path = r"D:\Work\2018\code\LT5G\OLT\Radar_labelling_bsig\bsig_readers\20160608_1306_{4556C7A6-7F27-4A91-923E-4392C9785675}.bsig"
def publ_signal_names():
print "Publish bsig signal names......."
ecal.initialize(sys.argv, "Python Signal name publisher")
BSIG_INFO_OBJ = Radar_pb2.BsigDataRequest()
publisher_roi_obj = ecal.publisher(topic_name="BsigSignalNames")
sig_name_lst = ['MTS.Package.TimeStamp']
BSIG_INFO_OBJ.bsigPath = bsig_path
BSIG_INFO_OBJ.objectIdCount = 40
BSIG_INFO_OBJ.timestamp = -1
for sig_name in sig_name_lst:
BSIG_INFO_OBJ.signalNames.append(sig_name)
# while ecal.ok():
# print("BSIG_INFO_OBJ.SerializeToString() :: ", BSIG_INFO_OBJ.SerializeToString())
time.sleep(1)
publisher_roi_obj.send(BSIG_INFO_OBJ.SerializeToString())
def publ_multiple_signal_names():
print "Publish bsig signal names......."
ecal.initialize(sys.argv, "Python Signal name publisher")
BSIG_INFO_OBJ = Radar_pb2.BsigDataRequest()
publisher_roi_obj = ecal.publisher(topic_name="BsigSignalNames")
# sig_name = "SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Longitudinal.MotVar.Velocity"
sig_name_lst = ['SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Longitudinal.MotVar.Velocity',
'MTS.Package.TimeStamp',
'SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Longitudinal.MotVar.Accel',
'SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Lateral.YawRate.YawRate',
'SIM VFB ALL.DataProcCycle.ObjSyncEgoDynamic.Lateral.SlipAngle.SideSlipAngle',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Kinematic.fDistX',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Kinematic.fDistY',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Kinematic.fVrelX',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Legacy.uiLifeTime',
'SIM VFB ALL.DataProcCycle.EMPublicObjData.Objects[%].Attributes.eDynamicProperty',
'SIM VFB ALL.AlgoSenCycle.gSI_OOI_LIST.SI_OOI_LIST[%].object_id',
'SIM VFB ALL.AlgoSenCycle.gSI_OOI_LIST.SI_OOI_LIST[%].long_displacement',
'SIM VFB ALL.AlgoSenCycle.gSI_OOI_LIST.SI_OOI_LIST[%].lat_displacement_to_curvature']
BSIG_INFO_OBJ.bsigPath = bsig_path
BSIG_INFO_OBJ.objectIdCount = 100
# BSIG_INFO_OBJ.timestamp = 1465391170943194
BSIG_INFO_OBJ.timestamp = 8308331816
for sig_name in sig_name_lst:
BSIG_INFO_OBJ.signalNames.append(sig_name)
# while ecal.ok():
# print("BSIG_INFO_OBJ.SerializeToString() :: ", BSIG_INFO_OBJ.SerializeToString())
time.sleep(1)
publisher_roi_obj.send(BSIG_INFO_OBJ.SerializeToString())
#=================================================================================================================
if __name__ == '__main__':
publ_signal_names()
publ_multiple_signal_names()
|
364d173ccc8f916b54e2a0adf98ed5d46446a100
|
[
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 37 |
Python
|
tanveer941/miscellaneous_supporting_app
|
25c79341573860abf97a803f3e28395159898314
|
117e73357f4ca11e2e7cf95621daebab162bf33e
|
refs/heads/master
|
<file_sep><?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.ipbhalle.metfrag</groupId>
<artifactId>MetFrag</artifactId>
<version>2.4.6</version>
</parent>
<packaging>jar</packaging>
<groupId>de.ipbhalle.metfraglib</groupId>
<artifactId>MetFragLib</artifactId>
<name>MetFragLib</name>
<url>http://maven.apache.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>org.openscience.cdk</groupId>
<artifactId>cdk-bundle</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
</dependency>
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
</dependency>
<dependency>
<groupId>com.apporiented</groupId>
<artifactId>hierarchical-clustering</artifactId>
</dependency>
<dependency>
<groupId>net.rforge</groupId>
<artifactId>Rserve</artifactId>
</dependency>
<dependency>
<groupId>net.rforge</groupId>
<artifactId>REngine</artifactId>
</dependency>
<dependency>
<groupId>com.chemspider.www</groupId>
<artifactId>chemspider_webservices</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.ipbhalle.metfrag</groupId>
<artifactId>MetFrag</artifactId>
<version>2.4.6</version>
</parent>
<groupId>de.ipbhalle.metfragweb</groupId>
<artifactId>MetFragWeb</artifactId>
<packaging>war</packaging>
<name>MetFragWeb</name>
<build>
<finalName>MetFragWeb</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven3-plugin</artifactId>
<version>1.9.8</version>
<configuration>
<container>
<containerId>tomcat9x</containerId>
<type>embedded</type>
</container>
<deployables>
<deployable>
<type>war</type>
<location>${project.build.directory}/${project.build.finalName}.war</location>
<properties>
<context>/</context>
</properties>
</deployable>
</deployables>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>de.ipbhalle.metfraglib</groupId>
<artifactId>MetFragLib</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.omnifaces</groupId>
<artifactId>omnifaces</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>el-impl</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
</dependencies>
</project>
<file_sep>package de.ipbhalle.metfrag.hdx;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Iterator;
import java.util.Set;
import java.util.ArrayList;
import java.util.Arrays;
import net.sf.jniinchi.JniInchiInput;
import net.sf.jniinchi.JniInchiOutput;
import net.sf.jniinchi.JniInchiOutputStructure;
import net.sf.jniinchi.JniInchiStructure;
import net.sf.jniinchi.JniInchiWrapper;
import org.openscience.cdk.aromaticity.ElectronDonation;
import org.openscience.cdk.DefaultChemObjectBuilder;
import org.openscience.cdk.aromaticity.Aromaticity;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.graph.Cycles;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IBond;
import org.openscience.cdk.smiles.SmiFlavor;
import org.openscience.cdk.smiles.SmilesGenerator;
import org.openscience.cdk.tautomers.InChITautomerGenerator;
import org.openscience.cdk.tools.manipulator.AtomContainerManipulator;
import de.ipbhalle.metfraglib.FastBitArray;
import de.ipbhalle.metfraglib.inchi.InChIToStructure;
import de.ipbhalle.metfraglib.molecularformula.HDByteMolecularFormula;
import de.ipbhalle.metfraglib.parameter.Constants;
public class InChIDeuteriumGeneration {
public static void main(String[] args) throws Exception {
boolean withAromaticRings = false;
boolean combinatorial = true;
/*
* read input inchis
*/
ArrayList<String> inchis = new ArrayList<String>();
ArrayList<Integer> numberToAddDeuteriums = new ArrayList<Integer>();
ArrayList<String> identifiers = new ArrayList<String>();
BufferedReader breader = new BufferedReader(
new FileReader(
new File(
args[0])));
String line = "";
int identifier = 1;
while ((line = breader.readLine()) != null) {
String[] tmp = line.trim().split("\\s+");
inchis.add(tmp[0].trim());
if(tmp.length >= 2) numberToAddDeuteriums.add(Integer.parseInt(tmp[1].trim()));
if(tmp.length == 3) identifiers.add(tmp[2].trim());
else identifiers.add(identifier + "");
identifier++;
}
breader.close();
/*
* generate deuterated version of inchi
*/
InChITautomerGenerator tg = new InChITautomerGenerator();
java.io.BufferedWriter bwriter = null;
if(args.length == 2) {
bwriter = new java.io.BufferedWriter(new java.io.FileWriter(new java.io.File(args[1])));
}
for (int j = 0; j < inchis.size(); j++) {
System.out.println(inchis.get(j));
/*
* build the jni inchi atom container
*/
InChIToStructure its = new InChIToStructure(inchis.get(j),
DefaultChemObjectBuilder.getInstance());
int numberDeuteriums = 0;
int numberDeuteriumsEasilyExchanged = 0;
int numberDeuteriumsAromaticExchanged = 0;
JniInchiOutputStructure jios = its.getInchiOutputStructure();
FastBitArray atomsWithDeuterium = new FastBitArray(jios.getNumAtoms());
int[] toExchange = searchForDeuteriumExchangeablePositions(
new String[] { "O", "N", "S" }, jios);
if(!combinatorial || (numberToAddDeuteriums.size() == 0 || toExchange.length <= numberToAddDeuteriums.get(j))) {
for (int i = 0; i < toExchange.length; i++) {
if(!atomsWithDeuterium.get(toExchange[i])) {
atomsWithDeuterium.set(toExchange[i]);
numberDeuteriums += jios.getAtom(toExchange[i]).getImplicitH();
numberDeuteriumsEasilyExchanged += jios.getAtom(toExchange[i]).getImplicitH();
jios.getAtom(toExchange[i]).setImplicitDeuterium(
jios.getAtom(toExchange[i]).getImplicitH());
jios.getAtom(toExchange[i]).setImplicitH(0);
}
}
}
else if(toExchange.length > numberToAddDeuteriums.get(j)) {
ArrayList<JniInchiOutputStructure> deuteratedStrutures = new ArrayList<JniInchiOutputStructure>();
ArrayList<Integer> numberDeuteriumsVec = new ArrayList<Integer>();
ArrayList<Integer> numberDeuteriumsEasilyExchangedVec = new ArrayList<Integer>();
//get all possible combinations of exchanges with given number
//of exchangeable hydrogens
int[][] combs = getCombinations(toExchange, numberToAddDeuteriums.get(j));
for (int k = 0; k < combs.length; k++) {
numberDeuteriumsEasilyExchanged = 0;
numberDeuteriums = 0;
InChIToStructure itsNew = new InChIToStructure(inchis.get(j),
DefaultChemObjectBuilder.getInstance());
IAtomContainer con = itsNew.getAtomContainer();
AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(con);
java.util.List<IAtomContainer> tautos = tg.getTautomers(con);
SmilesGenerator sg = new SmilesGenerator(SmiFlavor.Generic);
for(IAtomContainer tautomer : tautos) {
System.out.println(sg.create(tautomer));
}
JniInchiOutputStructure jiosNew = itsNew.getInchiOutputStructure();
//System.out.println(Arrays.toString(combs[k]));
for(int l = 0; l < combs[k].length; l++) {
numberDeuteriums += jiosNew.getAtom(combs[k][l]).getImplicitH();
int numberDs = jiosNew.getAtom(combs[k][l]).getImplicitDeuterium();
int numberHs = jiosNew.getAtom(combs[k][l]).getImplicitH();
jiosNew.getAtom(combs[k][l]).setImplicitDeuterium(numberDs + 1);
jiosNew.getAtom(combs[k][l]).setImplicitH(numberHs - 1);
numberDeuteriumsEasilyExchanged++;
//System.out.println(numberHs + " " + combs[k][l] + " " + jiosNew.getAtom(combs[k][l]).getImplicitH() + " " + jiosNew.getAtom(combs[k][l]).getImplicitDeuterium());
}
//System.out.println("JniInchiOutputStructure");
//printInfo(jiosNew);
numberDeuteriumsVec.add(numberDeuteriums);
numberDeuteriumsEasilyExchangedVec.add(numberDeuteriumsEasilyExchanged);
deuteratedStrutures.add(jiosNew);
}
for(int k = 0; k < deuteratedStrutures.size(); k++) {
JniInchiStructure jis = new JniInchiStructure();
jis.setStructure(deuteratedStrutures.get(k));
JniInchiInput input = new JniInchiInput(jis);
//System.out.println("JniInchiInput");
//printInfo(input);
JniInchiOutput output = JniInchiWrapper.getInchi(input);
String inchi = output.getInchi();
HDByteMolecularFormula formula = null;
try {
formula = new HDByteMolecularFormula(inchi.split("/")[1]);
}
catch(Exception e) {
System.err.println(identifiers.get(j));
e.printStackTrace();
System.exit(1);
}
formula.setNumberHydrogens((short)formula.getNumberHydrogens());
formula.setNumberDeuterium((short) (int) numberDeuteriumsVec.get(k));
double mass = formula.getMonoisotopicMass();
System.out.println(identifiers.get(j) + "-" + (k+1) + "|" + inchi + "|" + formula.toString() + "|" + mass + "|"
+ JniInchiWrapper.getInchiKey(inchi).getKey().split("-")[0] + "|" + JniInchiWrapper.getInchiKey(inchi).getKey().split("-")[1]
+ "|" + numberDeuteriumsEasilyExchangedVec.get(k) + "|0|" + (toExchange.length - numberToAddDeuteriums.get(j))
+ "|" + (mass + Constants.getMonoisotopicMassOfAtom("D") - Constants.ELECTRON_MASS)
+ "|" + (mass - Constants.getMonoisotopicMassOfAtom("D") + Constants.ELECTRON_MASS));
}
continue;
}
/*
* for aromatic ring deuteration generate the cdk atomcontainer and
* detect aromatic rings
*/
if(withAromaticRings || (numberToAddDeuteriums.size() != 0 && numberToAddDeuteriums.get(j) > numberDeuteriums)) {
IAtomContainer container = its.getAtomContainer();
FastBitArray aromaticAtoms = getAromaticAtoms(container);
int[] indeces = aromaticAtoms.getSetIndeces();
if(withAromaticRings) {
for(int i : indeces) {
if(!atomsWithDeuterium.get(toExchange[i])) {
atomsWithDeuterium.set(toExchange[i]);
numberDeuteriums += jios.getAtom(toExchange[i]).getImplicitH();
numberDeuteriumsAromaticExchanged += jios.getAtom(toExchange[i]).getImplicitH();
jios.getAtom(toExchange[i]).setImplicitDeuterium(jios.getAtom(toExchange[i]).getImplicitH());
jios.getAtom(toExchange[i]).setImplicitH(0);
}
}
}
/* else {
Random rand = new Random(1000);
ArrayList<Integer> vec_indeces = new ArrayList<Integer>();
for(int index : indeces) vec_indeces.add(index);
while(numberToAddDeuteriums.get(j) != numberDeuteriums && vec_indeces.size() != 0) {
int atom_index = rand.nextInt(vec_indeces.size());
int atom = vec_indeces.get(atom_index);
vec_indeces.remove(atom_index);
if(!atomsWithDeuterium.get(atom)) {
atomsWithDeuterium.set(atom);
numberDeuteriums += jios.getAtom(atom).getImplicitH();
numberDeuteriumsAromaticExchanged += jios.getAtom(atom).getImplicitH();
jios.getAtom(atom).setImplicitDeuterium(jios.getAtom(atom).getImplicitH());
jios.getAtom(atom).setImplicitH(0);
}
}
}*/
else {
int numberMissing = numberToAddDeuteriums.get(j) - numberDeuteriums;
numberDeuteriums += numberMissing;
numberDeuteriumsAromaticExchanged += numberMissing;
}
}
JniInchiStructure jis = new JniInchiStructure();
jis.setStructure(jios);
JniInchiInput input = new JniInchiInput(jis);
JniInchiOutput output = JniInchiWrapper.getInchi(input);
String inchi = output.getInchi();
HDByteMolecularFormula formula = null;
try {
formula = new HDByteMolecularFormula(inchi.split("/")[1]);
}
catch(Exception e) {
System.err.println(identifiers.get(j));
e.printStackTrace();
System.exit(1);
}
formula.setNumberHydrogens((short)formula.getNumberHydrogens());
formula.setNumberDeuterium((short) numberDeuteriums);
// Identifier|InChI|MolecularFormula|MonoisotopicMass|InChIKey1|InChIKey2|OSN-Deuteriums|AromaticDeuteriums
if(numberToAddDeuteriums.size() == 0 || numberDeuteriums == numberToAddDeuteriums.get(j)) {
double mass = formula.getMonoisotopicMass();
double negMass = mass - Constants.getMonoisotopicMassOfAtom("D") + Constants.ELECTRON_MASS;
if(numberDeuteriumsEasilyExchanged + numberDeuteriumsAromaticExchanged == 0) negMass = mass - Constants.getMonoisotopicMassOfAtom("H") + Constants.ELECTRON_MASS;
System.out.println(identifiers.get(j) + "|" + inchi + "|" + formula.toString() + "|" + mass + "|"
+ JniInchiWrapper.getInchiKey(inchi).getKey().split("-")[0] + "|" + JniInchiWrapper.getInchiKey(inchi).getKey().split("-")[1]
+ "|" + numberDeuteriumsEasilyExchanged + "|" + numberDeuteriumsAromaticExchanged + "|0"
+ "|" + (mass + Constants.getMonoisotopicMassOfAtom("D") - Constants.ELECTRON_MASS)
+ "|" + negMass);
if(bwriter != null) {
bwriter.write(identifiers.get(j) + "|" + inchi + "|" + formula.toString() + "|" + mass + "|"
+ JniInchiWrapper.getInchiKey(inchi).getKey().split("-")[0] + "|" + JniInchiWrapper.getInchiKey(inchi).getKey().split("-")[1]
+ "|" + numberDeuteriumsEasilyExchanged + "|" + numberDeuteriumsAromaticExchanged + "|0"
+ "|" + (mass + Constants.getMonoisotopicMassOfAtom("D") - Constants.ELECTRON_MASS)
+ "|" + negMass);
bwriter.newLine();
}
}
else if(!combinatorial) System.err.println("discarded to many easy exchangeable hydrogens " + numberDeuteriums + " " + identifiers.get(j));
/*
String[] masses = getAllFormulas(formula);
for(int i = 0; i < masses.length; i++) {
System.out.print(masses[i] + " ");
}
System.out.println();
*/
}
if(bwriter != null) bwriter.close();
}
public static void printInfo(JniInchiOutputStructure jios) {
for(int i = 0; i < jios.getNumAtoms(); i++) {
if(jios.getAtom(i).getImplicitDeuterium() > 0) {
System.out.println(jios.getAtom(i).getElementType() + " " + i + " H:" + jios.getAtom(i).getImplicitH() + " D:" + jios.getAtom(i).getImplicitDeuterium());
}
}
}
public static void printInfo(JniInchiInput jios) {
for(int i = 0; i < jios.getNumAtoms(); i++) {
if(jios.getAtom(i).getImplicitDeuterium() > 0) {
System.out.println(jios.getAtom(i).getElementType() + " " + i + " H:" + jios.getAtom(i).getImplicitH() + " D:" + jios.getAtom(i).getImplicitDeuterium());
}
}
}
public static double[] getAllMasses(HDByteMolecularFormula formula) {
short numberDeuterium = formula.getNumberDeuterium();
double[] masses = new double[numberDeuterium];
for(int i = 0; i < masses.length; i++) {
formula.setNumberDeuterium((short)(i + 1));
masses[i] = formula.getMonoisotopicMass();
}
formula.setNumberDeuterium(numberDeuterium);
return masses;
}
public static String[] getAllFormulas(HDByteMolecularFormula formula) {
short numberDeuterium = formula.getNumberDeuterium();
String[] formulas = new String[numberDeuterium];
for(int i = 0; i < formulas.length; i++) {
formula.setNumberDeuterium((short)(i + 1));
formulas[i] = formula.toString();
}
formula.setNumberDeuterium(numberDeuterium);
return formulas;
}
/**
*
* @param elementsToExchange
* @param its
* @return
*/
public static int[] searchForDeuteriumExchangeablePositions(
String[] elementsToExchange, JniInchiOutputStructure its) {
ArrayList<Integer> positionsToExchange = new ArrayList<Integer>();
for (int i = 0; i < its.getNumAtoms(); i++) {
String symbol = its.getAtom(i).getElementType();
if (symbol.equals("H"))
continue;
for (int k = 0; k < elementsToExchange.length; k++) {
if (symbol.equals(elementsToExchange[k]) && its.getAtom(i).getImplicitH() > 0) {
for(int l = 0; l < its.getAtom(i).getImplicitH(); l++) {
positionsToExchange.add(i);
}
break;
}
}
}
int[] array = new int[positionsToExchange.size()];
for(int i = 0; i < positionsToExchange.size(); i++) {
array[i] = positionsToExchange.get(i);
}
return array;
}
public static int[][] getCombinations(int[] toExchange, int numToDraw) {
ArrayList<String> results = new ArrayList<String>();
String[] toDrawFrom = new String[toExchange.length];
for(int i = 0; i < toDrawFrom.length; i++) toDrawFrom[i] = String.valueOf(toExchange[i]);
combinations(toDrawFrom, numToDraw, 0, new String[numToDraw], results);
int[][] combinations = new int[results.size()][numToDraw];
for(int i = 0; i < results.size(); i++) {
String string = results.get(i).replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s+", "");
String[] tmp = string.split(",");
for(int j = 0; j < tmp.length; j++) combinations[i][j] = Integer.parseInt(tmp[j]);
}
return combinations;
}
public static void combinations(String[] arr, int len, int startPosition, String[] result, ArrayList<String> finalResults){
if (len == 0){
finalResults.add(Arrays.toString(result));
return;
}
for (int i = startPosition; i <= arr.length-len; i++){
result[result.length - len] = arr[i];
combinations(arr, len-1, i+1, result, finalResults);
}
}
/**
*
* @param molecule
* @return
*/
public static FastBitArray getAromaticAtoms(IAtomContainer molecule) {
Aromaticity arom = new Aromaticity(ElectronDonation.cdk(),
Cycles.cdkAromaticSet());
FastBitArray aromaticAtoms = new FastBitArray(molecule.getAtomCount());
try {
AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(molecule);
arom.apply(molecule);
Set<IBond> aromaticBonds = arom.findBonds(molecule);
Iterator<IBond> it = aromaticBonds.iterator();
while(it.hasNext()) {
IBond bond = it.next();
for(int k = 0; k < bond.getAtomCount(); k++)
aromaticAtoms.set(molecule.indexOf(bond.getAtom(k)));
}
} catch (CDKException e) {
e.printStackTrace();
}
return aromaticAtoms;
}
}
|
21e0e2e30a7a05440d43493c4df8d54383b1a965
|
[
"Java",
"Maven POM"
] | 3 |
Maven POM
|
meier-rene/MetFragRelaunched
|
fe3d145ed719c1892b3127c97a55620c24c6b1ca
|
482219187e7683c7728e7c11a652c936e4f00f46
|
refs/heads/main
|
<file_sep>import * as actions from '../../action-types'
import Axios from 'axios'
export default{
[actions.ADD_PRODUCT]({commit},payload){
Axios.post('/product', payload)
.then(res=>{
})
.catch(err=>{
})
}
}<file_sep>// for categories
export const SET_CATEGORIES ='SET_CATEGORIES'
// for brands
export const SET_BRANDS ='SET_BRANDS'
// for sizes
export const SET_SIZES ='SET_SIZES'<file_sep><?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CategoriesController;
use App\Http\Controllers\BrandsController;
use App\Http\Controllers\SizesController;
use App\Http\Controllers\ProductsController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::middleware(['auth:sanctum'])->group(function () {
// Category
Route::resource('categories', CategoriesController::class);
Route::get('/api/categories',[CategoriesController::class,'getCategoriesJson']);
// Brand
Route::resource('brands', BrandsController::class);
Route::get('/api/brands',[BrandsController::class,'getBrandsJson']);
// Size
Route::resource('sizes', SizesController::class);
Route::get('/api/sizes',[SizesController::class,'getSizesJson']);
// Product
Route::resource('products', ProductsController::class);
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
|
d20dd228da1a7d77a171a20e0daea6bb0b45ab09
|
[
"JavaScript",
"PHP"
] | 3 |
JavaScript
|
jowel007/IMS
|
01fcfa1e0c8f9d4bf94f7f5b922a1b6b0912d146
|
61f54ab4bda0a3389d2294cb066aff0f304e59a8
|
refs/heads/master
|
<repo_name>Romanua911/simple-mvc<file_sep>/model/Post.php
<?php
class Post {
public $id;
public $author;
public $post_url;
public $format;
public $width;
public $height;
public $filename;
public $author_url;
public function __construct($id,$author,$post_url,$format,$width,$height,$filename,$author_url)
{
$this->id = $id;
$this->author = $author;
$this->post_url = $post_url;
$this->format = $format;
$this->width = $width;
$this->height = $height;
$this->filename = $filename;
$this->author_url = $author_url;
}
}
?><file_sep>/controller/Controller.php
<?php
include_once("model/Model.php");
class Controller {
public $model;
public function __construct()
{
$this->model = new Model();
}
public function invoke()
{
if (!isset($_GET['post']))
{
//show a list of all available posts
$posts = $this->model->getpostList();
include 'view/postlist.php';
}
}
}
?><file_sep>/view/postlist.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Image Gallery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Image Gallery</h2>
<div class="row">
<?php
for($i = 0 ; $i<sizeof($posts); $i++)
{
echo('<div class="col-md-4">
<div class="thumbnail">
<a href="'.$posts[$i]->post_url.'/download?force=true" target="_blank">
<img src="'.$posts[$i]->post_url.'/download?force=true" alt="Lights" style="width:100%">
<div class="caption">
<a href='.$posts[$i]->author_url.'>'.$posts[$i]->author.'</a>
<p> Width:'.$posts[$i]->width.' Height:'.$posts[$i]->height.'</p>
</div>
</a>
</div>
</div>');
if($i % 3>1){
echo('</div><div class="row">');
}
}
?>
</div>
</div>
</body>
</html>
<file_sep>/model/Model.php
<?php
include_once("model/Post.php");
class Model {
// generate not repeat mass number
public function randomix($min, $max, $count) {
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $count);
}
public function getpostList()
{
// here goes some hardcoded values to simulate the database
$url = "https://picsum.photos/list";
$result = file_get_contents($url);
$array = json_decode($result,true);
$listOfItems[] = array();
$magicrandom = $this->randomix(0,sizeof($array),9);
for($i=0;$i<9;$i++){
$listOfItems[$i] = new post(
$array[$magicrandom[$i]]["id"],
$array[$magicrandom[$i]]["author"],
$array[$magicrandom[$i]]["post_url"],
$array[$magicrandom[$i]]["format"],
$array[$magicrandom[$i]]["width"],
$array[$magicrandom[$i]]["height"],
$array[$magicrandom[$i]]["filename"],
$array[$magicrandom[$i]]["author_url"]
);
}
return $listOfItems;
}
}
?><file_sep>/index.php
<?php
//Start point of code
include_once("controller/Controller.php");
$controller = new Controller();
$controller->invoke();
?><file_sep>/test.php
<?php
$url = "https://picsum.photos/list";
$result = file_get_contents($url);
$array = json_decode($result,true);
?>
<table>
<tr>
<th> № </th>
<th>Format</th>
<th>Width</th>
<th>Height</th>
<th>Filename</th>
<th>Id</th>
<th>Author</th>
<th>Author url</th>
<th>Post url</th>
</tr>
<?php
for ($i = 0; $i < sizeof($array); $i++) {
echo("<tr>");
echo("<td> ".$i."</td>");
echo("<td> ".$array[$i]["format"]."</td>");
echo("<td> ".$array[$i]["width"]."</td>");
echo("<td> ".$array[$i]["height"]."</td>");
echo("<td> ".$array[$i]["filename"]."</td>");
echo("<td> ".$array[$i]["id"]."</td>");
echo("<td> ".$array[$i]["author"]."</td>");
echo("<td> ".$array[$i]["author_url"]."</td>");
echo("<td> ".$array[$i]["post_url"]."</td>");
echo("</tr>");
}
?>
</table>
<?php $random = random_int ( 0 , sizeof($array) ) ?>
<img src=" <?php echo $array[$random]["post_url"]."/download?force=true" ?> " alt="some text" style="width:300px">
|
3d50fa095e5a8a095b093a17f75dca48144edb2a
|
[
"PHP"
] | 6 |
PHP
|
Romanua911/simple-mvc
|
5ff4375c1b3934aafa4aae8fc6aa57d830e703de
|
c5b534973f4f7928aae6a24a40543c9a0ed23764
|
refs/heads/master
|
<repo_name>strangesast/open62541_ua_server<file_sep>/nodeset.h
/* WARNING: This is a generated file.
* Any manual changes will be overwritten. */
#ifndef NODESET_H_
#define NODESET_H_
#ifdef UA_ENABLE_AMALGAMATION
# include "open62541.h"
#else
# include <open62541/server.h>
#endif
_UA_BEGIN_DECLS
extern UA_StatusCode nodeset(UA_Server *server);
_UA_END_DECLS
#endif /* NODESET_H_ */
<file_sep>/mtconnect_ids.h
#ifndef MTCONNECT_IDS_H
#define MTCONNECT_IDS_H
#include <map>
#include <string>
#define MT_ASCALESUBCLASSTYPE 2488
#define MT_ABSOLUTESUBCLASSTYPE 2478
#define MT_ACCELERATIONCLASSTYPE 2265
#define MT_ACCUMULATEDTIMECLASSTYPE 2267
#define MT_ACTIONSUBCLASSTYPE 2482
#define MT_ACTIVESTATEDATATYPE 2197
#define MT_ACTIVESTATEDATATYPE_ENUMSTRINGS 2197
#define MT_ACTUALSUBCLASSTYPE 2480
#define MT_ACTUATORCLASSTYPE 2411
#define MT_ACTUATORSTATECLASSTYPE 2146
#define MT_ACTUATORTYPE 2074
#define MT_ALLSUBCLASSTYPE 2484
#define MT_ALTERNATINGSUBCLASSTYPE 2486
#define MT_AMPERAGECLASSTYPE 2273
#define MT_ANGLECLASSTYPE 2275
#define MT_ANGULARACCELERATIONCLASSTYPE 2269
#define MT_ANGULARVELOCITYCLASSTYPE 2271
#define MT_ASSETCHANGEDCLASSTYPE 2405
#define MT_ASSETEVENTDATATYPE 2618
#define MT_ASSETREMOVEDCLASSTYPE 2407
#define MT_AUXILIARIESTYPE 2076
#define MT_AUXILIARYSUBCLASSTYPE 2490
#define MT_AVAILABILITYCLASSTYPE 2149
#define MT_AVAILABILITYDATATYPE 2198
#define MT_AVAILABILITYDATATYPE_ENUMSTRINGS 2198
#define MT_AXESTYPE 2078
#define MT_AXISCOUPLINGCLASSTYPE 2152
#define MT_AXISCOUPLINGDATATYPE 2199
#define MT_AXISCOUPLINGDATATYPE_ENUMSTRINGS 2199
#define MT_AXISFEEDRATECLASSTYPE 2277
#define MT_AXISFEEDRATEOVERRIDECLASSTYPE 2347
#define MT_AXISINTERLOCKCLASSTYPE 2155
#define MT_AXISSTATECLASSTYPE 2158
#define MT_AXISSTATEDATATYPE 2200
#define MT_AXISSTATEDATATYPE_ENUMSTRINGS 2200
#define MT_BSCALESUBCLASSTYPE 2496
#define MT_BADSUBCLASSTYPE 2492
#define MT_BARFEEDERINTERFACETYPE 2080
#define MT_BARFEEDERTYPE 2082
#define MT_BLOCKCLASSTYPE 2363
#define MT_BLOCKCOUNTCLASSTYPE 2349
#define MT_BODYDIAMETERMAXCLASSTYPE 3778
#define MT_BODYDIAMETERMAXCLASSTYPE_CODE 3779
#define MT_BODYDIAMETERMAXCLASSTYPE_UNITS 3780
#define MT_BODYLENGTHMAXCLASSTYPE 3782
#define MT_BODYLENGTHMAXCLASSTYPE_CODE 3783
#define MT_BODYLENGTHMAXCLASSTYPE_UNITS 3784
#define MT_BRINELLSUBCLASSTYPE 2494
#define MT_CSCALESUBCLASSTYPE 2504
#define MT_CHAMFERFLATLENGTHCLASSTYPE 3786
#define MT_CHAMFERFLATLENGTHCLASSTYPE_CODE 3787
#define MT_CHAMFERFLATLENGTHCLASSTYPE_UNITS 3788
#define MT_CHAMFERWIDTHCLASSTYPE 3790
#define MT_CHAMFERWIDTHCLASSTYPE_CODE 3791
#define MT_CHAMFERWIDTHCLASSTYPE_UNITS 3792
#define MT_CHUCKINTERFACETYPE 2084
#define MT_CHUCKINTERLOCKCLASSTYPE 2161
#define MT_CHUCKSTATECLASSTYPE 2164
#define MT_CHUCKTYPE 2086
#define MT_CLOCKTIMECLASSTYPE 2279
#define MT_CLOSECHUCKCLASSTYPE 2256
#define MT_CLOSEDOORCLASSTYPE 2250
#define MT_COMMANDEDSUBCLASSTYPE 2498
#define MT_COMMUNICATIONSCLASSTYPE 2413
#define MT_COMPOSITIONSTATECLASSTYPE 2173
#define MT_COMPOSITIONSTATEDATATYPE 2202
#define MT_COMPOSITIONSTATEDATATYPE_ENUMSTRINGS 2202
#define MT_CONCENTRATIONCLASSTYPE 2281
#define MT_CONDUCTIVITYCLASSTYPE 2283
#define MT_CONTROLSUBCLASSTYPE 2502
#define MT_CONTROLLERMODECLASSTYPE 2167
#define MT_CONTROLLERMODEDATATYPE 2203
#define MT_CONTROLLERMODEDATATYPE_ENUMSTRINGS 2203
#define MT_CONTROLLERMODEOVERRIDECLASSTYPE 2176
#define MT_CONTROLLERTYPE 2088
#define MT_COOLANTTYPE 2090
#define MT_CORNERRADIUSCLASSTYPE 3795
#define MT_CORNERRADIUSCLASSTYPE_CODE 3796
#define MT_CORNERRADIUSCLASSTYPE_UNITS 3797
#define MT_COUNTDIRECTIONDATATYPE 3685
#define MT_COUNTDIRECTIONDATATYPE_ENUMSTRINGS 3685
#define MT_COUPLEDAXESCLASSTYPE 2365
#define MT_CUTTERSTATUSDATATYPE 3686
#define MT_CUTTERSTATUSDATATYPE_ENUMSTRINGS 3686
#define MT_CUTTINGDIAMETERCLASSTYPE 3799
#define MT_CUTTINGDIAMETERCLASSTYPE_CODE 3800
#define MT_CUTTINGDIAMETERCLASSTYPE_UNITS 3801
#define MT_CUTTINGDIAMETERMAXTYPE 3803
#define MT_CUTTINGDIAMETERMAXTYPE_CODE 3804
#define MT_CUTTINGDIAMETERMAXTYPE_UNITS 3805
#define MT_CUTTINGEDGELENGTHCLASSTYPE 3807
#define MT_CUTTINGEDGELENGTHCLASSTYPE_CODE 3808
#define MT_CUTTINGEDGELENGTHCLASSTYPE_UNITS 3809
#define MT_CUTTINGHEIGHTCLASSTYPE 3811
#define MT_CUTTINGHEIGHTCLASSTYPE_CODE 3812
#define MT_CUTTINGHEIGHTCLASSTYPE_UNITS 3813
#define MT_CUTTINGITEMCLASSTYPE 3815
#define MT_CUTTINGITEMFUNCTIONALLENGTHCLASSTYPE 3817
#define MT_CUTTINGITEMFUNCTIONALLENGTHCLASSTYPE_CODE 3818
#define MT_CUTTINGITEMFUNCTIONALLENGTHCLASSTYPE_UNITS 3819
#define MT_CUTTINGITEMWEIGHTCLASSTYPE 3821
#define MT_CUTTINGITEMWEIGHTCLASSTYPE_CODE 3822
#define MT_CUTTINGITEMWEIGHTCLASSTYPE_UNITS 3823
#define MT_CUTTINGTOOLCLASSTYPE 3825
#define MT_CUTTINGTOOLCLASSTYPE_CODE 3826
#define MT_CUTTINGTOOLCLASSTYPE_UNITS 3827
#define MT_CUTTINGTOOLDEFINTIONFORMATDATATYPE 3687
#define MT_CUTTINGTOOLDEFINTIONFORMATDATATYPE_ENUMSTRINGS 3687
#define MT_DSCALESUBCLASSTYPE 2512
#define MT_DATARANGECLASSTYPE 2415
#define MT_DELAYSUBCLASSTYPE 2506
#define MT_DEPTHOFCUTMAXCLASSTYPE 3829
#define MT_DEPTHOFCUTMAXCLASSTYPE_CODE 3830
#define MT_DEPTHOFCUTMAXCLASSTYPE_UNITS 3831
#define MT_DIELECTRICTYPE 2092
#define MT_DIRECTSUBCLASSTYPE 2508
#define MT_DIRECTIONCLASSTYPE 2179
#define MT_DIRECTIONDATATYPE 2205
#define MT_DIRECTIONDATATYPE_ENUMSTRINGS 2205
#define MT_DISPLACEMENTCLASSTYPE 2285
#define MT_DOORINTERFACETYPE 2094
#define MT_DOORSTATECLASSTYPE 2182
#define MT_DOORTYPE 2096
#define MT_DRIVEANGLECLASSTYPE 3833
#define MT_DRIVEANGLECLASSTYPE_CODE 3834
#define MT_DRIVEANGLECLASSTYPE_UNITS 3835
#define MT_DRYRUNSUBCLASSTYPE 2510
#define MT_ELECTRICTYPE 2098
#define MT_ELECTRICALENERGYCLASSTYPE 2287
#define MT_EMERGENCYSTOPCLASSTYPE 2185
#define MT_EMERGENCYSTOPDATATYPE 2207
#define MT_EMERGENCYSTOPDATATYPE_ENUMSTRINGS 2207
#define MT_ENCLOSURETYPE 2100
#define MT_ENDOFBARCLASSTYPE 2188
#define MT_ENVIRONMENTALTYPE 2102
#define MT_EQUIPMENTMODECLASSTYPE 2191
#define MT_EQUIPMENTTIMERCLASSTYPE 2289
#define MT_EXECUTIONCLASSTYPE 2170
#define MT_EXECUTIONDATATYPE 2262
#define MT_EXECUTIONDATATYPE_ENUMSTRINGS 2262
#define MT_FEEDERTYPE 2104
#define MT_FILLLEVELCLASSTYPE 2291
#define MT_FIXTURESUBCLASSTYPE 2514
#define MT_FLANGEDIAMETERCLASSTYPE 3837
#define MT_FLANGEDIAMETERCLASSTYPE_CODE 3838
#define MT_FLANGEDIAMETERCLASSTYPE_UNITS 3839
#define MT_FLANGEDIAMETERMAXCLASSTYPE 3841
#define MT_FLANGEDIAMETERMAXCLASSTYPE_CODE 3842
#define MT_FLANGEDIAMETERMAXCLASSTYPE_UNITS 3843
#define MT_FLOWCLASSTYPE 2293
#define MT_FREQUENCYCLASSTYPE 2295
#define MT_FUNCTIONALLENGTHCLASSTYPE 3845
#define MT_FUNCTIONALLENGTHCLASSTYPE_FUNCTIONALLENGTH 3846
#define MT_FUNCTIONALLENGTHCLASSTYPE_UNITS 3847
#define MT_FUNCTIONALMODECLASSTYPE 2194
#define MT_FUNCTIONALMODEDATATYPE 2208
#define MT_FUNCTIONALMODEDATATYPE_ENUMSTRINGS 2208
#define MT_FUNCTIONALWIDTHCLASSTYPE 3849
#define MT_FUNCTIONALWIDTHCLASSTYPE_CODE 3850
#define MT_FUNCTIONALWIDTHCLASSTYPE_UNITS 3851
#define MT_GOODSUBCLASSTYPE 2500
#define MT_HARDNESSCLASSTYPE 2351
#define MT_HARDWARECLASSTYPE 2419
#define MT_HASMTCLASSTYPE 2680
#define MT_HASMTCOMPOSITION 2687
#define MT_HASMTREFERENCE 2672
#define MT_HASMTSOURCE 2689
#define MT_HASMTSUBCLASSTYPE 2683
#define MT_HYDRAULICTYPE 2106
#define MT_INCREMENTALSUBCLASSTYPE 2516
#define MT_INCRIBEDCIRCLEDIAMETERCLASSTYPE 3853
#define MT_INCRIBEDCIRCLEDIAMETERCLASSTYPE_CODE 3854
#define MT_INCRIBEDCIRCLEDIAMETERCLASSTYPE_UNITS 3855
#define MT_INSERTWIDTHCLASSTYPE 3857
#define MT_INSERTWIDTHCLASSTYPE_CODE 3858
#define MT_INSERTWIDTHCLASSTYPE_UNITS 3859
#define MT_INTERFACESTATECLASSTYPE 2227
#define MT_INTERFACESTATEDATATYPE 2234
#define MT_INTERFACESTATEDATATYPE_ENUMSTRINGS 2234
#define MT_INTERFACESTATUSDATATYPE 2230
#define MT_INTERFACESTATUSDATATYPE_ENUMSTRINGS 2230
#define MT_INTERFACESTYPE 2108
#define MT_JOBSUBCLASSTYPE 2518
#define MT_KINETICSUBCLASSTYPE 2520
#define MT_LATERALSUBCLASSTYPE 2522
#define MT_LEEBSUBCLASSTYPE 2524
#define MT_LENGTHCLASSTYPE 2297
#define MT_LENGTHSUBCLASSTYPE 2526
#define MT_LINECLASSTYPE 2409
#define MT_LINELABELCLASSTYPE 2367
#define MT_LINENUMBERCLASSTYPE 2353
#define MT_LINESUBCLASSTYPE 2530
#define MT_LINEARFORCECLASSTYPE 2299
#define MT_LINEARSUBCLASSTYPE 2528
#define MT_LINEARTYPE 2110
#define MT_LOADCLASSTYPE 2263
#define MT_LOADEDSUBCLASSTYPE 2532
#define MT_LOADERTYPE 2112
#define MT_LOGICPROGRAMCLASSTYPE 2417
#define MT_LUBRICATIONTYPE 2114
#define MT_MTASSETEVENTTYPE 2621
#define MT_MTASSETEVENTTYPE_CATEGORY 2753
#define MT_MTASSETEVENTTYPE_CONSTRAINTS 2760
#define MT_MTASSETEVENTTYPE_CONSTRAINTS_MAXIMUM 2763
#define MT_MTASSETEVENTTYPE_CONSTRAINTS_MINIMUM 2762
#define MT_MTASSETEVENTTYPE_CONSTRAINTS_NOMINAL 2764
#define MT_MTASSETEVENTTYPE_CONSTRAINTS_VALUES 2761
#define MT_MTASSETEVENTTYPE_MTSUBTYPENAME 2755
#define MT_MTASSETEVENTTYPE_MTTYPENAME 2754
#define MT_MTASSETEVENTTYPE_NAME 2752
#define MT_MTASSETEVENTTYPE_PERIODFILTER 2759
#define MT_MTASSETEVENTTYPE_REPRESENTATION 2758
#define MT_MTASSETEVENTTYPE_SAMPLERATE 2757
#define MT_MTASSETEVENTTYPE_SOURCEDATA 2756
#define MT_MTASSETEVENTTYPE_XMLID 2751
#define MT_MTASSETTYPE 3678
#define MT_MTASSETTYPE_ASSETID 3679
#define MT_MTASSETTYPE_DEVICEUUID 3680
#define MT_MTASSETTYPE_MTDESCRIPTION 3681
#define MT_MTASSETTYPE_REMOVED 3682
#define MT_MTASSETTYPE_TIMESTAMP 3683
#define MT_MTCATEGORYTYPE 2634
#define MT_MTCATEGORYTYPE_ENUMSTRINGS 2634
#define MT_MTCHANNELTYPE 2059
#define MT_MTCHANNELTYPE_CALIBRATIONDATE 2063
#define MT_MTCHANNELTYPE_CALIBRATIONINITIALS 2065
#define MT_MTCHANNELTYPE_MTDESCRIPTION 2062
#define MT_MTCHANNELTYPE_NAME 2061
#define MT_MTCHANNELTYPE_NEXTCALIBRATIONDATE 2064
#define MT_MTCHANNELTYPE_NUMBER 2060
#define MT_MTCOMPONENTTYPE 2021
#define MT_MTCOMPONENTTYPE_COMPONENTS 2042
#define MT_MTCOMPONENTTYPE_COMPOSITIONS 2043
#define MT_MTCOMPONENTTYPE_CONFIGURATION 2029
#define MT_MTCOMPONENTTYPE_DESCRIPTION 2028
#define MT_MTCOMPONENTTYPE_DESCRIPTION_DATA 2740
#define MT_MTCOMPONENTTYPE_DESCRIPTION_MANUFACTURER 2739
#define MT_MTCOMPONENTTYPE_DESCRIPTION_SERIALNUMBER 2738
#define MT_MTCOMPONENTTYPE_DESCRIPTION_STATION 2737
#define MT_MTCOMPONENTTYPE_NAME 2023
#define MT_MTCOMPONENTTYPE_NATIVENAME 2024
#define MT_MTCOMPONENTTYPE_SAMPLEINTERVAL 2027
#define MT_MTCOMPONENTTYPE_SAMPLERATE 2026
#define MT_MTCOMPONENTTYPE_UUID 2025
#define MT_MTCOMPONENTTYPE_XMLID 2022
#define MT_MTCOMPOSITIONTYPE 2067
#define MT_MTCOMPOSITIONTYPE_MTTYPENAME 2069
#define MT_MTCOMPOSITIONTYPE_NAME 2071
#define MT_MTCOMPOSITIONTYPE_UUID 2070
#define MT_MTCOMPOSITIONTYPE_XMLID 2068
#define MT_MTCONDITIONCLASSTYPE 2629
#define MT_MTCONDITIONEVENTTYPE 4326
#define MT_MTCONDITIONEVENTTYPE_ACTIVESTATE 4336
#define MT_MTCONDITIONEVENTTYPE_DATAITEMID 4327
#define MT_MTCONDITIONEVENTTYPE_MTSEVERITY 4328
#define MT_MTCONDITIONEVENTTYPE_MTSUBTYPENAME 4329
#define MT_MTCONDITIONEVENTTYPE_MTTYPENAME 4330
#define MT_MTCONDITIONEVENTTYPE_NATIVECODE 4331
#define MT_MTCONDITIONEVENTTYPE_NATIVESEVERITY 4332
#define MT_MTCONDITIONEVENTTYPE_QUALIFIER 4333
#define MT_MTCONDITIONTYPE 2660
#define MT_MTCONDITIONTYPE_CATEGORY 2917
#define MT_MTCONDITIONTYPE_CONSTRAINTS 2924
#define MT_MTCONDITIONTYPE_CONSTRAINTS_MAXIMUM 2927
#define MT_MTCONDITIONTYPE_CONSTRAINTS_MINIMUM 2926
#define MT_MTCONDITIONTYPE_CONSTRAINTS_NOMINAL 2928
#define MT_MTCONDITIONTYPE_CONSTRAINTS_VALUES 2925
#define MT_MTCONDITIONTYPE_MTSUBTYPENAME 2919
#define MT_MTCONDITIONTYPE_MTTYPENAME 2918
#define MT_MTCONDITIONTYPE_NAME 2916
#define MT_MTCONDITIONTYPE_PERIODFILTER 2923
#define MT_MTCONDITIONTYPE_REPRESENTATION 2922
#define MT_MTCONDITIONTYPE_SAMPLERATE 2921
#define MT_MTCONDITIONTYPE_SOURCEDATA 2920
#define MT_MTCONDITIONTYPE_XMLID 2915
#define MT_MTCONFIGURATIONTYPE 2044
#define MT_MTCONSTRAINTTYPE 2647
#define MT_MTCONSTRAINTTYPE_MAXIMUM 2650
#define MT_MTCONSTRAINTTYPE_MINIMUM 2649
#define MT_MTCONSTRAINTTYPE_NOMINAL 2651
#define MT_MTCONSTRAINTTYPE_VALUES 2648
#define MT_MTCONTROLLEDVOCABEVENTCLASSTYPE 2144
#define MT_MTCONTROLLEDVOCABEVENTTYPE 2626
#define MT_MTCONTROLLEDVOCABEVENTTYPE_CATEGORY 2773
#define MT_MTCONTROLLEDVOCABEVENTTYPE_CONSTRAINTS 2780
#define MT_MTCONTROLLEDVOCABEVENTTYPE_CONSTRAINTS_MAXIMUM 2783
#define MT_MTCONTROLLEDVOCABEVENTTYPE_CONSTRAINTS_MINIMUM 2782
#define MT_MTCONTROLLEDVOCABEVENTTYPE_CONSTRAINTS_NOMINAL 2784
#define MT_MTCONTROLLEDVOCABEVENTTYPE_CONSTRAINTS_VALUES 2781
#define MT_MTCONTROLLEDVOCABEVENTTYPE_MTSUBTYPENAME 2775
#define MT_MTCONTROLLEDVOCABEVENTTYPE_MTTYPENAME 2774
#define MT_MTCONTROLLEDVOCABEVENTTYPE_NAME 2772
#define MT_MTCONTROLLEDVOCABEVENTTYPE_PERIODFILTER 2779
#define MT_MTCONTROLLEDVOCABEVENTTYPE_REPRESENTATION 2778
#define MT_MTCONTROLLEDVOCABEVENTTYPE_SAMPLERATE 2777
#define MT_MTCONTROLLEDVOCABEVENTTYPE_SOURCEDATA 2776
#define MT_MTCONTROLLEDVOCABEVENTTYPE_VALUEASTEXT 3090
#define MT_MTCONTROLLEDVOCABEVENTTYPE_XMLID 2771
#define MT_MTCOORDINATESYSTEMTYPE 2635
#define MT_MTCOORDINATESYSTEMTYPE_ENUMSTRINGS 2635
#define MT_MTCUTTERSTATUSTYPE 3690
#define MT_MTCUTTINGITEMTYPE 3697
#define MT_MTCUTTINGITEMTYPE_CUTTERSTATUS 3706
#define MT_MTCUTTINGITEMTYPE_CUTTERSTATUS_DEFINITION 3926
#define MT_MTCUTTINGITEMTYPE_CUTTERSTATUS_ENUMSTRINGS 3928
#define MT_MTCUTTINGITEMTYPE_CUTTERSTATUS_VALUEPRECISION 3927
#define MT_MTCUTTINGITEMTYPE_GRADE 3698
#define MT_MTCUTTINGITEMTYPE_INDICES 3699
#define MT_MTCUTTINGITEMTYPE_ITEMID 3700
#define MT_MTCUTTINGITEMTYPE_LOCUS 3701
#define MT_MTCUTTINGITEMTYPE_MTDESCRIPTION 3703
#define MT_MTCUTTINGITEMTYPE_MANUFACTURES 3702
#define MT_MTCUTTINGITEMTYPE_MINUTESITEMLIFE 3705
#define MT_MTCUTTINGITEMTYPE_MINUTESITEMLIFE_COUNTDIRECTION 3919
#define MT_MTCUTTINGITEMTYPE_MINUTESITEMLIFE_DATATYPE 4263
#define MT_MTCUTTINGITEMTYPE_MINUTESITEMLIFE_DEFINITION 3917
#define MT_MTCUTTINGITEMTYPE_MINUTESITEMLIFE_INITIAL 3921
#define MT_MTCUTTINGITEMTYPE_MINUTESITEMLIFE_LIMIT 3922
#define MT_MTCUTTINGITEMTYPE_MINUTESITEMLIFE_MTTYPE 3923
#define MT_MTCUTTINGITEMTYPE_MINUTESITEMLIFE_VALUEPRECISION 3918
#define MT_MTCUTTINGITEMTYPE_MINUTESITEMLIFE_VALUERANK 4264
#define MT_MTCUTTINGITEMTYPE_MINUTESITEMLIFE_WARNING 3925
#define MT_MTCUTTINGITEMTYPE_PARTCOUNTITEMLIFE 3707
#define MT_MTCUTTINGITEMTYPE_PARTCOUNTITEMLIFE_COUNTDIRECTION 3932
#define MT_MTCUTTINGITEMTYPE_PARTCOUNTITEMLIFE_DATATYPE 4265
#define MT_MTCUTTINGITEMTYPE_PARTCOUNTITEMLIFE_DEFINITION 3930
#define MT_MTCUTTINGITEMTYPE_PARTCOUNTITEMLIFE_INITIAL 3934
#define MT_MTCUTTINGITEMTYPE_PARTCOUNTITEMLIFE_LIMIT 3935
#define MT_MTCUTTINGITEMTYPE_PARTCOUNTITEMLIFE_MTTYPE 3936
#define MT_MTCUTTINGITEMTYPE_PARTCOUNTITEMLIFE_VALUEPRECISION 3931
#define MT_MTCUTTINGITEMTYPE_PARTCOUNTITEMLIFE_VALUERANK 4266
#define MT_MTCUTTINGITEMTYPE_PARTCOUNTITEMLIFE_WARNING 3938
#define MT_MTCUTTINGITEMTYPE_WEARITEMLIFE 3709
#define MT_MTCUTTINGITEMTYPE_WEARITEMLIFE_COUNTDIRECTION 3941
#define MT_MTCUTTINGITEMTYPE_WEARITEMLIFE_DATATYPE 4267
#define MT_MTCUTTINGITEMTYPE_WEARITEMLIFE_DEFINITION 3939
#define MT_MTCUTTINGITEMTYPE_WEARITEMLIFE_INITIAL 3943
#define MT_MTCUTTINGITEMTYPE_WEARITEMLIFE_LIMIT 3944
#define MT_MTCUTTINGITEMTYPE_WEARITEMLIFE_MTTYPE 3945
#define MT_MTCUTTINGITEMTYPE_WEARITEMLIFE_VALUEPRECISION 3940
#define MT_MTCUTTINGITEMTYPE_WEARITEMLIFE_VALUERANK 4268
#define MT_MTCUTTINGITEMTYPE_WEARITEMLIFE_WARNING 3947
#define MT_MTCUTTINGTOOLARCHETYPETYPE 3710
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLDEFINITION 3716
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLDEFINITION_DATA 4017
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLDEFINITION_DATA_MIMETYPE 4018
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLDEFINITION_DATA_OPENCOUNT 4019
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLDEFINITION_DATA_SIZE 4020
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLDEFINITION_DATA_USERWRITABLE 4021
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLDEFINITION_DATA_WRITABLE 4022
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLDEFINITION_FORMAT 4016
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE 3715
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_CONNECTIONCODEMACHINESIDE 3948
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS 3951
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS_DEFINITION 3952
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS_ENUMSTRINGS 3954
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS_VALUEPRECISION 3953
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_LOCATION 3998
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_LOCATION_DATATYPE 4279
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_LOCATION_DEFINITION 3999
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_LOCATION_NEGATIVEOVERLAP 4002
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_LOCATION_POSITIVEOVERLAP 4003
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_LOCATION_TYPE 4004
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_LOCATION_VALUEPRECISION 4000
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_LOCATION_VALUERANK 4280
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE 3976
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_DATATYPE 4273
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_DEFINITION 3977
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_MAXIMUM 3980
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_MINIMUM 3981
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_NOMINAL 3982
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_VALUEPRECISION 3978
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_VALUERANK 4274
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED 3990
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_DATATYPE 4277
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_DEFINITION 3991
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_MAXIMUM 3994
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_MINIMUM 3995
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_NOMINAL 3996
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_VALUEPRECISION 3992
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_VALUERANK 4278
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROGRAMTOOLGROUP 3949
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_PROGRAMTOOLNUMBER 3950
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT 3984
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_DATATYPE 4275
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_DEFINITION 3985
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_MAXIMUMCOUNT 3988
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_VALUEPRECISION 3986
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_VALUERANK 4276
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES 4006
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_COUNTDIRECTION 4009
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_DATATYPE 4281
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_DEFINITION 4007
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_INITIAL 4011
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_LIMIT 4012
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_MTTYPE 4013
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_VALUEPRECISION 4008
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_VALUERANK 4282
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_WARNING 4015
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT 3956
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_COUNTDIRECTION 3959
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_DATATYPE 4269
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_DEFINITION 3957
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_INITIAL 3961
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_LIMIT 3962
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_MTTYPE 3963
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_VALUEPRECISION 3958
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_VALUERANK 4270
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_WARNING 3965
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR 3966
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_COUNTDIRECTION 3969
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_DATATYPE 4271
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_DEFINITION 3967
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_INITIAL 3971
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_LIMIT 3972
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_MTTYPE 3973
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_VALUEPRECISION 3968
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_VALUERANK 4272
#define MT_MTCUTTINGTOOLARCHETYPETYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_WARNING 3975
#define MT_MTCUTTINGTOOLARCHETYPETYPE_MANUFACTURERS 3711
#define MT_MTCUTTINGTOOLARCHETYPETYPE_SERIALNUMBER 3712
#define MT_MTCUTTINGTOOLARCHETYPETYPE_TOOLID 3713
#define MT_MTCUTTINGTOOLCONSTRAINTTYPE 3717
#define MT_MTCUTTINGTOOLCONSTRAINTTYPE_DATATYPE 3718
#define MT_MTCUTTINGTOOLCONSTRAINTTYPE_MAXIMUM 3719
#define MT_MTCUTTINGTOOLCONSTRAINTTYPE_MINIMUM 3720
#define MT_MTCUTTINGTOOLCONSTRAINTTYPE_NOMINAL 3721
#define MT_MTCUTTINGTOOLCONSTRAINTTYPE_VALUERANK 3722
#define MT_MTCUTTINGTOOLDEFINITIONTYPE 3724
#define MT_MTCUTTINGTOOLDEFINITIONTYPE_DATA 3727
#define MT_MTCUTTINGTOOLDEFINITIONTYPE_DATA_MIMETYPE 4023
#define MT_MTCUTTINGTOOLDEFINITIONTYPE_DATA_OPENCOUNT 4024
#define MT_MTCUTTINGTOOLDEFINITIONTYPE_DATA_SIZE 4025
#define MT_MTCUTTINGTOOLDEFINITIONTYPE_DATA_USERWRITABLE 4026
#define MT_MTCUTTINGTOOLDEFINITIONTYPE_DATA_WRITABLE 4027
#define MT_MTCUTTINGTOOLDEFINITIONTYPE_FORMAT 3725
#define MT_MTCUTTINGTOOLLIFECYCLETYPE 3728
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_CONNECTIONCODEMACHINESIDE 3729
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_CUTTERSTATUS 3733
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_CUTTERSTATUS_DEFINITION 4028
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_CUTTERSTATUS_ENUMSTRINGS 4030
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_CUTTERSTATUS_VALUEPRECISION 4029
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_LOCATION 3740
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_LOCATION_DATATYPE 4293
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_LOCATION_DEFINITION 4069
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_LOCATION_NEGATIVEOVERLAP 4072
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_LOCATION_POSITIVEOVERLAP 4073
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_LOCATION_TYPE 4074
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_LOCATION_VALUEPRECISION 4070
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_LOCATION_VALUERANK 4294
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSFEEDRATE 3736
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSFEEDRATE_DATATYPE 4287
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSFEEDRATE_DEFINITION 4050
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSFEEDRATE_MAXIMUM 4053
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSFEEDRATE_MINIMUM 4054
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSFEEDRATE_NOMINAL 4055
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSFEEDRATE_VALUEPRECISION 4051
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSFEEDRATE_VALUERANK 4288
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSSPINDLESPEED 3739
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSSPINDLESPEED_DATATYPE 4291
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSSPINDLESPEED_DEFINITION 4062
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSSPINDLESPEED_MAXIMUM 4065
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSSPINDLESPEED_MINIMUM 4066
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSSPINDLESPEED_NOMINAL 4067
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSSPINDLESPEED_VALUEPRECISION 4063
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROCESSSPINDLESPEED_VALUERANK 4292
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROGRAMTOOLGROUP 3730
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_PROGRAMTOOLNUMBER 3731
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_RECONDITIONCOUNT 3737
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_RECONDITIONCOUNT_DATATYPE 4289
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_RECONDITIONCOUNT_DEFINITION 4057
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_RECONDITIONCOUNT_MAXIMUMCOUNT 4060
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_RECONDITIONCOUNT_VALUEPRECISION 4058
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_RECONDITIONCOUNT_VALUERANK 4290
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEMINUTES 3741
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEMINUTES_COUNTDIRECTION 4078
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEMINUTES_DATATYPE 4295
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEMINUTES_DEFINITION 4076
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEMINUTES_INITIAL 4080
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEMINUTES_LIMIT 4081
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEMINUTES_MTTYPE 4082
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEMINUTES_VALUEPRECISION 4077
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEMINUTES_VALUERANK 4296
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEMINUTES_WARNING 4084
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEPARTCOUNT 3734
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEPARTCOUNT_COUNTDIRECTION 4034
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEPARTCOUNT_DATATYPE 4283
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEPARTCOUNT_DEFINITION 4032
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEPARTCOUNT_INITIAL 4036
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEPARTCOUNT_LIMIT 4037
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEPARTCOUNT_MTTYPE 4038
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEPARTCOUNT_VALUEPRECISION 4033
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEPARTCOUNT_VALUERANK 4284
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEPARTCOUNT_WARNING 4040
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEWEAR 3735
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEWEAR_COUNTDIRECTION 4043
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEWEAR_DATATYPE 4285
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEWEAR_DEFINITION 4041
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEWEAR_INITIAL 4045
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEWEAR_LIMIT 4046
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEWEAR_MTTYPE 4047
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEWEAR_VALUEPRECISION 4042
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEWEAR_VALUERANK 4286
#define MT_MTCUTTINGTOOLLIFECYCLETYPE_TOOLLIFEWEAR_WARNING 4049
#define MT_MTCUTTINGTOOLMEASUREMENTTYPE 3742
#define MT_MTCUTTINGTOOLMEASUREMENTTYPE_CODE 3743
#define MT_MTCUTTINGTOOLMEASUREMENTTYPE_ENGINERINGUNITS 3744
#define MT_MTCUTTINGTOOLMEASUREMENTTYPE_NATIVEUNITS 3745
#define MT_MTCUTTINGTOOLMEASUREMENTTYPE_SIGNIFICANTDIGITS 3746
#define MT_MTCUTTINGTOOLMEASUREMENTTYPE_UNITS 3747
#define MT_MTCUTTINGTOOLTYPE 3750
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE 3755
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_ASSETID 4085
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLDEFINITION 4162
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLDEFINITION_DATA 4164
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLDEFINITION_DATA_MIMETYPE 4165
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLDEFINITION_DATA_OPENCOUNT 4166
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLDEFINITION_DATA_SIZE 4167
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLDEFINITION_DATA_USERWRITABLE 4168
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLDEFINITION_DATA_WRITABLE 4169
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLDEFINITION_FORMAT 4163
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE 4093
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_CONNECTIONCODEMACHINESIDE 4094
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS 4097
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS_DEFINITION 4098
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS_ENUMSTRINGS 4100
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS_VALUEPRECISION 4099
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_LOCATION 4144
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_LOCATION_DATATYPE 4307
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_LOCATION_DEFINITION 4145
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_LOCATION_NEGATIVEOVERLAP 4148
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_LOCATION_POSITIVEOVERLAP 4149
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_LOCATION_TYPE 4150
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_LOCATION_VALUEPRECISION 4146
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_LOCATION_VALUERANK 4308
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE 4122
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_DATATYPE 4301
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_DEFINITION 4123
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_MAXIMUM 4126
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_MINIMUM 4127
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_NOMINAL 4128
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_VALUEPRECISION 4124
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_VALUERANK 4302
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED 4136
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_DATATYPE 4305
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_DEFINITION 4137
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_MAXIMUM 4140
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_MINIMUM 4141
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_NOMINAL 4142
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_VALUEPRECISION 4138
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_VALUERANK 4306
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROGRAMTOOLGROUP 4095
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_PROGRAMTOOLNUMBER 4096
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT 4130
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_DATATYPE 4303
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_DEFINITION 4131
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_MAXIMUMCOUNT 4134
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_VALUEPRECISION 4132
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_VALUERANK 4304
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES 4152
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_COUNTDIRECTION 4155
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_DATATYPE 4309
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_DEFINITION 4153
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_INITIAL 4157
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_LIMIT 4158
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_MTTYPE 4159
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_VALUEPRECISION 4154
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_VALUERANK 4310
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_WARNING 4161
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT 4102
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_COUNTDIRECTION 4105
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_DATATYPE 4297
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_DEFINITION 4103
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_INITIAL 4107
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_LIMIT 4108
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_MTTYPE 4109
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_VALUEPRECISION 4104
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_VALUERANK 4298
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_WARNING 4111
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR 4112
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_COUNTDIRECTION 4115
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_DATATYPE 4299
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_DEFINITION 4113
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_INITIAL 4117
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_LIMIT 4118
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_MTTYPE 4119
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_VALUEPRECISION 4114
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_VALUERANK 4300
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_WARNING 4121
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_DEVICEUUID 4086
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_MTDESCRIPTION 4087
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_MANUFACTURERS 4090
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_REMOVED 4088
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_SERIALNUMBER 4091
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_TIMESTAMP 4089
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLARCHITYPE_TOOLID 4092
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE 3756
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_CONNECTIONCODEMACHINESIDE 4170
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS 4173
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS_DEFINITION 4174
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS_ENUMSTRINGS 4176
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_CUTTERSTATUS_VALUEPRECISION 4175
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_LOCATION 4220
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_LOCATION_DATATYPE 4321
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_LOCATION_DEFINITION 4221
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_LOCATION_NEGATIVEOVERLAP 4224
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_LOCATION_POSITIVEOVERLAP 4225
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_LOCATION_TYPE 4226
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_LOCATION_VALUEPRECISION 4222
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_LOCATION_VALUERANK 4322
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE 4198
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_DATATYPE 4315
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_DEFINITION 4199
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_MAXIMUM 4202
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_MINIMUM 4203
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_NOMINAL 4204
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_VALUEPRECISION 4200
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSFEEDRATE_VALUERANK 4316
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED 4212
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_DATATYPE 4319
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_DEFINITION 4213
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_MAXIMUM 4216
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_MINIMUM 4217
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_NOMINAL 4218
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_VALUEPRECISION 4214
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROCESSSPINDLESPEED_VALUERANK 4320
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROGRAMTOOLGROUP 4171
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_PROGRAMTOOLNUMBER 4172
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT 4206
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_DATATYPE 4317
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_DEFINITION 4207
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_MAXIMUMCOUNT 4210
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_VALUEPRECISION 4208
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_RECONDITIONCOUNT_VALUERANK 4318
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES 4228
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_COUNTDIRECTION 4231
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_DATATYPE 4323
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_DEFINITION 4229
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_INITIAL 4233
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_LIMIT 4234
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_MTTYPE 4235
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_VALUEPRECISION 4230
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_VALUERANK 4324
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEMINUTES_WARNING 4237
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT 4178
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_COUNTDIRECTION 4181
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_DATATYPE 4311
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_DEFINITION 4179
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_INITIAL 4183
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_LIMIT 4184
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_MTTYPE 4185
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_VALUEPRECISION 4180
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_VALUERANK 4312
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEPARTCOUNT_WARNING 4187
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR 4188
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_COUNTDIRECTION 4191
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_DATATYPE 4313
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_DEFINITION 4189
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_INITIAL 4193
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_LIMIT 4194
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_MTTYPE 4195
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_VALUEPRECISION 4190
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_VALUERANK 4314
#define MT_MTCUTTINGTOOLTYPE_CUTTINGTOOLLIFECYCLE_TOOLLIFEWEAR_WARNING 4197
#define MT_MTCUTTINGTOOLTYPE_MANUFACTURERS 3751
#define MT_MTCUTTINGTOOLTYPE_SERIALNUMBER 3752
#define MT_MTCUTTINGTOOLTYPE_TOOLID 3753
#define MT_MTDATAITEMCLASSTYPE 2425
#define MT_MTDATAITEMSUBCLASSTYPE 2476
#define MT_MTDESCRIPTIONTYPE 2053
#define MT_MTDESCRIPTIONTYPE_DATA 2057
#define MT_MTDESCRIPTIONTYPE_MANUFACTURER 2056
#define MT_MTDESCRIPTIONTYPE_SERIALNUMBER 2055
#define MT_MTDESCRIPTIONTYPE_STATION 2054
#define MT_MTDEVICETYPE 2015
#define MT_MTDEVICETYPE_ISO841CLASS 2017
#define MT_MTDEVICETYPE_NAME 3668
#define MT_MTDEVICETYPE_UUID 3669
#define MT_MTDEVICETYPE_VERSION 2016
#define MT_MTEVENTCLASSTYPE 2631
#define MT_MTLOCATIONDATATYPE 3688
#define MT_MTLOCATIONDATATYPE_ENUMSTRINGS 3688
#define MT_MTLOCATIONTYPE 3757
#define MT_MTLOCATIONTYPE_DATATYPE 3758
#define MT_MTLOCATIONTYPE_NEGATIVEOVERLAP 3759
#define MT_MTLOCATIONTYPE_POSITIVEOVERLAP 3760
#define MT_MTLOCATIONTYPE_TYPE 3761
#define MT_MTLOCATIONTYPE_VALUERANK 3762
#define MT_MTMESSAGECLASSTYPE 2427
#define MT_MTMESSAGEEVENTTYPE 2656
#define MT_MTMESSAGEEVENTTYPE_NATIVECODE 2657
#define MT_MTMESSAGETYPE 2471
#define MT_MTMESSAGETYPE_CATEGORY 2793
#define MT_MTMESSAGETYPE_CONSTRAINTS 2800
#define MT_MTMESSAGETYPE_CONSTRAINTS_MAXIMUM 2803
#define MT_MTMESSAGETYPE_CONSTRAINTS_MINIMUM 2802
#define MT_MTMESSAGETYPE_CONSTRAINTS_NOMINAL 2804
#define MT_MTMESSAGETYPE_CONSTRAINTS_VALUES 2801
#define MT_MTMESSAGETYPE_MTSUBTYPENAME 2795
#define MT_MTMESSAGETYPE_MTTYPENAME 2794
#define MT_MTMESSAGETYPE_NAME 2792
#define MT_MTMESSAGETYPE_PERIODFILTER 2799
#define MT_MTMESSAGETYPE_REPRESENTATION 2798
#define MT_MTMESSAGETYPE_SAMPLERATE 2797
#define MT_MTMESSAGETYPE_SOURCEDATA 2796
#define MT_MTMESSAGETYPE_XMLID 2791
#define MT_MTNUMERICEVENTCLASSTYPE 2359
#define MT_MTNUMERICEVENTTYPE 2438
#define MT_MTNUMERICEVENTTYPE_CATEGORY 2807
#define MT_MTNUMERICEVENTTYPE_CONSTRAINTS 2814
#define MT_MTNUMERICEVENTTYPE_CONSTRAINTS_MAXIMUM 2817
#define MT_MTNUMERICEVENTTYPE_CONSTRAINTS_MINIMUM 2816
#define MT_MTNUMERICEVENTTYPE_CONSTRAINTS_NOMINAL 2818
#define MT_MTNUMERICEVENTTYPE_CONSTRAINTS_VALUES 2815
#define MT_MTNUMERICEVENTTYPE_COORDINATESYSTEM 2822
#define MT_MTNUMERICEVENTTYPE_DURATION 3671
#define MT_MTNUMERICEVENTTYPE_INITIALVALUE 2823
#define MT_MTNUMERICEVENTTYPE_MTSUBTYPENAME 2809
#define MT_MTNUMERICEVENTTYPE_MTTYPENAME 2808
#define MT_MTNUMERICEVENTTYPE_MINIMUMDELTAFILTER 2826
#define MT_MTNUMERICEVENTTYPE_NAME 2806
#define MT_MTNUMERICEVENTTYPE_NATIVEUNITS 2821
#define MT_MTNUMERICEVENTTYPE_PERIODFILTER 2813
#define MT_MTNUMERICEVENTTYPE_REPRESENTATION 2812
#define MT_MTNUMERICEVENTTYPE_RESETTRIGGER 2824
#define MT_MTNUMERICEVENTTYPE_RESETTRIGGEREDREASON 3675
#define MT_MTNUMERICEVENTTYPE_SAMPLERATE 2811
#define MT_MTNUMERICEVENTTYPE_SIGNIFICANTDIGITS 2819
#define MT_MTNUMERICEVENTTYPE_SOURCEDATA 2810
#define MT_MTNUMERICEVENTTYPE_STATISTIC 2820
#define MT_MTNUMERICEVENTTYPE_UNITS 2825
#define MT_MTNUMERICEVENTTYPE_XMLID 2805
#define MT_MTRECONDITIONCOUNTTYPE 3764
#define MT_MTRECONDITIONCOUNTTYPE_DATATYPE 3765
#define MT_MTRECONDITIONCOUNTTYPE_MAXIMUMCOUNT 3766
#define MT_MTRECONDITIONCOUNTTYPE_VALUERANK 3767
#define MT_MTREPRESENTATIONTYPE 2633
#define MT_MTREPRESENTATIONTYPE_ENUMSTRINGS 2633
#define MT_MTRESETTRIGGERTYPE 2636
#define MT_MTRESETTRIGGERTYPE_ENUMSTRINGS 2636
#define MT_MTSAMPLECLASSTYPE 2345
#define MT_MTSAMPLETYPE 2429
#define MT_MTSAMPLETYPE_CATEGORY 2841
#define MT_MTSAMPLETYPE_CONSTRAINTS 2848
#define MT_MTSAMPLETYPE_CONSTRAINTS_MAXIMUM 2851
#define MT_MTSAMPLETYPE_CONSTRAINTS_MINIMUM 2850
#define MT_MTSAMPLETYPE_CONSTRAINTS_NOMINAL 2852
#define MT_MTSAMPLETYPE_CONSTRAINTS_VALUES 2849
#define MT_MTSAMPLETYPE_COORDINATESYSTEM 2856
#define MT_MTSAMPLETYPE_DURATION 3672
#define MT_MTSAMPLETYPE_INITIALVALUE 2857
#define MT_MTSAMPLETYPE_MTSUBTYPENAME 2843
#define MT_MTSAMPLETYPE_MTTYPENAME 2842
#define MT_MTSAMPLETYPE_MINIMUMDELTAFILTER 2860
#define MT_MTSAMPLETYPE_NAME 2840
#define MT_MTSAMPLETYPE_NATIVEUNITS 2855
#define MT_MTSAMPLETYPE_PERIODFILTER 2847
#define MT_MTSAMPLETYPE_REPRESENTATION 2846
#define MT_MTSAMPLETYPE_RESETTRIGGER 2858
#define MT_MTSAMPLETYPE_RESETTRIGGEREDREASON 3676
#define MT_MTSAMPLETYPE_SAMPLERATE 2845
#define MT_MTSAMPLETYPE_SIGNIFICANTDIGITS 2853
#define MT_MTSAMPLETYPE_SOURCEDATA 2844
#define MT_MTSAMPLETYPE_STATISTIC 2854
#define MT_MTSAMPLETYPE_UNITS 2859
#define MT_MTSAMPLETYPE_XMLID 2839
#define MT_MTSENSORCONFIGURATIONTYPE 2046
#define MT_MTSENSORCONFIGURATIONTYPE_CALIBRATIONDATE 2048
#define MT_MTSENSORCONFIGURATIONTYPE_CALIBRATIONINITIALS 2050
#define MT_MTSENSORCONFIGURATIONTYPE_CHANNELS 2052
#define MT_MTSENSORCONFIGURATIONTYPE_FIRWAREVERSION 2047
#define MT_MTSENSORCONFIGURATIONTYPE_NEXTCALIBRATIONDATE 2049
#define MT_MTSEVERITYDATATYPE 2669
#define MT_MTSEVERITYDATATYPE_ENUMSTRINGS 2669
#define MT_MTSTATISTICTYPE 2659
#define MT_MTSTATISTICTYPE_ENUMSTRINGS 2659
#define MT_MTSTRINGEVENTCLASSTYPE 2361
#define MT_MTSTRINGEVENTTYPE 2433
#define MT_MTSTRINGEVENTTYPE_CATEGORY 2869
#define MT_MTSTRINGEVENTTYPE_CONSTRAINTS 2876
#define MT_MTSTRINGEVENTTYPE_CONSTRAINTS_MAXIMUM 2879
#define MT_MTSTRINGEVENTTYPE_CONSTRAINTS_MINIMUM 2878
#define MT_MTSTRINGEVENTTYPE_CONSTRAINTS_NOMINAL 2880
#define MT_MTSTRINGEVENTTYPE_CONSTRAINTS_VALUES 2877
#define MT_MTSTRINGEVENTTYPE_MTSUBTYPENAME 2871
#define MT_MTSTRINGEVENTTYPE_MTTYPENAME 2870
#define MT_MTSTRINGEVENTTYPE_NAME 2868
#define MT_MTSTRINGEVENTTYPE_PERIODFILTER 2875
#define MT_MTSTRINGEVENTTYPE_REPRESENTATION 2874
#define MT_MTSTRINGEVENTTYPE_SAMPLERATE 2873
#define MT_MTSTRINGEVENTTYPE_SOURCEDATA 2872
#define MT_MTSTRINGEVENTTYPE_XMLID 2867
#define MT_MTTHREESPACESAMPLETYPE 2641
#define MT_MTTHREESPACESAMPLETYPE_CATEGORY 2883
#define MT_MTTHREESPACESAMPLETYPE_CONSTRAINTS 2890
#define MT_MTTHREESPACESAMPLETYPE_CONSTRAINTS_MAXIMUM 2893
#define MT_MTTHREESPACESAMPLETYPE_CONSTRAINTS_MINIMUM 2892
#define MT_MTTHREESPACESAMPLETYPE_CONSTRAINTS_NOMINAL 2894
#define MT_MTTHREESPACESAMPLETYPE_CONSTRAINTS_VALUES 2891
#define MT_MTTHREESPACESAMPLETYPE_COORDINATESYSTEM 2898
#define MT_MTTHREESPACESAMPLETYPE_DURATION 3673
#define MT_MTTHREESPACESAMPLETYPE_ENGINEERINGUNITS 2642
#define MT_MTTHREESPACESAMPLETYPE_INITIALVALUE 2899
#define MT_MTTHREESPACESAMPLETYPE_MTSUBTYPENAME 2885
#define MT_MTTHREESPACESAMPLETYPE_MTTYPENAME 2884
#define MT_MTTHREESPACESAMPLETYPE_MINIMUMDELTAFILTER 2902
#define MT_MTTHREESPACESAMPLETYPE_NAME 2882
#define MT_MTTHREESPACESAMPLETYPE_NATIVEUNITS 2897
#define MT_MTTHREESPACESAMPLETYPE_PERIODFILTER 2889
#define MT_MTTHREESPACESAMPLETYPE_REPRESENTATION 2888
#define MT_MTTHREESPACESAMPLETYPE_RESETTRIGGER 2900
#define MT_MTTHREESPACESAMPLETYPE_RESETTRIGGEREDREASON 3677
#define MT_MTTHREESPACESAMPLETYPE_SAMPLERATE 2887
#define MT_MTTHREESPACESAMPLETYPE_SIGNIFICANTDIGITS 2895
#define MT_MTTHREESPACESAMPLETYPE_SOURCEDATA 2886
#define MT_MTTHREESPACESAMPLETYPE_STATISTIC 2896
#define MT_MTTHREESPACESAMPLETYPE_UNITS 2901
#define MT_MTTHREESPACESAMPLETYPE_XMLID 2881
#define MT_MTTOOLLIFETYPE 3769
#define MT_MTTOOLLIFETYPE_COUNTDIRECTION 3770
#define MT_MTTOOLLIFETYPE_DATATYPE 3771
#define MT_MTTOOLLIFETYPE_INITIAL 3772
#define MT_MTTOOLLIFETYPE_LIMIT 3773
#define MT_MTTOOLLIFETYPE_MTTYPE 3774
#define MT_MTTOOLLIFETYPE_VALUERANK 3775
#define MT_MTTOOLLIFETYPE_WARNING 3776
#define MT_MACHINEAXISLOCKSUBCLASSTYPE 2534
#define MT_MAINTENANCESUBCLASSTYPE 2536
#define MT_MANUALUNCLAMPSUBCLASSTYPE 2538
#define MT_MASSCLASSTYPE 2301
#define MT_MATERIALCHANGECLASSTYPE 2235
#define MT_MATERIALCLASSTYPE 2369
#define MT_MATERIALFEEDCLASSTYPE 2231
#define MT_MATERIALHANDLERINTERFACETYPE 2116
#define MT_MATERIALLOADCLASSTYPE 2241
#define MT_MATERIALRETRACTCLASSTYPE 2238
#define MT_MATERIALUNLOADCLASSTYPE 2244
#define MT_MATERIALSTYPE 2118
#define MT_MAXIMUMSUBCLASSTYPE 2540
#define MT_MESSAGECLASSTYPE 2403
#define MT_MESSAGEDATATYPE 2653
#define MT_MINIMUMSUBCLASSTYPE 2542
#define MT_MOHSSUBCLASSTYPE 2544
#define MT_MOLESUBCLASSTYPE 2546
#define MT_MOTIONPROGRAMCLASSTYPE 2421
#define MT_MOTIONSUBCLASSTYPE 2548
#define MT_NOSCALESUBCLASSTYPE 2550
#define MT_ONOFFDATATYPE 2204
#define MT_ONOFFDATATYPE_ENUMSTRINGS 2204
#define MT_OPENCHUCKCLASSTYPE 2253
#define MT_OPENDOORCLASSTYPE 2247
#define MT_OPENSTATEDATATYPE 2201
#define MT_OPENSTATEDATATYPE_ENUMSTRINGS 2201
#define MT_OPERATINGSUBCLASSTYPE 2552
#define MT_OPERATORIDCLASSTYPE 2371
#define MT_OPERATORSUBCLASSTYPE 2554
#define MT_OPTIONALSTOPSUBCLASSTYPE 2556
#define MT_OVERALLTOOLLENGTHCLASSTYPE 3861
#define MT_OVERALLTOOLLENGTHCLASSTYPE_CODE 3862
#define MT_OVERALLTOOLLENGTHCLASSTYPE_UNITS 3863
#define MT_OVERRIDESUBCLASSTYPE 2558
#define MT_PHCLASSTYPE 2307
#define MT_PALLETIDCLASSTYPE 2373
#define MT_PARTCHANGECLASSTYPE 2259
#define MT_PARTCOUNTCLASSTYPE 2355
#define MT_PARTIDCLASSTYPE 2375
#define MT_PARTNUMBERCLASSTYPE 2377
#define MT_PATHFEEDRATECLASSTYPE 2303
#define MT_PATHFEEDRATEOVERRIDECLASSTYPE 3628
#define MT_PATHMODECLASSTYPE 2215
#define MT_PATHMODEDATATYPE 2209
#define MT_PATHMODEDATATYPE_ENUMSTRINGS 2209
#define MT_PATHPOSITIONCLASSTYPE 2305
#define MT_PATHTYPE 2120
#define MT_PERSONNELTYPE 2122
#define MT_PNEUMATICTYPE 2124
#define MT_POINTANGLECLASSTYPE 3865
#define MT_POINTANGLECLASSTYPE_CODE 3866
#define MT_POINTANGLECLASSTYPE_UNITS 3867
#define MT_POSITIONCLASSTYPE 2309
#define MT_POWERFACTORCLASSTYPE 2311
#define MT_POWERSTATECLASSTYPE 2218
#define MT_POWEREDSUBCLASSTYPE 2562
#define MT_PRESSURECLASSTYPE 2313
#define MT_PRIMARYSUBCLASSTYPE 2560
#define MT_PROBESUBCLASSTYPE 2564
#define MT_PROCESSPOWERTYPE 2126
#define MT_PROCESSSUBCLASSTYPE 2566
#define MT_PROCESSTIMERCLASSTYPE 2315
#define MT_PROGRAMCLASSTYPE 2379
#define MT_PROGRAMCOMMENTCLASSTYPE 2385
#define MT_PROGRAMEDITCLASSTYPE 2221
#define MT_PROGRAMEDITDATATYPE 2210
#define MT_PROGRAMEDITDATATYPE_ENUMSTRINGS 2210
#define MT_PROGRAMEDITNAMECLASSTYPE 2381
#define MT_PROGRAMHEADERCLASSTYPE 2383
#define MT_PROGRAMMEDSUBCLASSTYPE 2568
#define MT_PROTECTIVETYPE 2128
#define MT_PROTRUDINGLENGTHCLASSTYPE 3869
#define MT_PROTRUDINGLENGTHCLASSTYPE_CODE 3870
#define MT_PROTRUDINGLENGTHCLASSTYPE_UNITS 3871
#define MT_QUALIFIERDATATYPE 2668
#define MT_QUALIFIERDATATYPE_ENUMSTRINGS 2668
#define MT_RADIALSUBCLASSTYPE 2570
#define MT_RAPIDSUBCLASSTYPE 2572
#define MT_RELATIVESUBCLASSTYPE 2574
#define MT_REMAININGSUBCLASSTYPE 2576
#define MT_REQUESTSUBCLASSTYPE 2578
#define MT_RESISTENCECLASSTYPE 2317
#define MT_RESOURCESTYPE 2130
#define MT_RESPONSESUBCLASSTYPE 2580
#define MT_ROCKWELLSUBCLASSTYPE 2582
#define MT_ROTARYMODECLASSTYPE 2224
#define MT_ROTARYMODEDATATYPE 2211
#define MT_ROTARYMODEDATATYPE_ENUMSTRINGS 2211
#define MT_ROTARYSUBCLASSTYPE 2584
#define MT_ROTARYTYPE 2132
#define MT_ROTARYVELOCITYCLASSTYPE 2319
#define MT_ROTARYVELOCITYOVERRIDECLASSTYPE 2357
#define MT_SENSORTYPE 2134
#define MT_SERIALNUMBERCLASSTYPE 2387
#define MT_SETUPSUBCLASSTYPE 2586
#define MT_SHANKDIAMETERCLASSTYPE 3873
#define MT_SHANKDIAMETERCLASSTYPE_CODE 3874
#define MT_SHANKDIAMETERCLASSTYPE_UNITS 3875
#define MT_SHANKHEIGHTCLASSTYPE 3877
#define MT_SHANKHEIGHTCLASSTYPE_CODE 3878
#define MT_SHANKHEIGHTCLASSTYPE_UNITS 3879
#define MT_SHANKLENGTHCLASSTYPE 3881
#define MT_SHANKLENGTHCLASSTYPE_CODE 3882
#define MT_SHANKLENGTHCLASSTYPE_UNITS 3883
#define MT_SHORESUBCLASSTYPE 2588
#define MT_SOUNDLEVELCLASSTYPE 2321
#define MT_SPINDLEINTERLOCKCLASSTYPE 2212
#define MT_STANDARDSUBCLASSTYPE 2590
#define MT_STEPDIAMETERLENGTHCLASSTYPE 3885
#define MT_STEPDIAMETERLENGTHCLASSTYPE_CODE 3886
#define MT_STEPDIAMETERLENGTHCLASSTYPE_UNITS 3887
#define MT_STEPINCLUDEDANGLECLASSTYPE 3889
#define MT_STEPINCLUDEDANGLECLASSTYPE_CODE 3890
#define MT_STEPINCLUDEDANGLECLASSTYPE_UNITS 3891
#define MT_STOCKTYPE 2136
#define MT_STRAINCLASSTYPE 2323
#define MT_SWITCHEDSUBCLASSTYPE 2592
#define MT_SYSTEMCLASSTYPE 2423
#define MT_SYSTEMSTYPE 2138
#define MT_TARGETSUBCLASSTYPE 2594
#define MT_TEMPERATURECLASSTYPE 2325
#define MT_TENSIONCLASSTYPE 2327
#define MT_THREESPACESAMPLEDATATYPE 2637
#define MT_TILTCLASSTYPE 2329
#define MT_TOOLASSETIDCLASSTYPE 2389
#define MT_TOOLCHANGESTOPSUBCLASSTYPE 2596
#define MT_TOOLCUTTINGEDGEANGLECLASSTYPE 3893
#define MT_TOOLCUTTINGEDGEANGLECLASSTYPE_CODE 3894
#define MT_TOOLCUTTINGEDGEANGLECLASSTYPE_UNITS 3895
#define MT_TOOLEDGESUBCLASSTYPE 2598
#define MT_TOOLGROUPSUBCLASSTYPE 2600
#define MT_TOOLLEADANGLECLASSTYPE 3897
#define MT_TOOLLEADANGLECLASSTYPE_CODE 3898
#define MT_TOOLLEADANGLECLASSTYPE_UNITS 3899
#define MT_TOOLNUMBERCLASSTYPE 2391
#define MT_TOOLOFFSETCLASSTYPE 2393
#define MT_TOOLORIENTATIONCLASSTYPE 3901
#define MT_TOOLORIENTATIONCLASSTYPE_CODE 3902
#define MT_TOOLORIENTATIONCLASSTYPE_UNITS 3903
#define MT_TOOLSUBCLASSTYPE 2602
#define MT_TOOLINGDELIVERYTYPE 2140
#define MT_TORQUECLASSTYPE 2331
#define MT_UASBLESUBCLASSTYPE 2604
#define MT_USABLELENGTHMAXCLASSTYPE 3905
#define MT_USABLELENGTHMAXCLASSTYPE_CODE 3906
#define MT_USABLELENGTHMAXCLASSTYPE_UNITS 3907
#define MT_USERCLASSTYPE 2395
#define MT_VELOCITYCLASSTYPE 2335
#define MT_VERTICALSUBCLASSTYPE 2606
#define MT_VICKERSSUBCLASSTYPE 2610
#define MT_VISCOSITYCLASSTYPE 2339
#define MT_VOLTAMPERECLASSTYPE 2333
#define MT_VOLTAMPEREREACTIVECLASSTYPE 2337
#define MT_VOLTAGECLASSTYPE 2341
#define MT_VOLUMESUBCLASSTYPE 2608
#define MT_WASTEDISPOSALTYPE 2142
#define MT_WATTAGECLASSTYPE 2343
#define MT_WEIGHTCLASSTYPE 3909
#define MT_WEIGHTCLASSTYPE_CODE 3910
#define MT_WEIGHTCLASSTYPE_UNITS 3911
#define MT_WEIGHTSUBCLASSTYPE 2612
#define MT_WIPEREDGELENGTHCLASSTYPE 3913
#define MT_WIPEREDGELENGTHCLASSTYPE_CODE 3914
#define MT_WIPEREDGELENGTHCLASSTYPE_UNITS 3915
#define MT_WIRECLASSTYPE 2397
#define MT_WORKOFFSETCLASSTYPE 2401
#define MT_WORKHOLDINGCLASSTYPE 2399
#define MT_WORKINGSUBCLASSTYPE 2614
#define MT_WORKPIECESUBCLASSTYPE 2616
#define MT_YESNODATATYPE 2206
#define MT_YESNODATATYPE_ENUMSTRINGS 2206
extern std::map<std::string, UA_UInt32> mtIDMap;
#endif
<file_sep>/settings.h
#ifndef ITEMMANAGER_H
#define ITEMMANAGER_H
#include <string>
#include <map>
using namespace std;
class Settings
{
private:
map< string, int> m_collection;
int m_nextns;
public:
static string getSettingsName(string progName);
void restore(string filename);
void save(string filename);
void set(string &key, int ns);
int get(string &key);
void dump();
Settings();
};
#endif // ITEMMANAGER_H
<file_sep>/Dockerfile
from ubuntu:latest
RUN apt-get update && apt-get install -y git make cmake build-essential python python3-dev python python-dev wget
RUN git clone https://github.com/openssl/openssl.git && \
cd openssl && \
git checkout OpenSSL_1_1_1-stable && \
./config && \
make && \
make install
RUN wget https://dl.bintray.com/boostorg/release/1.71.0/source/boost_1_71_0.tar.gz && \
tar -xf boost_1_71_0.tar.gz && \
cd boost_1_71_0 && \
./bootstrap.sh && \
./b2 link=static && \
./b2 link=static install
RUN git clone https://github.com/open62541/open62541.git && \
cd open62541 && \
git checkout 1.0 && \
git submodule update --init --recursive && \
mkdir build && cd build && \
cmake -DBUILD_SHARED_LIBS=FALSE -DCMAKE_BUILD_TYPE=RelWithDebInfo -DUA_NAMESPACE_ZERO=FULL -DUA_ENABLE_SUBSCRIPTIONS_EVENTS=ON .. && \
make && \
make install
RUN git clone https://github.com/mtconnect/open62541_ua_server.git && \
cd open62541_ua_server && \
mkdir build && cd build && \
cmake .. && \
make
<file_sep>/makeIds.sh
echo "#ifndef MTCONNECT_IDS_H" > mtconnect_ids.h
echo "#define MTCONNECT_IDS_H" >> mtconnect_ids.h
echo "" >> mtconnect_ids.h
echo "#include <map>" >> mtconnect_ids.h
echo "#include <string>" >> mtconnect_ids.h
echo " " >> mtconnect_ids.h
egrep -v "http|(Binary)|(XML)" MTConnect.NodeIds.csv | sort | uniq | awk -F, '{print "#define MT_" toupper($1) "\t\t" $2}' >> mtconnect_ids.h
echo " " >> mtconnect_ids.h
echo "extern std::map<std::string, UA_UInt32> mtIDMap; " >> mtconnect_ids.h
echo "#endif" >> mtconnect_ids.h
echo "#include <open62541/server.h>" > mtconnect_ids.cpp
echo "#include \"mtconnect_ids.h\" " >> mtconnect_ids.cpp
echo "std::map<std::string, UA_UInt32> mtIDMap = { " >> mtconnect_ids.cpp
egrep -v "http|(Binary)|(XML)" MTConnect.NodeIds.csv | sort | uniq | awk -F, '{print " { \""$1"\","$2 " }, " }' >> mtconnect_ids.cpp
echo " { \"\", 0 }" >> mtconnect_ids.cpp
echo "};" >> mtconnect_ids.cpp
<file_sep>/mtconnect_ids.cpp
#include <open62541/server.h>
#include "mtconnect_ids.h"
std::map<std::string, UA_UInt32> mtIDMap = {
{ "AScaleSubClassType",2488 },
{ "AbsoluteSubClassType",2478 },
{ "AccelerationClassType",2265 },
{ "AccumulatedTimeClassType",2267 },
{ "ActionSubClassType",2482 },
{ "ActiveStateDataType",2197 },
{ "ActiveStateDataType_EnumStrings",2197 },
{ "ActualSubClassType",2480 },
{ "ActuatorClassType",2411 },
{ "ActuatorStateClassType",2146 },
{ "ActuatorType",2074 },
{ "AllSubClassType",2484 },
{ "AlternatingSubClassType",2486 },
{ "AmperageClassType",2273 },
{ "AngleClassType",2275 },
{ "AngularAccelerationClassType",2269 },
{ "AngularVelocityClassType",2271 },
{ "AssetChangedClassType",2405 },
{ "AssetEventDataType",2618 },
{ "AssetRemovedClassType",2407 },
{ "AuxiliariesType",2076 },
{ "AuxiliarySubClassType",2490 },
{ "AvailabilityClassType",2149 },
{ "AvailabilityDataType",2198 },
{ "AvailabilityDataType_EnumStrings",2198 },
{ "AxesType",2078 },
{ "AxisCouplingClassType",2152 },
{ "AxisCouplingDataType",2199 },
{ "AxisCouplingDataType_EnumStrings",2199 },
{ "AxisFeedrateClassType",2277 },
{ "AxisFeedrateOverrideClassType",2347 },
{ "AxisInterlockClassType",2155 },
{ "AxisStateClassType",2158 },
{ "AxisStateDataType",2200 },
{ "AxisStateDataType_EnumStrings",2200 },
{ "BScaleSubClassType",2496 },
{ "BadSubClassType",2492 },
{ "BarFeederInterfaceType",2080 },
{ "BarFeederType",2082 },
{ "BlockClassType",2363 },
{ "BlockCountClassType",2349 },
{ "BodyDiameterMaxClassType",3778 },
{ "BodyDiameterMaxClassType_Code",3779 },
{ "BodyDiameterMaxClassType_Units",3780 },
{ "BodyLengthMaxClassType",3782 },
{ "BodyLengthMaxClassType_Code",3783 },
{ "BodyLengthMaxClassType_Units",3784 },
{ "BrinellSubClassType",2494 },
{ "CScaleSubClassType",2504 },
{ "ChamferFlatLengthClassType",3786 },
{ "ChamferFlatLengthClassType_Code",3787 },
{ "ChamferFlatLengthClassType_Units",3788 },
{ "ChamferWidthClassType",3790 },
{ "ChamferWidthClassType_Code",3791 },
{ "ChamferWidthClassType_Units",3792 },
{ "ChuckInterfaceType",2084 },
{ "ChuckInterlockClassType",2161 },
{ "ChuckStateClassType",2164 },
{ "ChuckType",2086 },
{ "ClockTimeClassType",2279 },
{ "CloseChuckClassType",2256 },
{ "CloseDoorClassType",2250 },
{ "CommandedSubClassType",2498 },
{ "CommunicationsClassType",2413 },
{ "CompositionStateClassType",2173 },
{ "CompositionStateDataType",2202 },
{ "CompositionStateDataType_EnumStrings",2202 },
{ "ConcentrationClassType",2281 },
{ "ConductivityClassType",2283 },
{ "ControlSubClassType",2502 },
{ "ControllerModeClassType",2167 },
{ "ControllerModeDataType",2203 },
{ "ControllerModeDataType_EnumStrings",2203 },
{ "ControllerModeOverrideClassType",2176 },
{ "ControllerType",2088 },
{ "CoolantType",2090 },
{ "CornerRadiusClassType",3795 },
{ "CornerRadiusClassType_Code",3796 },
{ "CornerRadiusClassType_Units",3797 },
{ "CountDirectionDataType",3685 },
{ "CountDirectionDataType_EnumStrings",3685 },
{ "CoupledAxesClassType",2365 },
{ "CutterStatusDataType",3686 },
{ "CutterStatusDataType_EnumStrings",3686 },
{ "CuttingDiameterClassType",3799 },
{ "CuttingDiameterClassType_Code",3800 },
{ "CuttingDiameterClassType_Units",3801 },
{ "CuttingDiameterMaxType",3803 },
{ "CuttingDiameterMaxType_Code",3804 },
{ "CuttingDiameterMaxType_Units",3805 },
{ "CuttingEdgeLengthClassType",3807 },
{ "CuttingEdgeLengthClassType_Code",3808 },
{ "CuttingEdgeLengthClassType_Units",3809 },
{ "CuttingHeightClassType",3811 },
{ "CuttingHeightClassType_Code",3812 },
{ "CuttingHeightClassType_Units",3813 },
{ "CuttingItemClassType",3815 },
{ "CuttingItemFunctionalLengthClassType",3817 },
{ "CuttingItemFunctionalLengthClassType_Code",3818 },
{ "CuttingItemFunctionalLengthClassType_Units",3819 },
{ "CuttingItemWeightClassType",3821 },
{ "CuttingItemWeightClassType_Code",3822 },
{ "CuttingItemWeightClassType_Units",3823 },
{ "CuttingToolClassType",3825 },
{ "CuttingToolClassType_Code",3826 },
{ "CuttingToolClassType_Units",3827 },
{ "CuttingToolDefintionFormatDataType",3687 },
{ "CuttingToolDefintionFormatDataType_EnumStrings",3687 },
{ "DScaleSubClassType",2512 },
{ "DataRangeClassType",2415 },
{ "DelaySubClassType",2506 },
{ "DepthOfCutMaxClassType",3829 },
{ "DepthOfCutMaxClassType_Code",3830 },
{ "DepthOfCutMaxClassType_Units",3831 },
{ "DielectricType",2092 },
{ "DirectSubClassType",2508 },
{ "DirectionClassType",2179 },
{ "DirectionDataType",2205 },
{ "DirectionDataType_EnumStrings",2205 },
{ "DisplacementClassType",2285 },
{ "DoorInterfaceType",2094 },
{ "DoorStateClassType",2182 },
{ "DoorType",2096 },
{ "DriveAngleClassType",3833 },
{ "DriveAngleClassType_Code",3834 },
{ "DriveAngleClassType_Units",3835 },
{ "DryRunSubClassType",2510 },
{ "ElectricType",2098 },
{ "ElectricalEnergyClassType",2287 },
{ "EmergencyStopClassType",2185 },
{ "EmergencyStopDataType",2207 },
{ "EmergencyStopDataType_EnumStrings",2207 },
{ "EnclosureType",2100 },
{ "EndOfBarClassType",2188 },
{ "EnvironmentalType",2102 },
{ "EquipmentModeClassType",2191 },
{ "EquipmentTimerClassType",2289 },
{ "ExecutionClassType",2170 },
{ "ExecutionDataType",2262 },
{ "ExecutionDataType_EnumStrings",2262 },
{ "FeederType",2104 },
{ "FillLevelClassType",2291 },
{ "FixtureSubClassType",2514 },
{ "FlangeDiameterClassType",3837 },
{ "FlangeDiameterClassType_Code",3838 },
{ "FlangeDiameterClassType_Units",3839 },
{ "FlangeDiameterMaxClassType",3841 },
{ "FlangeDiameterMaxClassType_Code",3842 },
{ "FlangeDiameterMaxClassType_Units",3843 },
{ "FlowClassType",2293 },
{ "FrequencyClassType",2295 },
{ "FunctionalLengthClassType",3845 },
{ "FunctionalLengthClassType_FunctionalLength",3846 },
{ "FunctionalLengthClassType_Units",3847 },
{ "FunctionalModeClassType",2194 },
{ "FunctionalModeDataType",2208 },
{ "FunctionalModeDataType_EnumStrings",2208 },
{ "FunctionalWidthClassType",3849 },
{ "FunctionalWidthClassType_Code",3850 },
{ "FunctionalWidthClassType_Units",3851 },
{ "GoodSubClassType",2500 },
{ "HardnessClassType",2351 },
{ "HardwareClassType",2419 },
{ "HasMTClassType",2680 },
{ "HasMTComposition",2687 },
{ "HasMTReference",2672 },
{ "HasMTSource",2689 },
{ "HasMTSubClassType",2683 },
{ "HydraulicType",2106 },
{ "IncrementalSubClassType",2516 },
{ "IncribedCircleDiameterClassType",3853 },
{ "IncribedCircleDiameterClassType_Code",3854 },
{ "IncribedCircleDiameterClassType_Units",3855 },
{ "InsertWidthClassType",3857 },
{ "InsertWidthClassType_Code",3858 },
{ "InsertWidthClassType_Units",3859 },
{ "InterfaceStateClassType",2227 },
{ "InterfaceStateDataType",2234 },
{ "InterfaceStateDataType_EnumStrings",2234 },
{ "InterfaceStatusDataType",2230 },
{ "InterfaceStatusDataType_EnumStrings",2230 },
{ "InterfacesType",2108 },
{ "JobSubClassType",2518 },
{ "KineticSubClassType",2520 },
{ "LateralSubClassType",2522 },
{ "LeebSubClassType",2524 },
{ "LengthClassType",2297 },
{ "LengthSubClassType",2526 },
{ "LineClassType",2409 },
{ "LineLabelClassType",2367 },
{ "LineNumberClassType",2353 },
{ "LineSubClassType",2530 },
{ "LinearForceClassType",2299 },
{ "LinearSubClassType",2528 },
{ "LinearType",2110 },
{ "LoadClassType",2263 },
{ "LoadedSubClassType",2532 },
{ "LoaderType",2112 },
{ "LogicProgramClassType",2417 },
{ "LubricationType",2114 },
{ "MTAssetEventType",2621 },
{ "MTAssetEventType_Category",2753 },
{ "MTAssetEventType_Constraints",2760 },
{ "MTAssetEventType_Constraints_Maximum",2763 },
{ "MTAssetEventType_Constraints_Minimum",2762 },
{ "MTAssetEventType_Constraints_Nominal",2764 },
{ "MTAssetEventType_Constraints_Values",2761 },
{ "MTAssetEventType_MTSubTypeName",2755 },
{ "MTAssetEventType_MTTypeName",2754 },
{ "MTAssetEventType_Name",2752 },
{ "MTAssetEventType_PeriodFilter",2759 },
{ "MTAssetEventType_Representation",2758 },
{ "MTAssetEventType_SampleRate",2757 },
{ "MTAssetEventType_SourceData",2756 },
{ "MTAssetEventType_XmlId",2751 },
{ "MTAssetType",3678 },
{ "MTAssetType_AssetId",3679 },
{ "MTAssetType_DeviceUuid",3680 },
{ "MTAssetType_MTDescription",3681 },
{ "MTAssetType_Removed",3682 },
{ "MTAssetType_Timestamp",3683 },
{ "MTCategoryType",2634 },
{ "MTCategoryType_EnumStrings",2634 },
{ "MTChannelType",2059 },
{ "MTChannelType_CalibrationDate",2063 },
{ "MTChannelType_CalibrationInitials",2065 },
{ "MTChannelType_MTDescription",2062 },
{ "MTChannelType_Name",2061 },
{ "MTChannelType_NextCalibrationDate",2064 },
{ "MTChannelType_Number",2060 },
{ "MTComponentType",2021 },
{ "MTComponentType_Components",2042 },
{ "MTComponentType_Compositions",2043 },
{ "MTComponentType_Configuration",2029 },
{ "MTComponentType_Description",2028 },
{ "MTComponentType_Description_Data",2740 },
{ "MTComponentType_Description_Manufacturer",2739 },
{ "MTComponentType_Description_SerialNumber",2738 },
{ "MTComponentType_Description_Station",2737 },
{ "MTComponentType_Name",2023 },
{ "MTComponentType_NativeName",2024 },
{ "MTComponentType_SampleInterval",2027 },
{ "MTComponentType_SampleRate",2026 },
{ "MTComponentType_Uuid",2025 },
{ "MTComponentType_XmlId",2022 },
{ "MTCompositionType",2067 },
{ "MTCompositionType_MTTypeName",2069 },
{ "MTCompositionType_Name",2071 },
{ "MTCompositionType_Uuid",2070 },
{ "MTCompositionType_XmlId",2068 },
{ "MTConditionClassType",2629 },
{ "MTConditionEventType",4326 },
{ "MTConditionEventType_ActiveState",4336 },
{ "MTConditionEventType_DataItemId",4327 },
{ "MTConditionEventType_MTSeverity",4328 },
{ "MTConditionEventType_MTSubTypeName",4329 },
{ "MTConditionEventType_MTTypeName",4330 },
{ "MTConditionEventType_NativeCode",4331 },
{ "MTConditionEventType_NativeSeverity",4332 },
{ "MTConditionEventType_Qualifier",4333 },
{ "MTConditionType",2660 },
{ "MTConditionType_Category",2917 },
{ "MTConditionType_Constraints",2924 },
{ "MTConditionType_Constraints_Maximum",2927 },
{ "MTConditionType_Constraints_Minimum",2926 },
{ "MTConditionType_Constraints_Nominal",2928 },
{ "MTConditionType_Constraints_Values",2925 },
{ "MTConditionType_MTSubTypeName",2919 },
{ "MTConditionType_MTTypeName",2918 },
{ "MTConditionType_Name",2916 },
{ "MTConditionType_PeriodFilter",2923 },
{ "MTConditionType_Representation",2922 },
{ "MTConditionType_SampleRate",2921 },
{ "MTConditionType_SourceData",2920 },
{ "MTConditionType_XmlId",2915 },
{ "MTConfigurationType",2044 },
{ "MTConstraintType",2647 },
{ "MTConstraintType_Maximum",2650 },
{ "MTConstraintType_Minimum",2649 },
{ "MTConstraintType_Nominal",2651 },
{ "MTConstraintType_Values",2648 },
{ "MTControlledVocabEventClassType",2144 },
{ "MTControlledVocabEventType",2626 },
{ "MTControlledVocabEventType_Category",2773 },
{ "MTControlledVocabEventType_Constraints",2780 },
{ "MTControlledVocabEventType_Constraints_Maximum",2783 },
{ "MTControlledVocabEventType_Constraints_Minimum",2782 },
{ "MTControlledVocabEventType_Constraints_Nominal",2784 },
{ "MTControlledVocabEventType_Constraints_Values",2781 },
{ "MTControlledVocabEventType_MTSubTypeName",2775 },
{ "MTControlledVocabEventType_MTTypeName",2774 },
{ "MTControlledVocabEventType_Name",2772 },
{ "MTControlledVocabEventType_PeriodFilter",2779 },
{ "MTControlledVocabEventType_Representation",2778 },
{ "MTControlledVocabEventType_SampleRate",2777 },
{ "MTControlledVocabEventType_SourceData",2776 },
{ "MTControlledVocabEventType_ValueAsText",3090 },
{ "MTControlledVocabEventType_XmlId",2771 },
{ "MTCoordinateSystemType",2635 },
{ "MTCoordinateSystemType_EnumStrings",2635 },
{ "MTCutterStatusType",3690 },
{ "MTCuttingItemType",3697 },
{ "MTCuttingItemType_CutterStatus",3706 },
{ "MTCuttingItemType_CutterStatus_Definition",3926 },
{ "MTCuttingItemType_CutterStatus_EnumStrings",3928 },
{ "MTCuttingItemType_CutterStatus_ValuePrecision",3927 },
{ "MTCuttingItemType_Grade",3698 },
{ "MTCuttingItemType_Indices",3699 },
{ "MTCuttingItemType_ItemId",3700 },
{ "MTCuttingItemType_Locus",3701 },
{ "MTCuttingItemType_MTDescription",3703 },
{ "MTCuttingItemType_Manufactures",3702 },
{ "MTCuttingItemType_MinutesItemLife",3705 },
{ "MTCuttingItemType_MinutesItemLife_CountDirection",3919 },
{ "MTCuttingItemType_MinutesItemLife_DataType",4263 },
{ "MTCuttingItemType_MinutesItemLife_Definition",3917 },
{ "MTCuttingItemType_MinutesItemLife_Initial",3921 },
{ "MTCuttingItemType_MinutesItemLife_Limit",3922 },
{ "MTCuttingItemType_MinutesItemLife_MTType",3923 },
{ "MTCuttingItemType_MinutesItemLife_ValuePrecision",3918 },
{ "MTCuttingItemType_MinutesItemLife_ValueRank",4264 },
{ "MTCuttingItemType_MinutesItemLife_Warning",3925 },
{ "MTCuttingItemType_PartCountItemLife",3707 },
{ "MTCuttingItemType_PartCountItemLife_CountDirection",3932 },
{ "MTCuttingItemType_PartCountItemLife_DataType",4265 },
{ "MTCuttingItemType_PartCountItemLife_Definition",3930 },
{ "MTCuttingItemType_PartCountItemLife_Initial",3934 },
{ "MTCuttingItemType_PartCountItemLife_Limit",3935 },
{ "MTCuttingItemType_PartCountItemLife_MTType",3936 },
{ "MTCuttingItemType_PartCountItemLife_ValuePrecision",3931 },
{ "MTCuttingItemType_PartCountItemLife_ValueRank",4266 },
{ "MTCuttingItemType_PartCountItemLife_Warning",3938 },
{ "MTCuttingItemType_WearItemLife",3709 },
{ "MTCuttingItemType_WearItemLife_CountDirection",3941 },
{ "MTCuttingItemType_WearItemLife_DataType",4267 },
{ "MTCuttingItemType_WearItemLife_Definition",3939 },
{ "MTCuttingItemType_WearItemLife_Initial",3943 },
{ "MTCuttingItemType_WearItemLife_Limit",3944 },
{ "MTCuttingItemType_WearItemLife_MTType",3945 },
{ "MTCuttingItemType_WearItemLife_ValuePrecision",3940 },
{ "MTCuttingItemType_WearItemLife_ValueRank",4268 },
{ "MTCuttingItemType_WearItemLife_Warning",3947 },
{ "MTCuttingToolArchetypeType",3710 },
{ "MTCuttingToolArchetypeType_CuttingToolDefinition",3716 },
{ "MTCuttingToolArchetypeType_CuttingToolDefinition_Data",4017 },
{ "MTCuttingToolArchetypeType_CuttingToolDefinition_Data_MimeType",4018 },
{ "MTCuttingToolArchetypeType_CuttingToolDefinition_Data_OpenCount",4019 },
{ "MTCuttingToolArchetypeType_CuttingToolDefinition_Data_Size",4020 },
{ "MTCuttingToolArchetypeType_CuttingToolDefinition_Data_UserWritable",4021 },
{ "MTCuttingToolArchetypeType_CuttingToolDefinition_Data_Writable",4022 },
{ "MTCuttingToolArchetypeType_CuttingToolDefinition_Format",4016 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle",3715 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ConnectionCodeMachineSide",3948 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_CutterStatus",3951 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_CutterStatus_Definition",3952 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_CutterStatus_EnumStrings",3954 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_CutterStatus_ValuePrecision",3953 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_Location",3998 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_Location_DataType",4279 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_Location_Definition",3999 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_Location_NegativeOverlap",4002 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_Location_PositiveOverlap",4003 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_Location_Type",4004 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_Location_ValuePrecision",4000 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_Location_ValueRank",4280 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessFeedRate",3976 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessFeedRate_DataType",4273 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessFeedRate_Definition",3977 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessFeedRate_Maximum",3980 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessFeedRate_Minimum",3981 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessFeedRate_Nominal",3982 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessFeedRate_ValuePrecision",3978 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessFeedRate_ValueRank",4274 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessSpindleSpeed",3990 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessSpindleSpeed_DataType",4277 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessSpindleSpeed_Definition",3991 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessSpindleSpeed_Maximum",3994 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessSpindleSpeed_Minimum",3995 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessSpindleSpeed_Nominal",3996 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessSpindleSpeed_ValuePrecision",3992 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProcessSpindleSpeed_ValueRank",4278 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProgramToolGroup",3949 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ProgramToolNumber",3950 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ReconditionCount",3984 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ReconditionCount_DataType",4275 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ReconditionCount_Definition",3985 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ReconditionCount_MaximumCount",3988 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ReconditionCount_ValuePrecision",3986 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ReconditionCount_ValueRank",4276 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeMinutes",4006 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeMinutes_CountDirection",4009 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeMinutes_DataType",4281 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeMinutes_Definition",4007 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeMinutes_Initial",4011 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeMinutes_Limit",4012 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeMinutes_MTType",4013 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeMinutes_ValuePrecision",4008 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeMinutes_ValueRank",4282 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeMinutes_Warning",4015 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifePartCount",3956 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifePartCount_CountDirection",3959 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifePartCount_DataType",4269 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifePartCount_Definition",3957 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifePartCount_Initial",3961 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifePartCount_Limit",3962 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifePartCount_MTType",3963 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifePartCount_ValuePrecision",3958 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifePartCount_ValueRank",4270 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifePartCount_Warning",3965 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeWear",3966 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeWear_CountDirection",3969 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeWear_DataType",4271 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeWear_Definition",3967 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeWear_Initial",3971 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeWear_Limit",3972 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeWear_MTType",3973 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeWear_ValuePrecision",3968 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeWear_ValueRank",4272 },
{ "MTCuttingToolArchetypeType_CuttingToolLifecycle_ToolLifeWear_Warning",3975 },
{ "MTCuttingToolArchetypeType_Manufacturers",3711 },
{ "MTCuttingToolArchetypeType_SerialNumber",3712 },
{ "MTCuttingToolArchetypeType_ToolId",3713 },
{ "MTCuttingToolConstraintType",3717 },
{ "MTCuttingToolConstraintType_DataType",3718 },
{ "MTCuttingToolConstraintType_Maximum",3719 },
{ "MTCuttingToolConstraintType_Minimum",3720 },
{ "MTCuttingToolConstraintType_Nominal",3721 },
{ "MTCuttingToolConstraintType_ValueRank",3722 },
{ "MTCuttingToolDefinitionType",3724 },
{ "MTCuttingToolDefinitionType_Data",3727 },
{ "MTCuttingToolDefinitionType_Data_MimeType",4023 },
{ "MTCuttingToolDefinitionType_Data_OpenCount",4024 },
{ "MTCuttingToolDefinitionType_Data_Size",4025 },
{ "MTCuttingToolDefinitionType_Data_UserWritable",4026 },
{ "MTCuttingToolDefinitionType_Data_Writable",4027 },
{ "MTCuttingToolDefinitionType_Format",3725 },
{ "MTCuttingToolLifeCycleType",3728 },
{ "MTCuttingToolLifeCycleType_ConnectionCodeMachineSide",3729 },
{ "MTCuttingToolLifeCycleType_CutterStatus",3733 },
{ "MTCuttingToolLifeCycleType_CutterStatus_Definition",4028 },
{ "MTCuttingToolLifeCycleType_CutterStatus_EnumStrings",4030 },
{ "MTCuttingToolLifeCycleType_CutterStatus_ValuePrecision",4029 },
{ "MTCuttingToolLifeCycleType_Location",3740 },
{ "MTCuttingToolLifeCycleType_Location_DataType",4293 },
{ "MTCuttingToolLifeCycleType_Location_Definition",4069 },
{ "MTCuttingToolLifeCycleType_Location_NegativeOverlap",4072 },
{ "MTCuttingToolLifeCycleType_Location_PositiveOverlap",4073 },
{ "MTCuttingToolLifeCycleType_Location_Type",4074 },
{ "MTCuttingToolLifeCycleType_Location_ValuePrecision",4070 },
{ "MTCuttingToolLifeCycleType_Location_ValueRank",4294 },
{ "MTCuttingToolLifeCycleType_ProcessFeedRate",3736 },
{ "MTCuttingToolLifeCycleType_ProcessFeedRate_DataType",4287 },
{ "MTCuttingToolLifeCycleType_ProcessFeedRate_Definition",4050 },
{ "MTCuttingToolLifeCycleType_ProcessFeedRate_Maximum",4053 },
{ "MTCuttingToolLifeCycleType_ProcessFeedRate_Minimum",4054 },
{ "MTCuttingToolLifeCycleType_ProcessFeedRate_Nominal",4055 },
{ "MTCuttingToolLifeCycleType_ProcessFeedRate_ValuePrecision",4051 },
{ "MTCuttingToolLifeCycleType_ProcessFeedRate_ValueRank",4288 },
{ "MTCuttingToolLifeCycleType_ProcessSpindleSpeed",3739 },
{ "MTCuttingToolLifeCycleType_ProcessSpindleSpeed_DataType",4291 },
{ "MTCuttingToolLifeCycleType_ProcessSpindleSpeed_Definition",4062 },
{ "MTCuttingToolLifeCycleType_ProcessSpindleSpeed_Maximum",4065 },
{ "MTCuttingToolLifeCycleType_ProcessSpindleSpeed_Minimum",4066 },
{ "MTCuttingToolLifeCycleType_ProcessSpindleSpeed_Nominal",4067 },
{ "MTCuttingToolLifeCycleType_ProcessSpindleSpeed_ValuePrecision",4063 },
{ "MTCuttingToolLifeCycleType_ProcessSpindleSpeed_ValueRank",4292 },
{ "MTCuttingToolLifeCycleType_ProgramToolGroup",3730 },
{ "MTCuttingToolLifeCycleType_ProgramToolNumber",3731 },
{ "MTCuttingToolLifeCycleType_ReconditionCount",3737 },
{ "MTCuttingToolLifeCycleType_ReconditionCount_DataType",4289 },
{ "MTCuttingToolLifeCycleType_ReconditionCount_Definition",4057 },
{ "MTCuttingToolLifeCycleType_ReconditionCount_MaximumCount",4060 },
{ "MTCuttingToolLifeCycleType_ReconditionCount_ValuePrecision",4058 },
{ "MTCuttingToolLifeCycleType_ReconditionCount_ValueRank",4290 },
{ "MTCuttingToolLifeCycleType_ToolLifeMinutes",3741 },
{ "MTCuttingToolLifeCycleType_ToolLifeMinutes_CountDirection",4078 },
{ "MTCuttingToolLifeCycleType_ToolLifeMinutes_DataType",4295 },
{ "MTCuttingToolLifeCycleType_ToolLifeMinutes_Definition",4076 },
{ "MTCuttingToolLifeCycleType_ToolLifeMinutes_Initial",4080 },
{ "MTCuttingToolLifeCycleType_ToolLifeMinutes_Limit",4081 },
{ "MTCuttingToolLifeCycleType_ToolLifeMinutes_MTType",4082 },
{ "MTCuttingToolLifeCycleType_ToolLifeMinutes_ValuePrecision",4077 },
{ "MTCuttingToolLifeCycleType_ToolLifeMinutes_ValueRank",4296 },
{ "MTCuttingToolLifeCycleType_ToolLifeMinutes_Warning",4084 },
{ "MTCuttingToolLifeCycleType_ToolLifePartCount",3734 },
{ "MTCuttingToolLifeCycleType_ToolLifePartCount_CountDirection",4034 },
{ "MTCuttingToolLifeCycleType_ToolLifePartCount_DataType",4283 },
{ "MTCuttingToolLifeCycleType_ToolLifePartCount_Definition",4032 },
{ "MTCuttingToolLifeCycleType_ToolLifePartCount_Initial",4036 },
{ "MTCuttingToolLifeCycleType_ToolLifePartCount_Limit",4037 },
{ "MTCuttingToolLifeCycleType_ToolLifePartCount_MTType",4038 },
{ "MTCuttingToolLifeCycleType_ToolLifePartCount_ValuePrecision",4033 },
{ "MTCuttingToolLifeCycleType_ToolLifePartCount_ValueRank",4284 },
{ "MTCuttingToolLifeCycleType_ToolLifePartCount_Warning",4040 },
{ "MTCuttingToolLifeCycleType_ToolLifeWear",3735 },
{ "MTCuttingToolLifeCycleType_ToolLifeWear_CountDirection",4043 },
{ "MTCuttingToolLifeCycleType_ToolLifeWear_DataType",4285 },
{ "MTCuttingToolLifeCycleType_ToolLifeWear_Definition",4041 },
{ "MTCuttingToolLifeCycleType_ToolLifeWear_Initial",4045 },
{ "MTCuttingToolLifeCycleType_ToolLifeWear_Limit",4046 },
{ "MTCuttingToolLifeCycleType_ToolLifeWear_MTType",4047 },
{ "MTCuttingToolLifeCycleType_ToolLifeWear_ValuePrecision",4042 },
{ "MTCuttingToolLifeCycleType_ToolLifeWear_ValueRank",4286 },
{ "MTCuttingToolLifeCycleType_ToolLifeWear_Warning",4049 },
{ "MTCuttingToolMeasurementType",3742 },
{ "MTCuttingToolMeasurementType_Code",3743 },
{ "MTCuttingToolMeasurementType_EngineringUnits",3744 },
{ "MTCuttingToolMeasurementType_NativeUnits",3745 },
{ "MTCuttingToolMeasurementType_SignificantDigits",3746 },
{ "MTCuttingToolMeasurementType_Units",3747 },
{ "MTCuttingToolType",3750 },
{ "MTCuttingToolType_CuttingToolArchitype",3755 },
{ "MTCuttingToolType_CuttingToolArchitype_AssetId",4085 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolDefinition",4162 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolDefinition_Data",4164 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolDefinition_Data_MimeType",4165 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolDefinition_Data_OpenCount",4166 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolDefinition_Data_Size",4167 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolDefinition_Data_UserWritable",4168 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolDefinition_Data_Writable",4169 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolDefinition_Format",4163 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle",4093 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ConnectionCodeMachineSide",4094 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_CutterStatus",4097 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_CutterStatus_Definition",4098 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_CutterStatus_EnumStrings",4100 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_CutterStatus_ValuePrecision",4099 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_Location",4144 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_Location_DataType",4307 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_Location_Definition",4145 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_Location_NegativeOverlap",4148 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_Location_PositiveOverlap",4149 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_Location_Type",4150 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_Location_ValuePrecision",4146 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_Location_ValueRank",4308 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessFeedRate",4122 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessFeedRate_DataType",4301 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessFeedRate_Definition",4123 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessFeedRate_Maximum",4126 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessFeedRate_Minimum",4127 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessFeedRate_Nominal",4128 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessFeedRate_ValuePrecision",4124 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessFeedRate_ValueRank",4302 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessSpindleSpeed",4136 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessSpindleSpeed_DataType",4305 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessSpindleSpeed_Definition",4137 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessSpindleSpeed_Maximum",4140 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessSpindleSpeed_Minimum",4141 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessSpindleSpeed_Nominal",4142 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessSpindleSpeed_ValuePrecision",4138 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProcessSpindleSpeed_ValueRank",4306 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProgramToolGroup",4095 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ProgramToolNumber",4096 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ReconditionCount",4130 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ReconditionCount_DataType",4303 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ReconditionCount_Definition",4131 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ReconditionCount_MaximumCount",4134 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ReconditionCount_ValuePrecision",4132 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ReconditionCount_ValueRank",4304 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeMinutes",4152 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeMinutes_CountDirection",4155 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeMinutes_DataType",4309 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeMinutes_Definition",4153 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeMinutes_Initial",4157 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeMinutes_Limit",4158 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeMinutes_MTType",4159 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeMinutes_ValuePrecision",4154 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeMinutes_ValueRank",4310 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeMinutes_Warning",4161 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifePartCount",4102 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifePartCount_CountDirection",4105 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifePartCount_DataType",4297 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifePartCount_Definition",4103 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifePartCount_Initial",4107 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifePartCount_Limit",4108 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifePartCount_MTType",4109 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifePartCount_ValuePrecision",4104 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifePartCount_ValueRank",4298 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifePartCount_Warning",4111 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeWear",4112 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeWear_CountDirection",4115 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeWear_DataType",4299 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeWear_Definition",4113 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeWear_Initial",4117 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeWear_Limit",4118 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeWear_MTType",4119 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeWear_ValuePrecision",4114 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeWear_ValueRank",4300 },
{ "MTCuttingToolType_CuttingToolArchitype_CuttingToolLifecycle_ToolLifeWear_Warning",4121 },
{ "MTCuttingToolType_CuttingToolArchitype_DeviceUuid",4086 },
{ "MTCuttingToolType_CuttingToolArchitype_MTDescription",4087 },
{ "MTCuttingToolType_CuttingToolArchitype_Manufacturers",4090 },
{ "MTCuttingToolType_CuttingToolArchitype_Removed",4088 },
{ "MTCuttingToolType_CuttingToolArchitype_SerialNumber",4091 },
{ "MTCuttingToolType_CuttingToolArchitype_Timestamp",4089 },
{ "MTCuttingToolType_CuttingToolArchitype_ToolId",4092 },
{ "MTCuttingToolType_CuttingToolLifecycle",3756 },
{ "MTCuttingToolType_CuttingToolLifecycle_ConnectionCodeMachineSide",4170 },
{ "MTCuttingToolType_CuttingToolLifecycle_CutterStatus",4173 },
{ "MTCuttingToolType_CuttingToolLifecycle_CutterStatus_Definition",4174 },
{ "MTCuttingToolType_CuttingToolLifecycle_CutterStatus_EnumStrings",4176 },
{ "MTCuttingToolType_CuttingToolLifecycle_CutterStatus_ValuePrecision",4175 },
{ "MTCuttingToolType_CuttingToolLifecycle_Location",4220 },
{ "MTCuttingToolType_CuttingToolLifecycle_Location_DataType",4321 },
{ "MTCuttingToolType_CuttingToolLifecycle_Location_Definition",4221 },
{ "MTCuttingToolType_CuttingToolLifecycle_Location_NegativeOverlap",4224 },
{ "MTCuttingToolType_CuttingToolLifecycle_Location_PositiveOverlap",4225 },
{ "MTCuttingToolType_CuttingToolLifecycle_Location_Type",4226 },
{ "MTCuttingToolType_CuttingToolLifecycle_Location_ValuePrecision",4222 },
{ "MTCuttingToolType_CuttingToolLifecycle_Location_ValueRank",4322 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessFeedRate",4198 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessFeedRate_DataType",4315 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessFeedRate_Definition",4199 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessFeedRate_Maximum",4202 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessFeedRate_Minimum",4203 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessFeedRate_Nominal",4204 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessFeedRate_ValuePrecision",4200 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessFeedRate_ValueRank",4316 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessSpindleSpeed",4212 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessSpindleSpeed_DataType",4319 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessSpindleSpeed_Definition",4213 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessSpindleSpeed_Maximum",4216 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessSpindleSpeed_Minimum",4217 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessSpindleSpeed_Nominal",4218 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessSpindleSpeed_ValuePrecision",4214 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProcessSpindleSpeed_ValueRank",4320 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProgramToolGroup",4171 },
{ "MTCuttingToolType_CuttingToolLifecycle_ProgramToolNumber",4172 },
{ "MTCuttingToolType_CuttingToolLifecycle_ReconditionCount",4206 },
{ "MTCuttingToolType_CuttingToolLifecycle_ReconditionCount_DataType",4317 },
{ "MTCuttingToolType_CuttingToolLifecycle_ReconditionCount_Definition",4207 },
{ "MTCuttingToolType_CuttingToolLifecycle_ReconditionCount_MaximumCount",4210 },
{ "MTCuttingToolType_CuttingToolLifecycle_ReconditionCount_ValuePrecision",4208 },
{ "MTCuttingToolType_CuttingToolLifecycle_ReconditionCount_ValueRank",4318 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeMinutes",4228 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeMinutes_CountDirection",4231 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeMinutes_DataType",4323 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeMinutes_Definition",4229 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeMinutes_Initial",4233 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeMinutes_Limit",4234 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeMinutes_MTType",4235 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeMinutes_ValuePrecision",4230 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeMinutes_ValueRank",4324 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeMinutes_Warning",4237 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifePartCount",4178 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifePartCount_CountDirection",4181 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifePartCount_DataType",4311 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifePartCount_Definition",4179 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifePartCount_Initial",4183 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifePartCount_Limit",4184 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifePartCount_MTType",4185 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifePartCount_ValuePrecision",4180 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifePartCount_ValueRank",4312 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifePartCount_Warning",4187 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeWear",4188 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeWear_CountDirection",4191 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeWear_DataType",4313 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeWear_Definition",4189 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeWear_Initial",4193 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeWear_Limit",4194 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeWear_MTType",4195 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeWear_ValuePrecision",4190 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeWear_ValueRank",4314 },
{ "MTCuttingToolType_CuttingToolLifecycle_ToolLifeWear_Warning",4197 },
{ "MTCuttingToolType_Manufacturers",3751 },
{ "MTCuttingToolType_SerialNumber",3752 },
{ "MTCuttingToolType_ToolId",3753 },
{ "MTDataItemClassType",2425 },
{ "MTDataItemSubClassType",2476 },
{ "MTDescriptionType",2053 },
{ "MTDescriptionType_Data",2057 },
{ "MTDescriptionType_Manufacturer",2056 },
{ "MTDescriptionType_SerialNumber",2055 },
{ "MTDescriptionType_Station",2054 },
{ "MTDeviceType",2015 },
{ "MTDeviceType_Iso841Class",2017 },
{ "MTDeviceType_Name",3668 },
{ "MTDeviceType_Uuid",3669 },
{ "MTDeviceType_Version",2016 },
{ "MTEventClassType",2631 },
{ "MTLocationDataType",3688 },
{ "MTLocationDataType_EnumStrings",3688 },
{ "MTLocationType",3757 },
{ "MTLocationType_DataType",3758 },
{ "MTLocationType_NegativeOverlap",3759 },
{ "MTLocationType_PositiveOverlap",3760 },
{ "MTLocationType_Type",3761 },
{ "MTLocationType_ValueRank",3762 },
{ "MTMessageClassType",2427 },
{ "MTMessageEventType",2656 },
{ "MTMessageEventType_NativeCode",2657 },
{ "MTMessageType",2471 },
{ "MTMessageType_Category",2793 },
{ "MTMessageType_Constraints",2800 },
{ "MTMessageType_Constraints_Maximum",2803 },
{ "MTMessageType_Constraints_Minimum",2802 },
{ "MTMessageType_Constraints_Nominal",2804 },
{ "MTMessageType_Constraints_Values",2801 },
{ "MTMessageType_MTSubTypeName",2795 },
{ "MTMessageType_MTTypeName",2794 },
{ "MTMessageType_Name",2792 },
{ "MTMessageType_PeriodFilter",2799 },
{ "MTMessageType_Representation",2798 },
{ "MTMessageType_SampleRate",2797 },
{ "MTMessageType_SourceData",2796 },
{ "MTMessageType_XmlId",2791 },
{ "MTNumericEventClassType",2359 },
{ "MTNumericEventType",2438 },
{ "MTNumericEventType_Category",2807 },
{ "MTNumericEventType_Constraints",2814 },
{ "MTNumericEventType_Constraints_Maximum",2817 },
{ "MTNumericEventType_Constraints_Minimum",2816 },
{ "MTNumericEventType_Constraints_Nominal",2818 },
{ "MTNumericEventType_Constraints_Values",2815 },
{ "MTNumericEventType_CoordinateSystem",2822 },
{ "MTNumericEventType_Duration",3671 },
{ "MTNumericEventType_InitialValue",2823 },
{ "MTNumericEventType_MTSubTypeName",2809 },
{ "MTNumericEventType_MTTypeName",2808 },
{ "MTNumericEventType_MinimumDeltaFilter",2826 },
{ "MTNumericEventType_Name",2806 },
{ "MTNumericEventType_NativeUnits",2821 },
{ "MTNumericEventType_PeriodFilter",2813 },
{ "MTNumericEventType_Representation",2812 },
{ "MTNumericEventType_ResetTrigger",2824 },
{ "MTNumericEventType_ResetTriggeredReason",3675 },
{ "MTNumericEventType_SampleRate",2811 },
{ "MTNumericEventType_SignificantDigits",2819 },
{ "MTNumericEventType_SourceData",2810 },
{ "MTNumericEventType_Statistic",2820 },
{ "MTNumericEventType_Units",2825 },
{ "MTNumericEventType_XmlId",2805 },
{ "MTReconditionCountType",3764 },
{ "MTReconditionCountType_DataType",3765 },
{ "MTReconditionCountType_MaximumCount",3766 },
{ "MTReconditionCountType_ValueRank",3767 },
{ "MTRepresentationType",2633 },
{ "MTRepresentationType_EnumStrings",2633 },
{ "MTResetTriggerType",2636 },
{ "MTResetTriggerType_EnumStrings",2636 },
{ "MTSampleClassType",2345 },
{ "MTSampleType",2429 },
{ "MTSampleType_Category",2841 },
{ "MTSampleType_Constraints",2848 },
{ "MTSampleType_Constraints_Maximum",2851 },
{ "MTSampleType_Constraints_Minimum",2850 },
{ "MTSampleType_Constraints_Nominal",2852 },
{ "MTSampleType_Constraints_Values",2849 },
{ "MTSampleType_CoordinateSystem",2856 },
{ "MTSampleType_Duration",3672 },
{ "MTSampleType_InitialValue",2857 },
{ "MTSampleType_MTSubTypeName",2843 },
{ "MTSampleType_MTTypeName",2842 },
{ "MTSampleType_MinimumDeltaFilter",2860 },
{ "MTSampleType_Name",2840 },
{ "MTSampleType_NativeUnits",2855 },
{ "MTSampleType_PeriodFilter",2847 },
{ "MTSampleType_Representation",2846 },
{ "MTSampleType_ResetTrigger",2858 },
{ "MTSampleType_ResetTriggeredReason",3676 },
{ "MTSampleType_SampleRate",2845 },
{ "MTSampleType_SignificantDigits",2853 },
{ "MTSampleType_SourceData",2844 },
{ "MTSampleType_Statistic",2854 },
{ "MTSampleType_Units",2859 },
{ "MTSampleType_XmlId",2839 },
{ "MTSensorConfigurationType",2046 },
{ "MTSensorConfigurationType_CalibrationDate",2048 },
{ "MTSensorConfigurationType_CalibrationInitials",2050 },
{ "MTSensorConfigurationType_Channels",2052 },
{ "MTSensorConfigurationType_FirwareVersion",2047 },
{ "MTSensorConfigurationType_NextCalibrationDate",2049 },
{ "MTSeverityDataType",2669 },
{ "MTSeverityDataType_EnumStrings",2669 },
{ "MTStatisticType",2659 },
{ "MTStatisticType_EnumStrings",2659 },
{ "MTStringEventClassType",2361 },
{ "MTStringEventType",2433 },
{ "MTStringEventType_Category",2869 },
{ "MTStringEventType_Constraints",2876 },
{ "MTStringEventType_Constraints_Maximum",2879 },
{ "MTStringEventType_Constraints_Minimum",2878 },
{ "MTStringEventType_Constraints_Nominal",2880 },
{ "MTStringEventType_Constraints_Values",2877 },
{ "MTStringEventType_MTSubTypeName",2871 },
{ "MTStringEventType_MTTypeName",2870 },
{ "MTStringEventType_Name",2868 },
{ "MTStringEventType_PeriodFilter",2875 },
{ "MTStringEventType_Representation",2874 },
{ "MTStringEventType_SampleRate",2873 },
{ "MTStringEventType_SourceData",2872 },
{ "MTStringEventType_XmlId",2867 },
{ "MTThreeSpaceSampleType",2641 },
{ "MTThreeSpaceSampleType_Category",2883 },
{ "MTThreeSpaceSampleType_Constraints",2890 },
{ "MTThreeSpaceSampleType_Constraints_Maximum",2893 },
{ "MTThreeSpaceSampleType_Constraints_Minimum",2892 },
{ "MTThreeSpaceSampleType_Constraints_Nominal",2894 },
{ "MTThreeSpaceSampleType_Constraints_Values",2891 },
{ "MTThreeSpaceSampleType_CoordinateSystem",2898 },
{ "MTThreeSpaceSampleType_Duration",3673 },
{ "MTThreeSpaceSampleType_EngineeringUnits",2642 },
{ "MTThreeSpaceSampleType_InitialValue",2899 },
{ "MTThreeSpaceSampleType_MTSubTypeName",2885 },
{ "MTThreeSpaceSampleType_MTTypeName",2884 },
{ "MTThreeSpaceSampleType_MinimumDeltaFilter",2902 },
{ "MTThreeSpaceSampleType_Name",2882 },
{ "MTThreeSpaceSampleType_NativeUnits",2897 },
{ "MTThreeSpaceSampleType_PeriodFilter",2889 },
{ "MTThreeSpaceSampleType_Representation",2888 },
{ "MTThreeSpaceSampleType_ResetTrigger",2900 },
{ "MTThreeSpaceSampleType_ResetTriggeredReason",3677 },
{ "MTThreeSpaceSampleType_SampleRate",2887 },
{ "MTThreeSpaceSampleType_SignificantDigits",2895 },
{ "MTThreeSpaceSampleType_SourceData",2886 },
{ "MTThreeSpaceSampleType_Statistic",2896 },
{ "MTThreeSpaceSampleType_Units",2901 },
{ "MTThreeSpaceSampleType_XmlId",2881 },
{ "MTToolLifeType",3769 },
{ "MTToolLifeType_CountDirection",3770 },
{ "MTToolLifeType_DataType",3771 },
{ "MTToolLifeType_Initial",3772 },
{ "MTToolLifeType_Limit",3773 },
{ "MTToolLifeType_MTType",3774 },
{ "MTToolLifeType_ValueRank",3775 },
{ "MTToolLifeType_Warning",3776 },
{ "MachineAxisLockSubClassType",2534 },
{ "MaintenanceSubClassType",2536 },
{ "ManualUnclampSubClassType",2538 },
{ "MassClassType",2301 },
{ "MaterialChangeClassType",2235 },
{ "MaterialClassType",2369 },
{ "MaterialFeedClassType",2231 },
{ "MaterialHandlerInterfaceType",2116 },
{ "MaterialLoadClassType",2241 },
{ "MaterialRetractClassType",2238 },
{ "MaterialUnloadClassType",2244 },
{ "MaterialsType",2118 },
{ "MaximumSubClassType",2540 },
{ "MessageClassType",2403 },
{ "MessageDataType",2653 },
{ "MinimumSubClassType",2542 },
{ "MohsSubClassType",2544 },
{ "MoleSubClassType",2546 },
{ "MotionProgramClassType",2421 },
{ "MotionSubClassType",2548 },
{ "NoScaleSubClassType",2550 },
{ "OnOffDataType",2204 },
{ "OnOffDataType_EnumStrings",2204 },
{ "OpenChuckClassType",2253 },
{ "OpenDoorClassType",2247 },
{ "OpenStateDataType",2201 },
{ "OpenStateDataType_EnumStrings",2201 },
{ "OperatingSubClassType",2552 },
{ "OperatorIdClassType",2371 },
{ "OperatorSubClassType",2554 },
{ "OptionalStopSubClassType",2556 },
{ "OverallToolLengthClassType",3861 },
{ "OverallToolLengthClassType_Code",3862 },
{ "OverallToolLengthClassType_Units",3863 },
{ "OverrideSubClassType",2558 },
{ "PHClassType",2307 },
{ "PalletIdClassType",2373 },
{ "PartChangeClassType",2259 },
{ "PartCountClassType",2355 },
{ "PartIdClassType",2375 },
{ "PartNumberClassType",2377 },
{ "PathFeedrateClassType",2303 },
{ "PathFeedrateOverrideClassType",3628 },
{ "PathModeClassType",2215 },
{ "PathModeDataType",2209 },
{ "PathModeDataType_EnumStrings",2209 },
{ "PathPositionClassType",2305 },
{ "PathType",2120 },
{ "PersonnelType",2122 },
{ "PneumaticType",2124 },
{ "PointAngleClassType",3865 },
{ "PointAngleClassType_Code",3866 },
{ "PointAngleClassType_Units",3867 },
{ "PositionClassType",2309 },
{ "PowerFactorClassType",2311 },
{ "PowerStateClassType",2218 },
{ "PoweredSubClassType",2562 },
{ "PressureClassType",2313 },
{ "PrimarySubClassType",2560 },
{ "ProbeSubClassType",2564 },
{ "ProcessPowerType",2126 },
{ "ProcessSubClassType",2566 },
{ "ProcessTimerClassType",2315 },
{ "ProgramClassType",2379 },
{ "ProgramCommentClassType",2385 },
{ "ProgramEditClassType",2221 },
{ "ProgramEditDataType",2210 },
{ "ProgramEditDataType_EnumStrings",2210 },
{ "ProgramEditNameClassType",2381 },
{ "ProgramHeaderClassType",2383 },
{ "ProgrammedSubClassType",2568 },
{ "ProtectiveType",2128 },
{ "ProtrudingLengthClassType",3869 },
{ "ProtrudingLengthClassType_Code",3870 },
{ "ProtrudingLengthClassType_Units",3871 },
{ "QualifierDataType",2668 },
{ "QualifierDataType_EnumStrings",2668 },
{ "RadialSubClassType",2570 },
{ "RapidSubClassType",2572 },
{ "RelativeSubClassType",2574 },
{ "RemainingSubClassType",2576 },
{ "RequestSubClassType",2578 },
{ "ResistenceClassType",2317 },
{ "ResourcesType",2130 },
{ "ResponseSubClassType",2580 },
{ "RockwellSubClassType",2582 },
{ "RotaryModeClassType",2224 },
{ "RotaryModeDataType",2211 },
{ "RotaryModeDataType_EnumStrings",2211 },
{ "RotarySubClassType",2584 },
{ "RotaryType",2132 },
{ "RotaryVelocityClassType",2319 },
{ "RotaryVelocityOverrideClassType",2357 },
{ "SensorType",2134 },
{ "SerialNumberClassType",2387 },
{ "SetUpSubClassType",2586 },
{ "ShankDiameterClassType",3873 },
{ "ShankDiameterClassType_Code",3874 },
{ "ShankDiameterClassType_Units",3875 },
{ "ShankHeightClassType",3877 },
{ "ShankHeightClassType_Code",3878 },
{ "ShankHeightClassType_Units",3879 },
{ "ShankLengthClassType",3881 },
{ "ShankLengthClassType_Code",3882 },
{ "ShankLengthClassType_Units",3883 },
{ "ShoreSubClassType",2588 },
{ "SoundLevelClassType",2321 },
{ "SpindleInterlockClassType",2212 },
{ "StandardSubClassType",2590 },
{ "StepDiameterLengthClassType",3885 },
{ "StepDiameterLengthClassType_Code",3886 },
{ "StepDiameterLengthClassType_Units",3887 },
{ "StepIncludedAngleClassType",3889 },
{ "StepIncludedAngleClassType_Code",3890 },
{ "StepIncludedAngleClassType_Units",3891 },
{ "StockType",2136 },
{ "StrainClassType",2323 },
{ "SwitchedSubClassType",2592 },
{ "SystemClassType",2423 },
{ "SystemsType",2138 },
{ "TargetSubClassType",2594 },
{ "TemperatureClassType",2325 },
{ "TensionClassType",2327 },
{ "ThreeSpaceSampleDataType",2637 },
{ "TiltClassType",2329 },
{ "ToolAssetIdClassType",2389 },
{ "ToolChangeStopSubClassType",2596 },
{ "ToolCuttingEdgeAngleClassType",3893 },
{ "ToolCuttingEdgeAngleClassType_Code",3894 },
{ "ToolCuttingEdgeAngleClassType_Units",3895 },
{ "ToolEdgeSubClassType",2598 },
{ "ToolGroupSubClassType",2600 },
{ "ToolLeadAngleClassType",3897 },
{ "ToolLeadAngleClassType_Code",3898 },
{ "ToolLeadAngleClassType_Units",3899 },
{ "ToolNumberClassType",2391 },
{ "ToolOffsetClassType",2393 },
{ "ToolOrientationClassType",3901 },
{ "ToolOrientationClassType_Code",3902 },
{ "ToolOrientationClassType_Units",3903 },
{ "ToolSubClassType",2602 },
{ "ToolingDeliveryType",2140 },
{ "TorqueClassType",2331 },
{ "UasbleSubClassType",2604 },
{ "UsableLengthMaxClassType",3905 },
{ "UsableLengthMaxClassType_Code",3906 },
{ "UsableLengthMaxClassType_Units",3907 },
{ "UserClassType",2395 },
{ "VelocityClassType",2335 },
{ "VerticalSubClassType",2606 },
{ "VickersSubClassType",2610 },
{ "ViscosityClassType",2339 },
{ "VoltAmpereClassType",2333 },
{ "VoltAmpereReactiveClassType",2337 },
{ "VoltageClassType",2341 },
{ "VolumeSubClassType",2608 },
{ "WasteDisposalType",2142 },
{ "WattageClassType",2343 },
{ "WeightClassType",3909 },
{ "WeightClassType_Code",3910 },
{ "WeightClassType_Units",3911 },
{ "WeightSubClassType",2612 },
{ "WiperEdgeLengthClassType",3913 },
{ "WiperEdgeLengthClassType_Code",3914 },
{ "WiperEdgeLengthClassType_Units",3915 },
{ "WireClassType",2397 },
{ "WorkOffsetClassType",2401 },
{ "WorkholdingClassType",2399 },
{ "WorkingSubClassType",2614 },
{ "WorkpieceSubClassType",2616 },
{ "YesNoDataType",2206 },
{ "YesNoDataType_EnumStrings",2206 },
{ "", 0 }
};
<file_sep>/opcua_server.cpp
#include <signal.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <open62541/plugin/log_stdout.h>
#include <open62541/server.h>
#include <open62541/server_config_default.h>
#include <open62541/types.h>
#include <open62541/types_generated_handling.h>
#include <boost/thread.hpp>
#include <boost/tokenizer.hpp>
#include <boost/filesystem.hpp>
#include "worker.h"
#include "nodeset.h"
#include "mtconnect_ids.h"
#include "types_mtconnect_generated.h"
using namespace boost;
static Settings settings;
static string settingsName;
static Worker *createWorker(UA_Server *server, UA_NodeId &nodeId, string uri, string poll)
{
Worker *worker = new Worker();
if (!worker->setup(server, nodeId, &settings, uri, poll))
return nullptr;
return worker;
}
static volatile UA_Boolean running = true;
static void stopHandler(int sig)
{
UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "received ctrl-c");
running = false;
}
static UA_DataTypeArray customTypesArray =
{
nullptr,
UA_TYPES_MTCONNECT_COUNT,
UA_TYPES_MTCONNECT
};
int main(int argc, char** argv)
{
signal(SIGINT, stopHandler);
signal(SIGTERM, stopHandler);
// Check command line arguments.
if (argc < 2 || argc > 3)
{
std::cerr <<
"Usage: " << endl <<
" OPCUA-MTServer <uri> <poll cycle in seconds>" << endl <<
"Example:" << endl <<
" OPCUA-MTServer https://smstestbed.nist.gov/vds 60" << endl <<
"or" << endl <<
" OPCUA-MTServer <config file>" << endl;
return -1;
}
// settingsName = Settings::getSettingsName("OPCUA-MTServer");
// settings.restore(settingsName);
UA_Server *server = UA_Server_new();
UA_ServerConfig *config = UA_Server_getConfig(server);
UA_ServerConfig_setDefault(config);
config->customDataTypes = &customTypesArray;
if (nodeset(server) != UA_STATUSCODE_GOOD) {
UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "Could not add the nodeset. "
"Check previous output for any error.");
return -1;
}
UA_NodeId topId = UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER);
vector<Worker*> worker_pool;
vector<thread*> thread_pool;
boost::thread *bthread = nullptr;
if (argc != 2)
{
string uri = argv[1];
string poll = argc > 2 ? argv[2] : "60";
Worker *worker = createWorker(server, topId, uri, poll);
if (worker == nullptr)
return -1;
worker_pool.push_back(worker);
bthread = new boost::thread(boost::bind(&Worker::run, worker));
thread_pool.push_back(bthread);
}
else {
ifstream in(argv[1]);
if (!in.is_open()) {
std::cerr << "Cannot open config file " << argv[1] << "!" << endl;
return -1;
}
typedef tokenizer< escaped_list_separator<char> > Tokenizer;
vector< string > vec;
string line;
while (getline(in, line))
{
Tokenizer tok(line);
vec.assign(tok.begin(), tok.end());
unsigned long argc = vec.size();
// empty line
if (argc == 0)
continue;
if (argc != 1 && argc != 2)
{
std::cerr << "Invalid input [" << line << "]" << endl;
return -1;
}
string uri = vec[0];
if (uri[0] == '#')
continue;
string poll = argc > 1 ? vec[1] : "60";
Worker *worker = createWorker(server, topId, uri, poll);
if (worker == nullptr)
continue;
worker_pool.push_back(worker);
bthread = new boost::thread(boost::bind(&Worker::run, worker));
thread_pool.push_back(bthread);
}
}
if (worker_pool.size() == 0)
return -1;
// settings.save(settingsName);
UA_StatusCode retval = UA_Server_run(server, &running);
UA_Server_delete(server);
for (size_t i=0; i<thread_pool.size(); i++)
delete thread_pool[i];
for (size_t i=0; i<worker_pool.size(); i++)
delete worker_pool[i];
return retval == UA_STATUSCODE_GOOD ? EXIT_SUCCESS : EXIT_FAILURE;
}
<file_sep>/util.h
#ifndef UTIL_H
#define UTIL_H
#include <boost/property_tree/ptree.hpp>
#include <string>
using namespace std;
using boost::property_tree::ptree;
#define VerifyReturn(a) util::handleStatus(a, __FUNCTION__, __FILE__, __LINE__ )
class util
{
public:
static string toString(UA_String& ua_str) {
return std::string(reinterpret_cast<char*>(ua_str.data), ua_str.length);
}
static UA_String toUAString(string &str) {
return UA_STRING((char*) str.c_str());
}
static UA_LocalizedText toUALocalizedText(string &str) {
return UA_LOCALIZEDTEXT("en-US", (char*) str.c_str());
}
static UA_QualifiedName toUAQualifiedName(UA_UInt16 nsIndex, string &str) {
return UA_QUALIFIEDNAME(nsIndex, (char*) str.c_str());
}
static UA_NodeId toUANodeId(UA_UInt16 nsIndex, string &str) {
return UA_NODEID_STRING (nsIndex, (char*) str.c_str());
}
static UA_DateTime toUADateTime(string &dateTime);
static inline bool handleStatus(UA_StatusCode status, const char *function, const char *filename, int linenum)
{
if (status == UA_STATUSCODE_GOOD)
return true;
else
{
fprintf(stderr, "UA call error (%s, %s, %d): [%s]\n", function, filename, linenum, UA_StatusCode_name(status));
return false;
}
}
static string toCamelCase(string &input);
static string getJSON_data(ptree &tree, string path);
static bool isLeafNode(ptree::iterator &p);
static void dump(ptree &pt);
static void strptime(const char* s, const char* f, struct tm* tm);
static void writeDataWithTimeStamp(UA_Server *server, UA_NodeId nodeId, string dateTime, UA_Variant &myVar);
static bool writeNodeData(UA_Server *server, UA_NodeId &nodeId, string result);
static UA_StatusCode writeObject(UA_Server *server, const UA_NodeId objectId,
const UA_NodeId referenceType,
const UA_QualifiedName componentName,
const UA_Variant value);
static UA_StatusCode writeObject_scalar(UA_Server *server, const UA_NodeId objectId,
const UA_NodeId referenceType,
const UA_QualifiedName componentName,
const void *value, const UA_DataType *type);
};
#endif // UTIL_H
<file_sep>/worker.cpp
#include <stdlib.h>
#include <open62541/server.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
#include <boost/chrono.hpp>
#include <boost/filesystem.hpp>
#include "httpreader.h"
#include "agenthandler.h"
#include "worker.h"
Worker::Worker()
{
m_interval = 60;
m_poll_count = 0;
}
Worker::~Worker()
{
m_reader.close();
}
bool Worker::setup(UA_Server *uaServer, UA_NodeId topNode, Settings *settings, string uri, string interval)
{
m_uri = uri;
m_settings = settings;
m_uaServer = uaServer;
m_topNode = topNode;
m_interval = atoi(interval.c_str());
if (m_interval <= 0) {
std::cerr << "interval [" << interval << "] is invalid" << endl;
return false;
}
m_namespace = UA_Server_addNamespace(m_uaServer, uri.c_str());
std::cout << "----------------" << endl;
std::cout << "Agent Uri: " << uri << endl;
std::cout << "Poll Interval: " << interval << endl;
std::cout << "namespace : " << m_namespace << endl;
m_handler.setup(m_uaServer, m_topNode, m_namespace);
if (m_reader.parseUri(uri))
return setMetaInfo();
return false;
}
bool Worker::setMetaInfo()
{
m_reader.setQuery("/probe");
string probeXml = m_reader.read();
if (probeXml.length() == 0)
{
std::cerr << "No data!" << endl;
return false;
}
m_handler.processProbeInfo(probeXml);
m_reader.close();
return true;
}
void Worker::run()
{
while (true)
{
poll();
boost::this_thread::sleep_for( boost::chrono::seconds(m_interval) );
}
}
void Worker::poll()
{
m_poll_count++;
if (m_next_sequence.length() == 0)
m_reader.setQuery("/current");
else
m_reader.setQuery("/sample?count=10000&from="+m_next_sequence);
string xmlData = m_reader.read();
if (xmlData.length() == 0)
{
std::cerr << "No data!" << endl;
return;
}
try {
m_handler.parseStreamData(xmlData);
}
catch (exception & e)
{
std::cerr << e.what() << endl;
return;
}
// don't output if data has not changed
string sequence = m_handler.getJSON_data("MTConnectStreams.Header.<xmlattr>.nextSequence");
if (sequence.compare(m_next_sequence) == 0)
{
std::cout << "========== { " << m_uri << " [round: "<< m_poll_count << "] process items = 0, next sequence = " << m_next_sequence << " } ==========" << std::endl;
return;
}
if (sequence.length() == 0)
{
// last next_sequence may be invalid, reset to using "current" to fetch the latest data
std::cout << "========== { " << m_uri << " [round: "<< m_poll_count << "] BAD sequence number, reset to fetch current data } ==========" << std::endl;
return;
}
int processCount = m_handler.processStreamData();
m_next_sequence = sequence;
std::cout << "========== { " << m_uri << " [round: " << m_poll_count << "] processed items = " << processCount << ", next sequence = " << m_next_sequence << " } ==========" << std::endl;
}
<file_sep>/README.md
MTConnect OPC UA Gateway server, **opcua-MTServer**, implements MTConnect OPC UA Companion Specification. It connects to MTConnect agents for the information of MT devices and monitors their real-time data.
Building
-------
**opcua-MTServer** is written in C++ using **open62541**, **boost** and **openssl** libraries. It uses **CMake** as the build system. First download and install them:
- [open62541](https://open62541.org/)
- [CMake](https://cmake.org)
- [boost](https://www.boost.org)
- [openssl](https://www.openssl.org) - This is to support https secure protocol. For Windows, after the build, prepend the location of libcrypto.dll and libssl.dll to the PATH system variable.
Then run these commands:
- **mkdir build && cd build**
- **cmake ..**
- **make**
If build successful, **opcua-MTServer** should be generated in the current directory.
Checkout **binaries/Windows/README.md** and **binaries/Ubuntu/README.md** for detailed instructions.
Usage:
- opcua-MTServer **[MTConnect Agent URL address] [poll cycle in seconds]**
Example: opcua-MTServer https://smstestbed.nist.gov/vds/GFAgie01 60
or
- opcua-MTServer **[configuration file]**
Example: opcua-MTServer opcua.cfg
opcua.cfg allows connections to multiple MTConnect Agents. The file is a CSV file. Each line contains <agent's url> and its poll frequency in seconds.
Binary Releases
-------
Windows, Ubuntu, MacOS and Raspberry PI 4 pre-built binaries are available:
Windows: [opcua-MTServer-1.0.0-win32.zip](https://github.com/mtconnect/open62541_ua_server/files/3993033/opcua-MTServer-1.0.0-win32.zip)
Ubunt: [opcua-MTServer-1.0.0rc2-Linux.zip](https://github.com/mtconnect/open62541_ua_server/files/3993002/opcua-MTServer-1.0.0rc2-Linux.zip)
MacOS: [opcua-MTServer-1.0.0rc2-Darwin.zip](https://github.com/mtconnect/open62541_ua_server/files/3992997/opcua-MTServer-1.0.0rc2-Darwin.zip)
Raspberry PI 4: [opcua-MTServer-1.0.0rc2-Linux.zip](https://github.com/mtconnect/open62541_ua_server/files/3993028/opcua-MTServer-1.0.0rc2-Linux.zip)
<file_sep>/settings.cpp
#include <iostream>
#include <fstream>
#include <boost/thread.hpp>
#include <boost/tokenizer.hpp>
#include <boost/filesystem.hpp>
#include "settings.h"
Settings::Settings()
{
m_nextns = 1;
}
string Settings::getSettingsName(string progName)
{
const char* homeDrive = getenv("HOMEDRIVE");
const char* homePath = getenv("HOMEPATH");
string homeDir = "";
if (homeDrive != nullptr && homePath != nullptr)
{
// Windows
homeDir = homeDrive;
homeDir += homePath;
}
else {
// unix
const char *home = getenv("HOME");
if (home != nullptr)
homeDir = home;
// homeDir is "" (current directory) if no environment
}
boost::filesystem::path dir (homeDir);
boost::filesystem::path file (progName + ".settings");
boost::filesystem::path fullFilename = dir / file;
return fullFilename.string();
}
void Settings::set(string &key, int ns)
{
map<string, int>::iterator i = m_collection.find(key);
if (i != m_collection.end())
i->second = ns;
else
m_collection.insert(pair<string, int>(key, ns));
}
int Settings::get(string &key)
{
std::map<string, int>::iterator i = m_collection.find(key);
if (i != m_collection.end())
return i->second;
int ret = m_nextns++;
m_collection.insert(pair<string, int>(key, ret));
return ret;
}
void Settings::dump()
{
for (map<string, int>::iterator p = m_collection.begin(); p != m_collection.end(); p++)
std::cout << p->first << ": " << p->second << std::endl;
}
void Settings::restore(string filename)
{
std::ifstream os(filename);
string input;
while (std::getline(os, input))
{
unsigned long pos = input.find_first_of("|");
string key = input.substr(0, pos);
int value = std::stoi(input.substr(pos + 1));
if (value > m_nextns)
m_nextns = value + 1;
std::cout << "Restoring - " << key << " = " << value << std::endl;
m_collection.insert(pair<string, int>(key, value));
}
os.close();
}
void Settings::save(string filename)
{
std::ofstream os(filename);
for (map<string, int>::iterator p = m_collection.begin(); p != m_collection.end(); p++)
{
std::cout << "Updating - " << p->first << " = " << p->second << std::endl;
os << p->first << "|" << p->second << std::endl;
}
os.close();
}
<file_sep>/cmake/open62541.cmake
####################################################################################################
# Providing LibXML2 library - https://gitlab.gnome.org/GNOME/libxml2.git #
# #
# To use the LibXML2 library simply link to it: #
# target_link_libraries(<project> PRIVATE LibXml2::LibXml2). #
# This automatically sets all required information such as include directories, definitions etc. #
####################################################################################################
set(open62541_version_tag "v1.0")
if(NOT TARGET Open62541::Open62541)
message(STATUS "Make Open62541 (${open62541_version_tag}) available.")
include(FetchContent)
FetchContent_Declare(
open62541provider
GIT_REPOSITORY "https://github.com/open62541/open62541.git"
GIT_TAG ${open62541_version_tag}
)
FetchContent_GetProperties(open62541provider)
if(UNIX)
set(build_options "-j4")
else()
set(build_options "-m:4")
endif()
set(_link_library "${CMAKE_BINARY_DIR}/install/open62541/lib/${CMAKE_STATIC_LIBRARY_PREFIX}open62541${CMAKE_STATIC_LIBRARY_SUFFIX}")
if(EXISTS "${_link_library}")
message(STATUS " * Reusing previously built open62541 library")
else()
message(STATUS " * Donwload open62541")
FetchContent_Populate(open62541provider)
message(STATUS " * Configure open62541")
execute_process(
COMMAND ${CMAKE_COMMAND}
-DBUILD_SHARED_LIBS=FALSE
-DCMAKE_BUILD_TYPE=RelWithDebInfo
-DUA_NAMESPACE_ZERO=FULL
-DUA_ENABLE_SUBSCRIPTIONS_EVENTS=ON
-DCMAKE_VERBOSE_MAKEFILE=${CMAKE_VERBOSE_MAKEFILE}
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}
-DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}
-DCMAKE_CXX_STANDARD_REQUIRED=${CMAKE_CXX_STANDARD_REQUIRED}
-DCMAKE_CXX_EXTENSIONS=${CMAKE_CXX_EXTENSIONS}
-DWINVER=${WINVER}
-DBUILD_SHARED_LIBS=OFF
-DOPEN62541_VERSION=${open62541_version_tag}
-DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/install/open62541
${open62541provider_SOURCE_DIR}
WORKING_DIRECTORY ${open62541provider_BINARY_DIR}
OUTPUT_FILE ${open62541provider_BINARY_DIR}/configure_output.log
ERROR_FILE ${open62541provider_BINARY_DIR}/configure_output.log
)
file(READ "${open62541provider_BINARY_DIR}/configure_output.log" _output)
message("============================================================")
message("${_output}")
message("============================================================")
message(STATUS " * Build Open62541")
execute_process(
COMMAND ${CMAKE_COMMAND} --build . --target install -- ${build_options}
WORKING_DIRECTORY ${open62541provider_BINARY_DIR}
OUTPUT_FILE ${open62541provider_BINARY_DIR}/build_output.log
ERROR_FILE ${open62541provider_BINARY_DIR}/build_output.log
)
file(READ "${open62541provider_BINARY_DIR}/build_output.log" _output)
message("============================================================")
message("${_output}")
message("============================================================")
endif()
# Make Open62541 library available within CMake
add_library(Open62541::Open62541 STATIC IMPORTED)
set_target_properties(Open62541::Open62541 PROPERTIES
IMPORTED_LOCATION "${_link_library}"
INTERFACE_INCLUDE_DIRECTORIES "${CUSTOM_MAKE_PATH}/include;${CMAKE_BINARY_DIR}/install/open62541/include"
)
endif()
<file_sep>/types_mgr.h
#ifndef TYPES_MGR_H
#define TYPES_MGR_H
#include <string>
#include <map>
using namespace std;
class TypesMgr
{
private:
static int m_namespace; // MTConnect Nodes namespace
UA_Server *m_uaServer;
map<string, map<string, int>> m_store;
bool loadDictionary(string typeName);
bool loadDictionary(string key, UA_NodeId node);
bool findChildId(UA_NodeId &parentNode, UA_NodeId referenceType,
const UA_QualifiedName targetName, UA_NodeId *result);
map<string, int>& getMap(string typeName);
public:
TypesMgr();
void setup(UA_Server *server);
int lookup(string typeName, string data);
int lookup(string typeName, UA_NodeId node, string data);
bool getDictionary(string typeName, UA_Variant &enumStrings);
};
#endif // TYPES_MGR_H
<file_sep>/types_mgr.cpp
#include <iostream>
#include <open62541/server.h>
#include <open62541/types.h>
#include "types_mgr.h"
#include "mtconnect_ids.h"
#include "util.h"
int TypesMgr::m_namespace = 2;
TypesMgr::TypesMgr()
{
}
void TypesMgr::setup(UA_Server *server)
{
m_uaServer = server;
}
int TypesMgr::lookup(string typeName, string data)
{
map<string, int> &dict = getMap(typeName);
auto searchDict = dict.find(data);
if (searchDict == dict.end())
return -1;
return searchDict->second;
}
int TypesMgr::lookup(string typeName, UA_NodeId node, string data)
{
auto search = m_store.find(typeName);
if (search == m_store.end())
{
// try to load the dictionary on the fly from UA_Nodes
if (!loadDictionary(typeName, node))
return -1;
search = m_store.find(typeName);
if (search == m_store.end())
return -1; // should be loaded, something is wrong
}
map<string, int> &dict = search->second;
auto searchDict = dict.find(data);
if (searchDict == dict.end())
return -1;
return searchDict->second;
}
bool TypesMgr::getDictionary(string typeName, UA_Variant &enumStrings)
{
map<string, int> & dict = getMap(typeName);
int numEnumValues = dict.size();
if (numEnumValues == 0)
return false;
UA_LocalizedText *data = (UA_LocalizedText *)UA_malloc(sizeof(UA_LocalizedText) * numEnumValues);
int i = 0;
for (std::map<string,int>::iterator it = dict.begin(); it != dict.end(); it++, i++)
data[i] = UA_LOCALIZEDTEXT("en", (char*)it->first.c_str());
UA_Variant_setArrayCopy(&enumStrings, data, numEnumValues, &UA_TYPES[UA_TYPES_LOCALIZEDTEXT]);
UA_free(data);
return true;
}
bool TypesMgr::loadDictionary(string typeName)
{
auto search = mtIDMap.find(typeName);
if (search == mtIDMap.end())
return false;
UA_NodeId node = UA_NODEID_NUMERIC(m_namespace, search->second);
return loadDictionary(typeName, node);
}
bool TypesMgr::loadDictionary(string key, UA_NodeId node)
{
// look up its "EnumStrings" property
UA_NodeId childID;
if (!findChildId(node,
UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY),
UA_QUALIFIEDNAME(0, "EnumStrings"), &childID))
{
if (!findChildId(node,
UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY),
UA_QUALIFIEDNAME(m_namespace, "EnumStrings"), &childID))
return false;
}
// load the enum table from its value
UA_Variant attr;
UA_Server_readValue(m_uaServer, childID, &attr);
if (attr.type->typeIndex != UA_TYPES_LOCALIZEDTEXT)
return false;
map<string, int> dict;
int len = attr.arrayLength;
UA_LocalizedText *results = (UA_LocalizedText *)attr.data;
for (int i=0; i<len; i++, results++)
{
string data = util::toString(results->text);
dict.insert(std::pair<string, int>(data, i) );
}
m_store.insert(std::pair<string, map<string, int>>(key, dict));
UA_Variant_deleteMembers(&attr);
UA_NodeId_deleteMembers(&childID);
return true;
}
bool TypesMgr::findChildId(UA_NodeId &parentNode, UA_NodeId referenceType,
const UA_QualifiedName targetName, UA_NodeId *result)
{
UA_RelativePathElement rpe;
UA_RelativePathElement_init(&rpe);
rpe.referenceTypeId = referenceType;
rpe.isInverse = false;
rpe.includeSubtypes = false;
rpe.targetName = targetName;
UA_BrowsePath bp;
UA_BrowsePath_init(&bp);
bp.startingNode = parentNode;
bp.relativePath.elementsSize = 1;
bp.relativePath.elements = &rpe; //clion complains but is ok
UA_BrowsePathResult bpr = UA_Server_translateBrowsePathToNodeIds(m_uaServer, &bp);
if(bpr.statusCode != UA_STATUSCODE_GOOD ||
bpr.targetsSize < 1)
return false;
UA_NodeId_copy(&bpr.targets[0].targetId.nodeId, result);
UA_BrowsePathResult_deleteMembers(&bpr);
return true;
}
map<string, int>& TypesMgr::getMap(string typeName)
{
auto search = m_store.find(typeName);
if (search == m_store.end())
{
// try to load the dictionary on the fly from UA_Nodes
if (!loadDictionary(typeName))
return m_store[""];
search = m_store.find(typeName);
if (search == m_store.end())
return m_store[""]; // should be loaded, something is wrong
}
return search->second;
}
<file_sep>/httpreader.cpp
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio.hpp>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <iostream>
#include <cctype>
#include <regex>
#include "httpreader.h"
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
HttpReader::HttpReader()
{
m_stream = nullptr;
m_isSSL = false;
m_lastConnectionTime = 0;
}
HttpReader::~HttpReader()
{
close();
}
bool HttpReader::connect()
{
try {
if (m_scheme.compare("https") == 0)
connectSSL();
else {
// These objects perform our I/O
tcp::resolver resolver(m_ioc);
m_stream = new tcp::socket(m_ioc);
// Look up the domain name
auto const results = resolver.resolve(m_host, m_port);
boost::asio::connect(*m_stream, results.begin(), results.end());
}
}
catch (exception &e)
{
std::cerr << "[" << m_host << ":" << m_port << "] " << e.what() << endl;
return false;
}
boost::system::error_code ec;
boost::asio::socket_base::keep_alive option(true);
m_stream->set_option(option, ec);
m_lastConnectionTime = time(nullptr);
return true;
}
bool HttpReader::connectSSL()
{
// The SSL context is required, and holds certificates
ssl::context ctx(ssl::context::tlsv12_client);
// Verify the remote server's certificate
ctx.set_verify_mode(ssl::verify_none);
// These objects perform our I/O
tcp::resolver resolver(m_ioc);
ssl::stream<tcp::socket> *stream = new ssl::stream<tcp::socket>(m_ioc, ctx);
// Set SNI Hostname (many hosts need this to handshake successfully)
if(!SSL_set_tlsext_host_name(stream->native_handle(), m_host.c_str()))
{
beast::error_code ec{static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()};
throw beast::system_error{ec};
}
// Look up the domain name
auto const results = resolver.resolve(m_host, m_port);
// Make the connection on the IP address we get from a lookup
boost::asio::connect(stream->next_layer(), results.begin(), results.end());
// Perform the SSL handshake
stream->handshake(ssl::stream_base::client);
if (m_stream)
delete m_stream;
m_stream = (tcp::socket *)stream;
return true;
}
void HttpReader::close()
{
if (m_stream != nullptr)
{
try {
beast::error_code ec;
m_stream->shutdown(tcp::socket::shutdown_both, ec);
m_buffer.consume(m_buffer.size());
// delete m_stream;
}
catch (exception &e)
{
cerr << e.what() << endl;
}
delete m_stream;
m_stream = nullptr;
}
m_lastConnectionTime = 0;
}
string HttpReader::read()
{
if (m_stream == nullptr)
{
// try to reconnect
if (!connect())
return "";
}
// Declare a container to hold the response
http::response<http::string_body> res;
try {
// Set up an HTTP GET request message
http::request<http::string_body> req{http::verb::get, "/"+m_path + m_query, 11};
req.set(http::field::host, m_host);
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
if (m_isSSL)
http::write(*(ssl::stream<tcp::socket> *)m_stream, req);
else
http::write(*m_stream, req);
// Receive the HTTP response
if (m_isSSL)
http::read(*(ssl::stream<tcp::socket> *)m_stream, m_buffer, res);
else
http::read(*m_stream, m_buffer, res);
return res.body().data();
}
catch(std::exception const& e)
{
std::cerr << "[" << m_host << ":" << m_port << "] Error: " << e.what() << std::endl;
string respdata = res.body().data();
// try reconnect
close();
time_t last = m_lastConnectionTime;
if (!connect())
std::cerr <<
"[" << m_host << ":" << m_port << "] Fail to reconnect to MT agent!" << std::endl;
else {
std::cerr <<
"[" << m_host << ":" << m_port << "] Reconnect to MT agent!" << std::endl;
// avoid repeat read errors if reconnect happens within 5 seconds
if (m_lastConnectionTime - last > 5)
return read();
}
}
return "";
}
static const char* SCHEME_REGEX = "((http[s]?)://)?"; // match http or https before the ://
static const char* USER_REGEX = "(([^@/:\\s]+)@)?"; // match anything other than @ / : or whitespace before the ending @
static const char* HOST_REGEX = "([^@/:\\s]+)"; // mandatory. match anything other than @ / : or whitespace
static const char* PORT_REGEX = "(:([0-9]{1,5}))?"; // after the : match 1 to 5 digits
static const char* PATH_REGEX = "(/[^:#?\\s]*)?"; // after the / match anything other than : # ? or whitespace
static const char* QUERY_REGEX = "(\\?(([^?;&#=]+=[^?;&#=]+)([;|&]([^?;&#=]+=[^?;&#=]+))*))?"; // after the ? match any number of x=y pairs, seperated by & or ;
static const char* FRAGMENT_REGEX = "(#([^#\\s]*))?"; // after the # match anything other than # or whitespace
static const std::regex regExpr(std::string("^")
+ SCHEME_REGEX + USER_REGEX
+ HOST_REGEX + PORT_REGEX
+ PATH_REGEX + QUERY_REGEX
+ FRAGMENT_REGEX + "$");
bool HttpReader::parseUri(const string &uri)
{
std::smatch matchResults;
if (std::regex_match(uri.cbegin(), uri.cend(), matchResults, regExpr))
{
m_scheme.assign(matchResults[2].first, matchResults[2].second);
boost::algorithm::to_lower(m_scheme);
m_user.assign(matchResults[4].first, matchResults[4].second);
m_host.assign(matchResults[5].first, matchResults[5].second);
m_port.assign(matchResults[7].first, matchResults[7].second);
m_path.assign(matchResults[8].first, matchResults[8].second);
m_query.assign(matchResults[10].first, matchResults[10].second);
m_fragment.assign(matchResults[15].first, matchResults[15].second);
if (m_port.length() == 0)
{
if (m_scheme.compare("https") == 0)
{
m_port = "443";
m_isSSL = true;
}
else
m_port = "80";
}
return true;
}
return false;
}
<file_sep>/httpreader.h
#ifndef HTTPREADER_H
#define HTTPREADER_H
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <string>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = boost::beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
namespace ssl = net::ssl; // from <boost/asio/ssl.hpp>
using namespace std;
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
class HttpReader
{
private:
string httpAddress;
string m_scheme;
string m_user;
string m_host;
string m_port;
string m_path;
string m_query;
string m_fragment;
bool m_isSSL;
tcp::socket *m_stream;
time_t m_lastConnectionTime;
beast::flat_buffer m_buffer;
net::io_context m_ioc;
bool connectSSL();
string readSSL();
public:
HttpReader();
~HttpReader();
void setQuery(string query) { m_query = query; }
bool parseUri(const string &uri);
bool connect();
void close();
string read();
};
#endif // HTTPREADER_H
<file_sep>/mteuInfo.h
#include <string>
#include <map>
class EuInfo {
public:
string m_code;
int m_unitId;
string m_displayName;
string m_description;
public:
EuInfo(string code, int unitId, string displayName, string description)
{
m_code = code;
m_unitId = unitId;
m_displayName = displayName;
m_description = description;
}
};
static map<string, EuInfo> euStore = {
{"AMPERE", EuInfo("AMP", 4279632, "A", "Amps") },
{"CELSIUS", EuInfo("CEL", 4408652, "◦Celsuis", "Degrees Celsius") },
{"COUNT", EuInfo("", 0, "", "Count") },
{"DECIBEL", EuInfo("2N", 12878, "dB", "Sound Level") },
{"DEGREE", EuInfo("DD", 17476, "◦", "degree [unit of angle]") },
{"DEGREE/SECOND", EuInfo("E96", 4536630, "◦/s", "Angular degrees per second") },
{"DEGREE/SECONDˆ2", EuInfo("M45", 5059637, "◦", "Angular acceleration in degrees per second squared") },
{"HERTZ", EuInfo("HTZ", 4740186, "Hz", "Frequency measured in cycles per second") },
{"JOULE", EuInfo("JOU", 4869973, "J", "A measurement of energy.") },
{"KILOGRAM", EuInfo("KGM", 4933453, "kg", "kilogram") },
{"LITER", EuInfo("LTR", 5002322, "l", "Litre") },
{"LITER/SECOND", EuInfo("G51", 4666673, "l/s", "Litre per second") },
{"MICRO_RADIAN", EuInfo("B97", 4340023, "μ", "microradian - Measurement of Tilt") },
{"MILLIMETER", EuInfo("MMT", 5066068, "mm", "millimetre") },
{"MILLIMETER/SECOND", EuInfo("C16", 4403510, "mm/s", "millimetre per second") },
{"MILLIMETER/SECONDˆ2", EuInfo("M41", 5059633, "mm/s2", "Acceleration in millimeters per second squared") },
{"MILLIMETER_3D", EuInfo("MMT", 5066068, "mm(R3", "A point in space identified by X") },
{"NEWTON", EuInfo("NEW", 5129559, "N", "Force in Newtons") },
{"NEWTON_METER", EuInfo("NU", 20053, "N·m", "Torque") },
{"OHM", EuInfo("OHM", 5195853, "Ω", "Measure of Electrical Re- sistance") },
{"PASCAL", EuInfo("PAL", 5259596, "Pa", "Pressure in Newtons per square meter") },
{"PASCAL_SECOND", EuInfo("C65", 4404789, "Pa·s", "Measurement of Viscosity") },
{"PERCENT", EuInfo("P1", 20529, "%", "Percent") },
{"PH", EuInfo("Q30", 5321520, "pH", "pH (potential of Hydrogen) - A measure of the acidity or alkalinity of a solution") },
{"REVOLUTION/MINUTE", EuInfo("RPM", 5394509, "r/min", "revolutions per minute") },
{"SECOND", EuInfo("SEC", 5457219, "s", "second [unit of time]") },
{"SIEMENS/METER", EuInfo("D10", 4469040, "S/m", "siemens per metre - A mea- surement of Electrical Con- ductivity") },
{"VOLT", EuInfo("VLT", 5655636, "V", "volt") },
{"VOLT_AMPERE", EuInfo("D46", 4469814, "VA", "volt - ampere") },
{"VOLT_AMPERE_REACTIVE", EuInfo("", -1, "VAR", "Volt-Ampere Reactive (VAR)") },
{"WATT", EuInfo("WTT", 5723220, "W", "watt") },
{"WATT_SECOND", EuInfo("J55", 4863285, "W·s", "Measurement of electrical energy") }
};
|
7f0c8e7e6f4012845ee1c4b0db26a4ab628985fb
|
[
"CMake",
"Markdown",
"Dockerfile",
"C",
"C++",
"Shell"
] | 17 |
C
|
strangesast/open62541_ua_server
|
7efa67c9bcc4ff5b3f4862bb98c1d42a2858e897
|
3282ed8b965131106d1ef0cbc8ee78dc17a29ae5
|
refs/heads/master
|
<file_sep># ComboBox Demo
import Tkinter
import Tkinter as tkinter
import ttk
import tkFont
from Tkinter import *
from ttk import *
# Get flyer name module
def foo(event):
#print v.get()
category = v.get()
# Main Root
root = Tkinter.Tk()
root.title("ComboBox Demo")
tab = ttk.Notebook(root)
tab1 = ttk.Frame(root)
tab.add(tab1, text = "ComboBox Demo")
tab.place(width=700, height=500)
labelframe = LabelFrame(tab1, text="Analyzer")
labelframe.pack(fill="both", expand="yes")
var = StringVar()
label1 = Label(labelframe, font="Tahoma 11", text="Select Flyer")
label1.place(x=10,y=18)
# here in this list you need to populate it with the data from MonoDB
options = ['','rcwhalen','JaJillian','smb50','vickie_risbie']
v = StringVar()#a string variable to hold user selection
#available combobox options
frame = Frame(labelframe)
frame.pack(side='top', fill='x', padx=12, pady=8)
#frame.place(x=125,y=10)
combo = Combobox(labelframe,textvariable=v, values=options,font="Tahoma 11")
combo.bind('<<ComboboxSelected>>',foo)#binding of user selection with a custom callback
combo.current(0)#set as default "option 2"
#combo.pack(side='left', anchor='w', padx=12, pady=8 )
combo.place(x=125,y=16)
root.resizable(width=FALSE, height=FALSE) # disable maximize button
root.geometry("700x500")
root.mainloop()
exit()
<file_sep># python-source-code
Python Source Codes
<file_sep># Python Program to register courses to students using Stable Roommate Algorithm
|
6efbf878a1983cbe44aba97e04b090bb6fbbf454
|
[
"Markdown",
"Python"
] | 3 |
Python
|
HumayunMulla/python-source-code
|
c8a6ea0055566d48361d69746307f98d760fca1f
|
c3ecad4eb8bd9a0b8bbf70b2704abcf9ae896308
|
refs/heads/master
|
<file_sep>#include "IdleCell.h"
/*
Constructors
*/
IdleCell::IdleCell() : Cell(CellLabels::Idle){}
/*
Member Functions
*/
bool IdleCell::in_action(){
return true;
}
bool IdleCell::out_action(){
return true;
}
bool IdleCell::idle_action(){
return true;
}<file_sep>#include "Agent.h"
bool Agent::set_loaded(bool loaded){
_loaded = loaded;
return true;
}
bool Agent::set_path(std::vector<std::pair<int, int>> path)
{
_path = std::move(path);
_path_i = 0;
return true;
}
int Agent::get_row()
{
return _row;
}
int Agent::get_col()
{
return _col;
}
bool Agent::get_loaded()
{
return _loaded;
}
std::vector<std::pair<int, int>> Agent::get_path()
{
return _path;
}<file_sep>#include "PickupCell.h"
/*
Constructors
*/
PickupCell::PickupCell() : Cell(CellLabels::Pickup){}
/*
Member Functions
*/
bool PickupCell::in_action(){
return true;
}
bool PickupCell::out_action(){
return true;
}
bool PickupCell::idle_action(){
return true;
}<file_sep>#ifndef AGENT_H
#define AGENT_H
#include <vector>
#include <utility>
class Agent
{
protected:
int _row;
int _col;
bool _loaded;
std::vector<std::pair<int, int>> _path;
int _path_i;
public:
Agent() : _row(), _col() {}
Agent(int row, int col) : _row(row), _col(col) {}
virtual ~Agent() = default;
bool set_loaded(bool loaded);
bool set_path(std::vector<std::pair<int, int>> path);
int get_row();
int get_col();
bool get_loaded();
std::vector<std::pair<int, int>> get_path();
virtual bool move(int drow, int dcol) = 0;
virtual bool move() = 0;
};
#endif<file_sep>#pragma once
struct DeliveryBlock {
int row;
int col;
int height;
int width;
};
struct PickupBlock {
int row;
int col;
int height;
int width;
};
struct IdleBlock {
int row;
int col;
int height;
int width;
};<file_sep>#include "Grid.h"
/*
Constructors
*/
Grid::Grid(int n_rows, int n_cols)
{
_n_rows = n_rows;
_n_cols = n_cols;
_grid.resize(n_rows);
for(auto &i : _grid){
i.reserve(n_cols);
for (int j = 0; j < n_cols; ++j)
i.push_back(std::make_unique<TileCell>());
}
}
/*
Member Functions
*/
//pretty fast for grids
std::vector<std::pair<int, int>> Grid::dijkstras(std::pair<int, int> src, std::pair<int, int> dest){
long INF = LONG_MAX;
int dr[] = {1, -1, 0, 0};
int dc[] = {0, 0, 1, -1};
std::vector<std::vector<long>> dists(_n_rows, std::vector<long>(_n_cols, INF));
std::vector<std::vector<std::pair<int, int>>> preds(_n_rows, std::vector<std::pair<int, int>>(_n_cols, std::make_pair(-1, -1)));
dists[src.first][src.second] = 0;
std::priority_queue<std::pair<long, std::pair<int, int>>, std::vector<std::pair<long, std::pair<int, int>> >, std::greater<std::pair<long, std::pair<int, int>>>> pq;
pq.push(std::make_pair(1, std::make_pair(src.first, src.second)));
while(!pq.empty()){
std::pair<long, std::pair<int, int>> p = pq.top();
pq.pop();
int r = p.second.first;
int c = p.second.second;
if(r == dest.first && c == dest.second) break;
std::vector<std::pair<int, int>> valid_dirs = _grid[r][c]->get_dirs();
for(int i = 0; i<4; ++i){
int nr = r+dr[i];
int nc = c+dc[i];
// && _grid[nr][nc]->get_label() == CellLabels::Tile
if(is_valid_pos(nr, nc) && std::count(valid_dirs.begin(), valid_dirs.end(), std::make_pair(dr[i], dc[i]))){
if(dists[r][c] + 1 < dists[nr][nc]){
dists[nr][nc] = dists[r][c] + 1;
preds[nr][nc] = std::make_pair(r, c);
//FIXME Look at this function, maybe make the beach effect easier
if((r == src.first && c == src.second && _grid[nr][nc]->get_label() == CellLabels::Tile) || _grid[r][c]->get_label() == CellLabels::Tile)
pq.push(std::make_pair(dists[nr][nc], std::make_pair(nr, nc)));
}
}
}
}
// printf("Shortest Path: %ld\n", dists[dest.first][dest.second]);
std::vector<std::pair<int, int>> path;
if(dists[dest.first][dest.second] != INF){
std::pair<int, int> pos = dest;
while(pos != src){
path.push_back(pos);
pos = preds[pos.first][pos.second];
}
std::reverse(path.begin(), path.end());
}
return path;
}
std::pair<int, int> Grid::find_nearest_empty(std::pair<int, int> src, CellLabels label)
{
int dr[] = {1, -1, 0, 0};
int dc[] = {0, 0, 1, -1};
std::vector<std::vector<bool>> vis(_n_rows, std::vector<bool>(_n_cols, false));
std::stack<std::pair<int, int>> st;
st.push(src);
while(!st.empty()){
std::pair<int, int> pos = st.top();
int r = pos.first;
int c = pos.second;
if(_grid[r][c]->get_label() == label){
//FIXME Look at this function, maybe apply occupied to a cell
bool occupied = false;
for(auto & agent : _agents)
if(agent->get_row() == r && agent->get_col() == c){
occupied = true;
break;
}
if(!occupied)
return pos;
}
st.pop();
vis[r][c] = true;
std::vector<std::pair<int, int>> valid_dirs = _grid[r][c]->get_dirs();
for(int i = 0; i < 4; ++i){
int nr = r+dr[i];
int nc = c+dc[i];
if(is_valid_pos(nr, nc) && !vis[nr][nc] && std::count(valid_dirs.begin(), valid_dirs.end(), std::make_pair(dr[i], dc[i])))
st.push({nr, nc});
}
}
return {-1, -1};
}
bool Grid::is_valid_pos(int row, int col)
{
return row >= 0 && row < _grid.size() && col >= 0 && col < _grid[row].size();
}
std::vector<std::pair<int, int>> Grid::find_path(std::pair<int, int> src, std::pair<int, int> dest)
{
if(!is_valid_pos(dest.first, dest.second) || !is_valid_pos(src.first, src.second))
return { {-1, -1} };
std::vector<std::pair<int, int>> path = dijkstras(src, dest);
return path;
}
bool Grid::add_agent(std::unique_ptr<Agent> agent)
{
_agents.push_back(std::move(agent));
return true;
}
bool Grid::signal_agents()
{
for(auto & agent : _agents){
int row = agent->get_row();
int col = agent->get_col();
if(_grid[row][col]->get_label() == CellLabels::Idle){
std::vector<std::pair<int, int>> path = find_path({row, col}, {0,0});
agent->set_path(path);
}else if(agent->get_path().empty() && _grid[row][col]->get_label() == CellLabels::Tile){
//FIXME Consider concurrency issues with agent movement
std::pair<int, int> nearest_idle = find_nearest_empty({row, col}, CellLabels::Idle);
printf("%d %d\n", nearest_idle.first, nearest_idle.second);
if(nearest_idle != std::make_pair(-1, -1)){
std::vector<std::pair<int, int>> path = find_path({row, col}, nearest_idle);
for(auto p : path)
printf("(%d %d) ", p.first, p.second);
printf("\n");
agent->set_path(path);
}
}
}
for(auto & agent : _agents)
agent->move();
return true;
}
bool Grid::set_cell(int row, int col, std::unique_ptr<Cell> cell)
{
if(!is_valid_pos(row, col))
return false;
_grid[row][col] = std::move(cell);
return true;
}
bool Grid::set_cell_block(int row, int col, int width, int height, CellLabels cell_type)
{
for(int i = row; i < row + height; ++i){
for(int j = col; j < col + width; ++j){
if(is_valid_pos(i, j)){
switch(cell_type){
case CellLabels::Tile:
{
set_cell(i, j, std::make_unique<TileCell>());
break;
}
case CellLabels::Idle:
{
set_cell(i, j, std::make_unique<IdleCell>());
break;
}
case CellLabels::Pickup:
{
set_cell(i, j, std::make_unique<PickupCell>());
break;
}
case CellLabels::Delivery:
{
set_cell(i, j, std::make_unique<DeliveryCell>());
break;
}
default:
return false;
}
}else
return false;
}
}
return true;
}
int Grid::get_n_rows()
{
return _n_rows;
}
int Grid::get_n_cols()
{
return _n_cols;
}
Cell * Grid::get_cell(int row, int col)
{
if(!is_valid_pos(row, col))
return nullptr;
return _grid[row][col].get();
}
std::vector<std::pair<int, int>> Grid::get_agent_positions()
{
std::vector<std::pair<int, int>> positions;
for(auto & agent : _agents)
positions.push_back(std::make_pair(agent->get_row(), agent->get_col()));
return positions;
}<file_sep>#ifndef CELL_H
#define CELL_H
#include <vector>
#include <utility>
enum CellLabels { Delivery, Idle, Pickup, Tile, Error };
enum Directions { North, South, East, West, None };
class Cell
{
protected:
std::vector<std::pair<int, int>> _dirs;
CellLabels _label;
public:
Cell() : _dirs(), _label() {}
Cell(CellLabels label) : _label(label) {}
Cell(std::vector<std::pair<int, int>> dirs) : _dirs(std::move(dirs)) {}
Cell(std::vector<std::pair<int, int>> dirs, CellLabels label) : _dirs(std::move(dirs)), _label(label) {}
virtual ~Cell() = default;
void add_dir(std::pair<int, int> to_pos);
std::vector<std::pair<int, int>> get_dirs();
CellLabels get_label();
virtual bool in_action() = 0;
virtual bool out_action() = 0;
virtual bool idle_action() = 0;
};
#endif<file_sep>#ifndef IDLECELL_H
#define IDLECELL_H
#include "Cell.h"
class IdleCell : public Cell
{
private:
public:
IdleCell();
bool in_action();
bool out_action();
bool idle_action();
};
#endif<file_sep>#ifndef TILECELL_H
#define TILECELL_H
#include "Cell.h"
class TileCell : public Cell
{
private:
public:
TileCell();
bool in_action();
bool out_action();
bool idle_action();
};
#endif<file_sep>#ifndef GRID_H
#define GRID_H
#include <vector>
#include <utility>
#include <queue>
#include <stack>
#include <memory>
#include "WorkAgent.h"
#include "TileCell.h"
#include "IdleCell.h"
#include "PickupCell.h"
#include "DeliveryCell.h"
class Grid
{
private:
int _n_rows;
int _n_cols;
std::vector<std::vector<std::unique_ptr<Cell>>> _grid;
std::vector<std::unique_ptr<Agent>> _agents;
std::vector<std::pair<int, int>> dijkstras(std::pair<int, int> src, std::pair<int, int> dest);
public:
Grid(int n_rows, int n_cols);
bool is_valid_pos(int row, int col);
std::vector<std::pair<int, int>> find_path(std::pair<int, int> src, std::pair<int, int> dest);
std::pair<int, int> find_nearest_empty(std::pair<int, int> src, CellLabels label);
bool add_agent(std::unique_ptr<Agent> agent);
bool signal_agents();
bool set_cell(int row, int col, std::unique_ptr<Cell> cell);
bool set_cell_block(int row, int col, int width, int height, CellLabels cell_type);
int get_n_rows();
int get_n_cols();
Cell * get_cell(int row, int col);
std::vector<std::pair<int, int>> get_agent_positions();
};
#endif<file_sep>#ifndef PICKUPCELL_H
#define PICKUPCELL_H
#include "Cell.h"
class PickupCell : public Cell
{
private:
public:
PickupCell();
bool in_action();
bool out_action();
bool idle_action();
};
#endif<file_sep>#include "Cell.h"
void Cell::add_dir(std::pair<int, int> to_pos)
{
if(std::count(_dirs.begin(), _dirs.end(), to_pos) == 0)
_dirs.push_back(to_pos);
}
std::vector<std::pair<int, int>> Cell::get_dirs()
{
return _dirs;
}
CellLabels Cell::get_label()
{
return _label;
}<file_sep>#include "DeliveryCell.h"
/*
Constructors
*/
DeliveryCell::DeliveryCell() : Cell(CellLabels::Delivery){}
/*
Member Functions
*/
bool DeliveryCell::in_action(){
return true;
}
bool DeliveryCell::out_action(){
return true;
}
bool DeliveryCell::idle_action(){
return true;
}<file_sep>#ifndef WORKAGENT_H
#define WORKAGENT_H
#include "Agent.h"
class WorkAgent : public Agent
{
private:
public:
WorkAgent(int row, int col);
bool move(int drow, int dcol);
bool move();
};
#endif<file_sep># depotech
# Build
```
git clone https://github.com/danjrauch/depotech
cd depotech
mkdir build
cmake --build build/
./build/depotech
```
# Memchecks
## Using experimental valgrind on macOS Catalina
https://github.com/sowson/valgrind
Not currently working on Catalina. Need to wait for main valgrind master branch.
```
valgrind ./client --leak-check=full -vvv
```<file_sep>#include "WorkAgent.h"
/*
Constructors
*/
WorkAgent::WorkAgent(int row, int col) : Agent(row, col){}
/*
Member Functions
*/
bool WorkAgent::move(int drow, int dcol)
{
_row += drow;
_col += dcol;
return true;
}
bool WorkAgent::move()
{
if(_path.empty() || _path_i < 0 || _path_i >= _path.size())
return false;
int drow = _path[_path_i].first - _row;
int dcol = _path[_path_i].second - _col;
move(drow, dcol);
_path_i++;
if(_path_i == _path.size()){
_path.clear();
_path_i = 0;
}
return true;
}<file_sep>#include "TileCell.h"
/*
Constructors
*/
TileCell::TileCell() : Cell(CellLabels::Tile){}
/*
Member Functions
*/
bool TileCell::in_action(){
return true;
}
bool TileCell::out_action(){
return true;
}
bool TileCell::idle_action(){
return true;
}<file_sep>#ifndef DELIVERYCELL_H
#define DELIVERYCELL_H
#include "Cell.h"
class DeliveryCell : public Cell
{
private:
public:
DeliveryCell();
bool in_action();
bool out_action();
bool idle_action();
};
#endif<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include "raylib.h"
#include "raymath.h"
#include "block.h"
#include "Grid.h"
using namespace std;
const int tile_width = 15;
const int screen_width = tile_width * 56;
const int screen_height = tile_width * 26;
const double agent_radius = 0.3*tile_width;
const int dr[4] = { 0, 0, 1, -1 };
const int dc[4] = { 1, -1, 0, 0 };
vector<DeliveryBlock> delivery_block_positions { {6,5,6,2}, {10,5,6,2}, {14,5,6,2}, {18,5,6,2},
{6,45,6,2}, {10,45,6,2}, {14,45,6,2}, {18,45,6,2} };
vector<PickupBlock> pickup_block_positions { {6,13,6,2}, {6,21,6,2}, {6,29,6,2}, {6,37,6,2},
{10,13,6,2}, {10,21,6,2}, {10,29,6,2}, {10,37,6,2},
{14,13,6,2}, {14,21,6,2}, {14,29,6,2}, {14,37,6,2},
{18,13,6,2}, {18,21,6,2}, {18,29,6,2}, {18,37,6,2} };
vector<IdleBlock> idle_block_positions { {5,0,3,4}, {11,0,3,4}, {17,0,3,4},
{0,10,4,3}, {0,18,4,3}, {0,26,4,3}, {0,34,4,3}, {0,42,4,3},
{5,53,3,4}, {11,53,3,4}, {17,53,3,4},
{23,10,4,3}, {23,18,4,3}, {23,26,4,3}, {23,34,4,3}, {23,42,4,3} };
void DrawCellDirection(int row, int col, Directions dir)
{
float x = (float)col*tile_width;
float y = (float)row*tile_width;
int offset = (float)tile_width * 0.35;
Vector2 top_left = {x+offset, y+offset};
Vector2 top_right = {x+tile_width-offset, y+offset};
Vector2 bot_left = {x+offset, y+tile_width-offset};
Vector2 bot_right = {x+tile_width-offset, y+tile_width-offset};
float arrow_side_length = Vector2Distance(top_left, bot_left);
float arrow_height = arrow_side_length * sqrtf(3) / 2;
switch(dir)
{
case Directions::West:
DrawTriangle(top_left, {x+offset-arrow_height, y+offset+arrow_side_length*(float)0.5}, bot_left, RED);
break;
case Directions::North:
DrawTriangle(top_left, top_right, {x+offset+arrow_side_length*(float)0.5, y+offset-arrow_height}, RED);
break;
case Directions::East:
DrawTriangle(top_right, bot_right, {x+tile_width-offset+arrow_height, y+offset+arrow_side_length*(float)0.5}, RED);
break;
case Directions::South:
DrawTriangle(bot_left, {x+offset+arrow_side_length*(float)0.5, y+tile_width-offset+arrow_height}, bot_right, RED);
break;
default:
break;
}
}
std::pair<int, int> GetMouseCell(){
int mouse_x = GetMouseX();
int mouse_y = GetMouseY();
int row = mouse_y / tile_width;
int col = mouse_x / tile_width;
return make_pair(row, col);
}
int main(void)
{
// Grid G (3, 3);
// G.set_cell(2, 2, std::make_unique<PickupCell>(true));
// for(int i = 0; i < G.get_n_rows(); ++i){
// for(int j = 0; j < G.get_n_cols(); ++j)
// printf("%d ", G.is_cell_occupied(i, j));
// printf("\n");
// }
// printf("\n");
// printf("(2,2) is %s\n", G.is_cell_occupied(2,2) ? "occupied" : "unoccupied");
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screen_width, screen_height, "Depotech Simulator");
SetTargetFPS(60);
srand(time(NULL));
Grid G (screen_height/tile_width, screen_width/tile_width);
for(DeliveryBlock b : delivery_block_positions)
G.set_cell_block(b.row, b.col, b.height, b.width, CellLabels::Delivery);
for(PickupBlock b : pickup_block_positions)
G.set_cell_block(b.row, b.col, b.height, b.width, CellLabels::Pickup);
for(IdleBlock b : idle_block_positions)
G.set_cell_block(b.row, b.col, b.height, b.width, CellLabels::Idle);
for(int i = 0; i < G.get_n_rows(); ++i)
for(int j = 0; j < G.get_n_cols(); ++j){
if(G.get_cell(i, j)->get_label() == CellLabels::Idle){
std::unique_ptr<Agent> agent = std::make_unique<WorkAgent>(i, j);
// agent->set_path()
G.add_agent(std::move(agent));
}
}
std::pair<int, int> prev_mouse_cell = GetMouseCell();
std::pair<int, int> mouse_cell = GetMouseCell();
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if(IsKeyDown(KEY_SPACE)){
mouse_cell = GetMouseCell();
if(G.is_valid_pos(mouse_cell.first, mouse_cell.second)){
std::vector<std::pair<int, int>> path = G.find_path(prev_mouse_cell, {0,0});
if(!path.empty()){
for(auto p : path)
DrawRectangle(p.second*tile_width, p.first*tile_width, tile_width, tile_width, LIME);
}
}
if(abs(prev_mouse_cell.first - mouse_cell.first) > 1 || abs(prev_mouse_cell.second - mouse_cell.second) > 1){
prev_mouse_cell = GetMouseCell();
}
if(IsKeyDown(KEY_SPACE) && G.is_valid_pos(mouse_cell.first, mouse_cell.second) && G.is_valid_pos(prev_mouse_cell.first, prev_mouse_cell.second) && mouse_cell != prev_mouse_cell){
int drow = mouse_cell.first - prev_mouse_cell.first;
int dcol = mouse_cell.second - prev_mouse_cell.second;
G.get_cell(prev_mouse_cell.first, prev_mouse_cell.second)->add_dir(std::make_pair(drow, dcol));
}
prev_mouse_cell = mouse_cell;
}
G.signal_agents();
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(LIGHTGRAY);
for(int i = 0; i < G.get_n_rows(); ++i)
for(int j = 0; j < G.get_n_cols(); ++j){
switch(G.get_cell(i, j)->get_label()){
case CellLabels::Tile:
// DrawRectangleLines(j*tile_width, i*tile_width, tile_width, tile_width, BLACK);
if(IsMouseButtonDown(MOUSE_LEFT_BUTTON)){
for(auto p : G.get_cell(i, j)->get_dirs()){
if(p == make_pair(0, 1))
DrawCellDirection(i, j, Directions::East);
else if(p == make_pair(1, 0))
DrawCellDirection(i, j, Directions::South);
else if(p == make_pair(0, -1))
DrawCellDirection(i, j, Directions::West);
else if(p == make_pair(-1, 0))
DrawCellDirection(i, j, Directions::North);
}
}
break;
case CellLabels::Delivery:
DrawRectangle(j*tile_width, i*tile_width, tile_width, tile_width, BLUE);
DrawRectangleLines(j*tile_width, i*tile_width, tile_width, tile_width, BLACK);
if(IsMouseButtonDown(MOUSE_LEFT_BUTTON))
DrawText("D", j*tile_width+(float)tile_width*0.2, i*tile_width+(float)tile_width*0.2, 4, BLACK);
break;
case CellLabels::Pickup:
DrawRectangle(j*tile_width, i*tile_width, tile_width, tile_width, GREEN);
DrawRectangleLines(j*tile_width, i*tile_width, tile_width, tile_width, BLACK);
if(IsMouseButtonDown(MOUSE_LEFT_BUTTON))
DrawText("P", j*tile_width+(float)tile_width*0.2, i*tile_width+(float)tile_width*0.2, 4, BLACK);
break;
case CellLabels::Idle:
DrawRectangle(j*tile_width, i*tile_width, tile_width, tile_width, MAROON);
DrawRectangleLines(j*tile_width, i*tile_width, tile_width, tile_width, BLACK);
if(IsMouseButtonDown(MOUSE_LEFT_BUTTON))
DrawText("I", j*tile_width+(float)tile_width*0.2, i*tile_width+(float)tile_width*0.2, 4, BLACK);
break;
case CellLabels::Error:
default:
break;
}
}
for(auto pos : G.get_agent_positions()){
int row = pos.first;
int col = pos.second;
DrawCircleV({col*tile_width+(float)tile_width/2, row*tile_width+(float)tile_width/2}, agent_radius, BLACK);
}
std::stringstream cell_string;
cell_string << "Mouse is in cell [" << mouse_cell.first << ", " << mouse_cell.second << "]";
DrawText(cell_string.str().c_str(), 0, 20, 10, BLACK);
DrawFPS(0, 0);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
|
31e3c5377592100c0f0338ef2443592d17bad88c
|
[
"Markdown",
"C",
"C++"
] | 19 |
C++
|
danjrauch/depotech
|
7a2956a52ade1db198f9541819d1ba764e5338b6
|
3c7621c7f366c200662701b1deb7df277b68726b
|
refs/heads/master
|
<repo_name>hermex-trade/FreeArticles<file_sep>/src/Providers/FreeArticleServiceProvider.php
<?php
namespace FreeArticles\Providers;
use FreeArticles\Contracts\FreeArticleRepositoryContract;
use Plenty\Plugin\ServiceProvider;
use FreeArticles\Repositories\FreeArticleRepository;
class FreeArticleServiceProvider extends ServiceProvider
{
public function register()
{
$this->getApplication()->register(FreeArticleRouteServiceProvider::class);
$this->getApplication()->bind(FreeArticleRepositoryContract::class, FreeArticleRepository::class);
}
}
?><file_sep>/resources/lang/en/FreeArticles.properties
description = "Plugin to manage and display free articles"<file_sep>/src/Controllers/FreeArticleSearchController.php
<?php
namespace FreeArticles\Controllers;
use Plenty\Plugin\Controller;
use Plenty\Modules\Item\Variation\Contracts\VariationSearchRepositoryContract;
class FreeArticleSearchController extends Controller
{
/**
*/
public function find()
{
$repo = pluginApp(VariationSearchRepositoryContract::class);
$repo->setFilters([
'variationTagId' => 126
]);
$repo->setSearchParams([
'variationTagId' => 126,
'with' => [
'item' => null,
]
]);
$result = $repo->search();
$variation = $result->getResult();
return $variation;
}
}
?><file_sep>/src/Providers/FreeArticleRouteServiceProvider.php
<?php
namespace FreeArticles\Providers;
use Plenty\Plugin\RouteServiceProvider;
use Plenty\Plugin\Routing\Router;
class FreeArticleRouteServiceProvider extends RouteServiceProvider
{
public function map(Router $router)
{
// TODO Secure all routes but /freearticle
$router->get('freearticle', 'FreeArticles\Controllers\FreeArticleContentController@show');
$router->post('freearticle', 'FreeArticles\Controllers\FreeArticleContentController@create');
$router->put('freearticle/{id}', 'FreeArticles\Controllers\FreeArticleContentController@update')->where('id', '\d+');
$router->delete('freearticle/{id}', 'FreeArticles\Controllers\FreeArticleContentController@delete')->where('id', '\d+');
$router->get('freearticle/tag', 'FreeArticles\Controllers\FreeArticleSearchController@search')->addMiddleware(['oauth.cookie', 'oauth',]);
}
}
?><file_sep>/src/Controllers/FreeArticleContentController.php
<?php
namespace FreeArticles\Controllers;
use Plenty\Plugin\Controller;
use Plenty\Plugin\Http\Request;
use Plenty\Plugin\Templates\Twig;
use FreeArticles\Contracts\FreeArticleRepositoryContract;
class FreeArticleContentController extends Controller
{
public function show(Twig $twig, FreeArticleRepositoryContract $freeArticleRepo): string
{
$freeArticleList = $freeArticleRepo->getFreeArticleList();
//$templateData = array("freearticles" => $freeArticleList);
//return $twig->render('FreeArticles::content.freearticle', $templateData);
return json_encode($freeArticleList);
}
public function create(Request $request, FreeArticleRepositoryContract $freeArticleRepo): string
{
$createdFreeArticle = $freeArticleRepo->createFreeArticle($request->all());
return json_encode($createdFreeArticle);
}
public function update(int $id, array $data, FreeArticleRepositoryContract $freeArticleRepo): string
{
$updatedFreeArticle = $freeArticleRepo->update($id, $data);
return json_encode($updatedFreeArticle);
}
public function delete(int $id, FreeArticleRepositoryContract $freeArticleRepo): string
{
$deletedFreeArticle = $freeArticleRepo->delete($id);
return json_encode($deletedFreeArticle);
}
}
?><file_sep>/src/Contracts/FreeArticleRepositoryContract.php
<?php
namespace FreeArticles\Contracts;
use FreeArticles\Models\FreeArticle;
interface FreeArticleRepositoryContract
{
public function createFreeArticle(array $data): FreeArticle;
public function getFreeArticleList(): array;
public function updateFreeArticle($id, array $data): FreeArticle;
public function deleteFreeArticle($id): FreeArticle;
}
?><file_sep>/src/Migrations/CreateFreeArticleTable.php
<?php
namespace FreeArticles\Migrations;
use FreeArticles\Helpers\Plenty\Logger;
use FreeArticles\Models\FreeArticle;
use Plenty\Modules\Plugin\DataBase\Contracts\Migrate;
class CreateFreeArticleTable
{
public function run(Migrate $migrate)
{
Logger::info("CreateFreeArticleTable", "Migration executed", "Migration executed");
$result = $migrate->createTable(FreeArticle::class);
Logger::info('CreateFreeArticleTable_finished', 'Migration finished', $result);
}
}<file_sep>/src/Models/FreeArticle.php
<?php
namespace FreeArticles\Models;
use Plenty\Modules\Plugin\Database\Contracts\Model;
use FreeArticles\Repositories\FreeArticleRepository;
/**
* Class FreeArticle
*
* @property int $id
* @property string $type
* @property string $condition
*/
class FreeArticle extends Model
{
public $id = 0;
public $variationId = 0;
public $type = "";
public $condition = "";
public function getTableName(): string
{
return 'FreeArticles::FreeArticle';
}
public static function createInitalFreeArticles()
{
//TODO we should fill the table with test data
FreeArticleRepository::findOrCreate([
"variationId" => 123,
"type" => "category",
"condition" => "Toner & Druckerpatronen"
]);
FreeArticleRepository::findOrCreate([
"variationId" => 123,
"type" => "category",
"condition" => "Erotik"
]);
}
}
?><file_sep>/src/Validators/FreeArticleValidator.php
<?php
namespace FreeArticles\Validators;
use Plenty\Validation\Validator;
class FreeArticleValidator extends Validator
{
protected function defineAttributes()
{
$this->addString('type', true);
$this->addString('condition', true);
}
public function buildCustomMessages()
{
// TODO: Implement buildCustomMessages() method.
}
}<file_sep>/src/Repositories/FreeArticleRepository.php
<?php
namespace FreeArticles\Repositories;
use Plenty\Exceptions\ValidationException;
use Plenty\Modules\Plugin\DataBase\Contracts\DataBase;
use FreeArticles\Contracts\FreeArticleRepositoryContract;
use FreeArticles\Models\FreeArticle;
use FreeArticles\Validators\FreeArticleValidator;
class FreeArticleRepository implements FreeArticleRepositoryContract
{
public static function create(array $data): FreeArticle
{
try {
FreeArticleValidator::validateOrFail($data);
} catch (ValidationException $e) {
throw $e;
}
$database = pluginApp(DataBase::class);
$freeArticle = pluginApp(FreeArticle::class);
$freeArticle->type = $data['type'];
$freeArticle->condition = $data['condition'];
$database->save($freeArticle);
return $freeArticle;
}
public static function all(): array
{
$database = pluginApp(Database::class);
$freeArticleList = $database->query(FreeArticle::class)->get();
return $freeArticleList;
}
public static function update($id, array $data): FreeArticle
{
$database = pluginApp(DataBase::class);
$freeArticleList = $database->query(FreeArticle::class)
->where('id', '=', $id)
->get();
$freeArticle = $freeArticleList[0];
$type = $data[0];
$condition = $data[1];
if ($type) {
$freeArticle->type = $type;
}
if ($condition) {
$freeArticle->condition = $condition;
}
$database->save($freeArticle);
return $freeArticle;
}
public static function delete($id): FreeArticle
{
$database = pluginApp(DataBase::class);
$freeArticleList = $database->query(FreeArticle::class)
->where('id', '=', $id)
->get();
$freeArticle = $freeArticleList[0];
$database->delete($freeArticle);
return $freeArticle;
}
public static function findOrCreate(array $fields)
{
$freeArticle = FreeArticleRepository::findById($fields["id"]);
if ($freeArticle) {
return $freeArticle;
}
return FreeArticleRepository::create($fields);
}
}
?><file_sep>/resources/lang/de/FreeArticles.properties
description = "Plugin für das Verwalten und Anzeigen von Gratisartikel"<file_sep>/src/Helpers/Plenty/Logger.php
<?php
namespace FreeArticles\Helpers\Plenty;
use Plenty\Plugin\Log\Loggable;
class Logger
{
use Loggable;
public function __construct()
{
}
public static function info($identifikator, $message, $value)
{
return pluginApp(Logger::class)->getLogger($identifikator)->info($message, $value);
}
}
?><file_sep>/resources/lang/en/Config.properties
FreeArticleTag=Id for free article tag
FreeArticleTagHeading=Free articles
freeArticleTagId=Id for free article tag
|
b0b91127266e18bdff6149e5b6f500f33691c011
|
[
"PHP",
"INI"
] | 13 |
PHP
|
hermex-trade/FreeArticles
|
5676d21e455452180ef95f07534097da1fc5d109
|
0c2209b2b33a2d1a8fbd56562964238f43d148bf
|
refs/heads/main
|
<repo_name>cthoyt/more_click<file_sep>/README.md
# more_click
<a href="https://pypi.org/project/more_click">
<img alt="PyPI" src="https://img.shields.io/pypi/v/more_click" />
</a>
<a href="https://pypi.org/project/more_click">
<img alt="PyPI - Python Version" src="https://img.shields.io/pypi/pyversions/more_click" />
</a>
<a href="https://github.com/cthoyt/more_click/blob/main/LICENSE">
<img alt="PyPI - License" src="https://img.shields.io/pypi/l/more_click" />
</a>
<a href="https://zenodo.org/badge/latestdoi/319609575">
<img src="https://zenodo.org/badge/319609575.svg" alt="DOI">
</a>
Extra stuff for click I use in basically every repo
## More Options
The module `more_click.options` has several options (pre-defined instances of `click.option()`) that I use often. First,
`verbose_option` makes it easy to adjust the logger of your package using `-v`.
There are also several that are useful for web stuff, including
| Name | Type | Flag |
| ------------------------ | ---- | -------- |
| `more_click.host_option` | str | `--host` |
| `more_click.port_option` | str | `--port` |
## Web Tools
In many packages, I've included a Flask web application in `wsgi.py`. I usually use the following form inside `cli.py`
file to import the web application and keep it insulated from other package-related usages:
```python
# cli.py
import click
from more_click import host_option, port_option
@click.command()
@host_option
@port_option
def web(host: str, port: str):
from .wsgi import app # modify to point to your module-level flask.Flask instance
app.run(host=host, port=port)
if __name__ == '__main__':
web()
```
However, sometimes I want to make it possible to run via `gunicorn` from the CLI, so I would use the following
extensions to automatically determine if it should be run with Flask's development server or gunicorn.
```python
# cli.py
import click
from more_click import host_option, port_option, with_gunicorn_option, workers_option, run_app
@click.command()
@host_option
@port_option
@with_gunicorn_option
@workers_option
def web(host: str, port: str, with_gunicorn: bool, workers: int):
from .wsgi import app # modify to point to your module-level flask.Flask instance
run_app(app=app, with_gunicorn=with_gunicorn, host=host, port=port, workers=workers)
if __name__ == '__main__':
web()
```
For ultimate lazy mode, I've written a wrapper around the second:
```python
# cli.py
from more_click import make_web_command
web = make_web_command('my_package_name.wsgi:app')
if __name__ == '__main__':
web()
```
This uses a standard `wsgi`-style string to locate the app, since you don't want to be eagerly importing the app in your
CLI since it might rely on optional dependencies like Flask. If your CLI has other stuff, you can include the web
command in a group like:
```python
# cli.py
import click
from more_click import make_web_command
@click.group()
def main():
"""My awesome CLI."""
make_web_command('my_package_name.wsgi:app', group=main)
if __name__ == '__main__':
main()
```
<file_sep>/src/more_click/__init__.py
# -*- coding: utf-8 -*-
"""More click."""
from .options import * # noqa:F401,F403
from .web import * # noqa:F401,F403
<file_sep>/src/more_click/options.py
# -*- coding: utf-8 -*-
"""More click options."""
import logging
import multiprocessing
from typing import Union
import click
__all__ = [
"verbose_option",
"host_option",
"port_option",
"with_gunicorn_option",
"workers_option",
"force_option",
"debug_option",
"log_level_option",
"flask_debug_option",
"gunicorn_timeout_option",
]
LOG_FMT = "%(asctime)s %(levelname)-8s %(message)s"
LOG_DATEFMT = "%Y-%m-%d %H:%M:%S"
def _debug_callback(_ctx, _param, value):
if not value:
logging.basicConfig(level=logging.WARNING, format=LOG_FMT, datefmt=LOG_DATEFMT)
elif value == 1:
logging.basicConfig(level=logging.INFO, format=LOG_FMT, datefmt=LOG_DATEFMT)
else:
logging.basicConfig(level=logging.DEBUG, format=LOG_FMT, datefmt=LOG_DATEFMT)
verbose_option = click.option(
"-v",
"--verbose",
count=True,
callback=_debug_callback,
expose_value=False,
help="Enable verbose mode. More -v's means more verbose.",
)
def _number_of_workers() -> int:
"""Calculate the default number of workers."""
return (multiprocessing.cpu_count() * 2) + 1
host_option = click.option("--host", type=str, default="0.0.0.0", help="Flask host.", show_default=True)
port_option = click.option("--port", type=int, default=5000, help="Flask port.", show_default=True)
with_gunicorn_option = click.option("--with-gunicorn", is_flag=True, help="Use gunicorn instead of flask dev server")
workers_option = click.option(
"--workers",
type=int,
default=_number_of_workers(),
show_default=True,
help="Number of workers (when using --with-gunicorn)",
)
force_option = click.option("-f", "--force", is_flag=True)
debug_option = click.option("--debug", is_flag=True)
flask_debug_option = click.option(
"--debug",
is_flag=True,
help="Run flask dev server in debug mode (when not using --with-gunicorn)",
)
gunicorn_timeout_option = click.option("--timeout", type=int, help="The timeout used for gunicorn")
# sorted level names, by log-level
_level_names = sorted(logging._nameToLevel, key=logging._nameToLevel.get) # type: ignore
def log_level_option(default: Union[str, int] = logging.INFO):
"""Create a click option to select a log-level by name."""
# normalize default to be a string
if isinstance(default, int):
default = logging.getLevelName(level=default)
return click.option(
"-ll",
"--log-level",
type=click.Choice(choices=_level_names, case_sensitive=False),
default=default,
)
<file_sep>/tests/__init__.py
"""Tests for more_click."""
<file_sep>/tests/test_trivial.py
"""Trivial tests."""
import inspect
import unittest
from more_click import debug_option
class TestTrivial(unittest.TestCase):
"""A trivial test case."""
def test_option(self):
"""Test types."""
self.assertTrue(inspect.isfunction(debug_option))
<file_sep>/src/more_click/web.py
# -*- coding: utf-8 -*-
"""Utilities for web applications."""
import importlib
import sys
from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional, Union
import click
from .options import flask_debug_option, gunicorn_timeout_option, verbose_option, with_gunicorn_option, workers_option
if TYPE_CHECKING:
import flask # noqa
import gunicorn.app.base # noqa
__all__ = [
"make_web_command",
"run_app",
"make_gunicorn_app",
]
def make_web_command(
app: Union[str, "flask.Flask", Callable[[], "flask.Flask"]],
*,
group: Optional[click.Group] = None,
command_kwargs: Optional[Mapping[str, Any]] = None,
default_port: Union[None, str, int] = None,
default_host: Optional[str] = None,
) -> click.Command:
"""Make a command for running a web application."""
if group is None:
group = click
if isinstance(default_port, str):
default_port = int(default_port)
@group.command(**(command_kwargs or {}))
@click.option("--host", type=str, default=default_host or "0.0.0.0", help="Flask host.", show_default=True)
@click.option("--port", type=int, default=default_port or 5000, help="Flask port.", show_default=True)
@with_gunicorn_option
@workers_option
@verbose_option
@gunicorn_timeout_option
@flask_debug_option
def web(
host: str,
port: str,
with_gunicorn: bool,
workers: int,
debug: bool,
timeout: Optional[int],
):
"""Run the web application."""
import flask
nonlocal app
if isinstance(app, str):
if app.count(":") != 1:
raise ValueError(
"there should be exactly one colon in the string pointing to"
" an app like modulename.submodulename:appname_in_module"
)
package_name, class_name = app.split(":", 1)
package = importlib.import_module(package_name)
app = getattr(package, class_name)
if isinstance(app, flask.Flask):
pass
elif callable(app):
app = app()
else:
raise TypeError(
"when using a string path with more_click.make_web_command(),"
" it's required that it points to either an instance of a Flask"
" application or a 0-argument function that returns one."
)
elif isinstance(app, flask.Flask):
pass
elif callable(app):
app = app()
else:
raise TypeError(
"when using more_click.make_web_command(), the app argument should either"
" be an instance of a Flask app, a 0-argument function that returns a Flask app,"
" a string pointing to a Flask app in a python module, or a string pointing to a"
" 0-argument function that returns a Flask app"
)
if debug and with_gunicorn:
click.secho("can not use --debug and --with-gunicorn together")
return sys.exit(1)
run_app(
app=app,
host=host,
port=port,
workers=workers,
with_gunicorn=with_gunicorn,
debug=debug,
timeout=timeout,
)
return web
def run_app(
app: "flask.Flask",
with_gunicorn: bool,
host: Optional[str] = None,
port: Optional[str] = None,
workers: Optional[int] = None,
timeout: Optional[int] = None,
debug: bool = False,
):
"""Run the application."""
if not with_gunicorn:
app.run(host=host, port=port, debug=debug)
elif host is None or port is None or workers is None:
raise ValueError("must specify host, port, and workers.")
elif debug:
raise ValueError("can not use debug=True with with_gunicorn=True")
else:
gunicorn_app = make_gunicorn_app(
app,
host=host,
port=port,
workers=workers,
timeout=timeout,
)
gunicorn_app.run()
def make_gunicorn_app(
app: "flask.Flask",
host: str,
port: str,
workers: int,
timeout: Optional[int] = None,
**kwargs,
) -> "gunicorn.app.base.BaseApplication":
"""Make a GUnicorn App."""
from gunicorn.app.base import BaseApplication
class StandaloneApplication(BaseApplication):
def __init__(self, options=None):
self.options = options or {}
self.application = app
super().__init__()
def init(self, parser, opts, args):
pass
def load_config(self):
for key, value in self.options.items():
if key in self.cfg.settings and value is not None:
self.cfg.set(key.lower(), value)
def load(self):
return self.application
kwargs.update(
{
"bind": f"{host}:{port}",
"workers": workers,
}
)
if timeout is not None:
kwargs["timeout"] = timeout
return StandaloneApplication(kwargs)
|
49665e368aad78f18974dd4a0544c8277b85977e
|
[
"Markdown",
"Python"
] | 6 |
Markdown
|
cthoyt/more_click
|
a7b2ca24c8f922578def2a0e92a94c35a9dde226
|
7377c09b51dec59186e2a60b34b8787de2b8eb25
|
refs/heads/main
|
<repo_name>Shubham1201/shop_selling<file_sep>/shopmanage/shophome/migrations/0004_auto_20210308_2236.py
# Generated by Django 3.1.7 on 2021-03-08 17:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shophome', '0003_auto_20210308_2231'),
]
operations = [
migrations.AlterField(
model_name='customers',
name='dates',
field=models.DateField(auto_now=True),
),
]
<file_sep>/shopmanage/shophome/migrations/0015_auto_20210309_1522.py
# Generated by Django 3.1.7 on 2021-03-09 09:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shophome', '0014_auto_20210309_1507'),
]
operations = [
migrations.AlterField(
model_name='customers',
name='selling',
field=models.FloatField(blank=True, default=0, null=True),
),
]
<file_sep>/shopmanage/shophome/migrations/0005_auto_20210308_2254.py
# Generated by Django 3.1.7 on 2021-03-08 17:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shophome', '0004_auto_20210308_2236'),
]
operations = [
migrations.AlterField(
model_name='customers',
name='customername',
field=models.CharField(default='unknown', max_length=200),
),
migrations.AlterField(
model_name='customers',
name='selldetail',
field=models.TextField(blank=True, null=True),
),
]
<file_sep>/shopmanage/shophome/migrations/0009_auto_20210308_2324.py
# Generated by Django 3.1.7 on 2021-03-08 17:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shophome', '0008_auto_20210308_2323'),
]
operations = [
migrations.AlterField(
model_name='customers',
name='shopkipper',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shophome.merchant'),
),
]
<file_sep>/shopmanage/shophome/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class merchant(models.Model):
shopkipper = models.ForeignKey(User, on_delete=models.CASCADE)
shopname = models.CharField(max_length=200)
def __str__(self):
return self.shopkipper.username
class customers(models.Model):
shopkipper = models.ForeignKey(User, on_delete=models.CASCADE)
shopname = models.ForeignKey(merchant, on_delete=models.CASCADE)
customername = models.CharField(max_length=200, default='unknown')
selldetail = models.TextField(null=True, blank=True)
dates = models.DateField(auto_now=True)
selling = models.FloatField(default=0)
def __str__(self):
return self.shopkipper.username + '-' + 'selling data'<file_sep>/shopmanage/shophome/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User, auth
from django.contrib import messages
from .models import *
import datetime
# Create your views here.
def homeapp(request):
return render(request, 'index.html')
def signUp(request):
if request.method == 'POST':
email = request.POST.get('email')
username = request.POST.get('username')
password = request.POST.get('password')
if User.objects.filter(username=username).exists():
messages.info(request, 'Username taken')
elif User.objects.filter(email=email).exists():
messages.info(request, 'Email taken')
else:
user = User.objects.create_user(username=username, password=<PASSWORD>, email=email)
user.save()
else:
return render(request, 'signup.html')
return redirect('login')
def logIn(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = auth.authenticate(username=username, password=<PASSWORD>)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request, "Invalid credentials")
return redirect('login')
else:
return render(request, 'login.html')
def logOut(request):
auth.logout(request)
return redirect('/')
def addShop(request):
if request.method == 'POST':
shopname = request.POST.get('shopname')
godata = merchant.objects.create(shopkipper=User.objects.get(id=request.user.id), shopname=shopname)
godata.save()
return redirect('/')
else:
return render(request, 'addshop.html')
def addEntry(request):
if request.method == "POST":
customer = request.POST.get('customer')
sellingdetail = request.POST.get('sellingdetail')
amount = request.POST.get('amount')
shopnamevar = request.POST.get('shopn')
logged_user = User.objects.get(username=request.user.username)
amount = float(amount)
godata = customers.objects.create(shopkipper=logged_user, shopname=merchant.objects.get(shopname=shopnamevar), customername=customer, selldetail=sellingdetail, dates=datetime.date.today(), selling=amount)
godata.save()
return redirect('/')
else:
logged_user = User.objects.get(username=request.user.username)
mer_user = merchant.objects.filter(shopkipper=logged_user).all()
return render(request, 'addentry.html', {'merchant': mer_user})
def History(request):
logged_user = User.objects.get(username=request.user.username)
mer_user = merchant.objects.filter(shopkipper=logged_user).all()
dataset = customers.objects.filter(shopkipper=logged_user).all()
return render(request, 'history.html', {'dataset': dataset, 'merchant': mer_user})<file_sep>/shopmanage/shophome/migrations/0013_customers.py
# Generated by Django 3.1.7 on 2021-03-08 18:07
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('shophome', '0012_delete_customers'),
]
operations = [
migrations.CreateModel(
name='customers',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('customername', models.CharField(default='unknown', max_length=200)),
('selldetail', models.TextField(blank=True, null=True)),
('dates', models.DateField(auto_now=True)),
('selling', models.FloatField()),
('shopkipper', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('shopname', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shophome.merchant')),
],
),
]
<file_sep>/shopmanage/shophome/urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('', homeapp, name='homepage'),
path('signup/', signUp, name='signup'),
path('login/', logIn, name='login'),
path('logout/', logOut, name='logout'),
path('addshop/', addShop, name='addshop'),
path('addentry/', addEntry, name='addentry'),
path('history/', History, name='history'),
]<file_sep>/shopmanage/shophome/migrations/0007_auto_20210308_2319.py
# Generated by Django 3.1.7 on 2021-03-08 17:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shophome', '0006_auto_20210308_2307'),
]
operations = [
migrations.AlterField(
model_name='customers',
name='shopkipper',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shophome.merchant'),
),
]
<file_sep>/shopmanage/shophome/migrations/0014_auto_20210309_1507.py
# Generated by Django 3.1.7 on 2021-03-09 09:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shophome', '0013_customers'),
]
operations = [
migrations.AlterField(
model_name='customers',
name='selling',
field=models.FloatField(default=0),
),
]
<file_sep>/shopmanage/shophome/migrations/0002_auto_20210308_1428.py
# Generated by Django 3.1.7 on 2021-03-08 08:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shophome', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='merchant',
name='customername',
),
migrations.RemoveField(
model_name='merchant',
name='dates',
),
migrations.RemoveField(
model_name='merchant',
name='selling',
),
migrations.CreateModel(
name='customers',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('customername', models.CharField(max_length=200)),
('selldetail', models.TextField()),
('dates', models.DateField()),
('selling', models.FloatField()),
('shopkipper', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shophome.merchant')),
],
),
]
|
b12b2ee7ef6c639527be62c55f21c70622cb0db3
|
[
"Python"
] | 11 |
Python
|
Shubham1201/shop_selling
|
4e49653dec4b290be32cbf49856dd18645ac4595
|
73265da6304aa75672374358399ec953c3df7172
|
refs/heads/master
|
<repo_name>adfuhr/homework7<file_sep>/src/edu/uwm/cs552/GoalCard.java
package edu.uwm.cs552;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class GoalCard extends Observable {
public static final int NUM_GOALS = 3;
private final Goal[] goals;
private int selected = -1;
private GoalCard(Goal[] gs) {
goals = gs;
}
public Goal getGoal(int i) {
return goals[i];
}
public int getSelected() { return selected; }
/**
* @param index
*/
public void setSelected(final int index) {
if (index != selected) setChanged();
selected = index;
notifyObservers();
}
public static GoalCard generate(HexBoard board) {
Goal[] goals = new Goal[NUM_GOALS];
for (int i=0; i < NUM_GOALS; ++i) {
goals[i] = Goal.generate(board);
}
return new GoalCard(goals);
}
public class Panel extends JPanel {
/**
* Keep Eclipse Happy
*/
private static final long serialVersionUID = 1L;
public Panel() {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final int index = ((RadioButton)arg0.getSource()).getIndex();
setSelected(index);
}
};
ButtonGroup g = new ButtonGroup();
setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
for (int i=0; i < NUM_GOALS; ++i) {
RadioButton b = new RadioButton(i);
b.addActionListener(listener);
g.add(b);
JPanel goalPanel = new JPanel();
goalPanel.add(b);
goalPanel.add(getGoal(i).asLabel());
goalPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
add(goalPanel);
}
setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
public GoalCard getGoalCard() {
return GoalCard.this;
}
}
private class RadioButton extends JRadioButton {
/**
* Keep Eclipse happy
*/
private static final long serialVersionUID = 1L;
private final int index;
public RadioButton(int i) {
super();
index = i;
}
public int getIndex() {
return index;
}
}
}
<file_sep>/src/edu/uwm/cs552/net/RailGameServer.java
package edu.uwm.cs552.net;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import edu.uwm.cs552.HexBoard;
import edu.uwm.cs552.Player;
import edu.uwm.cs552.RailGame;
import edu.uwm.cs552.util.Broadcast;
public class RailGameServer extends RailGame {
public static final int SERVER_PORT = 50552;
final int numPlayers;
final String boardURL;
final Broadcast<Object> actions;
private final Handler[] handlers;
public RailGameServer(HexBoard b, int players, String burl) {
super(b, players);
numPlayers = players;
boardURL = burl;
handlers = new Handler[players];
actions = new Broadcast<Object>();
}
@Override
public void autoMove() {
// do nothing (no auto moves on server);
}
public void listen() {
try {
ServerSocket ss = new ServerSocket(SERVER_PORT);
for (;;) {
final Socket s = ss.accept();
new Thread(new Runnable() {
public void run() {
handlerBorn(s);
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void handlerBorn(Socket s) {
try {
Handler handler = null;
synchronized (this) {
for (int i = 0; i < handlers.length; i++) {
if (handlers[i] == null) {
handler = new Handler(this, s, i);
handlers[i] = handler;
break;
}
}
}
if (handler == null) {
handler = new Handler(this, s, -1);
}
} catch (IOException e) {
// muffle
}
}
public void handlerDied(int handler) {
if (handler == -1)
return;
synchronized (this) {
if (handlers[handler] != null)
handlers[handler] = null;
}
}
/**
* @param args
*/
public static void main(String[] args) {
final HexBoard board = new HexBoard();
try {
board.read(new BufferedReader(new FileReader(args[0])));
final int numPlayers = Integer.parseInt(args[1]);
System.out.println("Creating a game for " + numPlayers + " players");
final RailGameServer game = new RailGameServer(board, numPlayers, args[0]);
game.initPlayers();
game.listen();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public void addAction(int playerID, Action a) {
a = validateAction(playerID, a);
actions.add(playerID);
actions.add(a);
}
private void initPlayers() {
checkTime();
}
private Action validateAction(int pid, Action a) {
Player player = getPlayer(pid);
List<ActionResponse> errors = new ArrayList<ActionResponse>();
if (player == null)
return a;
else if (a instanceof TurnAction) {
TurnAction t = (TurnAction) a;
player.getTrainStatus().addPlanned(t.getNext());
player.getTrackStatus().propose(t.getBuild());
player.setWant(t.getLoad());
TurnAction validTurn = (TurnAction) player.move();
validTurn.setSale(t.getSale());
if ((validTurn.getBuild() == null && t.getBuild() != null)
|| (validTurn.getBuild() != null && !validTurn.getBuild().equals(t.getBuild())))
errors.add(ActionResponse.BUILD_TOO_LATE);
if ((validTurn.getNext() == null && t.getNext() != null)
|| (validTurn.getNext() != null && !validTurn.getNext().equals(t.getNext())))
errors.add(ActionResponse.MOVE_BLOCKED);
if (validTurn.isEmpty()) {
errors.add(ActionResponse.REJECT);
a = null;
}
else
a = t;
if (!errors.isEmpty())
notifyErrors(pid, errors);
}
getPlayer(pid).doTurn(a);
return a;
}
private void notifyErrors(int playerID, List<ActionResponse> errors) {
synchronized (this) {
for (int i=0; i<handlers.length; i++) {
if (handlers[i] != null && handlers[i].playerID == playerID) {
for (ActionResponse error : errors) {
handlers[i].update(actions, error);
}
break;
}
}
}
}
}<file_sep>/src/edu/uwm/cs552/TerrainDraw.java
package edu.uwm.cs552;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
/**
* A class for editing the board to set
* the location given as a particular terrain.
*/
class TerrainDraw implements HexBoardEditAction {
private final Terrain terrain;
private static ImageIcon[] icons;
private static CityDialog cityDialog = null;
private static City askCity(City c) {
if (cityDialog == null) {
cityDialog = new CityDialog(null);
}
cityDialog.open(c);
return cityDialog.getCity();
}
public TerrainDraw(Terrain t) {
terrain = t;
}
public Terrain getTerrain() {
return terrain;
}
public void apply(HexBoard hexBoard, Point p, double scale) {
HexCoordinate h = HexCoordinate.fromPoint(p, scale);
if (terrain == null) hexBoard.removeTerrain(h);
else if (terrain.isCity()) {
City c = askCity(hexBoard.getCity(h));
if (c == null) return; // cancelled apply.
hexBoard.putTerrain(h,terrain,c);
}
else hexBoard.putTerrain(h,terrain);
}
public String getLabel() {
return terrain == null ? "[Erase terrain]" : terrain.toString();
}
public ImageIcon getIcon() {
final ImageIcon icon;
ImageIcon[] icons = getTerrainIcons();
if (terrain != null) {
icon = icons[terrain.ordinal()];
} else {
icon = icons[Terrain.values().length];
}
return icon;
}
/**
* Return the (singleton) array of icons for terrains indexed by terrain ordinal.
* With one extra item at the end for blank icon.
* @return
*/
static ImageIcon[] getTerrainIcons() {
if (TerrainDraw.icons == null) {
ImageIcon[] result = new ImageIcon[Terrain.values().length+1];
for (int i=0; i < result.length; ++i) {
BufferedImage im = new BufferedImage(TerrainDraw.ICON_SIZE,TerrainDraw.ICON_SIZE, BufferedImage.TYPE_INT_ARGB);
Graphics g = im.getGraphics();
g.translate(TerrainDraw.ICON_SIZE/2, TerrainDraw.ICON_SIZE/2);
if (i < Terrain.values().length) {
Terrain.values()[i].draw(g, HexCoordinate.ORIGIN, TerrainDraw.ICON_SIZE, true);
}
result[i] = new ImageIcon(im);
}
TerrainDraw.icons = result;
}
return TerrainDraw.icons;
}
}<file_sep>/src/edu/uwm/cs552/HexEdge.java
package edu.uwm.cs552;
import java.awt.Graphics;
import java.awt.Point;
import java.io.Serializable;
import java.util.NoSuchElementException;
import edu.uwm.cs552.util.FormatException;
import edu.uwm.cs552.util.Pair;
/**
* The edge of a hexagon on a hexagonal game board.
* Note that each edge is the edge of two different hexagons (in opposite directions).
*/
public class HexEdge implements Serializable {
private static final long serialVersionUID = 1L;
private final HexCoordinate base;
private final HexDirection direction;
/**
* Create an edge for a hexagonal grid hexagon.
* This edge will be equal to one created using the other hexagon
* with the opposite direction.
* @param base the hexagon the edge is for
* @param direction2 one of the six directions.
*/
public HexEdge(HexCoordinate base2, HexDirection direction2) {
base = base2;
direction = direction2;
}
/**
* Create an edge from the first hexagon toward the other.
* If the other is not adjacent, try to move in the correct direction.
* If the direction is not clear, choose something arbitrarily.
* @param h1
* @param h2
*/
public HexEdge(HexCoordinate h1, HexCoordinate h2) {
base = h1;
direction = HexDirection.fromDelta(h2.a()-h1.a(), h2.b()-h1.b());
}
public double a() { return base.a() + 0.5 * direction.da(); }
public double b() { return base.b() + 0.5 * direction.db(); }
private HexCoordinate getDual() {
return base.move(direction);
}
@Override
public String toString() {
return base + "@" + direction;
}
public static HexEdge fromString(String s) throws FormatException {
int at = s.indexOf('@');
if (at <= 0) throw new FormatException("HexEdge requires @ separator: " + s);
try {
return new HexEdge(HexCoordinate.fromString(s.substring(0,at)),
HexDirection.valueOf(s.substring(at+1)));
} catch (NoSuchElementException e) {
throw new FormatException(e);
}
}
@Override
public boolean equals(Object x) {
if (!(x instanceof HexEdge)) return false;
HexEdge o = (HexEdge)x;
if (o.base.equals(base) && o.direction == direction) return true;
if (o.base.equals(getDual()) && o.direction == direction.reverse()) return true;
return false;
}
@Override
public int hashCode() {
return (int)(a()*2) *197 + (int)(b()*2);
}
public Pair<Point,Point> toLineSegment(double scale) {
HexDirection next = direction.nextClockwise();
HexDirection prev = direction.nextCounterClockwise();
double a1 = base.a() + (prev.da() + direction.da())/3.0;
double b1 = base.b() + (prev.db() + direction.db())/3.0;
double a2 = base.a() + (next.da() + direction.da())/3.0;
double b2 = base.b() + (next.db() + direction.db())/3.0;
final Point p1 = HexCoordinate.toPoint(a1, b1, scale);
final Point p2 = HexCoordinate.toPoint(a2,b2,scale);
return new Pair<Point,Point>(p1,p2);
}
public Pair<HexCoordinate,HexCoordinate> getHexagons() {
return new Pair<HexCoordinate,HexCoordinate>(base,getDual());
}
public void draw(Graphics g, double scale) {
Pair<Point,Point> pp = toLineSegment(scale);
g.drawLine(pp.fst.x, pp.fst.y, pp.snd.x, pp.snd.y);
}
private static final double SQRT32 = Math.sqrt(3)/2;
/**
* Return the edge closest to this point, or null if the edge
* is too far away. Distance is measured using the hex metric,
* not Euclidean distance between points on the screen.
* @param p (x,y) point on screen
* @param scale width of hexagons
* @param bound portion of maximum distance (1.0) to permit.
* @return hex edge closest to point if within bound, else null
*/
public static HexEdge fromPoint(Point p, double scale, double bound) {
HexCoordinate base = HexCoordinate.fromPoint(p,scale);
double b = p.y / scale / SQRT32;
double a = p.x / scale + b / 2;
double da = a - base.a();
double db = b - base.b();
HexDirection direction = HexDirection.fromDelta(da,db);
HexEdge e = new HexEdge(base,direction);
da = a - e.a();
db = b - e.b();
if (Math.abs(da) + Math.abs(db) + Math.abs(da-db) > bound) return null;
return e;
}
public static HexEdge fromPoint(Point p, double scale) {
return fromPoint(p,scale,1.0);
}
}
<file_sep>/src/edu/uwm/cs552/ScaleComboBox.java
package edu.uwm.cs552;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
public class ScaleComboBox extends JComboBox {
/**
* Keep Eclipse happy
*/
private static final long serialVersionUID = 1L;
private static Integer[] scales = new Integer[] {
10, 15, 20, 30, 40, 50, 60, 75, 100, 120, 150, 200
};
private static Integer defaultScale = 20;
private final HexBoardPanel panel;
public ScaleComboBox(HexBoardPanel p) {
super(scales);
panel = p;
this.setMaximumSize(this.getPreferredSize());
this.setEditable(true);
this.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
scaleChangeRequested();
}
});
this.setSelectedItem(defaultScale);
}
public void scaleChangeRequested() {
double newScale = defaultScale;
Object x = super.getSelectedItem();
if (x instanceof String) {
try {
newScale = Float.parseFloat((String)x);
} catch (NumberFormatException e) {
super.setSelectedItem(newScale = defaultScale);
}
} else if (x instanceof Number) {
newScale = ((Number)x).doubleValue();
}
if (newScale < HexBoardPanel.MIN_SCALE) {
JOptionPane.showMessageDialog(this, "Scale must be at least " + HexBoardPanel.MIN_SCALE, "Scale error", JOptionPane.ERROR_MESSAGE);
super.setSelectedItem(newScale = defaultScale);
}
panel.setScale(newScale);
}
}
<file_sep>/src/edu/uwm/cs552/TrackStatus.java
package edu.uwm.cs552;
import java.awt.Graphics2D;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Observable;
import java.util.Set;
/**
* The rails of a player.
* There are three kinds of rails:
* <ol>
* <li> Completed track.
* <li> Track current under construction.
* <li> Track being considered for construction
* (visible only to the player proposing it).
* </ol>
*/
public class TrackStatus extends Observable {
private Set<HexEdge> built = new HashSet<HexEdge>();
private Map<HexEdge,RailState> underConstruction = new HashMap<HexEdge,RailState>();
private LinkedList<HexEdge> proposed = new LinkedList<HexEdge>();
private HexEdge last = null;
/**
* Draw the track on a graphics context.
* @param g graphics context, cannot be null
* @param scale width of hexagons
* @param showProposed whether to show proposed rails (only for the player
* proposing the track).
*/
public void draw(Graphics2D g, double scale, boolean showProposed) {
for (HexEdge e : built) {
RailState.BUILT.draw(g, e, scale);
}
for (Map.Entry<HexEdge, RailState> e : underConstruction.entrySet()) {
e.getValue().draw(g, e.getKey(), scale);
}
if (showProposed) {
for (HexEdge e : proposed) {
RailState.PROPOSED.draw(g, e, scale);
}
}
}
/**
* Return state of rail on this edge.
* Either built or under construction.
* (This does not take into account proposed rail construction.)
* @param e edge in question, must not be null
* @return rail state or null if no rail at this point.
*/
public RailState getTrack(HexEdge e) {
if (built.contains(e)) return RailState.BUILT;
return underConstruction.get(e);
}
/**
* Move construction forward for track being constructed.
* @param turns amount of turns to go forward with construction
* @return if any progress made
*/
public boolean progress(int turns) {
if (underConstruction.isEmpty()) return false;
Map<HexEdge,RailState> newUnder = new HashMap<HexEdge,RailState>();
for (Map.Entry<HexEdge, RailState> e : underConstruction.entrySet()) {
RailState rs = e.getValue().progress(turns);
setChanged();
if (rs == RailState.BUILT) {
built.add(e.getKey());
last =e.getKey();
} else {
newUnder.put(e.getKey(), rs);
}
}
underConstruction.clear();
underConstruction.putAll(newUnder);
notifyObservers(newUnder);
return true;
}
/**
* Start to construct a piece of track.
* @param e edge on which to construct track.
*/
public void constructTrack(HexEdge e) {
underConstruction.put(e, RailState.startBuildState());
setChanged();
notifyObservers(e);
}
/**
* Return whether this edge is proposed for construction.
* @param e edge track would cross
* @return whether this edge is being proposed for construction.
*/
public boolean hasProposed(HexEdge e) {
return proposed.contains(e);
}
/**
* Remove and return the next piece of track proposed for construction.
* @return proposed track or null if nothing proposed.
*/
public HexEdge nextProposed() {
return proposed.poll();
}
/**
* This player proposed a new section of track.
* @param e edge on which track is proposed to be laid.
*/
public void propose(HexEdge e) {
if (proposed.contains(e)) return;
proposed.add(e);
setChanged();
notifyObservers(e);
}
/**
* Put a proposed edge back on the front of the queue.
* @param e
*/
public void pushProposed(HexEdge e) {
proposed.addFirst(e);
}
/**
* Clear all proposals currently pending.
*/
public void clearProposed() {
proposed.clear();
setChanged();
notifyObservers(this);
}
public void removeProposal(HexEdge e) {
if (proposed.remove(e)) setChanged();
notifyObservers(e);
}
public HexEdge getLastBuilt(){
return last;
}
}
<file_sep>/src/edu/uwm/cs552/util/MouseHoverListenerAdapter.java
package edu.uwm.cs552.util;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
public final class MouseHoverListenerAdapter extends MouseAdapter implements Runnable {
public static void addHoverListener(JComponent c, MouseHoverListener l) {
MouseHoverListenerAdapter a = new MouseHoverListenerAdapter(l);
c.addMouseListener(a);
c.addMouseMotionListener(a);
}
private final MouseHoverListener listener;
private boolean waiting = false;
private boolean hovering = false;
private long lastMoved = 0;
private MouseEvent lastEvent = null;
public MouseHoverListenerAdapter(MouseHoverListener l) {
listener = l;
Clock.getInstance().addListener(this, MouseHoverListener.HOVER_WAIT);
}
@Override
public void mouseEntered(MouseEvent arg0) {
stopHover(arg0);
waiting = true;
lastMoved = System.currentTimeMillis();
lastEvent = arg0;
}
@Override
public void mouseExited(MouseEvent arg0) {
stopHover(arg0);
waiting = false;
lastEvent = null;
}
@Override
public void mouseMoved(MouseEvent arg0) {
stopHover(arg0);
waiting = true;
lastMoved = System.currentTimeMillis();
lastEvent = arg0;
}
private void stopHover(MouseEvent arg) {
if (hovering) {
listener.mouseHoverStop(arg);
hovering = false;
}
}
public void run() {
if (waiting && (System.currentTimeMillis() - lastMoved) > MouseHoverListener.HOVER_WAIT) {
listener.mouseHoverStart(lastEvent);
hovering = true;
waiting = false;
lastEvent = null;
}
}
}
<file_sep>/src/edu/uwm/cs552/City.java
package edu.uwm.cs552;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* A class to store information about cities.
* This class is immutable and instances are not registered.
*/
public class City implements Iterable<Good> {
private final String name;
private final List<Good> goods = new ArrayList<Good>();
/**
* Create city information for a named city.
* The name cannot include a comma (to allow comma separation).
* @param n name of city, must not be null or include a comma
*/
public City(String n) {
if (n == null || n.indexOf(',') >= 0) {
throw new IllegalArgumentException("name of city cannot include a comma");
}
name = n;
}
public String getName() {
return name;
}
public void addGood(Good g) {
goods.add(g);
}
/**
* Return true if this good is one of theones normally
* provided by this city. It does not check whether the good
* is available.
* @param g good to check, must not be null
* @return true if this city provides this good.
*/
public boolean hasGood(Good g) {
if (g == null) throw new IllegalArgumentException("good may not be null");
for (Good has : goods) {
if (has == g) return true;
}
return false;
}
@Override
public String toString() {
return name;
}
public Iterator<Good> iterator() {
return goods.iterator();
}
private Font lastFont = null;
private double lastScale = 0.0;
public void draw(Graphics g, HexCoordinate h, double scale) {
if (scale != lastScale) {
lastFont = new Font("Sans",Font.PLAIN,(int)(scale/2));
lastScale = scale;
}
g.setFont(lastFont);
g.setColor(Color.BLACK);
Point p = h.toPoint(scale);
g.drawString(name, p.x, p.y+(int)(scale/4));
}
}
<file_sep>/src/edu/uwm/cs552/TrainStatusPanel.java
package edu.uwm.cs552;
import java.awt.Color;
import java.awt.Component;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TrainStatusPanel extends JPanel implements Observer {
/**
* Keep Eclipse Happy
*/
private static final long serialVersionUID = 1L;
private final TrainStatus train;
private final Component[] goodPanels;
private static Component asComponent(Good g) {
if (g == null) return Box.createHorizontalGlue();
return g.asLabel(false);
}
public TrainStatusPanel(TrainStatus c) {
train = c;
add(Box.createHorizontalGlue());
add(new JLabel("Load:"));
goodPanels = new Component[c.size()];
setLayout(new BoxLayout(this,BoxLayout.LINE_AXIS));
for (int i=0; i < c.size(); ++i) {
goodPanels[i] = asComponent(c.getGood(i));
add(Box.createHorizontalGlue());
add(goodPanels[i]);
}
add(Box.createHorizontalGlue());
c.addObserver(this);
setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
public void update(Observable obs, Object obj) {
if (obs == train && obj instanceof Integer) {
int i = ((Integer)obj).intValue();
if (i < 0 || i >= train.size()) return;
remove(goodPanels[i]);
goodPanels[i] = asComponent(train.getGood(i));
add(goodPanels[i]);
this.validate();
}
}
}
<file_sep>/src/Main.java
import edu.uwm.cs552.net.RailGameClient;
import edu.uwm.cs552.net.RailGameServer;
public class Main {
public static void main(String[] args) {
if (args.length == 1)
RailGameClient.main(args);
else if (args.length == 2)
RailGameServer.main(args);
}
}<file_sep>/src/edu/uwm/cs552/util/Pair.java
package edu.uwm.cs552.util;
/**
* Mutable pair structure.
* @param <T1>
* @param <T2>
*/
public class Pair<T1, T2> {
public T1 fst;
public T2 snd;
public Pair(T1 x1, T2 x2) {
fst = x1;
snd = x2;
}
}
<file_sep>/src/edu/uwm/cs552/PlayerStatusPanel.java
package edu.uwm.cs552;
import java.text.DecimalFormat;
import java.util.Observable;
import java.util.Observer;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PlayerStatusPanel extends JPanel implements Observer {
/**
* Keep Eclipse happy
*/
private static final long serialVersionUID = 1L;
private final Player player;
private static DecimalFormat moneyFormat = new DecimalFormat("#.00");
private static String formatMoney(double m) {
return "Money: " + moneyFormat.format(m);
}
private static String formatTime(int t) {
return "Time: " + t;
}
private JLabel money = new JLabel(formatMoney(0));
private JLabel time = new JLabel(formatTime(0));
public PlayerStatusPanel(Player p) {
super();
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
player = p;
money.setText(formatMoney(p.getMoney()));
time.setText(formatTime(p.getTime()));
final CardStatusPanel cardsPanel = new CardStatusPanel(p.getCardStatus());
final JPanel statusPanel = new JPanel();
final JPanel trainPanel = new TrainStatusPanel(p.getTrainStatus());
statusPanel.add(money);
statusPanel.add(Box.createHorizontalGlue());
statusPanel.add(time);
add(statusPanel);
add(trainPanel);
add(Box.createVerticalGlue());
add(cardsPanel);
p.addObserver(this);
}
public void update(Observable o, Object arg) {
if (o == player) {
if (arg instanceof Double) money.setText(formatMoney(player.getMoney()));
time.setText(formatTime(player.getTime()));
}
}
}
<file_sep>/src/edu/uwm/cs552/ConstructionCost.java
package edu.uwm.cs552;
public interface ConstructionCost {
/**
* Compute the cost of building track between hexagons with
* the given terrain and given barrier.
* @param t1 terrain on one end of track
* @param b barrier (if any) between the hexagons, may be null
* @param t2 terrain on other end of track.
* @return cost associated with building track, or {@link Double#POSITIVE_INFINITY}
* if track cannot be built.
*/
public double cost(Terrain t1, Barrier b, Terrain t2);
}
<file_sep>/src/edu/uwm/cs552/RailState.java
package edu.uwm.cs552;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;
import edu.uwm.cs552.util.Pair;
/**
* The state of track laid down by a player in the game.
* Track starts in state {@link #startBuildState()} and then
* progresses turn by turn until it is {@link #BUILT}.
* A player may plan construction through the use of {@link #PROPOSED}.
*/
public enum RailState {
BUILT(null),
BUILD1(new float[]{9.5f,1,9.5f}),
BUILD2(new float[]{4.5f,1,9,1,4.5f}),
BUILD3(new float[]{3,1,5.5f,1,5.5f,1,3}),
BUILD4(new float[]{2,1,4,1,4,1,4,1,2}),
BUILD5(new float[]{1.5f,1,3,1,3,1,3,1,3,1,1.5f}),
BUILD6(new float[]{1.5f,1,2,1,2,1,3,1,2,1,2,1,1.5f}),
BUILD7(new float[]{0, 1,2,1,2,1,2,1,2,1,2,1,2,1,1}),
BUILD8(new float[]{1, 1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,1}),
BUILD9(new float[]{1, 1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1}),
BUILD10(new float[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}),
PROPOSED(new float[]{1,3,1,2,1,2,1,3,1,2,1,2});
public void draw(Graphics2D g, HexEdge e, double scale) {
Stroke savedStroke = g.getStroke();
g.setStroke(getStroke(scale));
Pair<HexCoordinate,HexCoordinate> hs = e.getHexagons();
Point p1 = hs.fst.toPoint(scale);
Point p2 = hs.snd.toPoint(scale);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
g.setStroke(savedStroke);
}
private final float[] dashPatternModel;
private static final float MODEL_SIZE = 20;
private RailState(float[] model) {
if (model != null) {
float sum = 0;
for (float f : model) {
sum += f;
}
assert sum == MODEL_SIZE : "dash pattern not correct";
}
dashPatternModel = model;
}
/**
* Return the state of when building just starts.
* @return the stateof a rail just starting to be laid.
*/
public static RailState startBuildState() {
return BUILD10;
}
/**
* Return the state of the track after a certain number of turns.
* Fully built track and proposed track are not affected.
* @param turns turns of the game that have passed.
* @return the state of the track after this many turns.
*/
public RailState progress(int turns) {
if (this == PROPOSED) return this;
if (this.ordinal() <= turns) return BUILT;
return values()[this.ordinal()-turns];
}
private transient float lastScale = 0;
private transient Stroke lastStroke = null;
private Stroke getStroke(double scale) {
if (scale == lastScale) return lastStroke;
lastScale = (float)scale;
float width = lastScale / 10;
if (dashPatternModel == null) {
lastStroke = new BasicStroke(width,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
} else if (lastScale == MODEL_SIZE) {
lastStroke = new BasicStroke(width,BasicStroke.CAP_BUTT,1,BasicStroke.JOIN_BEVEL,dashPatternModel,0);
} else {
float[] dashes = new float[dashPatternModel.length];
for (int i=0; i < dashPatternModel.length; ++i) {
dashes[i] = dashPatternModel[i] * lastScale / MODEL_SIZE;
}
lastStroke = new BasicStroke(width,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL,1,dashes,0);
}
return lastStroke;
}
}
<file_sep>/src/edu/uwm/cs552/GoodComboBox.java
package edu.uwm.cs552;
import javax.swing.JComboBox;
/**
* A combo-box for choosing a Good.
* The selected item is always null or a Good.
*/
public class GoodComboBox extends JComboBox {
/**
* Eclipse wants this.
*/
private static final long serialVersionUID = 1L;
private static Good[] goodsArray;
private static Good[] getGoodsArray() {
if (goodsArray == null) {
Good[] regularGoodArray = Good.allGoods();
goodsArray = new Good[regularGoodArray.length+1];
for (int i = 0; i < regularGoodArray.length; ++i) {
goodsArray[i+1] = regularGoodArray[i];
}
}
return goodsArray;
}
public GoodComboBox() {
super(getGoodsArray());
setRenderer(new GoodRenderer());
}
@Override
public Good getSelectedItem() {
return (Good)super.getSelectedItem();
}
@Override
public void setSelectedItem(Object x) {
super.setSelectedItem((Good)x); // may throw exception
}
}
<file_sep>/src/edu/uwm/cs552/Player.java
package edu.uwm.cs552;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Logger;
import edu.uwm.cs552.net.Action;
import edu.uwm.cs552.net.TurnAction;
import edu.uwm.cs552.net.UnloadAction;
import edu.uwm.cs552.util.Pair;
public class Player extends Observable implements Observer {
private final RailGame game;
private final int index;
private final Logger log = Logger.getAnonymousLogger();
private final Color color;
private final TrackStatus track = new TrackStatus();
private final TrainStatus train = new TrainStatus(RailGame.TRAIN_INITIAL_CAPACITY);
private final CardStatus cards;
private Good want; // the good this player wants to take
private int time;
private double money;
private boolean autoMoveEnabled;
/**
* Create a player at the given index and using the given color. Everyone
* starts with one game tick of time.
*
* @param g game, must not be null
* @param i index of player (1 based)
* @param c color to use for track
* @param startupMoney initial money
*/
public Player(RailGame g, int i, Color c, double startupMoney, GoalCard[] cds) {
game = g;
index = i;
color = c;
time = 1;
cards = new CardStatus(cds);
money = startupMoney;
track.addObserver(this);
train.addObserver(this);
cards.addObserver(this);
}
/**
* Return the index of the player (1-based)
*
* @return number of player
*/
public int getIndex() {
return index;
}
/**
* Get (anonymous) logger which gets errors, warnings and information
* messages.
*
* @return logger used
*/
public Logger getLogger() {
return log;
}
/**
* Draw player specific information on the graphics context. We assume the
* board is already drawn.
*
* @param g graphics context
* @param scale width of hexagons
* @param showConfidential whether to show information private only to player
*/
public void draw(Graphics2D g, double scale, boolean showConfidential) {
g.setColor(color);
track.draw(g, scale, showConfidential);
train.draw(g, scale, showConfidential);
}
/**
* Return how much money this player has.
*
* @return how much money this player has
*/
public double getMoney() {
return money;
}
/**
* Give money to this player, for example from track rental
*
* @param extra money to give, must be non-negative
*/
public void addMoney(double extra) {
if (extra < 0)
throw new IllegalArgumentException("adding negative money");
money += extra;
if (extra > 0)
setChanged();
notifyObservers(new Double(money));
}
/**
* Return whether this player can still move. If they don't have time, return
* false.
*
* @return whether they have units of time
*/
public boolean hasTime() {
return time > 0;
}
/**
* Return
*
* @return
*/
public int getTime() {
return time;
}
/**
* Give the player more time.
*
* @param ticks game turns to add
*/
public void addTime(int ticks) {
time += ticks;
if (ticks > 0)
setChanged();
notifyObservers();
}
/**
* Return state of rail at this location. Return null if no rail being built
* or fully built here. This does not take into account proposed construction.
*
* @param e edge in question, may not be null
* @return
*/
public RailState getTrack(HexEdge e) {
return track.getTrack(e);
}
public void doTurn(Action a) {
if (a instanceof TurnAction) {
TurnAction t = (TurnAction) a;
sellGood();
if (t.getLoad() != null)
train.addGood(t.getLoad());
// Build track
if (t.getBuild() != null)
getTrackStatus().constructTrack(t.getBuild());
getTrackStatus().progress(1);
// Move train
if (t.getNext() != null)
getTrainStatus().move(t.getNext());
progressMade = true;
}
else if (a instanceof UnloadAction) {
UnloadAction u = (UnloadAction) a;
train.removeGood(u.getGood());
}
}
/**
* Return true if the player has a train on this coordinate.
*
* @param h
* @return
*/
public boolean occupies(HexCoordinate h) {
return h.equals(train.getLocation());
}
/**
* Return selected goal card (if any)
*/
public GoalCard getSelectedCard() {
return cards.getSelectedCard();
}
/**
* Discard selected card. This costs {@link RailGame#DISCARD_TIME} in time.
*/
public void discard() {
if (cards.getSelectedCard() == null) {
log.warning("No card selected to discard");
return;
}
cards.replaceSelectedCard(game.genCard());
time -= RailGame.DISCARD_TIME;
log.info("Card discarded and replaced.");
setChanged();
notifyObservers();
}
/**
* Set the good that this player wants to pick up.
*
* @param g
*/
public void setWant(Good g) {
if (want != g)
setChanged();
want = g;
notifyObservers();
}
/**
* Set whenever a move action makes progress. If no progress, then we stop
* automatic movement.
*/
private boolean progressMade = false;
/**
* Return true if progress was made since the last time this method was
* called. This method clears the "progress made" flag.
*
* @return whether progress was made since last call.
*/
public boolean wasProgressMade() {
boolean result = progressMade;
progressMade = false;
return result;
}
/**
* Set whether or not this player want auto move.
*
* @param status
*/
public void setAutoMove(boolean status) {
autoMoveEnabled = status;
}
public Action autoMove() {
if (autoMoveEnabled && wasProgressMade()) {
return move();
}
return null;
}
public Action move() {
if (!hasTime())
return null;
HexCoordinate nextTrainMove = nextTrainMove();
HexEdge nextBuiltTrack = nextBuiltTrack();
Good goodPickedUp = nextGoodPickedUp();
return new TurnAction(256 * cards.getSelectedCardIndex()
+ cards.getSelectedGoalIndex(), goodPickedUp, nextTrainMove, nextBuiltTrack);
}
private HexCoordinate nextTrainMove() {
for (;;) {
HexCoordinate next = train.nextPlanned();
if (next == null)
return null; // no progress
HexCoordinate current = train.getLocation();
if (current == null) {
Terrain t = game.getTerrain(next);
if (t == null)
continue;
switch (t) {
default:
continue;
case SMALL:
case MEDIUM:
case LARGE:
return next;
}
}
else if (current.distance(next) != 1)
continue;
else if (game.occupier(next) != null) {
train.pushPlanned(next);
return null; // no progress
}
else {
HexEdge edge = new HexEdge(current, next);
Player trackOwner = game.occupier(edge);
boolean usableTrack = trackOwner != null
&& trackOwner.getTrack(edge) == RailState.BUILT;
if (usableTrack && trackOwner == this) {
return next;
}
// 2. track owner can rent it to us
else if (usableTrack) {
double cost = game.getTrackRental().cost(game.getTerrain(current), game.getBarrier(edge), game.getTerrain(next));
if (!pay(cost)) {
log.warning("Insufficient fund to rent track, needed " + cost);
continue;
}
trackOwner.addMoney(cost);
return next;
}
// 3. we can travel for free if it's in the suburbs of a large city
else if (inCity(edge))
return next;
// 4. track will be built soon, just wait
else if (trackOwner != null) {
log.info("train waiting for track completion at " + next);
train.pushPlanned(next);
return null;
}
// 5. We are planning to build soon, wait
else if (track.hasProposed(edge)) {
log.info("train waiting for track constrution at " + next);
train.pushPlanned(next);
return null;
}
// 6. toss
else {
log.warning("no track to " + next + " ?");
}
}
}
}
private void sellGood() {
Goal g = cards.getSelectedGoal();
if (g == null)
return;
System.out.println("Goal is " + g + " in "
+ game.getCity(train.getLocation()));
if (!train.getLocation().equals(g.getTarget()))
return;
if (!train.removeGood(g.getGood()))
return;
addMoney(g.getPayoff());
log.info("Sold " + g.getGood() + " for " + g.getPayoff());
cards.replaceSelectedCard(game.genCard());
}
public Good getWant() {
return want;
}
private Good nextGoodPickedUp() {
System.out.println("Looking for " + want + " in "
+ game.getCity(train.getLocation()));
if (want == null)
return null;
City c = game.getCity(train.getLocation());
if (c == null || !c.hasGood(want))
return null;
if (!want.isAvailable())
return null;
if (!train.addGood(want))
return null;
train.removeGood(want); // balance
log.info("Grabbed " + want);
return want;
}
/**
* Build one new piece of track, as proposed. We consider the next proposed
* construction. The cost must be bearable, and there must not already be
* track there, and at least one end point of the edge must already be
* connected to this player's network or be a suburb. If the track is legal
* but the player has insufficient funds, the proposal
*/
private HexEdge nextBuiltTrack() {
// build track
for (;;) {
HexEdge edge = track.nextProposed();
if (edge == null)
return null;
Pair<HexCoordinate, HexCoordinate> p = edge.getHexagons();
final double cost = game.getConstructionCost().cost(game.getTerrain(p.fst), game.getBarrier(edge), game.getTerrain(p.snd));
if (cost == Double.POSITIVE_INFINITY) {
log.warning("proposed track edge absolutely impossible: " + edge);
continue;
}
if (!isConnected(p.fst) && !isConnected(p.snd)) {
log.warning("proposed track doesn't connect with player's network: "
+ edge);
continue;
}
if (game.occupier(edge) != null) {
log.warning("proposed track already built: " + edge);
continue;
}
if (!pay(cost)) {
log.warning("construction too expensive (waiting): " + edge + " = $"
+ cost);
track.pushProposed(edge);
return null;
}
log.info("Constructed track: " + edge);
return edge;
}
}
/**
* Pay out the sum given, or fail to do so.
*
* @param cost amount to pay out
* @return whether payment succeeded
*/
protected boolean pay(double cost) {
if (money < cost)
return false;
if (cost != 0.0)
setChanged();
money -= cost;
notifyObservers(new Double(cost));
return true;
}
/**
* Return true whether this edge is in a large city (between suburbs or
* between suburbs of a large city). Such edges can be travelled by any train
* that
*
* @param e edge of concern, not null
* @return whether in a city
*/
protected boolean inCity(HexEdge e) {
Pair<HexCoordinate, HexCoordinate> p = e.getHexagons();
return inCity(p.fst) && inCity(p.snd);
}
/**
* Return true if cooridnate is a large city or a suburb.
*
* @param h coordinate to examine, not null
* @return true if terrain at this coordinate is a large city or a suburb.
*/
protected boolean inCity(HexCoordinate h) {
Terrain t = game.getTerrain(h);
return t == Terrain.LARGE || t == Terrain.SUBURB;
}
/**
* Return whether this player is already connected to the hex coordinate,
* either because they already have track to the location or because it is a
* suburb of a large city.
*
* @param h
* @return whether connected to this coordinate
*/
protected boolean isConnected(HexCoordinate h) {
if (game.getTerrain(h) == Terrain.SUBURB)
return true;
for (HexDirection d : HexDirection.values()) {
if (game.occupier(new HexEdge(h, d)) == this)
return true;
}
return false;
}
public void update(Observable source, Object arg) {
setChanged();
if (arg == null)
arg = this;
super.notifyObservers(arg);
}
/**
* The player proposes to construct track here. If there already is a proposal
* to construct track, this new proposal is ignored. If the remove flag is
* given, we remove any existing plans for this edge.
*
* @param e location of track, not null
* @param remove remove proposal rather than add proposal
*/
public void proposeConstruction(HexEdge e, boolean remove) {
if (remove)
track.removeProposal(e);
else
track.propose(e);
}
/**
* Forget all proposed construction projects.
*/
public void clearConstructionProposal() {
track.clearProposed();
}
/**
* Plan to move the train here after previous plans. If the remove flag is
* set, remove plans instead of adding them. Adding the same coordinate twice
* in succession has no effect, but adding the same coordinate after
* intervening coordinates is assumed intentional: perhaps the train stops and
* turns back.
*
* @param h coordinate to move to, not null
* @param remove whether to remove a plan for this coordinate rather than add
*/
public void planMovement(HexCoordinate h, boolean remove) {
if (remove)
train.removePlanned(h);
else
train.addPlanned(h);
}
/**
* Clear any plans for movement.
*/
public void clearMovementPlan() {
train.clearPlanned();
}
public CardStatus getCardStatus() {
return cards;
}
public TrainStatus getTrainStatus() {
return train;
}
public TrackStatus getTrackStatus() {
return track;
}
}
<file_sep>/src/edu/uwm/cs552/DefaultConstructionCost.java
package edu.uwm.cs552;
/**
* Default construction cost.
* Assuming track is legal (not BLOCKed and not within a large city or into water),
* then we charge 1 for the track itself, one extra for mountains
* (twice if between two mountains), two extra for crossing rivers or entering
* small or medium cities, and four extra for crossing an inlet.
*/
public class DefaultConstructionCost implements ConstructionCost {
private static ConstructionCost instance;
/**
* Return the singleton instance of this class.
* @return
*/
public static ConstructionCost getInstance() {
if (instance == null) instance = new DefaultConstructionCost();
return instance;
}
private DefaultConstructionCost() {}
private double barrierCost(Barrier b) {
if (b == null) return 0.0;
switch (b) {
case BLOCK:
return Double.POSITIVE_INFINITY;
case INLET:
return 4.0;
case RIVER:
case DRAWN:
return 2.0;
}
return Double.POSITIVE_INFINITY;
}
private double terrainCost(Terrain t) {
if (t == null) return Double.POSITIVE_INFINITY;
switch (t) {
case SUBURB:
case PLAIN: return 0.0;
case DESERT: return 0.0;
case MOUNTAIN: return 1.0;
case SMALL:
case MEDIUM: return 2.0;
case LARGE:
case WATER: return Double.POSITIVE_INFINITY;
}
return Double.POSITIVE_INFINITY;
}
public double cost(Terrain t1, Barrier b, Terrain t2) {
// special case: not allowed to build between two suburbs,
// because we assume they are for the same city.
if (t1 == Terrain.SUBURB && t2 == Terrain.SUBURB) return Double.POSITIVE_INFINITY;
return 1 + terrainCost(t1) + barrierCost(b) + terrainCost(t2);
}
}
<file_sep>/src/edu/uwm/cs552/TrackRental.java
package edu.uwm.cs552;
public interface TrackRental {
/**
* How much does it cost to travel on another
* players rails between two points, across a given barrier.
* @param t1 first terrain
* @param b barrier being crossed, may be null
* @param t2 second terrain
* @return standardized track usage fee
*/
public double cost(Terrain t1, Barrier b, Terrain t2);
}
<file_sep>/src/edu/uwm/cs552/HexBoard.java
package edu.uwm.cs552;
import java.awt.Color;
import java.awt.Graphics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Set;
import edu.uwm.cs552.gfx.SVGImageCreator;
import edu.uwm.cs552.util.FormatException;
/**
* The fixed part of a hexagonal game board.
* We have a back image, terrain and barriers (rivers) for certain coordinates.
*/
public class HexBoard extends Observable implements Serializable{
/**
* We may need to serialize this class.
*/
private static final long serialVersionUID = 1L;
private SVGImageCreator background;
private double naturalWidth, naturalHeight;
private Map<HexCoordinate,Terrain> terrains = new HashMap<HexCoordinate,Terrain>();
private Map<HexEdge,Barrier> barriers = new HashMap<HexEdge,Barrier>();
private Map<HexCoordinate,City> cities = new HashMap<HexCoordinate,City>();
private Map<Good,List<HexCoordinate>> sources = new HashMap<Good,List<HexCoordinate>>();
public static final int DEFAULT_WIDTH = 75;
public static final int DEFAULT_HEIGHT = 50;
public HexBoard() {
initialize();
}
private void initialize() {
background = null;
naturalWidth = DEFAULT_WIDTH;
naturalHeight = DEFAULT_HEIGHT;
}
/**
* Create a hex board with the given background image
* and natural width and height (in terms of hexagon widths).
* @param im background image, may be null
* @param w width
* @param h height
*/
public HexBoard(SVGImageCreator im, double w, double h) {
background = im;
naturalWidth = w;
naturalHeight = h;
}
protected void addSources(HexCoordinate h, City c) {
if (c == null) return;
for (Good g : c) {
List<HexCoordinate> l = sources.get(g);
if (l == null) {
l = new ArrayList<HexCoordinate>();
sources.put(g, l);
}
l.add(h);
}
}
protected void removeSources(HexCoordinate h, City c) {
if (c == null) return;
for (Good g : c) {
sources.get(g).remove(h);
}
}
/**
* Return locations where this good can be found.
* @param g good to look for
* @return places where source can be found, never null
*/
public Iterable<HexCoordinate> getSources(Good g) {
List<HexCoordinate> s = sources.get(g);
if (s == null) s = Collections.emptyList();
return s;
}
/**
* Return city (if any) at the given location
* @param h location to check, may be null
* @return city at this location, or null
*/
public City getCity(HexCoordinate h) {
return cities.get(h);
}
/**
* Return an immutable collection of all city locations on the board.
* @return collection of city locations.
*/
public Set<HexCoordinate> allCityLocations() {
return Collections.unmodifiableSet(cities.keySet());
}
public Terrain getTerrain(HexCoordinate h) {
return terrains.get(h);
}
public Terrain putTerrain(HexCoordinate h, Terrain t) {
Terrain result = terrains.put(h, t);
City former = cities.remove(h);
removeSources(h,former);
super.setChanged();
super.notifyObservers(h);
return result;
}
public Terrain putTerrain(HexCoordinate h, Terrain t, City c) {
if (!t.isCity()) throw new IllegalArgumentException("Cannot assign city info for " + t);
if (c == null) return putTerrain(h,t);
Terrain result = terrains.put(h, t);
removeSources(h,cities.put(h, c));
addSources(h,c);
super.setChanged();
super.notifyObservers();
return result;
}
public Terrain removeTerrain(HexCoordinate h) {
final Terrain result = terrains.remove(h);
removeSources(h,cities.remove(h));
super.setChanged();
super.notifyObservers(h);
return result;
}
public Barrier getBarrier(HexEdge e) {
return barriers.get(e);
}
public Barrier putBarrier(HexEdge e, Barrier b) {
final Barrier result = barriers.put(e, b);
super.setChanged();
super.notifyObservers(e);
return result;
}
public Barrier removeBarrier(HexEdge e) {
final Barrier result = barriers.remove(e);
super.setChanged();
super.notifyObservers(e);
return result;
}
public void setBackground(SVGImageCreator im, double w, double h) {
background = im;
naturalWidth = w;
naturalHeight = h;
super.setChanged();
super.notifyObservers(this);
}
public void clear() {
initialize();
terrains.clear();
barriers.clear();
cities.clear();
super.setChanged();
super.notifyObservers(this);
}
/**
* Copy everything from the other board to this.
* @param b board to copy, must not be null
*/
public void copy(HexBoard b) {
terrains.clear();
barriers.clear();
cities.clear();
terrains.putAll(b.terrains);
barriers.putAll(b.barriers);
cities.putAll(b.cities);
setBackground(b.background,b.naturalWidth,b.naturalHeight);
}
private static final double SQRT32 = Math.sqrt(3)/2; // ##
/**
* Draw the game board into the given graphics context.
* @param g graphics context, must not be null
* @param scale width of hexagons
* @param showHidden whether to draw implicit barriers and suburbs
* @param drawMesh whether to draw the outline of all hexagons
*/
public void draw(Graphics g, double scale, boolean showHidden, boolean drawMesh) {
if (background != null) {
background.draw(g, getWidth(scale), getHeight(scale));
}
for (Map.Entry<HexCoordinate,Terrain> e : terrains.entrySet()) {
e.getValue().draw(g, e.getKey(), scale, showHidden);
}
for (Map.Entry<HexEdge,Barrier> e : barriers.entrySet()) {
e.getValue().draw(g, e.getKey(), scale, showHidden);
}
for (Map.Entry<HexCoordinate, City> ec : cities.entrySet()) {
ec.getValue().draw(g, ec.getKey(), scale);
}
if (drawMesh) {
g.setColor(Color.black);
int abound = (int)Math.ceil(naturalWidth);
int bbound = (int)Math.ceil(naturalHeight/SQRT32);
for (int b = 0; b <= bbound; ++b) {
for (int a = 0; a <= abound; ++a) {
HexCoordinate h = new HexCoordinate(a+b/2,b);
g.drawPolygon(h.toPolygon(scale));
}
}
}
}
/**
* Get the height of the board (the height of the background image)
* given the current scale.
* @param scale scale to use
* @return height of board.
*/
public int getHeight(double scale) {
return (int)(naturalHeight*scale);
}
/**
* Get the width of the board (the width of the background image)
* given the current scale.
* @param scale scale to use
* @return width of board
*/
public int getWidth(double scale) {
return (int)(naturalWidth*scale);
}
/**
* Write a hexboard out using the form:
* <pre>
* <i>URL (or empty, if no background image)</i>
* <i>width</i>
* <i>height</i>
* <i>goods</i>
* <i>[The following section repeated indefinitely]</i>
* <i>terrain</i>
* <i>hexcoordinate<sb>1</db></i>
* <i>hexcoordinate<sb>2</db></i>
* ...
* <i>hexcoordinate<sb>n</db></i>
* OR
* <i>barrier</i>
* <i>hexedge<sb>1</db></i>
* <i>hexedge<sb>2</db></i>
* ...
* <i>hexedge<sb>n</db></i>
* </pre>
* @param pw output to use, must not be null
*/
public void write(PrintWriter pw) {
if (background == null) {
pw.println();
} else {
pw.println(background.getURL().toExternalForm());
}
pw.println(naturalWidth);
pw.println(naturalHeight);
Good.writeGoods(pw);
Terrain previous = null;
for (Map.Entry<HexCoordinate,Terrain> e : terrains.entrySet()) {
if (e.getValue() == null) continue;
if (e.getValue() != previous) {
previous = e.getValue();
pw.println(e.getValue());
}
pw.print(e.getKey());
if (previous.isCity() && cities.containsKey(e.getKey())) {
City city = cities.get(e.getKey());
//pw.print(",");
pw.print(city.getName());
for (Good g : city) {
pw.print(",");
pw.print(g.getName());
}
}
pw.println();
}
Barrier barrier = null;
for (Map.Entry<HexEdge,Barrier> e : barriers.entrySet()) {
if (e.getValue() == null) continue;
if (e.getValue() != barrier) {
barrier = e.getValue();
pw.println(e.getValue());
}
pw.println(e.getKey());
}
}
private static final Set<String> ALL_TERRAINS = new HashSet<String>();
private static final Set<String> ALL_BARRIERS = new HashSet<String>();
static {
for (Terrain t : Terrain.values()) {
ALL_TERRAINS.add(t.name());
}
for (Barrier b : Barrier.values()) {
ALL_BARRIERS.add(b.name());
}
}
/**
* Read in a hex board using the format given in {@link #write(PrintWriter)}.
* Throw an appropriate exception given a problem.
* @param br buffered reader to use, must not be null
* @return a new hex board
* @throws IOException if there is an error reading the file, or if the URL is bad, or the SVG in it
* @throws FormatException an error reading a hex coordinate or terrain
* @throws NumberFormatException an error reading the width or height
*/
public void read(BufferedReader br) throws IOException, FormatException, NumberFormatException {
String url = br.readLine();
double newWidth = Double.parseDouble(br.readLine());
double newHeight = Double.parseDouble(br.readLine());
Terrain terrain = null;
Barrier barrier = null;
String s;
SVGImageCreator im = url.equals("") ? null : new SVGImageCreator(new URL(url));
Map<HexCoordinate,Terrain> newTerrains = new HashMap<HexCoordinate,Terrain>();
Map<HexEdge,Barrier> newBarriers = new HashMap<HexEdge,Barrier>();
Map<HexCoordinate,City> newCities = new HashMap<HexCoordinate,City>();
s = Good.readGoods(br);
while (s != null) {
if (ALL_TERRAINS.contains(s)) {
barrier = null;
terrain = Terrain.valueOf(s);
} else if (ALL_BARRIERS.contains(s)) {
terrain = null;
barrier = Barrier.valueOf(s);
} else if (terrain != null) {
int coordEnd = s.indexOf('>');
if (coordEnd < 0) throw new FormatException("Expecting coordinate: <...,...>: " + s);
if (terrain.isCity() && coordEnd+1 < s.length()) {
String[] pieces = s.substring(coordEnd+1).split(",");
HexCoordinate h = HexCoordinate.fromString(s.substring(0,coordEnd+1));
City city = new City(pieces[0]);
for (int i=1; i < pieces.length; ++i) {
city.addGood(Good.findGood(pieces[i]));
}
newCities.put(h, city);
newTerrains.put(h, terrain);
s = br.readLine();
continue;
}
HexCoordinate h = HexCoordinate.fromString(s);
newTerrains.put(h, terrain);
} else if (barrier != null) {
HexEdge e = HexEdge.fromString(s);
newBarriers.put(e, barrier);
} else {
throw new FormatException("expected terrain or barrier first: " + s);
}
s = br.readLine();
}
terrains.clear();
barriers.clear();
cities.clear();
sources.clear();
terrains.putAll(newTerrains);
barriers.putAll(newBarriers);
cities.putAll(newCities);
for (Map.Entry<HexCoordinate,City> e : cities.entrySet()) {
addSources(e.getKey(),e.getValue());
}
setBackground(im,newWidth,newHeight);
}
}
<file_sep>/src/edu/uwm/cs552/DefaultTrackRental.java
package edu.uwm.cs552;
/**
* Default track rental costs.
* Normally 0.5, but increasing to 1.0 to cross an inlet.
*/
public class DefaultTrackRental implements TrackRental {
private static TrackRental instance;
public static TrackRental getInstance() {
if (instance == null) instance = new DefaultTrackRental();
return instance;
}
private DefaultTrackRental() {}
public double cost(Terrain t1, Barrier b, Terrain t2) {
// between suburbs of (presumably) the same city,
// and going into the city center or out, is free
if (t1 == Terrain.SUBURB && t2 == Terrain.SUBURB) return 0.0;
if (t1 == Terrain.LARGE || t2 == Terrain.LARGE) return 0.0;
if (b == null) return 0.5;
switch (b) {
default: return 0.5;
case INLET: return 1.0; // charge extra for major bridges
}
}
}
<file_sep>/src/edu/uwm/cs552/net/ActionResponse.java
package edu.uwm.cs552.net;
/**
* Possible responses to an action.
* Either we complete an action, or we return an error.
* We assume that a client is only sending legal turn requests,
* so it can only be because of a race condition that someone fails.
* But in order to handle an erroneous or malicious client,
* we have an error that a turn is rejected.
*/
public enum ActionResponse {
OK, // action completed successfully
INSUFFICIENT_FUNDS, // not enough money
BUILD_TOO_LATE, // someone has already built
MOVE_BLOCKED, // cannot move because someone is in way
LOAD_UNAVAILABLE, // all units have been removed
REJECT; // action illegal, may indicate client is out-of-sync with server
public String message() {
switch (this) {
default:
return "Unknown message";
case OK: return "Action successful";
case INSUFFICIENT_FUNDS: return "Insufficient funds";
case BUILD_TOO_LATE: return "Track already constructed by another player";
case MOVE_BLOCKED: return "Move block by another player";
case LOAD_UNAVAILABLE: return "Good not currently available";
case REJECT: return "Request not legal in some way";
}
}
}
|
342766353ef0e98441068bbfef1c35fe41218244
|
[
"Java"
] | 21 |
Java
|
adfuhr/homework7
|
de8dd85e29d7193a5524225e125f3222bbc8ff45
|
fed43315ee28eef64fcc0c6fc0109f7bcc65add9
|
refs/heads/master
|
<file_sep>#include "types.h"
#include "param.h"
#include "defs.h"
#include "mmu.h"
#include "proc.h"
void sys_monopolize(int password){
#ifdef MLFQ_SCHED
argint(0,&password);
monopolize(password);
#endif
return;
}<file_sep>#include "types.h"
#include "param.h"
#include "defs.h"
#include "mmu.h"
#include "proc.h"
// ppid system call
int getppid(void){
// cprintf("%s\n",str);
return myproc()->parent->pid;
}
// wrapper
int sys_getppid(void){
char *str;
if(argstr(0,&str)<0)
return -1;
return getppid();
}
<file_sep>#include "types.h"
#include "param.h"
#include "defs.h"
#include "mmu.h"
#include "proc.h"
void sys_setpriority(int pid,int priority){
#ifdef MLFQ_SCHED
argint(0,&pid);
argint(1,&priority);
setprocpriority(pid,priority);
#endif
}<file_sep>#include "types.h"
#include "param.h"
#include "defs.h"
#include "mmu.h"
#include "proc.h"
int sys_getlev(void){
#ifdef MLFQ_SCHED
return getlev();
#endif
return 0;
}<file_sep>운영체제 과제 2(implementing simple schedulers on xv6)
---
---
### 테스트 환경 :
##### OS : Ubuntu 16.04
##### gcc : gcc 5.4.0
### 개요 :
운영체제 두번째 과제인 **Implementing simple schedulers (FCFS,MLFQ)**에 대한 내용입니다.
크게 **FCFS** 정책과 **MLFQ** 정책을 사용하게끔 분기됩니다.
---
## FCFS
### 과제 명세 :
먼저 **FCFS** 스케쥴링의 명세는 다음과 같습니다.

1. 먼저 생성(fork())된 프로세스가 먼저 스케줄링 되어야 한다.
2. 스케줄링된 프로세스는 종료되기 전까지는 swithc-out 되지 않는다.
3. 프로세스가 스케쥴링 된 이후 100ticks이 지날때까지 종료되거나 sleeping 하지 않으면 종료해야한다.
4. 실행중인 프로세스가 sleeping으로 전환되면 다음 프로세스가 스케줄링된다.
5. sleeping 상태이면서 먼저 생성된 P가 깨어나면 그 프로세스로 스케줄링 된다.
### 작동과정 설명 :
첫번째로 **FCFS** 스케쥴링 정책 내에서의 작동 과정,설정값들과 예시입니다.
먼저, **ptable**에는 **pid** 순서대로(**만들어진 순서대로**) 삽입되어 있습니다.

그렇기 때문에 **ptable**에서 ptable.proc[0,1,2,3....]이렇게 접근을 한다면 생성된 프로세스에 접근을 할 수 있습니다.
또, **pid** 순서대로 들어있기 때문에 별도의 큰 조작 없이도 **First Come First Served**의 스케쥴링이 수행가능합니다. (1번 명세)
하지만 기존의 정의되어 있는 **struct proc**에는 이 Process가 얼마만큼의 시간동안 수행되었는지에 대한 정보를 담고있지 않기 때문에

위와 같이 **uint ctime**과 **uint stime**을 추가해줍니다.
**ctime**의 역할은 프로세스가 생성된 시간을 의미하고,
*(사실 pid가 이 역할을 대체할 수 있고 더 정확합니다.)*
**stime**은 스케쥴러에 의해 이 Process가 선택된 시간(**ticks**)을 의미합니다.

위의 사진처럼 **FCFS** 알고리즘에 의해서 선택되었을때 , **stime**을 현재의 **ticks**로 설정해줍니다.
**FCFS** 알고리즘의 역할은 **가장 이전에 생성된,다시 말해서 pid가 가장 작고**, **현재 수행가능한 상태(RUNNABLE)**인
Process를 고르는 것입니다..
그렇기 때문에 아래와 같은 code block으로 조건을 만족하는 적합한 Process를 선택합니다.
```
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){ // ptable.proc을 앞에서부터 순차적으로 탐색함, NPROC까지 탐색함
if(p->state!=RUNNABLE)
continue;
else{
p->stime=ticks;
...
p->state=RUNNING
...
swtch(&(c->scheduelr),p->context);
...
}
```
SLPEEING이 끝나고 wake 하게 될때도 **ptable**을 순차적으로 앞에서부터 탐색하기 때문에
**pid가 낮은,먼저 생성된** Process를 처리할 수 있습니다.
또, **실행된지 100ticks**가 넘어갔을때 종료하는 조건은 trap.c 내에

로 구성되어 있습니다. **현재 tick**에서 **stime**을 뺀 결과가 100보다 크거나 같다는 뜻은,
이 Process가 100tick이상 run되었다는 뜻입니다.***(항상 스케쥴될때 stime=0으로 현재 ticks으로 초기화)***
그렇기 때문에 이 Process의 killed을 1로 바꿔주고, 이렇게 되면 다음 timer때 이 프로세스는 죽습니다.
---
### FCFS Test 결과와 간단한 설명
**조건 : NUM_CHILD를 5에서 7로 수정,**
첫번째 테스트 **(sleep이나 yield를 하지 않고)**

예상대로, sleep,yield 아무것도 하지 않았으니 먼저 생성되는 P5부터 P11까지 출력을 순차적으로 진행합니다.
두번째 테스트 **(yield를 할때)**

예상대로, yeild를 하더라도 먼저 생성된 프로세스에게 우선권이 있으므로 다시 CPU 사용권한이 돌아와 진행합니다.
세번째 테스트 **(sleep)**을 할때

sleep을 하면 순차적으로 진행되는것처럼 보이지만 ,
...P25->P19->P20->P21->P22->P23->P24->**P19** 이부분에서
P24의 다음으로 P25가 스케쥴링되는것이 아니라 wakeup한 P19가 선택되어 진행됩니다.
이러한 현상은 꾸준히 관찰할수 있습니다만, 테스팅되는 하드웨어에 따라 상황이 달라짐을 확인했습니다.
네번째 테스트 **100tick을 초과했을때**

예상대로 , **pid**가 가장 작은 프로세스가 실행되다가 100tick이 지나면 강제종료되고,
다음 프로세스가 스케줄링됨을 확인할수 있습니다. 또 모든 자식 프로세스가 강제 종료되면 OK메세지를 확인가능합니다.
---
### 트러블슈팅
**FCFS**는 비교적 간단한 구현이어서 **FCFS** 그 자체는 크게 어렵지는 않았습니다.
다만 xv6의 내부적인 기능을 처음 구현하다보니 sched 함수나 scheduler 함수와 같은 중추적인 함수들을 분석하는데 시간을 쏟았습니다.
또 trap.c 함수 내에서의 trap 함수가 어떻게 사용되는지 분석하는데 시간을 투자했습니다..
---
## MLFQ (Multi Level Feedback Queue)
### 과제 명세 :
먼저 **MLFQ** 스케쥴링의 명세는 다음과 같습니다.


### 작동 과정 설명:
**MLFQ** 구현의 가장 중요한 점은 **L0 큐**와 **L1 큐** 각각의 스케쥴링 알고리즘이 같은 부분이 존재하지만 몇가지 점이 다르다는 것입니다.
**L0 큐**는 기본적으로 **Round robin(Q=4ticks)**이고, **L1 큐**는 **Round robin(Q=8tciks)**에 **priority**가 고려대상이라는 것입니다.
먼저 **ptable**의 구조는 이전과 동일합니다. 차이점은 proc.h에 정의되어 있는 proc 구조체입니다.

속해있는 Q level 을 드러내는 **int lev**, 우선순위를 나타내는 **int priority**, 작동한 시간을 의미하는 **int rtime**(0부터 시작),
이 Process가 CPU를 독점하는지 체크하는 **int monopolize** ( 1은 독점중,0은 독점중이 아님)등이 추가되었습니다.
먼저 proc.c 안에 정의된 **allocproc** 함수에서

와 같은 코드로, 초기에 **priority**를 0으로, 초기 **lev**을 0으로, **monopolize** 값을 0으로 초기화해줍니다.
이를 통해 처음 실행되는 프로세스의 우선순위를 0으로 , 그리고 가장 높은 레벨의 큐(L0)로 삽입됩니다.
그 다음으로 스케쥴링을 담당하는 **scheduler**함수입니다.
첫번째 사진은 **RUNNABLE**한 프로세스 중 **L0큐**에 속해있는 프로세스의 존재를 측정하고,
있다면 **L0큐**를 탐색하여 적절한 Process를 찾는 부분입니다.

먼저 **L0 큐 **내에 존재하는한 Process를 개수를
**적절한 프로세스**는 다음과 같이 찾을수 있습니다.
1. 프로세스가 **구동가능한 상태인가?** ***(RUNNABLE)***
2. 프로세스의 **큐 레벨이 0**인가?
위 두가지 조건을 모두 만족해야 **적절한 프로세스**라고 할수 있습니다.
적절한 프로세스를 찾았다면, **rtime**을 0으로 초기화해주고 **context swithcing**이 일어납니다.
두번째 사진은 **L0 큐**에 적절한 Process가 없을때 **L1 큐**를 탐색하고 가장 높은 Priority 를 가지는 Process를 선택하는 부분입니다.

프로세스를 **순차적으로 돌면서** **L1 큐**에 있는 것중에서 **Priority가 가장 높은 프로세스를 선택**합니다.
그 후 그 프로세스로 **context swithcing**이 일어납니다.
priority 우선순위가 같다면 , ptable을 시작에서부터 순차적으로 탐색하기때문에 **FCFS**로 행동합니다.
---
#### **MLFQ** 구조는 trap.c가 중요합니다.
trap.c에서 MLFQ와 관련해서 동작하는 것은 크게
1. 지금 현재 프로세스의 **rtime**을 증가시키는것.
2. 지금 현재 구동중인 프로세스가 **L0큐**인데,**rtime**이 **4 tick** 이상이고, **독점적**이지 않을때 L1 큐로 강등하고 **yield()**수행함.
3. 지금 현재 구동중인 프로세스가 **L1큐**인데,**rtime**이 **8 tick** 이상이고, **독점적**이지 않을때 **priority**가 0보다 크다면 1만큼 감소시키고,
**yield()**을 수행.
4. ***Starvation***을 방지하기 위해 **100 tick** 마다 **Priority boosting**을 수행.
하는 4가지로 구분 될 수 있습니다.
그 중에 첫번째로
*1. 지금 현재 프로세스의 **rtime**을 증가시키는것.*입니다.

위와 같은 코드로 수행됩니다.
주요 원리는 *TIMER interrupt는 매 tick 마다 발생*되므로, 그에 맞춰서 현재 구동중인 프로세스 정보를 얻어오고 그 프로세스의 **rtime**을 1만큼 증가시킵니다.
두번째로
* 2. 지금 현재 구동중인 프로세스가 **L0큐**인데,**rtime**이 **4 tick** 이상이고, **독점적**이지 않을때 L1 큐로 강등하고 **yield()**수행함. *

위와 같은 코드로 수행됩니다.
현재 레벨이 0이고, 실행된 **rtime**이 4tick상이고, 독점적이지 않는다면 **yield()**를 호출하고 L1 큐로 강등시킵니다. **yield** 함수는 sched 함수를 호출하고 sched에서 scheduler가 호출되니 다음 프로세스를 스케쥴링합니다.
세번째로
*3. 지금 현재 구동중인 프로세스가 **L1큐**인데,**rtime**이 **8 tick** 이상이고, **독점적**이지 않을때 **priority**가 0보다 크다면 1만큼 감소시키고,
**yield()**을 수행.*

위와 같은 코드로 수행됩니다.
전체적으로 두번째 L0 와 비슷하지만, priority가 0보다 크다면 1만큼 감소시키는것이 다릅니다. 감소를 하거나 하지 않은 두가지 경우 모두에서 **yield**를 호출 하기 때문에 **yield** 함수는 sched 함수를 호출하고 sched에서 scheduler가 호출되니 다음 프로세스를 스케쥴링합니다.
네번째로는
*4. ***Starvation***을 방지하기 위해 **100 tick** 마다 **Priority boosting**을 수행.*
*trap.c*

*proc.c*

위와 같이 trap.c에서 proc.c에 정의된 priboosting 함수를 호출합니다.
priboosting 함수는 아래에서 설명하겠지만, L1에 있는 모든 프로세스들을 L0큐로 올리고, priority를 0으로 초기화합니다.
---
### MLFQ Test 결과와 간단한 설명
**조건 :**
1. NUM_LOOP2를 **300000(30만)**으로 수정
2. NUM_LOOP3를 **200000(20만)**으로 수정
3. NUM_LOOP4를 **500000(50만)**으로 수정
> 테스트 조건을 수정한 이유는 뚜렷한 경향성을 파악하기 위해서 **충분한 Iteration**을 확보하기 위함입니다.
첫번째 테스트 (**priority를 변경하면서**)

예상대로 pid 값이 더 큰 프로세스의 **priority**가 더 높게 설정되기 때문에, pid 값이 더 큰 프로세스가 먼저 끝나게 되고,
**pid값이 작은 프로세스** ( 사진에서 **5번 프로세스 혹은 4번**)가 L0에서 실행되는 시간이 긴 경향을 보입니다.
두번째 테스트(**priority 변경 없이**)

예상대로 pid 값이 작은 프로세스가 **L1의 비율이 높습니다.**
이는 , L1 큐에서는 같은 **priority** 를 가지는 프로세스라면 **FCFS**로 동작하기 때문입니다..
세번째 테스트 (**yield**)

왠만하면 L0의 **4 tick quantum**을 다 사용하지 않기 때문에 시간 사용량이 초기화되니,
계속 L0에 남아있게 됩니다. L0는 **Round robin**이기 때문에 거의 동시에 작업이 완료됩니다.
네번째 테스트 (**monopolize**)

**monopolize**라는 시스템콜을 사용한 테스트입니다.
가장 큰 PID를 가진 프로세스가 CPU 독점을 요청하기 때문에 가장 큰 pid인
Process 45가 CPU를 독점합니다. **MLFQ** 스케쥴링은 일어나지 않기 때문에
L0의 에서 모든 작업을 완료합니다.
다른 프로세스는 test2의 결과와 유사한것을 볼 수 있습니다.
---
#### 트러블슈팅
**FCFS** 와는 다르게 고려해야할 부분이 많았습니다.
대표적으로 두가지 문제가 있었습니다.
1. 스케쥴링 함수를 구현할때 여러가지 조건문이 중첩됨.
2. monopolizing의 구현
다음과 같이 해결했습니다.
1. 중첩되는 모든 케이스를 명시하는것이 아니라 큰 틀에서 if문을 분기하여 처리함.
2. 현재 프로세스가 **rtime**을 넘겼을때 yield하는 부분에서 monopolize 체크를 위하여, proc 구조체에 플래그를 삽입함. 이를 통해 trap 함수에서 호출될때 혖현재 프로세스의 monopolize flag를 체크해서 독점적이지 않을때만 CPU 자원을 포기하도록 구현함.
---
### 시스템 콜
과제 수행을 위해 필요한 **System call**은 총 4개입니다.
1. void yield(void)
2. int getlev(void)
3. void setprioirty(int pid,int priority)
4. void monopolize(int password)
각각의 시스템 콜 구현체를 먼저 보이고 , 공통적인 부분은 마지막에 첨부합니다
첫번재로 **void yield(void) 함수**입니다.

sys_yield 시스템콜은 proc.c에 정의되어 있는 yield 함수를 호출하는 것입니다. 현재 프로세스가 CPU 자원을 반납하는 행동입니다.
두번째로 **int getlev(void) 함수**입니다. 현재 프로세스의 큐 레벨을 반환하는 것입니다.


getlev 시스템콜은 proc.c 에 정의 한 getlev 함수를 호출합니다.
proc.c 에서 정의된 getlev 함수는
현재 프로세스가 독점중인 상태라면 1을 반환하고,
그렇지 않다면 현재 프로세스의 큐레벨인 **lev** 을 반환합니다. (*return myproc()->lev*);
세번째로 **void setpriority(int pid,int priority) 함수 **입니다. 인자로 받은 pid와 일치하는 프로세스의 priority를 인자 priority로 변경합니다.


setpriority 시스템콜은 proc.c에 정의한 setprocpriority 함수를 호출합니다.
proc.c에서 정의된 setprocpriority 함수는
현재 **ptable**에서 **인자 pid와 매칭되는 프로세스**를 찾고, **인자 priority로 프로세스의 priorirty를 변경**합니다.*(targetP->priority=priority)*
시스템콜이기 때문에 argint를 이용하여 인자를 받습니다.
마지막으로 ** void monopolize(int password) 함수 **입니다. 인자로 받은 password와 미리 설정한 본인의 학번과 비교한뒤 일치하면
현재 프로세스를 **CPU에 독점적인 권한**을 가지게 변경합니다.


monopolize 시스템콜은 proc.c에 정의한 monopolize 함수를 호출합니다.
proc.c에 정의된 monopolize 함수는
먼저 **ptable**의 **lock을 acquire**해주고
현재 프로세스의 **monopolize**가 1이라면,**독점적이라면**, 인자 password를 학번 <PASSWORD>와 체크한후, **일치**하면
**monopolize**를 0으로 바꾸어 독점해제하고, 현재 프로세스를 L0으로 이동시키고 **priority**를 0으로 변경합니다.
**일치하지 않으면** 독점을 해제하고, 현재 프로세스를 kill 합니다.*(kill 함수의 행동과 유사하게 행동합니다)*
**그 후 "wrong password at calling monopolize"라고 유저에게 안내합니다.**
현재 프로세스의 **monopolize**가 0이라면,**독점적이 아니라면,** 인자 password를 학번 <PASSWORD>와 체크한후, **일치**하면
**monopolize**를 1으로 바꾸어 독점을 시작하고, 현재 프로세스를 L0으로 이동시키고 **priority**를 0으로 변경합니다.
**일치하지 않으면** 현재 프로세스를 kill 합니다.*(kill 함수의 행동과 유사하게 행동합니다)*.
**그 후 "wrong password at calling monopolize"라고 유저에게 안내합니다.**
그 후 **ptable**의 **lock을 release** 해줍니다.
---
### 시스템 콜 공통 사항
#### usys.S

#### user.h

#### syscall.h

#### syscall.c


#### Makefile 시스템 콜 부분

#### Makefile 코드 분기를 위해서 삽입한 부분


---
### 시스템콜 트러블슈팅
몇가지 마이너한 이슈가 있었습니다.
시스템콜의 인자를 처리할때는 **argint**을 사용한다는 것을 몰라 사용하지 못했고, 좀 더 자료를 찾아본 후 적용가능했습니다.
**monopolize** 함수의 처리가 **trap.c 내부** 에서 일어나야 할지 , **proc.c 내부**에서 일어나야할지 선택해야 했습니다.
**proc 구조체**를 수정해 monopolize flag 자체는 **proc.c 내부에서 수정**하되 **trap 내부에서 체크**하여 적용하는 것으로 구현했습니다.
<file_sep>#include "types.h"
#include "defs.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "x86.h"
#include "proc.h"
#include "spinlock.h"
struct {
struct spinlock lock;
struct proc proc[NPROC];
}ptable;
int sys_yield(void){
yield();
return 0;
}
<file_sep>#include "types.h"
#include "stat.h"
#include "user.h"
#include "mmu.h"
#include "x86.h"
#include "param.h"
#include "spinlock.h"
#include "memlayout.h"
#include "proc.h"
int main(int argc,char*argv[]){
int pid;
pid=fork();
for(int i=0;i<10;i++){
if(pid==0){
printf(1,"Child\n");
yield();
}
else{
printf(1,"Parent\n");
yield();
}
}
return 0;
}
<file_sep>운영체제 과제 4(double indirect inode)
---
---
### 테스트 환경 :
##### OS : Ubuntu 16.04
##### gcc : gcc 5.4.0
### 개요 :
운영체제 네번째 과제인 **double indirect inode**에 대한 내용입니다.
크게 **fs.c**안의 **bmap , itrunc**함수를 수정하고, **fs.h**와 **file.h**, **param.h**의 값을 조금 수정함으로써 **double indirect inode**를 구현합니다.
---
### 과제 명세 :
먼저 xv6의 기본적인 inode의 구조에 대한 간단한 구조입니다.

**dinode** 구조체에서 **direct block pointer는 12개**가 존재하고, 1개의 **indirect block pointer**가 존재합니다.
그런 구조를 아래와 같이 수정해야합니다.

**dinode** 구조체에서 **direct block pointer**가 11개로 바뀌고, 1개의 **single indirect block pointer**, 그리고 1개의 **dobule indirect block pointer**가 존재합니다.
구현하기 위해서는 **bmap**과 **itrunc** 함수를 수정해야 합니다.

---
## fs.h 수정 사항
**fs.h**에서 NDIRECT의 값을 1만큼 줄여주고 **(12->11)**,
**NDOUBLEINDIRECT** 의 값을 **NINDIRECT의 제곱**으로 정의합니다.
**addrs 배열**의 크기를 NDIRECT의 값과 매치되게 수정합니다.
```
( addrs[NDIRECT+1]->addrs[NDIRECT+2])
```

이렇게 작성하면 **direct block pointer**의 개수는 11개로 줄어들고,
**single(addrs[11]), dobule indirect block pointer(addrs[12])**가 만들어집니다.
## file.h ,param.h 수정 사항
**inode **의 구조체 안에 있는 addrs 배열도 **dinode**에서 addrs 배열을 수정한것과 같이 수정해줍니다.
```
( addrs[NDIRECT+1]->addrs[NDIRECT+2])
```

**param.h** 안의 **FSSIZE** 값도 20000이상인 **30000**으로 수정해줍니다.

---
## fs.c 수정 사항
먼저 **bmap** 함수를 수정했습니다.
기존의 bmap 함수를 최대한 참고하여 , double indirect block pointer의 역할을 수행할 수 있게 수행했습니다.

그 후에는 **itrunc** 함수를 수정했습니다.
기존의 iturnc 함수를 참조하고, double indirect이기 때문에 두번의 for문이 필요한 구조입니다.

---
### file_test 결과
**file_test**는 T1,T2,T3로 구성되어 있습니다.
T1은 파일에 8MB정도의 크기를 쓰고, T2는 8MB의 크기를 읽고 T3는 T1과 T2를 10회 정도 반복해서 전체적인 구조에서 문제가 생기지 않는지를 체크합니다.

위의 그림과 같이 큰 문제 없이 T1과 T2,T3를 통과합니다. 여러번의 file_test를 시도해도
테스트는 성공적으로 종료됩니다.
---
### 추가 구현점과 문제점
눈에 보이는 큰 문제점은 없습니다. 추가 구현점이라면 ,
Project 3(LWP)에서 만들었던 Thread의 개념을 응용해 **multi-thread** 환경에서 파일을
읽고 쓰는 기능을 만들수 있을것 같습니다.
<file_sep>#include "types.h"
#include "stat.h"
#include "user.h"
int main(int argc, char * argv[]){
int current_id=getpid();
int parent_id=getppid();
printf(1,"My pid is %d\n",current_id);
printf(1,"My ppid is %d\n",parent_id);
exit();
}
<file_sep>운영체제 과제 1 ( Simple User-level Unix Shell)
--
### 테스트 환경 :
##### OS : Ubuntu 16.04
##### gcc : gcc 5.4.0
### 개요 :
운영체제 첫번째 과제인 Simple User-level Unix shell에 대한 내용입니다.
크게 **interactvie mode**와 **batch mode**로 나뉘어지고
사용자가 입력한 명령 혹은 batch file을 읽어와서
명령을 수행하고 그 결과를 출력하는 프로그램입니다.
### 작동과정 설명 :
## Interactvie Mode
첫번째로 **interactvie mode**내에서의 작동 과정과 예시입니다.
크게 사용자로부터 **입력을 받아오고**,
입력을 **특정한 기준을 가지고 분할**하여
**execvp 함수를 사용**하여 처리합니다.
1. fgets() 함수를 통해 사용자에게 입력을 받습니다.
2. strtok 함수를 사용하여 semi-colon과 space를 기준으로 raw한 입력을 유의미하게 분할합니다.
3. 분할된 명령어들은 char* 이차원 배열에 저장됩니다.
3. 명령의 개수만큼 fork 함수를 통해 자식프로세스를 생성합니다.
4. 자식프로세스안에서 execvp 함수를 통해 저장된 명령어를 처리합니다.
5. 부모 프로세스에서는 모든 자식프로세스가 끝나기를 기다린후, 모두 종료되면 다시 1번으로 돌아가도록 유도합니다.
만약 이 과정에서 에러가 검출된다면 유저에게 알려줍니다.
---
### 작동예시 :
실행된 후 먼저 사용자가 명령을 입력할때까지 프로그램은 대기합니다.
그 후 사용자가 명령을 입력하면 (ex.ls -al)
``` > ls -al ```

위와 같이 명령을 처리합니다.
복수의 명령어( **semi-colon**으로 구분된)도 **병렬적으로** 처리가 가능합니다. (출력 순서는 섞일수 있습니다.)
``` > ls -al;pwd;ifconfig ```

quit command 입력시 쉘을 종료합니다.
``` > quit ```

### 에러 처리:
**존재하지 않는 명령어**를 입력시 유저에게 알려줍니다.
``` > thisisnotvalid ```

**아무 입력을 하지 않고 엔터를 입력할 경우** 다시 입력하도록 유도합니다.

**아무 입력을 하지 않은 상태에서 ctrl-D를 입력할 경우** shell은 종료됩니다.

### 실행 전제 :
1. **입력의 길이는 최대 1000자**입니다.
2. **입력받는 명령어는 최대 50개**입니다.
3. **명령어당 옵션의 개수(space로 구분하는 ex) -a -l -v -> 3개)는 최대 10개**입니다.
---
### 작동과정 설명 :
## Batch mode
두번째로 **batch mode**에 대한 설명과 예시입니다.
유저가 main 함수의 인자로 넘긴 batch_file을 읽어오고
명령어를 분할하고 처리하는 과정은 **interactvie mode**와 동일합니다.
1. fgets() 함수를 통해 사용자가 실행될때 첨부한 batch_file을 한줄단위로 읽어옵니다.
2. 마지막줄을 읽었다면 중지합니다.
2. 만약 명령어가 없고 개행문자만 있는 빈 줄(\n)을 읽었다면 다음 라인을 읽기 위해 1번으로 돌아갑니다.
2. strtok 함수를 사용하여 semi-colon과 space를 기준으로 raw한 입력을 유의미하게 분할합니다.
3. 분할된 명령어들은 char* 이차원 배열에 저장됩니다.
3. 명령의 개수만큼 fork 함수를 통해 자식프로세스를 생성합니다.
4. 자식프로세스안에서 execvp 함수를 통해 저장된 명령어를 처리합니다.
5. 부모 프로세스에서는 모든 자식프로세스가 끝나기를 기다린후, 모두 종료되면 다음 라인을 읽기 위해 1번으로 돌아갑니다.
만약 이 과정에서 에러가 검출된다면 유저에게 알려줍니다.
---
### 작동예시:
```./shell [batch_file]``` 형식으로 **batch mode**를 사용합니다.
``` vim test.txt```


### 에러 처리:
**존재하지 않는 명령어**를 입력시 유저에게 알려줍니다.
``` > vim test.txt ```


**사용자가 두개의 batch file을 인자로 넣을시** 유저에게 경고를 보여주고 shell을 종료합니다.

### 실행 전제 :
1. **입력의 길이는 최대 1000자**입니다.
2. **입력받는 명령어는 최대 50개**입니다.
3. **명령어당 옵션의 개수(space로 구분하는 ex) -a -l -v -> 3개)는 최대 10개**입니다.
---
### 기타 에러 처리 사항:
1. fork가 실패했을시 메모리에 심각한 문제가 있다고 판단하여 shell 을 종료합니다.
2. batch file을 fopen을 사용했을대 NULL이 반환될시 비정상적 작동을 막기 위해 shell을 종료합니다.
2. batch file을 두개 이상 사용시 (ex. ./shell batch_file batch_file 유저에게 경고를 보여준후 shell을 종료합니다.
3. 명령어를 분할하는 단계에서 \n 개행문자를 삭제합니다. 개행문자가 삭제되지 않고 execvp의 인자로 입력될시 illegal option 에러를 표출하기 때문입니다.
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#define BUF_SIZE 1000
#define LIMIT_NUM_CMD 50
#define LIMIT_NUM_CMD_OPTION 10
#define ERR_CODE -1
#define CMD_TOKEN ";"
#define CMD_OPTION_TOKEN " "
int main(int argc, char *argv[])
{
if (argc == 1)
{
while (1)
{
int num_of_cmd = 0;
int k = 0;
char *all_cmd_sets[LIMIT_NUM_CMD][LIMIT_NUM_CMD_OPTION] = {};
printf("> ");
char raw_input[BUF_SIZE];
// ctrl-D check
if (fgets(raw_input, BUF_SIZE, stdin) == NULL)
_exit(0);
// if user type no command and press enter
if (!strcmp(raw_input, "\n")) continue;
printf("Your current command is %s", raw_input);
printf("Working...\n");
// replace new line into null
char *newline_pointer = strchr(raw_input, '\n');
if (newline_pointer != NULL) *newline_pointer = '\0';
char *temp_for_tokenized_cmd;
temp_for_tokenized_cmd = strtok(raw_input, CMD_TOKEN);
//ok
char *cmd_sets[LIMIT_NUM_CMD] = {};
int i = 0;
while (temp_for_tokenized_cmd != NULL)
{
cmd_sets[i] = temp_for_tokenized_cmd;
temp_for_tokenized_cmd = strtok(NULL, CMD_TOKEN);
i++;
// if (temp_for_tokenized_cmd != NULL)num_of_cmd++;
}
char *temp_for_separated_cmd;
for (k = 0; k < LIMIT_NUM_CMD && cmd_sets[k] != NULL; k++)
{
int ii = 0;
char *cmd_with_options[LIMIT_NUM_CMD_OPTION] = {};
temp_for_separated_cmd = strtok(cmd_sets[k], CMD_OPTION_TOKEN);
while (temp_for_separated_cmd != NULL)
{
cmd_with_options[ii++] = temp_for_separated_cmd;
temp_for_separated_cmd = strtok(NULL, CMD_OPTION_TOKEN);
}
if (cmd_with_options[0] != NULL && !strcmp(cmd_with_options[0], "quit"))
{
_exit(0);
}
// limit num of cmd options to 8,
// 0 for cmd ,1~8 for options,9 for null
for (int j = 0;
j < LIMIT_NUM_CMD_OPTION - 1
&& cmd_with_options[j] != NULL; j++)
{
all_cmd_sets[k][j] = cmd_with_options[j];
}
}
//execvp section
pid_t child_pid, wait_pid;
int status_child = 0;
for (int id = 0; id < k; id++)
{
child_pid = fork();
if (child_pid == 0)
{
//child section
int execvp_return = execvp(all_cmd_sets[id][0], all_cmd_sets[id]);
if (execvp_return == ERR_CODE)
{
switch (errno)
{
case ECHILD :
perror("Unknown Command\n");
break;
case ENOENT :
perror("Unknown Command please try valid command\n");
break;
default :
printf("errno:%d\n", errno);
break;
}
_exit(errno);
}
}
else if (child_pid < 0)
{
fprintf(stderr, "Fork failed");
exit(-1);
}
}
int wait_cnt = 0;
while ((wait_pid = wait(&status_child)) > 0
&& ++wait_cnt < k);
switch (status_child)
{
case ECHILD :
printf("Unknown Command\n");
break;
case ENOENT :
printf("Unknown Command\n");
break;
default :
// printf("errno:%d\n", errno);
break;
}
}
}
else if (argc == 2)
{
// batch mode
FILE *batch_file = fopen(argv[1], "r");
if (batch_file == NULL)
{
exit(0);
}
else
{
int num_of_cmd = 0;
while (!feof(batch_file))
{
char batch_line[BUF_SIZE] = {};
if (fgets(batch_line, BUF_SIZE, batch_file) == NULL)
{
exit(0);
}
if (!strcmp(batch_line, "\n")) continue;
printf("Your current command is %s", batch_line);
printf("Working...\n");
// replace \n into null char
char *newline_pointer = strchr(batch_line, '\n');
if (newline_pointer != NULL) *newline_pointer = '\0';
int num_of_cmd_in_oneline = 0;
// semicolon tokenize
char *temp_for_tokenized_cmd;
temp_for_tokenized_cmd = strtok(batch_line, CMD_TOKEN);
char *cmd_sets[LIMIT_NUM_CMD] = {};
while (temp_for_tokenized_cmd != NULL)
{
cmd_sets[num_of_cmd_in_oneline++] = temp_for_tokenized_cmd;
temp_for_tokenized_cmd = strtok(NULL, CMD_TOKEN);
}
char *temp_for_separated_cmd;
char *cmd_with_options[LIMIT_NUM_CMD][LIMIT_NUM_CMD_OPTION] = {};
for (int p = 0; p < num_of_cmd_in_oneline; p++)
{
temp_for_separated_cmd = strtok(cmd_sets[p], CMD_OPTION_TOKEN);
for (int temp_target = 0;
temp_target < LIMIT_NUM_CMD_OPTION - 1
&& temp_for_separated_cmd != NULL; temp_target++)
{
cmd_with_options[p][temp_target] = temp_for_separated_cmd;
temp_for_separated_cmd = strtok(NULL, CMD_OPTION_TOKEN);
}
}
pid_t child_pid, wait_pid;
int status_child = 0;
for (int fork_count = 0; fork_count < num_of_cmd_in_oneline; fork_count++)
{
if (!strcmp(cmd_with_options[fork_count][0], "quit"))
{
//quit command
printf("quit command encountered\n");
_exit(0);
}
child_pid = fork();
if (child_pid == 0)
{
// child section
int execvp_return = execvp(cmd_with_options[fork_count][0],
cmd_with_options[fork_count]);
if (execvp_return == ERR_CODE)
{
switch (errno)
{
case ECHILD :
perror("Unknown Command\n");
break;
case ENOENT :
perror("Unknown Command please try valid command\n");
break;
default :
printf("errno:%d\n", errno);
break;
}
_exit(errno);
}
}
else if (child_pid < 0)
{
fprintf(stderr, "Fork failed");
exit(-1);
}
}
int wait_cnt = 0; // count how many times wait function called
while ((wait_pid = wait(&status_child)) > 0
&& ++wait_cnt < num_of_cmd_in_oneline)
switch (errno)
{
case ECHILD :
printf("Unknown Command\n");
break;
case ENOENT :
printf("Unknown Command\n");
break;
default :
// printf("errno:%d\n", errno);
break;
}
}
fclose(batch_file);
}
}
else if (argc >= 3)
{
printf("only single batch file accepted\n");
return 0;
}
}
<file_sep>운영체제 과제 3(LWP)
---
---
### 테스트 환경 :
##### OS : Ubuntu 16.04
##### gcc : gcc 5.4.0
### 개요 :
운영체제 세번째 과제인 **Light-weight Process (Thread)**에 대한 내용입니다.
크게 **thread_create**, **thread_exit**, **thread_join**을 통해 구현됩니다.
---
## thread 구현을 위한 proc 구조체 변경사항
`int isThread,int numOfThread,int nextThreadId,thread_t tid,void * retval, struct proc*p creator`등을 추가했습니다.
그중에서 creator 멤버는 기존 ** proc 구조체**의 **parent**와 비슷한 역할을 수행합니다.
이번 설계에서 process와 **thread_create**를 통해 생성된 thread는 *parent-child* 관계가 아니고 **pid**도 다르기 때문에 **creator**라는 포인터를 가짐으로써 *최소한의 연결 관계*를 유지해줍니다. *( 이 방식은 밑에 다시 설명드립니다.)*
*(단 프로세스의 경우에는 creator와 parent가 같다고 생각합니다.)*
### 기본적인 Thread 기능 명세 :
먼저 **Thread**의 기본 명세는 다음과 같습니다.

1. LWP는 Process와는 다르게 주소 공간을 공유합니다.
2. LWP는 본인을 생성한 Process와 다른 **pid** 값을 가집니다.
3. LWP는 본인을 생성한 Process를 pointer로 **creator**에 저장함으로써 최소한의 연결관계를 유지합니다.
3. LWP가 **fork**를 만나면 정상적으로 수행해야 합니다. * 단, fork된 process는 LWP의 **creator**에는 접근이 불가합니다.*
4. LWP가 **exec**를 만나면 정상적으로 수행해야 합니다. *exec를 수행할때 , LWP의 creator의 다른 LWP들은 종료되어야 합니다.*
5. LWP가 **exit**를 만나면 다른 모든 LWP가 종료되어야 합니다.
6. LWP의 creator가 kill의 대상이 되면 craetor의 다른 모든 LWP역시 종료되어야 합니다.
### 선언하고 구현한 시스템콜

1. **thread_create** : thread를 생성합니다. 기존의 시스템콜인 fork와 유사합니다.
2. **thread_exit** : thread를 종료합니다. 기존 시스템콜인 exit와 유사합니다. 이때 결과물을 proc 인자로 받은 retval 안에 저장합니다.
3. **thread_join** : 특정 thread를 기다립니다. 기존 시스템콜인 wait과 유사합니다. 다른 점은 인자로 받은 double-pointer에 return 값을 저장합니다.
4. (**thread_exit_target**) : 명세에는 표시되지 않았지만, 특정 쓰레드를 종료시키기 위해서 직접 구현했습니다.
### Thread의 생성 : thread_create
첫번째로 **thread_create** 함수에 대해서 설명과 예시입니다.
먼저 함수의 인자에 대해서 간략히 설명합니다.
1. 첫번째 인자인 **thread_t * thread**는 thread 생성이 끝난 후 추적을 위해 Thread의 id를 저장하는 용도로 사용했습니다.
2. 두번째 인자인 **함수 포인터 start_routine**은 생성된 Thread가 해야하는 함수의 진입점으로 사용됩니다.
3. 세번째 인자인 **void * arg**는 두번째 인자인 함수를 수행하는데 사용되는 것으로 ustack에 저장됩니다.
전체적인 동작사항은 **fork** 시스콜과 다르지 않지만

위의 부분에서 ```allocproc```를 통해 반환받은 proc 구조체를
thread 처럼 동작하게끔 하기 위해 **isThread** 값을 1로 설정해주고 , **tid**값을 현재 proc의 **nextThreadId**값을 가져와서 설정해줍니다. * ( 단 이 tid는 연속적이나, 실행되고 있는 Thread들의 tid는 연속적임을 보장하지 않습니다. Ex) tid : 1 2 5 6*
**creator**를 현재 Process로 설정해줍니다. 이를 통해 thread와 Process간의 *Parent-Child* 관계는 아니지만 *(```np->parent=curproc->parent``` 이기 때문에)*
**어느 정도의 관계를 가지고 있게끔 구현했습니다.
또 시작지점을 설정하는 부분에서는 기존 시스템콜인 **exec**을 참고하였습니다.

**ustack**을 만들어주고 **copyout**을 통해서 복사해줍니다.
``` np->tf->eip=(uint)start_routine ```
또 **eip**값을 인자로 들어온 start_routine으로 설정해주어서 thread 가 수행할
함수의 진입점을 올바르게 설정해줍니다.
또 LWP끼리는 주소공간을 공유해야 하기 때문에
```
acquire(&ptable.lock);
struct proc* p;
~~~
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->parent->pid==np->parent->pid){
p->sz=np->sz;
}
}
~~~
release(&ptable.lock);
```
위와 같은 코드를 통해서 sz값을 공유시켜줍니다. 이를 통해 **Memory Illegal Access** 문제를 방지 할 수 있습니다.
**fork** 시스템콜에서는 생성된 Process의 **pid**값을 반환했지만, thread_create에서는 인자로 전달받은
**thread_t * thread**에 thread의 **tid**를 저장해줍니다.
### Thread의 종료 : thread_exit
두번째로 **thread_exit** 함수에 대해서 설명과 예시입니다.
반환형은 void이고 함수의 인자에 대해서 설명합니다.
1. 첫번째 인자인 **void * retval** 입니다. thread가 종료될때 이 인자에 결과값을 저장합니다.
전체적인 동작은 ** exit ** 시스템콜과 크게 다르지 않습니다.

한가지 다른점은
```
curproc->creator->numOfThread--;
```
을 통해 자신이 속해있는 Process의 쓰레드 개수를 줄이는 기록을 합니다.
### Thread가 끝나기를 기다림 : thread_join
세번째로 **thread_join** 함수의 설명입니다.
반환형은 int로, join이 성공적이면 0을 .그렇지 않으면 다른 값을 반환합니다.
함수의 인자는 두개 입니다.
1. 첫번째 인자인 **thread_t thread**입니다. join의 대상 thread를 지칭하는데 사용됩니다.
2. 두번째 인자는 ** void ** retval **입니다. thread_exit을 통해서 반환된 값을 저장해줍니다.
**thread_join**도 기존의 **wait**시스템콜과 유사합니다.

다른 점이 몇가지 있는데
1. ```freevm(p->pgdir)```을 사용하지 않습니다. 주소공간을 공유하기 때문에 이 함수를 join에서는 사용하지 않습니다.
2. ```*retval=p->retval```이라는 새로운 코드를 추가합니다. 인자로 전달받은 **double-pointer retval**에 저장합니다. 이를 통해 완료된 값들을 받아갈 수 있습니다.
또 한가지 중요한점은
```sleep (curproc,&ptable.lock);```
을 사용한다는 점입니다(기존의 **wait**에도 존재합니다.) 이를 통해서 모든 자식들이 끝나기를 기다립니다.
### xv6와의 상호작용
* 일부기능을 제외하고는 프로세스와 같이 움직여야 하며 , 내장 스케쥴러인 RR을 사용합니다 *
1. **Fork** 의 경우에는 LWP의 대부분의 기능이 Process와 비슷하게 동작하기 때문에 큰 수정 없이 정상작동합니다.
2. **Exec**의 경우에도 큰 수정 없이 정상작동합니다. *단 , thread가 exec를 만났을때,자신을 제외한 같은 프로세스에 속해 있는 다른 thread을 종료해야 하도록 구현했습니다.*
3. **sbrk**의 경우에는 **growproc** 시스템콜의 수정이 필요합니다. 스레드의 주소공간이 늘어났다면, 같은 프로세스 군에 속해있는 모든 thread가 이 변경된 **sz**의 값을 알아야합니다. 그렇기에 아래처럼

같은 군에 속해있거나 특정 프로세스(프로세스 군의 main)의 sz를 변경해줍니다. 그렇지 않으면 **page fault**가 나는것을 확인했습니다. 또
growproc에서 sz을 접근할때, 다른 스레드가 sz를 수정중일 수 있으니 growproc 전체적으로 ptable lock을 잡아야합니다.
5. **kill**의 경우에는 **thread_kill **test 에서 다시 언급하겠지만, Process가 kill을 당하면 그 프로세스에 속해있는 모든 프로세스를 종료해줍니다. 기존의 **kill** 시스템콜에서 조금의 추가가 있습니다.
6. **Exit**의 경우에 thread가 exit을 만나면 같은 프로세스에 속해있는 다른 thread와 자기 자신을 종료하도록 구현했습니다.
### xv6와의 상호작용 - 기존 시스템콜 변경점
## kill

**kill** 시스템에 다른부분은 기존과 동일하지만 사진과 같이
ptable을 돌면서 같은 process 집합에 속해있는 Thread들을 killed=1로 바꿉니다.
이것은 **kill**의 시스템콜의 기능과 유사합니다. 이것을 통해서 프로세스가 kill 되었을때 속해있는 다른 쓰레드들도 kill을 당하게 합니다.
## exit

exit도 ptable을 돌면서 자신과 같은 프로세스군에 있지만 자신을 제외한 스레드를 종료하고 같은 집합에 속해있는 Process도 삭제하는
killAllFromThread을 호출하여 exit을 수행합니다.
위의 상황은 thread가 exit을 만낫을때고 Process가 exit을 만낫을때도 자신이 생성한 thread를 모두 죽이는 역할을 수행하는것이
killAllFromThread입니다.
## growproc
상기 언급한것과 같이 sz사이즈를 전체적으로 조절합니다.
*단 좀더 광범위하게 ptable에 대한 lock을 요청하여 다른 쓰레드가 sz를 수정하는것을 방지합니다.*
## Test 결과
테스트 결과입니다.
* **단 앞단에 기재한것과 같이 test 구동에 문제가 있기에 테스트 하나를 끝내고
xv6를 다시 실행해야 합니다.** *
### thread_test 1:create,exit,join
*생성하는 thread의 개수를 3개로 늘려서 진행해보았습니다.*

정상적으로 thread를 3개 생성하고, 3개 exit 한후 join해서 정상적으로 테스트를 수행합니다.
### thread_test 2:fork

thread 내에서 fork를 진행한후 정상적으로 끝내는 모습을 확인할 수 있습니다.
### thread_test 3:sbrk

thread 내에서 malloc을 사용해 **growproc**을 호출하고 , free(dealloc)을 사용해 다시 **growproc**을 정상적으로 호출하는 것을 볼 수 있습니다. **growproc**을 수정하지 않으면 remap 패닉이 발생합니다.
thread_test 내 3가지 세부 테스트 모두 성공한 것을 확인 할 수 있습니다.
-- --
### thread_exec

thread가 exec을 만났을때, 자신을 제외한 thread를 모두 종료시키고
정상적으로 Hello, thread를 출력하는것을 확인 할 수 있습니다.
### thread_exit

thread가 exit을 만났을때, 그 프로세스 내의 모든 thraed를 종료시키는 테스트입니다.
정상작동합니다.
### thread_kill

thread가 속한 프로세스가 kill 되었을때, 그 프로세스에 속한 thread를 모두 종료시키는 테스트입니다.
정상작동합니다. zombie 프로세스 역시 생기지 않습니다.
### 트러블슈팅
thread의 기본적인 생성과 종료,그리고 join을 구현하는데 있어서 막막한 감이 있었습니다.
기존 xv6의 ** fork,exec,allocproc,wait,exit**의 코드등을 참고해서 새로운 시스템 콜들을 만들었고
기존의 시스템콜 역시 thread의 상황에 맞게 적절히 수정했습니다.
예를들어 thread_create 부분에서 단순히 **fork 시스템콜**의
```
switchuvm(np)
```
라는 부분이 있었는데, 이것을** thread_create **단으로 가져오니 알 수 없는 이유의
패닉이 자꾸 발생하였고,
switchuvm의 주요 목표가 * **cr3 레지스터의** 값을 변경하는것* 이라는걸 알기 위해서
수업시간에 진행했던 lab pdf를 참조 후 그 부분을
다음과 같이 수정했습니다.
```
// switchuvm-like
pushcli();
lcr3(V2P(np->pgdir));
popcli();
```
이렇게 수정하고 나니 패닉도 발생하지 않았고, 원하는 대로 함수가 구현되었습니다.
### 미구현점 혹은 남은 문제사항
## 하단에 표시된 문제사항 최신 커밋 기준으로 해결되었습니다.
<file_sep>#include "types.h"
#include "defs.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "x86.h"
#include "proc.h"
#include "spinlock.h"
struct {
struct spinlock lock;
struct proc proc[NPROC];
} ptable;
struct spinlock pgdirlock;
#define NULL 0
static struct proc *initproc;
int nextpid = 1;
extern void forkret(void);
extern void trapret(void);
static void wakeup1(void *chan);
void
pinit(void)
{
initlock(&ptable.lock, "ptable");
}
// Must be called with interrupts disabled
int
cpuid() {
return mycpu()-cpus;
}
// Must be called with interrupts disabled to avoid the caller being
// rescheduled between reading lapicid and running through the loop.
struct cpu*
mycpu(void)
{
int apicid, i;
if(readeflags()&FL_IF)
panic("mycpu called with interrupts enabled\n");
apicid = lapicid();
// APIC IDs are not guaranteed to be contiguous. Maybe we should have
// a reverse map, or reserve a register to store &cpus[i].
for (i = 0; i < ncpu; ++i) {
if (cpus[i].apicid == apicid)
return &cpus[i];
}
panic("unknown apicid\n");
}
// Disable interrupts so that we are not rescheduled
// while reading proc from the cpu structure
struct proc*
myproc(void) {
struct cpu *c;
struct proc *p;
pushcli();
c = mycpu();
p = c->proc;
popcli();
return p;
}
//PAGEBREAK: 32
// Look in the process table for an UNUSED proc.
// If found, change state to EMBRYO and initialize
// state required to run in the kernel.
// Otherwise return 0.
static struct proc*
allocproc(void)
{
struct proc *p;
char *sp;
//cprintf("81\n");
acquire2(&ptable.lock,81);
for(p = ptable.proc; p < &ptable.proc[NPROC]; p++)
if(p->state == UNUSED)
goto found;
release(&ptable.lock);
return 0;
found:
p->state = EMBRYO;
p->ctime=ticks;
p->pid = nextpid++;
//LWP options
p->isThread=0;
p->numOfThread=0;
p->nextThreadId=0;
p->tid=-1;
#ifdef MLFQ_SCHED
p->lev=0;
p->priority=0;
p->monopolize=0;
#endif
release(&ptable.lock);
// Allocate kernel stack.
if((p->kstack = kalloc()) == 0){
p->state = UNUSED;
return 0;
}
sp = p->kstack + KSTACKSIZE;
// Leave room for trap frame.
sp -= sizeof *p->tf;
p->tf = (struct trapframe*)sp;
// Set up new context to start executing at forkret,
// which returns to trapret.
sp -= 4;
*(uint*)sp = (uint)trapret;
sp -= sizeof *p->context;
p->context = (struct context*)sp;
memset(p->context, 0, sizeof *p->context);
p->context->eip = (uint)forkret;
return p;
}
//PAGEBREAK: 32
// Set up first user process.
void
userinit(void)
{
struct proc *p;
extern char _binary_initcode_start[], _binary_initcode_size[];
p = allocproc();
initproc = p;
if((p->pgdir = setupkvm()) == 0)
panic("userinit: out of memory?");
inituvm(p->pgdir, _binary_initcode_start, (int)_binary_initcode_size);
p->sz = PGSIZE;
p->ctime=ticks;
memset(p->tf, 0, sizeof(*p->tf));
p->tf->cs = (SEG_UCODE << 3) | DPL_USER;
p->tf->ds = (SEG_UDATA << 3) | DPL_USER;
p->tf->es = p->tf->ds;
p->tf->ss = p->tf->ds;
p->tf->eflags = FL_IF;
p->tf->esp = PGSIZE;
p->tf->eip = 0; // beginning of initcode.S
safestrcpy(p->name, "initcode", sizeof(p->name));
p->cwd = namei("/");
// this assignment to p->state lets other cores
// run this process. the acquire forces the above
// writes to be visible, and the lock is also needed
// because the assignment might not be atomic.
//cprintf("165\n");
acquire2(&ptable.lock,166);
p->state = RUNNABLE;
release(&ptable.lock);
}
// Grow current process's memory by n bytes.
// Return 0 on success, -1 on failure.
int
growproc(int n)
{
uint sz;
struct proc *curproc = myproc();
acquire(&ptable.lock);
sz = curproc->sz;
if(n > 0){
if((sz = allocuvm(curproc->pgdir, sz, sz + n)) == 0)
return -1;
} else if(n < 0){
if((sz = deallocuvm(curproc->pgdir, sz, sz + n)) == 0)
return -1;
}
curproc->sz = sz;
/* sz propagation */
struct proc* p;
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->creator==curproc->creator || p==curproc->creator){
p->sz=curproc->sz;
}
}
release(&ptable.lock);
/* end of sz propagation */
switchuvm(curproc);
return 0;
}
// Create a new process copying p as the parent.
// Sets up stack to return as if from system call.
// Caller must set state of returned proc to RUNNABLE.
int
fork(void)
{
int i, pid;
struct proc *np;
struct proc *curproc = myproc();
// Allocate process.
if((np = allocproc()) == 0){
return -1;
}
// Copy process state from proc.
if((np->pgdir = copyuvm(curproc->pgdir, curproc->sz)) == 0){
kfree(np->kstack);
np->kstack = 0;
np->state = UNUSED;
return -1;
}
np->sz = curproc->sz;
np->parent = curproc;
*np->tf = *curproc->tf;
np->creator=np;
// Clear %eax so that fork returns 0 in the child.
np->tf->eax = 0;
for(i = 0; i < NOFILE; i++)
if(curproc->ofile[i])
np->ofile[i] = filedup(curproc->ofile[i]);
np->cwd = idup(curproc->cwd);
safestrcpy(np->name, curproc->name, sizeof(curproc->name));
pid = np->pid;
//cprintf("232\n");
acquire2(&ptable.lock,233);
np->state = RUNNABLE;
release(&ptable.lock);
return pid;
}
// Exit the current process. Does not return.
// An exited process remains in the zombie state
// until its parent calls wait() to find out it exited.
void
exit(void)
{
struct proc *curproc = myproc();
struct proc *p;
int fd;
if(curproc == initproc)
panic("init exiting");
// Close all open files.
for(fd = 0; fd < NOFILE; fd++){
if(curproc->ofile[fd]){
fileclose(curproc->ofile[fd]);
curproc->ofile[fd] = 0;
}
}
acquire(&ptable.lock);
/* if curproc has any thread
if(curproc->isThread==1&&
curproc->creator->numOfThread!=0){
struct proc* p;
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->creator->pid==curproc->creator->pid&&
p->isThread==1&&p->pid!=curproc->pid){
p->killed=1;
if(p->state==SLEEPING){
p->state=RUNNABLE;
}
}
}
}*/
release(&ptable.lock);
// if(curproc->isThread==1){
killAllFromThread(curproc);
//thread_exit_target(curproc->creator);
// }
begin_op();
iput(curproc->cwd);
end_op();
curproc->cwd = 0;
//cprintf("268\n");
acquire(&ptable.lock);
// Parent might be sleeping in wait().
wakeup1(curproc->parent);
// Pass abandoned children to init.
for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
if(p->parent == curproc){
p->parent = initproc;
if(p->state == ZOMBIE)
wakeup1(initproc);
}
}
// Jump into the scheduler, never to return.
curproc->state = ZOMBIE;
sched();
panic("zombie exit");
}
// Wait for a child process to exit and return its pid.
// Return -1 if this process has no children.
int
wait(void)
{
struct proc *p;
int havekids, pid;
struct proc *curproc = myproc();
//cprintf("298\n");
acquire2(&ptable.lock,299);
for(;;){
// Scan through table looking for exited children.
havekids = 0;
for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
if(p->parent != curproc)
continue;
havekids = 1;
if(p->state == ZOMBIE){
// Found one.
pid = p->pid;
kfree(p->kstack);
p->kstack = 0;
freevm(p->pgdir);
p->pid = 0;
p->parent = 0;
p->name[0] = 0;
p->killed = 0;
p->state = UNUSED;
release(&ptable.lock);
return pid;
}
}
// No point waiting if we don't have any children.
if(!havekids || curproc->killed){
release(&ptable.lock);
return -1;
}
// Wait for children to exit. (See wakeup1 call in proc_exit.)
sleep(curproc, &ptable.lock); //DOC: wait-sleep
}
}
//PAGEBREAK: 42
// Per-CPU process scheduler.
// Each CPU calls scheduler() after setting itself up.
// Scheduler never returns. It loops, doing:
// - choose a process to run
// - swtch to start running that process
// - eventually that process transfers control
// via swtch back to the scheduler.
void
scheduler(void)
{
struct cpu *c = mycpu();
c->proc = 0;
for(;;){
// Enable interrupts on this processor.
sti();
// Loop over process table looking for process to run.
//cprintf("353\n");
acquire(&ptable.lock);
#ifdef FCFS_SCHED
struct proc *p;
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->state!=RUNNABLE) {
continue;
}
else{ //CPU를 받을 상태가 되었을때
p->stime=ticks;
c->proc=p; // 작업 변경
switchuvm(p);
p->state=RUNNING;
swtch(&(c->scheduler),p->context);
switchkvm();
c->proc=0;
break;
}
}
#elif DEFAULT
struct proc *p;
for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
if(p->state != RUNNABLE) // RUNNABLE==ready 상태인것,자원할당 가능한것 찾는것임
continue;
// Switch to chosen process. It is the process's job
// to release ptable.lock and then reacquire it
// before jumping back to us.
c->proc = p; // 현재 CPU 가져옴 그후 교체함
switchuvm(p);
p->state = RUNNING;
swtch(&(c->scheduler), p->context);
switchkvm();
// Process is done running for now.
// It should have changed its p->state before coming back.
c->proc = 0;
}
#elif MLFQ_SCHED
struct proc* priorityP=NULL;
struct proc* p;
int L0count=0;
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->lev==0&&p->state==RUNNABLE){
L0count=L0count+1;
break;
}
}
if(L0count>0){ // L0에서 탐색 후 RR수행
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->state!=RUNNABLE)
continue;
if(p->lev==0){
c->proc=p; // 작업 변경
switchuvm(p);
p->state=RUNNING;
p->stime=ticks;
p->rtime=0;
swtch(&(c->scheduler),p->context);
switchkvm();
c->proc=0;
}
}
}
else{ // L0이 비어있으니 , L1에서 priority 낮은 거 탐색
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->state!=RUNNABLE)
continue;
if(p->lev==1){
if(priorityP!=NULL){
if(priorityP->priority<p->priority)
priorityP=p;
else if(priorityP->priority==p->priority){
if(priorityP>p)
priorityP=p;
}
}
else
priorityP=p;
}
}
if(priorityP!=NULL){
p=priorityP;
c->proc=p;
switchuvm(p);
p->state=RUNNING;
p->stime=ticks;
p->rtime=0;
swtch(&(c->scheduler),p->context);
switchkvm();
c->proc=0;
}
}
#else
#endif
release(&ptable.lock);
}
}
// Enter scheduler. Must hold only ptable.lock
// and have changed proc->state. Saves and restores
// intena because intena is a property of this
// kernel thread, not this CPU. It should
// be proc->intena and proc->ncli, but that would
// break in the few places where a lock is held but
// there's no process.
void
sched(void)
{
int intena;
struct proc *p = myproc();
if(!holding(&ptable.lock))
panic("sched ptable.lock");
if(mycpu()->ncli != 1)
panic("sched locks");
if(p->state == RUNNING)
panic("sched running");
if(readeflags()&FL_IF)
panic("sched interruptible");
intena = mycpu()->intena;
swtch(&p->context, mycpu()->scheduler);
mycpu()->intena = intena;
}
// Give up the CPU for one scheduling round.
void
yield(void)
{
//cprintf("504\n");
acquire2(&ptable.lock,505); //DOC: yieldlock
myproc()->state = RUNNABLE; // todo ptable rb값을 조절
sched();
release(&ptable.lock);
}
// A fork child's very first scheduling by scheduler()
// will swtch here. "Return" to user space.
void
forkret(void)
{
static int first = 1;
// Still holding ptable.lock from scheduler.
release(&ptable.lock);
if (first) {
// Some initialization functions must be run in the context
// of a regular process (e.g., they call sleep), and thus cannot
// be run from main().
first = 0;
iinit(ROOTDEV);
initlog(ROOTDEV);
}
// Return to "caller", actually trapret (see allocproc).
}
// Atomically release lock and sleep on chan.
// Reacquires lock when awakened.
void
sleep(void *chan, struct spinlock *lk)
{
struct proc *p = myproc();
if(p == 0)
panic("sleep");
if(lk == 0)
panic("sleep without lk");
// Must acquire ptable.lock in order to
// change p->state and then call sched.
// Once we hold ptable.lock, we can be
// guaranteed that we won't miss any wakeup
// (wakeup runs with ptable.lock locked),
// so it's okay to release lk.
if(lk != &ptable.lock){ //DOC: sleeplock0
//cprintf("553\n");
acquire2(&ptable.lock,553); //DOC: sleeplock1
release(lk);
}
// Go to sleep.
p->chan = chan;
p->state = SLEEPING;
sched();
// Tidy up.
p->chan = 0;
// Reacquire original lock.
if(lk != &ptable.lock){ //DOC: sleeplock2
release(&ptable.lock);
acquire2(lk,569);
}
}
//PAGEBREAK!
// Wake up all processes sleeping on chan.
// The ptable lock must be held.
static void
wakeup1(void *chan)
{
struct proc *p;
for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
if(p->state == SLEEPING && p->chan == chan)
p->state = RUNNABLE;
}
}
// Wake up all processes sleeping on chan.
void
wakeup(void *chan)
{
acquire2(&ptable.lock,592);
wakeup1(chan);
release(&ptable.lock);
}
// Kill the process with the given pid.
// Process won't exit until it returns
// to user space (see trap in trap.c).
int
kill(int pid)
{
struct proc *p;
acquire2(&ptable.lock,606);
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->creator->pid==pid){
p->killed=1;
if(p->state==SLEEPING)
p->state=RUNNABLE;
}
}
for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
if(p->pid == pid){
p->killed = 1;
// Wake process from sleep if necessary.
if(p->state == SLEEPING)
p->state = RUNNABLE;
release(&ptable.lock);
return 0;
}
}
release(&ptable.lock);
return -1;
}
//PAGEBREAK: 36
// Print a process listing to console. For debugging.
// Runs when user types ^P on console.
// No lock to avoid wedging a stuck machine further.
void
procdump(void)
{
static char *states[] = {
[UNUSED] "unused",
[EMBRYO] "embryo",
[SLEEPING] "sleep ",
[RUNNABLE] "runble",
[RUNNING] "run ",
[ZOMBIE] "zombie"
};
int i;
struct proc *p;
char *state;
uint pc[10];
for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
if(p->state == UNUSED)
continue;
if(p->state >= 0 && p->state < NELEM(states) && states[p->state])
state = states[p->state];
else
state = "???";
cprintf("%d %s %s", p->pid, state, p->name);
if(p->state == SLEEPING){
getcallerpcs((uint*)p->context->ebp+2, pc);
for(i=0; i<10 && pc[i] != 0; i++)
cprintf(" %p", pc[i]);
}
cprintf("\n");
}
}
// pid에 매칭되는 process return
int setprocpriority(int pid,int priority){
acquire(&ptable.lock);
struct proc* p;
struct proc* targetP=NULL;
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->pid==pid){
targetP=p;
break;
}
}
#ifdef MLFQ_SCHED
if(targetP==NULL){
release(&ptable.lock);
return 0;
}
targetP->priority=priority;
// cprinf("paramter is %d and targetP : %d",priority,targetP->priority);
release(&ptable.lock);
return 1;
#endif
release(&ptable.lock);
if(targetP==NULL)
return 0;
return 0;
}
#ifdef MLFQ_SCHED
int getlev(void){
if(myproc()->monopolize==1){
return 0;}
return myproc()->lev;
}
void priboosting(void){
acquire(&ptable.lock);
struct proc* p;
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->lev==1){
p->lev=0;
p->priority=0;
}
}
release(&ptable.lock);
}
void monopolize(int password){
acquire(&ptable.lock);
if(myproc()->monopolize==1){// 현재 독점중일때
if(password==<PASSWORD>){ // 독점중인데 비밀번호 맞을때
myproc()->monopolize=0; // 독점해제
myproc()->lev=0; // L0로 이동
myproc()->priority=0; // PRI 조절
}
else{ //독점중인데 비밀번호 틀릴때
cprintf("wrong password at calling monopolize\n");
myproc()->monopolize=0; // 독점해제
myproc()->killed=1;
if(myproc()->state==SLEEPING) // kill함
myproc()->state=RUNNABLE;
}
}
else if(myproc()->monopolize==0){// 독점중이 아닐때
if(password==<PASSWORD>){ // 독점중이 아닐때 비밀번호 맞을때
myproc()->monopolize=1; // 독점시작
}
else{ // 독점중이 아닐때 비밀번호 틀릴때
// kill the P
cprintf("wrong password at calling monopolize\n");
myproc()->killed=1;
if(myproc()->state==SLEEPING) // 비정상접근,kill P
myproc()->state=RUNNABLE;
}
}
release(&ptable.lock);
}
#endif
/*
static struct proc*
allocthread(void){
struct proc *p;
struct proc* curproc=myproc();
char *sp;
acquire2(&ptable.lock,748);
for(p=ptable.proc;p<&ptable.proc[NPROC];p++)
if(p->state == UNUSED)
goto found;
release(&ptable.lock);
return 0;
found:
p->state=EMBRYO;
p->ctime=ticks;
p->pid=curproc->pid;
p->isThread=1;
p->numOfThread=-1;
p->nextThreadId=-1;
p->tid=-1;
curproc->numOfThread++;
p->tid=curproc->nextThreadId++;
release(&ptable.lock);
if((p->kstack=kalloc())==0){
p->state=UNUSED;
return 0;
}
cprintf("p kstack :%d\n",p->kstack);
sp=p->kstack+KSTACKSIZE;
sp-= sizeof *p->tf;
p->tf=(struct trapframe*)sp;
sp-=4;
*(uint*)sp=(uint)trapret;
sp-=sizeof *p->context;
p->context=(struct context*)sp;
memset(p->context,0,sizeof *p->context);
p->context->eip=(uint)forkret;
return p;
}*/
int thread_create(thread_t* thread,void*(*start_routine)(void*),void * arg){
uint sp,ustack[4];
//pde_t* pgdir;
struct proc* np;
struct proc* curproc=myproc();
//pgdir=curproc->pgdir;
// cprintf("before allocation\n");
if((np=allocproc())==0){
return -1;
}
//cprintf("allocation success\n");
np->pgdir=curproc->pgdir;
//cprintf("p.sz : %d\n",curproc->sz);
acquire(&ptable.lock);
if((curproc->sz=allocuvm(np->pgdir,curproc->sz,curproc->sz+2*PGSIZE))==0){
return -1;
}
clearpteu(np->pgdir, (char*)(curproc->sz - 2*PGSIZE));
np->sz=curproc->sz;
sp=np->sz;
np->isThread=1;
np->parent=curproc->parent;
np->creator=curproc;
//nextpid--;
// np->pid=curproc->pid;
np->tid=curproc->nextThreadId++;
curproc->numOfThread++;
*np->tf=*curproc->tf;
*thread=np->tid;
ustack[3]=(uint)arg;
ustack[2]=0;
ustack[1]=(uint)ustack[3];
ustack[0]=0xffffffff;
sp-=16;
if(copyout(np->pgdir,sp,ustack,16)<0)
return -1;
// invoke fatal error.
//cprintf("sr: %d\n", start_routine);
np->tf->eax=0;
np->tf->eip=(uint)start_routine;
np->tf->esp=sp;
//np->tf->ebp=sp;
//np->tf->esp=np->tf->ebp;
//cprintf("curproc-> %d\n",curproc->tf->esp);
struct proc* p;
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->parent->pid==np->parent->pid){
p->sz=np->sz;
}
}
for(int i=0;i<NOFILE;i++)
if(curproc->ofile[i])
np->ofile[i]=filedup(curproc->ofile[i]);
np->cwd=idup(curproc->cwd);
safestrcpy(np->name,curproc->name,sizeof(curproc->name));
// switchuvm-like
pushcli();
lcr3(V2P(np->pgdir));
popcli();
np->state=RUNNABLE;
release(&ptable.lock);
//cprintf("before retrun\n");
return 0;
}
void thread_exit(void *retval){
struct proc * curproc=myproc();
struct proc *p;
int fd;
for(fd=0;fd<NOFILE;fd++){
if(curproc->ofile[fd]){
fileclose(curproc->ofile[fd]);
curproc->ofile[fd]=0;
}
}
begin_op();
iput(curproc->cwd);
end_op();
curproc->cwd=0;
acquire(&ptable.lock);
/*
// if this thread is last remaining thread
if(curproc->creator->numOfThread==1){
cprintf("current is %d is Thread : %d\n",curproc->pid,curproc->isThread);
cprintf("creator sz %d\n and ntid %d\n",curproc->creator->sz,curproc->creator->nextThreadId);
curproc->creator->sz=deallocuvm(curproc->creator->pgdir,
curproc->creator->sz,curproc->creator->sz-curproc->creator->nextThreadId*PGSIZE*2);
cprintf("creator after sz %d\n",curproc->creator->sz);
curproc->creator->nextThreadId=0;
}
*/
//wakeup1(curproc->parent);
curproc->creator->numOfThread--;
wakeup1(curproc->creator);
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->parent==curproc){
p->parent=initproc;
if(p->state==ZOMBIE)
wakeup1(initproc);
}
}
curproc->state=ZOMBIE;
curproc->retval=retval;
sched();
panic("zombie exit");
}
int thread_join(thread_t thread, void **retval){
struct proc *p;
//int /*havekids,*/ pid;
struct proc *curproc = myproc();
acquire(&ptable.lock);
for(;;){
// Scan through table looking for exited children.
//havekids = 0;
for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
if(p->tid!=thread)
continue;
// havekids = 1;
if(p->state == ZOMBIE){
// Found one.
//pid = p->pid;
kfree(p->kstack);
p->kstack = 0;
//if(p->creator->numOfThread==1)
// freevm(p->pgdir);
p->pid = 0;
p->parent = 0;
p->name[0] = 0;
p->killed = 0;
p->state = UNUSED;
*retval=p->retval;
release(&ptable.lock);
return 0;
}
// No point waiting if we don't have any children.
/* if(!havekids || curproc->killed){
release(&ptable.lock);
return -1;
}*/
// Wait for children to exit. (See wakeup1 call in proc_exit.)
}
sleep(curproc, &ptable.lock); //DOC: wait-sleep
}
return -1;
}
void killAllFromThread(struct proc * curproc){
acquire2(&ptable.lock,1050);
struct proc* p;
for(p=ptable.proc;p<&ptable.proc[NPROC];p++){
if(p->pid==curproc->pid)
continue;
if(p->creator==curproc->creator
||p==curproc->creator){
if(p->kstack!=0){
kfree(p->kstack);
}
p->kstack=0;
p->pid=0;
p->parent=0;
p->name[0]=0;
p->killed=0;
p->state=UNUSED;
p->creator=0;
p->sz=0;
}
}
release(&ptable.lock);
// sched();
}
void thread_exit_target(struct proc* target){
int fd;
for(fd=0;fd<NOFILE;fd++){
if(target->ofile[fd]){
fileclose(target->ofile[fd]);
target->ofile[fd]=0;
}
}
begin_op();
iput(target->cwd);
end_op();
acquire(&ptable.lock);
target->cwd=0;
target->creator->numOfThread--;
wakeup1(target->creator);
release(&ptable.lock);
target->state=ZOMBIE;
/* if(target->isThread!=1){
kfree(target->kstack);
target->kstack=0;
//freevm(target->pgdir);
target->sz=0;
target->state=UNUSED;
}*/
return ;
}
|
708f6cb7a94a0fedfa14ab45a74ad3cee6d35365
|
[
"Markdown",
"C"
] | 13 |
C
|
BecomeWeasel/Operating-System-xv6
|
c15f43b926666e9cceaae022e8eb27e1a53480bf
|
c2d3ef61f35a1042e4ebb4a2cf038f740d531d91
|
refs/heads/master
|
<repo_name>AthinaHilakou/DesignComp<file_sep>/tests/state_alt_test.c
//////////////////////////////////////////////////////////////////
//
// Test για το state_alt.h module
//
//////////////////////////////////////////////////////////////////
#include "acutest.h" // Απλή βιβλιοθήκη για unit testing
#include "ADTSet.h"
#include "ADTList.h"
#include "ADTMap.h"
#include "state.h"
struct state {
Set objects; // περιέχει στοιχεία Object (Εμπόδια / Εχθροί / Πύλες)
Map portal_pairs; // περιέχει PortalPair (ζευγάρια πυλών, είσοδος/έξοδος)
struct state_info info;
};
void test_state_alt() {
State state = state_create();
TEST_ASSERT(state != NULL);
StateInfo info = state_info(state);
TEST_ASSERT(info != NULL);
TEST_ASSERT(info->current_portal == 1);
TEST_ASSERT(info->wins == 0);
TEST_ASSERT(info->playing == true);
TEST_ASSERT(info->paused == false);
bool check[100];
for(int i = 1; i <= 100 ; i++)
check[i] = 0;
for(MapNode node = map_first(state->portal_pairs);
node != MAP_EOF;
node = map_next(state->portal_pairs, node)) {
int val = *(int*)map_node_value(state->portal_pairs, node);
TEST_ASSERT(check[val] == 0);
}
struct key_state keys = { false, false, false, false, false, false };
Rectangle old_rect = state_info(state)->character->rect;
state_update(state, &keys);
Rectangle new_rect = state_info(state)->character->rect;
TEST_ASSERT(new_rect.x == old_rect.x + 7 && new_rect.y == old_rect.y);
keys.up = true;
old_rect = state_info(state)->character->rect;
state_update(state, &keys);
new_rect = state_info(state)->character->rect;
TEST_ASSERT(new_rect.y == old_rect.y);
keys.up = false; // character goes up at next frame
state_update(state, &keys);
new_rect = state_info(state)->character->rect;
TEST_ASSERT(new_rect.y == old_rect.y - 15);
state_destroy(state);
}
// Λίστα με όλα test προς εκτέλεση
TEST_LIST = {
{ "test_state_alt", test_state_alt},
{ NULL, NULL } // τερματίζουμε τη λίστα με NULL
};<file_sep>/modules/game.c
#include "interface.h"
#include "state.h"
#include <stdlib.h>
State state;
void update_and_draw() {
struct key_state keys = { false, false, false, false, false, false };
if(IsKeyPressed(KEY_UP)) keys.up = true;
else if(IsKeyPressed(KEY_LEFT)) keys.left = true;
else if(IsKeyDown(KEY_RIGHT)) keys.right = true;
else if(IsKeyPressed(KEY_ENTER)) keys.enter = true;
else if(IsKeyPressed(KEY_P)) keys.p = true;
else if(IsKeyPressed(KEY_N)) keys.n = true;
state_update(state, &keys);
interface_draw_frame(state);
}
int main() {
state = state_create();
interface_init();
// Η κλήση αυτή καλεί συνεχόμενα την update_and_draw μέχρι ο χρήστης να κλείσει το παράθυρο
start_main_loop(update_and_draw);
interface_close();
state_destroy(state);
return 0;
}<file_sep>/tests/set_utils_test.c
//////////////////////////////////////////////////////////////////
//
// Test για το set_utils.h module
//
//////////////////////////////////////////////////////////////////
#include "acutest.h" // Απλή βιβλιοθήκη για unit testing
#include "ADTSet.h"
#include "state.h"
int compare(Pointer a, Pointer b) {
Object object1 = (Object)a;
Object object2 = (Object)b;
return object1->rect.x - object2->rect.x;
}
Pointer set_find_eq_or_greater(Set set, Pointer value){
if(set_find_node(set, value) != SET_EOF)
return value;
int d;
for(SetNode node = set_first(set);
node != SET_EOF;
node = set_next(set, node)) {
d = compare(set_node_value(set, node), value);
if(d > 0)
return set_node_value(set, node);
}
return NULL;
}
Pointer set_find_eq_or_smaller(Set set, Pointer value){
if(set_find_node(set, value) != SET_EOF)
return value;
Pointer d = NULL;
for(SetNode node = set_first(set);
node != SET_EOF;
node = set_next(set, node)) {
if(compare(set_node_value(set, node), value) < 0)
d = set_node_value(set, node);
else
return d;
}
return NULL;
}
int compare_obj(Pointer a, Pointer b) {
Object obj1 = (Object)a;
Object obj2 = (Object)b;
return obj1->rect.x - obj2->rect.x;
}
void test_set_utils() {
Set set = set_create(compare_obj, free);
for(int i = 0; i < 400; i++) {
Object obj = malloc(sizeof(*obj));
obj->rect.x = (i+1)*700;
obj->forward = false;
set_insert(set, obj);
}
Object obj1 = (Object)set_node_value(set, set_first(set));
Object obj2 = malloc(sizeof(*obj2));
obj2->rect.x = obj1->rect.x - 10;
TEST_ASSERT(set_find_eq_or_smaller(set, obj2) == NULL);
obj1 = (Object)set_node_value(set, set_last(set));
obj2->rect.x = obj1->rect.x + 10;
TEST_ASSERT(set_find_eq_or_greater(set, obj2) == NULL);
set_destroy(set);
}
// Λίστα με test προς εκτέλεση
TEST_LIST = {
{ "test_set_utils", test_set_utils},
{ NULL, NULL } // τερματίζουμε τη λίστα με NULL
};<file_sep>/modules/set_utils.c
#include <stdlib.h>
#include <stdio.h>
#include "ADTVector.h"
#include "ADTSet.h"
#include "state.h"
int compare(Pointer a, Pointer b) {
Object object1 = (Object)a;
Object object2 = (Object)b;
return object1->rect.x - object2->rect.x;
}
Pointer set_find_eq_or_greater(Set set, Pointer value){
if(set_find_node(set, value) != SET_EOF)
return value;
for(SetNode node = set_first(set);
node != SET_EOF;
node = set_next(set, node)) {
int d = compare(set_node_value(set, node), value);
if(d > 0)
return set_node_value(set, node);
}
return NULL;
}
Pointer set_find_eq_or_smaller(Set set, Pointer value){
if(set_find_node(set, value) != SET_EOF)
return value;
Pointer d = NULL;
for(SetNode node = set_first(set);
node != SET_EOF;
node = set_next(set, node)) {
if(compare(set_node_value(set, node), value) < 0)
d = set_node_value(set, node);
else
return d;
}
return NULL;
}<file_sep>/modules/interface.c
#include "raylib.h"
#include <stdio.h>
#include <stdlib.h>
#include "state.h"
#include "interface.h"
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 450
Texture mario_img;
Texture mario2_img;
Texture enemy_img;
void interface_init() {
// Αρχικοποίηση του παραθύρου
InitWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Game");
SetTargetFPS(60);
mario_img = LoadTextureFromImage(LoadImage("../../mario.png"));
mario2_img = LoadTextureFromImage(LoadImage("../../mario2.png"));
enemy_img = LoadTextureFromImage(LoadImage("../../enemy.png"));
}
void interface_close() {
CloseWindow();
}
static int wins = 0;
void interface_draw_frame(State state) {
BeginDrawing();
// Καθαρισμός, θα τα σχεδιάσουμε όλα από την αρχή
ClearBackground(SKYBLUE);
int x1,x2;
if((state_info(state))->character->rect.x < (SCREEN_WIDTH/3)) {
x1 = 0;
x2 = SCREEN_WIDTH;
}
else {
x1 = (state_info(state))->character->rect.x - SCREEN_WIDTH/3;
x2 = (state_info(state))->character->rect.x + 10 + SCREEN_WIDTH*2/3;
}
DrawRectangle(0, 435, 800, 15, DARKGREEN);
List list = state_objects(state, x1 ,x2); // θα μου δωσει τα αντικειμενα στο frame που θελω καθε φορα
for(ListNode node = list_first(list);
node != LIST_EOF;
node = list_next(list, node)) {
Object obj = list_node_value(list, node);
if(obj->type == OBSTACLE)
DrawRectangle(obj->rect.x, obj->rect.y, obj->rect.width, obj->rect.height, MAROON);
if(obj->type == ENEMY)
DrawTexture(enemy_img,obj->rect.x , obj->rect.y, WHITE);
if(obj->type == PORTAL)
DrawRectangle(obj->rect.x, obj->rect.y , obj->rect.width, obj->rect.height, SKYBLUE);
}
// Σχεδιάζουμε τον χαρακτήρα
if((state_info(state))->character->forward == true)
DrawTexture(mario_img, (state_info(state))->character->rect.x, (state_info(state))->character->rect.y, WHITE);
else
DrawTexture(mario2_img, (state_info(state))->character->rect.x, (state_info(state))->character->rect.y, WHITE);
DrawFPS(SCREEN_WIDTH - 80, 0);
DrawText(TextFormat("PORTAL %03i", (state_info(state))->current_portal), 20, 20, 40, GRAY);
DrawText(TextFormat("WINS %01i", (state_info(state))->wins), 20 , 60, 40, GRAY);
if((state_info(state))->wins > wins) {
wins++;
DrawText(
"YOU WON! PRESS [ENTER] TO PLAY AGAIN",
GetScreenWidth() / 2 - MeasureText("YOU WON! PRESS [ENTER] TO PLAY AGAIN", 20) / 2,
GetScreenHeight() / 2 - 50, 20, GRAY
);
}
else if (!(state_info(state))->playing) {
DrawText(
"PRESS [ENTER] TO PLAY AGAIN",
GetScreenWidth() / 2 - MeasureText("PRESS [ENTER] TO PLAY AGAIN", 20) / 2,
GetScreenHeight() / 2 - 50, 20, GRAY
);
}
EndDrawing();
}<file_sep>/tests/state_test.c
//////////////////////////////////////////////////////////////////
//
// Test για το state.h module
//
//////////////////////////////////////////////////////////////////
#include "acutest.h" // Απλή βιβλιοθήκη για unit testing
#include "ADTSet.h"
#include "ADTList.h"
#include "state.h"
typedef struct portal_pair {
Object entrance; // η πύλη entrance
Object exit; // οδηγεί στην exit
}* PortalPair;
struct state {
Vector objects; // περιέχει στοιχεία Object (Εμπόδια / Εχθροί / Πύλες)
List portal_pairs; // περιέχει PortalPair (ζευγάρια πυλών, είσοδος/έξοδος)
struct state_info info;
};
void test_state_create() {
State state = state_create();
TEST_ASSERT(state != NULL);
StateInfo info = state_info(state);
TEST_ASSERT(info != NULL);
TEST_ASSERT(info->current_portal == 1);
TEST_ASSERT(info->wins == 0);
TEST_ASSERT(info->playing == true);
TEST_ASSERT(info->paused == false);
bool check[100];
for(int i = 1; i <= 100 ; i++)
check[i] = 0;
for(ListNode node = list_first(state->portal_pairs);
node != LIST_EOF;
node = list_next(state->portal_pairs, node)) {
PortalPair pair = (PortalPair)list_node_value(state->portal_pairs, node);
int exit = *(int*)(pair->exit);
TEST_ASSERT(check[exit] == 0);
}
}
void test_state_update() {
State state = state_create();
TEST_ASSERT(state != NULL && state_info(state) != NULL);
// Πληροφορίες για τα πλήκτρα (αρχικά κανένα δεν είναι πατημένο)
struct key_state keys = { false, false, false, false, false, false };
// Χωρίς κανένα πλήκτρο, ο χαρακτήρας μετακινείται 7 pixels μπροστά
Rectangle old_rect = state_info(state)->character->rect;
state_update(state, &keys);
Rectangle new_rect = state_info(state)->character->rect;
TEST_ASSERT( new_rect.x == old_rect.x + 7 && new_rect.y == old_rect.y );
//Με πατημένο το δεξί βέλος, ο χαρακτήρας μετακινείται 12 pixes μπροστά
// keys.right = true;
// old_rect = state_info(state)->character->rect;
// state_update(state, &keys);
// new_rect = state_info(state)->character->rect;
// TEST_ASSERT( new_rect.x == old_rect.x + 12 && new_rect.y == old_rect.y );
keys.up = true;
old_rect = state_info(state)->character->rect;
state_update(state, &keys);
new_rect = state_info(state)->character->rect;
TEST_ASSERT(new_rect.y == old_rect.y);
keys.up = false; // character goes up at next frame
state_update(state, &keys);
new_rect = state_info(state)->character->rect;
TEST_ASSERT(new_rect.y == old_rect.y - 15);
state_destroy(state);
}
// Λίστα με όλα τα tests προς εκτέλεση
TEST_LIST = {
{ "test_state_create", test_state_create },
{ "test_state_update", test_state_update },
{ NULL, NULL } // τερματίζουμε τη λίστα με NULL
};<file_sep>/programs/game/Makefile
# paths
LIB = ../../lib
INCLUDE = ../../include
MODULES = ../../modules
# compiler
CC = gcc
# Compile options. Το -I<dir> λέει στον compiler να αναζητήσει εκεί include files
CFLAGS = -Wall -g -Werror -I$(INCLUDE)
LDFLAGS = -lm
# Αρχεία .o
OBJS = $(MODULES)/game.o $(MODULES)/interface.o $(MODULES)/state.o $(LIB)/k08.a $(LIB)/libraylib.a
# OBJS = $(MODULES)/game.o $(MODULES)/interface.o $(MODULES)/state_alt.o $(LIB)/k08.a $(LIB)/libraylib.a
# OBJS = set_utils_test.o $(LIB)/k08.a $(LIB)/libraylib.a
# OBJS = state_alt_test.o $(MODULES)/state_alt.o $(LIB)/k08.a $(LIB)/libraylib.a
# OBJS = state_test.o $(MODULES)/state.o $(LIB)/k08.a $(LIB)/libraylib.a
# Το εκτελέσιμο πρόγραμμα
EXEC = game
# Παράμετροι για δοκιμαστική εκτέλεση
ARGS =
# Παράμετροι της βιβλιοθήκης raylib
include $(LIB)/libraylib.mk
$(EXEC): $(OBJS)
$(CC) $(OBJS) -o $(EXEC) $(LDFLAGS)
clean:
rm -f $(OBJS) $(EXEC)
run: $(EXEC)
./$(EXEC) $(ARGS)
$(LIB)/%.a:
$(MAKE) -C $(LIB) $*.a
valgrind: $(EXEC)
valgrind --error-exitcode=1 --leak-check=full --show-leak-kinds=all ./$(EXEC) $(ARGS)<file_sep>/modules/state.c
#include <stdlib.h>
#include <stdio.h>
#include "ADTVector.h"
#include "ADTList.h"
#include "state.h"
int* create_int(int value) {
int* pointer = malloc(sizeof(int));
*pointer = value;
return pointer;
}
int compare_entrances(Object a, Object b){
return *(int*)a - *(int*)b;
}
// Ζευγάρια πυλών
typedef struct portal_pair {
Object entrance; // η πύλη entrance
Object exit; // οδηγεί στην exit
}* PortalPair;
struct state {
Vector objects; // περιέχει στοιχεία Object (Εμπόδια / Εχθροί / Πύλες)
List portal_pairs; // περιέχει PortalPair (ζευγάρια πυλών, είσοδος/έξοδος)
struct state_info info;
};
void state_init(State state) {
// Γενικές πληροφορίες
(state_info(state))->current_portal = 1; // Δεν έχουμε περάσει καμία πύλη
(state_info(state))->wins = 0; // Δεν έχουμε νίκες ακόμα
(state_info(state))->playing = true; // Το παιχνίδι ξεκινάει αμέσως
(state_info(state))->paused = false; // Χωρίς να είναι paused.
// Πληροφορίες για το χαρακτήρα.
Object character = (state_info(state))->character = malloc(sizeof(*character));
character->type = CHARACTER;
character->forward = true;
character->jumping = false;
character->rect.width = 38;
character->rect.height = 70;
character->rect.x = 0;
character->rect.y = SCREEN_HEIGHT - character->rect.height;
state->objects = vector_create(0, free); // Δημιουργία του vector
for (int i = 0; i < 4*PORTAL_NUM; i++) {
// Δημιουργία του Object και προσθήκη στο vector
Object obj = malloc(sizeof(*obj));
vector_insert_last(state->objects, obj);
// Κάθε 4 αντικείμενα υπάρχει μια πύλη. Τα υπόλοιπα αντικείμενα
// επιλέγονται τυχαία.
if(i % 4 == 3) { // Το 4ο, 8ο, 12ο κλπ αντικείμενο
obj->type = PORTAL; // είναι πύλη.
obj->rect.width = 80;
obj->rect.height = 15;
}
else if(rand() % 2 == 0) { // Για τα υπόλοιπα, με πιθανότητα 50%
obj->type = OBSTACLE; // επιλέγουμε εμπόδιο.
obj->rect.width = 10;
obj->rect.height = 70;
}
else {
obj->type = ENEMY; // Και τα υπόλοιπα είναι εχθροί.
obj->rect.width = 30;
obj->rect.height = 30;
obj->forward = false; // Οι εχθροί αρχικά κινούνται προς τα αριστερά.
}
// Τα αντικείμενα είναι ομοιόμορφα τοποθετημένα σε απόσταση SPACING
// μεταξύ τους, και "κάθονται" πάνω στο δάπεδο.
obj->rect.x = (i+1) * SPACING; // το προηγουμενο +700
obj->rect.y = SCREEN_HEIGHT - obj->rect.height;
}
}
// Δημιουργεί και επιστρέφει την αρχική κατάσταση του παιχνιδιού
State state_create() {
// Δημιουργία του state
State state = malloc(sizeof(*state));
state_init(state);
// Aρχικοποίηση της λίστας state->portal_pairs
state->portal_pairs = list_create(free);
int t[PORTAL_NUM]; // πινακας με περιεχομενα τα exit που εχω πετυχει
for(int i = 0; i < PORTAL_NUM; i++) {
// αρχικοποιηση των pairs
PortalPair pair = malloc(sizeof(*pair));
pair->entrance = (Object)(create_int(i+1));
int k = rand() % PORTAL_NUM + 1;
int j = 0;
while(j < 100) {
if(k == t[j]) { k = rand() % PORTAL_NUM + 1; j = 0;}
else j++;
}
pair->exit = (Object)(create_int(k));
t[i] = k;
list_insert_next(state->portal_pairs, list_last(state->portal_pairs), pair);
}
return state;
}
// Επιστρέφει τις βασικές πληροφορίες του παιχνιδιού στην κατάσταση state
StateInfo state_info(State state) {
return &(state->info);
}
// Επιστρέφει μια λίστα με όλα τα αντικείμενα του παιχνιδιού στην κατάσταση state,
// των οποίων η συντεταγμένη x είναι ανάμεσα στο x_from και x_to.
List state_objects(State state, float x_from, float x_to) { // Προς υλοποίηση
List list = list_create(free);
for(VectorNode vec_node = vector_first(state->objects);
vec_node != VECTOR_EOF;
vec_node = vector_next(state->objects, vec_node)) {
Object obj = vector_node_value(state->objects, vec_node);
// Αν το object ειναι αναμεσα στις συντεταγμενες που με ενδιαφερουν
if(obj->rect.x >= x_from && obj->rect.x <= x_to) {
list_insert_next(list, list_last(list), obj); // Βαλτο στη λιστα
}
}
return list;
}
static int forward = 1, up = 0, f = 1, fast = 1;
// Ενημερώνει την κατάσταση state του παιχνιδιού μετά την πάροδο 1 frame.
// Το keys περιέχει τα πλήκτρα τα οποία ήταν πατημένα κατά το frame αυτό.
void state_update(State state, KeyState keys) {
// character update
if((keys->enter != false) && ((state_info(state))->playing == false) ){
state_init(state);
}
if((keys->p != false) && ((state_info(state))->paused == true)) {
(state_info(state))->paused = false;
return;
}
if((state_info(state))->playing == true && (state_info(state))->paused == false){
fast = 1;
// σταθεροποιω τον χαρακτηρα στο 1/3 της οθονης και μετακινω ολα τα αλλα αντικειμενα
if((state_info(state))->character->rect.x >= SCREEN_WIDTH/3 && forward == 1) {
(state_info(state))->character->rect.x = SCREEN_WIDTH/3;
}
else if((state_info(state))->character->rect.x < SCREEN_WIDTH/3 && forward == -1){
(state_info(state))->character->rect.x = SCREEN_WIDTH/3;
}
if(keys->enter == false && keys->left == false && keys->right == false && keys->up == false && keys->n == false && keys->p == false ){
(state_info(state))->character->rect.x += 7*(forward);
if((state_info(state))->character->rect.y > 220 && up == -1)
(state_info(state))->character->rect.y += 15*(up);
else{
up = 0;
if((state_info(state))->character->rect.y < SCREEN_HEIGHT - (state_info(state))->character->rect.height )
(state_info(state))->character->rect.y += 15;
}
}
else if(keys->right != false) {
if((state_info(state))->character->forward == false) {
(state_info(state))->character->forward = true;
forward = 1;
}
else
fast = 2;
}
else if(keys->left != false){
forward = -1;
(state_info(state))->character->forward = false;
}
else if(keys->up != false && ((state_info(state))->character->rect.y == SCREEN_HEIGHT - (state_info(state))->character->rect.height)){
up = -1;
}
else if(keys->p != false){
(state_info(state))->paused = true;
}
// enemies update
for(int i = 0; i < 4*PORTAL_NUM; i++) {
Object obj = vector_get_at(state->objects, i);
if(obj->type == ENEMY) {
for(int j = 0; j < 4*PORTAL_NUM; j++) {
Object obj2 = vector_get_at(state->objects, j);
// συγκρουση εχθρου με εμποδιο
if((CheckCollisionRecs(obj2->rect, obj->rect)) && (obj2->type == OBSTACLE)) {
obj->forward = !(obj->forward);
}
}
// συγκρουση χαρακτηρα με εχθρο
if(CheckCollisionRecs(obj->rect, (state_info(state))->character->rect)){
(state_info(state))->playing = false;
return;
}
if(obj->forward == false) f = 1;
else f = -1;
obj->rect.x -= 8*f*fast;
}
else if(obj->type == OBSTACLE) {
// συγκρουση εμποδιο με χαρακτηρα
obj->rect.x -= 7*forward*fast;
if(CheckCollisionRecs((state_info(state))->character->rect, obj->rect)){
(state_info(state))->playing = false;
}
}
else if(obj->type == PORTAL) {
obj->rect.x -= 7*forward*fast;
// συγκρουση εμποδιου ή εχθρου με πυλη
if((CheckCollisionRecs(obj->rect, (state_info(state))->character->rect))) { // Portal A->B
for(ListNode node = list_first(state->portal_pairs);
node != LIST_EOF;
node = list_next(state->portal_pairs, node)) {
PortalPair pair = list_node_value(state->portal_pairs, node);
int entr = *(int*)(pair->entrance);
if(entr == (state_info(state))->current_portal) {
// effects of falling
if((state_info(state))->character->rect.x < (obj->rect.x)/2)
(state_info(state))->character->rect.y += 15;
else if((state_info(state))->character->rect.x > (obj->rect.x)/2 && ((state_info(state))->character->rect.x <= (obj->rect.x)))
(state_info(state))->character->rect.y -= 15;
(state_info(state))->current_portal = *(int*)(pair->exit);
if((pair->exit) == (Object)create_int(100)) {
(state_info(state))->wins += 1;
(state_info(state))->playing = false;
}
if((state_info(state))->character->forward == false) { // Portal (A->B -->) B->C
for(ListNode node = list_first(state->portal_pairs);
node != LIST_EOF;
node = list_next(state->portal_pairs, node)) {
PortalPair pair = list_node_value(state->portal_pairs, node);
int entr = *(int*)(pair->entrance);
if(entr == (state_info(state))->current_portal) {
// effects
if((state_info(state))->character->rect.x < (obj->rect.x)/2)
(state_info(state))->character->rect.y += 15;
else if((state_info(state))->character->rect.x > (obj->rect.x)/2 && ((state_info(state))->character->rect.x <= (obj->rect.x)))
(state_info(state))->character->rect.y -= 15;
(state_info(state))->current_portal = *(int*)(pair->exit);
if((pair->exit) == (Object)create_int(100)) {
(state_info(state))->wins += 1;
(state_info(state))->playing = false;
}
}
}
}
}
}
}
}
}
}
}
// Καταστρέφει την κατάσταση state ελευθερώνοντας τη δεσμευμένη μνήμη.
void state_destroy(State state) {
list_destroy(state->portal_pairs);
vector_destroy(state->objects);
free(state);
}
|
67bad8c0b0b0f7d9aead42b35b90da204f4e777e
|
[
"C",
"Makefile"
] | 8 |
C
|
AthinaHilakou/DesignComp
|
3ceb51054263d0441ceeb8d621d9ec0c29a0ed28
|
45eea8c8c09bc695cb989d1a9523349c8b172ce4
|
refs/heads/master
|
<file_sep>import {Registry} from './Registry.mjs'
import cp from 'child_process'
import {SZ, MULTI_SZ, EXPAND_SZ, DWORD, QWORD, BINARY, NONE} from './constants.mjs'
let ERR_NOT_FOUND
export let VALUE_DEFAULT = undefined
export let VALUE_NOT_SET = undefined
let errMessagePromise
let defaultValuesPromise
function getErrorLine(stderr) {
return stderr.trim().split('\r\n')[0]
}
function setDefaultValues(stdout) {
// indexOf() because it's fastest.
let iNextStr = stdout.indexOf('\r\n', 1)
let iNameBracketOpen = stdout.indexOf('(', iNextStr)
let iNameBracketClose = stdout.indexOf(')', iNameBracketOpen)
let iValBracketOpen = stdout.indexOf('(', iNameBracketClose)
let iValBracketClose = stdout.indexOf(')', iValBracketOpen)
VALUE_DEFAULT = stdout.slice(iNameBracketOpen, iNameBracketClose+1)
VALUE_NOT_SET = stdout.slice(iValBracketOpen, iValBracketClose+1)
}
// Method for calling the reg.exe commands.
export var execute
// Temporary wrapper over execute() function that first gets localized values
// because reg.exe is locale based. Only runs on the first (few) calls.
execute = async args => {
// Ensure we get localized messages only once.
// ERR_NOT_FOUND message.
if (!errMessagePromise) {
errMessagePromise = spawn('reg.exe', ['QUERY', 'HKLM\\NONEXISTENT'])
.then(res => ERR_NOT_FOUND = getErrorLine(res.stderr))
}
// (Default) and (value not set) values.
if (!defaultValuesPromise) {
defaultValuesPromise = spawn('reg.exe', ['QUERY', 'HKCR', '/ve'])
.then(res => setDefaultValues(res.stdout))
}
// Postpone all execute() calls until the localized messages are resolved.
await Promise.all([errMessagePromise, defaultValuesPromise])
// Replace this temporary function with actual execute().
execute = _execute
return _execute(args)
}
// Actual execute() function.
var _execute = async args => {
var {stdout, stderr} = await spawn('reg.exe', args)
// REG command has finished running, resolve result or throw error if any occured.
if (stderr.length === 0) return stdout
var line = getErrorLine(stderr)
// Return undefined if the key path does not exist.
if (line === ERR_NOT_FOUND) return undefined
// Propagate the error forward.
throw new RegError(`${line.slice(7)} - Command 'reg ${args.join(' ')}'`)
}
function promiseOnce(eventEmitter, event) {
return new Promise(resolve => eventEmitter.once(event, resolve))
}
// Promise wrapper for child_process.spawn().
export var spawn = async (program, args) => {
var stdio = ['ignore', 'pipe', 'pipe']
var proc = cp.spawn(program, args, {stdio})
var stdout = ''
var stderr = ''
proc.stdout.on('data', data => stdout += data.toString())
proc.stderr.on('data', data => stderr += data.toString())
var result = await Promise.race([
promiseOnce(proc, 'close'),
promiseOnce(proc, 'error'),
])
proc.removeAllListeners()
if (result instanceof Error)
throw result
else
return {stdout, stderr}
}
// Replaces default spawn('reg.exe', ) with custom means of spawning reg.exe.
// For example allows to run the library in restricted environments.
// Default spawn('reg.exe', ) uses Node's child_process.spawn().
export function _replaceSpawn(externalHook) {
spawn = externalHook
}
class RegError extends Error {
constructor(message) {
super(message)
delete this.stack
}
}
export function inferAndStringifyData(data, type) {
if (data === undefined || data === null)
return [data, type]
switch (data.constructor) {
// Convert Buffer data into string and infer type to REG_BINARY if none was specified.
case Uint8Array:
data = data.buffer
case ArrayBuffer:
data = Buffer.from(data)
case Buffer:
if (type === undefined)
type = BINARY
// Convert to ones and zeroes if the type is REG_BINARY or fall back to utf8.
data = data.toString(type === BINARY ? 'hex' : 'utf8')
break
case Array:
// Set REG_MULTI_SZ type if none is specified.
if (type === undefined)
type = MULTI_SZ
// REG_MULTI_SZ contains a string with '\0' separated substrings.
data = data.join('\\0')
break
case Number:
// Set REG_DWORD type if none is specified.
if (type === undefined)
type = DWORD
break
case String:
//default:
// Set REG_SZ type if none is specified.
switch (type) {
case BINARY:
data = Buffer.from(data, 'utf8').toString('hex')
break
case MULTI_SZ:
data = data.replace(/\0/g, '\\0')
break
case undefined:
type = SZ
break
}
}
return [data, type]
}
export function parseValueData(data, type) {
if (type === BINARY)
data = Buffer.from(data, 'hex')
if (type === DWORD)
data = parseInt(data)
//if (type === QWORD && convertQword)
// data = parseInt(data)
if (type === MULTI_SZ)
data = data.split('\\0')
return [data, type]
}
// Transforms possible forwardslashes to Windows style backslash
export function sanitizePath(path) {
path = path.trim()
if (path.includes('/'))
return path.replace(/\//g, '\\')
else
return path
}
// Uppercases and prepends 'REG_' to a type string if needed.
export function sanitizeType(type) {
// Skip transforming if the type is undefined
if (type === undefined)
return
type = type.toUpperCase()
// Prepend REG_ if it's missing
if (!type.startsWith('REG_'))
type = 'REG_' + type
return type
}
export function getOptions(userOptions) {
var {lowercase, format} = Registry
var defaultOptions = {lowercase, format}
if (userOptions)
return Object.assign(defaultOptions, userOptions)
else
return defaultOptions
}
<file_sep>import {HIVES, shortenHive, extendHive} from './constants.mjs'
import {sanitizePath, spawn} from './util.mjs'
// Collection of static methods for interacting with any key in windows registry.
// Also a constructor of an object with access to given single registry key.
export class Registry {
constructor(path, options) {
path = sanitizePath(path)
if (path.endsWith('\\'))
path = path.slice(-1)
this.path = path
var hive = path.split('\\').shift()
this.hive = shortenHive(hive)
if (!HIVES.includes(this.hive))
throw new Error(`Invalid hive '${this.hive}', use one of the following: ${HIVES.join(', ')}`)
this.hiveLong = extendHive(hive)
this.options = Object.assign({}, Registry.options, options)
}
_formatArgs(args) {
if (args.length === 0)
return [this.path]
// TODO: simplified, lowercase
var firstArg = sanitizePath(args[0])
if (firstArg.startsWith('.\\'))
args[0] = this.path + firstArg.slice(1)
else if (firstArg.startsWith('\\'))
args[0] = this.path + firstArg
else
args.unshift(this.path)
return args
}
static async setCodePage(encoding) {
try {
await spawn('cmd.exe', ['/c', 'chcp', encoding])
} catch (e) {
throw new Error(`Invalid code page: ${encoding}`)
}
}
static async enableUnicode() {
if (this.unicode) return
var {stdout} = await spawn('cmd.exe', ['/c', 'chcp'])
var cp = Number(stdout.split(':')[1])
if (Number.isNaN(cp)) throw new Error(`Can't get current code page`)
this.lastCodePage = cp
this.unicode = true
}
static async disableUnicode() {
if (!this.unicode) return
await this.setCodePage(this.lastCodePage)
this.lastCodePage = undefined
this.unicode = false
}
}
Registry.VALUES = '$values'
Registry.DEFAULT = ''
Registry.unicode = false
Registry.lastCodePage
// Only names and paths are affected, not the data
Registry.lowercase = true
// Calls return simplified output format by default.
// Can be 'simple', 'complex', (TODO) 'naive'
Registry.format = 'simple'
Registry.FORMAT_SIMPLE = 'simple'
Registry.FORMAT_COMPLEX = 'complex'
|
abbd5b7eb4fe9ca92a08b9b7cd1a628363301e0f
|
[
"JavaScript"
] | 2 |
JavaScript
|
danielmorena/rage-edit
|
6e18ee85437f2b97d493b93de43ed1e9e1e2c117
|
b4a0e56c73d49162fec01ded1fd5322f71628a68
|
refs/heads/master
|
<repo_name>timexouts/PipTest<file_sep>/build/scripts-3.5/testpip.py
#!python
def sayhello():
print("Hey there!")
return 0
if __name__ == "__main__":
sayhello()
<file_sep>/Makefile
.PHONY: clean
clean:
rm -rf dist build *.egg-info
.PONEY: cleanall
cleanall: clean
rm -rf venv
build: clean
python3 setup.py sdist bdist_wheel
upload-to-test:
python3 -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*
install-from-test:
python3 -m pip install --index-url https://test.pypi.org/simple/ --no-deps demo-pkg-imeas
venv-create:
python3 -m venv venv
<file_sep>/README.md
# PipTest
This is a test. It do nothing<file_sep>/build/lib/pipTestpack/testpip.py
#!/usr/bin/env python3
def sayhello():
print("Hey there!")
return 0
if __name__ == "__main__":
sayhello()
<file_sep>/build/lib/pipTestpack/__init__.py
name = "pipTestpack"
|
49a5061ee9467fe9663bdf77e4eefcf060cfce84
|
[
"Markdown",
"Python",
"Makefile"
] | 5 |
Python
|
timexouts/PipTest
|
bd4ce0cf22c1de1f47cd6e605e167bdc29f3cd8c
|
43e9b407ab4971399c8e72bb39ff3cdecc5288a7
|
refs/heads/main
|
<file_sep>using System.Collections;
using UnityEngine;
public class WeaponManager1 : MonoBehaviour
{
public float switchDelay = 1f;
public GameObject[] weapon; //무기의 게임 오브젝트 배열
private int index = 0; // 무기의 인덱스
private bool isSwitching = false; // 딜레이를 확인하기 위함.
// Use this for initialization
private void Start()
{
InitializeWeapon();
}
// Update is called once per frame
private void Update()
{
if (Input.GetAxis("Mouse ScrollWheel") > 0 && !isSwitching) // 마우스 휠이 내려가고 딜레이가 아니면 인덱스 올리고 스위칭
{
index++;
if (index >= weapon.Length)
index = 0;
StartCoroutine(SwitchDelay(index)); //IEnumerator를 실행시키기 위해서 사용하는 함수
}
if (Input.GetAxis("Mouse ScrollWheel") < 0 && !isSwitching)
{
index--;
if (index < 0)
index = weapon.Length - 1;
StartCoroutine(SwitchDelay(index));
}
// weapon switching by alphanum
for (int i = 49; i < 52; i++) //1부터 3까지의 키를 입력받아 해당하는 인덱스로 지정 스위칭
{
if (Input.GetKeyDown((KeyCode)i) && !isSwitching && weapon.Length > i - 49 && index != i - 49)
{
index = i - 49;
StartCoroutine(SwitchDelay(index));
}
}
}
private void InitializeWeapon() //게임이 시작될때 초기화하는 부분.
//0번 인덱스의 무기만 Active하고 나머지는 Active를 false로 함.
{
for (int i = 0; i < weapon.Length; i++)
{
weapon[i].SetActive(false);
}
weapon[0].SetActive(true);
index = 0;
}
private IEnumerator SwitchDelay(int newIndex)
//함수가 실행될때 대기시간을 넣으려면 IEnumerator를 사용해야하는데
//yield 형으로 WaitForSeconds(초)의 리턴값을 리턴해주면
//해당 초만큼 대기를 한 후 다음줄부터 실행됨.
//따라서 isSwitching을 true로 만들고 switchDelay만큼의 초를 기다린 뒤 다시 false가 되는식.
{
isSwitching = true;
SwitchWeapons(newIndex);
yield return new WaitForSeconds(switchDelay);
isSwitching = false;
}
private void SwitchWeapons(int newIndex) // 입력받은 인덱스의 오브젝트를 활성화하고 나머지는 비활성화함.
{
for (int i = 0; i < weapon.Length; i++)
{
weapon[i].SetActive(false);
}
weapon[newIndex].SetActive(true);
}
}
|
8b8d1598c69f5a9f6067d0a75527a73b573f5154
|
[
"C#"
] | 1 |
C#
|
seoohyeon/2021-Meta-Bus-Knights
|
f58fa0441b6db8f3d5741a2bad027981661cbf87
|
87683f7aff22b95ca66d767c6ec511003442f63d
|
refs/heads/master
|
<file_sep>package com.previred.periodos.exception;
import com.previred.periodos.exception.dto.ResponseErrorDto;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class ExceptionManager {
@ResponseBody
@ExceptionHandler(FechaInicioMayorException.class)
private ResponseEntity<Object> mensajeException(FechaInicioMayorException exception) {
ResponseErrorDto errorDto = ResponseErrorDto.builder()
.codigo(HttpStatus.BAD_REQUEST.toString())
.mensaje(exception.getMessage())
.build();
return new ResponseEntity<>(errorDto, new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
@ResponseBody
@ExceptionHandler(ServiceEmptyException.class)
private ResponseEntity<Object> mensajeException(ServiceEmptyException exception) {
ResponseErrorDto errorDto = ResponseErrorDto.builder()
.codigo(HttpStatus.BAD_REQUEST.toString())
.mensaje(exception.getMessage())
.build();
return new ResponseEntity<>(errorDto, new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
@ResponseBody
@ExceptionHandler(ServerErrorException.class)
private ResponseEntity<Object> mensajeException(ServerErrorException exception) {
ResponseErrorDto errorDto = ResponseErrorDto.builder()
.codigo(HttpStatus.INTERNAL_SERVER_ERROR.toString())
.mensaje(exception.getMessage())
.build();
return new ResponseEntity<>(errorDto, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
<file_sep>rootProject.name = 'periodos'
<file_sep>package com.previred.periodos.exception.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ResponseErrorDto {
private String codigo;
private String mensaje;
}
|
0e8a68733cdce028180eeee3576a15b794b6ba18
|
[
"Java",
"Gradle"
] | 3 |
Java
|
diego-aguirre-rabanal/Desafio_Uno
|
727611020496e72f6717da8ee7a72c00ef3e3eb6
|
5ae85704c76cadb9a15f6b5d094994f6ef831250
|
refs/heads/master
|
<repo_name>TylersDesk/fancy-ass-comparison-table<file_sep>/javascripts/lib/main.js
//console.log('Loaded Zblog Main.js');
var zproto = zproto || {};
(function() {
'use strict';
//Zblog nav scripts
zproto.nav = (function () {
var container = $('.zcontent')
, navSrc = $('.nav-ham')
, hamburger = $('.ztoggle')
, navImage = navSrc.find('img').attr('src')
, closeImage = 'img/nav-close.png'
, navTab = $('.nav-choice')
;
hamburger.on('click', function(){
if(container.hasClass('view')) {
navSrc.find('img').attr('src', navImage);
container.removeClass('view');
} else {
navSrc.find('img').attr('src', closeImage);
container.addClass('view');
}
});
$('.nav-categories li a').on('click', function(e) {
$(this).next('ul').toggleClass('visible');
});
// $(document).on('click', '.visible', function(e) {
// e.stopPropagation();
// $(this).removeClass('visible');
// });
return {
init: function() {
console.log(navImage);
}
};
}());
zproto.heightFinder = (function(){
return {
init: function(){
}
};
}());
//Init Function
zproto.init = function() {
zproto.nav.init();
};
}());
var updateHiddenProducts = function() {
var showHiddenProducts = $('.imHiding');
if (showHiddenProducts.length) {
$('.show-all').find('span.hidden-number').html(showHiddenProducts.length);
}
};
$(document).ready(function() {
'use strict';
zproto.init();
$('.stickit').on('click', function() {
var elem = $(this).parent().clone();
elem.find('.stickit').html('Unstick').css('width','100%').addClass('removeMe');
elem.find('.hideit').remove();
console.log('Setting Height to ', $('.heightFinder').data('columnHeight'))
elem.css('height', $('.heightFinder').data('columnHeight'));
var myKids = $('.sticky-container').children().length;
if (myKids > 0) {
$('.sticky-container').css('width', (myKids + 1)*162);
}
$('.sticky-container').append(elem);
// var theElem = $(this).parent();
// theElem.css('height', $('.heightFinder').data('columnHeight'));
// theElem.animate({
// left:0
// });
});
$('.hideit').on('click', function() {
if (!$('.show-all').is(":visible")) {
$('.show-all').css('display','block');
$('.show-all').animate({
'height':'40',
'opacity':1,
padding: 10
});
}
var elem = $(this).parent();
elem.attr('oldHeight',elem.css('height'));
elem.animate({
'width':1,
'opacity':0,
'height':1
}, function(){
$(this).hide();
});
elem.addClass('imHiding');
updateHiddenProducts();
});
$(document).on('click', '.removeMe', function(){
$(this).parent().remove();
var theWidth = parseInt($('.sticky-container').css('width'), 10);
if (theWidth != 0) {
$('.sticky-container').css('width', theWidth - 161 );
}
console.log($('.sticky-container').css('width'));
});
$(document).on('click', '.showallproducts', function() {
console.log($('.imHiding').length);
$('.imHiding').each(function(i,elem){
var thisElem = $(elem),
oldHeight = thisElem.attr('oldHeight');
thisElem.removeClass('imHiding');
thisElem.css('display','block');
thisElem.animate({
opacity:1,
width:161,
height: oldHeight
});
});
$('.show-all').animate({
height:1,
opacity:0,
padding: 0
}, function(){
$(this).hide();
});
});
});
var homeCarousel = $('.carousel');
$('#home-carousel').on('swipeleft', function() {
homeCarousel.carousel('next');
});
$('#home-carousel').on('swiperight', function() {
homeCarousel.carousel('prev');
});
$(document).on('click', '.goToLevel2', function() {
$('.znav-content').toggleClass('view');
});
$(document).on('click', '.goToLevel3', function() {
$('.znav-content2').toggleClass('view');
});
$(document).on('click', '.login-block', function() {
$('.zsearch').removeClass('view');
$('.zlogin').toggleClass('view');
});
$(document).on('click', '.search', function() {
$('.zlogin').removeClass('view');
$('.zsearch').toggleClass('view');
});
(function() {
var target2 = $(".swipe2")[0]; // <== Getting raw element
$(".swipe1").scroll(function() {
// target.scrollTop = this.scrollTop;
target2.scrollLeft = this.scrollLeft;
});
})();
(function() {
var target1 = $(".swipe1")[0]; // <== Getting raw element
$(".swipe2").scroll(function() {
// target.scrollTop = this.scrollTop;
target1.scrollLeft = this.scrollLeft;
});
})();
$.fn.widthMaker = function() {
var cellWidth = parseInt(this.children().eq(1).css('width'), 10),
cellNum = this.children().length;
this.css('width', cellWidth*cellNum);
return this;
}
//HeightFinder Jquery Plugin
$.fn.heightFinder = function() {
var directSiblings = this.children();
console.log('directSiblings: ', directSiblings);
var allHeight = directSiblings.map(function(){
return $(this).height();
}).get();
var height = Math.max.apply(null, allHeight);
this.data({"columnHeight": height});
this.attr('columnHeight', height);
return this;
}
$('.heightFinder').heightFinder();
$('.heightFinder').widthMaker();
|
0cf524c1de4b7455c898d50973efc6ac7c7e678d
|
[
"JavaScript"
] | 1 |
JavaScript
|
TylersDesk/fancy-ass-comparison-table
|
b03753ef4da20b4b650a74204a6822ca4ce5e87a
|
89b490fddd9445e8c8dfda3d8c602f858528a430
|
refs/heads/master
|
<repo_name>isaacguerreir/mindminers-project<file_sep>/src/components/table.js
import React from 'react';
import MaterialTable from 'material-table'
import { TableIcons, Localization } from '../service/utils';
const TableResult = ({data, results}) => {
const dataMergeResults = data.map((obj, index) => {
return {
date: obj.date,
stockId: obj.stockId,
type: obj.type,
price: obj.price,
quantity: obj.quantity,
tax: obj.tax,
ir: results[index].ir
}
})
return (
<MaterialTable
icons={TableIcons}
columns={[
{ title: 'Nome da ação', field: 'stockId', headerStyle: styles.headerStyle, cellStyle: styles.cellStyle },
{ title: 'Tipo de operação', field: 'type', headerStyle: styles.headerStyle, cellStyle: styles.cellStyle, lookup: { BUY: 'Compra', SELL: 'Venda' } },
{ title: 'Data da operação', field: 'date', headerStyle: styles.headerStyle, cellStyle: styles.cellStyle, type: 'date' },
{ title: 'Preço unitário', field: 'price', headerStyle: styles.headerStyle, cellStyle: styles.cellStyle },
{ title: 'Quantidade de papéis', field: 'quantity', headerStyle: styles.headerStyle, cellStyle: styles.cellStyle },
{ title: 'Taxa de corretagem', field: 'tax', headerStyle: styles.headerStyle, cellStyle: styles.cellStyle },
{ title: 'Imposto de Renda', field: 'ir', headerStyle: styles.headerStyle, cellStyle: styles.cellStyle }
]}
data={dataMergeResults}
title=""
options={{
exportButton: true,
searchFieldStyle: styles.searchFieldStyle,
}}
localization={Localization}
/>
)
}
const styles = {
headerStyle: {
fontSize: '0.7rem',
padding: '1rem',
fontFamily: 'Karla'
},
cellStyle: {
padding: '1rem',
fontFamily: 'Karla'
},
searchFieldStyle: {
fontFamily: 'Karla'
}
}
export default TableResult;<file_sep>/src/domain/Operation.js
class Operation {
constructor(date, stockId, type, price, quantity, tax) {
this._id = this.generateUniqueId();
this._date = date;
this._stockId = stockId;
this._type = type;
this._price = price;
this._quantity = quantity;
this._tax = tax;
}
get id() {
return this._id;
}
get date() {
return this._date;
}
get stockId() {
return this._stockId;
}
get type() {
return this._type;
}
get price() {
return this._price;
}
get quantity() {
return this._quantity;
}
get tax() {
return this._tax;
}
generateUniqueId = () => {
return '_' + Math.random().toString(36).substr(2, 9);
}
}
export default Operation;<file_sep>/src/components/results.js
import React from "react"
import { calculateIR } from '../service/calculator';
import TableResult from './table';
import PieChart from './piechart';
import ColumnChart from './columnChart';
import TotalDetails from './totalDetails';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
const Results = ({ listStocks }) => {
const existThisMonth = (el, list) => {
return list.indexOf(el) === -1 ? true : false;
}
const stockDivideByMonth = (operationList) => {
const dateList = operationList.map((operation) => {
return operation.date
});
let months = [];
dateList.forEach(function(date) {
if (existThisMonth(date.getMonth(), months)) {
months.push(date.getMonth());
}
})
const opByMonth = months.map((month) => {
const operationsByMonth = operationList.filter((operation) => {
return operation.date.getMonth() === month;
})
return {
month: month,
operations: operationsByMonth,
result: []
}
})
return opByMonth;
}
const totalIR = (list) => {
const IRList = list.map((obj) => { return obj.ir })
return IRList.reduce((acc, val) => {
return acc += val
})
}
const totalProfit = (list) => {
const profitList = list.map((obj) => { return obj.profit })
return profitList.reduce((acc, val) => {
return acc += val
})
}
const totalLoss = (list) => {
const lossList = list.map((obj) => { return obj.loss })
return lossList.reduce((acc, val) => {
return acc += val
})
}
const totalLiquid = (list) => {
const profit = totalProfit(list);
const loss = totalLoss(list);
const ir = totalIR(list);
return profit - (loss + ir);
}
const returnMonthByNumber = (number) => {
var months = {
0: 'Janeiro',
1: 'Fevereiro',
2: 'Março',
3: 'Abril',
4: 'Maio',
5: 'Junho',
6: 'Julho',
7: 'Agosto',
8: 'Setembro',
9: 'Outubro',
10: 'Novembro',
11: 'Dezembro',
}
return months[number];
}
const IRcalc = listStocks.stocks.map((stock) => {
const months = stockDivideByMonth(stock.batch);
const result = months.map((obj) => {
obj.result = calculateIR(obj.operations);
return obj;
})
return result;
});
const stockIds = listStocks.stocks.map((stock)=> {
return stock.stockId;
})
return (
<>
<div style={styles.pieChart}>
<PieChart data={listStocks.stocks} />
</div>
<div style={styles.description.paragraph}>
Clique em cada <b>tipo de Ação</b> adicionada para conferir os detalhes (Lucro Total¹, Prejuízo Total² e Total Líquido³) e o IR calculado,
os quais estarão dividos por mês.
</div>
<div style={styles.description.tip}>
<div>¹ <i>Lucro Total</i> é calculado pelo somatório do valor de todas as operações em que o <i>Resultado Aferido</i> é maior que 0.</div>
<div>² <i>Prejuízo Total</i> é calculado pelo somatório do valor de todas as operações em que o <i>Resultado Aferido</i> é menor que 0.</div>
<div>³ <i>Total Líquido</i> é calculado pelo <i>Lucro Total</i> menos o <i>Prejuízo Total</i> menos o <i>Imposto de Renda Total</i>.</div>
</div>
{
stockIds.map((stockId, index) => {
return(
<ExpansionPanel key={stockId}>
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<div style={styles.expansion.stockId}>{stockId}</div>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<div style={styles.expansion.details.box}>
<div style={styles.expansion.details.columnChart}>
<ColumnChart data={IRcalc[index]}/>
</div>
{
IRcalc[index].map((obj) => {
return( <Month
key={stockId}
data={obj}
monthName={returnMonthByNumber(obj.month)}
profit={totalProfit(obj.result).toFixed(2)}
loss={totalLoss(obj.result).toFixed(2)}
ir={totalIR(obj.result).toFixed(2)}
total={totalLiquid(obj.result).toFixed(2)}
/>
)
})
}
</div>
</ExpansionPanelDetails>
</ExpansionPanel>
)
})
}
</>
)
}
function Month(props) {
const obj = props.data;
const { profit, loss, ir, total, monthName} = props;
return(
<React.Fragment key={obj.month}>
<ExpansionPanel key={obj.month}>
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<div style={styles.expansion.details.month.box}>
{monthName}
</div>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<div style={styles.expansion.details.month.result}>
<TableResult
data={obj.operations}
results={obj.result}
/>
<TotalDetails
profit={profit}
loss={loss}
ir={ir}
total={total}
/>
</div>
</ExpansionPanelDetails>
</ExpansionPanel>
</React.Fragment>
)
}
const styles = {
pieChart: {
marginBottom: '2rem'
},
description: {
paragraph: {
fontFamily: 'Rubik',
textAlign: `justify`,
textJustify: `inter-word`
},
tip: {
fontFamily: 'Rubik',
fontSize: '0.6rem',
marginBottom: '1rem',
paddingLeft: '1rem'
}
},
expansion: {
stockId: {
fontFamily: 'Rubik',
margin: 0,
fontWeight: '700'
},
details: {
box: {
display: 'flex',
flexDirection: 'column'
},
columnChart: {
maxWidth: '100vhm'
},
month: {
box: {
fontFamily: 'Rubik'
},
result: {
display: 'flex',
flexDirection: 'column'
}
}
}
}
}
export default Results;<file_sep>/src/service/calculator.js
const calculateIR = (listOperations) => {
let medianPrice = 0.0;
let medianQuantity = 0.0;
let accumulatedLoss = 0.0;
const result = listOperations.map(function(operation) {
let price = parseFloat(operation.price);
let quantity = parseFloat(operation.quantity);
let tax = parseFloat(operation.tax);
let type = operation.type;
if (type === "BUY") {
medianPrice = calculateMedianPrice(medianPrice, medianQuantity, price, quantity, tax);
medianQuantity = calculateMedianQuantity(medianQuantity, quantity);
return {
ir: 0.0,
profit: 0.0,
loss: 0.0
}
}
let measuredResult = calculateMeasuredResult(medianPrice, price, quantity, tax);
if (measuredResult < 0) {
accumulatedLoss += Math.abs(measuredResult);
return {
ir: 0.0,
profit: 0.0,
loss: Math.abs(measuredResult)
}
}
let IRTax = measuredResult - descountAccLoss(measuredResult, accumulatedLoss);
IRTax = (IRTax * 15.0) / 100.0;
accumulatedLoss = calculateAccumulatedLoss(measuredResult, accumulatedLoss);
return {
ir: IRTax,
profit: measuredResult,
loss: 0.0
};
})
return result;
}
const roundValue = (number) => {
return parseFloat(number.toFixed(12));
}
const calculateMeasuredResult = (medianPrice, price, quantity, tax) => {
let result = price - medianPrice;
result = result * quantity - tax;
return roundValue(result);
}
const calculateMedianPrice = (medianPrice, medianQuantity, price, quantity, tax) => {
let result = medianPrice * medianQuantity + price * quantity + tax;
result = result / (quantity + medianQuantity);
return roundValue(result);
}
const calculateMedianQuantity = (medianQuantity, quantity, isBuying = true) => {
if (isBuying) {
let result = medianQuantity + quantity;
return roundValue(result);
}
let result = medianQuantity - quantity;
return roundValue(result);
}
const calculateAccumulatedLoss = (measuredResult, accumulatedLoss) => {
let result = accumulatedLoss - descountAccLoss(measuredResult, accumulatedLoss);
return roundValue(result);
}
const descountAccLoss = (measuredResult, accumulatedLoss) => {
if (accumulatedLoss <= measuredResult) {
return accumulatedLoss;
}
return measuredResult;
}
const totalIR = (list) => {
const IRList = list.map((obj) => { return obj.ir })
return IRList.reduce((acc, val) => {
return acc += val
})
}
const totalProfit = (list) => {
const profitList = list.map((obj) => { return obj.profit })
return profitList.reduce((acc, val) => {
return acc += val
})
}
const totalLoss = (list) => {
const lossList = list.map((obj) => { return obj.loss })
return lossList.reduce((acc, val) => {
return acc += val
})
}
const totalLiquid = (list) => {
const profit = totalProfit(list);
const loss = totalLoss(list);
const ir = totalIR(list);
return profit - (loss + ir);
}
export {
calculateMedianPrice,
calculateMedianQuantity,
calculateAccumulatedLoss,
descountAccLoss,
calculateMeasuredResult,
calculateIR,
totalIR,
totalProfit,
totalLiquid,
totalLoss
};<file_sep>/src/components/piechart.js
import React from 'react';
import Chart from './chart';
const PieChart = ({data}) => {
const totalInvested = (list) => {
const values = list.map((obj) => {
if (obj.type === 'BUY') {
return obj.quantity * obj.price;
}
return obj.quantity * obj.price * -1;
})
return values.reduce((acc, val) => {
return acc += val;
})
}
const result = data.map((operationList) => {
return {
name: operationList.stockId,
y: Math.abs(totalInvested(operationList.batch))
}
})
const options = {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Composição atual da carteira'
},
tooltip: {
pointFormat: 'Investido: <b>R${point.y:.2f}</b>'
},
accessibility: {
point: {
valueSuffix: '%'
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
}
}
},
series: [{
name: 'Brands',
colorByPoint: true,
data: result
}]
}
return(
<Chart options={options} />
)
}
export default PieChart;<file_sep>/docker-compose.yml
version: "3.7"
services:
frontend:
build: ./ # link to subfolder of mono-repo
command: node node_modules/.bin/gatsby develop -H 0.0.0.0 -p 3000
volumes:
- ./app
restart: "no"
ports:
- 3000:3000
# allows the frontend to access the backend at localhost, which allows Gatsby to access the api
# and the Api to include localhost:8000 (and not backend:8000) in the image paths.
<file_sep>/src/pages/404.js
import React from "react"
import Layout from "../components/layout"
import SEO from "../components/seo"
const NotFoundPage = () => (
<Layout>
<SEO title="404: Not found" />
<h1>Não Encontrado!</h1>
<p>Você escolheu uma rota que não existe... que triste D:</p>
</Layout>
)
export default NotFoundPage
<file_sep>/run.sh
#!/bin/bash
node node_modules/.bin/gatsby build
node node_modules/.bin/gatsby serve -H 0.0.0.0<file_sep>/src/domain/ListOperations.js
class ListOperations {
constructor(stockId) {
this._batch = [];
this._stockId = stockId;
}
push(operation) {
let date = operation.date;
if (this.batch.length > 0) {
let index = this.positionByDate(date, this.batch);
this.batch.splice(index, 0, operation);
} else {
this.batch.push(operation);
}
return this.batch;
}
positionByDate(date, batch) {
for (let i = 0; i < this.batch.length; i++) {
let elementDate = this.batch[i].date;
if (this.isMoreRecent(date, elementDate)) {
return i;
}
}
return this.batch.length;
}
isMoreRecent(value, last) {
if(value < last) {
return true;
}
return false;
}
get batch() {
return this._batch;
}
get stockId() {
return this._stockId;
}
}
export default ListOperations;<file_sep>/README.md
<br />
<p align="center">
<a href="https://github.com/othneildrew/Best-README-Template">
<img src="src/images/document-logo.png" alt="Logo" width="300" height="300">
</a>
<h3 align="center">Projeto Front-End MindMiners</h3>
<p align="center">
O IRCalc é uma calculadora de Imposto de Renda sobre operações de compra e venda na Bolsa de Valores.
<br />
<br />
<a href="https://github.com/isaacguerreiro/mindminers-project/issues">Reportar Bug</a>
·
<a href="https://github.com/isaacguerreiro/mindminers-project/issues">Requerir Feature</a>
</p>
</p>
## Índice
* [Sobre o projeto](#sobre-o-projeto)
* [Tecnologias](#tecnologias)
* [Começando](#começando)
* [Pré-requisitos](#pré-requisitos)
* [Instalação](#instalação)
* [Licença](#licença)
* [Contato](#contato)
## Sobre o projeto
O projeto da MindMiners é uma aplicação front-end que tem como principal funcionalidade calcular o Imposto de Renda sobre operações de compra e venda na Bolsa de Valores.
Além do cálculo foram adicionados ao projeto:
* Gráfico com informações de Lucro, Prejuízo, Imposto de Renda e Total Líquido das operações dividas por mês.
* Tabela com valores de imposto de renda calculado por operação.
* Possibilidade de exportar tabelas na forma de arquivo csv.
* Gráfico com o valor investido em reais (R$) em cada ação operada da Bolsa de Valores.
### Tecnologias
Para se enquadrar dentro dos padrões de qualidade exigidos pela MindMiners foram utilizadas tecnologias recentes para a construção da aplicação.
* [Gatsby](https://www.gatsbyjs.org/)
* [React](https://reactjs.org/)
* [Material-UI](https://material-ui.com/)
* [Highcharts](https://www.highcharts.com/)
## Começando
Para inicializar a aplicação é necessário alguns prerequisitos. Para subir localmente basta seguir alguns passos simples.
### Pré-requisitos
Para facilitar a inicialização o projeto foi utilizado Docker, uma tecnologia de abstração e virtualização de ambientes para software. Se você quiser saber se já tem docker e docker-compose instalados localmente basta rodar:
* docker
```sh
docker -v
```
* docker-compose
```sh
docker-compose -v
```
Caso um ou ambos não estejam instalados basta rodar um arquivo sh criado especialmente pra instalação das duas ferramentas. Para isso execute:
```sh
sudo bash install-docker.sh
```
### Instalação
1. Execute o comando
```sh
sudo docker-compose up --build
```
2. Assim que o container estiver rodando, acesse o link: <a href="localhost:3000">https://localhost:3000</a>
3. Após a primeira execução, basta usar o comando
```sh
sudo docker-compose up
```
## Licença
Distribuido sobre o MIT License. Veja o arquivo `LICENSE` para mais informações.
## Contato
<NAME> - <EMAIL>
Link do projeto: [https://github.com/isaacguerreir/mindminers-project](https://github.com/isaacguerreir/mindminers-project)
<file_sep>/src/__tests__/domain/listOperations.spec.js
import ListOperations from '../../domain/ListOperations';
import Operation from '../../domain/Operation';
describe("Using List of Operations object", () => {
it("Testing list with 1 operation", () => {
const operations = new ListOperations('PTR4');
const op1 = new Operation(new Date(2020, 1, 17), 'PTR4', 'BUY', 0, 0, 0);
expect(operations.batch).toEqual([]);
expect(operations.push(op1)).toEqual([op1]);
})
it("Testing list with 2 operations and different dates", () => {
const operations = new ListOperations('PTR4');
const op1 = new Operation(new Date(2020, 1, 17), 'PTR4', 'BUY', 0, 0, 0);
const op2 = new Operation(new Date(2020, 1, 15), 'PTR4', 'BUY', 0, 0, 0);
expect(operations.push(op1)).toEqual([op1]);
expect(operations.push(op2)).toEqual([op2, op1]);
})
it("Testing list with 4 operations to test if they organize the list by date", () => {
const operations = new ListOperations('PTR4');
const op1 = new Operation(new Date(2020, 1, 17), 'PTR4', 'BUY', 0, 0, 0);
const op2 = new Operation(new Date(2020, 1, 15), 'PTR4', 'BUY', 0, 0, 0);
const op3 = new Operation(new Date(2020, 1, 18), 'PTR4', 'BUY', 0, 0, 0);
const op4 = new Operation(new Date(2020, 1, 17), 'PTR4', 'BUY', 0, 0, 0);
expect(operations.push(op1)).toEqual([op1]);
expect(operations.push(op2)).toEqual([op2, op1]);
expect(operations.push(op3)).toEqual([op2, op1, op3]);
expect(operations.push(op4)).toEqual([op2, op1, op4, op3]);
})
})<file_sep>/Dockerfile
# base image
FROM node:11
# set working directory
RUN mkdir /app
WORKDIR /app
# add `/app/node_modules/.bin` to $PATH
ENV PATH /app/node_modules/.bin:$PATH
# install and cache app dependencies using yarn
ADD package.json yarn.lock /app/
RUN yarn --pure-lockfile
# Copy all frontend stuff to new "app" folder
COPY . /app/
CMD ["./run.sh"]
EXPOSE 9000<file_sep>/src/pages/operations.js
import React, { useState } from "react"
import MaterialTable from 'material-table'
import Layout from "../components/layout";
import Results from "../components/results";
import Operation from "../domain/Operation";
import ListStocks from "../domain/ListStocks";
import { TableIcons, Localization } from '../service/utils';
import Snackbar from '@material-ui/core/Snackbar';
import MuiAlert from '@material-ui/lab/Alert';
import IconButton from '@material-ui/core/IconButton';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import NumberFormat from 'react-number-format';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import InputLabel from '@material-ui/core/InputLabel';
import FormControl from '@material-ui/core/FormControl';
import DateFnsUtils from '@date-io/date-fns';
import {
MuiPickersUtilsProvider,
KeyboardDatePicker,
} from '@material-ui/pickers';
export default function OperationsPage() {
const [values, setValues] = useState({
stockId: 'PETR4',
type: 'BUY',
date: new Date(),
price: '10',
quantity: '10',
tax: '10',
operationList: [],
open: false,
results: false
})
const [stocks, setStocks] = useState(new ListStocks());
const [alert, setAlert] = useState(false);
const handleChange = (event) => {
setValues({
...values,
[event.target.name]: event.target.value,
});
};
const isValid = (inputOp) => {
if (inputOp.date === "Invalid Date" |
inputOp.stockId === "" |
inputOp.type === "" |
parseFloat(inputOp.price) === 0 |
parseFloat(inputOp.quantity) === 0) {
return false;
}
return true;
}
const addOperation = () => {
const inputOp = {
date: values.date,
stockId: values.stockId,
type: values.type,
price: values.price,
quantity: values.quantity,
tax: values.tax
}
if (isValid(inputOp)) {
const operation = new Operation(
inputOp.date,
inputOp.stockId,
inputOp.type,
parseFloat(inputOp.price).toFixed(2),
parseFloat(inputOp.quantity).toFixed(2),
parseFloat(inputOp.tax).toFixed(2)
);
let operationListUpdated = values.operationList;
operationListUpdated.push(operation);
handleOperationListChange(operationListUpdated);
const copy = stocks;
copy.addOperationByStockId(operation);
setStocks(copy);
handleClose();
} else {
handleAlertClick();
}
}
const goToResults = () => {
handleChange({
target: {
name: 'results',
value: true
}
})
}
const returnToResults = () => {
handleChange({
target: {
name: 'results',
value: false
}
})
}
const updateBeforeDelete = (list) => {
handleOperationListChange(list);
const copy = stocks;
copy.stocks = [];
list.forEach(function(operation) {
copy.addOperationByStockId(operation);
})
setStocks(copy);
handleDateChange(new Date());
}
const handleOperationListChange = (value) => {
handleChange({
target: {
name: 'operationList',
value: value
}
});
}
const handleAlertClick = () => {
setAlert(true);
};
const handleAlertClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setAlert(false);
};
const handleDateChange = (value) => {
handleChange({
target: {
name: 'date',
value: value
}
});
}
const handleClickOpen = () => {
handleChange({
target: {
name: 'open',
value: true
}
});
};
const handleClose = () => {
handleChange({
target: {
name: 'open',
value: false
}
});
};
const headerStyle = {
fontSize: '0.7rem',
padding: '1rem',
fontFamily: 'Karla'
}
const cellStyle = {
padding: '1rem',
fontFamily: 'Karla'
}
if (!values.results) {
return (
<Layout>
<div style={styles.descriptionText}>
O IRCalc realiza o cálculo das suas operações na Bolsa dividas por mês e por ação.
Adicione as operações na bolsa clicando no botão <b>ADICIONAR OPERAÇÃO</b>.
Preencha os dados com cuidado, revise e por fim, aperte em <b>CALCULAR IMPOSTO DE RENDA</b>.
</div>
<div style={styles.addOperation.box}>
<Button style={styles.addOperation.button} size="large" variant="outlined" onClick={handleClickOpen}>
Adicionar Operação
</Button>
</div>
<div style={styles.table.box}>
<MaterialTable
icons={TableIcons}
columns={[
{ title: 'Nome da ação', headerStyle: headerStyle, cellStyle: cellStyle, field: 'stockId' },
{ title: 'Tipo de operação', headerStyle: headerStyle, cellStyle: cellStyle, field: 'type', lookup: { BUY: 'Compra', SELL: 'Venda' } },
{ title: 'Data da operação', headerStyle: headerStyle, cellStyle: cellStyle, field: 'date', type: 'date' },
{ title: 'Preço unitário', headerStyle: headerStyle, cellStyle: cellStyle, field: 'price'},
{ title: 'Quantidade de papéis', headerStyle: headerStyle, cellStyle: cellStyle, field: 'quantity'},
{ title: 'Taxa de corretagem', headerStyle: headerStyle, cellStyle: cellStyle, field: 'tax'}
]}
data={values.operationList}
editable={{
onRowDelete: oldData =>
new Promise((resolve, reject) => {
setTimeout(() => {
{
let data = values.operationList;
const index = data.indexOf(oldData);
data.splice(index, 1);
updateBeforeDelete(data, () => resolve());
}
resolve()
}, 1000)
}),
}}
title="Lista de operações"
localization={Localization}
option={styles.table.options}
/>
</div>
<div style={styles.calculateIR.box}>
<Button style={styles.calculateIR.button} size="large" variant="outlined" onClick={goToResults}>
Calcular Imposto de Renda
</Button>
</div>
<Card style={styles.card.box} variant="outlined">
<CardContent style={styles.card.content}>
Dicas para adicionar operações:
<ul>
<li>Aplique ponto (.) como separador decimal;</li>
<li>Caso queira deletar a operação adicionada, aperte no botão com o ícone de lixeira;</li>
<li>Por padrão, ficarão em exibição as cinco (5) PRIMEIRAS adições de operação. Caso queira ver mais que cinco (5), aperte em "5 linhas" e escolha a quantidade de sua preferência;</li>
</ul>
</CardContent>
</Card>
<Dialog open={values.open} onClose={handleClose} aria-labelledby="form-dialog-title">
<DialogTitle id="form-dialog-title">Adicionar Operação</DialogTitle>
<DialogContent style={styles.dialog.box}>
<TextField
fullWidth
required
id="stockId"
name="stockId"
label="Nome da ação. Ex: PETR4, VALE5"
type="text"
value={values.stockId}
onChange={handleChange}
/>
<FormControl style={styles.dialog.selectType} fullWidth required>
<InputLabel id="operation-type">Tipo de operação</InputLabel>
<Select
fullWidth
name="type"
labelId="operation-type"
value={values.type}
onChange={handleChange}
>
<MenuItem value={`BUY`}>Compra</MenuItem>
<MenuItem value={`SELL`}>Venda</MenuItem>
</Select>
</FormControl>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
style={styles.dialog.date}
required
disableToolbar
variant="inline"
format="dd/MM/yyyy"
margin="normal"
label="Data da operação"
helperText=""
name="date"
value={values.date}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
</MuiPickersUtilsProvider>
<TextField
fullWidth
required
label="Preço da operação"
name="price"
value={values.price}
onChange={handleChange}
InputProps={{
inputComponent: NumberFormatCustom,
}}
/>
<TextField
style={styles.dialog.quantity}
fullWidth
required
label="Quantidade"
name="quantity"
type="number"
value={values.quantity}
onChange={handleChange}
/>
<TextField
style={styles.dialog.tax}
fullWidth
required
label="Taxa de corretagem"
name="tax"
value={values.tax}
onChange={handleChange}
InputProps={{
inputComponent: NumberFormatCustom,
}}
/>
</DialogContent>
<DialogActions style={styles.dialog.actions}>
<Button onClick={handleClose} color="primary">Voltar</Button>
<Button onClick={addOperation} color="primary">Adicionar</Button>
</DialogActions>
</Dialog>
<Snackbar
anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
open={alert} autoHideDuration={6000} onClose={handleAlertClose}>
<Alert onClose={handleAlertClose} severity="error">
Erro no formulário! Todos os campos devem ser preenchidos e nenhum pode ser zero.
</Alert>
</Snackbar>
</Layout>
)
}
return (
<Layout>
<IconButton onClick={returnToResults}>
<ArrowBackIcon />
</IconButton>
<div style={{
display: 'flex',
justifyContent: 'center'
}}>
<h1>Visão Geral das Operações</h1>
</div>
<Results listStocks={stocks}/>
</Layout>
)
}
function Alert(props) {
return <MuiAlert elevation={6} variant="filled" {...props} />;
}
function NumberFormatCustom(props) {
const { inputRef, onChange, ...other } = props;
return (
<NumberFormat
{...other}
getInputRef={inputRef}
onValueChange={(values) => {
onChange({
target: {
name: props.name,
value: values.value,
},
});
}}
thousandSeparator
isNumericString
prefix="R$"
/>
);
}
const styles = {
descriptionText: {
fontFamily: `Rubik`,
fontSize: `0.92rem`,
textAlign: `justify`,
textJustify: `inter-word`
},
addOperation: {
box: {
display: `flex`,
flexDirection: `row-reverse`,
marginTop: `0.9rem`,
},
button: {
fontFamily: `Rubik`
}
},
table: {
box: {
marginTop: '1rem'
},
options: {
headerStyle: {
fontSize: '0.7rem',
padding: '1rem',
fontFamily: 'Karla'
},
rowStyle: {
padding: '1rem',
fontFamily: 'Karla'
}
}
},
calculateIR: {
box: {
display: `flex`,
flexDirection: `row-reverse`,
marginTop: `0.9rem`,
width: '100%'
},
button: {
fontFamily: `Rubik`
}
},
card: {
box: {
marginTop: '1rem'
},
content: {
fontFamily: 'Rubik',
fontSize: '0.7rem',
paddingBottom: 0
}
},
dialog: {
box: {
padding: '0px 24px'
},
selectType: {
marginTop: '0.5rem'
},
date: {
width: `100%`
},
quantity: {
marginTop: `0.5rem`
},
tax: {
marginTop: `0.5rem`
},
actions: {
padding: '24px 8px'
}
}
}<file_sep>/src/__tests__/service/calculator.spec.js
import {
calculateMedianPrice,
calculateMedianQuantity,
calculateAccumulatedLoss,
descountAccLoss,
calculateMeasuredResult,
calculateIR
} from '../../service/calculator';
import Operation from '../../domain/Operation';
describe("Using calculator", () => {
it("calculating median prices", () => {
expect(calculateMedianPrice(0.0, 0.0, 25.90, 100.0, 8.50)).toEqual(25.985);
expect(calculateMedianPrice(25.985, 100.0, 26.40, 200.0, 8.50)).toEqual(26.29);
expect(calculateMedianPrice(26.29, 300.0, 27.87, 100.0, 8.50)).toEqual(26.70625);
})
it("calculating median quantities", () => {
expect(calculateMedianQuantity(0, 100)).toEqual(100);
expect(calculateMedianQuantity(100, 200)).toEqual(300);
expect(calculateMedianQuantity(300, 100)).toEqual(400);
expect(calculateMedianQuantity(300, -100)).toEqual(200);
expect(calculateMedianQuantity(300, -300)).toEqual(0);
})
it("calculating descont from accumulated loss", () => {
expect(descountAccLoss(100.0, 50.0)).toEqual(50.0);
expect(descountAccLoss(122.5212, 122.5212)).toEqual(122.5212);
expect(descountAccLoss(213212313132132132132.5, 213212313132132132132.5)).toEqual(213212313132132132132.5);
expect(descountAccLoss(0.1264464655487895411, 0.1264464655487895411)).toEqual(0.1264464655487895411);
expect(descountAccLoss(25.0, 100.0)).toEqual(25.0);
})
it("calculating accumulated losses", () => {
expect(calculateAccumulatedLoss(0, 26.125)).toEqual(26.125);
expect(calculateAccumulatedLoss(100.0, 50.0)).toEqual(0);
expect(calculateAccumulatedLoss(100.0, 76.0)).toEqual(0);
expect(calculateAccumulatedLoss(13.0, 24.0)).toEqual(11.0);
})
it("calculating measured results", () => {
expect(calculateMeasuredResult(26.70625, 26.53, 100.0, 8.50)).toEqual(-26.125);
})
it("calculating IR based on a list of operations", () => {
const op1 = new Operation(new Date, 'PTR4', 'BUY', 25.90, 100.0, 8.50);
const op2 = new Operation(new Date, 'PTR4', 'BUY', 26.40, 200.0, 8.50);
const op3 = new Operation(new Date, 'PTR4', 'BUY', 27.87, 100.0, 8.50);
const op4 = new Operation(new Date, 'PTR4', 'SELL', 26.53, 100.0, 8.50);
const op5 = new Operation(new Date, 'PTR4', 'SELL', 27.39, 100.0, 8.50);
const buyRes = {
ir: 0,
profit: 0,
loss: 0
}
expect(calculateIR([op1])).toEqual([buyRes]);
expect(calculateIR([op1, op2])).toEqual([buyRes, buyRes]);
expect(calculateIR([op1, op2, op3])).toEqual([buyRes, buyRes, buyRes]);
expect(calculateIR([op1, op2, op3, op4])).toEqual([buyRes, buyRes, buyRes, {
ir: 0,
profit: 0,
loss: 26.125
}]);
expect(calculateIR([op1, op2, op3, op4, op5])).toEqual([buyRes, buyRes, buyRes, {
ir: 0,
profit: 0,
loss: 26.125
}, {
ir: 5.0625,
profit: 59.875,
loss: 0.0
}]);
})
})<file_sep>/src/components/columnChart.js
import React from 'react';
import Chart from './chart';
import { totalIR, totalLoss, totalProfit, totalLiquid } from '../service/calculator';
const ColumnChart = ({data}) => {
const returnMonthByNumber = (number) => {
var months = {
0: 'Janeiro',
1: 'Fevereiro',
2: 'Março',
3: 'Abril',
4: 'Maio',
5: 'Junho',
6: 'Julho',
7: 'Agosto',
8: 'Setembro',
9: 'Outubro',
10: 'Novembro',
11: 'Dezembro',
}
return months[number];
}
const createCategories = (data) => {
const categories = data.map((obj) => {
return returnMonthByNumber(obj.month);
});
return [categories];
}
const createSeries = (data) => {
const ir = data.map((obj) => {
return totalIR(obj.result)
});
const loss = data.map((obj) => {
return totalLoss(obj.result)
});
const profit = data.map((obj) => {
return totalProfit(obj.result)
});
const total = data.map((obj) => {
return totalLiquid(obj.result)
});
const series = [
{
name: 'IR Total',
data: ir
},
{
name: '<NAME>',
data: profit
},
{
name: 'Prejuízo Total',
data: loss
},
{
name: 'Total Líquido',
data: total
},
]
return series;
}
const options = {
chart: {
type: 'column'
},
title: {
text: 'Composição atual de ações'
},
tooltip: {
formatter: function() {
var s;
if (this.point.name) { // the pie chart
s = this.point.name +' R$'+ this.y.toFixed(2);
} else {
s = this.series.name + ': R$' + this.y.toFixed(2);
}
return s;
}
},
xAxis: {
categories: createCategories(data)
},
credits: {
enabled: false
},
series: createSeries(data)
}
return (
<Chart options={options} />
)
}
export default ColumnChart;
|
52c406e0bad8f72bb6ff6c08e9e31828c8739b87
|
[
"YAML",
"JavaScript",
"Markdown",
"Dockerfile",
"Shell"
] | 15 |
JavaScript
|
isaacguerreir/mindminers-project
|
96b982b66b682c351a5e191e5fa27da1f37d8d0d
|
e47061713506b1fae39459905aadccb8bc4c97eb
|
refs/heads/master
|
<repo_name>topalov909/list_with_numbers<file_sep>/script.js
Ar = [];
var i = 0;
do {
user_answer = +prompt('Введите количество натуральных чисел:');
}
while (user_answer<=0);
function add_items_to_list(n)
{
for (i; i<n; i++)
{
Ar[i]=i+1;
}
}
add_items_to_list(user_answer);
document.write(Ar.join('<br>'));
|
ab8d9364148184b4928ade3bc378987284c7aa44
|
[
"JavaScript"
] | 1 |
JavaScript
|
topalov909/list_with_numbers
|
0c583cc8c7547ddd07b27ef1818495ec310fb559
|
ec2e7b07e7d826b609442cca3cc27ae42a1ad483
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _06.BinaryToHexadecimal
{
class BinaryToHexadecimal
{
static void Main(string[] args)
{
//Write a program to convert binary numbers to hexadecimal numbers (directly)
Console.WriteLine("Enter binary number: ");
string binaryNumber = Console.ReadLine();
string result = string.Empty;
if (binaryNumber.Length % 4 != 0)
{
binaryNumber = new string('0', 4 - binaryNumber.Length%4) + binaryNumber;
}
for (int i = 0; i < binaryNumber.Length; i += 4)
{
string hexDigit = binaryNumber.Substring(i, 4);
switch (hexDigit)
{
case "0000":
result = result + "0";
break;
case "0001":
result = result + "1";
break;
case "0010":
result = result + "2";
break;
case "0011":
result = result + "3";
break;
case "0100":
result = result + "4";
break;
case "0101":
result = result + "5";
break;
case "0110":
result = result + "6";
break;
case "0111":
result = result + "7";
break;
case "1000":
result = result + "8";
break;
case "1001":
result = result + "9";
break;
case "1010":
result = result + "A";
break;
case "1011":
result = result + "B";
break;
case "1100":
result = result + "C";
break;
case "1101":
result = result + "D";
break;
case "1110":
result = result + "E";
break;
case "1111":
result = result + "F";
break;
default:
Console.WriteLine("Invalid number");
break;
}
}
Console.WriteLine("Hex number = {0}.", result);
}
}
}
<file_sep>using System;
namespace _02.BinaryToDecimal
{
class BinaryToDecimal
{
static void Main(string[] args)
{
//Write a program to convert binary numbers to their decimal representation.
Console.WriteLine("Enter binary number:");
string binaryNumber = Console.ReadLine();
int binary = int.Parse(binaryNumber);
double result = 0;
int lastDigit = 0;
for (int i = 0; i < binaryNumber.Length; i++)
{
lastDigit = binary % 10;
result = result + lastDigit * (Math.Pow(2, i));
binary = binary / 10;
}
Console.WriteLine("Decimal number = {0}", result);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03.DecimalToHexadecimal
{
class DecimalToHexadecimal
{
static void Main(string[] args)
{
//Write a program to convert decimal numbers to their hexadecimal representation.
Console.WriteLine("Enter decimal number: ");
int decimalNumber = int.Parse(Console.ReadLine());
int remainder = 0;
string result = "";
while (decimalNumber > 0)
{
remainder = decimalNumber % 16;
decimalNumber /= 16;
if (remainder < 10)
{
result = remainder.ToString() + result;
}
else if (remainder > 10)
{
switch (remainder)
{
case 10:
result = result + "A";
break;
case 11:
result = result + "B";
break;
case 12:
result = result + "C";
break;
case 13:
result = result + "D";
break;
case 14 :
result = result + "E";
break;
case 15:
result = result + "F";
break;
default:
result = result + "";
break;
}
}
}
Console.WriteLine("Hex number = {0}.", result);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04.HexadecimalToDecimal
{
class HexadecimalToDecimal
{
static void Main(string[] args)
{
//Write a program to convert hexadecimal numbers to their decimal representation.
Console.WriteLine("Enter hex number:");
string number = Console.ReadLine();
number = number.ToLower();
int result = 0;
int lastDigit = 0;
for (int i = number.Length - 1; i >= 0; i--)
{
if (Char.IsDigit(number[i]))
{
result += (int)((number[i] - '0') * Math.Pow(16, hexNumber.Length - i - 1));
result += (int)(lastDigit * Math.Pow(16, hexNumber.Length - i - 1));
}
else
{
switch (number[i])
{
case 'a':
result = result + 10;
break;
case 'b':
result = result + 11;
break;
case 'c':
result = result + 12;
break;
case 'd':
result = result + 13;
break;
case 'e':
result = result + 14;
break;
case 'f':
result = result + 15;
break;
default:
result = result + 0;
break;
}
result += (int)((number[i] - '0') * Math.Pow(16, hexNumber.Length - i - 1));
}
}
Console.WriteLine("Decimal number = {0}", result);
}
}
}
|
0222ad7f3246abf7612ca9026b2608205b43f3b3
|
[
"C#"
] | 4 |
C#
|
VDGone/Homework---NumeralSystems
|
5a2f0c29a99df5d75d385119146a5837fe1cbd89
|
7d85a731437a4be07d67148783c68a2a6e3bdd2b
|
refs/heads/caf-9.0
|
<file_sep>add_lunch_combo kaf_cedric-user
add_lunch_combo kaf_cedric-userdebug
add_lunch_combo kaf_cedric-eng
|
1132525c034ced283f0c1941875b901c4bb1401a
|
[
"Shell"
] | 1 |
Shell
|
Kalil-Devices/device_motorola_cedric
|
261d5c537f8ca1d7841198fd147dfd2b5d31f91e
|
998621fb16be720cc5ba5419f730ae8245d04577
|
refs/heads/master
|
<repo_name>gerAlvarez/TestXamarinMobileApp<file_sep>/Listar/Listar/MainPage.xaml.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Listar.Model;
namespace Listar
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
GetPhotos();
}
private async void GetPhotos()
{
HttpClient Client = new HttpClient();
string response = await Client.GetStringAsync("https://jsonplaceholder.typicode.com/photos"); // 5000! fotos
List<Photo> Photos = JsonConvert.DeserializeObject<List<Photo>>(response);
PhotosListView.ItemsSource = Photos;
}
}
}
<file_sep>/README.md
# Explicacion
La solución consiste de 3 proyectos:
1. Listar, un proyecto de C#. **Éste es el proyecto que nos importa y sobre el cual vamos a trabajar**.
2. Listar.Android, el proyecto para Android.
3. Listar.iOS, el proyecto para IOS.
4. Listar.UWP, el proyecto para [UWP](https://docs.microsoft.com/en-us/windows/uwp/get-started/universal-application-platform-guide) si hubiese tenido instaladas las bibliotecas adecuadas pero no las tenia asi que mala yuyu.
Los archivos que nos importan en éste proyecto (Listar a secas) son:
- MainPage.xaml que es la vista,
- MainPage.xaml.cs es la lógica y
- Photo.cs (dentro de la carpeta Model) es el modelo de datos.
## Las vistas
- se escriben en XAML.
- cada vista tiene un archivo CS con la logica asociado a ella.
- escribirlas es un poco laborioso pero puede ser una sensación mía por la falta de experiencia y conocimiento.
## La logica
- se escribe en C#.
## Dependencias
**JSon converter** o algo así de NewtonSoft. Lo necesitamos para formatear a JSon la cadena de texto que devuelve el api.
## Rendimiento
La aplicación demora 11 segundos en levantar una lista con 5000 registros.
|
2a9daa808f9359088e5845ca6e52196f5a434772
|
[
"Markdown",
"C#"
] | 2 |
C#
|
gerAlvarez/TestXamarinMobileApp
|
70d17f94e7f1f24864ca449044a21cfa6a38e8bf
|
a6d206fc962fe2ea52cdc3a59e526ee52f5a4ef1
|
refs/heads/main
|
<repo_name>nguyenthanhtrung1996/Products<file_sep>/scripts/dashboard.js
var arrProducts = ["Nokia","Nokia 1"];
function show(){
var tbody = document.getElementsByClassName('tbody');
tbody[0].innerHTML = arrProducts.map((item) => {
var index = arrProducts.indexOf(item);
return `<tr>
<td class="name-product">${item}</td>
<td><a href="#" class="btn btn-success" onclick = 'editItem(${index})'>Edit</a>
<a href="#" class="btn btn-danger" onclick = 'deleteItem(${index})'>Delete</a></td>
<tr>`
}).join('');
console.log(tbody[0].innerHTML);
}
function getValue(v){
return v.trim();
}
function checkValue(v,arr){
for (let value of arr) {
if(value.toLowerCase()== v.toLowerCase())
return true;
}
if(v.length == 0)
return true;
return false;
}
function addItem(){
// debugger;
var inputValue = document.getElementsByClassName('inputProducts')[0].value;
var inputProducts = getValue(inputValue);
// debugger;
if(arrProducts.indexOf(inputProducts) != -1 || checkValue(inputProducts,arrProducts)){
alert('Products is existing');
} else {
arrProducts.push(inputProducts);
show();
}
document.getElementsByClassName('inputProducts')[0].value = '';
}
var btnAdd = document.getElementsByClassName('add')[0];
btnAdd.addEventListener('click',addItem);
function keypressHandler(event,i,v){
var changeValue = event.target.value;
var nameProduct = getValue(changeValue);
if(arrProducts.indexOf(nameProduct) != -1 || checkValue(nameProduct,arrProducts)){
alert('Products is existing');
nameProduct = v;
} else {
arrProducts[i] = nameProduct;
show();
}
var inputNameProducts = document.getElementsByClassName('name-product')[i];
inputNameProducts.innerHTML = nameProduct;
}
function productChangeInput(i){
var inputNameProducts = document.getElementsByClassName('name-product')[i];
inputNameProducts.innerHTML = `<input type='text' onchange='keypressHandler(event,${i},"${inputNameProducts.innerHTML}")'>`;
console.log(inputNameProducts);
}
function editItem(i){
productChangeInput(i);
}
function deleteItem(i){
arrProducts.splice(i,1);
show();
}
function main(){
show();
}
main();
|
15fec83754eb9cb74d150aa1ce36be15557dcc01
|
[
"JavaScript"
] | 1 |
JavaScript
|
nguyenthanhtrung1996/Products
|
6f94d73371deb5935a4b4bc1a58cddc3e57ccc99
|
723a78f144e72e951101f9b9dd3c7a960f8fda5a
|
refs/heads/master
|
<file_sep># simpleAI
first python AI
<file_sep>import numpy as np
from NormalizingFunc import NormalizingFunc
training_data = np.array([[1,0,0],
[0,1,1],
[1,1,1],
[0,1,0]])
training_output = np.array([[1,0,1,0]]).T
weights = np.random.random((3,1)) * 2 - 1
for x in range(20000):
input_layer = training_data
output = NormalizingFunc.sigmoid(np.dot(input_layer, weights))
error = training_output - output
adjustments = error * NormalizingFunc.sigmoid_derivative(output)
weights += np.dot(input_layer.T, adjustments)
print(output)
<file_sep>import numpy as np
class NormalizingFunc:
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_derivative(x):
return x * (1-x)
|
2d17d91aa11fd4fc9af2ef4cd331e6ee9c0e3fe7
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
Runningsloths/simpleAI
|
b2b787663780023b0dcc61c44b691c12a05072e2
|
45c430f9173891344a071196fad76f0be158e646
|
refs/heads/master
|
<repo_name>albertyu1027/week-7-Train-Schedule<file_sep>/README.md
# week-7-Train-Schedule
Train Schedule HW
<file_sep>/train2.js
var config = {
apiKey: "<KEY>",
authDomain: "trainhw-cad24.firebaseapp.com",
databaseURL: "https://trainhw-cad24.firebaseio.com",
projectId: "trainhw-cad24",
storageBucket: "trainhw-cad24.appspot.com",
messagingSenderId: "134634576101"
};
firebase.initializeApp(config);
var database = firebase.database();
$("#add-train-btn").on("click", function(){
// Set form values to variables
var trainName = $("#train-name-input").val().trim();
var destination = $("#destination-input").val().trim();
var firstTrain = moment($("#first-train-input").val().trim(), "HH:mm").subtract(10, "years").format("X");
var frequency = $("#frequency-input").val().trim();
// Set form variable to trainInfo in order to push to Firebase
var trainInfo = {
name: trainName,
destination: destination,
firstTrain: firstTrain,
frequency: frequency
};
// pushing trainInfo to Firebase
database.ref().push(trainInfo);
alert("train added")
// clear text-boxes
$("#train-name-input").val("");
$("#destination-input").val("");
$("#first-train-input").val("");
$("#frequency-input").val("");
// stop refresh
return false;
});
database.ref().on("child_added", function(childSnapshot, prevChildKey){
console.log(childSnapshot.val());
// assign firebase variables to snapshots.
var fireName = childSnapshot.val().name;
var fireDestination = childSnapshot.val().destination;
var fireFrequency = childSnapshot.val().frequency;
var fireFirstTrain = childSnapshot.val().firstTrain;
var differenceTimes = moment().diff(moment.unix(fireFirstTrain), "minutes");
var remainder = moment().diff(moment.unix(fireFirstTrain), "minutes") % fireFrequency ;
var minutes = fireFrequency - remainder;
var arrival = moment().add(minutes, "m").format("hh:mm A");
// Append train data to table
$("#train-table > tbody").append("<tr><td>" + fireName + "</td><td>" + fireDestination + "</td><td>" + fireFrequency + "</td><td>" + arrival + "</td><td>" + minutes + "</td></tr>");
});
|
ab77dff2046a2b1a5f2c3c0a6fd25d7dc7223428
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
albertyu1027/week-7-Train-Schedule
|
47c893e8a0dbbba0431f3a0e9bca8be1302505f5
|
52b2ce08166de5f9cf65faeec161c715d5d2af96
|
refs/heads/master
|
<repo_name>atcheri/cvatsu<file_sep>/src/Perso/CVBundle/Controller/DefaultController.php
<?php
namespace Perso\CVBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller
{
public function indexAction()
{
return $this->render("PersoCVBundle:Default:index.html.twig");
}
public function choixlangueAction($langue = null)
{
// if($langue != null)
// {
// $this->get('request')->set('locale', $langue);
// }
$url = $this->container->get('request')->headers->get('referer');
if(empty($url)) {
$url = $this->container->get('router')->generate('PersoCVBundle_index');
}
return $this->redirect($url);
}
public function cvAction()
{
return $this->render("PersoCVBundle:Default:cv.html.twig");
}
public function voirprintpdfAction()
{
return $this->render("PersoCVBundle:Default:cv_pdf.html.twig");
}
public function cvpdfAction()
{
return $this->render("PersoCVBundle:Default:cv_pdf_style.html.twig");
}
// public function printpdfAction()
// {
// $html = $this->renderView('PersoCVBundle:Default:cv_pdf.html.twig');
// $filename = "ATSUHIRO_ENDO_CV_".strtoupper($this->getRequest()->getLocale());
// return new Response(
// $this->get('knp_snappy.pdf')->getOutputFromHtml($html),
// 200,
// array(
// 'Content-Type' => 'application/pdf',
// 'Content-Disposition' => 'attachment; filename="'.$filename.'.pdf"'
// )
// );
// }
/**
* @Route("/cv_printpdf")
*/
public function printpdfAction()
{
//creating html source
$html = $this->renderView('PersoCVBundle:Default:cv_pdf.html.twig');
$pdfGenerator = $this->get('spraed.pdf.generator');
$filename = "ATSUHIRO_ENDO_CV_".strtoupper($this->getRequest()->getLocale());
return new Response($pdfGenerator->generatePDF($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="'.$filename.'.pdf"'
)
);
}
}
<file_sep>/README.md
atsuhiro.cv
===========
|
a339f633b4b650af31247a4a534a73e4a5f94bb0
|
[
"Markdown",
"PHP"
] | 2 |
PHP
|
atcheri/cvatsu
|
16b2706564e19da5fa964a46bafb10d3d04b8b34
|
86d806602876044543a950e283395531bb0121cf
|
refs/heads/master
|
<repo_name>rexhomes/PreciselyAPIsSDK-NodeJS<file_sep>/api.ts
/**
* Precisely APIs
* Enhance & enrich your data, applications, business processes, and workflows with rich location, information, and identify APIs.
*
* OpenAPI spec version: 9.5.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import request = require('request');
import http = require('http');
import moment = require('moment');
import Promise = require('bluebird');
let defaultBasePath = 'https://api.precisely.com';
// ===============================================
// This file is autogenerated - Please do not edit
// ===============================================
/* tslint:disable:no-unused-variable */
export class oAuthCredInfo {
"access_token": string;
"tokenType": string;
"issuedAt": number;
"expiresIn": number;
"clientID": string;
"org": string;
}
export class AHJ {
'ahjType': string;
'ahjId': string;
'type': string;
'fccId': string;
'agency': string;
'phone': string;
'comments': string;
'coverage': Coverage;
'contactPerson': ContactPerson;
'mailingAddress': AHJmailingAddress;
}
export class AHJList {
'ahjs': Array<AHJ>;
}
export class AHJPlusPSAPResponse {
'ahjs': AHJList;
'psap': PSAPResponse;
'count': number;
}
export class AHJmailingAddress {
'formattedAddress': string;
'mainAddressLine': string;
'addressLastLine': string;
'placeName': string;
'areaName1': string;
'areaName2': string;
'areaName3': string;
'areaName4': string;
'postCode': string;
'postCodeExt': string;
'country': string;
'addressNumber': string;
'streetName': string;
'unitType': string;
'unitValue': string;
}
export class Accuracy {
'unit': string;
'value': string;
}
export class Address {
'objectId': string;
'displayName': string;
'streetSide': string;
'businessName': string;
'addressLine1': string;
'addressLine2': string;
'addressLine3': string;
'city': string;
'stateProvince': string;
'county': string;
'postalCode': string;
'latitude': string;
'longitude': string;
'status': string;
'urbanizationName': string;
'formattedAddress': string;
'mainAddressLine': string;
'addressLastLine': string;
'placeName': string;
'areaName1': string;
'areaName2': string;
'areaName3': string;
'areaName4': string;
'postCode': string;
'postCodeExt': string;
'country': string;
'addressNumber': string;
'streetName': string;
'unitType': string;
'unitValue': string;
}
export class AddressTime {
'timestamp': string;
'address': CommonAddress;
}
export class AddressType {
'value': string;
'description': string;
}
export class AddressesByBoundaryRequest {
'preferences': AddressesPreferences;
'geometry': CommonGeometry;
'geometryAsText': string;
'latitude': number;
'longitude': number;
'travelTime': string;
'travelTimeUnit': string;
'travelDistance': string;
'travelDistanceUnit': string;
'travelMode': string;
}
export class AddressesCount {
'totalAddressesFound': number;
}
export class AddressesDTO {
'pbKey': string;
'addressNumber': string;
'streetName': string;
'unitType': string;
'unitValue': string;
'type': AddressType;
'areaName1': string;
'areaName2': string;
'areaName3': string;
'areaName4': string;
'postCode': string;
'postCodeExt': string;
'country': string;
}
export class AddressesPreferences {
'maxCandidates': string;
'page': string;
}
export class AddressesResponse {
'page': string;
'candidates': string;
'addressList': Array<AddressesDTO>;
}
export class Age {
'range': string;
'value': number;
}
export class AgeTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class Area {
'unit': string;
'value': string;
}
export class AreaCodeInfo {
'companyName': string;
'ocn': string;
'ocnCategory': string;
'npa': string;
'nxx': string;
'startRange': string;
'endRange': string;
'lata': string;
'areaName4': string;
}
export class AssetsAndWealthTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariableV2>;
'rangeVariable': Array<RangeVariableV2>;
}
export class AttitudesAndMotivationTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class AutomobileTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class BaseFloodElevation {
'unit': string;
'value': string;
}
export class BasicBoundary {
'center': BoundaryPoint;
'geometry': PolygonGeometry;
'distance': Distance;
}
export class BasicBoundaryAddress {
'center': BoundaryPoint;
'geometry': PolygonGeometry;
'matchedAddress': MatchedAddress;
'distance': Distance;
}
export class Boundaries {
'boundary': Array<Boundary>;
}
export class Boundary {
'boundaryId': string;
'boundaryType': string;
'boundaryRef': string;
}
export class BoundaryBuffer {
'bufferRelation': BufferRelation;
'distanceToBorder': DistanceToBorder;
}
export class BoundaryPoint {
'type': string;
'coordinates': Array<number>;
}
export class BufferRelation {
'description': string;
'value': string;
}
export class Candidate {
'precisionLevel': number;
'formattedStreetAddress': string;
'formattedLocationAddress': string;
'identifier': string;
'precisionCode': string;
'sourceDictionary': string;
'matching': FieldsMatching;
'geometry': GeoPos;
'address': GeocodeAddress;
'ranges': Array<CandidateRange>;
}
export class CandidateRange {
'placeName': string;
'lowHouse': string;
'highHouse': string;
'side': CandidateRange.SideEnum;
'oddEvenIndicator': CandidateRange.OddEvenIndicatorEnum;
'units': Array<CandidateRangeUnit>;
'customValues': { [key: string]: any; };
}
export namespace CandidateRange {
export enum SideEnum {
UNKNOWN = <any> 'UNKNOWN',
LEFT = <any> 'LEFT',
RIGHT = <any> 'RIGHT',
BOTH = <any> 'BOTH'
}
export enum OddEvenIndicatorEnum {
UNKNOWN = <any> 'UNKNOWN',
BOTH = <any> 'BOTH',
ODD = <any> 'ODD',
EVEN = <any> 'EVEN',
IRREGULAR = <any> 'IRREGULAR'
}
}
export class CandidateRangeUnit {
'placeName': string;
'unitType': string;
'highUnitValue': string;
'lowUnitValue': string;
'customValues': { [key: string]: any; };
}
export class Carrier {
'asn': string;
'value': string;
}
export class CarrierRouteAddressRequest {
'addresses': Array<CommonAddress>;
'preferences': CarrierRoutePreference;
}
export class CarrierRouteBoundaries {
'boundary': Array<RouteBoundary>;
}
export class CarrierRoutePreference {
'includeGeometry': string;
'postCode': string;
}
export class CarrierRouteResponse {
'objectId': string;
'matchedAddress': MatchedAddress;
'code': string;
'state': CommonState;
'countyFips': string;
'postalTown': string;
'postCode': string;
'routeDelivery': RouteDelivery;
'boundary': RouteBoundary;
'boundaryRef': string;
}
export class CarrierRouteResponseList {
'boundaries': CarrierRouteBoundaries;
'carrierRoute': Array<CarrierRouteResponse>;
}
export class Category {
'categoryCode': string;
'tradeDivision': string;
'tradeGroup': string;
'subClass': string;
'class': string;
}
export class CategoryMetadata {
'code': string;
'sic': string;
'tradeDivision': string;
'tradeGroup': string;
'class': string;
'subClass': string;
'description': string;
}
export class Cbsa {
'name': string;
'code': string;
}
export class Census {
'cbsa': Cbsa;
'matchLevel': string;
'matchCode': string;
'tract': string;
'mcd': Mcd;
}
export class Center {
'type': string;
'coordinates': Array<number>;
}
export class ChannelPreferencesTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class City {
'confidence': string;
'value': string;
}
export class CommonAddress {
'objectId': string;
'mainAddressLine': string;
'addressLastLine': string;
'placeName': string;
'areaName1': string;
'areaName2': string;
'areaName3': string;
'areaName4': string;
'postCode': string;
'postCodeExt': string;
'country': string;
'addressNumber': string;
'streetName': string;
'unitType': string;
'unitValue': string;
}
export class CommonGeometry {
'type': string;
'coordinates': any;
}
export class CommonState {
'fips': string;
'code': string;
}
export class Community {
'number': string;
'status': Status;
}
export class CommuterPatternsTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class ConfiguredDictionaryResponse {
'dictionaries': Array<Dictionary>;
}
export class ConsistencyCode {
'description': string;
'value': string;
}
export class ContactDetails {
'address': MatchedAddress;
'propertyAddress': MatchedAddress;
}
export class ContactPerson {
'title': string;
'fullName': string;
'prefix': string;
'firstName': string;
'lastName': string;
'phone': string;
'fax': string;
'email': string;
'comments': string;
'additionalDetails': string;
}
export class Cost {
'cost': number;
'costUnit': string;
'geometry': DirectionGeometry;
}
export class Costs extends Array<Cost> {
}
export class CountrySupport {
'supportedCountries': Array<string>;
'supportedDataTypes': Array<string>;
}
export class County {
'name': string;
'fips': string;
}
export class Coverage {
'area': string;
'comments': string;
'exceptions': string;
}
export class CrimeBoundary {
'id': string;
'type': string;
'ref': string;
'geometry': GeoRiskGeometry;
}
export class CrimeIndexTheme {
'source': string;
'boundaryRef': string;
'indexVariable': Array<IndexVariable>;
}
export class CrimeRiskByAddressRequest {
'addresses': Array<RiskAddress>;
'preferences': CrimeRiskPreferences;
}
export class CrimeRiskByLocationRequest {
'locations': Array<GeoRiskLocations>;
'preferences': CrimeRiskPreferences;
}
export class CrimeRiskLocationResponse {
'themes': Array<GeoRiskCrimeTheme>;
'boundaries': GeoRiskBoundaries;
}
export class CrimeRiskLocationResponseList {
'crimeRisk': Array<CrimeRiskLocationResponse>;
}
export class CrimeRiskPreferences {
'includeGeometry': string;
'type': string;
}
export class CrimeRiskResponse {
'themes': Array<GeoRiskCrimeTheme>;
'boundaries': GeoRiskBoundaries;
'matchedAddress': MatchedAddress;
}
export class CrimeRiskResponseList {
'crimeRisk': Array<CrimeRiskResponse>;
}
export class Crs {
'type': string;
'properties': Properties;
}
export class CustomObject {
'name': string;
'description': string;
'properties': Array<CustomObjectMember>;
}
export class CustomObjectMember {
'name': string;
'input': InputParameter;
'output': OutputParameter;
}
export class CustomPreferences {
'fINDADDRPOINTINTERP': boolean;
'fINDSEARCHAREA': string;
'fINDADDRESSRANGE': boolean;
'fINDEXPANDEDSEARCHRADIUS': string;
'fINDALTERNATELOOKUP': string;
'fINDSTREETCENTROID': boolean;
'fINDFIRSTLETTEREXPANDED': boolean;
}
export class DateTimeEarthQuake {
'date': string;
'time': string;
}
export class Demographics {
'boundaries': Boundaries;
'themes': DemographicsThemesV2;
'boundaryThemes': Array<DemographicsThemesV2>;
}
export class DemographicsAdvancedPreferences {
'profile': string;
'filter': string;
'includeGeometry': string;
}
export class DemographicsAdvancedRequest {
'preferences': DemographicsAdvancedPreferences;
'geometry': CommonGeometry;
'geometryAsText': string;
}
export class DemographicsThemes {
'ageTheme': AgeTheme;
'genderTheme': GenderTheme;
'incomeTheme': IncomeTheme;
'raceTheme': RaceTheme;
'ethnicityTheme': EthnicityTheme;
'maritalStatusTheme': MaritalStatusTheme;
'automobileTheme': AutomobileTheme;
'purchasingBehaviorTheme': PurchasingBehaviorTheme;
'educationalAttainmentTheme': EducationalAttainmentTheme;
'financialProductsTheme': FinancialProductsTheme;
'commuterPatternsTheme': CommuterPatternsTheme;
'attitudesAndMotivationTheme': AttitudesAndMotivationTheme;
'channelPreferencesTheme': ChannelPreferencesTheme;
'householdSizeTheme': HouseholdSizeTheme;
}
export class DemographicsThemesV2 {
'boundaryId': string;
'populationTheme': PopulationTheme;
'raceAndEthnicityTheme': RaceAndEthnicityTheme;
'healthTheme': HealthTheme;
'educationTheme': EducationTheme;
'incomeTheme': IncomeThemeV2;
'assetsAndWealthTheme': AssetsAndWealthTheme;
'householdsTheme': HouseholdsTheme;
'housingTheme': HousingTheme;
'employmentTheme': EmploymentTheme;
'expenditureTheme': ExpenditureTheme;
'supplyAndDemandTheme': SupplyAndDemandTheme;
}
export class Depth {
'unit': string;
'value': number;
}
export class DeviceStatusNetwork {
'carrier': string;
'callType': string;
'locAccuracySupport': string;
'nationalNumber': string;
'country': GeoLocationFixedLineCountry;
}
export class Dictionary {
'vintage': string;
'source': string;
'description': string;
'countrySupportInfos': Array<CountrySupport>;
}
export class DirectionGeometry {
'type': string;
'coordinates': Array<Array<Array<Array<number>>>>;
}
export class Distance {
'unit': string;
'value': string;
}
export class DistanceToBorder {
'unit': string;
'value': string;
}
export class DistanceToFloodHazardAddressRequest {
'addresses': Array<RiskAddress>;
'preferences': FloodHazardPreferences;
}
export class DistanceToFloodHazardLocationRequest {
'locations': Array<GeoRiskLocations>;
'preferences': FloodHazardPreferences;
}
export class DistanceToFloodHazardLocationResponse {
'waterBodies': Array<WaterBodyLocationResponse>;
}
export class DistanceToFloodHazardResponse {
'waterBodies': Array<WaterBodyResponse>;
}
export class DistrictType {
'description': string;
'value': string;
}
export class DomesticUltimateBusiness {
'name': string;
'address': Address;
}
export class EarthquakeEvent {
'dateTime': DateTimeEarthQuake;
'seismicRegionNumber': number;
'depth': Depth;
'magnitude': Magnitude;
'cause': string;
'culturalEffect': string;
'intensity': number;
'diastrophism': string;
'miscPhenomena': string;
'location': EarthquakeLocation;
}
export class EarthquakeEventsResponse {
'event': Array<EarthquakeEvent>;
}
export class EarthquakeHistory {
'stateCode': string;
'county': string;
'postCode': string;
'events': EarthquakeEventsResponse;
}
export class EarthquakeLocation {
'type': string;
'coordinates': Array<number>;
}
export class EarthquakeRiskByAddressRequest {
'addresses': Array<RiskAddress>;
'preferences': EarthquakeRiskPreferences;
}
export class EarthquakeRiskByLocationRequest {
'locations': Array<GeoRiskLocations>;
'preferences': EarthquakeRiskPreferences;
}
export class EarthquakeRiskLocationResponse {
'riskLevel': string;
'eventsCount': EventsCount;
'grid': Grid;
}
export class EarthquakeRiskLocationResponseList {
'earthquakeRisk': Array<EarthquakeRiskLocationResponse>;
}
export class EarthquakeRiskPreferences {
'includeGeometry': string;
'richterValue': string;
}
export class EarthquakeRiskResponse {
'riskLevel': string;
'eventsCount': EventsCount;
'grid': Grid;
'matchedAddress': MatchedAddress;
}
export class EarthquakeRiskResponseList {
'earthquakeRisk': Array<EarthquakeRiskResponse>;
}
export class Education {
'name': string;
'degree': string;
'end': End;
}
export class EducationTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariableV2>;
'rangeVariable': Array<RangeVariableV2>;
}
export class EducationalAttainmentTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class Email {
'label': string;
'value': string;
'md5': string;
'sha256': string;
}
export class EmployeeCount {
'inLocalBranch': string;
'inOrganization': string;
}
export class Employment {
'name': string;
'current': boolean;
'title': string;
'start': Start;
'end': End;
}
export class EmploymentTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariableV2>;
'rangeVariable': Array<RangeVariableV2>;
}
export class End {
'year': number;
'month': number;
'day': number;
}
export class EthnicityTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class EventsCount {
'total': string;
'r0': string;
'r1': string;
'r2': string;
'r3': string;
'r4': string;
'r5': string;
'r6': string;
'r7': string;
'r0Ge': string;
'r1Ge': string;
'r2Ge': string;
'r3Ge': string;
'r4Ge': string;
'r5Ge': string;
'r6Ge': string;
'r7Ge': string;
}
export class ExpenditureTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariableV2>;
'rangeVariable': Array<RangeVariableV2>;
}
export class Field {
'value': string;
'description': string;
}
export class FieldV2 {
'value': string;
'name': string;
'description': string;
}
export class FieldsMatching {
'matchOnAddressNumber': boolean;
'matchOnPostCode1': boolean;
'matchOnPostCode2': boolean;
'matchOnAreaName1': boolean;
'matchOnAreaName2': boolean;
'matchOnAreaName3': boolean;
'matchOnAreaName4': boolean;
'matchOnAllStreetFields': boolean;
'matchOnStreetName': boolean;
'matchOnStreetType': boolean;
'matchOnStreetDirectional': boolean;
'matchOnPlaceName': boolean;
'matchOnInputFields': boolean;
}
export class FinancialProductsTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class FireDepartment {
'name': string;
'type': string;
'numberOfStations': number;
'administrativeOfficeOnly': boolean;
'contactDetails': FireDepartmentContactDetails;
}
export class FireDepartmentContactDetails {
'address': MatchedAddress;
'phone': string;
'fax': string;
}
export class FireEvent {
'fireStartDate': string;
'fireEndDate': string;
'fireName': string;
'area': Area;
'agency': string;
}
export class FireEventsResponse {
'event': Array<FireEvent>;
}
export class FireHistory {
'stateCode': string;
'postCode': string;
'events': FireEventsResponse;
}
export class FireRiskByAddressRequest {
'addresses': Array<RiskAddress>;
}
export class FireRiskByLocationRequest {
'locations': Array<GeoRiskLocations>;
}
export class FireRiskLocationResponse {
'objectId': string;
'state': CommonState;
'fireShed': FireShed;
}
export class FireRiskLocationResponseList {
'fireRisk': Array<FireRiskLocationResponse>;
}
export class FireRiskResponse {
'objectId': string;
'state': CommonState;
'fireShed': FireShed;
'matchedAddress': MatchedAddress;
}
export class FireRiskResponseList {
'fireRisk': Array<FireRiskResponse>;
}
export class FireShed {
'id': number;
'risk': Risk;
}
export class FireStation {
'numWithinDepartment': string;
'locationReference': string;
'travelDistance': Distance;
'travelTime': Time;
'contactDetails': FireStationContactDetails;
'fireDepartment': FireDepartment;
'geometry': Geometry;
}
export class FireStationContactDetails {
'address': MatchedAddress;
'phone': string;
}
export class FireStations {
'fireStation': Array<FireStation>;
'matchedAddress': MatchedAddress;
}
export class FireStationsLocation {
'fireStation': Array<FireStation>;
}
export class FloodBoundary {
'id': string;
'geometry': GeoRiskGeometry;
}
export class FloodHazardPreferences {
'searchDistanceUnit': string;
'searchDistance': string;
'waterBodyType': string;
'maxCandidates': string;
}
export class FloodRiskByAddressRequest {
'addresses': Array<RiskAddress>;
'preferences': FloodRiskPreferences;
}
export class FloodRiskByLocationRequest {
'locations': Array<GeoRiskLocations>;
'preferences': FloodRiskPreferences;
}
export class FloodRiskLocationResponse {
'objectId': string;
'state': CommonState;
'floodZone': FloodZone;
'community': Community;
'boundary': FloodBoundary;
}
export class FloodRiskLocationResponseList {
'floodRisk': Array<FloodRiskLocationResponse>;
}
export class FloodRiskPreferences {
'includeGeometry': string;
'includeZoneDesc': string;
}
export class FloodRiskResponse {
'objectId': string;
'state': CommonState;
'floodZone': FloodZone;
'community': Community;
'boundary': FloodBoundary;
'matchedAddress': MatchedAddress;
}
export class FloodRiskResponseList {
'floodRisk': Array<FloodRiskResponse>;
}
export class FloodZone {
'code': string;
'areaType': string;
'riskLevel': string;
'primaryZone': PrimaryZone;
'baseFloodElevation': BaseFloodElevation;
'additionalInfo': string;
}
export class FreeOrReducedPriceLunches {
'freeLunchesCount': string;
'reducedPriceLunchedCount': string;
'totalCount': string;
}
export class GenderTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class GeoEnrichMetadataResponse {
'sic': Array<SicMetadata>;
'category': Array<CategoryMetadata>;
}
export class GeoEnrichResponse {
'page': string;
'candidates': string;
'totalMatchingCandidates': string;
'poi': Array<POIPlaces>;
'matchedAddress': MatchedAddress;
}
export class GeoLocationAccessPoint {
'geometry': Geometry;
'accuracy': Accuracy;
}
export class GeoLocationCountry {
'code': string;
'confidence': string;
'value': string;
}
export class GeoLocationFixedLine {
'geometry': Geometry;
'accuracy': Accuracy;
'deviceId': string;
'country': GeoLocationFixedLineCountry;
}
export class GeoLocationFixedLineCountry {
'code': string;
'value': string;
}
export class GeoLocationIpAddr {
'geometry': Geometry;
'accuracy': Accuracy;
'ipInfo': IpInfo;
}
export class GeoLocationPlace {
'continent': string;
'country': GeoLocationCountry;
'consistencyCode': ConsistencyCode;
'region': string;
'state': GeoLocationState;
'city': City;
'postCode': string;
'postCodeConfidence': string;
}
export class GeoLocationState {
'confidence': string;
'value': string;
}
export class GeoPos {
'type': string;
'coordinates': Array<number>;
'crs': Crs;
}
export class GeoPostGeometry {
'type': string;
'coordinates': Array<Array<Array<Array<number>>>>;
}
export class GeoPropertyAddressRequest {
'addresses': Array<CommonAddress>;
}
export class GeoPropertyResponse {
'objectId': string;
'category': string;
'individualValueVariable': Array<IndividualValueVariable>;
'matchedAddress': MatchedAddress;
}
export class GeoPropertyResponses {
'propertyAttributes': Array<GeoPropertyResponse>;
}
export class GeoRiskBoundaries {
'boundary': Array<CrimeBoundary>;
}
export class GeoRiskCrimeTheme {
'crimeIndexTheme': CrimeIndexTheme;
}
export class GeoRiskGeometry {
'type': string;
'coordinates': Array<Array<Array<number>>>;
}
export class GeoRiskLocations {
'geometry': Geometry;
'objectId': string;
}
export class GeoRouteResponse {
'directionsStyle': string;
'distance': number;
'distanceUnit': string;
'language': string;
'timeUnit': string;
'time': number;
'geometry': RouteGeometry;
'routeDirections': RouteDirections;
}
export class GeoTaxLocations {
'geometry': Geometry;
'purchaseAmount': string;
'objectId': string;
}
export class GeoTaxRateLocations {
'geometry': Geometry;
'objectId': string;
}
export class GeoZoneGeometry {
'type': string;
'coordinates': Array<number>;
}
export class GeocodeAddress {
'mainAddressLine': string;
'addressLastLine': string;
'placeName': string;
'areaName1': string;
'areaName2': string;
'areaName3': string;
'areaName4': string;
'postCode1': string;
'postCode2': string;
'country': string;
'addressNumber': string;
'streetName': string;
'unitType': string;
'unitValue': string;
'customFields': { [key: string]: any; };
}
export class GeocodeCapabilitiesResponse {
'serviceName': string;
'serviceDescription': string;
'coreVersion': string;
'supportedCountries': Array<string>;
'supportedOperations': Array<Operation>;
'customObjects': Array<CustomObject>;
}
export class GeocodeCustomPreferences {
'fALLBACKTOWORLD': boolean;
'uSEADDRESSPOINTINTERPOLATION': boolean;
'uSECENTERLINEOFFSET': string;
'cENTERLINEOFFSET': string;
}
export class GeocodePreferences {
'returnAllCandidateInfo': boolean;
'fallbackToGeographic': boolean;
'fallbackToPostal': boolean;
'maxReturnedCandidates': string;
'streetOffset': string;
'cornerOffset': string;
'matchMode': string;
'clientLocale': string;
'clientCoordSysName': string;
'streetOffsetUnits': string;
'cornerOffsetUnits': string;
'mustMatchFields': FieldsMatching;
'returnFieldsDescriptor': ReturnFieldsDescriptor;
'outputRecordType': string;
'customPreferences': GeocodeCustomPreferences;
'preferredDictionaryOrders': Array<string>;
}
export class GeocodeRequest {
/**
* Type
*/
'type': string;
'preferences': GeocodePreferences;
'addresses': Array<GeocodeRequestAddress>;
}
export class GeocodeRequestAddress {
'mainAddressLine': string;
'addressLastLine': string;
'placeName': string;
'areaName1': string;
'areaName2': string;
'areaName3': string;
'areaName4': string;
'postCode1': string;
'postCode2': string;
'country': string;
'addressNumber': string;
'streetName': string;
'unitType': string;
'unitValue': string;
}
export class GeocodeServiceResponse {
'objectId': string;
'totalPossibleCandidates': number;
'totalMatches': number;
'candidates': Array<Candidate>;
}
export class GeocodeServiceResponseList {
'responses': Array<GeocodeServiceResponse>;
}
export class Geometry {
'type': string;
'coordinates': Array<number>;
}
export class GeosearchLocation {
'address': MatchedAddress;
'distance': Distance;
'geometry': Geometry;
'totalUnitCount': number;
'ranges': Array<TypeaheadRange>;
}
export class GeosearchLocations {
'location': Array<GeosearchLocation>;
}
export class GetCityStateProvinceAPIInput {
'row': Array<GetCityStateProvinceAPIInputRow>;
}
export class GetCityStateProvinceAPIInputRow {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* The validated ZIP Code or postal code.
*/
'postalCode': string;
}
export class GetCityStateProvinceAPIOptions {
/**
* Output VanityCity.
*/
'outputVanityCity': string;
/**
* PerformCanadianProcessing.
*/
'performCanadianProcessing': string;
/**
* MaximumResults.
*/
'maximumResults': string;
/**
* PerformUSProcessing.
*/
'performUSProcessing': string;
}
export class GetCityStateProvinceAPIOutput {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* The validated ZIP Code or postal code.
*/
'postalCode': string;
/**
* City
*/
'city': string;
/**
* City.Type
*/
'cityType': string;
/**
* The state or province.
*/
'stateProvince': string;
/**
* Reports the success or failure of the match attempt.
*/
'status': string;
/**
* Reason for failure, if there is one.
*/
'statusCode': string;
/**
* Description of the problem, if there is one.
*/
'statusDescription': string;
}
export class GetCityStateProvinceAPIRequest {
'options': GetCityStateProvinceAPIOptions;
'input': GetCityStateProvinceAPIInput;
}
export class GetCityStateProvinceAPIResponse {
'output': Array<GetCityStateProvinceAPIOutput>;
}
export class GetPostalCodesAPIInput {
'row': Array<GetPostalCodesAPIInputRow>;
}
export class GetPostalCodesAPIInputRow {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* The city name.
*/
'city': string;
/**
* The state or province.
*/
'stateProvince': string;
}
export class GetPostalCodesAPIOptions {
/**
* Output CityType.
*/
'outputCityType': string;
/**
* Output VanityCity.
*/
'outputVanityCity': string;
}
export class GetPostalCodesAPIOutput {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* The validated ZIP Code or postal code.
*/
'postalCode': string;
/**
* City.Type
*/
'cityType': string;
/**
* Reports the success or failure of the match attempt.
*/
'status': string;
/**
* Reason for failure, if there is one.
*/
'statusCode': string;
/**
* Description of the problem, if there is one.
*/
'statusDescription': string;
}
export class GetPostalCodesAPIRequest {
'options': GetPostalCodesAPIOptions;
'input': GetPostalCodesAPIInput;
}
export class GetPostalCodesAPIResponse {
'output': Array<GetPostalCodesAPIOutput>;
}
export class GlobalUltimateBusiness {
'name': string;
'address': Address;
}
export class GradeLevelsTaught {
'pk': string;
'kg': string;
'first': string;
'second': string;
'third': string;
'fourth': string;
'fifth': string;
'sixth': string;
'seventh': string;
'eighth': string;
'ninth': string;
'tenth': string;
'eleventh': string;
'twelfth': string;
}
export class Greatschools {
'gsId': string;
'url': string;
'rating': string;
}
export class Grid {
'code': string;
'geometry': GeoRiskGeometry;
}
export class HealthTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariableV2>;
'rangeVariable': Array<RangeVariableV2>;
}
export class HouseholdSizeTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class HouseholdsTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariableV2>;
'rangeVariable': Array<RangeVariableV2>;
}
export class HousingTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariableV2>;
'rangeVariable': Array<RangeVariableV2>;
}
export class IPDTaxByAddressBatchRequest {
'addresses': Array<TaxRateAddress>;
'preferences': Preferences;
}
export class IPDTaxJurisdiction {
'state': TaxState;
'county': TaxCounty;
'place': TaxPlace;
}
export class Identity {
'fullName': string;
'ageRange': string;
'gender': string;
'location': string;
'coreId': string;
'pbKey': string;
'details': IdentityDetail;
}
export class IdentityDemographics {
'maritalStatus': string;
'occupation': string;
}
export class IdentityDetail {
'name': IdentityName;
'age': Age;
'demographics': IdentityDemographics;
'photos': Array<Photo>;
'profiles': Profiles;
'urls': Array<Url>;
'education': Array<Education>;
'employment': Array<Employment>;
}
export class IdentityName {
'given': string;
'family': string;
}
export class IdentityResponse {
'identities': Array<Identity>;
}
export class IncomeTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class IncomeThemeV2 {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariableV2>;
'rangeVariable': Array<RangeVariableV2>;
}
export class IndexVariable {
'name': string;
'score': string;
'category': string;
'percentile': string;
'stateScore': string;
}
export class IndividualValueVariable {
'name': string;
'description': string;
'value': string;
}
export class IndividualValueVariableV2 {
'name': string;
'description': string;
'year': string;
'value': string;
}
export class InputParameter {
'name': string;
'description': string;
'type': string;
'defaultValue': string;
'lowBoundary': string;
'highBoundary': string;
'allowedValuesWithDescriptions': { [key: string]: any; };
}
export class Interest {
'name': string;
'id': string;
'affinity': string;
'parentIds': Array<string>;
'category': string;
}
export class Intersection {
'distance': Unit;
'driveTime': Unit;
'driveDistance': Unit;
'geometry': CommonGeometry;
'roads': Array<Road>;
}
export class IntersectionResponse {
'intersection': Array<Intersection>;
'matchedAddress': MatchedAddress;
}
export class IpInfo {
'ipAddress': string;
'proxy': Proxy;
'network': Network;
'place': GeoLocationPlace;
}
export class Ipd {
'id': string;
'districtName': string;
'districtType': DistrictType;
'taxCodeDescription': string;
'effectiveDate': string;
'expirationDate': string;
'boundaryBuffer': BoundaryBuffer;
'rates': Array<Rate>;
}
export class KeyLookupRequest {
'type': string;
'preferences': GeocodePreferences;
'keys': Array<Keys>;
}
export class Keys {
'objectId': string;
'country': string;
'value': string;
}
export class LatLongFields {
'matchCode': string;
'matchLevel': string;
'streetMatchCode': string;
'streetMatchLevel': string;
'geometry': Geometry;
}
export class LifeStyleTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class Location {
'label': string;
'city': string;
'region': string;
'regionCode': string;
'country': string;
'countryCode': string;
'formatted': string;
}
export class LocationTime {
'geometry': Geometry;
'objectId': string;
'timestamp': string;
}
export class Magnitude {
'value': number;
'scale': string;
'bodyWave': number;
'surfaceWave': number;
}
export class MaritalStatusTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class Match {
'confidence': string;
'percentGeocode': string;
'precisionLevel': string;
'locationCode': string;
'matchCode': string;
}
export class MatchedAddress {
'formattedAddress': string;
'mainAddressLine': string;
'addressLastLine': string;
'placeName': string;
'areaName1': string;
'areaName2': string;
'areaName3': string;
'areaName4': string;
'postCode': string;
'postCodeExt': string;
'country': string;
'addressNumber': string;
'streetName': string;
'unitType': string;
'unitValue': string;
}
export class Matrix {
'distance': number;
'distanceUnit': string;
'endPoint': StartEndPoint;
'startPoint': StartEndPoint;
'time': number;
'timeUnit': string;
}
export class Mcd {
'name': string;
'code': string;
}
export class Network {
'connectionFromHome': string;
'organization': string;
'carrier': Carrier;
'organizationType': OrganizationType;
'connectionType': string;
'lineSpeed': string;
'ipRouteType': string;
'hostingFacility': string;
}
export class Operation {
'name': string;
'requiredInputs': Array<InputParameter>;
'optionalInputs': Array<InputParameter>;
'outputs': Array<OutputParameter>;
'supportLevels': Array<SupportLevel>;
}
export class OrganizationType {
'naicsCode': string;
'isicCode': string;
'value': string;
}
export class OutputParameter {
'name': string;
'description': string;
'type': string;
}
export class PBKeyAddressRequest {
'addresses': Array<CommonAddress>;
}
export class PBKeyResponse {
'key': string;
'matchedAddress': MatchedAddress;
}
export class PBKeyResponseList {
'pbkey': Array<PbKey>;
}
export class POIBoundaryAddressRequest {
'addresses': Array<CommonAddress>;
'preferences': PoiBoundaryPreferences;
}
export class POIBoundaryLocationRequest {
'locations': Array<POIBoundaryLocations>;
'preferences': PoiBoundaryPreferences;
}
export class POIBoundaryLocations {
'geometry': Geometry;
'objectId': string;
}
export class POIBoundaryResponse {
'poiBoundary': Array<PoiBoundary>;
}
export class POIByGeometryRequest {
'name': string;
'type': string;
'categoryCode': string;
'sicCode': string;
'maxCandidates': string;
'fuzzyOnName': string;
'page': string;
'geometry': CommonGeometry;
'geometryAsText': string;
}
export class POIPlaces {
'id': string;
'name': string;
'brandName': string;
'tradeName': string;
'franchiseName': string;
'open24Hours': string;
'distance': Distance;
'relevanceScore': string;
'contactDetails': PoiContactDetails;
'poiClassification': PoiClassification;
'salesVolume': Array<SalesVolume>;
'employeeCount': EmployeeCount;
'yearStart': string;
'goodsAgentCode': string;
'goodsAgentCodeDescription': string;
'legalStatusCode': string;
'organizationStatusCode': string;
'organizationStatusCodeDescription': string;
'subsidaryIndicator': string;
'subsidaryIndicatorDescription': string;
'parentBusiness': ParentBusiness;
'domesticUltimateBusiness': DomesticUltimateBusiness;
'globalUltimateIndicator': string;
'globalUltimateBusiness': GlobalUltimateBusiness;
'familyMembers': string;
'hierarchyCode': string;
'tickerSymbol': string;
'exchangeName': string;
'geometry': Geometry;
}
export class PSAPResponse {
'psapId': string;
'fccId': string;
'type': string;
'count': number;
'agency': string;
'phone': string;
'county': County;
'coverage': Coverage;
'contactPerson': ContactPerson;
'siteDetails': SiteDetails;
'mailingAddress': MatchedAddress;
}
export class Parcel {
'id': string;
'censusCode': string;
'pbkey': string;
'address': MatchedAddress;
}
export class ParcelBoundary {
'objectId': string;
'apn': string;
'pid': string;
'center': Center;
'countyfips': string;
'geometry': CommonGeometry;
'parcelList': Array<Parcel>;
'adjacentParcelBoundary': Array<ParcelBoundary>;
'matchedAddress': MatchedAddress;
}
export class ParentBusiness {
'name': string;
'address': Address;
}
export class PbKey {
'objectId': string;
'key': string;
'matchedAddress': MatchedAddress;
}
export class PhoneVerification {
'phoneNumber': string;
'locatable': string;
'network': DeviceStatusNetwork;
'privacyConsentRequired': string;
}
export class Photo {
'label': string;
'value': string;
}
export class PlaceByLocations {
'location': Array<PlaceByLocationsLocation>;
}
export class PlaceByLocationsLocation {
'place': PlaceLocation;
}
export class PlaceLocation {
'level': string;
'levelName': string;
'name': Array<PlaceLocationName>;
}
export class PlaceLocationName {
'langType': string;
'langISOCode': string;
'value': string;
}
export class Poi {
'id': string;
'name': string;
'brandName': string;
'tradeName': string;
'franchiseName': string;
'open24Hours': string;
'contactDetails': ContactDetails;
'poiClassification': PoiClassification;
'employeeCount': EmployeeCount;
'organizationStatusCode': string;
'organizationStatusCodeDescription': string;
'parentBusiness': ParentBusiness;
'tickerSymbol': string;
'exchangeName': string;
}
export class PoiBoundary {
'objectId': string;
'center': GeoZoneGeometry;
'countyfips': string;
'geometry': CommonGeometry;
'poiList': Array<Poi>;
'matchedAddress': MatchedAddress;
'id': string;
}
export class PoiBoundaryPreferences {
'categoryCode': string;
'sicCode': string;
'naicsCode': string;
}
export class PoiClassification {
'sic': Sic;
'category': Category;
'alternateIndustryCode': string;
}
export class PoiContactDetails {
'address': Address;
'phone': string;
'fax': string;
'countryAccessCode': string;
'email': string;
'url': string;
}
export class PoiCount {
'totalPoisFound': number;
}
export class PoiCountRequest {
'name': string;
'type': string;
'categoryCode': string;
'sicCode': string;
'fuzzyOnName': string;
'geometry': CommonGeometry;
'geometryAsText': string;
}
export class Points {
'objectId': string;
'country': string;
'geometry': GeoPos;
}
export class Pois {
'page': string;
'candidates': string;
'totalMatchingCandidates': string;
'poi': Array<Poi>;
'matchedAddress': MatchedAddress;
}
export class PolygonGeometry {
'type': string;
'coordinates': Array<Array<Array<number>>>;
}
export class PopulationTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariableV2>;
'rangeVariable': Array<RangeVariableV2>;
}
export class PreferencTimeZone {
'matchMode': string;
}
export class Preferences {
'fallbackToGeographic': string;
'useGeoTaxAuxiliaryFile': string;
'matchMode': string;
'latLongOffset': string;
'squeeze': string;
'latLongFormat': string;
'defaultBufferWidth': string;
'distanceUnits': string;
'outputCasing': string;
'returnCensusFields': string;
'returnLatLongFields': string;
'customPreferences': CustomPreferences;
}
export class PrimaryZone {
'code': string;
'description': string;
}
export class Profile {
'username': string;
'userid': string;
'url': string;
'bio': string;
'service': string;
'followers': number;
'following': number;
}
export class Profiles {
'twitter': Profile;
'linkedin': Profile;
}
export class Properties {
'name': string;
}
export class Proxy {
'anonymizerStatus': string;
'level': string;
'lastDetected': string;
'type': string;
}
export class PurchasingBehaviorTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class RaceAndEthnicityTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariableV2>;
'rangeVariable': Array<RangeVariableV2>;
}
export class RaceTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariable>;
'rangeVariable': Array<RangeVariable>;
}
export class RangeVariable {
'count': string;
'order': string;
'name': string;
'description': string;
'field': Array<Field>;
}
export class RangeVariableV2 {
'count': string;
'order': string;
'name': string;
'alias': string;
'description': string;
'baseVariable': string;
'year': string;
'field': Array<FieldV2>;
}
export class Rate {
'name': string;
'format': string;
'formatDescription': string;
'value': string;
}
export class RateCenterResponse {
'id': string;
'name': string;
'alternateName': string;
'areaName1': string;
'geometry': Geometry;
'areaCodeInfoList': Array<AreaCodeInfo>;
'matchedAddress': MatchedAddress;
'match': Match;
'county': County;
'count': number;
'productCode': string;
}
export class ReturnFieldsDescriptor {
'returnAllCustomFields': boolean;
'returnMatchDescriptor': boolean;
'returnStreetAddressFields': boolean;
'returnUnitInformation': boolean;
'returnedCustomFieldKeys': Array<string>;
}
export class ReverseGeocodeRequest {
'preferences': Preferences;
'points': Array<Points>;
}
export class Risk {
'type': string;
'description': string;
'risk50Rating': number;
'frequency': number;
'nonburn': string;
'pastFires': number;
'severity': number;
'continuity': string;
'adjustment': string;
'aspect': string;
'crownFire': string;
'vegetation': string;
'foehn': string;
'golfCourse': string;
'roadDist': string;
'slope': string;
'waterDist': string;
'tier': string;
'tierDescription': string;
'distanceToFireStation': number;
}
export class RiskAddress {
'objectId': string;
'formattedAddress': string;
'mainAddressLine': string;
'addressLastLine': string;
'placeName': string;
'areaName1': string;
'areaName2': string;
'areaName3': string;
'areaName4': string;
'postCode': string;
'postCodeExt': string;
'country': string;
'addressNumber': string;
'streetName': string;
'unitType': string;
'unitValue': string;
}
export class Road {
'roadClass': string;
'name': string;
'type': string;
}
export class RouteBoundary {
'id': string;
'type': string;
'ref': string;
'geometry': GeoPostGeometry;
}
export class RouteDelivery {
'individualValueVariable': Array<IndividualValueVariable>;
}
export class RouteDirection {
'distance': number;
'distanceUnit': string;
'timeUnit': string;
'time': number;
'instruction': string;
'directionGeometry': RouteGeometry;
}
export class RouteDirections extends Array<RouteDirection> {
}
export class RouteGeometry {
'type': string;
'coordinates': Array<Array<number>>;
}
export class SalesTax {
'totalTax': number;
'totalTaxRate': number;
'totalTaxAmount': number;
'stateTax': number;
'stateTaxRate': number;
'stateTaxAmount': number;
'countyTax': number;
'countyTaxRate': number;
'countyTaxAmount': number;
'municipalTax': number;
'municipalTaxRate': number;
'municipalTaxAmount': number;
'spdsTax': Array<SpecialPurposeDistrictTaxRate>;
'specialTaxRulesApplied': boolean;
'specialTaxRulesDescriptor': string;
}
export class SalesTaxRate {
'totalTaxRate': number;
'stateTaxRate': number;
'countyTaxRate': number;
'municipalTaxRate': number;
'spdsTax': Array<SpecialPurposeDistrictTaxRate>;
}
export class SalesVolume {
'currencyCode': string;
'worldBaseCurrencyCode': string;
'value': string;
}
export class School {
'id': string;
'name': string;
'assigned': string;
'phone': string;
'website': string;
'addressType': string;
'address': Address;
'lowestGrade': string;
'highestGrade': string;
'schoolType': string;
'schoolTypeDesc': string;
'schoolSubType': string;
'schoolSubTypeDesc': string;
'gender': string;
'genderDesc': string;
'educationLevel': string;
'educationLevelDesc': string;
'greatschools': Greatschools;
'ncesSchoolId': string;
'ncesDistrictId': string;
'ncesDataYear': string;
'schoolRanking': Array<SchoolRanking>;
'students': string;
'teachers': string;
'status': string;
'studentTeacherRatio': string;
'choice': string;
'coextensiv': string;
'schoolDistricts': SchoolDistrict;
'schoolProfile': SchoolProfile;
'gradeLevelsTaught': GradeLevelsTaught;
'distance': Distance;
'geometry': Geometry;
}
export class SchoolDistrict {
'ncesDistrictId': string;
'name': string;
'totalSchools': string;
'districtType': string;
'metro': string;
'areaInSqM': string;
'supervisoryUnionId': string;
'districtEnrollment': string;
'districtUrl': string;
}
export class SchoolProfile {
'blueRibbon': string;
'internationalBaccalaureate': string;
'titleI': string;
'expensePerStudent': string;
'studentBelowPovertyPct': string;
'advancePlacementClasses': string;
'freeOrReducedPriceLunches': FreeOrReducedPriceLunches;
'studentEthnicity': StudentEthnicity;
}
export class SchoolRanking {
'current': string;
'rankYear': string;
'stateRank': string;
'numberOfSchools': string;
'avgMathScore': string;
'avgReadingScore': string;
'statePercentileScore': string;
}
export class SchoolsNearByResponse {
'matchedAddress': Address;
'school': Array<School>;
}
export class Segmentation {
'boundaries': Boundaries;
'themes': SegmentationThemes;
}
export class SegmentationThemes {
'lifeStyleTheme': LifeStyleTheme;
}
export class ShoreLineDistance {
'unit': string;
'value': string;
}
export class Sic {
'businessLine': string;
'sicCode': string;
'sicCodeDescription': string;
'primarySicCode': string;
'secondarySicCode': string;
}
export class SicMetadata {
'code': string;
'categoryCode': string;
'tradeDivision': string;
'tradeGroup': string;
'class': string;
'subClass': string;
'description': string;
}
export class SiteDetails {
'phone': string;
'fax': string;
'contactName': string;
'email': string;
'address': MatchedAddress;
}
export class SpecialPurposeDistrict {
'districtName': string;
'districtCode': string;
'districtNumber': string;
'versionDate': string;
'effectiveDate': string;
'compiledDate': string;
'updateDate': string;
}
export class SpecialPurposeDistrictTax {
'districtNumber': string;
'taxRate': number;
'taxAmount': number;
}
export class SpecialPurposeDistrictTaxRate {
'districtNumber': string;
'taxRate': number;
'taxAmount': number;
}
export class SpeedLimit {
'maxSpeed': string;
'speedUnit': string;
'speedVerification': string;
'amPeakAvgSpeed': string;
'pmPeakAvgSpeed': string;
'offPeakAvgSpeed': string;
'nightAvgSpeed': string;
'weekAvgSpeed': string;
'road': SpeedRoad;
}
export class SpeedRoad {
'id': string;
'name': string;
'altName': string;
'roadClass': string;
'type': string;
'lengthInMeters': string;
'routeNumber': string;
'surfaceType': string;
'trafficFlow': string;
'isToll': string;
'beginningLevel': string;
'endingLevel': string;
}
export class Start {
'year': number;
'month': number;
'day': number;
}
export class StartEndPoint {
'type': string;
'coordinates': Array<number>;
}
export class Status {
'code': string;
'description': string;
}
export class StudentEthnicity {
'indianAlaskaNative': string;
'asian': string;
'hispanic': string;
'black': string;
'white': string;
'hawaiianPacificlslander': string;
'twoOrMoreRaces': string;
}
export class SupplyAndDemandTheme {
'boundaryRef': string;
'individualValueVariable': Array<IndividualValueVariableV2>;
'rangeVariable': Array<RangeVariableV2>;
}
export class SupportLevel {
'supportedDataLevel': number;
'countries': Array<string>;
'updatedRequiredInputs': Array<InputParameter>;
'updatedOptionalInputs': Array<InputParameter>;
'updatedOptionalOutputs': Array<OutputParameter>;
}
export class TaxAddress {
'objectId': string;
'mainAddressLine': string;
'placeName': string;
'areaName1': string;
'areaName3': string;
'postCode1': string;
'country': string;
'purchaseAmount': string;
}
export class TaxAddressRequest {
'preferences': Preferences;
'taxAddresses': Array<TaxAddress>;
}
export class TaxBatchLocationResponse {
'objectId': string;
'confidence': number;
'jurisdiction': TaxJurisdiction;
'matchedAddress': MatchedAddress;
'salesTax': SalesTax;
'useTax': UseTax;
'census': Census;
'latLongFields': LatLongFields;
}
export class TaxBatchResponse {
'objectId': string;
'confidence': number;
'jurisdiction': TaxJurisdiction;
'matchedAddress': MatchedAddress;
'salesTax': SalesTax;
'useTax': UseTax;
'census': Census;
'latLongFields': LatLongFields;
}
export class TaxCounty {
'code': string;
'name': string;
}
export class TaxDistrictResponse {
'objectId': string;
'confidence': number;
'jurisdiction': IPDTaxJurisdiction;
'numOfIpdsFound': number;
'ipds': Array<Ipd>;
'matchedAddress': MatchedAddress;
}
export class TaxDistrictResponseList {
'taxDistrictResponse': Array<TaxDistrictResponse>;
}
export class TaxJurisdiction {
'state': TaxState;
'county': TaxCounty;
'place': TaxPlace;
'spds': Array<SpecialPurposeDistrict>;
}
export class TaxLocationPreferences {
'defaultBufferWidth': string;
'distanceUnits': string;
'outputCasing': string;
'returnCensusFields': string;
'returnLatLongFields': string;
}
export class TaxLocationRequest {
'preferences': TaxLocationPreferences;
'locations': Array<GeoTaxLocations>;
}
export class TaxLocationResponses {
'taxResponses': Array<TaxBatchLocationResponse>;
}
export class TaxPlace {
'name': string;
'code': string;
'gnisCode': string;
'selfCollected': boolean;
'classCode': string;
'incorporatedFlag': string;
'lastAnnexedDate': string;
'lastUpdatedDate': string;
'lastVerifiedDate': string;
}
export class TaxRateAddress {
'objectId': string;
'mainAddressLine': string;
'placeName': string;
'areaName1': string;
'areaName3': string;
'postCode1': string;
'country': string;
}
export class TaxRateAddressRequest {
'preferences': Preferences;
'taxRateAddresses': Array<TaxRateAddress>;
}
export class TaxRateBatchLocationResponse {
'objectId': string;
'confidence': number;
'jurisdiction': TaxJurisdiction;
'matchedAddress': MatchedAddress;
'salesTax': SalesTaxRate;
'useTax': UseTaxRate;
'census': Census;
'latLongFields': LatLongFields;
}
export class TaxRateBatchResponse {
'objectId': string;
'confidence': number;
'jurisdiction': TaxJurisdiction;
'matchedAddress': MatchedAddress;
'salesTax': SalesTaxRate;
'useTax': UseTaxRate;
'census': Census;
'latLongFields': LatLongFields;
}
export class TaxRateLocationRequest {
'preferences': TaxLocationPreferences;
'locations': Array<GeoTaxRateLocations>;
}
export class TaxRateLocationResponses {
'taxResponses': Array<TaxRateBatchLocationResponse>;
}
export class TaxRateResponse {
'objectId': string;
'confidence': number;
'jurisdiction': TaxJurisdiction;
'matchedAddress': MatchedAddress;
'salesTax': SalesTaxRate;
'useTax': UseTaxRate;
'latLongFields': LatLongFields;
}
export class TaxRateResponses {
'taxResponses': Array<TaxRateBatchResponse>;
}
export class TaxResponse {
'objectId': string;
'confidence': number;
'jurisdiction': TaxJurisdiction;
'matchedAddress': MatchedAddress;
'salesTax': SalesTax;
'useTax': UseTax;
'latLongFields': LatLongFields;
}
export class TaxResponses {
'taxResponses': Array<TaxBatchResponse>;
}
export class TaxState {
'code': string;
'name': string;
}
export class Time {
'value': string;
'unit': string;
}
export class Timezone {
'objectId': string;
'timezoneName': string;
'zoneType': string;
'utcOffset': number;
'dstOffset': number;
'timestamp': number;
'matchedAddress': MatchedAddress;
}
export class TimezoneAddressRequest {
'preferences': PreferencTimeZone;
'addressTime': Array<AddressTime>;
}
export class TimezoneLocation {
'objectId': string;
'timezoneName': string;
'zoneType': string;
'utcOffset': number;
'dstOffset': number;
'timestamp': number;
}
export class TimezoneLocationRequest {
'locationTime': Array<LocationTime>;
}
export class TimezoneLocationResponse {
'timezone': Array<TimezoneLocation>;
}
export class TimezoneResponse {
'timezone': Array<Timezone>;
}
export class Topic {
'name': string;
}
export class TravelBoundaries {
'travelBoundary': TravelBoundary;
}
export class TravelBoundary {
'costs': Costs;
}
export class TravelCostMatrixResponse {
'matrix': Array<Matrix>;
}
export class Type {
'code': string;
'value': string;
}
export class TypeaheadRange {
'placeName': string;
'units': Array<TypeaheadUnit>;
}
export class TypeaheadUnit {
'unitInfo': string;
'formattedUnitAddress': string;
}
export class Unit {
'value': number;
'unit': string;
}
export class Url {
'value': string;
}
export class UseTax {
'totalTaxRate': number;
'totalTaxAmount': number;
'stateTaxRate': number;
'stateTaxAmount': number;
'countyTaxRate': number;
'countyTaxAmount': number;
'municipalTaxRate': number;
'municipalTaxAmount': number;
'spdsTax': Array<SpecialPurposeDistrictTax>;
'specialTaxRulesApplied': boolean;
'specialTaxRulesDescriptor': string;
}
export class UseTaxRate {
'totalTaxRate': number;
'stateTaxRate': number;
'countyTaxRate': number;
'municipalTaxRate': number;
'spdsTax': Array<SpecialPurposeDistrictTaxRate>;
}
export class ValidateEmailAddressAPIRequest {
'options': ValidateEmailAddressOptions;
'input': ValidateEmailAddressInput;
}
export class ValidateEmailAddressAPIResponse {
'output': Array<ValidateEmailAddressOutput>;
}
export class ValidateEmailAddressInput {
'row': Array<ValidateEmailAddressInputRow>;
}
export class ValidateEmailAddressInputRow {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* Enables or disables real-time confirmation. If the deliverability of an email address cannot be determined via our knowledge base, a real-time confirmation can be attempted.
*/
'rtc': string;
/**
* Specifies whether to check if the email address is fictitious. For example, <EMAIL>.
*/
'bogus': string;
/**
* Specifies whether to check if the email address has a non-personal handle, such as info@, sales@, or webmaster@. For example, <EMAIL>.
*/
'role': string;
/**
* Specifies whether to check if the email address appears on the Direct Marketing Association's Do Not Email list (Electronic Mail Preference Service).
*/
'emps': string;
/**
* Specifies whether to check if the email address is associated with a domain that has restrictions on commercial email per the FCC.
*/
'fccwireless': string;
/**
* Specifies whether to check if the email address handle contains derogatory words.
*/
'language': string;
/**
* Specifies whether to check if the owner of the email address is known to submit spam complaints.
*/
'complain': string;
/**
* Specifies whether to check if the email address originates from a website that provides temporary email addresses, or if the email address appears to be temporary
*/
'disposable': string;
/**
* One character code controlling the advanced suggestion behavior.The possible values are: a, c, and n
*/
'atc': string;
/**
* The email address you want to validate.
*/
'emailAddress': string;
/**
* Specifies the timeout for real-time confirmation. See the description of the rtc parameter. Specify the timeout value in milliseconds. Valid values are 0 to 4000. By default, the system allows 1200 milliseconds for this check.
*/
'rtcTimeout': string;
}
export class ValidateEmailAddressOptions {
}
export class ValidateEmailAddressOutput {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* The email address submitted for verification.
*/
'eMAIL': string;
/**
* One character code indicating the validity of the submitted email address.
*/
'fINDING': string;
/**
* The comment string pertaining to the result of the submitted email address.
*/
'cOMMENT': string;
/**
* A short code which maps to each returned COMMENT field value.
*/
'cOMMENTCODE': string;
/**
* Suggested correction for submitted email address, if found. A suggestion will only be provided if it is valid and SafeToDeliver.
*/
'sUGGEMAIL': string;
/**
* This field contains suggestion not SafeToDeliver when ValidateEmailAddress corrected the address and the corrected version of the email address failed one or more SafeToDeliver process checks.
*/
'sUGGCOMMENT': string;
/**
* Pre-formatted response intended to be provided to user.
*/
'eRRORRESPONSE': string;
/**
* Field reserved for special features only.
*/
'eRROR': string;
/**
*
*/
'status': string;
/**
*
*/
'statusCode': string;
/**
*
*/
'statusDescription': string;
}
export class ValidateMailingAddressInput {
'row': Array<ValidateMailingAddressInputRow>;
}
export class ValidateMailingAddressInputRow {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* The first address line.
*/
'addressLine1': string;
/**
* The second address line.
*/
'addressLine2': string;
/**
* The company or firm name.
*/
'firmName': string;
/**
* The city name.
*/
'city': string;
/**
* The state or province.
*/
'stateProvince': string;
/**
* The country code or name.
*/
'country': string;
/**
* The postal code for the address.
*/
'postalCode': string;
}
export class ValidateMailingAddressInputRowUserFields {
/**
*
*/
'name': string;
/**
*
*/
'value': string;
}
export class ValidateMailingAddressOptions {
/**
* Specify the casing of the output data.
*/
'outputCasing': string;
}
export class ValidateMailingAddressOutput {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* The first line of the validated address.
*/
'addressLine1': string;
/**
* The second line of the validated address.
*/
'addressLine2': string;
/**
* The validated firm or company name.
*/
'firmName': string;
/**
* The validated city name.
*/
'city': string;
/**
* The validated ZIP Code or postal code.
*/
'postalCode': string;
/**
* The country name in English.
*/
'country': string;
/**
* The validated state or province abbreviation.
*/
'stateProvince': string;
/**
* The formatted address, as it would appear on a physical mail piece.
*/
'blockAddress': string;
/**
* Input data not used by the address validation process.
*/
'additionalInputData': string;
/**
* The 5-digit ZIP Code.
*/
'postalCodeBase': string;
/**
* The 4-digit add-on part of the ZIP Code.
*/
'postalCodeAddOn': string;
/**
* Reports the success or failure of the match attempt.
*/
'status': string;
/**
* Reason for failure, if there is one.
*/
'statusCode': string;
/**
* Description of the problem, if there is one.
*/
'statusDescription': string;
}
export class ValidateMailingAddressPremiumInput {
'row': Array<ValidateMailingAddressPremiumInputRow>;
}
export class ValidateMailingAddressPremiumInputRow {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* The first address line.
*/
'addressLine1': string;
/**
* The second address line.
*/
'addressLine2': string;
/**
* The third address line.
*/
'addressLine3': string;
/**
* The fourth address line.
*/
'addressLine4': string;
/**
* The fifth address line.
*/
'addressLine5': string;
/**
* The company or firm name.
*/
'firmName': string;
/**
* The city name.
*/
'city': string;
/**
* The state or province.
*/
'stateProvince': string;
/**
* The country code or name.
*/
'country': string;
/**
* The postal code for the address.
*/
'postalCode': string;
}
export class ValidateMailingAddressPremiumOptions {
/**
* Specifies whether to return a formatted version of the address as it would be printed on a physical mail piece.
*/
'outputAddressBlocks': string;
/**
* Specifies whether to return multiple address for those input addresses that have more than one possible match.
*/
'keepMultimatch': string;
/**
* Specifies the format to use for the country name returned in the Country output field.
*/
'outputCountryFormat': string;
/**
* Specifies the type of output record you get.
*/
'outputRecordType': string;
/**
* Specifies whether to include field-level result indicators.
*/
'outputFieldLevelReturnCodes': string;
/**
* Specifies the alphabet or script in which the output should be returned.
*/
'outputScript': string;
/**
* Specify the casing of the output data.
*/
'outputCasing': string;
/**
* A number between 1 and 10 that indicates the maximum number of addresses to return.
*/
'maximumResults': string;
}
export class ValidateMailingAddressPremiumOutput {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* Reports the success or failure of the match attempt.
*/
'status': string;
/**
* Reason for failure, if there is one.
*/
'statusCode': string;
/**
* Description of the problem, if there is one.
*/
'statusDescription': string;
/**
* The level of confidence assigned to the address being returned.
*/
'confidence': string;
/**
* Type of address record.
*/
'recordType': string;
/**
* Code indicating the default match.
*/
'recordTypeDefault': string;
/**
* Indicates which address component had multiple matches.
*/
'multipleMatches': string;
/**
* Mentions the address component that could not be validated, in case no match is found.
*/
'couldNotValidate': string;
/**
* The category of address matching available.
*/
'countryLevel': string;
/**
* The type of address data being returned.
*/
'addressFormat': string;
/**
* The first line of the validated address.
*/
'addressLine1': string;
/**
* The second line of the validated address.
*/
'addressLine2': string;
/**
* The third line of the validated address.
*/
'addressLine3': string;
/**
* The fourth line of the validated address.
*/
'addressLine4': string;
/**
* The validated city name.
*/
'city': string;
/**
* The validated state or province abbreviation.
*/
'stateProvince': string;
/**
* The validated ZIP Code or postal code.
*/
'postalCode': string;
/**
* The 5-digit ZIP Code.
*/
'postalCodeBase': string;
/**
* The 4-digit add-on part of the ZIP Code.
*/
'postalCodeAddOn': string;
/**
* The country in the format determined by what you selected.
*/
'country': string;
/**
* Input data that could not be matched to a particular address component.
*/
'additionalInputData': string;
/**
* The validated firm or company name.
*/
'firmName': string;
/**
* House number.
*/
'houseNumber': string;
/**
* Leading directional.
*/
'leadingDirectional': string;
/**
* Street name.
*/
'streetName': string;
/**
* Street suffix.
*/
'streetSuffix': string;
/**
* Trailing directional.
*/
'trailingDirectional': string;
/**
* Apartment designator (such as STE or APT).
*/
'apartmentLabel': string;
/**
* Apartment number.
*/
'apartmentNumber': string;
/**
* Secondary apartment designator.
*/
'apartmentLabel2': string;
/**
* Secondary apartment number.
*/
'apartmentNumber2': string;
/**
* Rural Route/Highway Contract indicator.
*/
'rRHC': string;
/**
* Post office box number.
*/
'pOBox': string;
/**
* Private mailbox indicator.
*/
'privateMailbox': string;
/**
* The type of private mailbox.
*/
'privateMailboxType': string;
/**
* House number.
*/
'houseNumberInput': string;
/**
* Leading directional.
*/
'leadingDirectionalInput': string;
/**
* Street name.
*/
'streetNameInput': string;
/**
* Street suffix.
*/
'streetSuffixInput': string;
/**
* Trailing directional.
*/
'trailingDirectionalInput': string;
/**
* Apartment designator (such as STE or APT).
*/
'apartmentLabelInput': string;
/**
* Apartment number.
*/
'apartmentNumberInput': string;
/**
* Rural Route/Highway Contract indicator.
*/
'rRHCInput': string;
/**
* Post office box number.
*/
'pOBoxInput': string;
/**
* Private mailbox indicator.
*/
'privateMailboxInput': string;
/**
* The type of private mailbox.
*/
'privateMailboxTypeInput': string;
/**
* Validated city name.
*/
'cityInput': string;
/**
* Validated state or province name.
*/
'stateProvinceInput': string;
/**
* Validated postal code.
*/
'postalCodeInput': string;
/**
* Country. Format is determined by what you selected in OutputCountryFormat.
*/
'countryInput': string;
/**
* The validated firm or company name.
*/
'firmNameInput': string;
/**
* The field-level result indicator for HouseNumber.
*/
'houseNumberResult': string;
/**
* The field-level result indicator for LeadingDirectional.
*/
'leadingDirectionalResult': string;
/**
* The field-level result indicator for Street.
*/
'streetResult': string;
/**
* The field-level result indicator for StreetName.
*/
'streetNameResult': string;
/**
* The field-level result indicator for StreetName Alias.
*/
'streetNameAliasType': string;
/**
* The field-level result indicator for StreetSuffix.
*/
'streetSuffixResult': string;
/**
* The field-level result indicator for TrailingDirectional.
*/
'trailingDirectionalResult': string;
/**
* The field-level result indicator for ApartmentLabel.
*/
'apartmentLabelResult': string;
/**
* The field-level result indicator for ApartmentNumber.
*/
'apartmentNumberResult': string;
/**
* The field-level result indicator for ApartmentLabel2.
*/
'apartmentLabel2Result': string;
/**
* The field-level result indicator for ApartmentNumber2.
*/
'apartmentNumber2Result': string;
/**
* The field-level result indicator for RRHC.
*/
'rRHCResult': string;
/**
* The field-level result indicator for RRHC Type.
*/
'rRHCType': string;
/**
* The field-level result indicator for POBox.
*/
'pOBoxResult': string;
/**
* The field-level result indicator for City.
*/
'cityResult': string;
/**
* The field-level result indicator for StateProvince.
*/
'stateProvinceResult': string;
/**
* The field-level result indicator for PostalCode.
*/
'postalCodeResult': string;
/**
* The field-level result indicator for PostalCodeCity.
*/
'postalCodeCityResult': string;
/**
* The field-level result indicator for AddressRecord.
*/
'addressRecordResult': string;
/**
* The field-level result indicator for PostalCode Source.
*/
'postalCodeSource': string;
/**
* Indicates the type of postal code returned.
*/
'postalCodeType': string;
/**
* The validated firm or company name.
*/
'countryResult': string;
/**
* Indicates if the firm name got validated.
*/
'firmNameResult': string;
/**
* Indicates the result of preferred alias processing.
*/
'streetNamePreferredAliasResult': string;
/**
* Indicates the result of abbreviated alias processing.
*/
'streetNameAbbreviatedAliasResult': string;
/**
* The fifth line of the validated address.
*/
'addressLine5': string;
/**
* A two character code indicating overall quality of the resulting address.
*/
'addressQuality': string;
/**
* An estimate of confidence that an item mailed or shipped to this address would be successfully delivered.
*/
'deliverability': string;
/**
* A single letter code that indicates the type of address.
*/
'addressType': string;
/**
* A locality is a village in rural areas or it may be a suburb in urban areas.
*/
'locality': string;
/**
* A value of 0 and 100 that reflects how much the address has changed to make it valid.
*/
'changeScore': string;
/**
* The validated firm or company name.
*/
'suburb': string;
/**
* It is the formatted address, as it would appear on a physical mail piece.
*/
'blockAddress': string;
/**
* Seven-digit number in degrees, calculated to four decimal places.
*/
'latitude': string;
/**
* Seven-digit number in degrees, calculated to four decimal places.
*/
'longitude': string;
}
export class ValidateMailingAddressPremiumRequest {
'options': ValidateMailingAddressPremiumOptions;
'input': ValidateMailingAddressPremiumInput;
}
export class ValidateMailingAddressPremiumResponse {
'output': Array<ValidateMailingAddressPremiumOutput>;
}
export class ValidateMailingAddressProInput {
'row': Array<ValidateMailingAddressProInputRow>;
}
export class ValidateMailingAddressProInputRow {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* The first address line.
*/
'addressLine1': string;
/**
* The second address line.
*/
'addressLine2': string;
/**
* The company or firm name.
*/
'firmName': string;
/**
* The city name.
*/
'city': string;
/**
* The state or province.
*/
'stateProvince': string;
/**
* The country code or name.
*/
'country': string;
/**
* The postal code for the address.
*/
'postalCode': string;
}
export class ValidateMailingAddressProOptions {
/**
* Specifies whether to return a formatted version of the address as it would be printed on a physical mail piece.
*/
'outputAddressBlocks': string;
/**
* Specifies whether to return multiple address for those input addresses that have more than one possible match.
*/
'keepMultimatch': string;
/**
* Specifies the format to use for the country name returned in the Country output field.
*/
'outputCountryFormat': string;
/**
* Specifies the alphabet or script in which the output should be returned.
*/
'outputScript': string;
/**
* Specify the casing of the output data.
*/
'outputCasing': string;
/**
* A number between 1 and 10 that indicates the maximum number of addresses to return.
*/
'maximumResults': string;
}
export class ValidateMailingAddressProOutput {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* The first line of the validated address.
*/
'addressLine1': string;
/**
* The second line of the validated address.
*/
'addressLine2': string;
/**
* The validated firm or company name.
*/
'firmName': string;
/**
* A value of 0 and 100 that reflects how much the address has changed to make it valid.
*/
'changeScore': string;
/**
* Generally a locality is a village in rural areas or it may be a suburb in urban areas.
*/
'locality': string;
/**
* The suburb name.
*/
'suburb': string;
/**
* A single letter code that indicates the type of address.
*/
'addressType': string;
/**
* An estimate of confidence that an item mailed or shipped to this address would be successfully delivered.
*/
'deliverability': string;
/**
* A two character code indicating overall quality of the resulting address.
*/
'addressQuality': string;
/**
* Mentions the address component that could not be validated, in case no match is found.
*/
'couldNotValidate': string;
/**
* The validated city name.
*/
'city': string;
/**
* The validated ZIP Code or postal code.
*/
'postalCode': string;
/**
* The country in the format determined by what you selected.
*/
'country': string;
/**
* The validated state or province abbreviation.
*/
'stateProvince': string;
/**
* The formatted address, as it would appear on a physical mail piece.
*/
'blockAddress': string;
/**
* Input data that could not be matched to a particular address component.
*/
'additionalInputData': string;
/**
* The 5-digit ZIP Code.
*/
'postalCodeBase': string;
/**
* The 4-digit add-on part of the ZIP Code.
*/
'postalCodeAddOn': string;
/**
* Reports the success or failure of the match attempt.
*/
'status': string;
/**
* Reason for failure, if there is one.
*/
'statusCode': string;
/**
* Description of the problem, if there is one.
*/
'statusDescription': string;
}
export class ValidateMailingAddressProRequest {
'options': ValidateMailingAddressProOptions;
'input': ValidateMailingAddressProInput;
}
export class ValidateMailingAddressProResponse {
'output': Array<ValidateMailingAddressProOutput>;
}
export class ValidateMailingAddressRequest {
'options': ValidateMailingAddressOptions;
'input': ValidateMailingAddressInput;
}
export class ValidateMailingAddressResponse {
'output': Array<ValidateMailingAddressOutput>;
}
export class ValidateMailingAddressUSCANAPIInput {
'row': Array<ValidateMailingAddressUSCANAPIInputRow>;
}
export class ValidateMailingAddressUSCANAPIInputRow {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* The first address line.
*/
'addressLine1': string;
/**
* The second address line.
*/
'addressLine2': string;
/**
* The third address line.
*/
'addressLine3': string;
/**
* The fourth address line.
*/
'addressLine4': string;
/**
* The company or firm name.
*/
'firmName': string;
/**
* The city name.
*/
'city': string;
/**
* The state or province.
*/
'stateProvince': string;
/**
* The country code or name.
*/
'country': string;
/**
* The postal code for the address.
*/
'postalCode': string;
/**
* U.S. address urbanization name. Used primarily for Puerto Rico addresses.
*/
'uSUrbanName': string;
/**
* Canadian language.
*/
'canLanguage': string;
}
export class ValidateMailingAddressUSCANAPIOptions {
/**
* Specifies whether to return a formatted version of the address.
*/
'outputAddressBlocks': string;
/**
* Specifies whether or not to process U.S. addresses.
*/
'performUSProcessing': string;
/**
* Delivery Point Validation (DPV®) validates that a specific address exists
*/
'performDPV': string;
/**
* Specifies whether to return a formatted address when an address cannot be validated.
*/
'outputFormattedOnFail': string;
/**
* Specifies whether to use separators (spaces or hyphens) in ZIP™ Codes or Canadian postal codes.
*/
'outputPostalCodeSeparator': string;
/**
* Specifies the format to use for the country name returned in the Country output field.
*/
'outputCountryFormat': string;
/**
* Indicates whether to return multiple address for input addresses that have more than one possible matches.
*/
'keepMultimatch': string;
/**
* Specifies the casing of the output address. M for mixed case and U for upper case.
*/
'outputCasing': string;
/**
* Specifies a number between 1 and 10 that indicates the maximum number of addresses to be returned.
*/
'maximumResults': string;
/**
* Specifies the type of the output record.
*/
'outputRecordType': string;
/**
* Identifies which output addresses are candidate addresses as value if Y for OutputFieldLevelReturnCodes.
*/
'outputFieldLevelReturnCodes': string;
/**
* Determines the no stat status of an address which means it exists but cannot receive mails.
*/
'dPVDetermineNoStat': string;
/**
* Specifies the algorithm to determe if an input address matches in the postal database.
*/
'streetMatchingStrictness': string;
/**
* Specifies the default apartment label for the output if there is no apartment label in the input address. This is specific to French address.
*/
'canFrenchApartmentLabel': string;
/**
* Specifies whether to use a street's abbreviated alias in the output if the output address line is longer than 31 characters.
*/
'outputAbbreviatedAlias': string;
/**
* Selecting the match condition where a DPV result does NOT cause a record to fail.
*/
'dPVSuccessfulStatusCondition': string;
/**
* Specifies where Private Mailbox (PMB) information is placed.
*/
'standardAddressPMBLine': string;
/**
* Specifies the algorithm to determining if an input address matches in the postal database.
*/
'firmMatchingStrictness': string;
/**
* Specifies where to place rural route delivery information.
*/
'canRuralRouteFormat': string;
/**
* Specifies whether to select a house number of postal code in case of conflict.
*/
'canPreferHouseNum': string;
/**
* Specifies whether to use a street's preferred alias in the output.
*/
'outputPreferredAlias': string;
/**
* Specifies the algorithm to determine if an input address matches in the postal database.
*/
'directionalMatchingStrictness': string;
/**
* Specifies whether to extract the firm name from AddressLine1 through AddressLine4 and place it in the FirmName output field.
*/
'extractFirm': string;
/**
* Specifies whether to consider Treat Commercial Mail Receiving Agency (CMRA) matches as failures?
*/
'failOnCMRAMatch': string;
/**
* Specifies whether or not non-civic keywords are abbreviated in the output.
*/
'canNonCivicFormat': string;
/**
* Changes the civic and/or suite information to match the LVR or single-single record.
*/
'canSSLVRFlg': string;
/**
* Specifies how to handle street name aliases used in the input. This is specific to US.
*/
'outputStreetNameAlias': string;
/**
* Specifies the Early Warning System (EWS) that uses the USPS EWS File to validate addresses that are not in the ZIP + 4 database.
*/
'performEWS': string;
/**
* Specifies whether to use the long, medium, or short version of the city if the city has a long name.
*/
'canOutputCityFormat': string;
/**
* Specifies how to return a match if multiple non-blank address lines are present or multiple address types are on the same address line. (U.S. addresses only.)
*/
'dualAddressLogic': string;
/**
* Specifies whether to perform SuiteLink processing.
*/
'performSuiteLink': string;
/**
* Specifies where to place secondary address information in the output address.
*/
'canStandardAddressFormat': string;
/**
* Specifies whether the preferred last line city name should be stored.
*/
'outputPreferredCity': string;
/**
* Specifies whether to return multinational characters, including diacritical marks such as umlauts or accents.
*/
'outputMultinationalCharacters': string;
/**
* Specifies where to place station information.
*/
'canDeliveryOfficeFormat': string;
/**
* Facilitates the conversion of rural route address converting into street-style address using the LACS.
*/
'performLACSLink': string;
/**
* Specifies whether ValidateMailingAddressUSCAN should return a street match or a PO Box/non-civic match when the address contains both civic and non-civic information.
*/
'canDualAddressLogic': string;
/**
* Specifies whether to extract the urbanization name from AddressLine1 through AddressLine4 and place it in the USUrbanName output field.
*/
'extractUrb': string;
/**
* Specifies where to place secondary address information for U.S. addresses.
*/
'standardAddressFormat': string;
/**
* Specifies how to determine the language (English or French) to use to format the address and directional.
*/
'canFrenchFormat': string;
/**
* Determines if the location has been unoccupied for at least 90 days.
*/
'dPVDetermineVacancy': string;
/**
* Specifies the default apartment label to use in the output if there is no apartment label in the input address. rhis is specific to English addresses.
*/
'canEnglishApartmentLabel': string;
/**
* Specifies whether to supress addresses with Carrier Route R777.
*/
'suppressZplusPhantomCarrierR777': string;
/**
* Specifies whether or not to return the city alias when the alias is in the input address.
*/
'canOutputCityAlias': string;
/**
* Specifies how to format city names that have short city name or non-mailing city name alternatives.
*/
'outputShortCityName': string;
}
export class ValidateMailingAddressUSCANAPIOutput {
/**
* These fields are returned, unmodified, in the user_fields section of the response.
*/
'userFields': Array<ValidateMailingAddressInputRowUserFields>;
/**
* Reports the success or failure of the match attempt.
*/
'status': string;
/**
* Reason for failure, if there is one.
*/
'statusCode': string;
/**
* Specifies the description of the problem, if there is one.
*/
'statusDescription': string;
/**
* Specifies the first line of the validated and standardized address.
*/
'addressLine1': string;
/**
* Specifies the second line of the validated and standardized address.
*/
'addressLine2': string;
/**
* Specifies the validated city name.
*/
'city': string;
/**
* Specifies the validated state or province abbreviation.
*/
'stateProvince': string;
/**
* Specifies the validated ZIP Code or postal code.
*/
'postalCode': string;
/**
* Specifies the country in the format determined by the selection from ISO or UPO or English.
*/
'country': string;
/**
* Specifies the validated firm or company name.
*/
'firmName': string;
/**
* Specifies the formatted address, as it would appear on a physical mail piece.
*/
'blockAddress': string;
/**
* Specifies the 5-digit ZIP Code.
*/
'postalCodeBase': string;
/**
* Specifies the 4-digit add-on part of the ZIP Code.
*/
'postalCodeAddOn': string;
/**
* Specifies input data not used by the address validation process.
*/
'additionalInputData': string;
/**
* Specifies the address component that could not be validated, in case no match is found.
*/
'couldNotValidate': string;
/**
* Specifies the type of address data being returned.
*/
'addressFormat': string;
/**
* Specifies the third line of the validated and standardized address. If the address could not be validated, the third line of the input address without any changes.
*/
'addressLine3': string;
/**
* Specifies the fourth line of the validated and standardized address. If the address could not be validated, the fourth line of the input address without any changes.
*/
'addressLine4': string;
/**
* Specifies the result codes that apply to international addresses only.
*/
'addressRecordResult': string;
/**
* Specifies the apartment designator such as STE or APT.
*/
'apartmentLabel': string;
/**
* Specifies the apartment designator such as STE or APT.
*/
'apartmentLabelInput': string;
/**
* Specifies the result of apartment label.
*/
'apartmentLabelResult': string;
/**
* Specifies the apartment number.
*/
'apartmentNumber': string;
/**
* Specifies the apartment number.
*/
'apartmentNumberInput': string;
/**
* Specifies the result of apartment number.
*/
'apartmentNumberResult': string;
/**
* Specifies the validated city name.
*/
'cityInput': string;
/**
* Specifies the result of the validated city name.
*/
'cityResult': string;
/**
* Specifies the the level of confidence assigned to the address being returned.
*/
'confidence': string;
/**
* Specifies the name of the country.
*/
'countryInput': string;
/**
* Specifies the result code for the country.
*/
'countryResult': string;
/**
* Specifies the category of address matching available.
*/
'countryLevel': string;
/**
* Specifies the validated firm or company name.
*/
'firmNameInput': string;
/**
* Specifies if the firm name got validated.
*/
'firmNameResult': string;
/**
* Specifies the house number.
*/
'houseNumber': string;
/**
* Specifies the house number.
*/
'houseNumberInput': string;
/**
* Specifies the result for house number.
*/
'houseNumberResult': string;
/**
* Specifies the leading directional.
*/
'leadingDirectional': string;
/**
* Specifies the leading directional.
*/
'leadingDirectionalInput': string;
/**
* Specifies the result of leading directional.
*/
'leadingDirectionalResult': string;
/**
* Specifies the address component with multiple matches, if multiple matches were found:
*/
'multipleMatches': string;
/**
* Specifies the post office box number.
*/
'pOBox': string;
/**
* Specifies the post office box number.
*/
'pOBoxInput': string;
/**
* Specifies the result of post office box number.
*/
'pOBoxResult': string;
/**
* Specifies the validated postal code. For U.S. addresses, this is the ZIP code.
*/
'postalCodeInput': string;
/**
* Specifies the result of validated postal code.
*/
'postalCodeResult': string;
/**
* Specifies the result code.
*/
'postalCodeSource': string;
/**
* Specifies the type of postal code returned.
*/
'postalCodeType': string;
/**
* Specifies the international result code.
*/
'postalCodeCityResult': string;
/**
* Specifies the private mailbox indicator.
*/
'privateMailbox': string;
/**
* Specifies the private mailbox indicator.
*/
'privateMailboxInput': string;
/**
* Specifies the type of private mailbox.
*/
'privateMailboxType': string;
/**
* Specifies the type of private mailbox.
*/
'privateMailboxTypeInput': string;
/**
* Specifies the type of address record, as defined by U.S. and Canadian postal authorities.
*/
'recordType': string;
/**
* Specifies the code indicating the default match.
*/
'recordTypeDefault': string;
/**
* Specifies the Rural Route/Highway Contract indicator.
*/
'rRHC': string;
/**
* Specifies the Rural Route/Highway Contract indicator.
*/
'rRHCInput': string;
/**
* Specifies the result for Rural Route/Highway Contract indicator.
*/
'rRHCResult': string;
/**
* Specifies the result code for Rural Route/Highway Contract indicator.
*/
'rRHCType': string;
/**
* Specifies the validated state or province abbreviation.
*/
'stateProvinceInput': string;
/**
* Specifies the result of validated state or province abbreviation.
*/
'stateProvinceResult': string;
/**
* Specifies the result codes for international addresses.
*/
'streetResult': string;
/**
* Specifies the street name.
*/
'streetName': string;
/**
* Specifies result code that applies to U.S. addresses only.
*/
'streetNameAliasType': string;
/**
* Specifies the street name.
*/
'streetNameInput': string;
/**
* Specifies the result of the street name.
*/
'streetNameResult': string;
/**
* Indicates the result of abbreviated alias processing.
*/
'streetNameAbbreviatedAliasResult': string;
/**
* Specifies the result of preferred alias processing.
*/
'streetNamePreferredAliasResult': string;
/**
* Specifies the street suffix.
*/
'streetSuffix': string;
/**
* Specifies the street suffix.
*/
'streetSuffixInput': string;
/**
* Specifies the result of the street suffix.
*/
'streetSuffixResult': string;
/**
* Specifies the trailing directional.
*/
'trailingDirectional': string;
/**
* Specifies the trailing directional.
*/
'trailingDirectionalInput': string;
/**
* Specifies the result of the trailing directional.
*/
'trailingDirectionalResult': string;
/**
* Specifies an indication of the degree to which the output address is correct.
*/
'matchScore': string;
/**
* Specifies whether the address is a candidate for LACS conversion. This is for U.S. addresses only).
*/
'uSLACS': string;
/**
* Specifies the the success or failure of LACS processing. This is for U.S. addresses only).
*/
'uSLACSReturnCode': string;
/**
* Specifies the values indicating address type.
*/
'rDI': string;
/**
* Specifies if the address is a Commercial Mail Receiving Agency (CMRA).
*/
'cMRA': string;
/**
* Specifies the results of Delivery Point Validation (DPV) processing.
*/
'dPV': string;
/**
* Specifies the DPV footnote codes.
*/
'dPVFootnote': string;
/**
* Indicates whether or not API corrected the secondary address information (U.S. addresses only).
*/
'suiteLinkReturnCode': string;
/**
* Provides additional information on the SuiteLink match attempt. (U.S. addresses only)
*/
'suiteLinkMatchCode': string;
/**
* Indicates how well ValidateAddress matched the firm name to the firm names in the SuiteLink database.
*/
'suiteLinkFidelity': string;
/**
* Specifies the check-digit portion of the 11-digit delivery point barcode.
*/
'uSBCCheckDigit': string;
/**
* Specifies the delivery point portion of the delivery point barcode.
*/
'postalBarCode': string;
/**
* Specifies carrier route code.
*/
'uSCarrierRouteCode': string;
/**
* Specifies FIPS (Federal Information Processing Standards) county number (U.S. addresses only).
*/
'uSFIPSCountyNumber': string;
/**
* Specifies the county name (U.S. addresses only).
*/
'uSCountyName': string;
/**
* Specifies congressional district (U.S. addresses only).
*/
'uSCongressionalDistrict': string;
/**
* Specifies whether the alternate address matching logic was used, and if so which logic was used (U.S. addresses only).
*/
'uSAltAddr': string;
/**
* Specifies a six-character alphanumeric value that groups together ZIP Codes that share the same primary city.
*/
'uSLastLineNumber': string;
/**
* Specifies the finance number in which the address resides (U.S. addresses only).
*/
'uSFinanceNumber': string;
/**
* U.S. address urbanization name. Used primarily for Puerto Rico addresses.
*/
'uSUrbanName': string;
/**
* U.S. address urbanization name. Used primarily for Puerto Rico addresses.
*/
'uSUrbanNameInput': string;
/**
* U.S. address urbanization name. Used primarily for Puerto Rico addresses.
*/
'uSUrbanNameResult': string;
/**
* If the address was matched to multiple candidate addresses in the reference data, this field contains the number of candidate matches found.
*/
'multimatchCount': string;
/**
* AddressBlock1
*/
'addressBlock1': string;
/**
* AddressBlock2
*/
'addressBlock2': string;
/**
* AddressBlock3
*/
'addressBlock3': string;
/**
* AddressBlock4
*/
'addressBlock4': string;
/**
* AddressBlock5
*/
'addressBlock5': string;
/**
* AddressBlock6
*/
'addressBlock6': string;
/**
* AddressBlock7
*/
'addressBlock7': string;
/**
* AddressBlock8
*/
'addressBlock8': string;
/**
* AddressBlock9
*/
'addressBlock9': string;
/**
* Specifies whether the address is in English or French. This is for Canadian address only.
*/
'canLanguage': string;
/**
* Specifies whether the building is a no stat building and therefore unable to receive mail.
*/
'dPVNoStat': string;
/**
* Specifies whether the building is vacant, unoccupied for 90 days.
*/
'dPVVacant': string;
}
export class ValidateMailingAddressUSCANAPIRequest {
'options': ValidateMailingAddressUSCANAPIOptions;
'input': ValidateMailingAddressUSCANAPIInput;
}
export class ValidateMailingAddressUSCANAPIResponse {
'output': Array<ValidateMailingAddressUSCANAPIOutput>;
}
export class WaterBody {
'name': string;
'distance': ShoreLineDistance;
'type': Type;
}
export class WaterBodyLocationResponse {
'waterBody': Array<WaterBody>;
}
export class WaterBodyResponse {
'waterBody': Array<WaterBody>;
'matchedAddress': MatchedAddress;
}
export interface Authentication {
/**
* Apply authentication settings to header and query params.
*/
getOAuthCredentials(requestOptions: request.Options): Promise<{body: oAuthCredInfo; }>;
}
/*export class HttpBasicAuth implements Authentication {
public username: string;
public password: string;
applyToRequest(requestOptions: request.Options): void {
requestOptions.auth = {
username: this.username, password: this.password
}
}
}*/
/*export class ApiKeyAuth implements Authentication {
public apiKey: string;
constructor(private location: string, private paramName: string) {
}
applyToRequest(requestOptions: request.Options): void {
if (this.location == "query") {
(<any>requestOptions.qs)[this.paramName] = this.apiKey;
} else if (this.location == "header") {
requestOptions.headers[this.paramName] = this.apiKey;
}
}
}*/
export class OAuth implements Authentication {
public objOAuthCredInfo: oAuthCredInfo;
public oAuthApiKey : string;
public oAuthSecret : string;
public oAuthUrl :string;
public oAuthToken :string;
constructor()
constructor(oAuthApiKey?: string, oAuthSecret?: string) {
this.oAuthApiKey=oAuthApiKey;
this.oAuthSecret=oAuthSecret;
}
public getOAuthCredentials(): Promise<{ response: http.IncomingMessage; body: oAuthCredInfo; }> {
if (this.oAuthApiKey === undefined || this.oAuthSecret === undefined ) {
Promise.reject({response: "Validation Error", body: "oAuthApiKey or oAuthSecret missing"})
}
if ((this.objOAuthCredInfo === null || this.objOAuthCredInfo === undefined)) {
return this.refreshToken();
}
else {
if((Number(this.objOAuthCredInfo.issuedAt) + Number(this.objOAuthCredInfo.expiresIn)) < (moment().valueOf()+ 10000))
{
return this.refreshToken();
}
return Promise.resolve({response: null, body: this.objOAuthCredInfo})
}
}
private refreshToken():Promise<{ response: http.IncomingMessage; body: oAuthCredInfo; }>{
this.oAuthToken = "Basic " + new Buffer(this.oAuthApiKey + ":" + this.oAuthSecret).toString('base64')
//.toString('base64');
if (this.oAuthUrl === undefined || this.oAuthUrl === null) {
this.oAuthUrl = "https://api.precisely.com/oauth/token";
}
let requestOptions: request.Options = {
method: 'POST',
url: this.oAuthUrl,
headers:
{
'cache-control': 'no-cache',
authorization: this.oAuthToken
},
body: 'grant_type=client_credentials'
};
return new Promise<{ response: http.IncomingMessage; body: oAuthCredInfo; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject({response: response, body: JSON.parse(error)});
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
this.objOAuthCredInfo = JSON.parse(body);
resolve({response: response, body: JSON.parse(body)});
} else {
reject({response: response, body: JSON.parse(body)});
}
}
});
});
}
}
/*export class VoidAuth implements Authentication {
public username: string;
public password: string;
applyToRequest(requestOptions: request.Options): void {
// Do nothing
}
}*/
export enum AddressVerificationServiceApiApiKeys {
}
export class AddressVerificationServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: AddressVerificationServiceApiApiKeys, value: string) {
this.authentications[AddressVerificationServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* GetCityStateProvince
* GetCityStateProvince returns a city and state/province for a given input postal code for U.S. and Canadian addresses.
* @param inputAddress
*/
public getCityStateProvince (inputAddress: GetCityStateProvinceAPIRequest) : Promise<{ response: http.IncomingMessage; body: GetCityStateProvinceAPIResponse; }> {
const localVarPath = this.basePath + '/addressverification/v1/getcitystateprovince/results.json';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'inputAddress' is not null or undefined
if (inputAddress === null || inputAddress === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter inputAddress was null or undefined when calling getCityStateProvince."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: inputAddress,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GetCityStateProvinceAPIResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* GetPostalCodes
* GetPostalCodes takes a city and state as input for U.S. addresses and returns the postal codes for that city.
* @param inputAddress
*/
public getPostalCodes (inputAddress: GetPostalCodesAPIRequest) : Promise<{ response: http.IncomingMessage; body: GetPostalCodesAPIResponse; }> {
const localVarPath = this.basePath + '/addressverification/v1/getpostalcodes/results.json';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'inputAddress' is not null or undefined
if (inputAddress === null || inputAddress === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter inputAddress was null or undefined when calling getPostalCodes."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: inputAddress,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GetPostalCodesAPIResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* ValidateMailingAddress
* ValidateMailingAddress analyses and compares the input addresses against the known address databases around the world to output a standardized detail.
* @param inputAddress
*/
public validateMailingAddress (inputAddress: ValidateMailingAddressRequest) : Promise<{ response: http.IncomingMessage; body: ValidateMailingAddressResponse; }> {
const localVarPath = this.basePath + '/addressverification/v1/validatemailingaddress/results.json';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'inputAddress' is not null or undefined
if (inputAddress === null || inputAddress === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter inputAddress was null or undefined when calling validateMailingAddress."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: inputAddress,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: ValidateMailingAddressResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* ValidateMailingAddressPremium
* ValidateMailing AddressPremium expands on the ValidateMailingAddressPro service by adding premium address data sources to get the best address validation result possible.
* @param inputAddress
*/
public validateMailingAddressPremium (inputAddress: ValidateMailingAddressPremiumRequest) : Promise<{ response: http.IncomingMessage; body: ValidateMailingAddressPremiumResponse; }> {
const localVarPath = this.basePath + '/addressverification/v1/validatemailingaddresspremium/results.json';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'inputAddress' is not null or undefined
if (inputAddress === null || inputAddress === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter inputAddress was null or undefined when calling validateMailingAddressPremium."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: inputAddress,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: ValidateMailingAddressPremiumResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* ValidateMailingAddressPro
* ValidateMailingAddressPro builds upon the ValidateMailingAddress service by using additional address databases so it can provide enhanced detail.
* @param inputAddress
*/
public validateMailingAddressPro (inputAddress: ValidateMailingAddressProRequest) : Promise<{ response: http.IncomingMessage; body: ValidateMailingAddressProResponse; }> {
const localVarPath = this.basePath + '/addressverification/v1/validatemailingaddresspro/results.json';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'inputAddress' is not null or undefined
if (inputAddress === null || inputAddress === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter inputAddress was null or undefined when calling validateMailingAddressPro."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: inputAddress,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: ValidateMailingAddressProResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* ValidateMailingAddressUSCAN
* ValidateMailingAddressUSCAN analyses and compares the input addresses against the known address databases around the world to output a standardized detail for US and CANADAIt gives RDI and DPV also along with other US/CAN specific functionalities.
* @param inputAddress
*/
public validateMailingAddressUSCAN (inputAddress: ValidateMailingAddressUSCANAPIRequest) : Promise<{ response: http.IncomingMessage; body: ValidateMailingAddressUSCANAPIResponse; }> {
const localVarPath = this.basePath + '/addressverification/v1/validatemailingaddressuscan/results.json';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'inputAddress' is not null or undefined
if (inputAddress === null || inputAddress === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter inputAddress was null or undefined when calling validateMailingAddressUSCAN."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: inputAddress,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: ValidateMailingAddressUSCANAPIResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum AddressesAPIServiceApiApiKeys {
}
export class AddressesAPIServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: AddressesAPIServiceApiApiKeys, value: string) {
this.authentications[AddressesAPIServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Addresses By Boundary Area.
* This service accepts zip code, neighborhood, county, or city names, and returns all known & valid addresses associated with these names.
* @param country Name of country. Acceptable values are CAN, USA.
* @param areaName1 Specifies the largest geographical area, typically a state or province.
* @param areaName2 Specifies the secondary geographic area, typically a county or district.
* @param areaName3 Specifies a city or town name.
* @param areaName4 Specifies a city subdivision or locality/neighborhood.
* @param postCode Specifies the postcode (ZIP code) in the appropriate format for the country.
* @param maxCandidates Maximum number of addresses to be returned in response. Max. value is 100 for XML/JSON, and 2000 for CSV.
* @param page Response will indicate the page number.
*/
public getAddressesByBoundaryName (country: string, areaName1?: string, areaName2?: string, areaName3?: string, areaName4?: string, postCode?: string, maxCandidates?: string, page?: string) : Promise<{ response: http.IncomingMessage; body: AddressesResponse; }> {
const localVarPath = this.basePath + '/addresses/v1/address/byboundaryname';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'country' is not null or undefined
if (country === null || country === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter country was null or undefined when calling getAddressesByBoundaryName."}]}})
}
if (areaName1 !== undefined) {
queryParameters['areaName1'] = areaName1;
}
if (areaName2 !== undefined) {
queryParameters['areaName2'] = areaName2;
}
if (areaName3 !== undefined) {
queryParameters['areaName3'] = areaName3;
}
if (areaName4 !== undefined) {
queryParameters['areaName4'] = areaName4;
}
if (postCode !== undefined) {
queryParameters['postCode'] = postCode;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
if (page !== undefined) {
queryParameters['page'] = page;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: AddressesResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Address Counts by Boundary.
* This service accepts custom geographic boundaries or drivetimes & drive distances, returns the total number of addresses within these boundaries.
* @param body
*/
public getAddressesCountByBoundary (body?: AddressesByBoundaryRequest) : Promise<{ response: http.IncomingMessage; body: AddressesCount; }> {
const localVarPath = this.basePath + '/addresses/v1/addresscount/byboundary';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: AddressesCount; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Address Counts by Boundary Name.
* This service accepts zip code, neighborhood, county, or city names, and returns the total number of addresses associated with these names.
* @param country Name of country. Acceptable values are CAN, USA.
* @param areaName1 Specifies the largest geographical area, typically a state or province.
* @param areaName2 Specifies the secondary geographic area, typically a county or district.
* @param areaName3 Specifies a city or town name.
* @param areaName4 Specifies a city subdivision or locality/neighborhood.
* @param postCode Specifies the postcode (ZIP code) in the appropriate format for the country.
*/
public getAddressesCountByBoundaryName (country: string, areaName1?: string, areaName2?: string, areaName3?: string, areaName4?: string, postCode?: string) : Promise<{ response: http.IncomingMessage; body: AddressesCount; }> {
const localVarPath = this.basePath + '/addresses/v1/addresscount/byboundaryname';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'country' is not null or undefined
if (country === null || country === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter country was null or undefined when calling getAddressesCountByBoundaryName."}]}})
}
if (areaName1 !== undefined) {
queryParameters['areaName1'] = areaName1;
}
if (areaName2 !== undefined) {
queryParameters['areaName2'] = areaName2;
}
if (areaName3 !== undefined) {
queryParameters['areaName3'] = areaName3;
}
if (areaName4 !== undefined) {
queryParameters['areaName4'] = areaName4;
}
if (postCode !== undefined) {
queryParameters['postCode'] = postCode;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: AddressesCount; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Addresses by Boundary.
* This service accepts custom geographic boundaries or drivetimes & drive distances, returns all known & valid addresses within these boundaries.
* @param body
*/
public getAddressesbyBoundary (body?: AddressesByBoundaryRequest) : Promise<{ response: http.IncomingMessage; body: AddressesResponse; }> {
const localVarPath = this.basePath + '/addresses/v1/address/byboundary';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: AddressesResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum DemographicsServiceApiApiKeys {
}
export class DemographicsServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: DemographicsServiceApiApiKeys, value: string) {
this.authentications[DemographicsServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Demographics Advanced Endpoint
* Demographics Advanced Endpoint will return the aggregated values of the selected demographics variables of the regions falling inside a user provided geometry or travel time/distance boundaries. All the intersecting demographic boundaries will be snapped completely, and user will have option to request these boundaries in response.
* @param body
*/
public getDemographicsAdvanced (body?: DemographicsAdvancedRequest) : Promise<{ response: http.IncomingMessage; body: Demographics; }> {
const localVarPath = this.basePath + '/demographics-segmentation/v1/advanced/demographics';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Demographics; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Demographics Basic
* Demographics Basic Endpoint will return the aggregated values of the selected demographics variables of the regions falling inside the search radius. All the intersecting demographic boundaries will be snapped completely and user will have option to request these boundaries in response.
* @param address Address to be searched
* @param longitude Longitude of the location
* @param latitude Latitude of the location
* @param searchRadius Radius within which demographics details are required. Max. value is 52800 Feet or 10 miles
* @param searchRadiusUnit Radius unit such as Feet, Kilometers, Miles or Meters
* @param travelTime Travel Time based on ‘travelMode’ within which demographics details are required. Max. value is 1 hour.
* @param travelTimeUnit minutes,hours,seconds,milliseconds. Default is meters.Default is minutes.
* @param travelDistance Travel Distance based on ‘travelMode’ within which demographics details are required. Max. value is 10 miles.
* @param travelDistanceUnit feet,kilometers,miles,meters. Default is feet.
* @param travelMode Default is driving.
* @param country 3 digit ISO country code (Used in case address is mentioned).
* @param profile Applicable on ranged variables. Returns top sorted result based on the input value.
* @param filter If Y, demographic boundaries are returned in response.
* @param includeGeometry
*/
public getDemographicsBasic (address?: string, longitude?: string, latitude?: string, searchRadius?: string, searchRadiusUnit?: string, travelTime?: string, travelTimeUnit?: string, travelDistance?: string, travelDistanceUnit?: string, travelMode?: string, country?: string, profile?: string, filter?: string, includeGeometry?: string) : Promise<{ response: http.IncomingMessage; body: Demographics; }> {
const localVarPath = this.basePath + '/demographics-segmentation/v1/basic/demographics';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
if (address !== undefined) {
queryParameters['address'] = address;
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (searchRadius !== undefined) {
queryParameters['searchRadius'] = searchRadius;
}
if (searchRadiusUnit !== undefined) {
queryParameters['searchRadiusUnit'] = searchRadiusUnit;
}
if (travelTime !== undefined) {
queryParameters['travelTime'] = travelTime;
}
if (travelTimeUnit !== undefined) {
queryParameters['travelTimeUnit'] = travelTimeUnit;
}
if (travelDistance !== undefined) {
queryParameters['travelDistance'] = travelDistance;
}
if (travelDistanceUnit !== undefined) {
queryParameters['travelDistanceUnit'] = travelDistanceUnit;
}
if (travelMode !== undefined) {
queryParameters['travelMode'] = travelMode;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (profile !== undefined) {
queryParameters['profile'] = profile;
}
if (filter !== undefined) {
queryParameters['filter'] = filter;
}
if (includeGeometry !== undefined) {
queryParameters['includeGeometry'] = includeGeometry;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Demographics; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Demographics By Address.
* Provides the demographic details around a specified address. GeoLife 'byaddress' service accepts address as an input to return a specific population segment's age group, ethnicity, income, purchasing behaviour, commuter patterns and more.
* @param address The address to be searched.
* @param country 3 letter ISO code of the country to be searched.Allowed values USA,CAN,GBR,AUS.
* @param profile Retrieves the sorted demographic data on the basis of pre-defined profiles that can display the top 3 or top 5 results (by address) either in ascending or descending order.Allowed values Top5Ascending,Top5Descending,Top3Ascending,Top3Descending
* @param filter The 'filter' parameter retrieves the demographic data based upon specified input themes.
* @param valueFormat The 'valueFormat' parameter is applicable for few ranged variables where percent & count both are available and filter response based on the input value.
* @param variableLevel The 'variableLevel' retrieves demographic facts in response based on the input value
*/
public getDemographicsByAddressV2 (address: string, country?: string, profile?: string, filter?: string, valueFormat?: string, variableLevel?: string) : Promise<{ response: http.IncomingMessage; body: Demographics; }> {
const localVarPath = this.basePath + '/demographics-segmentation/v1/demographics/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getDemographicsByAddressV2."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (profile !== undefined) {
queryParameters['profile'] = profile;
}
if (filter !== undefined) {
queryParameters['filter'] = filter;
}
if (valueFormat !== undefined) {
queryParameters['valueFormat'] = valueFormat;
}
if (variableLevel !== undefined) {
queryParameters['variableLevel'] = variableLevel;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Demographics; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Demographics By Boundaryids.
* This endpoint will allow the user to request demographics details by census boundary id. Multiple comma separated boundary ids will be accepted.
* @param boundaryIds Accepts comma separated multiple boundary ids.
* @param profile Applicable on ranged variables. Returns top sorted result based on the input value.
* @param filter Accept the comma separated theme names and filter response based on value. Maximum 10 can be provided.
* @param valueFormat Applicable for few ranged variables where percent & count both are available and filter response based on the input value.
* @param variableLevel Retrieves demographic facts in response based on the input value.
*/
public getDemographicsByBoundaryIds (boundaryIds?: string, profile?: string, filter?: string, valueFormat?: string, variableLevel?: string) : Promise<{ response: http.IncomingMessage; body: Demographics; }> {
const localVarPath = this.basePath + '/demographics-segmentation/v1/demographics/byboundaryids';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
if (boundaryIds !== undefined) {
queryParameters['boundaryIds'] = boundaryIds;
}
if (profile !== undefined) {
queryParameters['profile'] = profile;
}
if (filter !== undefined) {
queryParameters['filter'] = filter;
}
if (valueFormat !== undefined) {
queryParameters['valueFormat'] = valueFormat;
}
if (variableLevel !== undefined) {
queryParameters['variableLevel'] = variableLevel;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Demographics; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Demographics By Location.
* Provides the demographic details around a specified location. GeoLife 'bylocation' service accepts longitude and latitude as an input to return a specific population segment's age group, ethnicity, income, purchasing behaviour, commuter patterns and more.
* @param longitude Longitude of the location.
* @param latitude Latitude of the location.
* @param profile Retrieves the sorted demographic data on the basis of pre-defined profiles that can display the top 3 or top 5 results (by location) either in ascending or descending order.Allowed values Top5Ascending,Top5Descending,Top3Ascending,Top3Descending
* @param filter The 'filter' parameter retrieves the demographic data based upon specified input themes.
* @param valueFormat The 'valueFormat' parameter is applicable for few ranged variables where percent & count both are available and filter response based on the input value.
* @param variableLevel The 'variableLevel' retrieves demographic facts in response based on the input value
*/
public getDemographicsByLocationV2 (longitude: string, latitude: string, profile?: string, filter?: string, valueFormat?: string, variableLevel?: string) : Promise<{ response: http.IncomingMessage; body: Demographics; }> {
const localVarPath = this.basePath + '/demographics-segmentation/v1/demographics/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getDemographicsByLocationV2."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getDemographicsByLocationV2."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (profile !== undefined) {
queryParameters['profile'] = profile;
}
if (filter !== undefined) {
queryParameters['filter'] = filter;
}
if (valueFormat !== undefined) {
queryParameters['valueFormat'] = valueFormat;
}
if (variableLevel !== undefined) {
queryParameters['variableLevel'] = variableLevel;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Demographics; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Segmentation By Address.
* Provides the segmentation details around a specified address. GeoLife 'Segmentation by Address' service accepts address as an input to return the lifestyle characteristics of households in terms of their family status, children characteristics, income behaviors, financial preferences and interests.
* @param address The address to be searched.
* @param country 3 letter ISO code of the country to be searched.Allowed values USA,CAN,GBR,FRA,ITA,AUS,DEU.
*/
public getSegmentationByAddress (address: string, country?: string) : Promise<{ response: http.IncomingMessage; body: Segmentation; }> {
const localVarPath = this.basePath + '/demographics-segmentation/v1/segmentation/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getSegmentationByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Segmentation; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Segmentation By Location.
* Provides the segmentation details around a specified location. GeoLife 'segmentation bylocation' service accepts longitude and latitude as an input to return the lifestyle characteristics of households in terms of their family status, children characteristics, income behaviors, financial preferences and interests.
* @param longitude Longitude of the location.
* @param latitude Latitude of the location.
*/
public getSegmentationByLocation (longitude: string, latitude: string) : Promise<{ response: http.IncomingMessage; body: Segmentation; }> {
const localVarPath = this.basePath + '/demographics-segmentation/v1/segmentation/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getSegmentationByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getSegmentationByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Segmentation; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum EmailVerificationServiceApiApiKeys {
}
export class EmailVerificationServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: EmailVerificationServiceApiApiKeys, value: string) {
this.authentications[EmailVerificationServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* ValidateEmailAddress
* Confirm that your customer’s mailing address exists and that mail and packages can be delivered to it.
* @param inputEmailAddress
*/
public validateEmailAddress (inputEmailAddress: ValidateEmailAddressAPIRequest) : Promise<{ response: http.IncomingMessage; body: ValidateEmailAddressAPIResponse; }> {
const localVarPath = this.basePath + '/emailverification/v1/validateemailaddress/results.json';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'inputEmailAddress' is not null or undefined
if (inputEmailAddress === null || inputEmailAddress === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter inputEmailAddress was null or undefined when calling validateEmailAddress."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: inputEmailAddress,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: ValidateEmailAddressAPIResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum GeocodeServiceApiApiKeys {
}
export class GeocodeServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: GeocodeServiceApiApiKeys, value: string) {
this.authentications[GeocodeServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Get Forward Geocode
* This service accepts an address and returns the location coordinates corresponding to that address. Premium offers the best accuracy and is a high precision geocoder leveraging Master Location Data - geocodes to Street or building level.
* @param datapackBundle value of datapackBundle
* @param country Country name or ISO code.
* @param placeName Building name, place name, Point of Interest (POI), company or firm name associated with the input address.
* @param mainAddress Single line input, treated as collection of field elements.
* @param lastLine The last line of the address.
* @param areaName1 Specifies the largest geographical area, typically a state or province.
* @param areaName2 Specifies the secondary geographic area, typically a county or district.
* @param areaName3 Specifies a city or town name.
* @param areaName4 Specifies a city subdivision or locality.
* @param postalCode The postal code in the appropriate format for the country.
* @param matchMode Match modes determine the leniency used to make a match between the input address and the reference data.
* @param fallbackGeo Specifies whether to attempt to determine a geographic region centroid when an address-level geocode cannot be determined.
* @param fallbackPostal Specifies whether to attempt to determine a post code centroid when an address-level geocode cannot be determined.
* @param maxCands The maximum number of candidates to return.
* @param streetOffset Indicates the offset distance from the street segments to use in street-level geocoding.
* @param streetOffsetUnits Specifies the unit of measurement for the street offset.
* @param cornerOffset Specifies the distance to offset the street end points in street-level matching.
* @param cornerOffsetUnits Specifies the unit of measurement for the corner offset.
*/
public geocode (datapackBundle: string, country?: string, placeName?: string, mainAddress?: string, lastLine?: string, areaName1?: string, areaName2?: string, areaName3?: string, areaName4?: string, postalCode?: number, matchMode?: string, fallbackGeo?: boolean, fallbackPostal?: boolean, maxCands?: number, streetOffset?: number, streetOffsetUnits?: string, cornerOffset?: number, cornerOffsetUnits?: string) : Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponse; }> {
const localVarPath = this.basePath + '/geocode/v1/{datapackBundle}/geocode'
.replace('{' + 'datapackBundle' + '}', String(datapackBundle));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'datapackBundle' is not null or undefined
if (datapackBundle === null || datapackBundle === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter datapackBundle was null or undefined when calling geocode."}]}})
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (placeName !== undefined) {
queryParameters['placeName'] = placeName;
}
if (mainAddress !== undefined) {
queryParameters['mainAddress'] = mainAddress;
}
if (lastLine !== undefined) {
queryParameters['lastLine'] = lastLine;
}
if (areaName1 !== undefined) {
queryParameters['areaName1'] = areaName1;
}
if (areaName2 !== undefined) {
queryParameters['areaName2'] = areaName2;
}
if (areaName3 !== undefined) {
queryParameters['areaName3'] = areaName3;
}
if (areaName4 !== undefined) {
queryParameters['areaName4'] = areaName4;
}
if (postalCode !== undefined) {
queryParameters['postalCode'] = postalCode;
}
if (matchMode !== undefined) {
queryParameters['matchMode'] = matchMode;
}
if (fallbackGeo !== undefined) {
queryParameters['fallbackGeo'] = fallbackGeo;
}
if (fallbackPostal !== undefined) {
queryParameters['fallbackPostal'] = fallbackPostal;
}
if (maxCands !== undefined) {
queryParameters['maxCands'] = maxCands;
}
if (streetOffset !== undefined) {
queryParameters['streetOffset'] = streetOffset;
}
if (streetOffsetUnits !== undefined) {
queryParameters['streetOffsetUnits'] = streetOffsetUnits;
}
if (cornerOffset !== undefined) {
queryParameters['cornerOffset'] = cornerOffset;
}
if (cornerOffsetUnits !== undefined) {
queryParameters['cornerOffsetUnits'] = cornerOffsetUnits;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Forward Geocode
* This is a Batch offering for geocode service. It accepts a single address or a list of addresses and returns location coordinates.
* @param body Geocode Request Object
* @param datapackBundle value of datapackBundle
*/
public geocodeBatch (body: GeocodeRequest, datapackBundle: string) : Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponseList; }> {
const localVarPath = this.basePath + '/geocode/v1/{datapackBundle}/geocode'
.replace('{' + 'datapackBundle' + '}', String(datapackBundle));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter body was null or undefined when calling geocodeBatch."}]}})
}
// verify required parameter 'datapackBundle' is not null or undefined
if (datapackBundle === null || datapackBundle === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter datapackBundle was null or undefined when calling geocodeBatch."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Capabilities
* Get Capabilities of Geocode API
* @param datapackBundle value of datapackBundle
* @param operation Geocode or ReverseGeocode Operation.
* @param country Country name or ISO code.
*/
public getCapabilities (datapackBundle: string, operation?: string, country?: string) : Promise<{ response: http.IncomingMessage; body: GeocodeCapabilitiesResponse; }> {
const localVarPath = this.basePath + '/geocode/v1/{datapackBundle}/capabilities'
.replace('{' + 'datapackBundle' + '}', String(datapackBundle));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'datapackBundle' is not null or undefined
if (datapackBundle === null || datapackBundle === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter datapackBundle was null or undefined when calling getCapabilities."}]}})
}
if (operation !== undefined) {
queryParameters['operation'] = operation;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeocodeCapabilitiesResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get installed Dictionaries
* Get installed Dictionaries
* @param datapackBundle value of datapackBundle
* @param country Three Letter ISO Country code
*/
public getDictionaries (datapackBundle: string, country?: string) : Promise<{ response: http.IncomingMessage; body: ConfiguredDictionaryResponse; }> {
const localVarPath = this.basePath + '/geocode/v1/{datapackBundle}/dictionaries'
.replace('{' + 'datapackBundle' + '}', String(datapackBundle));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'datapackBundle' is not null or undefined
if (datapackBundle === null || datapackBundle === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter datapackBundle was null or undefined when calling getDictionaries."}]}})
}
if (country !== undefined) {
queryParameters['country'] = country;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: ConfiguredDictionaryResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get PreciselyID By Address
* This service accepts an address and returns the corresponding PreciselyID.
* @param address free form address text
* @param country Country ISO code.
*/
public getPreciselyID (address: string, country?: string) : Promise<{ response: http.IncomingMessage; body: PBKeyResponse; }> {
const localVarPath = this.basePath + '/geocode/v1/key/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getPreciselyID."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: PBKeyResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post PreciselyID By Address
* This is a Batch offering for 'PreciselyID By Address' service. It accepts a single address or a list of addresses and returns the corresponding PreciselyID.
* @param body
*/
public getPreciselyIDs (body: PBKeyAddressRequest) : Promise<{ response: http.IncomingMessage; body: PBKeyResponseList; }> {
const localVarPath = this.basePath + '/geocode/v1/key/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter body was null or undefined when calling getPreciselyIDs."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: PBKeyResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Key Lookup
* This service accepts a PreciselyID and returns the corresponding address associated with that PreciselyID.
* @param key free form text
* @param type
* @param country
*/
public keyLookup (key: string, type?: string, country?: string) : Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponse; }> {
const localVarPath = this.basePath + '/geocode/v1/keylookup';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'key' is not null or undefined
if (key === null || key === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter key was null or undefined when calling keyLookup."}]}})
}
if (key !== undefined) {
queryParameters['key'] = key;
}
if (type !== undefined) {
queryParameters['type'] = type;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Key Lookup
* This service accepts batches of PreciselyID's and returns the corresponding address associated with those PreciselyID's.
* @param body
*/
public keyLookupBatch (body?: KeyLookupRequest) : Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponseList; }> {
const localVarPath = this.basePath + '/geocode/v1/keylookup';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Reverse Geocode
* It accepts a single location coordinate or a list of location coordinates and returns addresses.
* @param datapackBundle value of datapackBundle
* @param body Request for Reverse Geocode
*/
public reverseGeocodBatch (datapackBundle: string, body?: ReverseGeocodeRequest) : Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponseList; }> {
const localVarPath = this.basePath + '/geocode/v1/{datapackBundle}/reverseGeocode'
.replace('{' + 'datapackBundle' + '}', String(datapackBundle));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'datapackBundle' is not null or undefined
if (datapackBundle === null || datapackBundle === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter datapackBundle was null or undefined when calling reverseGeocodBatch."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Reverse Geocode
* This service accepts location coordinate and returns an address.
* @param datapackBundle value of datapackBundle
* @param x Longitude of the location.
* @param y Latitude of the location.
* @param country Country name or ISO code.
* @param coordSysName Coordinate system to convert geometry to in format codespace:code.
* @param distance Radius in which search is performed.
* @param distanceUnits Unit of measurement.
*/
public reverseGeocode (datapackBundle: string, x: number, y: number, country?: string, coordSysName?: string, distance?: number, distanceUnits?: string) : Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponse; }> {
const localVarPath = this.basePath + '/geocode/v1/{datapackBundle}/reverseGeocode'
.replace('{' + 'datapackBundle' + '}', String(datapackBundle));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'datapackBundle' is not null or undefined
if (datapackBundle === null || datapackBundle === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter datapackBundle was null or undefined when calling reverseGeocode."}]}})
}
// verify required parameter 'x' is not null or undefined
if (x === null || x === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter x was null or undefined when calling reverseGeocode."}]}})
}
// verify required parameter 'y' is not null or undefined
if (y === null || y === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter y was null or undefined when calling reverseGeocode."}]}})
}
if (x !== undefined) {
queryParameters['x'] = x;
}
if (y !== undefined) {
queryParameters['y'] = y;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (coordSysName !== undefined) {
queryParameters['coordSysName'] = coordSysName;
}
if (distance !== undefined) {
queryParameters['distance'] = distance;
}
if (distanceUnits !== undefined) {
queryParameters['distanceUnits'] = distanceUnits;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeocodeServiceResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum GeolocationServiceApiApiKeys {
}
export class GeolocationServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: GeolocationServiceApiApiKeys, value: string) {
this.authentications[GeolocationServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Location By IP Address.
* This service accepts an IP address and returns the location coordinates corresponding to that IP address.
* @param ipAddress This is the ip address of network connected device. It must be a standard IPv4 octet and a valid external address.
*/
public getLocationByIPAddress (ipAddress: string) : Promise<{ response: http.IncomingMessage; body: GeoLocationIpAddr; }> {
const localVarPath = this.basePath + '/geolocation/v1/location/byipaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'ipAddress' is not null or undefined
if (ipAddress === null || ipAddress === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter ipAddress was null or undefined when calling getLocationByIPAddress."}]}})
}
if (ipAddress !== undefined) {
queryParameters['ipAddress'] = ipAddress;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoLocationIpAddr; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Location by WiFi Access Point.
* This service accepts a WiFi access point MAC address and returns the location coordinates corresponding to that access point. Only mac or accessPoint are mandatory parameters (one of them has to be provided), rest are optional.
* @param mac This should be the 48 bit mac address (or BSSID) of wireless access point. Accepted format is Six groups of two hexadecimal digits, separated by hyphens (-) or colons.
* @param ssid The service set identifier for wi-fi access point. It should be alphanumeric with maximum 32 characters.
* @param rsid This is the received signal strength indicator from particular wi-fi access point. It should be a number from -113 to 0 and the unit of this strength is dBm.
* @param speed This is the connection speed for wi-fi. It should be a number from 0 to 6930 and the unit should be Mbps.
* @param accessPoint This is the JSON based list of wifi access points in the vicinity of device to be located. This parameter is helpful in case, multiple wifi points are visible and we want to make sure that the location of device is best calculated considering all the access points location.
*/
public getLocationByWiFiAccessPoint (mac?: string, ssid?: string, rsid?: string, speed?: string, accessPoint?: string) : Promise<{ response: http.IncomingMessage; body: GeoLocationAccessPoint; }> {
const localVarPath = this.basePath + '/geolocation/v1/location/byaccesspoint';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
if (mac !== undefined) {
queryParameters['mac'] = mac;
}
if (ssid !== undefined) {
queryParameters['ssid'] = ssid;
}
if (rsid !== undefined) {
queryParameters['rsid'] = rsid;
}
if (speed !== undefined) {
queryParameters['speed'] = speed;
}
if (accessPoint !== undefined) {
queryParameters['accessPoint'] = accessPoint;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoLocationAccessPoint; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum IdentityProfilesServiceApiApiKeys {
}
export class IdentityProfilesServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: IdentityProfilesServiceApiApiKeys, value: string) {
this.authentications[IdentityProfilesServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Identities By Address
* Accepts an Address as input and returns rich localized Identity profiles, demographics, lifestyle segmentations, neighborhood names, property ownership & values, and social affinity insights from twitter, linkedin, and more along with education, job history and other identity information.
* @param address free form address text
* @param confidence To adjust quality threshold of data returned. Default is HIGH
* @param maxCandidates Number of identities returned in response
* @param theme theme parameter for filtering results
* @param filter filter params
*/
public getIdentityByAddress (address: string, confidence?: string, maxCandidates?: string, theme?: string, filter?: string) : Promise<{ response: http.IncomingMessage; body: IdentityResponse; }> {
const localVarPath = this.basePath + '/identityprofiles/v1/identity/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getIdentityByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (confidence !== undefined) {
queryParameters['confidence'] = confidence;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
if (theme !== undefined) {
queryParameters['theme'] = theme;
}
if (filter !== undefined) {
queryParameters['filter'] = filter;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: IdentityResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Identity By Email
* Accepts an Email address as input and returns rich localized Identity profiles and social affinity insights from twitter, linkedin, and more along with education, job history and other identity information.
* @param email This specifies the email address
* @param confidence To adjust quality threshold of data returned. Default is HIGH
* @param theme theme parameter for filtering results
* @param filter filter params
*/
public getIdentityByEmail (email: string, confidence?: string, theme?: string, filter?: string) : Promise<{ response: http.IncomingMessage; body: Identity; }> {
const localVarPath = this.basePath + '/identityprofiles/v1/identity/byemail';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'email' is not null or undefined
if (email === null || email === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter email was null or undefined when calling getIdentityByEmail."}]}})
}
if (email !== undefined) {
queryParameters['email'] = email;
}
if (confidence !== undefined) {
queryParameters['confidence'] = confidence;
}
if (theme !== undefined) {
queryParameters['theme'] = theme;
}
if (filter !== undefined) {
queryParameters['filter'] = filter;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Identity; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Identity By Twitter
* Accepts a Twiiter handle as input and returns rich localized Identity profiles and social affinity insights from twitter, linkedin, and more along with education, job history and other identity information.
* @param twitter Twitter handle of the identity.
* @param confidence To adjust quality threshold of data returned. Default is HIGH
* @param theme theme parameter for filtering results
* @param filter filter params
*/
public getIdentityByTwitter (twitter: string, confidence?: string, theme?: string, filter?: string) : Promise<{ response: http.IncomingMessage; body: Identity; }> {
const localVarPath = this.basePath + '/identityprofiles/v1/identity/bytwitter';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'twitter' is not null or undefined
if (twitter === null || twitter === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter twitter was null or undefined when calling getIdentityByTwitter."}]}})
}
if (twitter !== undefined) {
queryParameters['twitter'] = twitter;
}
if (confidence !== undefined) {
queryParameters['confidence'] = confidence;
}
if (theme !== undefined) {
queryParameters['theme'] = theme;
}
if (filter !== undefined) {
queryParameters['filter'] = filter;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Identity; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum LocalTaxServiceApiApiKeys {
}
export class LocalTaxServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: LocalTaxServiceApiApiKeys, value: string) {
this.authentications[LocalTaxServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Post Tax By Address
* This is a Batch offering for 'Tax By Address' service. It accepts a single address, purchase amount or a list of addresses, purchase amounts and retrieve applicable taxes.
* @param taxRateTypeId The tax rate id.
* @param body TaxAddressRequest Class Object having tax request.
*/
public getBatchTaxByAddress (taxRateTypeId: string, body: TaxAddressRequest) : Promise<{ response: http.IncomingMessage; body: TaxResponses; }> {
const localVarPath = this.basePath + '/localtax/v1/tax/{taxRateTypeId}/byaddress'
.replace('{' + 'taxRateTypeId' + '}', String(taxRateTypeId));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'taxRateTypeId' is not null or undefined
if (taxRateTypeId === null || taxRateTypeId === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter taxRateTypeId was null or undefined when calling getBatchTaxByAddress."}]}})
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter body was null or undefined when calling getBatchTaxByAddress."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TaxResponses; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Tax By Location
* This is a Batch offering for 'Tax By Location' service. It accepts a single location coordinate, purchase amount or a list of location coordinates, purchase amounts and retrieve applicable tax.
* @param taxRateTypeId The tax rate id.
* @param body TaxAddressRequest Class Object having tax request.
*/
public getBatchTaxByLocation (taxRateTypeId: string, body: TaxLocationRequest) : Promise<{ response: http.IncomingMessage; body: TaxLocationResponses; }> {
const localVarPath = this.basePath + '/localtax/v1/tax/{taxRateTypeId}/bylocation'
.replace('{' + 'taxRateTypeId' + '}', String(taxRateTypeId));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'taxRateTypeId' is not null or undefined
if (taxRateTypeId === null || taxRateTypeId === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter taxRateTypeId was null or undefined when calling getBatchTaxByLocation."}]}})
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter body was null or undefined when calling getBatchTaxByLocation."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TaxLocationResponses; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Taxrate By Address
* This is a Batch offering for 'Taxrate By Address' service. It accepts a single address or a list of addresses and retrieve applicable tax rates.
* @param taxRateTypeId The tax rate id.
* @param body TaxRateAddressRequest Class Object having tax rate request.
*/
public getBatchTaxRateByAddress (taxRateTypeId: string, body: TaxRateAddressRequest) : Promise<{ response: http.IncomingMessage; body: TaxRateResponses; }> {
const localVarPath = this.basePath + '/localtax/v1/taxrate/{taxRateTypeId}/byaddress'
.replace('{' + 'taxRateTypeId' + '}', String(taxRateTypeId));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'taxRateTypeId' is not null or undefined
if (taxRateTypeId === null || taxRateTypeId === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter taxRateTypeId was null or undefined when calling getBatchTaxRateByAddress."}]}})
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter body was null or undefined when calling getBatchTaxRateByAddress."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TaxRateResponses; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Taxrate By Location
* This is a Batch offering for 'Taxrate By Location' service. It accepts a single location coordinate or a list of location coordinates and retrieve applicable tax rates.
* @param taxRateTypeId The tax rate id.
* @param body TaxRateLocationRequest Class Object having tax rate request.
*/
public getBatchTaxRateByLocation (taxRateTypeId: string, body: TaxRateLocationRequest) : Promise<{ response: http.IncomingMessage; body: TaxRateLocationResponses; }> {
const localVarPath = this.basePath + '/localtax/v1/taxrate/{taxRateTypeId}/bylocation'
.replace('{' + 'taxRateTypeId' + '}', String(taxRateTypeId));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'taxRateTypeId' is not null or undefined
if (taxRateTypeId === null || taxRateTypeId === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter taxRateTypeId was null or undefined when calling getBatchTaxRateByLocation."}]}})
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter body was null or undefined when calling getBatchTaxRateByLocation."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TaxRateLocationResponses; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get IPD Tax by Address
* This will accept 'address' as a parameter and will return one or many IPDs details for that region in which address will fall.
* @param address The address to be searched.
* @param returnLatLongFields Y or N (default is N) - Returns Latitude Longitude Fields
* @param latLongFormat (default is Decimal) - Returns Desired Latitude Longitude Format
*/
public getIPDTaxByAddress (address: string, returnLatLongFields?: string, latLongFormat?: string) : Promise<{ response: http.IncomingMessage; body: TaxDistrictResponse; }> {
const localVarPath = this.basePath + '/localtax/v1/taxdistrict/ipd/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getIPDTaxByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (returnLatLongFields !== undefined) {
queryParameters['returnLatLongFields'] = returnLatLongFields;
}
if (latLongFormat !== undefined) {
queryParameters['latLongFormat'] = latLongFormat;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TaxDistrictResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get IPD Tax for batch requests
* Get IPD Tax for batch requests
* @param body IPDTaxByAddressBatchRequest Class Object having IPD tax request
*/
public getIPDTaxByAddressBatch (body: IPDTaxByAddressBatchRequest) : Promise<{ response: http.IncomingMessage; body: TaxDistrictResponseList; }> {
const localVarPath = this.basePath + '/localtax/v1/taxdistrict/ipd/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter body was null or undefined when calling getIPDTaxByAddressBatch."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TaxDistrictResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Tax By Address
* This service calculates and returns taxes applicable at a specific address. Address, purchase amount and supported tax rate type are inputs to the service.
* @param taxRateTypeId The tax rate id.
* @param address The address to be searched.
* @param purchaseAmount The amount on which tax to be calculated.
*/
public getSpecificTaxByAddress (taxRateTypeId: string, address: string, purchaseAmount: string) : Promise<{ response: http.IncomingMessage; body: TaxResponse; }> {
const localVarPath = this.basePath + '/localtax/v1/tax/{taxRateTypeId}/byaddress'
.replace('{' + 'taxRateTypeId' + '}', String(taxRateTypeId));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'taxRateTypeId' is not null or undefined
if (taxRateTypeId === null || taxRateTypeId === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter taxRateTypeId was null or undefined when calling getSpecificTaxByAddress."}]}})
}
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getSpecificTaxByAddress."}]}})
}
// verify required parameter 'purchaseAmount' is not null or undefined
if (purchaseAmount === null || purchaseAmount === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter purchaseAmount was null or undefined when calling getSpecificTaxByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (purchaseAmount !== undefined) {
queryParameters['purchaseAmount'] = purchaseAmount;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TaxResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Tax By Location
* This service calculates and returns tax applicable at a specific location. Longitude, latitude, purchase amount and supported tax rate type are inputs to the service.
* @param taxRateTypeId The tax rate id.
* @param latitude Latitude of the location.
* @param longitude Longitude of the location.
* @param purchaseAmount The amount on which tax to be calculated.
*/
public getSpecificTaxByLocation (taxRateTypeId: string, latitude: string, longitude: string, purchaseAmount: string) : Promise<{ response: http.IncomingMessage; body: TaxResponse; }> {
const localVarPath = this.basePath + '/localtax/v1/tax/{taxRateTypeId}/bylocation'
.replace('{' + 'taxRateTypeId' + '}', String(taxRateTypeId));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'taxRateTypeId' is not null or undefined
if (taxRateTypeId === null || taxRateTypeId === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter taxRateTypeId was null or undefined when calling getSpecificTaxByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getSpecificTaxByLocation."}]}})
}
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getSpecificTaxByLocation."}]}})
}
// verify required parameter 'purchaseAmount' is not null or undefined
if (purchaseAmount === null || purchaseAmount === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter purchaseAmount was null or undefined when calling getSpecificTaxByLocation."}]}})
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (purchaseAmount !== undefined) {
queryParameters['purchaseAmount'] = purchaseAmount;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TaxResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Taxrate By Address
* Retrieves tax rates applicable to a specific address. This service accepts address and supported tax rate type as inputs to retrieve applicable tax rates.
* @param taxRateTypeId The tax rate id.
* @param address The address to be searched.
*/
public getSpecificTaxRateByAddress (taxRateTypeId: string, address: string) : Promise<{ response: http.IncomingMessage; body: TaxRateResponse; }> {
const localVarPath = this.basePath + '/localtax/v1/taxrate/{taxRateTypeId}/byaddress'
.replace('{' + 'taxRateTypeId' + '}', String(taxRateTypeId));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'taxRateTypeId' is not null or undefined
if (taxRateTypeId === null || taxRateTypeId === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter taxRateTypeId was null or undefined when calling getSpecificTaxRateByAddress."}]}})
}
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getSpecificTaxRateByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TaxRateResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Taxrate By Location
* Retrieves tax rates applicable to a specific location. This service accepts longitude, latitude and supported tax rate type as inputs to retrieve applicable tax rates.
* @param taxRateTypeId The tax rate id.
* @param latitude Latitude of the location.
* @param longitude Longitude of the location.
*/
public getSpecificTaxRateByLocation (taxRateTypeId: string, latitude: string, longitude: string) : Promise<{ response: http.IncomingMessage; body: TaxRateResponse; }> {
const localVarPath = this.basePath + '/localtax/v1/taxrate/{taxRateTypeId}/bylocation'
.replace('{' + 'taxRateTypeId' + '}', String(taxRateTypeId));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'taxRateTypeId' is not null or undefined
if (taxRateTypeId === null || taxRateTypeId === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter taxRateTypeId was null or undefined when calling getSpecificTaxRateByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getSpecificTaxRateByLocation."}]}})
}
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getSpecificTaxRateByLocation."}]}})
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TaxRateResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum NeighborhoodsServiceApiApiKeys {
}
export class NeighborhoodsServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: NeighborhoodsServiceApiApiKeys, value: string) {
this.authentications[NeighborhoodsServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Place By Location.
* Identifies and retrieves the nearest neighborhood around a specific location. This Places service accepts latitude & longitude as input and returns a place name.
* @param longitude Longitude of the location.
* @param latitude Latitude of the location.
* @param levelHint Numeric code of geographic hierarchy level which is classified at six levels.Allowed values 1,2,3,4,5,6
*/
public getPlaceByLocation (longitude: string, latitude: string, levelHint?: string) : Promise<{ response: http.IncomingMessage; body: PlaceByLocations; }> {
const localVarPath = this.basePath + '/neighborhoods/v1/place/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getPlaceByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getPlaceByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (levelHint !== undefined) {
queryParameters['levelHint'] = levelHint;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: PlaceByLocations; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum PhoneVerificationServiceApiApiKeys {
}
export class PhoneVerificationServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: PhoneVerificationServiceApiApiKeys, value: string) {
this.authentications[PhoneVerificationServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Phone verification.
* This service accepts a phone number as input and returns details distinguishing landline and wireless numbers and also checks if a wireless number can be located.
* @param phoneNumber E.164 formatted phone number. Accepts digits only. Country Code (1) optional for USA & CAN.
* @param includeNetworkInfo Y or N (default is Y) – if it is N, then network/carrier details will not be added in the response.
*/
public phoneVerification (phoneNumber: string, includeNetworkInfo?: string) : Promise<{ response: http.IncomingMessage; body: PhoneVerification; }> {
const localVarPath = this.basePath + '/phoneverification/v1/phoneVerification';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'phoneNumber' is not null or undefined
if (phoneNumber === null || phoneNumber === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter phoneNumber was null or undefined when calling phoneVerification."}]}})
}
if (phoneNumber !== undefined) {
queryParameters['phoneNumber'] = phoneNumber;
}
if (includeNetworkInfo !== undefined) {
queryParameters['includeNetworkInfo'] = includeNetworkInfo;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: PhoneVerification; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum PlacesServiceApiApiKeys {
}
export class PlacesServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: PlacesServiceApiApiKeys, value: string) {
this.authentications[PlacesServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Returns Category Codes with their sub-categories (if exist), descriptions and SIC Codes mapping
* Accepts first partial digits or full category codes to filter the response
* @param categoryCode Specify starting digits or full category code to filter the response
* @param level Allowed values are 1,2,3. If level=1, then only 4 digits category codes will be returned, level=2 means only 6 digits category codes will be returned, level=3 means only 11 digits category codes will be returned. Multiple comma-separated values will also be accepted. So level='1,2' means return 4 digits and 6 digits category codes.
*/
public getCategoryCodeMetadata (categoryCode?: string, level?: string) : Promise<{ response: http.IncomingMessage; body: GeoEnrichMetadataResponse; }> {
const localVarPath = this.basePath + '/places/v1/metadata/category';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
if (categoryCode !== undefined) {
queryParameters['categoryCode'] = categoryCode;
}
if (level !== undefined) {
queryParameters['level'] = level;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoEnrichMetadataResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Points Of Interest Details By Id
* This service returns complete details of a chosen point of interest by an identifier. The identifier could be selected from Autocomplete API response.
* @param id POI unique Identifier. Accepts only numbers.
*/
public getPOIById (id: string) : Promise<{ response: http.IncomingMessage; body: POIPlaces; }> {
const localVarPath = this.basePath + '/places/v1/poi/{id}'
.replace('{' + 'id' + '}', String(id));
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter id was null or undefined when calling getPOIById."}]}})
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: POIPlaces; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Points of Interest By Address.
* Accepts address as an input to retrieve nearby points of interest.
* @param address Address
* @param country Country
* @param name Matched against Name, BrandName and Trade Name. Partial terms are also matched with fuzziness (max edit distance is 1)
* @param type Matched against the content which defines the type of the poi.
* @param categoryCode Specific Category/Categories Codes for the desired POIs. Accepts a mix of 4 digit (Top Category), 6 digit (Second-Level Category) and 11 digit (Low-Level Category) Category Codes. https://developer.precisely.com/download?CategoryCodes.xlsx
* @param sicCode Specific SIC Codes/Codes for the desired POIs. Accepts a mix of 4 digit (Top Category) and 8 digit (Low-Level Category) SIC Codes.
* @param maxCandidates Maximum number of POIs that can be retrieved.
* @param searchRadius Radius range within which search is performed.
* @param searchRadiusUnit Radius unit such as Feet, Kilometers, Miles or Meters.
* @param travelTime Specifies the travel time within which method searches for results (POIs which can be reached within travel time)the search boundary in terms of time mentioned in 'travelTimeUnit'. The results are retrieved from the polygon formed based on the travel time specified. This means search can be done in the mentioned time results be from the mentioned time.
* @param travelTimeUnit Specifies acceptable time units.Allowed values Minutes,Hours,Seconds and Milliseconds
* @param travelDistance Specifies the search boundary in terms of distance mentioned in 'travelDistanceUnit'. The results are retrieved from the polygon formed based on the travel distance specified.
* @param travelDistanceUnit Specifies acceptable time units.Allowed values Feet,Kilometers,Miles and Meters
* @param travelMode Specifies the available mode of commute. This is required when u r trying to do search by travel distance or travel time. Allowed values driving and walking
* @param sortBy Specifies the order in which POIs are retrieved.
* @param fuzzyOnName Allowed values are Y/N. If N, the search on name will not allow fuzziness.
* @param page Will support pagination, by default 1st page with maxCandidates results are returned.
*/
public getPOIsByAddress (address: string, country?: string, name?: string, type?: string, categoryCode?: string, sicCode?: string, maxCandidates?: string, searchRadius?: string, searchRadiusUnit?: string, travelTime?: string, travelTimeUnit?: string, travelDistance?: string, travelDistanceUnit?: string, travelMode?: string, sortBy?: string, fuzzyOnName?: string, page?: string) : Promise<{ response: http.IncomingMessage; body: GeoEnrichResponse; }> {
const localVarPath = this.basePath + '/places/v1/poi/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getPOIsByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (name !== undefined) {
queryParameters['name'] = name;
}
if (type !== undefined) {
queryParameters['type'] = type;
}
if (categoryCode !== undefined) {
queryParameters['categoryCode'] = categoryCode;
}
if (sicCode !== undefined) {
queryParameters['sicCode'] = sicCode;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
if (searchRadius !== undefined) {
queryParameters['searchRadius'] = searchRadius;
}
if (searchRadiusUnit !== undefined) {
queryParameters['searchRadiusUnit'] = searchRadiusUnit;
}
if (travelTime !== undefined) {
queryParameters['travelTime'] = travelTime;
}
if (travelTimeUnit !== undefined) {
queryParameters['travelTimeUnit'] = travelTimeUnit;
}
if (travelDistance !== undefined) {
queryParameters['travelDistance'] = travelDistance;
}
if (travelDistanceUnit !== undefined) {
queryParameters['travelDistanceUnit'] = travelDistanceUnit;
}
if (travelMode !== undefined) {
queryParameters['travelMode'] = travelMode;
}
if (sortBy !== undefined) {
queryParameters['sortBy'] = sortBy;
}
if (fuzzyOnName !== undefined) {
queryParameters['fuzzyOnName'] = fuzzyOnName;
}
if (page !== undefined) {
queryParameters['page'] = page;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoEnrichResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Points of Interest By Area.
* Accepts postcode or city as an input to retrieve nearby points of interest.
* @param country Country
* @param areaName3 Either areaName3 or postcode is required
* @param postcode1 Either areaName3 or postcode is required
* @param postcode2 postcode extension
* @param name Matched against Name, BrandName and Trade Name. Partial terms are also matched with fuzziness (max edit distance is 1)
* @param type Matched against the content which defines the type of the poi.
* @param categoryCode Specific Category/Categories Codes for the desired POIs. Accepts a mix of 4 digit (Top Category), 6 digit (Second-Level Category) and 11 digit (Low-Level Category) Category Codes. https://developer.precisely.com/download?CategoryCodes.xlsx
* @param sicCode Specific SIC Codes/Codes for the desired POIs. Accepts a mix of 4 digit (Top Category) and 8 digit (Low-Level Category) SIC Codes.
* @param maxCandidates Maximum number of POIs that can be retrieved.
* @param fuzzyOnName Allowed values are Y/N. If N, the search on name will not allow fuzziness.
* @param page Will support pagination, by default 1st page with maxCandidates results are returned.
*/
public getPOIsByArea (country: string, areaName3?: string, postcode1?: string, postcode2?: string, name?: string, type?: string, categoryCode?: string, sicCode?: string, maxCandidates?: string, fuzzyOnName?: string, page?: string) : Promise<{ response: http.IncomingMessage; body: GeoEnrichResponse; }> {
const localVarPath = this.basePath + '/places/v1/poi/byarea';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'country' is not null or undefined
if (country === null || country === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter country was null or undefined when calling getPOIsByArea."}]}})
}
if (areaName3 !== undefined) {
queryParameters['areaName3'] = areaName3;
}
if (postcode1 !== undefined) {
queryParameters['postcode1'] = postcode1;
}
if (postcode2 !== undefined) {
queryParameters['postcode2'] = postcode2;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (name !== undefined) {
queryParameters['name'] = name;
}
if (type !== undefined) {
queryParameters['type'] = type;
}
if (categoryCode !== undefined) {
queryParameters['categoryCode'] = categoryCode;
}
if (sicCode !== undefined) {
queryParameters['sicCode'] = sicCode;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
if (fuzzyOnName !== undefined) {
queryParameters['fuzzyOnName'] = fuzzyOnName;
}
if (page !== undefined) {
queryParameters['page'] = page;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoEnrichResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Points Of Interest By Boundary
* Accepts a user-defined boundary as input and returns all Points of Interest within the boundary. Additionally, user can filter the response by name, type, standard industrial classifications and category codes.
* @param accept
* @param contentType
* @param body
*/
public getPOIsByBoundary (accept?: string, contentType?: string, body?: POIByGeometryRequest) : Promise<{ response: http.IncomingMessage; body: Pois; }> {
const localVarPath = this.basePath + '/places/v1/poi/byboundary';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
headerParams['Accept'] = accept;
headerParams['Content-Type'] = contentType;
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Pois; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Points of Interest By Location.
* Accepts longitude and latitude as an input to retrieve nearby points of interest.
* @param longitude Longitude of the location.
* @param latitude Latitude of the location.
* @param searchText Matched against Name, BrandName and Trade Name. Partial terms are also matched with fuzziness (max edit distance is 1)
* @param type Matched against the content which defines the type of the poi.
* @param categoryCode Specific Category/Categories Codes for the desired POIs. Accepts a mix of 4 digit (Top Category), 6 digit (Second-Level Category) and 11 digit (Low-Level Category) Category Codes. https://developer.precisely.com/download?CategoryCodes.xlsx
* @param sicCode Specific SIC Codes/Codes for the desired POIs. Accepts a mix of 4 digit (Top Category) and 8 digit (Low-Level Category) SIC Codes.
* @param maxCandidates Maximum number of POIs that can be retrieved.
* @param searchRadius Radius range within which search is performed.
* @param searchRadiusUnit Radius unit such as Feet, Kilometers, Miles or Meters.
* @param travelTime Specifies the travel time within which method searches for results (POIs which can be reached within travel time)the search boundary in terms of time mentioned in 'travelTimeUnit'. The results are retrieved from the polygon formed based on the travel time specified. This means search can be done in the mentioned time results be from the mentioned time.
* @param travelTimeUnit Specifies acceptable time units.Allowed values Minutes,Hours,Seconds and Milliseconds
* @param travelDistance Specifies the search boundary in terms of distance mentioned in 'travelDistanceUnit'. The results are retrieved from the polygon formed based on the travel distance specified.
* @param travelDistanceUnit Specifies acceptable time units.Allowed values Feet,Kilometers,Miles and Meters
* @param travelMode Specifies the available mode of commute. This is required when u r trying to do search by travel distance or travel time. Allowed values driving and walking
* @param sortBy Specifies the order in which POIs are retrieved.
* @param fuzzyOnName Allowed values are Y/N. If N, the search on name will not allow fuzziness.
* @param page Will support pagination, by default 1st page with maxCandidates results are returned.
* @param searchOnNameOnly search name description
*/
public getPOIsByLocation (longitude: string, latitude: string, searchText?: string, type?: string, categoryCode?: string, sicCode?: string, maxCandidates?: string, searchRadius?: string, searchRadiusUnit?: string, travelTime?: string, travelTimeUnit?: string, travelDistance?: string, travelDistanceUnit?: string, travelMode?: string, sortBy?: string, fuzzyOnName?: string, page?: string, searchOnNameOnly?: string) : Promise<{ response: http.IncomingMessage; body: GeoEnrichResponse; }> {
const localVarPath = this.basePath + '/places/v1/poi/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getPOIsByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getPOIsByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (searchText !== undefined) {
queryParameters['searchText'] = searchText;
}
if (type !== undefined) {
queryParameters['type'] = type;
}
if (categoryCode !== undefined) {
queryParameters['categoryCode'] = categoryCode;
}
if (sicCode !== undefined) {
queryParameters['sicCode'] = sicCode;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
if (searchRadius !== undefined) {
queryParameters['searchRadius'] = searchRadius;
}
if (searchRadiusUnit !== undefined) {
queryParameters['searchRadiusUnit'] = searchRadiusUnit;
}
if (travelTime !== undefined) {
queryParameters['travelTime'] = travelTime;
}
if (travelTimeUnit !== undefined) {
queryParameters['travelTimeUnit'] = travelTimeUnit;
}
if (travelDistance !== undefined) {
queryParameters['travelDistance'] = travelDistance;
}
if (travelDistanceUnit !== undefined) {
queryParameters['travelDistanceUnit'] = travelDistanceUnit;
}
if (travelMode !== undefined) {
queryParameters['travelMode'] = travelMode;
}
if (sortBy !== undefined) {
queryParameters['sortBy'] = sortBy;
}
if (fuzzyOnName !== undefined) {
queryParameters['fuzzyOnName'] = fuzzyOnName;
}
if (page !== undefined) {
queryParameters['page'] = page;
}
if (searchOnNameOnly !== undefined) {
queryParameters['searchOnNameOnly'] = searchOnNameOnly;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoEnrichResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Point of Interests count By Geometry.
* Accepts geometry/loc/address as an input to count nearby point of interests.
* @param contentType
* @param body
*/
public getPOIsCount (contentType?: string, body?: PoiCountRequest) : Promise<{ response: http.IncomingMessage; body: PoiCount; }> {
const localVarPath = this.basePath + '/places/v1/poicount';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
headerParams['Content-Type'] = contentType;
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: PoiCount; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Returns SIC Codes with their Industry Titles and Category Codes mapping
* Accepts first few partial digits or full SIC codes to filter the response
* @param sicCode Specify starting digits or full sic code to filter the response
* @param level Allowed values are 1,2. If level=1, then only 4 digits sic codes will be returned, level=2 means only 8 digits sic codes will be returned. Multiple comma-separated values will also be accepted. So level='1,2' means return both 4 digits and 8 digits sic codes.
*/
public getSICMetadata (sicCode?: string, level?: string) : Promise<{ response: http.IncomingMessage; body: GeoEnrichMetadataResponse; }> {
const localVarPath = this.basePath + '/places/v1/metadata/sic';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
if (sicCode !== undefined) {
queryParameters['sicCode'] = sicCode;
}
if (level !== undefined) {
queryParameters['level'] = level;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoEnrichMetadataResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Points of Interest Autocomplete.
* POIs-Autocomplete will return POIs predictions based on the full or partial words specified in the search.The search can then be narrowed based on Location, IP Address or Country along with other supporting filters.
* @param longitude Longitude of the location.
* @param latitude Latitude of the location.
* @param searchText Matched against Name, BrandName and Trade Name. Partial terms are also matched with fuzziness (max edit distance is 1)
* @param searchRadius Radius range within which search is performed.
* @param searchRadiusUnit Radius unit such as Feet, Kilometers, Miles or Meters.
* @param travelTime Specifies the travel time within which method searches for results (POIs which can be reached within travel time)the search boundary in terms of time mentioned in 'travelTimeUnit'. The results are retrieved from the polygon formed based on the travel time specified. This means search can be done in the mentioned time results be from the mentioned time.
* @param travelTimeUnit Specifies acceptable time units.Allowed values Minutes,Hours,Seconds and Milliseconds
* @param travelDistance Specifies the search boundary in terms of distance mentioned in 'travelDistanceUnit'. The results are retrieved from the polygon formed based on the travel distance specified.
* @param travelDistanceUnit Specifies acceptable time units.Allowed values Feet,Kilometers,Miles and Meters
* @param travelMode Specifies the available mode of commute. This is required when u r trying to do search by travel distance or travel time. Allowed values driving and walking
* @param country Country
* @param areaName1 Specifies the largest geographical area, typically a state or province.
* @param areaName3 Specifies the name of the city or town.
* @param postcode1 Postal Code of the input to be searched
* @param postcode2 Postcode2
* @param ipAddress IP address of network connected device in standard IPv4 octet and a valid external address.
* @param autoDetectLocation Specifies whether to auto-detect location from IP address. If 'True' is set, the location is detected from the specified ip address. If 'False' is set. the search will happen according to country or location.
* @param type Matched against the content which defines the type of the poi.
* @param categoryCode Specific Category/Categories Codes for the desired POIs. Accepts a mix of 4 digit (Top Category), 6 digit (Second-Level Category) and 11 digit (Low-Level Category) Category Codes. https://developer.precisely.com/download?CategoryCodes.xlsx
* @param sicCode Specific SIC Codes/Codes for the desired POIs. Accepts a mix of 4 digit (Top Category) and 8 digit (Low-Level Category) SIC Codes.
* @param maxCandidates Maximum number of POIs that can be retrieved.
* @param sortBy Specifies the order in which POIs are retrieved.
* @param searchOnNameOnly specifies search on name
*/
public poisAutocomplete (longitude?: string, latitude?: string, searchText?: string, searchRadius?: string, searchRadiusUnit?: string, travelTime?: string, travelTimeUnit?: string, travelDistance?: string, travelDistanceUnit?: string, travelMode?: string, country?: string, areaName1?: string, areaName3?: string, postcode1?: string, postcode2?: string, ipAddress?: string, autoDetectLocation?: string, type?: string, categoryCode?: string, sicCode?: string, maxCandidates?: string, sortBy?: string, searchOnNameOnly?: string) : Promise<{ response: http.IncomingMessage; body: GeoEnrichResponse; }> {
const localVarPath = this.basePath + '/places/v1/poi/autocomplete';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (searchText !== undefined) {
queryParameters['searchText'] = searchText;
}
if (searchRadius !== undefined) {
queryParameters['searchRadius'] = searchRadius;
}
if (searchRadiusUnit !== undefined) {
queryParameters['searchRadiusUnit'] = searchRadiusUnit;
}
if (travelTime !== undefined) {
queryParameters['travelTime'] = travelTime;
}
if (travelTimeUnit !== undefined) {
queryParameters['travelTimeUnit'] = travelTimeUnit;
}
if (travelDistance !== undefined) {
queryParameters['travelDistance'] = travelDistance;
}
if (travelDistanceUnit !== undefined) {
queryParameters['travelDistanceUnit'] = travelDistanceUnit;
}
if (travelMode !== undefined) {
queryParameters['travelMode'] = travelMode;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (areaName1 !== undefined) {
queryParameters['areaName1'] = areaName1;
}
if (areaName3 !== undefined) {
queryParameters['areaName3'] = areaName3;
}
if (postcode1 !== undefined) {
queryParameters['postcode1'] = postcode1;
}
if (postcode2 !== undefined) {
queryParameters['postcode2'] = postcode2;
}
if (ipAddress !== undefined) {
queryParameters['ipAddress'] = ipAddress;
}
if (autoDetectLocation !== undefined) {
queryParameters['autoDetectLocation'] = autoDetectLocation;
}
if (type !== undefined) {
queryParameters['type'] = type;
}
if (categoryCode !== undefined) {
queryParameters['categoryCode'] = categoryCode;
}
if (sicCode !== undefined) {
queryParameters['sicCode'] = sicCode;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
if (sortBy !== undefined) {
queryParameters['sortBy'] = sortBy;
}
if (searchOnNameOnly !== undefined) {
queryParameters['searchOnNameOnly'] = searchOnNameOnly;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoEnrichResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum PropertyInformationServiceApiApiKeys {
}
export class PropertyInformationServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: PropertyInformationServiceApiApiKeys, value: string) {
this.authentications[PropertyInformationServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Get Property Attributes By Address
* Accepts address as input and returns property attributes for the matched address.
* @param address free form address text
*/
public getGeoPropertyByAddress (address: string) : Promise<{ response: http.IncomingMessage; body: GeoPropertyResponse; }> {
const localVarPath = this.basePath + '/property/v1/all/attributes/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getGeoPropertyByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoPropertyResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Property Attributes By Address
* This is a Batch offering for 'Property Attributes By Address' service. It accepts a single address or a list of addresses and returns property attributes for the matched address.
* @param body
*/
public getGeoPropertyByAddressBatch (body?: GeoPropertyAddressRequest) : Promise<{ response: http.IncomingMessage; body: GeoPropertyResponses; }> {
const localVarPath = this.basePath + '/property/v1/all/attributes/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoPropertyResponses; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Parcel Boundary By Address
* Accepts address as input and returns property parcel boundary around that address.
* @param address free form address text
* @param accept
*/
public getParcelBoundaryByAddress (address: string, accept?: string) : Promise<{ response: http.IncomingMessage; body: ParcelBoundary; }> {
const localVarPath = this.basePath + '/property/v1/parcelboundary/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getParcelBoundaryByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
headerParams['Accept'] = accept;
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: ParcelBoundary; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Parcel Boundary By Location
* Accepts latitude/longitude as input and returns property parcel boundary around that location.
* @param longitude Longitude of Location
* @param latitude Latitude of Location
* @param accept
*/
public getParcelBoundaryByLocation (longitude: string, latitude: string, accept?: string) : Promise<{ response: http.IncomingMessage; body: ParcelBoundary; }> {
const localVarPath = this.basePath + '/property/v1/parcelboundary/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getParcelBoundaryByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getParcelBoundaryByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
headerParams['Accept'] = accept;
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: ParcelBoundary; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum RisksServiceApiApiKeys {
}
export class RisksServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: RisksServiceApiApiKeys, value: string) {
this.authentications[RisksServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Get Crime Risk By Address
* Accepts addresses as input and Returns local crime indexes.
* @param address Free-form address text.
* @param type Type of crime like violent crime, property crime, etc., multiple crime type indexes could be requested as comma separated values with 'all' as default.)
* @param includeGeometry Y or N (default is N) - if it is Y, then geometry will be part of response
*/
public getCrimeRiskByAddress (address: string, type?: string, includeGeometry?: string) : Promise<{ response: http.IncomingMessage; body: CrimeRiskResponse; }> {
const localVarPath = this.basePath + '/risks/v1/crime/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getCrimeRiskByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (type !== undefined) {
queryParameters['type'] = type;
}
if (includeGeometry !== undefined) {
queryParameters['includeGeometry'] = includeGeometry;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: CrimeRiskResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Crime Risk By Address
* This is a Batch offering for 'Crime Risk By Address' service. It accepts a single address or a list of addresses and retrieve local crime indexes.
* @param body
*/
public getCrimeRiskByAddressBatch (body?: CrimeRiskByAddressRequest) : Promise<{ response: http.IncomingMessage; body: CrimeRiskResponseList; }> {
const localVarPath = this.basePath + '/risks/v1/crime/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: CrimeRiskResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Crime Risk By Location
* Returns the crime data or crime indexes for a given location.
* @param longitude The longitude of the location
* @param latitude The latitude of the location
* @param type Refers to crime type. Valid values are following 11 crime types with 'all' as default (more than one can also be given as comma separated types)
* @param includeGeometry Y or N (default is N) - if it is Y, then geometry will be part of response
*/
public getCrimeRiskByLocation (longitude: string, latitude: string, type?: string, includeGeometry?: string) : Promise<{ response: http.IncomingMessage; body: CrimeRiskLocationResponse; }> {
const localVarPath = this.basePath + '/risks/v1/crime/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getCrimeRiskByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getCrimeRiskByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (type !== undefined) {
queryParameters['type'] = type;
}
if (includeGeometry !== undefined) {
queryParameters['includeGeometry'] = includeGeometry;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: CrimeRiskLocationResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Crime Risk By Location
* This is a Batch offering for 'Crime Risk By Location' service. It accepts a single location coordinate or a list of location coordinates and retrieve local crime indexes.
* @param body
*/
public getCrimeRiskByLocationBatch (body?: CrimeRiskByLocationRequest) : Promise<{ response: http.IncomingMessage; body: CrimeRiskLocationResponseList; }> {
const localVarPath = this.basePath + '/risks/v1/crime/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: CrimeRiskLocationResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Distance To Flood Hazard By Address
* Accepts addresses as input and Returns the distance from nearest water bodies along with body name and location.
* @param address The address of the location
* @param maxCandidates This specifies the value of maxCandidates
* @param waterBodyType all (default value), oceanandsea,lake,others,unknown,intermittent
* @param searchDistance This specifies the search distance
* @param searchDistanceUnit miles (default value),feet, kilometers, meters
*/
public getDistanceToFloodHazardByAddress (address: string, maxCandidates?: string, waterBodyType?: string, searchDistance?: string, searchDistanceUnit?: string) : Promise<{ response: http.IncomingMessage; body: WaterBodyResponse; }> {
const localVarPath = this.basePath + '/risks/v1/shoreline/distancetofloodhazard/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getDistanceToFloodHazardByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
if (waterBodyType !== undefined) {
queryParameters['waterBodyType'] = waterBodyType;
}
if (searchDistance !== undefined) {
queryParameters['searchDistance'] = searchDistance;
}
if (searchDistanceUnit !== undefined) {
queryParameters['searchDistanceUnit'] = searchDistanceUnit;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: WaterBodyResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Distance To Flood Hazard By Address
* This is a Batch offering for 'Distance To Flood Hazard By Address' service. It accepts a single address or a list of addresses and retrieve the distance from nearest water bodies along with body name and location.
* @param body
*/
public getDistanceToFloodHazardByAddressBatch (body?: DistanceToFloodHazardAddressRequest) : Promise<{ response: http.IncomingMessage; body: DistanceToFloodHazardResponse; }> {
const localVarPath = this.basePath + '/risks/v1/shoreline/distancetofloodhazard/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: DistanceToFloodHazardResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Distance To Flood Hazard By Location
* Accepts latitude & longitude as input and Returns the distance from nearest water bodies along with body name and location.
* @param longitude The longitude of the location
* @param latitude The latitude of the location
* @param maxCandidates This specifies the value of maxCandidates
* @param waterBodyType all (default value), oceanandsea,lake,others,unknown,intermittent
* @param searchDistance This specifies the search distance
* @param searchDistanceUnit miles (default value),feet, kilometers, meters
*/
public getDistanceToFloodHazardByLocation (longitude: string, latitude: string, maxCandidates?: string, waterBodyType?: string, searchDistance?: string, searchDistanceUnit?: string) : Promise<{ response: http.IncomingMessage; body: WaterBodyLocationResponse; }> {
const localVarPath = this.basePath + '/risks/v1/shoreline/distancetofloodhazard/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getDistanceToFloodHazardByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getDistanceToFloodHazardByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
if (waterBodyType !== undefined) {
queryParameters['waterBodyType'] = waterBodyType;
}
if (searchDistance !== undefined) {
queryParameters['searchDistance'] = searchDistance;
}
if (searchDistanceUnit !== undefined) {
queryParameters['searchDistanceUnit'] = searchDistanceUnit;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: WaterBodyLocationResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Distance To Flood Hazard By Location
* This is a Batch offering for 'Distance To Flood Hazard By Location' service. It accepts a single location coordinate or a list of location coordinates and retrieve the distance from nearest water bodies along with body name and location.
* @param body
*/
public getDistanceToFloodHazardByLocationBatch (body?: DistanceToFloodHazardLocationRequest) : Promise<{ response: http.IncomingMessage; body: DistanceToFloodHazardLocationResponse; }> {
const localVarPath = this.basePath + '/risks/v1/shoreline/distancetofloodhazard/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: DistanceToFloodHazardLocationResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Earthquake History
* Accepts postcode as input and Returns historical earthquake details for a particular postcode.
* @param postCode 5 digit Postal code to search
* @param startDate Start time in milliseconds(UTC)
* @param endDate End time in milliseconds(UTC)
* @param minMagnitude Minimum richter scale magnitude
* @param maxMagnitude Maximum Richter scale magnitude
* @param maxCandidates Maximum response events
*/
public getEarthquakeHistory (postCode: string, startDate?: string, endDate?: string, minMagnitude?: string, maxMagnitude?: string, maxCandidates?: string) : Promise<{ response: http.IncomingMessage; body: EarthquakeHistory; }> {
const localVarPath = this.basePath + '/risks/v1/earthquakehistory';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'postCode' is not null or undefined
if (postCode === null || postCode === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter postCode was null or undefined when calling getEarthquakeHistory."}]}})
}
if (postCode !== undefined) {
queryParameters['postCode'] = postCode;
}
if (startDate !== undefined) {
queryParameters['startDate'] = startDate;
}
if (endDate !== undefined) {
queryParameters['endDate'] = endDate;
}
if (minMagnitude !== undefined) {
queryParameters['minMagnitude'] = minMagnitude;
}
if (maxMagnitude !== undefined) {
queryParameters['maxMagnitude'] = maxMagnitude;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: EarthquakeHistory; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Earthquake Risk By Address
* Accepts addresses as input and Returns counts of earthquakes for various richter measurements and values.
* @param address Free-form address text
* @param richterValue Richter values like R5 (count of richter scale 5 events), R7 (count of richter scale 7 events), R6_GE (count of events >= richter scale 6), etc., multiple richter scales could be requested as comma separated values with 'all' as default. Valid values: All (default value), R0, R1, R2, R3, R4, R5, R6, R7, R0_GE, R1_GE, R2_GE, R3_GE, R4_GE, R5_GE, R6_GE, R7_GE
* @param includeGeometry Y or N (default is N) - if it is Y, then geometry will be part of response
*/
public getEarthquakeRiskByAddress (address: string, richterValue?: string, includeGeometry?: string) : Promise<{ response: http.IncomingMessage; body: EarthquakeRiskResponse; }> {
const localVarPath = this.basePath + '/risks/v1/earthquake/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getEarthquakeRiskByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (richterValue !== undefined) {
queryParameters['richterValue'] = richterValue;
}
if (includeGeometry !== undefined) {
queryParameters['includeGeometry'] = includeGeometry;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: EarthquakeRiskResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Earthquake Risk By Address
* This is a Batch offering for 'Earthquake Risk By Address' service. It accepts a single address or a list of addresses and retrieve counts of earthquakes for various richter measurements and values.
* @param body
*/
public getEarthquakeRiskByAddressBatch (body?: EarthquakeRiskByAddressRequest) : Promise<{ response: http.IncomingMessage; body: EarthquakeRiskResponseList; }> {
const localVarPath = this.basePath + '/risks/v1/earthquake/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: EarthquakeRiskResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Earthquake Risk By Location
* Accepts latitude & longitude as input and Returns counts of earthquakes for various richter measurements and values.
* @param longitude The longitude of the location
* @param latitude The latitude of the location
* @param richterValue Richter values like R5 (count of richter scale 5 events), R7 (count of richter scale 7 events), R6_GE (count of events >= richter scale 6), etc., multiple richter scales could be requested as comma separated values with 'all' as default. Valid values: All (default value), R0, R1, R2, R3, R4, R5, R6, R7, R0_GE, R1_GE, R2_GE, R3_GE, R4_GE, R5_GE, R6_GE, R7_GE
* @param includeGeometry Y or N (default is N) - if it is Y, then geometry will be part of response
*/
public getEarthquakeRiskByLocation (longitude: string, latitude: string, richterValue?: string, includeGeometry?: string) : Promise<{ response: http.IncomingMessage; body: EarthquakeRiskLocationResponse; }> {
const localVarPath = this.basePath + '/risks/v1/earthquake/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getEarthquakeRiskByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getEarthquakeRiskByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (richterValue !== undefined) {
queryParameters['richterValue'] = richterValue;
}
if (includeGeometry !== undefined) {
queryParameters['includeGeometry'] = includeGeometry;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: EarthquakeRiskLocationResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Earthquake Risk By Location
* This is a Batch offering for 'Earthquake Risk By Location' service. It accepts a single location coordinate or a list of location coordinates and retrieve counts of earthquakes for various richter measurements and values.
* @param body
*/
public getEarthquakeRiskByLocationBatch (body?: EarthquakeRiskByLocationRequest) : Promise<{ response: http.IncomingMessage; body: EarthquakeRiskLocationResponseList; }> {
const localVarPath = this.basePath + '/risks/v1/earthquake/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: EarthquakeRiskLocationResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Fire History
* Accepts postcode as input and Returns fire event details for a particular postcode.
* @param postCode 5 digit Postal code to search
* @param startDate Start time in milliseconds(UTC)
* @param endDate End time in milliseconds(UTC)
* @param maxCandidates Maximum response events
*/
public getFireHistory (postCode: string, startDate?: string, endDate?: string, maxCandidates?: string) : Promise<{ response: http.IncomingMessage; body: FireHistory; }> {
const localVarPath = this.basePath + '/risks/v1/firehistory';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'postCode' is not null or undefined
if (postCode === null || postCode === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter postCode was null or undefined when calling getFireHistory."}]}})
}
if (postCode !== undefined) {
queryParameters['postCode'] = postCode;
}
if (startDate !== undefined) {
queryParameters['startDate'] = startDate;
}
if (endDate !== undefined) {
queryParameters['endDate'] = endDate;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: FireHistory; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Fire Risk By Address
* Accepts addresses as input and Returns fire risk data by risk types.
* @param address Free-form address text
*/
public getFireRiskByAddress (address: string) : Promise<{ response: http.IncomingMessage; body: FireRiskResponse; }> {
const localVarPath = this.basePath + '/risks/v1/fire/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getFireRiskByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: FireRiskResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Fire Risk By Address
* This is a Batch offering for 'Fire Risk By Address' service. It accepts a single address or a list of addresses and retrieve fire risk data by risk types.
* @param body
*/
public getFireRiskByAddressBatch (body?: FireRiskByAddressRequest) : Promise<{ response: http.IncomingMessage; body: FireRiskResponseList; }> {
const localVarPath = this.basePath + '/risks/v1/fire/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: FireRiskResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Fire Risk By Location
* Accepts latitude & longitude as input and Returns fire risk data by risk types.
* @param longitude Longitude of Location
* @param latitude Latitude of Location
*/
public getFireRiskByLocation (longitude: string, latitude: string) : Promise<{ response: http.IncomingMessage; body: FireRiskLocationResponse; }> {
const localVarPath = this.basePath + '/risks/v1/fire/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getFireRiskByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getFireRiskByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: FireRiskLocationResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Fire Risk By Location
* This is a Batch offering for 'Fire Risk By Location' service. It accepts a single location coordinate or a list of location coordinates and retrieve fire risk data by risk types.
* @param body
*/
public getFireRiskByLocationBatch (body?: FireRiskByLocationRequest) : Promise<{ response: http.IncomingMessage; body: FireRiskLocationResponseList; }> {
const localVarPath = this.basePath + '/risks/v1/fire/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: FireRiskLocationResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Fire Station By Address
* Accepts addresses as input and Returns nearest fire stations.
* @param address The address to be searched.
* @param maxCandidates Specifies the maximum number of fire stations that this service retrieves. The default value is 3 and maximum value is 5. The retrieved results are traveldistance sorted from the input location.
* @param travelTime Max travel time from input location to fire station. Maximum allowed is 2 hours
* @param travelTimeUnit Travel time unit such as minutes (default), hours, seconds or milliseconds.
* @param travelDistance Maximum travel distance from input location to fire station. Maximum allowed is 50 miles
* @param travelDistanceUnit Travel distance unit such as Feet (default), Kilometers, Miles or Meters.
* @param sortBy Sort the fire stations results by either travel time or travel distance (nearest first). Default sorting is by travel time.
* @param historicTrafficTimeBucket Historic traffic time slab
*/
public getFireStationByAddress (address: string, maxCandidates?: string, travelTime?: string, travelTimeUnit?: string, travelDistance?: string, travelDistanceUnit?: string, sortBy?: string, historicTrafficTimeBucket?: string) : Promise<{ response: http.IncomingMessage; body: FireStations; }> {
const localVarPath = this.basePath + '/risks/v1/firestation/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getFireStationByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
if (travelTime !== undefined) {
queryParameters['travelTime'] = travelTime;
}
if (travelTimeUnit !== undefined) {
queryParameters['travelTimeUnit'] = travelTimeUnit;
}
if (travelDistance !== undefined) {
queryParameters['travelDistance'] = travelDistance;
}
if (travelDistanceUnit !== undefined) {
queryParameters['travelDistanceUnit'] = travelDistanceUnit;
}
if (sortBy !== undefined) {
queryParameters['sortBy'] = sortBy;
}
if (historicTrafficTimeBucket !== undefined) {
queryParameters['historicTrafficTimeBucket'] = historicTrafficTimeBucket;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: FireStations; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Fire Station By Location
* Accepts latitude & longitude as input and Returns nearest fire stations.
* @param longitude Longitude of Location
* @param latitude Latitude of Location
* @param maxCandidates Specifies the maximum number of fire stations that this service retrieves. The default value is 3. The retrieved fire stations are distance ordered from the specified location. Maximum of 5 fire stations can be retrieved.
* @param travelTime Maximum travel time from input location to fire station. Maximum allowed is 2 hours
* @param travelTimeUnit Travel time unit such as minutes (default), hours, seconds or milliseconds.
* @param travelDistance Maximum travel distance from input location to fire station. Maximum allowed is 50 miles
* @param travelDistanceUnit Travel distance unit such as Feet (default), Kilometers, Miles or Meters.
* @param sortBy Sorting of fire stations in result by travel time/distance (nearest first from input location).
* @param historicTrafficTimeBucket Historic traffic time slab
*/
public getFireStationByLocation (longitude: string, latitude: string, maxCandidates?: string, travelTime?: string, travelTimeUnit?: string, travelDistance?: string, travelDistanceUnit?: string, sortBy?: string, historicTrafficTimeBucket?: string) : Promise<{ response: http.IncomingMessage; body: FireStationsLocation; }> {
const localVarPath = this.basePath + '/risks/v1/firestation/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getFireStationByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getFireStationByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
if (travelTime !== undefined) {
queryParameters['travelTime'] = travelTime;
}
if (travelTimeUnit !== undefined) {
queryParameters['travelTimeUnit'] = travelTimeUnit;
}
if (travelDistance !== undefined) {
queryParameters['travelDistance'] = travelDistance;
}
if (travelDistanceUnit !== undefined) {
queryParameters['travelDistanceUnit'] = travelDistanceUnit;
}
if (sortBy !== undefined) {
queryParameters['sortBy'] = sortBy;
}
if (historicTrafficTimeBucket !== undefined) {
queryParameters['historicTrafficTimeBucket'] = historicTrafficTimeBucket;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: FireStationsLocation; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Flood Risk By Address
* Accepts addresses as input and Returns flood risk data for flood zones and base flood elevation values.
* @param address Free-text Address
* @param includeZoneDesc Specifies primary zone description. Valid Values: 'Y' or 'N'.
* @param includeGeometry Y or N (default is N) - if it is Y, then geometry will be part of response
*/
public getFloodRiskByAddress (address: string, includeZoneDesc?: string, includeGeometry?: string) : Promise<{ response: http.IncomingMessage; body: FloodRiskResponse; }> {
const localVarPath = this.basePath + '/risks/v1/flood/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getFloodRiskByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (includeZoneDesc !== undefined) {
queryParameters['includeZoneDesc'] = includeZoneDesc;
}
if (includeGeometry !== undefined) {
queryParameters['includeGeometry'] = includeGeometry;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: FloodRiskResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Flood Risk By Address
* This is a Batch offering for 'Flood Risk By Address' service. It accepts a single address or a list of addresses and retrieve flood risk data for flood zones and base flood elevation values.
* @param body
*/
public getFloodRiskByAddressBatch (body?: FloodRiskByAddressRequest) : Promise<{ response: http.IncomingMessage; body: FloodRiskResponseList; }> {
const localVarPath = this.basePath + '/risks/v1/flood/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: FloodRiskResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Flood Risk By Location
* Accepts latitude & longitude as input and Returns flood risk data for flood zones and base flood elevation values.
* @param longitude Longitude of Location
* @param latitude Latitude of Location
* @param includeZoneDesc Specifies primary zone description. Valid Values: 'Y' or 'N'. Default: 'Y'
* @param includeGeometry Y or N (default is N) - if it is Y, then geometry will be part of response
*/
public getFloodRiskByLocation (longitude: string, latitude: string, includeZoneDesc?: string, includeGeometry?: string) : Promise<{ response: http.IncomingMessage; body: FloodRiskLocationResponse; }> {
const localVarPath = this.basePath + '/risks/v1/flood/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getFloodRiskByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getFloodRiskByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (includeZoneDesc !== undefined) {
queryParameters['includeZoneDesc'] = includeZoneDesc;
}
if (includeGeometry !== undefined) {
queryParameters['includeGeometry'] = includeGeometry;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: FloodRiskLocationResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Post Flood Risk By Location
* This is a Batch offering for 'Flood Risk By Location' service. It accepts a single location coordinate or a list of location coordinates and retrieve flood risk data for flood zones and base flood elevation values.
* @param body
*/
public getFloodRiskByLocationBatch (body?: FloodRiskByLocationRequest) : Promise<{ response: http.IncomingMessage; body: FloodRiskLocationResponseList; }> {
const localVarPath = this.basePath + '/risks/v1/flood/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: FloodRiskLocationResponseList; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum RoutingServiceApiApiKeys {
}
export class RoutingServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: RoutingServiceApiApiKeys, value: string) {
this.authentications[RoutingServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Gets Route by Address
* Routing Directions for Single and Multiple Origin & Destination Inputs. Accepts addresses as input and Returns Point-to-Point and Multi-Point travel directions by various travel modes.
* @param startAddress Starting address of the route.
* @param endAddress Ending address of the route.
* @param db Mode of commute.
* @param country Three digit ISO country code
* @param intermediateAddresses List of intermediate addresses of the route.
* @param oip Specifies whether waypoints need to be optimized.
* @param destinationSrs Specifies the desired coordinate system of the returned route.
* @param optimizeBy Specifies whether the route should be optimized by time or distance.
* @param returnDistance Specifies whether distance needs to be part of direction information in response.
* @param distanceUnit Return Distance Unit such as ft(Foot), km(Kilometer), mi(Mile), m(Meter) or yd(Yard).
* @param returnTime Specifies whether time needs to be part of direction information in response.
* @param timeUnit Return time unit such as min(Minute), h(Hour), s(Second) or msec(Millisecond).
* @param language Language of travel directions.
* @param directionsStyle Specifies whether route directions text is to be returned in the response and in what detail (Normal or Terse).
* @param segmentGeometryStyle Specifies whether the route geometry is to be returned in the response and in what detail (End or All).
* @param primaryNameOnly If true then only the primary street name is returned otherwise all the names for a street.
* @param majorRoads Whether to include all roads in route calculation or just major roads.
* @param historicTrafficTimeBucket Specifies whether routing calculation uses the historic traffic speeds.
* @param returnDirectionGeometry Whether to include geometry associated with each route instruction in response.
* @param useCvr This parameter will enable/disable CVR (Commercial Vehicle Restrictions) capability in our APIs
* @param looseningBarrierRestrictions Specifies that barriers will be removed when determining the route
* @param vehicleType vehicle type
* @param weight Specifies the maximum weight of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param weightUnit The unit of weight eg. kg(kilogram), lb(pound), mt(metric ton), t(ton)
* @param height Specifies the maximum height of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param heightUnit The unit of height e.g m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
* @param length Specifies the maximum length of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param lengthUnit The unit of length eg. m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
* @param width Specifies the maximum width of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param widthUnit The unit of width eg. m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
*/
public getRouteByAddress (startAddress: string, endAddress: string, db?: string, country?: string, intermediateAddresses?: string, oip?: string, destinationSrs?: string, optimizeBy?: string, returnDistance?: string, distanceUnit?: string, returnTime?: string, timeUnit?: string, language?: string, directionsStyle?: string, segmentGeometryStyle?: string, primaryNameOnly?: string, majorRoads?: string, historicTrafficTimeBucket?: string, returnDirectionGeometry?: string, useCvr?: string, looseningBarrierRestrictions?: string, vehicleType?: string, weight?: string, weightUnit?: string, height?: string, heightUnit?: string, length?: string, lengthUnit?: string, width?: string, widthUnit?: string) : Promise<{ response: http.IncomingMessage; body: GeoRouteResponse; }> {
const localVarPath = this.basePath + '/routing/v1/route/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'startAddress' is not null or undefined
if (startAddress === null || startAddress === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter startAddress was null or undefined when calling getRouteByAddress."}]}})
}
// verify required parameter 'endAddress' is not null or undefined
if (endAddress === null || endAddress === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter endAddress was null or undefined when calling getRouteByAddress."}]}})
}
if (startAddress !== undefined) {
queryParameters['startAddress'] = startAddress;
}
if (endAddress !== undefined) {
queryParameters['endAddress'] = endAddress;
}
if (db !== undefined) {
queryParameters['db'] = db;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (intermediateAddresses !== undefined) {
queryParameters['intermediateAddresses'] = intermediateAddresses;
}
if (oip !== undefined) {
queryParameters['oip'] = oip;
}
if (destinationSrs !== undefined) {
queryParameters['destinationSrs'] = destinationSrs;
}
if (optimizeBy !== undefined) {
queryParameters['optimizeBy'] = optimizeBy;
}
if (returnDistance !== undefined) {
queryParameters['returnDistance'] = returnDistance;
}
if (distanceUnit !== undefined) {
queryParameters['distanceUnit'] = distanceUnit;
}
if (returnTime !== undefined) {
queryParameters['returnTime'] = returnTime;
}
if (timeUnit !== undefined) {
queryParameters['timeUnit'] = timeUnit;
}
if (language !== undefined) {
queryParameters['language'] = language;
}
if (directionsStyle !== undefined) {
queryParameters['directionsStyle'] = directionsStyle;
}
if (segmentGeometryStyle !== undefined) {
queryParameters['segmentGeometryStyle'] = segmentGeometryStyle;
}
if (primaryNameOnly !== undefined) {
queryParameters['primaryNameOnly'] = primaryNameOnly;
}
if (majorRoads !== undefined) {
queryParameters['majorRoads'] = majorRoads;
}
if (historicTrafficTimeBucket !== undefined) {
queryParameters['historicTrafficTimeBucket'] = historicTrafficTimeBucket;
}
if (returnDirectionGeometry !== undefined) {
queryParameters['returnDirectionGeometry'] = returnDirectionGeometry;
}
if (useCvr !== undefined) {
queryParameters['useCvr'] = useCvr;
}
if (looseningBarrierRestrictions !== undefined) {
queryParameters['looseningBarrierRestrictions'] = looseningBarrierRestrictions;
}
if (vehicleType !== undefined) {
queryParameters['vehicleType'] = vehicleType;
}
if (weight !== undefined) {
queryParameters['weight'] = weight;
}
if (weightUnit !== undefined) {
queryParameters['weightUnit'] = weightUnit;
}
if (height !== undefined) {
queryParameters['height'] = height;
}
if (heightUnit !== undefined) {
queryParameters['heightUnit'] = heightUnit;
}
if (length !== undefined) {
queryParameters['length'] = length;
}
if (lengthUnit !== undefined) {
queryParameters['lengthUnit'] = lengthUnit;
}
if (width !== undefined) {
queryParameters['width'] = width;
}
if (widthUnit !== undefined) {
queryParameters['widthUnit'] = widthUnit;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoRouteResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Gets Route by Location
* Returns the fastest or shortest route based on a starting and ending location with optional intermediate points as input.
* @param startPoint Start Point in 'Lat,Long,coordsys' format
* @param endPoint End Point in 'Lat,Long,coordsys' format
* @param db Mode of commute.
* @param intermediatePoints List of intermediate points of the route.
* @param oip Specifies whether waypoints need to be optimized.
* @param destinationSrs Specifies the desired coordinate system of the returned route.
* @param optimizeBy Specifies whether the route should be optimized by time or distance.
* @param returnDistance Specifies whether distance needs to be part of direction information in response.
* @param distanceUnit Return Distance Unit such as ft(Foot), km(Kilometer), mi(Mile), m(Meter) or yd(Yard).
* @param returnTime Specifies whether time needs to be part of direction information in response.
* @param timeUnit Return time unit such as min(Minute), h(Hour), s(Second) or msec(Millisecond).
* @param language Specifies the language of travel directions.
* @param directionsStyle Specifies whether route directions text is to be returned in the response and in what detail (Normal or Terse).
* @param segmentGeometryStyle Specifies whether the route geometry is to be returned in the response and in what detail (End or All).
* @param primaryNameOnly If true then only the primary street name is returned otherwise all the names for a street.
* @param majorRoads Whether to include all roads in route calculation or just major roads.
* @param historicTrafficTimeBucket Specifies whether routing calculation uses the historic traffic speeds.
* @param returnDirectionGeometry Whether to include geometry associated with each route instruction in response.
* @param useCvr This parameter will enable/disable CVR (Commercial Vehicle Restrictions) capability in our APIs
* @param looseningBarrierRestrictions Specifies that barriers will be removed when determining the route
* @param vehicleType vehicle type
* @param weight Specifies the maximum weight of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param weightUnit The unit of weight eg. kg(kilogram), lb(pound), mt(metric ton), t(ton)
* @param height Specifies the maximum height of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param heightUnit The unit of height e.g m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
* @param length Specifies the maximum length of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param lengthUnit The unit of length eg. m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
* @param width Specifies the maximum width of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param widthUnit The unit of width eg. m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
*/
public getRouteByLocation (startPoint: string, endPoint: string, db?: string, intermediatePoints?: string, oip?: string, destinationSrs?: string, optimizeBy?: string, returnDistance?: string, distanceUnit?: string, returnTime?: string, timeUnit?: string, language?: string, directionsStyle?: string, segmentGeometryStyle?: string, primaryNameOnly?: string, majorRoads?: string, historicTrafficTimeBucket?: string, returnDirectionGeometry?: string, useCvr?: string, looseningBarrierRestrictions?: string, vehicleType?: string, weight?: string, weightUnit?: string, height?: string, heightUnit?: string, length?: string, lengthUnit?: string, width?: string, widthUnit?: string) : Promise<{ response: http.IncomingMessage; body: GeoRouteResponse; }> {
const localVarPath = this.basePath + '/routing/v1/route/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'startPoint' is not null or undefined
if (startPoint === null || startPoint === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter startPoint was null or undefined when calling getRouteByLocation."}]}})
}
// verify required parameter 'endPoint' is not null or undefined
if (endPoint === null || endPoint === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter endPoint was null or undefined when calling getRouteByLocation."}]}})
}
if (startPoint !== undefined) {
queryParameters['startPoint'] = startPoint;
}
if (endPoint !== undefined) {
queryParameters['endPoint'] = endPoint;
}
if (db !== undefined) {
queryParameters['db'] = db;
}
if (intermediatePoints !== undefined) {
queryParameters['intermediatePoints'] = intermediatePoints;
}
if (oip !== undefined) {
queryParameters['oip'] = oip;
}
if (destinationSrs !== undefined) {
queryParameters['destinationSrs'] = destinationSrs;
}
if (optimizeBy !== undefined) {
queryParameters['optimizeBy'] = optimizeBy;
}
if (returnDistance !== undefined) {
queryParameters['returnDistance'] = returnDistance;
}
if (distanceUnit !== undefined) {
queryParameters['distanceUnit'] = distanceUnit;
}
if (returnTime !== undefined) {
queryParameters['returnTime'] = returnTime;
}
if (timeUnit !== undefined) {
queryParameters['timeUnit'] = timeUnit;
}
if (language !== undefined) {
queryParameters['language'] = language;
}
if (directionsStyle !== undefined) {
queryParameters['directionsStyle'] = directionsStyle;
}
if (segmentGeometryStyle !== undefined) {
queryParameters['segmentGeometryStyle'] = segmentGeometryStyle;
}
if (primaryNameOnly !== undefined) {
queryParameters['primaryNameOnly'] = primaryNameOnly;
}
if (majorRoads !== undefined) {
queryParameters['majorRoads'] = majorRoads;
}
if (historicTrafficTimeBucket !== undefined) {
queryParameters['historicTrafficTimeBucket'] = historicTrafficTimeBucket;
}
if (returnDirectionGeometry !== undefined) {
queryParameters['returnDirectionGeometry'] = returnDirectionGeometry;
}
if (useCvr !== undefined) {
queryParameters['useCvr'] = useCvr;
}
if (looseningBarrierRestrictions !== undefined) {
queryParameters['looseningBarrierRestrictions'] = looseningBarrierRestrictions;
}
if (vehicleType !== undefined) {
queryParameters['vehicleType'] = vehicleType;
}
if (weight !== undefined) {
queryParameters['weight'] = weight;
}
if (weightUnit !== undefined) {
queryParameters['weightUnit'] = weightUnit;
}
if (height !== undefined) {
queryParameters['height'] = height;
}
if (heightUnit !== undefined) {
queryParameters['heightUnit'] = heightUnit;
}
if (length !== undefined) {
queryParameters['length'] = length;
}
if (lengthUnit !== undefined) {
queryParameters['lengthUnit'] = lengthUnit;
}
if (width !== undefined) {
queryParameters['width'] = width;
}
if (widthUnit !== undefined) {
queryParameters['widthUnit'] = widthUnit;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeoRouteResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Gets Cost Matrix by Address
* Calculates the travel time and distances between an array of start and end addresses.
* @param startAddresses Start locations in text based addresses.
* @param endAddresses End locations in text based addresses.
* @param db Mode of commute.
* @param country 3 Digit ISO country code.
* @param optimizeBy Specifies the type of optimizing to use for the route (time/distance).
* @param returnDistance Specifies whether to return the travel distance in the response or not.
* @param destinationSrs Coordinate system used for the returned routes.
* @param distanceUnit Return Distance Unit such as ft(Foot), km(Kilometer), mi(Mile), m(Meter) or yd(Yard).
* @param returnTime Specifies whether to return the travel time in the response or not.
* @param timeUnit Return time unit such as min(Minute), h(Hour), s(Second) or msec(Millisecond).
* @param majorRoads Whether to include all roads in routes calculation or just major roads.
* @param returnOptimalRoutesOnly Specifies whether to return only the optimized route for each start and end point combination.
* @param historicTrafficTimeBucket Specifies whether routing calculation uses the historic traffic speeds.
* @param useCvr This parameter will enable/disable CVR (Commercial Vehicle Restrictions) capability in our APIs
* @param looseningBarrierRestrictions Specifies that barriers will be removed when determining the route
* @param vehicleType vehicle type
* @param weight Specifies the maximum weight of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param weightUnit The unit of weight eg. kg(kilogram), lb(pound), mt(metric ton), t(ton)
* @param height Specifies the maximum height of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param heightUnit The unit of height e.g m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
* @param length Specifies the maximum length of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param lengthUnit The unit of length eg. m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
* @param width Specifies the maximum width of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param widthUnit The unit of width eg. m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
*/
public getTravelCostMatrixByAddress (startAddresses: string, endAddresses: string, db?: string, country?: string, optimizeBy?: string, returnDistance?: string, destinationSrs?: string, distanceUnit?: string, returnTime?: string, timeUnit?: string, majorRoads?: string, returnOptimalRoutesOnly?: string, historicTrafficTimeBucket?: string, useCvr?: string, looseningBarrierRestrictions?: string, vehicleType?: string, weight?: string, weightUnit?: string, height?: string, heightUnit?: string, length?: string, lengthUnit?: string, width?: string, widthUnit?: string) : Promise<{ response: http.IncomingMessage; body: TravelCostMatrixResponse; }> {
const localVarPath = this.basePath + '/routing/v1/travelcostmatrix/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'startAddresses' is not null or undefined
if (startAddresses === null || startAddresses === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter startAddresses was null or undefined when calling getTravelCostMatrixByAddress."}]}})
}
// verify required parameter 'endAddresses' is not null or undefined
if (endAddresses === null || endAddresses === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter endAddresses was null or undefined when calling getTravelCostMatrixByAddress."}]}})
}
if (startAddresses !== undefined) {
queryParameters['startAddresses'] = startAddresses;
}
if (endAddresses !== undefined) {
queryParameters['endAddresses'] = endAddresses;
}
if (db !== undefined) {
queryParameters['db'] = db;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (optimizeBy !== undefined) {
queryParameters['optimizeBy'] = optimizeBy;
}
if (returnDistance !== undefined) {
queryParameters['returnDistance'] = returnDistance;
}
if (destinationSrs !== undefined) {
queryParameters['destinationSrs'] = destinationSrs;
}
if (distanceUnit !== undefined) {
queryParameters['distanceUnit'] = distanceUnit;
}
if (returnTime !== undefined) {
queryParameters['returnTime'] = returnTime;
}
if (timeUnit !== undefined) {
queryParameters['timeUnit'] = timeUnit;
}
if (majorRoads !== undefined) {
queryParameters['majorRoads'] = majorRoads;
}
if (returnOptimalRoutesOnly !== undefined) {
queryParameters['returnOptimalRoutesOnly'] = returnOptimalRoutesOnly;
}
if (historicTrafficTimeBucket !== undefined) {
queryParameters['historicTrafficTimeBucket'] = historicTrafficTimeBucket;
}
if (useCvr !== undefined) {
queryParameters['useCvr'] = useCvr;
}
if (looseningBarrierRestrictions !== undefined) {
queryParameters['looseningBarrierRestrictions'] = looseningBarrierRestrictions;
}
if (vehicleType !== undefined) {
queryParameters['vehicleType'] = vehicleType;
}
if (weight !== undefined) {
queryParameters['weight'] = weight;
}
if (weightUnit !== undefined) {
queryParameters['weightUnit'] = weightUnit;
}
if (height !== undefined) {
queryParameters['height'] = height;
}
if (heightUnit !== undefined) {
queryParameters['heightUnit'] = heightUnit;
}
if (length !== undefined) {
queryParameters['length'] = length;
}
if (lengthUnit !== undefined) {
queryParameters['lengthUnit'] = lengthUnit;
}
if (width !== undefined) {
queryParameters['width'] = width;
}
if (widthUnit !== undefined) {
queryParameters['widthUnit'] = widthUnit;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TravelCostMatrixResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Gets Cost Matrix by Location
* GeoRoute's 'Travel Cost Matrix By Location' service calculates the travel time and distances between an array of start and end points based on location coordinates.
* @param startPoints The address to be searched.
* @param endPoints The address to be searched.
* @param db Mode of commute.
* @param optimizeBy Specifies whether routes should be optimized by time or distance.
* @param returnDistance Specifies whether distance needs to be returned in response.
* @param destinationSrs Specifies the desired coordinate system of returned routes.
* @param distanceUnit Return Distance Unit such as ft(Foot), km(Kilometer), mi(Mile), m(Meter) or yd(Yard).
* @param returnTime Specifies whether time needs to be returned in response.
* @param timeUnit Return time unit such as min(Minute), h(Hour), s(Second) or msec(Millisecond).
* @param majorRoads Whether to include all roads in routes calculation or just major roads.
* @param returnOptimalRoutesOnly Specifies whether to return only the optimized route for each start and end point combination.
* @param historicTrafficTimeBucket Specifies whether routing calculation uses the historic traffic speeds.
* @param useCvr This parameter will enable/disable CVR (Commercial Vehicle Restrictions) capability in our APIs
* @param looseningBarrierRestrictions Specifies that barriers will be removed when determining the route
* @param vehicleType vehicle type
* @param weight Specifies the maximum weight of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param weightUnit The unit of weight eg. kg(kilogram), lb(pound), mt(metric ton), t(ton)
* @param height Specifies the maximum height of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param heightUnit The unit of height e.g m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
* @param length Specifies the maximum length of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param lengthUnit The unit of length eg. m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
* @param width Specifies the maximum width of a vehicle. Any vehicles over this value will be restricted when determining the route.
* @param widthUnit The unit of width eg. m(meter), km(kilometer), yd(yard), ft(foot), mi(mile)
*/
public getTravelCostMatrixByLocation (startPoints: string, endPoints: string, db?: string, optimizeBy?: string, returnDistance?: string, destinationSrs?: string, distanceUnit?: string, returnTime?: string, timeUnit?: string, majorRoads?: string, returnOptimalRoutesOnly?: string, historicTrafficTimeBucket?: string, useCvr?: string, looseningBarrierRestrictions?: string, vehicleType?: string, weight?: string, weightUnit?: string, height?: string, heightUnit?: string, length?: string, lengthUnit?: string, width?: string, widthUnit?: string) : Promise<{ response: http.IncomingMessage; body: TravelCostMatrixResponse; }> {
const localVarPath = this.basePath + '/routing/v1/travelcostmatrix/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'startPoints' is not null or undefined
if (startPoints === null || startPoints === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter startPoints was null or undefined when calling getTravelCostMatrixByLocation."}]}})
}
// verify required parameter 'endPoints' is not null or undefined
if (endPoints === null || endPoints === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter endPoints was null or undefined when calling getTravelCostMatrixByLocation."}]}})
}
if (startPoints !== undefined) {
queryParameters['startPoints'] = startPoints;
}
if (endPoints !== undefined) {
queryParameters['endPoints'] = endPoints;
}
if (db !== undefined) {
queryParameters['db'] = db;
}
if (optimizeBy !== undefined) {
queryParameters['optimizeBy'] = optimizeBy;
}
if (returnDistance !== undefined) {
queryParameters['returnDistance'] = returnDistance;
}
if (destinationSrs !== undefined) {
queryParameters['destinationSrs'] = destinationSrs;
}
if (distanceUnit !== undefined) {
queryParameters['distanceUnit'] = distanceUnit;
}
if (returnTime !== undefined) {
queryParameters['returnTime'] = returnTime;
}
if (timeUnit !== undefined) {
queryParameters['timeUnit'] = timeUnit;
}
if (majorRoads !== undefined) {
queryParameters['majorRoads'] = majorRoads;
}
if (returnOptimalRoutesOnly !== undefined) {
queryParameters['returnOptimalRoutesOnly'] = returnOptimalRoutesOnly;
}
if (historicTrafficTimeBucket !== undefined) {
queryParameters['historicTrafficTimeBucket'] = historicTrafficTimeBucket;
}
if (useCvr !== undefined) {
queryParameters['useCvr'] = useCvr;
}
if (looseningBarrierRestrictions !== undefined) {
queryParameters['looseningBarrierRestrictions'] = looseningBarrierRestrictions;
}
if (vehicleType !== undefined) {
queryParameters['vehicleType'] = vehicleType;
}
if (weight !== undefined) {
queryParameters['weight'] = weight;
}
if (weightUnit !== undefined) {
queryParameters['weightUnit'] = weightUnit;
}
if (height !== undefined) {
queryParameters['height'] = height;
}
if (heightUnit !== undefined) {
queryParameters['heightUnit'] = heightUnit;
}
if (length !== undefined) {
queryParameters['length'] = length;
}
if (lengthUnit !== undefined) {
queryParameters['lengthUnit'] = lengthUnit;
}
if (width !== undefined) {
queryParameters['width'] = width;
}
if (widthUnit !== undefined) {
queryParameters['widthUnit'] = widthUnit;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TravelCostMatrixResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum SchoolsServiceApiApiKeys {
}
export class SchoolsServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: SchoolsServiceApiApiKeys, value: string) {
this.authentications[SchoolsServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Search Nearby Schools by Address
* Search Nearby Schools by Address
* @param address free form address text
* @param edLevel Single digit code for education level applicable values are P -> primary, M -> Middle, H -> High, O -> Mixed Grades for public school type andE -> Elementary , S -> Secondary , O -> Others mixed grades for private schools
* @param schoolType Single digit code for schoolTypes applicable values are PRI and PUB
* @param schoolSubType Single digit code for schoolSubType Applicable values are C, M, A, R, I, L, P, V, U, S (i.e. Charter, Magnet, Alternative, Regular, Indian, Military, Reportable Program, Vocational, Unknown, Special Education)
* @param gender Single digit code for gender Applicable values are C, F, M (Coed, All Females, All Males)
* @param assignedSchoolsOnly Single digit code for assignedSchoolOnly applicable values are Y/N
* @param districtSchoolsOnly Single digit code for districtSchoolOnly applicable values are Y/N
* @param searchRadius Search Radius within which schools are searched
* @param searchRadiusUnit Search Radius unit applicable values are feet,kilometers,miles,meters
* @param travelTime Travel Time based on ‘travelMode’ within which schools are searched.
* @param travelTimeUnit Travel Time unit applicable values are minutes,hours,seconds,milliseconds
* @param travelDistance Travel Distance based on ‘travelMode’ within which schools are searched.
* @param travelDistanceUnit Travel distanceUnit applicable values are feet,kilometers,miles,meters
* @param travelMode Travel mode Required when travelDistance or travelTime is specified. Accepted values are walking,driving
* @param maxCandidates Max result to search
*/
public getSchoolsByAddress (address: string, edLevel?: string, schoolType?: string, schoolSubType?: string, gender?: string, assignedSchoolsOnly?: string, districtSchoolsOnly?: string, searchRadius?: string, searchRadiusUnit?: string, travelTime?: string, travelTimeUnit?: string, travelDistance?: string, travelDistanceUnit?: string, travelMode?: string, maxCandidates?: string) : Promise<{ response: http.IncomingMessage; body: SchoolsNearByResponse; }> {
const localVarPath = this.basePath + '/schools/v1/school/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getSchoolsByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (edLevel !== undefined) {
queryParameters['edLevel'] = edLevel;
}
if (schoolType !== undefined) {
queryParameters['schoolType'] = schoolType;
}
if (schoolSubType !== undefined) {
queryParameters['schoolSubType'] = schoolSubType;
}
if (gender !== undefined) {
queryParameters['gender'] = gender;
}
if (assignedSchoolsOnly !== undefined) {
queryParameters['assignedSchoolsOnly'] = assignedSchoolsOnly;
}
if (districtSchoolsOnly !== undefined) {
queryParameters['districtSchoolsOnly'] = districtSchoolsOnly;
}
if (searchRadius !== undefined) {
queryParameters['searchRadius'] = searchRadius;
}
if (searchRadiusUnit !== undefined) {
queryParameters['searchRadiusUnit'] = searchRadiusUnit;
}
if (travelTime !== undefined) {
queryParameters['travelTime'] = travelTime;
}
if (travelTimeUnit !== undefined) {
queryParameters['travelTimeUnit'] = travelTimeUnit;
}
if (travelDistance !== undefined) {
queryParameters['travelDistance'] = travelDistance;
}
if (travelDistanceUnit !== undefined) {
queryParameters['travelDistanceUnit'] = travelDistanceUnit;
}
if (travelMode !== undefined) {
queryParameters['travelMode'] = travelMode;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: SchoolsNearByResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum StreetsServiceApiApiKeys {
}
export class StreetsServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: StreetsServiceApiApiKeys, value: string) {
this.authentications[StreetsServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Nearest Intersection By Address
* This service accepts an address as input and returns the Nearest Intersection.
* @param address Address
* @param roadClass Filters roads with specified class, allowed values are (Major, Motorways, Other and All), default is All
* @param driveTime Returns Intersection in specified drive time
* @param driveTimeUnit Drive time unit, allowed values are (hours, minutes, seconds and milliseconds), default is minutes
* @param searchRadius Search radius within which user wants to search, default is 50 miles
* @param searchRadiusUnit Search radius unit, allowed values are (feet, meter, kilometers and miles)
* @param historicSpeed Traffic flow in peak time, allowed values are (AMPEAK,PMPEAK,OFFPEAK,NIGHT)
* @param maxCandidates max candidates to be returned default is 1
*/
public getIntersectionByAddress (address: string, roadClass?: string, driveTime?: string, driveTimeUnit?: string, searchRadius?: string, searchRadiusUnit?: string, historicSpeed?: string, maxCandidates?: string) : Promise<{ response: http.IncomingMessage; body: IntersectionResponse; }> {
const localVarPath = this.basePath + '/streets/v1/intersection/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getIntersectionByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (roadClass !== undefined) {
queryParameters['roadClass'] = roadClass;
}
if (driveTime !== undefined) {
queryParameters['driveTime'] = driveTime;
}
if (driveTimeUnit !== undefined) {
queryParameters['driveTimeUnit'] = driveTimeUnit;
}
if (searchRadius !== undefined) {
queryParameters['searchRadius'] = searchRadius;
}
if (searchRadiusUnit !== undefined) {
queryParameters['searchRadiusUnit'] = searchRadiusUnit;
}
if (historicSpeed !== undefined) {
queryParameters['historicSpeed'] = historicSpeed;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: IntersectionResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Nearest Intersection By Location
* This service accepts latitude/longitude as input and returns the Nearest Intersection.
* @param longitude Longitude of the location.
* @param latitude Latitude of the location.
* @param roadClass Filters roads with specified class, allowed values are (Major, Motorways, Other and All), default is All
* @param driveTime Returns Intersection in specified drive time
* @param driveTimeUnit Drive time unit, allowed values are (hours, minutes, seconds and milliseconds), default is minutes
* @param searchRadius Search radius within which user wants to search, default is 50 miles
* @param searchRadiusUnit Search radius unit, allowed values are (feet, meter, kilometers and miles)
* @param historicSpeed Traffic flow in peak time, allowed values are (AMPEAK,PMPEAK,OFFPEAK,NIGHT)
* @param maxCandidates max candidates to be returned default is 1
*/
public getIntersectionByLocation (longitude: string, latitude: string, roadClass?: string, driveTime?: string, driveTimeUnit?: string, searchRadius?: string, searchRadiusUnit?: string, historicSpeed?: string, maxCandidates?: string) : Promise<{ response: http.IncomingMessage; body: IntersectionResponse; }> {
const localVarPath = this.basePath + '/streets/v1/intersection/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getIntersectionByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getIntersectionByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (roadClass !== undefined) {
queryParameters['roadClass'] = roadClass;
}
if (driveTime !== undefined) {
queryParameters['driveTime'] = driveTime;
}
if (driveTimeUnit !== undefined) {
queryParameters['driveTimeUnit'] = driveTimeUnit;
}
if (searchRadius !== undefined) {
queryParameters['searchRadius'] = searchRadius;
}
if (searchRadiusUnit !== undefined) {
queryParameters['searchRadiusUnit'] = searchRadiusUnit;
}
if (historicSpeed !== undefined) {
queryParameters['historicSpeed'] = historicSpeed;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: IntersectionResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Nearest Speedlimit
* This service accepts point coordinates of a path as input and returns the posted speed limit of the road segment on which this path will snap.
* @param path Accepts multiple points which will be snapped to the nearest road segment. Longitude and Latitude will be comma separated (longitude,latitude) and Point Coordinates will be separated by semi-colon(;)
*/
public getNearestSpeedLimit (path: string) : Promise<{ response: http.IncomingMessage; body: SpeedLimit; }> {
const localVarPath = this.basePath + '/streets/v1/speedlimit';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'path' is not null or undefined
if (path === null || path === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter path was null or undefined when calling getNearestSpeedLimit."}]}})
}
if (path !== undefined) {
queryParameters['path'] = path;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: SpeedLimit; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum TelecommInfoServiceApiApiKeys {
}
export class TelecommInfoServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: TelecommInfoServiceApiApiKeys, value: string) {
this.authentications[TelecommInfoServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Rate Center By Address.
* Accepts addresses as input and returns Incumbent Local Exchange Carrier (ILEC) doing-business-as names.
* @param address The address to be searched.
* @param country 3 letter ISO code of the country to be searched. Allowed values USA,CAN
* @param areaCodeInfo Specifies whether area code information will be part of response.Allowed values True,False
* @param level Level (basic/detail).Allowed values detail,basic.
*/
public getRateCenterByAddress (address: string, country?: string, areaCodeInfo?: string, level?: string) : Promise<{ response: http.IncomingMessage; body: RateCenterResponse; }> {
const localVarPath = this.basePath + '/telecomm/v1/ratecenter/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getRateCenterByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (areaCodeInfo !== undefined) {
queryParameters['AreaCodeInfo'] = areaCodeInfo;
}
if (level !== undefined) {
queryParameters['level'] = level;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: RateCenterResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Rate Center By Location.
* Accepts latitude & longitude as input and returns Incumbent Local Exchange Carrier (ILEC) doing-business-as names.
* @param longitude Longitude of the location.
* @param latitude Latitude of the location.
* @param areaCodeInfo Specifies whether area code information will be part of response.Allowed values True,False.
* @param level Level (basic/detail).Allowed values detail,basic.
*/
public getRateCenterByLocation (longitude: string, latitude: string, areaCodeInfo?: string, level?: string) : Promise<{ response: http.IncomingMessage; body: RateCenterResponse; }> {
const localVarPath = this.basePath + '/telecomm/v1/ratecenter/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getRateCenterByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getRateCenterByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (areaCodeInfo !== undefined) {
queryParameters['AreaCodeInfo'] = areaCodeInfo;
}
if (level !== undefined) {
queryParameters['level'] = level;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: RateCenterResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum TimeZoneServiceApiApiKeys {
}
export class TimeZoneServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: TimeZoneServiceApiApiKeys, value: string) {
this.authentications[TimeZoneServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Timezone Batch by Address
* Identifies and retrieves the local time of any location in the world for a given address and time. The input and retrieved time format is in milliseconds.
* @param body
*/
public getBatchTimezoneByAddress (body?: TimezoneAddressRequest) : Promise<{ response: http.IncomingMessage; body: TimezoneResponse; }> {
const localVarPath = this.basePath + '/timezone/v1/timezone/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TimezoneResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Timezone Batch by Location
* Identifies and retrieves the local time of any location in the world for a given latitude, longitude and time. The input and retrieved time format is in milliseconds.
* @param body
*/
public getBatchTimezoneByLocation (body?: TimezoneLocationRequest) : Promise<{ response: http.IncomingMessage; body: TimezoneLocationResponse; }> {
const localVarPath = this.basePath + '/timezone/v1/timezone/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TimezoneLocationResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Timezone By Address.
* Identifies and retrieves the local time of any location in the world for a given address and time. The input and retrieved time format is in milliseconds.
* @param timestamp Timestamp in miliseconds.
* @param address The address to be searched.
* @param matchMode Match modes determine the leniency used to make a match between the input address and the reference data.
* @param country Country ISO code.
*/
public getTimezoneByAddress (timestamp: string, address: string, matchMode?: string, country?: string) : Promise<{ response: http.IncomingMessage; body: Timezone; }> {
const localVarPath = this.basePath + '/timezone/v1/timezone/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'timestamp' is not null or undefined
if (timestamp === null || timestamp === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter timestamp was null or undefined when calling getTimezoneByAddress."}]}})
}
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getTimezoneByAddress."}]}})
}
if (timestamp !== undefined) {
queryParameters['timestamp'] = timestamp;
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (matchMode !== undefined) {
queryParameters['matchMode'] = matchMode;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Timezone; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Timezone By Location.
* Identifies and retrieves the local time of any location in the world for a given latitude, longitude and time. The input and retrieved time format is in milliseconds.
* @param timestamp Timestamp in miliseconds.
* @param longitude Longitude of the location.
* @param latitude Latitude of the location.
*/
public getTimezoneByLocation (timestamp: string, longitude: string, latitude: string) : Promise<{ response: http.IncomingMessage; body: TimezoneLocation; }> {
const localVarPath = this.basePath + '/timezone/v1/timezone/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'timestamp' is not null or undefined
if (timestamp === null || timestamp === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter timestamp was null or undefined when calling getTimezoneByLocation."}]}})
}
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getTimezoneByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getTimezoneByLocation."}]}})
}
if (timestamp !== undefined) {
queryParameters['timestamp'] = timestamp;
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TimezoneLocation; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum TypeaheadServiceApiApiKeys {
}
export class TypeaheadServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: TypeaheadServiceApiApiKeys, value: string) {
this.authentications[TypeaheadServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Typeahead Search
* Performs search to retrieve list of places by input text and location vicinity.
* @param searchText The input to be searched.
* @param latitude Latitude of the location. Either the latitude or the longitude must be provided.
* @param longitude Longitude of the location. Either the latitude or the longitude must be provided.
* @param searchRadius Radius range within which search is performed.
* @param searchRadiusUnit Radius unit such as Feet, Kilometers, Miles or Meters.
* @param maxCandidates Maximum number of addresses that can be retrieved.
* @param country Country ISO code. We need to make sure that either Lat/Lng or Country is provided to API
* @param matchOnAddressNumber Option so that we force api to match on address number
* @param autoDetectLocation Option to allow API to detect origin of API request automatically
* @param ipAddress
* @param areaName1 State province of the input to be searched
* @param areaName3 City of the input to be searched
* @param postCode Postal Code of the input to be searched
* @param returnAdminAreasOnly if value set 'Y' then it will only do a matching on postcode or areaName1, areaName2, areaName3 and areaName4 fields in the data
* @param includeRangesDetails if value set 'Y' then display all unit info of ranges, if value set 'N' then don't show ranges
* @param searchType Preference to control search type of interactive requests.
*/
public search (searchText: string, latitude?: string, longitude?: string, searchRadius?: string, searchRadiusUnit?: string, maxCandidates?: string, country?: string, matchOnAddressNumber?: string, autoDetectLocation?: string, ipAddress?: string, areaName1?: string, areaName3?: string, postCode?: string, returnAdminAreasOnly?: string, includeRangesDetails?: string, searchType?: string) : Promise<{ response: http.IncomingMessage; body: GeosearchLocations; }> {
const localVarPath = this.basePath + '/typeahead/v1/locations';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'searchText' is not null or undefined
if (searchText === null || searchText === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter searchText was null or undefined when calling search."}]}})
}
if (searchText !== undefined) {
queryParameters['searchText'] = searchText;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (searchRadius !== undefined) {
queryParameters['searchRadius'] = searchRadius;
}
if (searchRadiusUnit !== undefined) {
queryParameters['searchRadiusUnit'] = searchRadiusUnit;
}
if (maxCandidates !== undefined) {
queryParameters['maxCandidates'] = maxCandidates;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (matchOnAddressNumber !== undefined) {
queryParameters['matchOnAddressNumber'] = matchOnAddressNumber;
}
if (autoDetectLocation !== undefined) {
queryParameters['autoDetectLocation'] = autoDetectLocation;
}
if (ipAddress !== undefined) {
queryParameters['ipAddress'] = ipAddress;
}
if (areaName1 !== undefined) {
queryParameters['areaName1'] = areaName1;
}
if (areaName3 !== undefined) {
queryParameters['areaName3'] = areaName3;
}
if (postCode !== undefined) {
queryParameters['postCode'] = postCode;
}
if (returnAdminAreasOnly !== undefined) {
queryParameters['returnAdminAreasOnly'] = returnAdminAreasOnly;
}
if (includeRangesDetails !== undefined) {
queryParameters['includeRangesDetails'] = includeRangesDetails;
}
if (searchType !== undefined) {
queryParameters['searchType'] = searchType;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: GeosearchLocations; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum ZonesServiceApiApiKeys {
}
export class ZonesServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: ZonesServiceApiApiKeys, value: string) {
this.authentications[ZonesServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* Gets Basic Boundary by Address
* Gets Basic Boundary by Address
* @param address Address around which Basic Boundary is requested
* @param distance This is width of the buffer (in a complete circular buffer, it would be radius of the buffer). This has to be a positive number.
* @param country Three digit ISO country code
* @param distanceUnit Longitude around which Basic Boundary is requested
* @param resolution This is resolution of the buffer. Curves generated in buffer are approximated by line segments and it is measured in segments per circle. The higher the resolution, the smoother the curves of the buffer but more points would be required in the boundary geometry. Number greater than 0 and in multiple of 4. If not in 4, then it is approximated to nearest multiple of 4.
* @param responseSrs The spatial reference system to express the response in. By default, it would be epsg:4326
*/
public getBasicBoundaryByAddress (address: string, distance: string, country?: string, distanceUnit?: string, resolution?: string, responseSrs?: string) : Promise<{ response: http.IncomingMessage; body: BasicBoundaryAddress; }> {
const localVarPath = this.basePath + '/zones/v1/basicboundary/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getBasicBoundaryByAddress."}]}})
}
// verify required parameter 'distance' is not null or undefined
if (distance === null || distance === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter distance was null or undefined when calling getBasicBoundaryByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (distance !== undefined) {
queryParameters['distance'] = distance;
}
if (distanceUnit !== undefined) {
queryParameters['distanceUnit'] = distanceUnit;
}
if (resolution !== undefined) {
queryParameters['resolution'] = resolution;
}
if (responseSrs !== undefined) {
queryParameters['responseSrs'] = responseSrs;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: BasicBoundaryAddress; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Gets Basic Boundary by Location
* Gets Basic Boundary by Location
* @param latitude Latitude around which Basic Boundary is requested
* @param longitude Longitude around which Basic Boundary is requested
* @param distance This is width of the buffer (in a complete circular buffer, it would be radius of the buffer). This has to be a positive number.
* @param distanceUnit Longitude around which Basic Boundary is requested
* @param resolution This is resolution of the buffer. Curves generated in buffer are approximated by line segments and it is measured in segments per circle. The higher the resolution, the smoother the curves of the buffer but more points would be required in the boundary geometry. Number greater than 0 and in multiple of 4. If not in 4, then it is approximated to nearest multiple of 4.
* @param responseSrs The spatial reference system to express the response in. By default, it would be epsg:4326
* @param srsName The spatial reference system for input. By default, it would be epsg:4326
*/
public getBasicBoundaryByLocation (latitude: string, longitude: string, distance: string, distanceUnit?: string, resolution?: string, responseSrs?: string, srsName?: string) : Promise<{ response: http.IncomingMessage; body: BasicBoundary; }> {
const localVarPath = this.basePath + '/zones/v1/basicboundary/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getBasicBoundaryByLocation."}]}})
}
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getBasicBoundaryByLocation."}]}})
}
// verify required parameter 'distance' is not null or undefined
if (distance === null || distance === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter distance was null or undefined when calling getBasicBoundaryByLocation."}]}})
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (distance !== undefined) {
queryParameters['distance'] = distance;
}
if (distanceUnit !== undefined) {
queryParameters['distanceUnit'] = distanceUnit;
}
if (resolution !== undefined) {
queryParameters['resolution'] = resolution;
}
if (responseSrs !== undefined) {
queryParameters['responseSrs'] = responseSrs;
}
if (srsName !== undefined) {
queryParameters['srsName'] = srsName;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: BasicBoundary; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Point of Interests Boundary by Address
* Gets Point of Interests Boundary by Address
* @param address Address around which POI Boundary is requested
* @param categoryCode Specific Category/Categories Codes for the desired POIs. Accepts a mix of 4 digit (Top Category), 6 digit (Second-Level Category) and 11 digit (Low-Level Category) Category Codes.
* @param sicCode Specify starting digits or full sic code to filter the response
* @param naicsCode Will accept naicsCode to filter POIs in results. Max 10 allowed.
*/
public getPOIBoundaryByAddress (address: string, categoryCode?: string, sicCode?: string, naicsCode?: string) : Promise<{ response: http.IncomingMessage; body: PoiBoundary; }> {
const localVarPath = this.basePath + '/zones/v1/poiboundary/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getPOIBoundaryByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (categoryCode !== undefined) {
queryParameters['categoryCode'] = categoryCode;
}
if (sicCode !== undefined) {
queryParameters['sicCode'] = sicCode;
}
if (naicsCode !== undefined) {
queryParameters['naicsCode'] = naicsCode;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: PoiBoundary; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Batch method for getting Point of Interests Boundary by Address
* Batch method for getting Point of Interests Boundary by Address
* @param body
*/
public getPOIBoundaryByAddressBatch (body?: POIBoundaryAddressRequest) : Promise<{ response: http.IncomingMessage; body: POIBoundaryResponse; }> {
const localVarPath = this.basePath + '/zones/v1/poiboundary/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: POIBoundaryResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Get Point of Interests Boundary by Location
* Get Point of Interests Boundary by Location
* @param latitude Latitude around which POI Boundary is requested
* @param longitude Longitude around which POI Boundary is requested
* @param categoryCode Specific Category/Categories Codes for the desired POIs. Accepts a mix of 4 digit (Top Category), 6 digit (Second-Level Category) and 11 digit (Low-Level Category) Category Codes
* @param sicCode Specify starting digits or full sic code to filter the response
* @param naicsCode Will accept naicsCode to filter POIs in results. Max 10 allowed.
*/
public getPOIBoundaryByLocation (latitude: string, longitude: string, categoryCode?: string, sicCode?: string, naicsCode?: string) : Promise<{ response: http.IncomingMessage; body: PoiBoundary; }> {
const localVarPath = this.basePath + '/zones/v1/poiboundary/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getPOIBoundaryByLocation."}]}})
}
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getPOIBoundaryByLocation."}]}})
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (categoryCode !== undefined) {
queryParameters['categoryCode'] = categoryCode;
}
if (sicCode !== undefined) {
queryParameters['sicCode'] = sicCode;
}
if (naicsCode !== undefined) {
queryParameters['naicsCode'] = naicsCode;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: PoiBoundary; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Batch method for getting Point of Interests Boundary by Location
* Batch method for getting Point of Interests Boundary by Location
* @param body
*/
public getPOIBoundaryByLocationBatch (body?: POIBoundaryLocationRequest) : Promise<{ response: http.IncomingMessage; body: POIBoundaryResponse; }> {
const localVarPath = this.basePath + '/zones/v1/poiboundary/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
let useFormData = false;
let requestOptions: request.Options = {
method: 'POST',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: body,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: POIBoundaryResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Gets travel Boundary by Distance
* Returns the travel boundary based on travel distance.
* @param costs Travel distance(s)
* @param point Starting point from where the travel boundary is calculated. Point in 'Lat,Long,coordsys' format
* @param address Starting address from where the travel boundary is calculated.
* @param costUnit Travel distance such as ft(Foot), km(Kilometer), mi(Mile), m(Meter) or yd(Yard).
* @param db Mode of commute.
* @param country Three digit ISO country code.
* @param maxOffroadDistance Maximum distance to allow travel off the road network.
* @param maxOffroadDistanceUnit MaxOffroad Distance Unit such as ft(Foot), km(Kilometer), mi(Mile), m(Meter) or yd(Yard).
* @param destinationSrs Desired coordinate system of the travel boundary.
* @param majorRoads Whether to include all roads in the calculation or just major roads.
* @param returnHoles Whether to return holes, which are areas within the larger boundary that cannot be reached within the desired distance.
* @param returnIslands Whether to return islands, which are small areas outside the main boundary that can be reached within the desired distance.
* @param simplificationFactor Number between 0.0 and 1.0 where 0.0 is very simple and 1.0 means the most complex.
* @param bandingStyle Style of banding to be used in the result.
* @param historicTrafficTimeBucket Whether routing calculation uses the historic traffic speeds.
* @param defaultAmbientSpeed The speed to travel when going off a network road to find the travel boundary (for all road types).
* @param ambientSpeedUnit The unit of measure to use to calculate the ambient speed.
*/
public getTravelBoundaryByDistance (costs: string, point?: string, address?: string, costUnit?: string, db?: string, country?: string, maxOffroadDistance?: string, maxOffroadDistanceUnit?: string, destinationSrs?: string, majorRoads?: string, returnHoles?: string, returnIslands?: string, simplificationFactor?: string, bandingStyle?: string, historicTrafficTimeBucket?: string, defaultAmbientSpeed?: string, ambientSpeedUnit?: string) : Promise<{ response: http.IncomingMessage; body: TravelBoundaries; }> {
const localVarPath = this.basePath + '/zones/v1/travelboundary/bydistance';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'costs' is not null or undefined
if (costs === null || costs === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter costs was null or undefined when calling getTravelBoundaryByDistance."}]}})
}
if (point !== undefined) {
queryParameters['point'] = point;
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (costs !== undefined) {
queryParameters['costs'] = costs;
}
if (costUnit !== undefined) {
queryParameters['costUnit'] = costUnit;
}
if (db !== undefined) {
queryParameters['db'] = db;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (maxOffroadDistance !== undefined) {
queryParameters['maxOffroadDistance'] = maxOffroadDistance;
}
if (maxOffroadDistanceUnit !== undefined) {
queryParameters['maxOffroadDistanceUnit'] = maxOffroadDistanceUnit;
}
if (destinationSrs !== undefined) {
queryParameters['destinationSrs'] = destinationSrs;
}
if (majorRoads !== undefined) {
queryParameters['majorRoads'] = majorRoads;
}
if (returnHoles !== undefined) {
queryParameters['returnHoles'] = returnHoles;
}
if (returnIslands !== undefined) {
queryParameters['returnIslands'] = returnIslands;
}
if (simplificationFactor !== undefined) {
queryParameters['simplificationFactor'] = simplificationFactor;
}
if (bandingStyle !== undefined) {
queryParameters['bandingStyle'] = bandingStyle;
}
if (historicTrafficTimeBucket !== undefined) {
queryParameters['historicTrafficTimeBucket'] = historicTrafficTimeBucket;
}
if (defaultAmbientSpeed !== undefined) {
queryParameters['defaultAmbientSpeed'] = defaultAmbientSpeed;
}
if (ambientSpeedUnit !== undefined) {
queryParameters['ambientSpeedUnit'] = ambientSpeedUnit;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TravelBoundaries; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* Gets travel Boundary by Time
* Travel boundary based on travel time.
* @param costs Travel time used to calculate the travel boundary.
* @param point Starting point from where the travel boundary is calculated. Point in Lat,Long,coordsys format
* @param address Starting address from where the travel boundary is calculated.
* @param costUnit Travel time unit such as min(Minute), h(Hour), s(Second) or msec(Millisecond).
* @param db Mode of commute.
* @param country 3 character ISO code or country name.
* @param maxOffroadDistance Maximum distance to allow travel off the road network.
* @param maxOffroadDistanceUnit MaxOffroad Distance Unit such as ft(Foot), km(Kilometer), mi(Mile), m(Meter) or yd(Yard).
* @param destinationSrs Desired coordinate system of the travel boundary.
* @param majorRoads Whether to include all roads in the calculation or just major roads.
* @param returnHoles Whether to return holes, which are areas within the larger boundary that cannot be reached within the desired time.
* @param returnIslands Whether to return islands, which are small areas outside the main boundary that can be reached within the desired time.
* @param simplificationFactor Number between 0.0 and 1.0 where 0.0 is very simple and 1.0 means the most complex.
* @param bandingStyle Style of banding to be used in the result.
* @param historicTrafficTimeBucket Whether routing calculation uses the historic traffic speeds.
* @param defaultAmbientSpeed The speed to travel when going off a network road to find the travel boundary (for all road types).
* @param ambientSpeedUnit The unit of measure to use to calculate the ambient speed.
*/
public getTravelBoundaryByTime (costs: string, point?: string, address?: string, costUnit?: string, db?: string, country?: string, maxOffroadDistance?: string, maxOffroadDistanceUnit?: string, destinationSrs?: string, majorRoads?: string, returnHoles?: string, returnIslands?: string, simplificationFactor?: string, bandingStyle?: string, historicTrafficTimeBucket?: string, defaultAmbientSpeed?: string, ambientSpeedUnit?: string) : Promise<{ response: http.IncomingMessage; body: TravelBoundaries; }> {
const localVarPath = this.basePath + '/zones/v1/travelboundary/bytime';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'costs' is not null or undefined
if (costs === null || costs === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter costs was null or undefined when calling getTravelBoundaryByTime."}]}})
}
if (point !== undefined) {
queryParameters['point'] = point;
}
if (address !== undefined) {
queryParameters['address'] = address;
}
if (costs !== undefined) {
queryParameters['costs'] = costs;
}
if (costUnit !== undefined) {
queryParameters['costUnit'] = costUnit;
}
if (db !== undefined) {
queryParameters['db'] = db;
}
if (country !== undefined) {
queryParameters['country'] = country;
}
if (maxOffroadDistance !== undefined) {
queryParameters['maxOffroadDistance'] = maxOffroadDistance;
}
if (maxOffroadDistanceUnit !== undefined) {
queryParameters['maxOffroadDistanceUnit'] = maxOffroadDistanceUnit;
}
if (destinationSrs !== undefined) {
queryParameters['destinationSrs'] = destinationSrs;
}
if (majorRoads !== undefined) {
queryParameters['majorRoads'] = majorRoads;
}
if (returnHoles !== undefined) {
queryParameters['returnHoles'] = returnHoles;
}
if (returnIslands !== undefined) {
queryParameters['returnIslands'] = returnIslands;
}
if (simplificationFactor !== undefined) {
queryParameters['simplificationFactor'] = simplificationFactor;
}
if (bandingStyle !== undefined) {
queryParameters['bandingStyle'] = bandingStyle;
}
if (historicTrafficTimeBucket !== undefined) {
queryParameters['historicTrafficTimeBucket'] = historicTrafficTimeBucket;
}
if (defaultAmbientSpeed !== undefined) {
queryParameters['defaultAmbientSpeed'] = defaultAmbientSpeed;
}
if (ambientSpeedUnit !== undefined) {
queryParameters['ambientSpeedUnit'] = ambientSpeedUnit;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: TravelBoundaries; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
export enum _911PSAPServiceApiApiKeys {
}
export class _911PSAPServiceApi {
protected basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications : OAuth;
protected oAuthCred : oAuthCredInfo;
/*protected authentications = {
// 'default': <Authentication>new VoidAuth(),
'oAuth2Password': new OAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}*/
constructor(oAuthObj: oAuthCredInfo);
constructor(oAuthObj: oAuthCredInfo,basePath?: string)
{
if(oAuthObj)
{
this.oAuthCred=oAuthObj;
}
if (basePath) {
this.basePath = basePath;
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
public setApiKey(key: _911PSAPServiceApiApiKeys, value: string) {
this.authentications[_911PSAPServiceApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.objOAuthCredInfo.access_token = token;
}
/**
* AHJ & PSAP By Address.
* Accepts addresses as input and Returns contact details for Authorities Having Jurisdiction (AHJ) on-behalf-of local Public Safety Answering Points (PSAP). Geo911 accepts an address and returns PSAP contact data plus contact data for an AHJ to communicate directly with a PSAP. Details include agency name, phone number, city name, coverage, contact person's details, site details and mailing addresses for EMS, Fire, and Police PSAP contacts.
* @param address The address to be searched.
*/
public getAHJPlusPSAPByAddress (address: string) : Promise<{ response: http.IncomingMessage; body: AHJPlusPSAPResponse; }> {
const localVarPath = this.basePath + '/911/v1/ahj-psap/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getAHJPlusPSAPByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: AHJPlusPSAPResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* AHJ & PSAP By Location
* Accepts latitude & longitude as input and Returns contact details for Authorities Having Jurisdiction (AHJ) on-behalf-of local Public Safety Answering Points (PSAP). Geo911 accepts a location coordinate and returns PSAP contact data plus contact data for an AHJ to communicate directly with a PSAP. Details include agency name, phone number, city name, coverage, contact person's details, site details and mailing addresses for EMS, Fire, and Police PSAP contacts.
* @param longitude Longitude of the location.
* @param latitude Latitude of the location.
*/
public getAHJPlusPSAPByLocation (longitude: string, latitude: string) : Promise<{ response: http.IncomingMessage; body: AHJPlusPSAPResponse; }> {
const localVarPath = this.basePath + '/911/v1/ahj-psap/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getAHJPlusPSAPByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getAHJPlusPSAPByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: AHJPlusPSAPResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* PSAP By Address.
* Accepts addresses as input and returns contact details for local Public Safety Answering Points (PSAP). Geo911 accepts an address as input and returns the relevant PSAP address and contact details including agency name, phone number, county name, coverage, contact person's details, site details and mailing address.
* @param address The address to be searched.
*/
public getPSAPByAddress (address: string) : Promise<{ response: http.IncomingMessage; body: PSAPResponse; }> {
const localVarPath = this.basePath + '/911/v1/psap/byaddress';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'address' is not null or undefined
if (address === null || address === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter address was null or undefined when calling getPSAPByAddress."}]}})
}
if (address !== undefined) {
queryParameters['address'] = address;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: PSAPResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
/**
* PSAP By Location.
* Accepts latitude & longitude as input and Returns contact details for local Public Safety Answering Points (PSAP). Geo911 accepts a location coordinate and returns the relevant PSAP address and contact details including dispatch name, phone number, county name, coverage, contact person's details, site details and mailing address.
* @param longitude Longitude of the location.
* @param latitude Latitude of the location.
*/
public getPSAPByLocation (longitude: string, latitude: string) : Promise<{ response: http.IncomingMessage; body: PSAPResponse; }> {
const localVarPath = this.basePath + '/911/v1/psap/bylocation';
let queryParameters: any = {};
let headerParams: any = this.defaultHeaders;
let formParams: any = {};
// verify required parameter 'longitude' is not null or undefined
if (longitude === null || longitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter longitude was null or undefined when calling getPSAPByLocation."}]}})
}
// verify required parameter 'latitude' is not null or undefined
if (latitude === null || latitude === undefined) {
return Promise.reject({ response: null, body: {errors:[{"errorCode":"Validation_Error",errorDescription:"Required parameter latitude was null or undefined when calling getPSAPByLocation."}]}})
}
if (longitude !== undefined) {
queryParameters['longitude'] = longitude;
}
if (latitude !== undefined) {
queryParameters['latitude'] = latitude;
}
let useFormData = false;
let requestOptions: request.Options = {
method: 'GET',
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
//return this.authentications.oAuth2Password.applyToRequest()
//.then((data)=>{
// this.authentications.default.applyToRequest(requestOptions);
requestOptions.headers = {"authorization":"Bearer " + this.oAuthCred.access_token};
if (Object.keys(formParams).length) {
if (useFormData) {
(<any>requestOptions).formData = formParams;
} else {
requestOptions.form = formParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: PSAPResponse; }>((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(response);
}
}
});
});
/* })
.catch((error) =>{
return Promise.reject(error);
});*/
}
}
<file_sep>/README.md

# Precisely APIs
### Description
[Precisely APIs ](https://developer.precisely.com/) Enrich your data, and enhance your applications, business processes and workflows with dozens of powerful location & identity APIs.
### Precisely APIs:
* [Geocode](https://developer.precisely.com/apis/geocode): Accurate Geocoding. Convert individual or batch collections of addresses to latitude & longitude coordinates and vice versa. Useful for enhancing & enriching your customer addresses.
* [Typeahead](https://developer.precisely.com/apis/typeahead): Address Autocomplete. Build Address typeahead into your websites. The Typeahead API returns an autocompleted list of addresses based on the input of a partial address. Useful for any local search, checkout, shipping, or billing experiences on your website. Increase e-commerce conversion by 3-6%!
* [Maps](https://developer.precisely.com/apis/maps): Beautiful Visualization. Add your data and/or Precisely data atop beautiful maps for visualizations. Choose from three map styles - Bronze, Iron, and Steel.
* [Zones](https://developer.precisely.com/apis/zones): Smart Zones. The Zones API returns geographic zones by Radius, Drive Distance, Drive Time and highly localized geofence zones with the input of Location Coordinates or Addresses. Useful for anyone wanting to create smarter geofence zones for Local Engagement and Analysis.
* [Routing](https://developer.precisely.com/apis/routing): Accurate Routing. The Routing API returns Point-to-Point and Multi-Point Travel Directions by Various Travel Modes. Critical for any Simple or Complex Routing Requirement.
* [Streets](https://developer.precisely.com/apis/streets): Global Street Information. Enrich your applications, business processes, and workflows with global street information including nearest intersections and speed limits. The Streets API accepts an address or location and returns nearest intersection information. The speed limit method accepts a series of locations and returns speed limits along a street segment.
* [Places](https://developer.precisely.com/apis/places) : Global Place Data. Enrich your applications, business processes, and workflows with over 180 million of global retail businesses and landmark points-of-interest. The Places API accepts multiple powerful inputs & filtering options and returns thousands of records in a single API request. The Places API also supports global typeahead place search. Useful for enriching your data and/or analytics processes with rich commercial business information and place names.
* [Risks](https://developer.precisely.com/apis/risks): Risks Insights. Capture Crime, Earthquake, Flood, Fire, Fire Station and Distance-to-Flood-Hazard risk data for Analysis, Planning, Claims, and Mitigation. The Risks API returns risk intelligence with the input of Location Coordinates or Addresses. Critical for any impact analysis involving threats to lives or property.
* [911/PSAP](https://developer.precisely.com/apis/911): Emergency call handling. Integrate Public Safety Answering Point (PSAP) administrative call routing information plus Authority Having Jurisdiction (AHJ) phone numbers into your emergency services products and services. The 911/PSAP API retrieves 10-digit phone numbers and local contact info with the input of a location coordinate. Useful for emergency services administrators, call handlers, and dispatchers.
* [Demographics](https://developer.precisely.com/apis/demographics) : Audience Enrichment. Add local demographics and lifestyle segmentation to your people profiles. The Demographics & Lifestyle API returns household demographics and lifestyle characteristics with the input of an address or location coordinate. Know more about your customers and their customers.
* [Local Tax](https://developer.precisely.com/apis/localtax): Local Tax. Add hyperlocal tax rates to your applications, business processes, and workflows. The Local Tax API returns local tax rates with the input of location coordinates or addresses. Critical for any billing, commerce, payment, or payroll application or service.
* [Telecomm Info](https://developer.precisely.com/apis/telecomm): Service Provider Intelligence. Identify Local Exchange Carrier presence, area codes, exchanges, and more within a Rate Center area. The Telecomm Info API retrieves Incumbent Local Exchange Carrier (ILEC) doing-business-as names along with NPA/NXX, LATA, and phone number ranges with the input of an address or location coordinates. Useful for local telecommunications competitive intelligence, partnerships, and provisioning subscribers.
* [Time Zone](https://developer.precisely.com/apis/timezone): Local time. The Time Zone API returns time zones and UTC offsets with the input of a location coordinate or address. Useful for do-not-call, logistics, and customer engagement applications, business processes and workflows.
* [Geolocation](https://developer.precisely.com/apis/geolocation): Device Location. The Geolocation API returns location coordinates based on the input of an IP Address or Wi-Fi Access point MAC address. Useful for a variety of applications, business processes and workflows in eCommerce, Fraud Detection, Physical-Digital interactions, Field Service and more.
* [Identity Profiles](https://developer.precisely.com/apis/identityprofiles): Rich Identity Profiles. Powerful, local socio-economic & affinity insights about your customer. Enrich shipping addresses with rich, localized Identity profiles, demographics, lifestyle segmentations, neighborhood names, property ownership & values, and social affinity insights. The Identity Profiles API returns all these data with the input of a Physical Address, Email Address, or Twitter handle. Useful for enhancing & enriching a wide variety of applications, business processes, or workflows.
* [Schools](https://developer.precisely.com/apis/schools): School Listings. Gather local multiple school listings, types, districts and education levels for your applications. The Schools API accepts multiple powerful inputs & geographic filtering options and returns nearby school listings and additional data a single API request. Useful for enriching your applications and websites.
* [Neighborhoods](https://developer.precisely.com/apis/neighborhoods): Neighborhood Insights. Integrate global neighborhood names and classification information into your applications and enrich other data. The Neighborhood API accepts latitude & longitude coordinates and returns the corresponding neighborhood name & type. Useful for a wide range of data enrichment use cases.
* [Property Information](https://developer.precisely.com/apis/property): Property Insights. Integrate extensive residential & commercial property information into your applications. The Property Information API returns property parcel boundaries and hundreds of property attributes for millions of US properties with the input of Location Coordinates or Addresses. Useful for Real Estate use cases or those involving risk assessments.
* [Address Verification](https://developer.precisely.com/apis/addressverification): Real, accurate and complete address. Eliminate errors in address data, improve customer experience. The Address Verification API makes communication easier, faster and effortless by enriching customer details, keeping it up-to-date and maintaining its accuracy and consistency. It eliminates redundancy in reaching out to customers and makes it easy for distinct functional areas to work seamlessly in improving customer relationship.
* [Email Verification](https://developer.precisely.com/apis/emailverification): Email address validation and protection. The Email Verification API corrects and validates your email addresses to protect your database from invalid, toxic and undesirable email addresses. We help you avoid a damaged sender reputations by flagging those bouncing emails, spam trap hits, honeypots, stale lists and do-not-contact list before you have a chance to use them.
* [Addresses](https://developer.precisely.com/apis/addresses): Gather multiple Addresses if you don’t have them and use these to query all other Precisely APIs. The Addresses API accepts names of a boundary such as zip code, neighborhood, county, and city—as well as your custom geographic boundaries or drivetimes & drive distances—and returns all known & valid Addresses associated with these names, or Addresses contained with the supplied or chosen geographic boundary.
* [Phone Verification](https://developer.precisely.com/apis/phoneverification): The Phone Verification API accepts any phone number as input and returns verification information, Service Provider name, and more. Useful to verify if phone numbers exist to reduce fraud and improve communications.
The following platforms are supported by Precisely SDKs:
* [Android](https://developer.precisely.com/apis/docs/index.html#Android%20SDK/android_intro.html)
* [NodeJS]()
* [iOS](https://developer.precisely.com/apis/docs/index.html#iOS%20SDK/ios_intro.html)
* [Java](https://developer.precisely.com/apis/docs/index.html#Java%20SDK/java_intro.html)
* [C#](https://developer.precisely.com/apis/docs/index.html#C_sdk/java_intro.html)
[Click here](https://developer.precisely.com/apis/docs/index.html) for detailed Documentation on Precisely APIs
# PreciselyAPIs NodeJS SDK
### Description
PreciselyAPIs NodeJS SDK facilitates you to build NodeJS applications using Precisely APIs.
### Getting Started
To get started with NodeJS SDK, you must first register at [Precisely APIs Home Page](https://developer.precisely.com/) and obtain your API Key and Secret to get started with the NodeJS SDK and call Precisely APIs.
For more information refer to [‘Getting Started with NodeJS SDK’](https://developer.precisely.com/apis/docs/index.html#NodeJS/node.js_sdk.html) section in documentation.
# PreciselyAPIsSDK-NodeJS
## Building Project
To build the project locally by downloading from GitHub
``` shell
npm install
npm run build
```
## Requirements
Building the API client library requires latest [NodeJS](https://nodejs.org/en/) to be installed.
## Installation
To install the API client library to your local project, simply execute:
```shell
npm install preciselyapis-client
```
To deploy it globally, simply execute:
```shell
npm install -g preciselyapis-client
```
## Getting Started
Please follow the [installation](#installation) instruction and execute the following NodeJS code:
```js
//We are getting refrence to the installed preciselyapis-client package
const PreciselyAPINodeJS = require('preciselyapis-client');
try {
// Configure OAuth2 API_KEY and SECRET for authorization
const oAuth = new PreciselyAPINodeJS.OAuth();
oAuth.oAuthApiKey="API_KEY";
oAuth.oAuthSecret="SECRET";
oAuth.getOAuthCredentials().then((data) => {
var _911PSAPServiceApi = new PreciselyAPINodeJS._911PSAPServiceApi(data.body);
_911PSAPServiceApi.getAHJPlusPSAPByAddress("950 Josephine Street Denver CO 80204").then((response) => {
console.log("Result " + JSON.stringify(response.body));
}).catch((response) => {
console.log("Error " + JSON.stringify(response.body));
});
}).catch((error) => {
console.log("Error" + JSON.stringify(error))
});
}
catch (error1) {
console.log("Exception raised"+ error1);
}
```
|
9ef0f242332e9731e8a9e95acc007c1651f4c404
|
[
"Markdown",
"TypeScript"
] | 2 |
TypeScript
|
rexhomes/PreciselyAPIsSDK-NodeJS
|
f0963da718f72d11ddb15d8e114a6353f053965f
|
1ce847b975136884be155fa8bfd8c05011255450
|
refs/heads/master
|
<repo_name>btimmie/TP<file_sep>/src/main/java/com/branwyn/cput/tp/DIP/violation/ErrorMessage.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.branwyn.cput.tp.DIP.violation;
/**
*
* @author Branwyn
*/
class ErrorMessage {
public String intErrorMessage()
{
return "Invalid number entered.";
}
}
|
1385be090faf3cb0ce6545b077f84a252291ccd9
|
[
"Java"
] | 1 |
Java
|
btimmie/TP
|
4f38a9c502d7ce6948adbda80096d2096b96234c
|
fd6e60c1fb7fd48072b4f7ff8fcb9fc7e712378b
|
refs/heads/master
|
<repo_name>GolKost/first<file_sep>/1.rb
str = 'asdf aaaayyyee oooo kjhsdp uuuuuu eeeee iiiiiiauu'
puts str.scan(/\b[AEIOUYaeiouy]+\b/).select.with_index { |e, index| index.odd? }
all? {}
|
2a6daa0c83aca43d02ddcfded4d380d67ac3d168
|
[
"Ruby"
] | 1 |
Ruby
|
GolKost/first
|
975e33218f7eb113802aee9d128ee7ff39a0c124
|
eadca24db96d74dde1d669379e8f82bffe922793
|
refs/heads/master
|
<repo_name>sivertsenstian/UNITYBadlands<file_sep>/Assets/Badlands.Serialization/Save.cs
using System.Collections.Generic;
using System;
using Badlands.Blocks;
using Badlands.World;
namespace Badlands.Serialization
{
[Serializable]
public class Save
{
public Dictionary<MapPosition, Block> blocks = new Dictionary<MapPosition, Block>();
public Save(Chunk chunk)
{
for (int x = 0; x < Chunk.chunkSize; x++)
{
for (int y = 0; y < Chunk.chunkSize; y++)
{
for (int z = 0; z < Chunk.chunkSize; z++)
{
if (!chunk.blocks[x, y, z].changed)
continue;
MapPosition pos = new MapPosition(x, y, z);
blocks.Add(pos, chunk.blocks[x, y, z]);
}
}
}
}
}
}<file_sep>/Assets/Badlands.World/TerrainGenerator.cs
using UnityEngine;
using Badlands.Blocks;
using Badlands.Helpers;
namespace Badlands.World
{
public class TerrainGenerator
{
float stoneBaseHeight = 0;
float stoneBaseNoise = 0.05f;
float stoneBaseNoiseHeight = 4;
float stoneMountainHeight = 12;
float stoneMountainFrequency = 0.004f;
float stoneMinHeight = 6;
float sandBaseHeight = 1;
float sandNoise = 0.04f;
float sandNoiseHeight = 0;
float caveFrequency = 0.015f;
int caveSize = 8;
float treeFrequency = .04f;
int treeDensity = 40;
float waterFrequency = .005f;
int waterDensity = 50;
int waterDepth = 8;
public static int GetNoise(int x, int y, int z, float scale, int max)
{
return Mathf.FloorToInt((Noise.Generate(x * scale, y * scale, z * scale) + 1f) * (max / 2f));
}
public Chunk ChunkGenerator(Chunk chunk)
{
for (int x = chunk.pos.x; x < chunk.pos.x + Chunk.chunkSize; x++)
{
for (int z = chunk.pos.z; z < chunk.pos.z + Chunk.chunkSize; z++)
{
chunk = ChunkColumnGenerator(chunk, x, z);
}
}
return chunk;
}
public Chunk ChunkColumnGenerator(Chunk chunk, int x, int z)
{
int stoneHeight = Mathf.FloorToInt(stoneBaseHeight);
stoneHeight += GetNoise(x, 0, z, stoneMountainFrequency, Mathf.FloorToInt(stoneMountainHeight));
if (stoneHeight < stoneMinHeight)
stoneHeight = Mathf.FloorToInt(stoneMinHeight);
stoneHeight += GetNoise(x, 0, z, stoneBaseNoise, Mathf.FloorToInt(stoneBaseNoiseHeight));
int sandHeight = stoneHeight + Mathf.FloorToInt(sandBaseHeight);
sandHeight += GetNoise(x, 100, z, sandNoise, Mathf.FloorToInt(sandNoiseHeight));
for (int y = chunk.pos.y; y < chunk.pos.y + Chunk.chunkSize; y++)
{
int caveChance = GetNoise(x, y, z, caveFrequency, 100);
if (y <= stoneHeight && caveSize < caveChance)
{
SetBlock(x, y, z, new BlockDirt(), chunk);
}
else if (y <= sandHeight && caveSize < caveChance)
{
SetBlock(x, y, z, new BlockSand(), chunk);
if (y == sandHeight && GetNoise(x, 0, z, treeFrequency, 100) < treeDensity)
{
CreateTree(x, y + 1, z, chunk);
}
else
{
if (y == sandHeight && GetNoise(x, 0, z, waterFrequency, 150) < waterDensity)
{
CreateWater(x, y, z, chunk);
}
}
}
else
{
SetBlock(x, y, z, new BlockAir(), chunk);
}
}
return chunk;
}
public static void SetBlock(int x, int y, int z, Block block, Chunk chunk, bool replaceBlocks = false)
{
x -= chunk.pos.x;
y -= chunk.pos.y;
z -= chunk.pos.z;
if (Chunk.InRange(x) && Chunk.InRange(y) && Chunk.InRange(z))
{
if (replaceBlocks || chunk.blocks[x, y, z] == null)
chunk.SetBlock(x, y, z, block);
}
}
void CreateTree(int x, int y, int z, Chunk chunk)
{
//create tree
Block tree = (Random.value > 0.05) ? (Random.value > 0.5) ? new BlockTreeYellow() : new BlockTreeRed() as Block : new BlockTreeGreen() as Block;
SetBlock(x, y, z, tree, chunk, true);
}
void CreateWater(int x, int y, int z, Chunk chunk)
{
//create water
Block water = new BlockWater();
Block air = new BlockAir();
//Land buffer
SetBlock(x, y, z, air, chunk, true);
SetBlock(x, y - 1, z, air, chunk, true);
for(var i = 2; i < waterDepth; i++)
{
SetBlock(x, y - i, z, water, chunk, true);
}
}
}
}<file_sep>/Assets/Badlands.Blocks/BlockTreeYellow.cs
using System;
namespace Badlands.Blocks
{
[Serializable]
public class BlockTreeYellow : BlockTree
{
public BlockTreeYellow()
: base()
{
}
public override Tile TexturePosition(Direction direction)
{
Tile tile = new Tile();
switch (direction)
{
case Direction.down:
tile.x = 2;
tile.y = 1;
return tile;
}
tile.x = 3;
tile.y = 1;
return tile;
}
}
}<file_sep>/Assets/Badlands.Player/HumanController.cs
using System;
using UnityEngine;
using UnityEngine.UI;
namespace Badlands.Player
{
public class HumanController : MonoBehaviour
{
public int _gold;
public int _fuel;
public int _wood;
public int _upkeep;
public int _maxupkeep;
public Guid _id;
public string _name;
void Awake()
{
_id = new Guid();
}
void Update()
{
}
}
}
<file_sep>/Assets/Badlands.World/Map.cs
using UnityEngine;
using System.Collections.Generic;
using Badlands.Blocks;
using System;
namespace Badlands.World
{
public class Map : MonoBehaviour
{
public Dictionary<MapPosition, Chunk> chunks = new Dictionary<MapPosition, Chunk>();
public GameObject chunkPrefab;
public string worldName = "world";
public DateTime _date = new DateTime();
public void CreateChunk(int x, int y, int z)
{
//the coordinates of this chunk in the world
MapPosition mapPos = new MapPosition(x, y, z);
//Instantiate the chunk at the coordinates using the chunk prefab
GameObject newChunkObject = Instantiate(
chunkPrefab, new Vector3(mapPos.x, mapPos.y, mapPos.z),
Quaternion.Euler(Vector3.zero)
) as GameObject;
//Set this map as the parent gameobject
newChunkObject.GetComponent<Transform>().parent = this.GetComponent<Transform>();
//Get the object's chunk component
Chunk newChunk = newChunkObject.GetComponent<Chunk>();
//Assign its values
newChunk.pos = mapPos;
newChunk.world = this;
//Add it to the chunks dictionary with the position as the key
chunks.Add(mapPos, newChunk);
var terrainGenerator = new TerrainGenerator();
newChunk = terrainGenerator.ChunkGenerator(newChunk);
newChunk.SetBlocksUnmodified();
//Serializer.Load(newChunk);
}
public Chunk GetChunk(int x, int y, int z)
{
MapPosition pos = new MapPosition();
float multiple = Chunk.chunkSize;
pos.x = Mathf.FloorToInt(x / multiple) * Chunk.chunkSize;
pos.y = Mathf.FloorToInt(y / multiple) * Chunk.chunkSize;
pos.z = Mathf.FloorToInt(z / multiple) * Chunk.chunkSize;
Chunk containerChunk = null;
chunks.TryGetValue(pos, out containerChunk);
return containerChunk;
}
public Block GetBlock(int x, int y, int z)
{
Chunk containerChunk = GetChunk(x, y, z);
if (containerChunk != null)
{
Block block = containerChunk.GetBlock(
x - containerChunk.pos.x,
y - containerChunk.pos.y,
z - containerChunk.pos.z);
return block;
}
else
{
return new BlockAir();
}
}
void UpdateIfEqual(int value1, int value2, MapPosition pos)
{
if (value1 == value2)
{
Chunk chunk = GetChunk(pos.x, pos.y, pos.z);
if (chunk != null)
chunk.update = true;
}
}
public void SetBlock(int x, int y, int z, Block block)
{
Chunk chunk = GetChunk(x, y, z);
if (chunk != null)
{
chunk.SetBlock(x - chunk.pos.x, y - chunk.pos.y, z - chunk.pos.z, block);
chunk.update = true;
UpdateIfEqual(x - chunk.pos.x, 0, new MapPosition(x - 1, y, z));
UpdateIfEqual(x - chunk.pos.x, Chunk.chunkSize - 1, new MapPosition(x + 1, y, z));
UpdateIfEqual(y - chunk.pos.y, 0, new MapPosition(x, y - 1, z));
UpdateIfEqual(y - chunk.pos.y, Chunk.chunkSize - 1, new MapPosition(x, y + 1, z));
UpdateIfEqual(z - chunk.pos.z, 0, new MapPosition(x, y, z - 1));
UpdateIfEqual(z - chunk.pos.z, Chunk.chunkSize - 1, new MapPosition(x, y, z + 1));
}
}
public void DestroyChunk(int x, int y, int z)
{
Chunk chunk = null;
if (chunks.TryGetValue(new MapPosition(x, y, z), out chunk))
{
//Serializer.SaveChunk(chunk);
Destroy(chunk.gameObject);
chunks.Remove(new MapPosition(x, y, z));
}
}
void FixedUpdate()
{
this._date.AddHours(1);
}
}
}
<file_sep>/Assets/Badlands.UI/UpdateFuelFromPlayer.cs
using UnityEngine;
using UnityEngine.UI;
using Badlands.Player;
using System;
namespace Badlands.UI {
public class UpdateFuelFromPlayer : MonoBehaviour {
public GameObject Player;
private Text _fuel;
private HumanController _controller;
// Use this for initialization
void Start() {
this.enabled = true;
this._fuel = this.GetComponent<Text>();
this._controller = this.Player.GetComponent<HumanController>();
}
// Update is called once per frame
void Update() {
this._fuel.text = Convert.ToString(_controller._fuel);
}
}
}
<file_sep>/Assets/Badlands.Blocks/BlockWater.cs
using UnityEngine;
using System.Collections;
using System;
namespace Badlands.Blocks
{
[Serializable]
public class BlockWater : Block
{
public BlockWater()
: base()
{
}
public override Tile TexturePosition(Direction direction)
{
Tile tile = new Tile();
tile.x = 3;
tile.y = 2;
return tile;
}
public override bool IsSolid(Direction direction)
{
switch (direction)
{
case Direction.up:
return false;
}
return true;
}
}
}<file_sep>/Assets/Badlands.Player/Modify.cs
using UnityEngine;
using Badlands.Blocks;
using Badlands.World;
using UnityEngine.EventSystems;
using System.Collections.Generic;
namespace Badlands.Player
{
public class Modify : MonoBehaviour
{
private Block _activeBlock = new BlockWater();
private RaycastHit _hit;
private Vector3 _previousPosition;
private MapPosition? _hitBlock;
private List<RaycastHit> _highlights = new List<RaycastHit>();
private bool _editMode = false;
private Stack<RaycastHit[]> _stack = new Stack<RaycastHit[]>();
public void SetActiveBlock(string type)
{
switch (type.ToLower())
{
case "grass":
this._activeBlock = new BlockGrass();
break;
case "water":
this._activeBlock = new BlockWater();
break;
case "dirt":
this._activeBlock = new BlockDirt();
break;
case "snow":
this._activeBlock = new BlockSnow();
break;
case "sand":
this._activeBlock = new BlockSand();
break;
case "stone":
this._activeBlock = new BlockStone();
break;
case "treered":
this._activeBlock = new BlockTreeRed();
break;
case "treeyellow":
this._activeBlock = new BlockTreeYellow();
break;
case "road":
this._activeBlock = new BlockRoad();
break;
case "air":
this._activeBlock = new BlockAir();
break;
default:
this._activeBlock = null;
break;
}
}
void Update()
{
if (this._activeBlock != null)
{
if (!EventSystem.current.IsPointerOverGameObject())
{
//START EDIT
if (Input.GetMouseButtonDown(0))
{
if (!this._editMode)
{
this._editMode = true;
}
else
{
if (this._activeBlock.IsRoad())
{
for (var i = 0; i < _highlights.Count; i++)
{
EditTerrain.SetHighlightedRoadBlock(_highlights[i]);
}
}
else
{
for (var i = 0; i < _highlights.Count; i++)
{
EditTerrain.SetHighlightedBlock(_highlights[i], this._activeBlock);
}
}
this._editMode = false;
_stack.Push(_highlights.ToArray());
_highlights.Clear();
}
}
//CANCEL EDIT
if (Input.GetMouseButtonDown(1))
{
for (var i = 0; i < _highlights.Count; i++)
{
EditTerrain.SetHighlightedBlock(_highlights[i], new BlockAir());
}
this._editMode = false;
_highlights.Clear();
}
}
}
//UNDO
if (Input.GetKeyDown(KeyCode.Z))
{
var list = _stack.Pop();
for (var i = 0; i < list.Length; i++)
{
EditTerrain.SetUpIfSolidBlock(list[i], new BlockAir());
}
}
}
void FixedUpdate()
{
//HIGHLIGHT BLOCKS TO BE MODIFIED IF EDIT IS TRUE
if (this._editMode && this._activeBlock != null)
{
if (Input.mousePosition != _previousPosition)
{
if (!EventSystem.current.IsPointerOverGameObject())
{
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out _hit))
{
_hitBlock = EditTerrain.HighlightBlock(_hit);
_highlights.Add(_hit);
}
}
_previousPosition = Input.mousePosition;
}
}
}
}
}<file_sep>/Assets/Badlands.World/EditTerrain.cs
using UnityEngine;
using Badlands.Blocks;
namespace Badlands.World
{
public static class EditTerrain
{
public static MapPosition GetBlockPos(Vector3 pos)
{
MapPosition blockPos = new MapPosition(
Mathf.RoundToInt(pos.x),
Mathf.RoundToInt(pos.y),
Mathf.RoundToInt(pos.z)
);
return blockPos;
}
public static MapPosition GetBlockPos(RaycastHit hit, bool adjacent = false)
{
Vector3 pos = new Vector3(
MoveWithinBlock(hit.point.x, hit.normal.x, adjacent),
MoveWithinBlock(hit.point.y, hit.normal.y, adjacent),
MoveWithinBlock(hit.point.z, hit.normal.z, adjacent)
);
return GetBlockPos(pos);
}
static float MoveWithinBlock(float pos, float norm, bool adjacent = false)
{
if (pos - (int)pos == 0.5f || pos - (int)pos == -0.5f)
{
if (adjacent)
{
pos += (norm / 2);
}
else
{
pos -= (norm / 2);
}
}
return (float)pos;
}
public static bool SetBlock(RaycastHit hit, Block block, bool adjacent = false)
{
Chunk chunk = hit.collider.GetComponent<Chunk>();
if (chunk == null)
return false;
MapPosition pos = GetBlockPos(hit, adjacent);
chunk.world.SetBlock(pos.x, pos.y, pos.z, block);
return true;
}
public static bool SetUpIfSolidBlock(RaycastHit hit, Block block)
{
Chunk chunk = hit.collider.GetComponent<Chunk>();
if (chunk == null)
return false;
MapPosition pos = GetBlockPos(hit);
if (chunk.world.GetBlock(pos.x, pos.y, pos.z).IsSolid(Direction.up))
{
chunk.world.SetBlock(pos.x, pos.y + 1, pos.z, block);
return true;
}
return false;
}
public static bool SetHighlightedBlock(RaycastHit hit, Block block)
{
Chunk chunk = hit.collider.GetComponent<Chunk>();
if (chunk == null)
return false;
MapPosition pos = GetBlockPos(hit);
if (chunk.world.GetBlock(pos.x, pos.y, pos.z).IsSolid(Direction.up) && chunk.world.GetBlock(pos.x, pos.y + 1, pos.z) is BlockHighlight)
{
chunk.world.SetBlock(pos.x, pos.y + 1, pos.z, block);
return true;
}
return false;
}
public static bool SetHighlightedRoadBlock(RaycastHit hit)
{
Chunk chunk = hit.collider.GetComponent<Chunk>();
if (chunk == null)
return false;
MapPosition pos = GetBlockPos(hit);
return _setRoad(chunk, pos);
}
//TODO: ORIENTATION
//http://gamedev.stackexchange.com/questions/29524/choose-tile-based-on-adjacent-tiles
//http://www.angryfishstudios.com/2011/04/adventures-in-bitmasking/
private static bool _setRoad(Chunk chunk, MapPosition pos)
{
if (chunk.world.GetBlock(pos.x, pos.y, pos.z).IsSolid(Direction.up) && chunk.world.GetBlock(pos.x, pos.y + 1, pos.z) is BlockHighlight)
{
chunk.world.SetBlock(pos.x, pos.y + 1, pos.z, new BlockRoad());
return true;
}
return false;
}
//private static bool _setRoad(Chunk chunk, MapPosition pos)
//{
// if (chunk == null)
// return false;
// Block road;
// Block westBlock = chunk.world.GetBlock(pos.x - 1, pos.y + 1, pos.z);
// Block eastBlock = chunk.world.GetBlock(pos.x + 1, pos.y + 1, pos.z);
// Block northBlock = chunk.world.GetBlock(pos.x, pos.y + 1, pos.z + 1);
// Block southBlock = chunk.world.GetBlock(pos.x, pos.y + 1, pos.z - 1);
// bool west, east, north, south;
// //chunk.world.SetBlock(pos.x, pos.y + 1, pos.z + 1, new BlockSnow());
// //chunk.world.SetBlock(pos.x, pos.y + 1, pos.z - 1, new BlockGrass());
// //chunk.world.SetBlock(pos.x + 1, pos.y + 1, pos.z, new BlockStone());
// //chunk.world.SetBlock(pos.x - 1, pos.y + 1, pos.z, new BlockSand());
// west = westBlock.IsRoad() || westBlock is BlockHighlight;
// east = eastBlock.IsRoad() || eastBlock is BlockHighlight;
// north = northBlock.IsRoad() || northBlock is BlockHighlight;
// south = southBlock.IsRoad() || southBlock is BlockHighlight;
// if (east || west)
// {
// if (south && east)
// {
// road = new BlockRoadNE();
// }
// else if (south && west)
// {
// road = new BlockRoadNW();
// }
// else if (north && east)
// {
// road = new BlockRoadSE();
// }
// else if (north && west)
// {
// road = new BlockRoadSW();
// }
// else
// {
// road = new BlockRoadEW();
// }
// }
// else if (north || south)
// {
// road = new BlockRoadNS();
// }
// else
// {
// road = new Block();
// }
// if (chunk.world.GetBlock(pos.x, pos.y, pos.z).IsSolid(Direction.up) && chunk.world.GetBlock(pos.x, pos.y + 1, pos.z) is BlockHighlight)
// {
// chunk.world.SetBlock(pos.x, pos.y + 1, pos.z, road);
// return true;
// }
// return false;
//}
public static MapPosition? HighlightBlock(RaycastHit hit)
{
Chunk chunk = hit.collider.GetComponent<Chunk>();
if (chunk == null)
return null;
MapPosition pos = GetBlockPos(hit);
if (chunk.world.GetBlock(pos.x, pos.y, pos.z).IsSolid(Direction.up) && chunk.world.GetBlock(pos.x, pos.y + 1, pos.z) is BlockAir)
{
chunk.world.SetBlock(pos.x, pos.y + 1, pos.z, new BlockHighlight());
return pos;
}
return null;
}
public static bool RemoveHighlightBlock(RaycastHit hit)
{
Chunk chunk = hit.collider.GetComponent<Chunk>();
if (chunk == null)
return false;
MapPosition pos = GetBlockPos(hit);
if (chunk.world.GetBlock(pos.x, pos.y, pos.z).IsSolid(Direction.up) && chunk.world.GetBlock(pos.x, pos.y + 1, pos.z) is BlockHighlight)
{
chunk.world.SetBlock(pos.x, pos.y + 1, pos.z, new BlockAir());
return true;
}
return false;
}
public static Block GetBlock(RaycastHit hit, bool adjacent = false)
{
Chunk chunk = hit.collider.GetComponent<Chunk>();
if (chunk == null)
return null;
MapPosition pos = GetBlockPos(hit, adjacent);
Block block = chunk.world.GetBlock(pos.x, pos.y, pos.z);
return block;
}
}
}<file_sep>/Assets/Badlands.UI/UpdateGoldFromPlayer.cs
using UnityEngine;
using UnityEngine.UI;
using Badlands.Player;
using System;
namespace Badlands.UI
{
public class UpdateGoldFromPlayer : MonoBehaviour
{
public GameObject Player;
private Text _gold;
private HumanController _controller;
// Use this for initialization
void Start()
{
this.enabled = true;
this._gold = this.GetComponent<Text>();
this._controller = this.Player.GetComponent<HumanController>();
}
// Update is called once per frame
void Update()
{
this._gold.text = Convert.ToString(_controller._gold);
}
}
}
<file_sep>/Assets/Badlands.Player/LoadChunks.cs
using UnityEngine;
using System.Collections.Generic;
using Badlands.World;
namespace Badlands.Player
{
public class LoadChunks : MonoBehaviour
{
public Map world;
List<MapPosition> updateList = new List<MapPosition>();
List<MapPosition> buildList = new List<MapPosition>();
int timer = 0;
static MapPosition[] chunkPositions = { new MapPosition( 0, 0, 0), new MapPosition(-1, 0, 0), new MapPosition( 0, 0, -1), new MapPosition( 0, 0, 1), new MapPosition( 1, 0, 0),
new MapPosition(-1, 0, -1), new MapPosition(-1, 0, 1), new MapPosition( 1, 0, -1), new MapPosition( 1, 0, 1), new MapPosition(-2, 0, 0),
new MapPosition( 0, 0, -2), new MapPosition( 0, 0, 2), new MapPosition( 2, 0, 0), new MapPosition(-2, 0, -1), new MapPosition(-2, 0, 1),
new MapPosition(-1, 0, -2), new MapPosition(-1, 0, 2), new MapPosition( 1, 0, -2), new MapPosition( 1, 0, 2), new MapPosition( 2, 0, -1),
new MapPosition( 2, 0, 1), new MapPosition(-2, 0, -2), new MapPosition(-2, 0, 2), new MapPosition( 2, 0, -2), new MapPosition( 2, 0, 2),
new MapPosition(-3, 0, 0), new MapPosition( 0, 0, -3), new MapPosition( 0, 0, 3), new MapPosition( 3, 0, 0), new MapPosition(-3, 0, -1),
new MapPosition(-3, 0, 1), new MapPosition(-1, 0, -3), new MapPosition(-1, 0, 3), new MapPosition( 1, 0, -3), new MapPosition( 1, 0, 3),
new MapPosition( 3, 0, -1), new MapPosition( 3, 0, 1), new MapPosition(-3, 0, -2), new MapPosition(-3, 0, 2), new MapPosition(-2, 0, -3),
new MapPosition(-2, 0, 3), new MapPosition( 2, 0, -3), new MapPosition( 2, 0, 3), new MapPosition( 3, 0, -2), new MapPosition( 3, 0, 2),
new MapPosition(-4, 0, 0), new MapPosition( 0, 0, -4), new MapPosition( 0, 0, 4), new MapPosition( 4, 0, 0), new MapPosition(-4, 0, -1),
new MapPosition(-4, 0, 1), new MapPosition(-1, 0, -4), new MapPosition(-1, 0, 4), new MapPosition( 1, 0, -4), new MapPosition( 1, 0, 4),
new MapPosition( 4, 0, -1), new MapPosition( 4, 0, 1), new MapPosition(-3, 0, -3), new MapPosition(-3, 0, 3), new MapPosition( 3, 0, -3),
new MapPosition( 3, 0, 3), new MapPosition(-4, 0, -2), new MapPosition(-4, 0, 2), new MapPosition(-2, 0, -4), new MapPosition(-2, 0, 4),
new MapPosition( 2, 0, -4), new MapPosition( 2, 0, 4), new MapPosition( 4, 0, -2), new MapPosition( 4, 0, 2), new MapPosition(-5, 0, 0),
new MapPosition(-4, 0, -3), new MapPosition(-4, 0, 3), new MapPosition(-3, 0, -4), new MapPosition(-3, 0, 4), new MapPosition( 0, 0, -5),
new MapPosition( 0, 0, 5), new MapPosition( 3, 0, -4), new MapPosition( 3, 0, 4), new MapPosition( 4, 0, -3), new MapPosition( 4, 0, 3),
new MapPosition( 5, 0, 0), new MapPosition(-5, 0, -1), new MapPosition(-5, 0, 1), new MapPosition(-1, 0, -5), new MapPosition(-1, 0, 5),
new MapPosition( 1, 0, -5), new MapPosition( 1, 0, 5), new MapPosition( 5, 0, -1), new MapPosition( 5, 0, 1), new MapPosition(-5, 0, -2),
new MapPosition(-5, 0, 2), new MapPosition(-2, 0, -5), new MapPosition(-2, 0, 5), new MapPosition( 2, 0, -5), new MapPosition( 2, 0, 5),
new MapPosition( 5, 0, -2), new MapPosition( 5, 0, 2), new MapPosition(-4, 0, -4), new MapPosition(-4, 0, 4), new MapPosition( 4, 0, -4),
new MapPosition( 4, 0, 4), new MapPosition(-5, 0, -3), new MapPosition(-5, 0, 3), new MapPosition(-3, 0, -5), new MapPosition(-3, 0, 5),
new MapPosition( 3, 0, -5), new MapPosition( 3, 0, 5), new MapPosition( 5, 0, -3), new MapPosition( 5, 0, 3), new MapPosition(-6, 0, 0),
new MapPosition( 0, 0, -6), new MapPosition( 0, 0, 6), new MapPosition( 6, 0, 0), new MapPosition(-6, 0, -1), new MapPosition(-6, 0, 1),
new MapPosition(-1, 0, -6), new MapPosition(-1, 0, 6), new MapPosition( 1, 0, -6), new MapPosition( 1, 0, 6), new MapPosition( 6, 0, -1),
new MapPosition( 6, 0, 1), new MapPosition(-6, 0, -2), new MapPosition(-6, 0, 2), new MapPosition(-2, 0, -6), new MapPosition(-2, 0, 6),
new MapPosition( 2, 0, -6), new MapPosition( 2, 0, 6), new MapPosition( 6, 0, -2), new MapPosition( 6, 0, 2), new MapPosition(-5, 0, -4),
new MapPosition(-5, 0, 4), new MapPosition(-4, 0, -5), new MapPosition(-4, 0, 5), new MapPosition( 4, 0, -5), new MapPosition( 4, 0, 5),
new MapPosition( 5, 0, -4), new MapPosition( 5, 0, 4), new MapPosition(-6, 0, -3), new MapPosition(-6, 0, 3), new MapPosition(-3, 0, -6),
new MapPosition(-3, 0, 6), new MapPosition( 3, 0, -6), new MapPosition( 3, 0, 6), new MapPosition( 6, 0, -3), new MapPosition( 6, 0, 3),
new MapPosition(-7, 0, 0), new MapPosition( 0, 0, -7), new MapPosition( 0, 0, 7), new MapPosition( 7, 0, 0), new MapPosition(-7, 0, -1),
new MapPosition(-7, 0, 1), new MapPosition(-5, 0, -5), new MapPosition(-5, 0, 5), new MapPosition(-1, 0, -7), new MapPosition(-1, 0, 7),
new MapPosition( 1, 0, -7), new MapPosition( 1, 0, 7), new MapPosition( 5, 0, -5), new MapPosition( 5, 0, 5), new MapPosition( 7, 0, -1),
new MapPosition( 7, 0, 1), new MapPosition(-6, 0, -4), new MapPosition(-6, 0, 4), new MapPosition(-4, 0, -6), new MapPosition(-4, 0, 6),
new MapPosition( 4, 0, -6), new MapPosition( 4, 0, 6), new MapPosition( 6, 0, -4), new MapPosition( 6, 0, 4), new MapPosition(-7, 0, -2),
new MapPosition(-7, 0, 2), new MapPosition(-2, 0, -7), new MapPosition(-2, 0, 7), new MapPosition( 2, 0, -7), new MapPosition( 2, 0, 7),
new MapPosition( 7, 0, -2), new MapPosition( 7, 0, 2), new MapPosition(-7, 0, -3), new MapPosition(-7, 0, 3), new MapPosition(-3, 0, -7),
new MapPosition(-3, 0, 7), new MapPosition( 3, 0, -7), new MapPosition( 3, 0, 7), new MapPosition( 7, 0, -3), new MapPosition( 7, 0, 3),
new MapPosition(-6, 0, -5), new MapPosition(-6, 0, 5), new MapPosition(-5, 0, -6), new MapPosition(-5, 0, 6), new MapPosition( 5, 0, -6),
new MapPosition( 5, 0, 6), new MapPosition( 6, 0, -5), new MapPosition( 6, 0, 5)
};
void Update()
{
if (DeleteChunks()) //Check to see if a delete happened
return; //and if so return early
FindChunksToLoad();
LoadAndRenderChunks();
}
void FindChunksToLoad()
{
//Get the position of this gameobject to generate around
MapPosition playerPos = new MapPosition(
Mathf.FloorToInt(transform.position.x / Chunk.chunkSize) * Chunk.chunkSize,
Mathf.FloorToInt(transform.position.y / Chunk.chunkSize) * Chunk.chunkSize,
Mathf.FloorToInt(transform.position.z / Chunk.chunkSize) * Chunk.chunkSize
);
//If there aren't already chunks to generate
if (updateList.Count == 0)
{
//Cycle through the array of positions
for (int i = 0; i < chunkPositions.Length; i++)
{
//translate the player position and array position into chunk position
MapPosition newChunkPos = new MapPosition(chunkPositions[i].x * Chunk.chunkSize + playerPos.x, 0, chunkPositions[i].z * Chunk.chunkSize + playerPos.z);
//Get the chunk in the defined position
Chunk newChunk = world.GetChunk(newChunkPos.x, newChunkPos.y, newChunkPos.z);
//If the chunk already exists and it's already
//rendered or in queue to be rendered continue
if (newChunk != null && (newChunk.rendered || updateList.Contains(newChunkPos)))
continue;
//-4 - 4
//load a column of chunks in this position
for (int y = 0; y < 2; y++)
{
for (int x = newChunkPos.x - Chunk.chunkSize; x <= newChunkPos.x + Chunk.chunkSize; x += Chunk.chunkSize)
{
for (int z = newChunkPos.z - Chunk.chunkSize; z <= newChunkPos.z + Chunk.chunkSize; z += Chunk.chunkSize)
{
buildList.Add(new MapPosition(x, y * Chunk.chunkSize, z));
}
}
updateList.Add(new MapPosition(newChunkPos.x, y * Chunk.chunkSize, newChunkPos.z));
}
return;
}
}
}
void BuildChunk(MapPosition pos)
{
if (world.GetChunk(pos.x, pos.y, pos.z) == null)
world.CreateChunk(pos.x, pos.y, pos.z);
}
void LoadAndRenderChunks()
{
if (buildList.Count != 0)
{
for (int i = 0; i < buildList.Count && i < 16; i++)
{
BuildChunk(buildList[0]);
buildList.RemoveAt(0);
}
//If chunks were built return early
//return;
}
if (updateList.Count != 0)
{
Chunk chunk = world.GetChunk(updateList[0].x, updateList[0].y, updateList[0].z);
if (chunk != null)
chunk.update = true;
updateList.RemoveAt(0);
}
}
bool DeleteChunks()
{
if (timer == 10)
{
var chunksToDelete = new List<MapPosition>();
foreach (var chunk in world.chunks)
{
float distance = Vector3.Distance(
new Vector3(chunk.Value.pos.x, 0, chunk.Value.pos.z),
new Vector3(transform.position.x, 0, transform.position.z));
if (distance > 256)
chunksToDelete.Add(chunk.Key);
}
foreach (var chunk in chunksToDelete)
world.DestroyChunk(chunk.x, chunk.y, chunk.z);
timer = 0;
return true;
}
timer++;
return false;
}
}
}<file_sep>/Assets/Badlands.UI/UI_Hidden.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class UI_Hidden : MonoBehaviour {
GUIElement panel;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void Toggle()
{
var test = transform.parent.GetComponent<Canvas>().gameObject;
test.SetActive(false);
}
}
<file_sep>/Assets/Badlands.Blocks/BlockTree.cs
using UnityEngine;
using System.Collections;
using System;
using Badlands.World;
namespace Badlands.Blocks
{
[Serializable]
public class BlockTree : Block
{
private float treeOffset;
private float treeHeight;
public BlockTree()
: base()
{
blockSize = base.blockSize / 6;
treeOffset = UnityEngine.Random.Range(0.15f, 0.4f);
treeHeight = UnityEngine.Random.Range(8.0f, 16.0f);
}
public override bool IsSolid(Direction direction)
{
return false;
}
protected override MeshData FaceDataUp
(Chunk chunk, int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddQuadTriangles();
return meshData;
}
protected override MeshData FaceDataWest
(Chunk chunk, int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddQuadTriangles();
return meshData;
}
protected override MeshData FaceDataEast
(Chunk chunk, int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddQuadTriangles();
return meshData;
}
protected override MeshData FaceDataNorth
(Chunk chunk, int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddQuadTriangles();
return meshData;
}
protected override MeshData FaceDataSouth
(Chunk chunk, int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y + (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y + (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y + (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddQuadTriangles();
return meshData;
}
protected override MeshData FaceDataDown
(Chunk chunk, int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), (z - treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), (z - treeOffset) + blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), z - blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) + blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddVertex(new Vector3((x - treeOffset) - blockSize, y - (blockSize * treeHeight), z + blockSize));
meshData.AddQuadTriangles();
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), (z + treeOffset) - blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) + blockSize, y - (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddVertex(new Vector3((x + treeOffset) - blockSize, y - (blockSize * treeHeight), (z + treeOffset) + blockSize));
meshData.AddQuadTriangles();
return meshData;
}
public override MeshData Blockdata(Chunk chunk, int x, int y, int z, MeshData meshData)
{
this.chunk = chunk;
meshData.useRenderDataForCol = true;
//DOWN
meshData = FaceDataUp(chunk, x, y, z, meshData);
meshData.uv.AddRange(FaceUVs(Direction.down));
meshData.uv.AddRange(FaceUVs(Direction.down));
meshData.uv.AddRange(FaceUVs(Direction.down));
meshData.uv.AddRange(FaceUVs(Direction.down));
//UP
meshData = FaceDataDown(chunk, x, y, z, meshData);
meshData.uv.AddRange(FaceUVs(Direction.up));
meshData.uv.AddRange(FaceUVs(Direction.up));
meshData.uv.AddRange(FaceUVs(Direction.up));
meshData.uv.AddRange(FaceUVs(Direction.up));
//SOUTH
meshData = FaceDataNorth(chunk, x, y, z, meshData);
meshData.uv.AddRange(FaceUVs(Direction.south));
meshData.uv.AddRange(FaceUVs(Direction.south));
meshData.uv.AddRange(FaceUVs(Direction.south));
meshData.uv.AddRange(FaceUVs(Direction.south));
//NORTH
meshData = FaceDataSouth(chunk, x, y, z, meshData);
meshData.uv.AddRange(FaceUVs(Direction.north));
meshData.uv.AddRange(FaceUVs(Direction.north));
meshData.uv.AddRange(FaceUVs(Direction.north));
meshData.uv.AddRange(FaceUVs(Direction.north));
//WEST
meshData = FaceDataEast(chunk, x, y, z, meshData);
meshData.uv.AddRange(FaceUVs(Direction.west));
meshData.uv.AddRange(FaceUVs(Direction.west));
meshData.uv.AddRange(FaceUVs(Direction.west));
meshData.uv.AddRange(FaceUVs(Direction.west));
//EAST
meshData = FaceDataWest(chunk, x, y, z, meshData);
meshData.uv.AddRange(FaceUVs(Direction.east));
meshData.uv.AddRange(FaceUVs(Direction.east));
meshData.uv.AddRange(FaceUVs(Direction.east));
meshData.uv.AddRange(FaceUVs(Direction.east));
return meshData;
}
}
}<file_sep>/Assets/Badlands.Blocks/BlockHighlight.cs
using UnityEngine;
using System.Collections;
using System;
using Badlands.World;
namespace Badlands.Blocks
{
[Serializable]
public class BlockHighlight : Block
{
public BlockHighlight()
: base()
{
}
public override bool IsSolid(Direction direction)
{
return false;
}
public override Tile TexturePosition(Direction direction)
{
Tile tile = new Tile();
switch (direction)
{
case Direction.down:
tile.x = 3;
tile.y = 3;
return tile;
}
tile.x = 0;
tile.y = 0;
return tile;
}
public override MeshData Blockdata(Chunk chunk, int x, int y, int z, MeshData meshData)
{
this.chunk = chunk;
meshData.useRenderDataForCol = true;
if (chunk.GetBlock(x, y - 1, z).IsSolid(Direction.up))
{
meshData = FaceDataDown(chunk, x, y, z, meshData);
meshData.uv.AddRange(FaceUVs(Direction.down));
}
return meshData;
}
protected override MeshData FaceDataDown
(Chunk chunk, int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3(x + blockSize, y - blockSize, z - blockSize));
meshData.AddVertex(new Vector3(x - blockSize, y - blockSize, z - blockSize));
meshData.AddVertex(new Vector3(x - blockSize, y - blockSize, z + blockSize));
meshData.AddVertex(new Vector3(x + blockSize, y - blockSize, z + blockSize));
meshData.AddQuadTriangles();
return meshData;
}
}
}<file_sep>/Assets/Badlands.World/Chunk.cs
using UnityEngine;
using Badlands.Blocks;
namespace Badlands.World {
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshCollider))]
public class Chunk : MonoBehaviour
{
public Map world;
public MapPosition pos;
public static int chunkSize = 16;
public bool update = false;
public bool rendered;
public Block[,,] blocks = new Block[chunkSize, chunkSize, chunkSize];
MeshFilter filter;
MeshCollider coll;
// Use this for initialization
void Start()
{
filter = gameObject.GetComponent<MeshFilter>();
coll = gameObject.GetComponent<MeshCollider>();
}
//Update is called once per frame
void Update()
{
if (update)
{
update = false;
UpdateChunk();
}
}
public void SetBlocksUnmodified()
{
foreach (Block block in blocks)
{
block.changed = false;
}
}
public Block GetBlock(int x, int y, int z)
{
if (InRange(x) && InRange(y) && InRange(z))
return blocks[x, y, z];
return world.GetBlock(pos.x + x, pos.y + y, pos.z + z);
}
public void SetBlock(int x, int y, int z, Block block)
{
if (InRange(x) && InRange(y) && InRange(z))
{
blocks[x, y, z] = block;
}
else
{
world.SetBlock(pos.x + x, pos.y + y, pos.z + z, block);
}
}
public static bool InRange(int index)
{
if (index < 0 || index >= chunkSize)
return false;
return true;
}
void UpdateChunk()
{
rendered = true;
MeshData meshData = new MeshData();
for (int x = 0; x < chunkSize; x++)
{
for (int y = 0; y < chunkSize; y++)
{
for (int z = 0; z < chunkSize; z++)
{
meshData = blocks[x, y, z].Blockdata(this, x, y, z, meshData);
}
}
}
RenderMesh(meshData);
}
// Sends the calculated mesh information
// to the mesh and collision components
void RenderMesh(MeshData meshData)
{
filter.mesh.Clear();
filter.mesh.vertices = meshData.vertices.ToArray();
filter.mesh.triangles = meshData.triangles.ToArray();
filter.mesh.uv = meshData.uv.ToArray();
filter.mesh.RecalculateNormals();
coll.sharedMesh = null;
Mesh mesh = new Mesh();
mesh.vertices = meshData.colVertices.ToArray();
mesh.triangles = meshData.colTriangles.ToArray();
mesh.RecalculateNormals();
coll.sharedMesh = mesh;
}
//RaycastHit hit;
//RaycastHit previousHit;
//Vector3 previousPosition;
//Block previousBlock;
//void OnMouseOver()
//{
// if (Input.mousePosition != previousPosition)
// {
// if (GetComponent<Collider>().Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 1000))
// {
// if (previousBlock != null && previousHit.collider != null && !hit.Equals(previousHit))
// {
// EditTerrain.SetBlock(previousHit, previousBlock);
// }
// if (hit.collider != null && !hit.Equals(previousHit))
// {
// previousBlock = EditTerrain.GetBlock(hit);
// EditTerrain.SetBlock(hit, new BlockHighlight());
// }
// previousHit = hit;
// }
// previousPosition = Input.mousePosition;
// }
//}
}
}<file_sep>/Assets/Badlands.Blocks/BlockTreeRed.cs
namespace Badlands.Blocks
{
public class BlockTreeRed : BlockTree
{
public BlockTreeRed()
: base()
{
}
public override Tile TexturePosition(Direction direction)
{
Tile tile = new Tile();
switch (direction)
{
case Direction.down:
tile.x = 0;
tile.y = 2;
return tile;
}
tile.x = 1;
tile.y = 2;
return tile;
}
}
}
<file_sep>/Assets/Badlands.UI/UpdateUpkeepFromPlayer.cs
using UnityEngine;
using UnityEngine.UI;
using Badlands.Player;
using System;
namespace Badlands.UI
{
public class UpdateUpkeepFromPlayer : MonoBehaviour
{
public GameObject Player;
private Text _upkeep;
private HumanController _controller;
// Use this for initialization
void Start()
{
this.enabled = true;
this._upkeep = this.GetComponent<Text>();
this._controller = this.Player.GetComponent<HumanController>();
}
// Update is called once per frame
void Update()
{
this._upkeep.text = Convert.ToString(_controller._upkeep) + " / " + Convert.ToString(_controller._maxupkeep);
}
}
}
<file_sep>/Assets/Badlands.World/MapPosition.cs
using System;
namespace Badlands.World
{
[Serializable]
public struct MapPosition
{
public int x, y, z;
public MapPosition(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
//Add this function:
public override bool Equals(object obj)
{
return GetHashCode() == obj.GetHashCode();
}
public override int GetHashCode()
{
unchecked
{
int hash = 47;
hash = hash * 227 + x.GetHashCode();
hash = hash * 227 + y.GetHashCode();
hash = hash * 227 + z.GetHashCode();
return hash;
}
}
}
}<file_sep>/Assets/Badlands.Blocks/BlockRoad.cs
using UnityEngine;
using System.Collections;
using System;
using Badlands.World;
namespace Badlands.Blocks
{
[Serializable]
public class BlockRoad : Block
{
public BlockRoad()
: base()
{
}
//Road orientation based on neighbours
// [0 1 2]
// [7 3]
// [6 5 4]
//TODO: ORIENTATION
//http://gamedev.stackexchange.com/questions/29524/choose-tile-based-on-adjacent-tiles
//http://www.angryfishstudios.com/2011/04/adventures-in-bitmasking/
private bool[] orientation = new bool[8] { false, false, false, false, false, false, false, false };
public override bool IsRoad()
{
return true;
}
public override bool IsSolid(Direction direction)
{
return false;
}
public override Tile TexturePosition(Direction direction)
{
Tile tile = new Tile();
switch (direction)
{
case Direction.down:
tile.x = 0;
tile.y = 5;
return tile;
}
tile.x = 0;
tile.y = 0;
return tile;
}
public void UpdateOrientation(Chunk chunk, MapPosition pos)
{
Block westBlock = chunk.world.GetBlock(pos.x - 1, pos.y + 1, pos.z);
Block eastBlock = chunk.world.GetBlock(pos.x + 1, pos.y + 1, pos.z);
Block northBlock = chunk.world.GetBlock(pos.x, pos.y + 1, pos.z + 1);
Block southBlock = chunk.world.GetBlock(pos.x, pos.y + 1, pos.z - 1);
this.orientation[1] = northBlock.IsRoad() || northBlock is BlockHighlight;
this.orientation[3] = eastBlock.IsRoad() || eastBlock is BlockHighlight;
this.orientation[5] = southBlock.IsRoad() || southBlock is BlockHighlight;
this.orientation[7] = westBlock.IsRoad() || westBlock is BlockHighlight;
}
public override MeshData Blockdata(Chunk chunk, int x, int y, int z, MeshData meshData)
{
this.chunk = chunk;
meshData.useRenderDataForCol = true;
if (chunk.GetBlock(x, y - 1, z).IsSolid(Direction.up))
{
meshData = FaceDataDown(chunk, x, y, z, meshData);
meshData.uv.AddRange(FaceUVs(Direction.down));
}
return meshData;
}
protected override MeshData FaceDataDown
(Chunk chunk, int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3(x + blockSize, y - blockSize, z - blockSize));
meshData.AddVertex(new Vector3(x - blockSize, y - blockSize, z - blockSize));
meshData.AddVertex(new Vector3(x - blockSize, y - blockSize, z + blockSize));
meshData.AddVertex(new Vector3(x + blockSize, y - blockSize, z + blockSize));
meshData.AddQuadTriangles();
return meshData;
}
}
}
|
679c820c7379d2bbe300b50681988f2411c1e4e6
|
[
"C#"
] | 19 |
C#
|
sivertsenstian/UNITYBadlands
|
d2a1efcb73714913547803ef8de13102f71cf22a
|
fee843d1c5b0d312bda5598920bcdac1c3d35867
|
refs/heads/master
|
<file_sep>#include "wheel.h"
GLuint wheelIndices[] = {
0, 1, 2,
0, 2, 3,
};
GLfloat wheelVertices[] = {
// coordinates // color // texture
0.2f, 0.2f, -0.799, 1.0f, 0.0f,
-0.2f, 0.2f, -0.799f, 1.0f, 1.0f,
-0.2f, -0.2f, -0.799f, 0.0f, 1.0f,
0.2f, -0.2f, -0.799f, 0.0f, 0.0f,
};
GLfloat wheelRotAngle = 0;
void createWheel(GLuint & VBO, GLuint & EBO, GLuint & VAO)
{
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(wheelVertices), wheelVertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(wheelIndices), wheelIndices, GL_STATIC_DRAW);
// vertex geometry data
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
// vertex texture coordinates
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind
glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)
// Set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT (usually basic wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// prepare textures
wheelTexture = LoadMipmapTexture(GL_TEXTURE0, "wheel.png");
}
void updateWheel(ShaderProgram theProgram, GLuint & VAO, GLuint & EBO)
{
theProgram.Use();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, wheelTexture);
glUniform1i(glGetUniformLocation(theProgram.get_programID(), "wheelTexture"), 0);
glm::mat4 trans;
trans = glm::rotate(trans, -(float)glm::radians(wheelRotAngle), glm::vec3(0.0, 0.0, 1.0));
if (wheelRotAngle >= 500)
wheelRotAngle = 500;
if (wheelRotAngle <= -500)
wheelRotAngle = -500;
GLuint transformLoc = glGetUniformLocation(theProgram.get_programID(), "transform");
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(trans));
GLint projectionLoc = glGetUniformLocation(theProgram.get_programID(), "projection");
glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection));
GLint viewLoc = glGetUniformLocation(theProgram.get_programID(), "view");
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
GLint brightLoc = glGetUniformLocation(theProgram.get_programID(), "brightness");
glUniform1f(brightLoc, brightness);
// Draw our first triangl
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, _countof(wheelIndices), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}<file_sep>#include "water.h"
GLfloat waterVertices[] = {
// coordinates
3.0f, -0.4f, 3.0f,
-3.0f, -0.4f, 3.0f,
3.0f, -0.4f, -3.0f,
-3.0f, -0.4f, -3.0f,
};
GLuint waterIndices[] = {
0, 1, 2,
3, 1, 2,
};
void createWater(GLuint & VBO, GLuint & EBO, GLuint & VAO)
{
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(waterVertices), waterVertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(waterIndices), waterIndices, GL_STATIC_DRAW);
// vertex geometry data
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind
glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)
}
void updateWater(ShaderProgram theProgram, GLuint & VAO, GLuint & EBO)
{
theProgram.Use();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glm::mat4 trans;
trans = glm::rotate(trans, -(float)glm::radians(0.0f), glm::vec3(0.0, 1.0, 0.0));
GLuint transformLoc = glGetUniformLocation(theProgram.get_programID(), "transform");
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(trans));
GLint projectionLoc = glGetUniformLocation(theProgram.get_programID(), "projection");
glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection));
GLint viewLoc = glGetUniformLocation(theProgram.get_programID(), "view");
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
GLint brightLoc = glGetUniformLocation(theProgram.get_programID(), "brightness");
glUniform1f(brightLoc, brightness);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, _countof(waterIndices), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}<file_sep>#include "skybox.h"
GLfloat skyboxVertices[] = {
// Positions
-3.0f, 3.0f, -3.0f,
-3.0f, -3.0f, -3.0f,
3.0f, -3.0f, -3.0f,
3.0f, -3.0f, -3.0f,
3.0f, 3.0f, -3.0f,
-3.0f, 3.0f, -3.0f,
-3.0f, -3.0f, 3.0f,
-3.0f, -3.0f, -3.0f,
-3.0f, 3.0f, -3.0f,
-3.0f, 3.0f, -3.0f,
-3.0f, 3.0f, 3.0f,
-3.0f, -3.0f, 3.0f,
3.0f, -3.0f, -3.0f,
3.0f, -3.0f, 3.0f,
3.0f, 3.0f, 3.0f,
3.0f, 3.0f, 3.0f,
3.0f, 3.0f, -3.0f,
3.0f, -3.0f, -3.0f,
-3.0f, -3.0f, 3.0f,
-3.0f, 3.0f, 3.0f,
3.0f, 3.0f, 3.0f,
3.0f, 3.0f, 3.0f,
3.0f, -3.0f, 3.0f,
-3.0f, -3.0f, 3.0f,
-3.0f, 3.0f, -3.0f,
3.0f, 3.0f, -3.0f,
3.0f, 3.0f, 3.0f,
3.0f, 3.0f, 3.0f,
-3.0f, 3.0f, 3.0f,
-3.0f, 3.0f, -3.0f,
-3.0f, -3.0f, -3.0f,
-3.0f, -3.0f, 3.0f,
3.0f, -3.0f, -3.0f,
3.0f, -3.0f, -3.0f,
-3.0f, -3.0f, 3.0f,
3.0f, -3.0f, 3.0f
};
GLuint skyboxIndices[] = {
0, 2, 3,
0, 1, 2,
};
GLuint loadCubemap(vector<const GLchar*> faces)
{
GLuint textureID;
glGenTextures(1, &textureID);
glActiveTexture(GL_TEXTURE0);
int width, height;
unsigned char* image;
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
for (GLuint i = 0; i < faces.size(); i++)
{
image = SOIL_load_image(faces[i], &width, &height, 0, SOIL_LOAD_RGB);
glTexImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0,
GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image
);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
return textureID;
}
void createSkybox(GLuint & VBO, GLuint & EBO, GLuint & VAO)
{
// Setup skybox VAO
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glBindVertexArray(0);
#pragma endregion
// Cubemap (Skybox)
vector<const GLchar*> faces;
faces.push_back("right.png");
faces.push_back("left.png");
faces.push_back("top.png");
faces.push_back("bottom.png");
faces.push_back("back.png");
faces.push_back("front.png");
skyboxTexture = loadCubemap(faces);
}
void updateSkybox(ShaderProgram theProgram, GLuint & VAO, GLuint & EBO)
{
glDepthMask(GL_FALSE);// Remember to turn depth writing off
theProgram.Use();
GLint projectionLoc = glGetUniformLocation(theProgram.get_programID(), "projection");
glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection));
GLint viewLoc = glGetUniformLocation(theProgram.get_programID(), "view");
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
GLint brightLoc = glGetUniformLocation(theProgram.get_programID(), "brightness");
glUniform1f(brightLoc, brightness);
// skybox cube
glBindVertexArray(VAO);
glActiveTexture(GL_TEXTURE0);
glUniform1i(glGetUniformLocation(theProgram.get_programID(), "skybox"), 0);
glBindTexture(GL_TEXTURE_CUBE_MAP, skyboxTexture);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glDepthMask(GL_TRUE);
}<file_sep>#include "rudder.h"
GLfloat rudderVertices[] = {
// coordinates // texture
0.0f, -0.3f, 0.0f, 0.0f, 0.0f,
0.0f, -0.3f, 0.2f, 1.0f, 0.0f,
0.0f, -0.9f, 0.0f, 0.0f, 1.0f,
0.0f, -0.9f, 0.2f, 1.0f, 1.0f,
};
GLuint rudderIndices[] = {
0, 1, 3,
0, 2, 3,
};
GLfloat rudderRotAngle;
void createRudder(GLuint & VBO, GLuint & EBO, GLuint & VAO)
{
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(rudderVertices), rudderVertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(rudderIndices), rudderIndices, GL_STATIC_DRAW);
// vertex geometry data
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
// vertex texture coordinates
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind
glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)
// Set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT (usually basic wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// prepare textures
rudderTexture = LoadMipmapTexture(GL_TEXTURE0, "metal.png");
rudderRotAngle = 0;
}
void updateRudder(ShaderProgram theProgram, GLuint & VAO, GLuint & EBO)
{
theProgram.Use();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, rudderTexture);
glUniform1i(glGetUniformLocation(theProgram.get_programID(), "rudderTexture"), 0);
glm::mat4 trans;
trans = glm::rotate(trans, -(float)glm::radians(rudderRotAngle), glm::vec3(0.0, 1.0, 0.0));
if (rudderRotAngle >= 60)
rudderRotAngle = 60;
if (rudderRotAngle <= -60)
rudderRotAngle = -60;
GLuint transformLoc = glGetUniformLocation(theProgram.get_programID(), "transform");
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(trans));
GLint projectionLoc = glGetUniformLocation(theProgram.get_programID(), "projection");
glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection));
GLint viewLoc = glGetUniformLocation(theProgram.get_programID(), "view");
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
GLint brightLoc = glGetUniformLocation(theProgram.get_programID(), "brightness");
glUniform1f(brightLoc, brightness);
// Draw our first triangl
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, _countof(rudderIndices), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}<file_sep>#ifndef wheel_h
#define wheel_h
#include "shprogram.h"
extern glm::mat4 projection;
extern glm::mat4 view;
extern GLfloat brightness;
static GLuint wheelTexture;
void createWheel(GLuint & VBO, GLuint & EBO, GLuint & VAO);
void updateWheel(ShaderProgram theProgram, GLuint & VAO, GLuint & EBO);
#endif
<file_sep>#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <SOIL.h>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "boat.h"
#include "rudder.h"
#include "shprogram.h"
#include "wheel.h"
#include "skybox.h"
#include "water.h"
using namespace std;
const GLuint WIDTH = 1000, HEIGHT = 600;
const float CAMERA_ROTATION = 2.0;
extern GLfloat rudderRotAngle;
extern GLfloat wheelRotAngle;
GLfloat brightness = 1.0;
glm::mat4 projection;
glm::mat4 view;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
if (key == GLFW_KEY_A)
{
wheelRotAngle -= 5.0;
rudderRotAngle += 0.6f;
}
if (key == GLFW_KEY_D)
{
wheelRotAngle += 5.0;
rudderRotAngle -= 0.6f;
}
if (key == GLFW_KEY_LEFT)
{
view = glm::translate(view, glm::vec3(0.0f, -0.0f, -0.5f));
view = glm::rotate(view, glm::radians(CAMERA_ROTATION), glm::vec3(0.0, 1.0, 0.0));
view = glm::translate(view, glm::vec3(0.0f, -0.0f, 0.5f));
}
if (key == GLFW_KEY_RIGHT)
{
view = glm::translate(view, glm::vec3(0.0f, -0.0f, -0.5f));
view = glm::rotate(view, glm::radians(-CAMERA_ROTATION), glm::vec3(0.0, 1.0, 0.0));
view = glm::translate(view, glm::vec3(0.0f, -0.0f, 0.5f));
}
if (key == GLFW_KEY_UP)
{
brightness += 0.01;
}
if (key == GLFW_KEY_DOWN)
{
brightness -= 0.01;
}
}
ostream& operator<<(ostream& os, const glm::mat4& mx)
{
for (int row = 0; row < 4; ++row)
{
for (int col = 0; col < 4; ++col)
cout << mx[row][col] << ' ';
cout << endl;
}
return os;
}
int main()
{
projection = glm::perspective(45.0f, (float)WIDTH / (float)HEIGHT, 0.4f, 100.0f);
view = glm::translate(view, glm::vec3(0.0f, -0.0f, -1.5f));
view = glm::rotate(view, glm::radians((float)20.0), glm::vec3(1.0, 0.1, 0.0));
if (glfwInit() != GL_TRUE)
{
cout << "GLFW initialization failed" << endl;
return -1;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
try
{
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "GKOM - OpenGL 05", nullptr, nullptr);
if (window == nullptr)
throw exception("GLFW window not created");
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
throw exception("GLEW Initialization failed");
glViewport(0, 0, WIDTH, HEIGHT);
// Let's check what are maximum parameters counts
GLint nrAttributes;
glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &nrAttributes);
cout << "Max vertex attributes allowed: " << nrAttributes << std::endl;
glGetIntegerv(GL_MAX_TEXTURE_COORDS, &nrAttributes);
cout << "Max texture coords allowed: " << nrAttributes << std::endl;
ShaderProgram theProgram("boat.vert", "boat.frag");
ShaderProgram theProgram2("texture.vert", "texture.frag");
ShaderProgram theProgram3("skybox.vert", "skybox.frag");
ShaderProgram theProgram4("water.vert", "water.frag");
GLuint VBO, EBO, VAO;
createBoat(VBO, EBO, VAO);
GLuint VBO2, EBO2, VAO2;
createRudder(VBO2, EBO2, VAO2);
GLuint VBO3, EBO3, VAO3;
createWheel(VBO3, EBO3, VAO3);
GLuint VBO4, EBO4, VAO4;
createSkybox(VBO4, EBO4, VAO4);
GLuint VBO5, EBO5, VAO5;
createWater(VBO5, EBO5, VAO5);
// main event loop
while (!glfwWindowShouldClose(window))
{
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents();
// Clear the colorbuffer
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
updateSkybox(theProgram3, VAO4, EBO4);
updateBoat(theProgram, VAO, EBO);
updateRudder(theProgram2, VAO2, EBO2);
updateWater(theProgram4, VAO5, EBO5);
updateWheel(theProgram2, VAO3, EBO3);
if (brightness >= 1.25) brightness = 1.25;
if (brightness <= 0.5) brightness = 0.5;
// Swap the screen buffers
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
}
catch (exception ex)
{
cout << ex.what() << endl;
}
glfwTerminate();
return 0;
}
<file_sep>#ifndef rudder_h
#define rudder_h
#include <iostream>
#include "shprogram.h"
extern glm::mat4 projection;
extern glm::mat4 view;
extern GLfloat brightness;
static GLuint rudderTexture;
void createRudder(GLuint & VBO, GLuint & EBO, GLuint & VAO);
void updateRudder(ShaderProgram theProgram, GLuint & VAO, GLuint & EBO);
#endif<file_sep>#include "boat.h"
GLfloat boatVertices[] = {
// coordinates // normals
0.4f, -0.2f, -1.0f, 0.0f, 1.0f, 1.0f,
-0.4f, -0.2f, -1.0f, 1.0f, 1.0f, 0.0f,
0.0f, -0.7f, -1.0f, 1.0f, 0.0f, 1.0f,
0.0f, -0.2f, -1.5f, 1.0f, 1.0f, 1.0f,
0.4f, -0.2f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.4f, -0.2f, 0.0f, 0.0f, 0.0f, 1.0f,
0.0f, -0.7f, 0.0f, 0.0f, 1.0f, 1.0f,
//prost. przód
0.1f, -0.2f, -0.9f, 0.0f, 0.0f, -1.0f,
-0.1f, -0.2f, -0.9f, 0.0f, 0.0f, -1.0f,
-0.1f, 0.1f, -0.9f, 0.0f, 0.0f, -1.0f,
0.1f, 0.1f, -0.9f, 0.0f, 0.0f, -1.0f,
//prost. tył
0.1f, -0.2f, -0.8f, 0.0f, 0.0f, 1.0f,
-0.1f, -0.2f, -0.8f, 0.0f, 0.0f, 1.0f,
-0.1f, 0.1f, -0.8f, 0.0f, 0.0f, 1.0f,
0.1f, 0.1f, -0.8f, 0.0f, 0.0f, 1.0f,
//rufa
0.4f, -0.2f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.4f, -0.2f, 0.0f, 0.0f, 0.0f, 1.0f,
0.0f, -0.7f, 0.0f, 0.0f, 0.0f, 1.0f,
//pokład
0.4f, -0.2f, -1.0f, 0.0f, 1.0f, 0.0f,
-0.4f, -0.2f, -1.0f, 0.0f, 1.0f, 0.0f,
0.0f, -0.2f, -1.5f, 0.0f, 1.0f, 0.0f,
0.4f, -0.2f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.4f, -0.2f, 0.0f, 0.0f, 1.0f, 0.0f,
//prost. prawo
0.1f, -0.2f, -0.9f, 1.0f, 0.0f, 0.0f,
0.1f, 0.1f, -0.9f, 1.0f, 0.0f, 0.0f,
0.1f, -0.2f, -0.8f, 1.0f, 0.0f, 0.0f,
0.1f, 0.1f, -0.8f, 1.0f, 0.0f, 0.0f,
//prost. lewo
-0.1f, -0.2f, -0.9f, 1.0f, 0.0f, 0.0f,
-0.1f, 0.1f, -0.9f, 1.0f, 0.0f, 0.0f,
-0.1f, -0.2f, -0.8f, 1.0f, 0.0f, 0.0f,
-0.1f, 0.1f, -0.8f, 1.0f, 0.0f, 0.0f,
//prost. góra
-0.1f, 0.1f, -0.8f, 0.0f, 1.0f, 0.0f,
0.1f, 0.1f, -0.8f, 0.0f, 1.0f, 0.0f,
-0.1f, 0.1f, -0.9f, 0.0f, 1.0f, 0.0f,
0.1f, 0.1f, -0.9f, 0.0f, 1.0f, 0.0f,
//dziub prawy
0.4f, -0.2f, -1.0f, 1.0f, -1.0f, -1.0f,
0.0f, -0.7f, -1.0f, 1.0f, -1.0f, -1.0f,
0.0f, -0.2f, -1.5f, 1.0f, -1.0f, -1.0f,
//dziub lewy
-0.4f, -0.2f, -1.0f, -1.0f, -1.0f, -1.0f,
0.0f, -0.7f, -1.0f, -1.0f, -1.0f, -1.0f,
0.0f, -0.2f, -1.5f, -1.0f, -1.0f, -1.0f,
//prawa burta
0.4f, -0.2f, -1.0f, 1.0f, -1.0f, 0.0f,
0.4f, -0.2f, 0.0f, 1.0f, -1.0f, 0.0f,
0.0f, -0.7f, 0.0f, 1.0f, -1.0f, 0.0f,
0.0f, -0.7f, -1.0f, 1.0f, -1.0f, 0.0f,
//lewa burta
-0.4f, -0.2f, -1.0f, -1.0f, -1.0f, 0.0f,
-0.4f, -0.2f, 0.0f, -1.0f, -1.0f, 0.0f,
-0.0f, -0.7f, 0.0f, -1.0f, -1.0f, 0.0f,
-0.0f, -0.7f, -1.0f, -1.0f, -1.0f, 0.0f,
};
GLuint boatIndices[] = {
7, 8, 9,
7, 10, 9,
11, 12, 13,
11, 14, 13,
15, 16, 17,
18, 21, 22,
18, 19, 22,
18, 19, 20,
23, 24, 25,
26, 25, 24,
27, 28, 29,
30, 29, 28,
31, 32, 33,
32, 34, 33,
35, 37, 36,
38, 40, 39,
41, 42, 43,
41, 44, 43,
45, 46, 47,
45, 48, 47,
};
void createBoat(GLuint & VBO, GLuint & EBO, GLuint & VAO)
{
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(boatVertices), boatVertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(boatIndices), boatIndices, GL_STATIC_DRAW);
// vertex geometry data
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
// vertex color data
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind
glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)
}
void updateBoat(ShaderProgram theProgram, GLuint & VAO, GLuint & EBO)
{
theProgram.Use();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glm::mat4 trans;
trans = glm::rotate(trans, -glm::radians(0.0f), glm::vec3(0.0, 1.0, 0.0));
GLuint transformLoc = glGetUniformLocation(theProgram.get_programID(), "transform");
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(trans));
GLint projectionLoc = glGetUniformLocation(theProgram.get_programID(), "projection");
glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection));
GLint viewLoc = glGetUniformLocation(theProgram.get_programID(), "view");
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glm::vec3 lightPos = glm::vec3(1.5f, 1.0f, 1.5f);
GLint lightLoc = glGetUniformLocation(theProgram.get_programID(), "lightPos");
glUniform3fv(lightLoc, 1, glm::value_ptr(lightPos));
GLint brightLoc = glGetUniformLocation(theProgram.get_programID(), "brightness");
glUniform1f(brightLoc, brightness);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, _countof(boatIndices), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
<file_sep>#ifndef skybox_h
#define skybox_h
#include <vector>
#include "shprogram.h"
using namespace std;
extern glm::mat4 projection;
extern glm::mat4 view;
extern GLfloat brightness;
static GLuint skyboxTexture;
void createSkybox(GLuint & VBO, GLuint & EBO, GLuint & VAO);
void updateSkybox(ShaderProgram theProgram, GLuint & VAO, GLuint & EBO);
#endif
<file_sep>#ifndef water_h
#define water_h
#include <iostream>
#include "shprogram.h"
extern glm::mat4 projection;
extern glm::mat4 view;
extern GLfloat brightness;
void createWater(GLuint & VBO, GLuint & EBO, GLuint & VAO);
void updateWater(ShaderProgram theProgram, GLuint & VAO, GLuint & EBO);
#endif<file_sep>#ifndef boat_h
#define boat_h
#include "shprogram.h"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <SOIL.h>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
extern glm::mat4 projection;
extern glm::mat4 view;
extern GLfloat brightness;
void createBoat(GLuint & VBO, GLuint & EBO, GLuint & VAO);
void updateBoat(ShaderProgram theProgram, GLuint & VAO, GLuint & EBO);
#endif<file_sep>#pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <SOIL.h>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
class ShaderProgram
{
GLuint program_id; // The program ID
public:
// Constructor reads and builds the shader
ShaderProgram(const GLchar* vertexPath, const GLchar* fragmentPath);
// Use the program
void Use() const
{
glUseProgram(get_programID());
}
// returns program ID
GLuint get_programID() const
{
return program_id;
}
};
GLuint LoadMipmapTexture(GLuint texId, const char* fname);
|
6b36e156e6d50df8bd34d7d951b89a07798e4de3
|
[
"C",
"C++"
] | 12 |
C++
|
Spinaker1/GKOM_BoatSimulator
|
3030fffd9fbc1a754d83c87004243463dfd52e5e
|
3f743c084b81a69b329ba511533ea97bbf651325
|
refs/heads/main
|
<repo_name>OkawaraTakumi/lendorborrowserver<file_sep>/controllers/users.js
const ErrorResponse = require('../utils/errorResponse');
const asyncHandler = require('../middlewares/async');
const mongoose = require('mongoose');
const User = require('../models/User');
const ObjectId = require('mongodb').ObjectId
//ユーザー情報をまとめて取得
exports.getUsers = asyncHandler(async (req, res, next) => {
res.status(200).json(res.advancedResults);
})
//指定したユーザーの情報を取得
exports.getUser = asyncHandler(async (req, res, next) => {
const user = await User.findById(req.body.id);
res.status(200).json({
success:true,
data:{
id:user._id,
name:user.name
}
});
});
//userをフォローして自分のフォローデータを取得
exports.followUser = asyncHandler(async (req, res, next) => {
const { email } = req.body
console.log(email)
const DBId = await User.findOne({email:email}).select("_id, name")
console.log(DBId)
const user = await User.findOneAndUpdate({
_id:req.user.id
},{$addToSet:{follow:DBId}});
const followData = await User.findOne({_id:req.user.id}).select("follow")
res.status(200).json({
success:true,
data: {
followData:followData.follow
}
});
})
//フォローデータを取得
exports.getFollow = asyncHandler(async (req, res, next) => {
const followData = await User.findOne({_id:req.user.id}).select("follow")
console.log(followData,'followData')
const count = followData.follow.length
console.log(followData.follow)
res.status(200).json({
success:true,
followData:followData.follow,
count
});
})
//フォロワーのデータを取得
exports.getFollower = asyncHandler(async (req, res, next) => {
const myId = ObjectId(req.user.id)
const followerData = await User.aggregate([
{
$match:{"_id":{"$ne":myId}}
},
{
$match: {"follow._id":req.user.id}
},
{
$unwind:"$follow"
},
{
$replaceRoot:{
"newRoot":"$follow"
}
}
])
if(!followerData) {
return next (new ErrorResponse('取得に失敗しました', 400))
}
const count = followerData.length
res.status(200).json({
success:true,
followerData,
count
})
})
//ユーザーの作成
exports.createUser = asyncHandler(async (req, res, next) => {
const user =await User.create(req.body);
res.status(201).json({
success:true,
data: user
});
});
//ユーザー情報の更新
exports.updateUser = asyncHandler(async (req, res, next) => {
const user = await User.findByIdAndUpdate(req.body.id, req.body, {
new: true,
runValidators:true
});
res.status(200).json({
success:true,
data: user
});
});
//ユーザーの削除処理
exports.deleteUser = asyncHandler(async (req, res ,next) => {
await User.findByIdAndDelete(req.params.id);
res.status(200).json({
success:true,
data:{}
});
});
<file_sep>/models/negotiateObj.js
// const mongoose = require('mongoose');
// const negotiateObjSchema = new mongoose.Schema({
// negotiateItem:{
// type:String
// },
// negotiateDetail:{
// type:String
// }
// })
// module.exports = mongoose.model('detailObj',detailObjSchema)<file_sep>/server.js
const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
const errorHandler = require("./middlewares/error");
const cookieParser = require("cookie-parser");
const connectDB = require("./config/db");
// ルートの読み込み
const user = require("./routes/users");
const auth = require("./routes/auth");
const LorB = require("./routes/lendOrBorrow");
//コンフィグファイルの読み込み
dotenv.config({ path: "./config/config.env" });
//データベースと繋がる
connectDB();
const app = express();
//CORSの設定
app.use(
cors({
credentials: true,
origin: "https://react-sample-lorb.ml",
methods: ["GET", "POST", "DELETE", "UPDATE", "PUT", "PATCH"],
})
);
app.use(function (req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With"
);
next();
});
//jsonを取得できるようにパースする
app.use(express.json());
//cookieをパースする
app.use(cookieParser());
//routerをマウント
app.use("/user", user);
app.use("/auth", auth);
app.use("/LorB", LorB);
app.use(errorHandler);
const PORT = process.env.PORT || 5000;
const server = app.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);
//サーバーで何らかのエラーがあった場合
process.on("unhandledRejection", (err, promise) => {
console.log(`Error: ${err.message}`);
//エラーがあった場合サーバーを閉じる
server.close(() => process.exit(1));
});
<file_sep>/routes/users.js
const express = require('express');
const router = express.Router({mergeParams:true});
const {
getUser,
updateUser,
deleteUser,
followUser,
getFollow,
getFollower
} = require('../controllers/users');
const { protect } = require('../middlewares/auth');
router.use(protect)
// router.get('/fetchUsers', getUsers) 今のところ必要ない
// router.post('/register', createUser) この機能はauthに移植
router.route('/edit')
.get(getUser)
.put(updateUser)
.delete(deleteUser)
router.post('/followUser', followUser)
router.get('/getFollow', getFollow)
router.get('/getFollower', getFollower)
module.exports = router;
<file_sep>/routes/lendOrBorrow.js
const express = require('express');
const router = express.Router({mergeParams:true});
const {
createLorB,
getLorB,
getAllLorB,
updateLorBDetail,
getLorBIhave,
updateNegotiate,
rejectNegotiate,
deleteLorBtable,
getLorBCompleted,
getOnBeingSuggested,
getLorBKeepLorB,
approveCreate,
rejectCreate,
getOnMaking
} = require("../controllers/lendOrBorrow")
const { protect } = require('../middlewares/auth');
router.use(protect)
//createが呼び出され、すでにLorBが存在していた場合は更新処理
router.post('/createLorB', createLorB, updateLorBDetail)
router.put('/approveCreate', approveCreate)
router.put('/rejectCreate', rejectCreate)
router.get('/getOnMaking', getOnMaking)
router.get('/getOnBeingSuggested', getOnBeingSuggested)
router.get('/getLorB', getLorB)
router.get('/getLorBKeepLorB', getLorBKeepLorB)
router.get('/getAllLorB', getAllLorB)
router.get('/getLorBIhave', getLorBIhave)
router.get('/getLorBCompleted', getLorBCompleted)
router.put('/updateNegotiate', updateNegotiate)
router.put('/rejectNegotiate', rejectNegotiate)
router.put('/deleteLorBtable', deleteLorBtable);
module.exports = router;<file_sep>/models/DetailObj.js
// const mongoose = require('mongoose');
// const detailObjSchema = new mongoose.Schema({
// detailClass:{
// type:String
// },
// aboutDetail:{
// type:String
// }
// })
// module.exports = mongoose.model('detailObj',detailObjSchema)
|
7e19eb07bb4d7f14b9b16f9673602d5356495b55
|
[
"JavaScript"
] | 6 |
JavaScript
|
OkawaraTakumi/lendorborrowserver
|
dd3c62665a98c70b90a03364e378ae916fac7950
|
6b991c65e5950b773ef239fcb468afeb382d011e
|
refs/heads/master
|
<file_sep>#!/bin/bash
#=================================================
# Description: DIY script
# Lisence: MIT
# Author: P3TERX
# Blog: https://p3terx.com
#=================================================
# Modify default IP
#sed -i 's/192.168.1.1/192.168.50.5/g' package/base-files/files/bin/config_generate
# git clone https://github.com/vernesong/OpenClash.git && mv OpenClash/luci-app-openclash openwrt/package/luci-app-openclash
# git clone https://github.com/Mrbai98/luci-theme-atmaterial.git openwrt/package/luci-theme-atmaterial
|
77985f84b0b7862e77d90899f1509b20dc1c3202
|
[
"Shell"
] | 1 |
Shell
|
syfirefox/Actions-OpenWrt
|
7252bac78ff0f57fc9a31547ee30251719e97f39
|
4cbe432cb269cff8cfd04e361af9e8dae4bf082e
|
refs/heads/master
|
<repo_name>Bangula/hotel<file_sep>/fe/src/components/admin/rooms/RoomTypes.js
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import {
makeStyles,
Button,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper,
CircularProgress,
Collapse,
ListItemText,
ListItemIcon,
ListItem,
List
} from "@material-ui/core";
import { getRoomTypes, deleteRoomType } from "@endpoints/rooms";
import "@zendeskgarden/react-pagination/dist/styles.css";
import { ThemeProvider } from "@zendeskgarden/react-theming";
import { Pagination } from "@zendeskgarden/react-pagination";
import Modal from "../Modal";
import Alert from "react-s-alert";
import ExpandLess from "@material-ui/icons/ExpandLess";
import ExpandMore from "@material-ui/icons/ExpandMore";
import EditRoomType from "./EditRoomType";
const useStyles = makeStyles(theme => ({
root: {
backgroundColor: theme.palette.background.paper
}
}));
//DISABLE ON CLICK RIPPLE
function RoomTypes() {
const classes = useStyles();
const [currentPage, setCurrentPage] = useState(1); //for api
const [totalPages, setTotalPages] = useState(1);
const [types, setTypes] = useState([]);
const [openModal, setOpenModal] = React.useState(false);
const [modalType, setModalType] = React.useState(""); //stores data of current type id for modal
const [openList, setOpenList] = React.useState(false);
const [typeForEdit, setTypeForEdit] = React.useState({});
function handleClickOpenModal(id) {
setModalType(id);
setOpenModal(true);
}
function handleCloseModal() {
setOpenModal(false);
}
//Toggle list
function handleClickList() {
setOpenList(!openList);
}
const getAllRoomTypes = async page => {
const { data, error } = await getRoomTypes(page);
if (data) {
console.log("types fetched", data.data);
setTypes(data.data.data);
setTotalPages(data.data.meta.pagination.total_pages);
} else if (error) {
console.log(error.response);
}
};
const deleteSingleRoomType = async typeId => {
const { data, error } = await deleteRoomType(typeId);
if (data) {
Alert.success("Room Type Deleted!");
getAllRoomTypes(currentPage);
handleCloseModal();
} else if (error) {
console.log(error.response);
}
};
//Kada se menja strana paginacije
useEffect(() => {
if (types.length) getAllRoomTypes(currentPage);
}, [currentPage, types]);
//Inicijalno ucitavanje
useEffect(() => {
if (!types.length) getAllRoomTypes(currentPage);
}, [currentPage, types]);
return (
<div className="text-center" style={{ marginTop: "55px" }}>
<Alert />
<Modal
open={openModal}
handleClose={handleCloseModal}
userAction={() => deleteSingleRoomType(modalType)}
modalHeader={"Delete Room Type"}
modalText={"Are you shure you want to delete this room type?"}
/>
{/* //////////////////// Add new room Type //////////////////////////// */}
<List
component="nav"
aria-labelledby="nested-list-subheader"
className="bg-gray-400 py-6"
>
<ListItem button onClick={handleClickList}>
<ListItemIcon>{/* icon */}</ListItemIcon>
<ListItemText primary="Add New Type" />
{openList ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={openList} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
<EditRoomType
type={typeForEdit}
setTypeForEdit={setTypeForEdit}
getAllRoomTypes={() => getAllRoomTypes(currentPage)}
/>
</List>
</Collapse>
</List>
{types.length ? (
<>
<Paper className={classes.root}>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell>Type Name</TableCell>
<TableCell className="cell-xs" align="left">
Beds
</TableCell>
<TableCell className="cell-sm" align="left">
Max <br /> Persons
</TableCell>
<TableCell className="cell-sm" align="left">
Price <br /> Adult
</TableCell>
<TableCell className="cell-sm" align="left">
Price <br /> Child
</TableCell>
<TableCell className="cell-sm" size="small" align="left">
Edit <br /> Type
</TableCell>
<TableCell className="cell-sm" align="left">
Delete <br /> Type
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{types.map(type => (
<TableRow key={type.id}>
<TableCell align="left">{type.name}</TableCell>
<TableCell align="left">{type.bed_count}</TableCell>
<TableCell align="left">{type.max_persons}</TableCell>
<TableCell align="left">{type.price_adult}</TableCell>
<TableCell align="left">{type.price_child}</TableCell>
<TableCell align="left">
{" "}
<Link to="#">
<Button
onClick={() => {
setOpenList(true);
setTypeForEdit(type);
}}
variant="contained"
color="primary"
className={classes.button}
>
Edit
</Button>
</Link>
</TableCell>
<TableCell align="left">
{" "}
<Button
onClick={() => handleClickOpenModal(type.id)}
variant="contained"
color="secondary"
className={classes.button}
>
Delete
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
{totalPages > 1 ? (
<ThemeProvider>
<Pagination
totalPages={totalPages}
currentPage={currentPage}
onChange={currentPage => {
console.log("current page", currentPage);
return setCurrentPage(currentPage);
}}
/>
</ThemeProvider>
) : null}
</>
) : (
<CircularProgress />
)}
</div>
);
}
export default RoomTypes;
<file_sep>/fe/src/components/admin/subscribers/Subscribers.js
import React, { useState, useEffect } from "react";
import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Tabs from "@material-ui/core/Tabs";
import TabContainer from "./components/TabContainer";
import LinkTab from "./components/LinkTab";
import NewCampaign from "./components/NewCampaign";
import {
Button,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper,
CircularProgress
} from "@material-ui/core";
import {
getAllSubscribers,
deleteSubscriber,
subscribeUser
} from "@endpoints/subscribe";
import "@zendeskgarden/react-pagination/dist/styles.css";
import { ThemeProvider } from "@zendeskgarden/react-theming";
import { Pagination } from "@zendeskgarden/react-pagination";
import Modal from "../Modal";
import Alert from "react-s-alert";
const useStyles = makeStyles(theme => ({
root: {
backgroundColor: theme.palette.background.paper,
input: {
marginLeft: 8,
flex: 1
},
root2: {
flexGrow: 1,
backgroundColor: theme.palette.background.paper
},
iconButton: {
padding: 10
},
divider: {
width: 1,
height: 28,
margin: 4
}
}
}));
function Subscribers() {
const [openModal, setOpenModal] = React.useState(false);
const [email, setEmail] = React.useState("");
const [value, setValue] = React.useState(0);
React.useEffect(() => {
document.title = "Quantox Hotel - Admin Panel - Subscribers";
}, []);
function handleChange(event, newValue) {
setValue(newValue);
}
// const handleSubmit = async e => {
// e.preventDefault();
// const { data, error } = await subscribeUser({ email });
// console.log(email);
// if (data) {
// console.log(data);
// Alert.success(<i className="fas fa-check" />, {
// effect: "slide",
// timeout: 2000
// });
// getAllSubscribers(currentPage);
// } else if (error) {
// console.log(error.response);
// }
// };
function handleClickOpenModal(email) {
setEmail(email);
setOpenModal(true);
}
function handleCloseModal() {
setOpenModal(false);
}
const classes = useStyles();
const [currentPage, setCurrentPage] = useState(1); //for api
const [totalPages, setTotalPages] = useState(1);
const [subscribers, setSubscribers] = useState([]);
const [subscribeError, setSubscribeError] = useState("");
const [newEmail, setNewEmail] = useState("");
const getSubscribers = async page => {
const { data, error } = await getAllSubscribers(page);
if (data) {
console.log(" fetched", data.data);
setSubscribers(data.data.data);
setTotalPages(data.data.meta.pagination.total_pages);
} else if (error) {
console.log(error.response);
}
};
const deleteSubscriberById = async email => {
const { data, error } = await deleteSubscriber(email);
if (data) {
handleCloseModal();
getSubscribers(currentPage);
} else if (error) {
console.log(error.response);
}
};
useEffect(() => {
if (subscribers.length) getSubscribers(currentPage);
}, [currentPage, subscribers]);
useEffect(() => {
if (!subscribers.length) getSubscribers(currentPage);
}, [subscribers, currentPage]);
const handleSubscribe = async e => {
e.preventDefault();
const { data, error } = await subscribeUser({ email: newEmail });
console.log(newEmail);
if (data) {
console.log(data.data);
setSubscribeError("");
getSubscribers(currentPage);
Alert.success(<i className="fas fa-check" />, {
effect: "slide",
timeout: 2000,
position: "bottom-right"
});
} else if (error) {
console.log(error.response);
if (error.response.data.message)
setSubscribeError(error.response.data.message);
}
};
return (
<div className={classes.root2} style={{ marginTop: "42px" }}>
<Alert />
<AppBar position="static">
<Tabs variant="fullWidth" value={value} onChange={handleChange}>
<LinkTab label="All subscribers" href="/drafts" />
<LinkTab label="Create new Subscriber" href="/trash" />
<LinkTab label="Create new campaign" href="/spam" />
</Tabs>
</AppBar>
{value === 0 && (
<TabContainer>
<div className="text-center">
<Modal
open={openModal}
handleClose={handleCloseModal}
userAction={() => deleteSubscriberById(email)}
modalHeader={"Remove subscriber"}
modalText={"Are you shure you want to delete this subscriber?"}
/>
{subscribers.length ? (
<>
<Paper className={classes.root}>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell className="cell-xs">Id</TableCell>
<TableCell align="left">Email</TableCell>
<TableCell align="right" />
</TableRow>
</TableHead>
<TableBody>
{subscribers.map(user => (
<TableRow key={user.id}>
<TableCell
component="th"
scope="row"
className="cell-xs"
>
{user.real_id}
</TableCell>
<TableCell
align="left"
style={{
fontWeight: "bold",
fontSize: "1rem",
fontStyle: "italic"
}}
>
{user.email}
</TableCell>
<TableCell align="right">
{" "}
<Button
onClick={() => handleClickOpenModal(user.email)}
variant="contained"
color="secondary"
className={classes.button}
>
REMOVE SUBSCRIBER
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
{totalPages > 1 ? (
<div className="mt-8 mb-16">
<ThemeProvider>
<Pagination
totalPages={totalPages}
currentPage={currentPage}
onChange={currentPage => {
console.log("current page", currentPage);
return setCurrentPage(currentPage);
}}
/>
</ThemeProvider>
</div>
) : null}
</>
) : (
<CircularProgress />
)}
</div>
</TabContainer>
)}
{value === 1 && (
<TabContainer>
<div className="shadow-lg mb-16 border py-8">
<h1 className="text-center text-gray-600 italic">
Create new subscriber
</h1>
<div className="flex justify-center mx-auto mt-8">
<form
onSubmit={handleSubscribe}
style={{ margin: 0, padding: 0 }}
>
<TextField
id="standard-name"
label="Email"
className=""
onChange={e => setNewEmail(e.target.value)}
/>
<Button
variant="contained"
color="primary"
type="submit"
style={{
marginTop: "10px",
marginLeft: "20px"
}}
>
Submit
</Button>
</form>
</div>
<h1 className="text-red-600 italic text-center mt-8">
{subscribeError ? subscribeError : ""}
</h1>
</div>
</TabContainer>
)}
{value === 2 && (
<TabContainer>
<NewCampaign Alert={Alert} />
</TabContainer>
)}
</div>
);
}
export default Subscribers;
<file_sep>/fe/src/components/rooms/Rooms.js
import React, { useState, useEffect } from "react";
import { getAllRooms } from "../../services/http/endpoints/rooms";
import { makeStyles } from "@material-ui/core/styles";
import CircularProgress from "@material-ui/core/CircularProgress";
import Room from "./components/Room";
import { useSelector } from "react-redux";
import "@zendeskgarden/react-pagination/dist/styles.css";
import { ThemeProvider } from "@zendeskgarden/react-theming";
import { Pagination } from "@zendeskgarden/react-pagination";
// Components
const useStyles = makeStyles(theme => ({
progress: {
position: "fixed",
top: "50%",
zIndex: "100",
left: 0,
right: 0,
margin: "0 auto",
transform: "translateY(-50%)"
}
}));
const Rooms = () => {
const [allRooms, setAllRooms] = useState([]);
const [loader, setLoader] = useState(true);
const [currentPage, setCurrentPage] = useState(1); //for api
const [totalPages, setTotalPages] = useState(1);
const classes = useStyles();
const isAuthenticated = useSelector(state => state.user.isAuthenticated);
useEffect(() => {
getData(currentPage);
}, []);
useEffect(() => {
if (allRooms.length) getData(currentPage);
}, [currentPage]);
async function getData(page) {
const { data, error } = await getAllRooms(page);
if (data) {
console.log(data);
setAllRooms(data.data.data);
setLoader(false);
setTotalPages(data.data.meta.pagination.total_pages);
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth"
});
} else if (error) {
console.log(error);
}
}
return (
<>
<div className="header-image" />
<h1 className="home-header text-center text-5xl text-gray-600 z-50">
<i className="fas fa-bed " />
<br />
Rooms
</h1>
{loader ? <CircularProgress className={classes.progress} /> : null}
<div className="container mx-auto lg:flex flex-wrap mt-8 pb-32">
{allRooms.length > 0
? allRooms.map(item => {
return (
<Room data={item} key={item.id} isAuth={isAuthenticated} />
);
})
: null}
{!loader ? (
<div className="w-full flex justify-center mt-16">
<ThemeProvider>
<Pagination
totalPages={totalPages}
currentPage={currentPage}
onChange={currentPage => {
return setCurrentPage(currentPage);
}}
/>
</ThemeProvider>
</div>
) : null}
</div>
{/* <Modal open={modalIsOpen} close={setModalIsOpen}>
<ModalContent close={() => setModalIsOpen(false)} />
</Modal> */}
</>
);
};
export default Rooms;
<file_sep>/fe/src/components/cart/Cart.js
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";
import Moment from "react-moment";
import Button from "@material-ui/core/Button";
import { Link as RouteLink } from "react-router-dom";
import Alert from "react-s-alert";
import { createReservation } from "../../services/http/endpoints/reservations";
import { useSelector, useDispatch } from "react-redux";
import Modal from "../admin/Modal";
const useStyles = makeStyles(theme => ({
root: {
width: "100%",
marginTop: theme.spacing(3),
overflowX: "auto"
},
table: {
minWidth: 650
}
}));
export default function Cart() {
const [modalIsActive, setModalIsActive] = React.useState(false);
const [bookModalIsActive, setBookModalIsActive] = React.useState(false);
const [promotionId, setPromotionId] = React.useState("");
const [roomId, setRoomId] = React.useState("");
const promotions = useSelector(state => state.cart.promotions);
const rooms = useSelector(state => state.cart.rooms);
React.useEffect(() => {
document.title = "Quantox Hotel - Cart";
}, []);
React.useEffect(() => {
window.scrollTo(0, 0);
}, []);
const cartItems = promotions.concat(rooms);
const dispatch = useDispatch();
const classes = useStyles();
if (rooms.length) console.log(rooms);
if (promotions.length) console.log(promotions);
const handleBook = async () => {
if (rooms.length) {
let room = { rooms: rooms };
const { data, error } = await createReservation(room);
if (data) {
console.log(data);
Alert.success("Reservation completed!", {
effect: "slide",
timeout: 2000
});
dispatch({ type: "RESERVATION_COMPLETED" });
} else if (error) {
Alert.error("Error creating reservation!", {
effect: "slide",
timeout: 2000
});
console.log(error.response);
}
}
if (promotions.length) {
let promotion = { promotion: promotions[0] };
const { data, error } = await createReservation(promotion);
if (data) {
console.log(data);
Alert.success("Reservation completed!", {
effect: "slide",
timeout: 2000
});
dispatch({ type: "RESERVATION_COMPLETED" });
} else if (error) {
Alert.error("Error creating reservation!", {
effect: "slide",
timeout: 2000
});
console.log(error.response);
}
}
};
const handleDelete = () => {
if (promotionId.length) {
dispatch({
type: "DELETE_PROMOTION",
payload: promotionId
});
} else if (roomId.length) {
dispatch({
type: "DELETE_ROOM",
payload: roomId
});
}
};
const promotionTable =
promotions.length > 0 ? (
<Paper className={classes.root}>
<h1 className="p-2 italic">Promotions</h1>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell>Room Type</TableCell>
<TableCell align="left">From Date</TableCell>
<TableCell align="left">To Date</TableCell>
<TableCell align="right">Remove From Cart</TableCell>
</TableRow>
</TableHead>
<TableBody>
{promotions
? promotions.map((item, index) => (
<TableRow key={index}>
<TableCell align="left">Room type</TableCell>
<TableCell align="left">
<Moment format="YYYY/MM/DD">{item.started_at}</Moment>
</TableCell>
<TableCell align="left">
<Moment format="YYYY/MM/DD">{item.ended_at}</Moment>
</TableCell>
<TableCell align="right">
<Button
variant="contained"
color="secondary"
onClick={
() => {
setPromotionId(item.promotion_id);
setModalIsActive(true);
}
// dispatch({
// type: "DELETE_PROMOTION",
// payload: item.promotion_id
// })
}
>
<i className="far fa-trash-alt" />
</Button>
</TableCell>
</TableRow>
))
: null}
</TableBody>
</Table>
</Paper>
) : null;
const roomsTable =
rooms.length > 0 ? (
<Paper>
<h1 className="p-2 italic">Rooms</h1>
<Table>
<TableHead>
<TableRow>
<TableCell className="cell-sm">Room Type</TableCell>
<TableCell className="cell-sm" align="left">
From Date
</TableCell>
<TableCell className="cell-sm" align="left">
To Date
</TableCell>
<TableCell className="cell-sm" align="right">
Remove From Cart
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rooms
? rooms.map((item, index) => (
<TableRow key={index}>
<TableCell className="cell-sm" align="left">
Room type
</TableCell>
<TableCell className="cell-sm" align="left">
<Moment format="YYYY/MM/DD">{item.started_at}</Moment>
</TableCell>
<TableCell className="cell-sm" align="left">
<Moment format="YYYY/MM/DD">{item.ended_at}</Moment>
</TableCell>
<TableCell align="right">
<Button
variant="contained"
color="secondary"
onClick={
() => {
setRoomId(item.room_id);
console.log(item.room_id);
setModalIsActive(true);
}
// dispatch({
// type: "DELETE_ROOM",
// payload: item.room_id
// })
}
>
<i className="far fa-trash-alt" />
</Button>
</TableCell>
</TableRow>
))
: null}
</TableBody>
</Table>
</Paper>
) : null;
return (
<>
<Modal
open={modalIsActive}
handleClose={() => setModalIsActive(false)}
userAction={() => handleDelete()}
modalHeader={"Remove item"}
modalText={"Are you shure you want to remove item from cart?"}
/>
<Modal
open={bookModalIsActive}
handleClose={() => setBookModalIsActive(false)}
userAction={handleBook}
modalHeader={"Make reservation"}
modalText={"Proceed with reservation?"}
/>
<Alert />
<div className="header-image" />
<div className="pb-32 px-2">
<h1 className="home-header text-center text-5xl text-gray-600 z-50">
<i className="fas fa-shopping-cart text-2xl" />
<br />
Cart
</h1>
<div className="mt-16 container mx-auto">
{cartItems.length > 0 ? (
<>
<div>
{promotionTable}
{roomsTable}
</div>
<div className="mt-8 w-full flex justify-end">
<Button
variant="contained"
color="primary"
onClick={() => setBookModalIsActive(true)}
>
BOOK
</Button>
</div>
</>
) : (
<div className="text-center h-32">
<h1 className="italic text-gray-600 text-center mb-8">
No items in cart
</h1>
<RouteLink
style={{ transition: "all 0.3s" }}
className="border border-blue-400 text-blue-600 px-8 py-4 rounded-lg hover:text-blue-400 shadow-lg hover:shadow-xl"
to="/booking"
>
Show available rooms
</RouteLink>
</div>
)}
</div>
</div>
</>
);
}
<file_sep>/fe/src/store/actions/authActions.js
import {
loginUser,
registerUser,
getLogedUser
} from "../../services/http/endpoints/users";
import { SAVE_USER_INFO } from "@store/types";
export const login = (user, history) => {
return async dispatch => {
const { data, error } = await loginUser(user);
if (data) {
let jwtToken = `${data.data.token_type} ${data.data.access_token}`;
localStorage.setItem("jwtToken", jwtToken);
history.push("/");
} else if (error) {
dispatch({
type: "LOGIN_ERROR"
});
console.log(error);
}
};
};
export const register = (user, history) => {
return async dispatch => {
const { data, error } = await registerUser(user);
if (data) {
console.log(data);
history.push("/login");
} else if (error) {
dispatch({ type: "REGISTRATION_ERROR" });
console.log(error.response);
}
};
};
export const getProfile = () => {
return async dispatch => {
const { data, error } = await getLogedUser();
if (data) {
localStorage.setItem("user", JSON.stringify(data.data));
console.log(data.data);
dispatch({ type: SAVE_USER_INFO, payload: data.data });
} else if (error) {
console.log(error);
}
};
};
<file_sep>/fe/src/store/types.js
export const SET_USER = "SET_USER";
export const LOGOUT_USER = "LOGOUT_USER";
export const SAVE_USER_INFO = "SAVE_USER_INFO";
export const SHOW_LAYOUT = "SHOW_LAYOUT";
export const HIDE_LAYOUT = "HIDE_LAYOUT";
<file_sep>/fe/src/services/http/interceptors/authentication.js
// import store from '@state/store';
export function authRequest(config) {
const token = localStorage.getItem("jwtToken");
if (token) {
config.headers.Authorization = token;
}
return config;
}
export const authResponse = [
function(response) {
return response;
},
function(error) {
if (401 === error.response.status) {
// store.dispatch({ type: 'DEAUTHENTICATE_USER' });
// localStorage.removeItem('jwtToken');
// localStorage.removeItem('user');
}
return Promise.reject(error);
}
];
<file_sep>/fe/src/components/reviews/Reviews.js
import React, { useState, useEffect } from "react";
import Review from "./Review";
import { getReviewsApproved, getPage, createReview } from "@endpoints/reviews";
import { getAllRooms } from "@endpoints/rooms";
import * as Yup from "yup";
import { Formik, Form } from "formik";
import {
Button,
CircularProgress,
Collapse,
ListItemText,
ListItemIcon,
ListItem,
List,
TextField,
Radio,
FormControl,
FormControlLabel,
FormLabel,
RadioGroup,
Divider,
InputLabel,
Select,
MenuItem
} from "@material-ui/core";
import "@zendeskgarden/react-pagination/dist/styles.css";
import { ThemeProvider } from "@zendeskgarden/react-theming";
import { Pagination } from "@zendeskgarden/react-pagination";
import ExpandLess from "@material-ui/icons/ExpandLess";
import ExpandMore from "@material-ui/icons/ExpandMore";
const schema = Yup.object().shape({
comment: Yup.string()
.min(2, "Minimum 2 characters are required")
.max(5000)
.required("Comment is required"),
hotel_rate: Yup.number()
.min(0, "Minimum number of characters is 1")
.max(5)
.required("Hotel Rate is required"),
room_rate: Yup.number()
.min(0, "Minimum number of characters is 1")
.max(5)
.required("Room Rate is required"),
accommodation_rate: Yup.number()
.min(0, "Minimum number of characters is 1")
.max(5)
.required("Accomodation Rate is required"),
room_id: Yup.string().required()
});
const Reviews = () => {
const [isSubmited, setIsSubmited] = useState(false);
const [reviews, setReviews] = useState({});
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
const [comment, setComment] = useState("");
const [roomId, setRoomId] = useState("");
const [rooms, setRooms] = useState(true);
const [selectedHotelRate, setSelectedHotelRate] = React.useState("1"); //value for radio buttons
const [selectedRoomRate, setSelectedRoomRate] = React.useState("1"); //value for radio buttons
const [
selectedAccomodationRate,
setSelectedAccomodationRate
] = React.useState("1"); //value for radio buttons
const [openList, setOpenList] = React.useState(false);
React.useEffect(() => {
window.scrollTo(0, 0);
}, []);
function handleRadioHotelChange(event) {
setSelectedHotelRate(event.target.value);
}
function handleRadioRoomChange(event) {
setSelectedRoomRate(event.target.value);
}
function handleRadioAccomodationChange(event) {
setSelectedAccomodationRate(event.target.value);
}
//Toggle list
function handleClickList() {
setOpenList(!openList);
}
const initialValues = {
comment: comment,
hotel_rate: selectedHotelRate,
room_rate: selectedRoomRate,
accommodation_rate: selectedAccomodationRate,
room_id: roomId
};
const getAllReviews = async () => {
const { data, error } = await getReviewsApproved();
if (data) {
console.log(data);
setReviews(data.data);
setCurrentPage(data.data.meta.pagination.current_page);
console.log(data.data.meta.pagination);
setTotalPages(data.data.meta.pagination.total_pages);
} else if (error) {
console.log(error.response);
}
};
const getCurrentPage = async (pageNum, currentPage) => {
const { data, error } = await getPage(pageNum);
if (data) {
setReviews(data.data);
} else if (error) {
console.log(error.response);
}
};
const createSingleReview = async credentials => {
const { data, error } = await createReview(credentials);
if (data) {
console.log("review created", data.data);
getAllReviews();
} else if (error) {
console.log("review erro", error.response);
}
};
const getRooms = async (page = 1) => {
const { data, error } = await getAllRooms(page);
if (data) {
console.log("rooms fetch", data.data);
setRooms(data.data.data);
} else if (error) {
console.log("Rooms err", error.response);
}
};
useEffect(() => {
document.title = "Quantox Hotel - Reviews";
getAllReviews();
getRooms();
}, []);
useEffect(() => {
getCurrentPage(currentPage);
window.scrollTo(0, 0); // scroll to top after selecting page
}, [currentPage]);
return (
<>
<div className="header-image" />
<h1 className="home-header text-center text-5xl text-gray-600 z-50">
<i className="fas fa-comments" />
<br />
Reviews
</h1>
<div className="container mx-auto text-center mt-16 px-2">
<List
component="nav"
aria-labelledby="nested-list-subheader"
className="bg-gray-400 mb-4 "
style={{ marginBottom: "50px" }}
>
<ListItem button onClick={handleClickList} className="p-6">
<ListItemIcon>{/* icon */}</ListItemIcon>
<ListItemText primary="Give us new review" />
{openList ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={openList} timeout="auto" unmountOnExit>
<List component="div">
<Formik
enableReinitialize
onSubmit={(values, actions) => {
console.log("Create review", values);
setIsSubmited(true);
createSingleReview(values);
setSelectedHotelRate("1");
setSelectedRoomRate("1");
setSelectedAccomodationRate("1");
}}
initialValues={initialValues}
validationSchema={schema}
>
{({
handleChange,
handleBlur,
values,
errors,
touched,
handleSubmit,
resetForm,
...formProps
}) => {
if (isSubmited) {
setComment("");
setRoomId("");
} else {
if (values.comment) {
setComment(values.comment);
}
if (values.room_id !== "") {
setRoomId(values.room_id);
}
}
return (
<Form className="p-8">
<TextField
margin="normal"
type="text"
fullWidth
label="Give us some feedback with honest comment"
name="comment"
onChange={handleChange}
onBlur={handleBlur}
value={values.comment}
error={
(errors.comment && touched.comment) || ""
? true
: false
}
/>
{(errors.comment && touched.comment) || "" ? (
<span className="text-danger">
{errors.comment || ""}
</span>
) : null}
<FormControl className="w-full ">
<InputLabel htmlFor="age-simple">
Select Room{" "}
</InputLabel>
<Select
className="mb-8"
value={values.room_id}
onChange={handleChange}
onBlur={handleBlur}
inputProps={{
name: "room_id",
id: "age-simple"
}}
error={
(errors.room_id && touched.room_id) || ""
? true
: false
}
>
{rooms.length
? rooms.map(room => {
return (
<MenuItem value={room.id} key={room.id}>
{room.room_number}
</MenuItem>
);
})
: null}
</Select>
{(errors.room_id && touched.room_id) || "" ? (
<span className="text-danger">
{errors.room_id || ""}
</span>
) : null}{" "}
</FormControl>
<div className="flex flex-col w-2/4 mx-auto my-6">
<FormControl component="fieldset">
<FormLabel component="legend">
Rate Hotel Experience
</FormLabel>
<RadioGroup
className="flex justify-between pt-4"
aria-label="position"
name="position"
value={values.hotel_rate}
onChange={handleRadioHotelChange}
row
>
<FormControlLabel
value="1"
control={<Radio color="primary" />}
label="1"
labelPlacement="end"
/>
<FormControlLabel
value="2"
control={<Radio color="primary" />}
label="2"
labelPlacement="end"
/>
<FormControlLabel
value="3"
control={<Radio color="primary" />}
label="3"
labelPlacement="end"
/>
<FormControlLabel
value="4"
control={<Radio color="primary" />}
label="4"
labelPlacement="end"
/>
<FormControlLabel
value="5"
control={<Radio color="primary" />}
label="5"
labelPlacement="end"
/>
</RadioGroup>
</FormControl>
<Divider style={{ marginBottom: "15px" }} />
{/* END RATE HOTEL EXP */}
<FormControl component="fieldset">
<FormLabel component="legend">
Rate Room Experience
</FormLabel>
<RadioGroup
className="flex justify-between pt-4"
aria-label="position"
name="position"
value={values.room_rate}
onChange={handleRadioRoomChange}
row
>
<FormControlLabel
value="1"
control={<Radio color="primary" />}
label="1"
labelPlacement="end"
/>
<FormControlLabel
value="2"
control={<Radio color="primary" />}
label="2"
labelPlacement="end"
/>
<FormControlLabel
value="3"
control={<Radio color="primary" />}
label="3"
labelPlacement="end"
/>
<FormControlLabel
value="4"
control={<Radio color="primary" />}
label="4"
labelPlacement="end"
/>
<FormControlLabel
value="5"
control={<Radio color="primary" />}
label="5"
labelPlacement="end"
/>
</RadioGroup>
</FormControl>
<Divider style={{ marginBottom: "15px" }} />
{/* END RATE ROOM EXP */}
<FormControl component="fieldset">
<FormLabel className="mt-6" component="legend">
Rate Accomodation Experience
</FormLabel>
<RadioGroup
className="flex justify-between pt-4"
aria-label="position"
name="position"
value={values.accommodation_rate}
onChange={handleRadioAccomodationChange}
row
>
<FormControlLabel
value="1"
control={<Radio color="primary" />}
label="1"
labelPlacement="end"
/>
<FormControlLabel
value="2"
control={<Radio color="primary" />}
label="2"
labelPlacement="end"
/>
<FormControlLabel
value="3"
control={<Radio color="primary" />}
label="3"
labelPlacement="end"
/>
<FormControlLabel
value="4"
control={<Radio color="primary" />}
label="4"
labelPlacement="end"
/>
<FormControlLabel
value="5"
control={<Radio color="primary" />}
label="5"
labelPlacement="end"
/>
</RadioGroup>
</FormControl>{" "}
<Divider />
</div>
<Button
type="submit"
//fullWidth
variant="contained"
color="primary"
margin="normal"
style={{ marginBottom: "15px" }}
>
Submit
</Button>
</Form>
);
}}
</Formik>
</List>
</Collapse>
</List>
{Object.keys(reviews).length ? (
reviews.data.map(data => {
return <Review {...data} key={data.id} />;
})
) : (
<CircularProgress />
)}
</div>
{Object.keys(reviews).length ? (
<ThemeProvider>
<Pagination
totalPages={totalPages}
currentPage={currentPage}
onChange={currentPage => setCurrentPage(currentPage)}
/>
</ThemeProvider>
) : null}
<div className="h-32 w-full" />
</>
);
};
export default Reviews;
<file_sep>/fe/src/components/admin/songs/components/CreateSong.js
import React, { useState, useEffect } from "react";
import { Field, Formik, Form, ErrorMessage } from "formik";
import * as Yup from "yup";
import { getAllGenres } from "@endpoints/genres";
import { getSongById, createSong, updateSong } from "@endpoints/songs";
import TextField from "@material-ui/core/TextField";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import Button from "@material-ui/core/Button";
const CreateSong = ({ id, setValue }) => {
const [genres, setGenres] = useState([]);
const [songData, setSongData] = useState({});
useEffect(() => {
getGenres();
}, []);
useEffect(() => {
getSongData(id);
}, [id]);
async function getGenres() {
const { data, error } = await getAllGenres();
if (data) {
console.log(data.data);
setGenres(data.data.data);
} else if (error) {
console.log(error.response);
}
}
async function getSongData(id) {
if (id.length) {
const { data, error } = await getSongById(id);
if (data) {
console.log(data.data.data);
setSongData(data.data.data);
} else if (error) {
console.log(error.response);
}
}
}
const Schema = Yup.object().shape({
name: Yup.string()
.min(2, "Name is to short")
.max(30, "Too LONG!.")
.required("Song name is required field"),
artist: Yup.string()
.min(2, "To short")
.max(30, "Too LONG!.")
.required("Artist is required field"),
link: Yup.string()
.required("Link is required")
.min(5, "To short")
.max(200, "Too LONG!."),
duration: Yup.number()
.required("Duration is required")
.min(1, "To short")
.max(200, "Too LONG!."),
genre_id: Yup.string()
.required("Genre is required")
.min(1, "To short")
.max(20, "Too LONG!.")
});
let genreSelectList = genres.length
? genres.map(item => {
return (
<MenuItem key={item.id} value={item.name}>
{item.name}
</MenuItem>
);
})
: null;
const initialValues = {
name: Object.keys(songData).length > 0 ? songData.name : "",
artist: Object.keys(songData).length > 0 ? songData.artist : "",
link: Object.keys(songData).length > 0 ? songData.link : "",
duration: Object.keys(songData).length > 0 ? songData.duration : "",
genre_id:
Object.keys(songData).length > 0 ? songData.genre.data.name : "Rock"
};
if (Object.keys(songData).length > 0) console.log(songData.name);
const handleCreateSubmit = async values => {
const genreId = genres.filter(item => {
return item.name === values.genre_id;
})[0].id;
const newSong = {
name: values.name,
artist: values.artist,
duration: values.duration,
link: values.link,
genre_id: genreId
};
const { data, error } = await createSong(newSong);
if (data) {
console.log(data.data);
setValue();
} else if (error) {
console.log(error.response);
}
};
const handleEditSubmit = async values => {
const genreId = genres.filter(item => {
return item.name === values.genre_id;
})[0].id;
const newSong = {
name: values.name,
artist: values.artist,
duration: values.duration,
link: values.link,
genre_id: genreId
};
const { data, error } = await updateSong(newSong, id);
if (data) {
console.log(data.data);
setValue();
} else if (error) {
console.log(error.response);
}
};
return (
<div>
<div style={{ width: "100%", maxWidth: "600px" }} className="mx-auto">
<h1 className="text-center italic text-gray-600 mt-8">
{Object.keys(songData).length > 0 ? "Edit song" : "Create new song"}
</h1>
<Formik
enableReinitialize
initialValues={initialValues}
validationSchema={Schema}
onSubmit={values => {
if (Object.keys(songData).length > 0) handleEditSubmit(values);
else handleCreateSubmit(values);
}}
render={props => (
<Form>
<Field name="name">
{({ field }) => (
<TextField
id="standard-textarea"
fullWidth
label="Song name"
{...field}
/>
)}
</Field>
<ErrorMessage name="name">
{mssg => (
<small className="block text-center text-red-600">
{mssg}
</small>
)}
</ErrorMessage>
<br />
<Field name="artist">
{({ field }) => (
<TextField
id="standard-textarea"
label="Artist"
fullWidth
{...field}
/>
)}
</Field>
<ErrorMessage name="artist">
{mssg => (
<small className="block text-center text-red-600">
{mssg}
</small>
)}
</ErrorMessage>
<br />
<Field name="link">
{({ field }) => (
<TextField
id="standard-textarea"
fullWidth
label="Link"
{...field}
/>
)}
</Field>
<ErrorMessage name="link">
{mssg => (
<small className="block text-center text-red-600">
{mssg}
</small>
)}
</ErrorMessage>
<br />
<Field name="duration">
{({ field }) => (
<TextField
id="standard-textarea"
label="Duration"
fullWidth
{...field}
/>
)}
</Field>
<ErrorMessage name="duration">
{mssg => (
<small className="block text-center text-red-600">
{mssg}
</small>
)}
</ErrorMessage>
<br />
<div className="w-full flex justify-start mt-8">
<p className="italic text-gray-600 mr-8">Select genre: </p>
<Field name="genre_id">
{({ field }) => (
<Select {...field} label="Select genre">
{genreSelectList}
</Select>
)}
</Field>
<ErrorMessage name="genre_id">
{mssg => (
<small className="block text-center text-red-600">
{mssg}
</small>
)}
</ErrorMessage>
</div>
<br />
<div className="w-full flex justify-end">
<Button
variant="contained"
color="primary"
type="submit"
fullWidth
>
{Object.keys(songData).length > 0 ? "Edit" : "Create"}
</Button>
</div>
</Form>
)}
/>
</div>
</div>
);
};
export default CreateSong;
<file_sep>/fe/src/services/http/endpoints/gallery.js
import http from "../index";
import toResponse from "@helpers/toResponse";
export const createGallery = credentials => {
return toResponse(http.post("/galleries", credentials));
};
export const getGalleries = () => {
return toResponse(http.get("/galleries"));
};
<file_sep>/fe/src/components/contactUs/ContactUs.js
import React, { useEffect } from "react";
// Components
import ContactForm from "./components/ContactForm";
import Map from "./components/Map";
const ContactUs = () => {
useEffect(() => {
window.scrollTo(0, 0);
document.title = "Quantox Hotel - Contact";
});
return (
<>
<div className="header-image" />
<div>
<h1 className="home-header text-center text-5xl text-gray-600 z-50">
<i className="fas fa-envelope" />
<br />
Contact Us
</h1>
<div className="flex flex-wrap contact-info container mx-auto mt-16 px-4 text-center md:text-left">
<div className="w-full md:w-1/2 ">
<h1 className="home-header text-3xl text-gray-600">Info:</h1>
<p className="leading-loose mt-8 text-lg">
<i className="fas fa-map-marker-alt mr-2 text-gray-600" />
<NAME> 245
</p>
<p className="leading-loose">
<i className="fas fa-phone mr-2 text-gray-600 home-header" />
+38111300400
</p>
<p className="leading-loose">
<i className="fas fa-envelope mr-2 text-gray-600 home-header" />
<EMAIL>
</p>
</div>
<div className="w-full md:w-1/2 home-header mt-16 md:mt-0">
<ContactForm />
</div>
</div>
</div>
<Map />
</>
);
};
export default ContactUs;
<file_sep>/fe/src/services/http/endpoints/events.js
import http from "../index";
import toResponse from "@helpers/toResponse";
export const getAllEvents = page => {
return toResponse(
http.get(`/events?page=${page}?include=songs,users,location`)
);
};
export const joinToEvent = id => {
return toResponse(http.post(`/events/join/${id}`));
};
export const deleteEvent = id => {
return toResponse(http.delete(`/events/${id}`));
};
export const createEvent = obj => {
return toResponse(http.post("/events", obj));
};
export const getEventById = id => {
return toResponse(http.get(`/events/${id}?include=songs,users,location`));
};
export const updateEvent = (obj, id) => {
return toResponse(http.patch(`/events/${id}`, obj));
};
// Event types
export const getAllEventTypes = page => {
return toResponse(http.get(`/event-types?page=${page}`));
};
export const createEventType = name => {
return toResponse(http.post("/event-types", name));
};
export const deleteEventType = id => {
return toResponse(http.delete(`/event-types/${id}`));
};
export const getEventTypeById = id => {
return toResponse(http.get(`/event-types/${id}`));
};
export const updateEventType = (id, name) => {
return toResponse(http.patch(`/event-types/${id}`, name));
};
<file_sep>/fe/src/components/admin/rooms/Facilities.js
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import {
makeStyles,
Button,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper,
CircularProgress,
Collapse,
ListItemText,
ListItemIcon,
ListItem,
List
} from "@material-ui/core";
import { getFacilities, deleteFacilitiy } from "@endpoints/rooms";
import "@zendeskgarden/react-pagination/dist/styles.css";
import { ThemeProvider } from "@zendeskgarden/react-theming";
import { Pagination } from "@zendeskgarden/react-pagination";
import Alert from "react-s-alert";
import ExpandLess from "@material-ui/icons/ExpandLess";
import ExpandMore from "@material-ui/icons/ExpandMore";
import CreateOrEditFacilities from "./CreateOrEditFacilities";
const useStyles = makeStyles(theme => ({
root: {
backgroundColor: theme.palette.background.paper
}
}));
//DISABLE ON CLICK RIPPLE
function Facilities() {
const classes = useStyles();
const [currentPage, setCurrentPage] = useState(1); //for api
const [totalPages, setTotalPages] = useState(1);
const [facilities, setFacilities] = useState([]);
const [openList, setOpenList] = React.useState(false);
const [facilityForEdit, setFacilityForEdit] = React.useState({});
//Toggle list
function handleClickList() {
setOpenList(!openList);
}
const getAllFacilities = async page => {
const { data, error } = await getFacilities(page);
if (data) {
console.log("types fetched", data.data);
setFacilities(data.data.data);
setTotalPages(data.data.meta.pagination.total_pages);
} else if (error) {
console.log(error.response);
}
};
const deleteSingleFacility = async facilityId => {
const { data, error } = await deleteFacilitiy(facilityId);
if (data) {
Alert.success("Facility Deleted!");
getAllFacilities(currentPage);
} else if (error) {
console.log(error.response);
}
};
//Kada se menja strana paginacije
useEffect(() => {
if (facilities.length) getAllFacilities(currentPage);
}, [currentPage, facilities]);
//Inicijalno ucitavanje
useEffect(() => {
if (!facilities.length) getAllFacilities(currentPage);
}, [facilities, currentPage]);
return (
<div className="text-center">
<Alert />
{/* //////////////////// Add new room Type //////////////////////////// */}
<div style={{ marginTop: "60px" }} />
<List
component="nav"
aria-labelledby="nested-list-subheader"
className="bg-gray-400 my-6"
>
<ListItem button onClick={handleClickList}>
<ListItemIcon>{/* icon */}</ListItemIcon>
<ListItemText primary="Add new Facility" />
{openList ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={openList} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
<CreateOrEditFacilities
facility={facilityForEdit}
setFacilityForEdit={setFacilityForEdit}
getAllFacilities={() => getAllFacilities(currentPage)}
/>
</List>
</Collapse>
</List>
{facilities.length ? (
<>
<Paper className={classes.root}>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell>Type Name</TableCell>
<TableCell align="left" className="cell-sm">
Price <br />
Child
</TableCell>
<TableCell size="small" align="left">
Edit Type
</TableCell>
<TableCell align="left">Delete Type</TableCell>
</TableRow>
</TableHead>
<TableBody>
{facilities.map(facility => (
<TableRow key={facility.id}>
<TableCell align="left">{facility.name}</TableCell>
<TableCell align="left">{facility.price}</TableCell>
<TableCell align="left">
{" "}
<Link to="#">
<Button
onClick={() => {
setOpenList(true);
setFacilityForEdit(facility);
}}
variant="contained"
color="primary"
className={classes.button}
>
Edit
</Button>
</Link>
</TableCell>
<TableCell align="left">
{" "}
<Button
// onClick={() => handleClickOpenModal(facility.id)}
onClick={() => deleteSingleFacility(facility.id)}
variant="contained"
color="secondary"
className={classes.button}
>
Delete
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
{totalPages > 1 ? (
<ThemeProvider>
<Pagination
totalPages={totalPages}
currentPage={currentPage}
onChange={currentPage => {
console.log("current page", currentPage);
return setCurrentPage(currentPage);
}}
/>
</ThemeProvider>
) : null}
</>
) : (
<CircularProgress />
)}
</div>
);
}
export default Facilities;
<file_sep>/fe/src/components/home/components/PromotionCard.js
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardActions from "@material-ui/core/CardActions";
import CardContent from "@material-ui/core/CardContent";
import CardMedia from "@material-ui/core/CardMedia";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import Fab from "@material-ui/core/Fab";
import bgImage from "@assets/images/special-offer-heading.png";
const useStyles = makeStyles({
card: {
paddingBottom: "20px"
},
media: {
height: 140,
backgroundSize: "60% 120px"
},
fab: {
left: "0",
right: "0",
margin: "0 auto",
bottom: "24px"
}
});
const PromotionCard = ({ item, openModal }) => {
const classes = useStyles();
return (
<div
className="w-full text-center px-2 md:px-8"
style={{ height: "400px" }}
>
<Card
className={`${classes.card} hover:shadow-2xl text-center`}
style={{ margin: "0 auto" }}
>
<CardMedia
className={`${classes.media} relative bg-contain`}
image={bgImage}
title="Room 1"
/>
<Fab
variant="extended"
aria-label="Add"
color="primary"
className={`${classes.fab} absolute mx-auto p-6`}
>
<span className="" style={{ color: "#fff" }} to="# ">
{`$${item.price}`}
</span>
</Fab>
<CardContent>
<Typography gutterBottom variant="h5" component="h2" align="center">
{item.name}
</Typography>
<Typography variant="body2" color="textSecondary" component="p">
{item.description.slice(0, 100) + "..."}
</Typography>
</CardContent>
<CardActions>
<Button
size="small"
color="primary"
variant="contained"
onClick={() => openModal(item.id)}
>
More details
</Button>
</CardActions>
</Card>
</div>
);
};
export default PromotionCard;
<file_sep>/fe/src/components/admin/gallery/Gallery.js
import React from "react";
const Gallery = () => {
React.useEffect(() => {
document.title = "Quantox Hotel - Admin Panel - Gallery";
}, []);
return <div>GALLERY</div>;
};
export default Gallery;
<file_sep>/fe/src/components/rooms/components/ModalContent.js
import React from "react";
import { Link } from "react-router-dom";
import Button from "@material-ui/core/Button";
const ModalContent = ({ close }) => {
return (
<div className="p-8 text-center">
<p>
<Link to="/login" className="italic text-blue-600">
Login
</Link>{" "}
or{" "}
<Link className="italic text-blue-600" to="register">
Register
</Link>{" "}
to be able to reserve room.
</p>
<div className="flex justify-end mt-8">
<Button onClick={close} variant="contained" color="secondary">
Close
</Button>
</div>
</div>
);
};
export default ModalContent;
<file_sep>/fe/src/components/admin/users/EditUser.js
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import {
Button,
TextField,
Container,
CircularProgress
} from "@material-ui/core";
import { getUser } from "@endpoints/users";
import Modal from "../Modal";
//initial values formik
const phoneRegExp = /^(\+?\d{0,4})?\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{4}\)?)?$/;
const editUserSchema = Yup.object().shape({
first_name: Yup.string()
.min(2, "Minimum number of characters is 2")
.max(50)
.required("Name is required"),
last_name: Yup.string()
.min(2, "Minimum number of characters is 2")
.max(50)
.required("Last Name is required"),
email: Yup.string()
.label("Email")
.email()
.required("Email is required"),
phone_number: Yup.string()
.matches(phoneRegExp, "Phone number is not valid")
.required("Phone is required"),
city: Yup.string()
.min(2)
.max(60)
.required("City is required"),
address: Yup.string()
.min(2)
.max(200)
.required("Address is required")
});
const EditUser = props => {
const [user, setUser] = useState({});
const [openModal, setOpenModal] = React.useState(false);
const [modalUser, setModalUser] = React.useState({});
function handleClickOpenModal() {
setOpenModal(true);
}
function handleCloseModal() {
setOpenModal(false);
}
const initialValues = {
first_name: user.first_name ? user.first_name : "",
last_name: user.last_name ? user.last_name : "",
email: user.email ? user.email : "",
phone_number: user.phone_number ? user.phone_number : "",
city: user.city ? user.city : "",
address: user.address ? user.address : ""
};
const getUserById = async userId => {
const { data, error } = await getUser(userId);
if (data) {
console.log("single user fetched", data);
setUser(data.data.data);
} else if (error) {
console.log(error.response);
}
};
useEffect(() => {
//props.match.params.userId
if (Object.keys(props.match.params).length && props.match.params.userId)
getUserById(props.match.params.userId);
}, [props.match.params]);
//Compoment has been reused for edit
return (
<>
{!(Object.keys(props.match.params).length && props.match.params.userId)
? "renderuj input field"
: "renderuj formu"}
{Object.keys(user).length ? (
<Container maxWidth="md">
<h1 className="large text-primary mt-16">Edit Your Profile</h1>
<Formik
enableReinitialize
onSubmit={async values => {
console.log("Edit user", values);
if (Object.keys(values).length) {
handleClickOpenModal();
setModalUser(values);
}
console.log(typeof values);
// dispatch(register(values));
}}
initialValues={initialValues}
validationSchema={editUserSchema}
>
{({
handleChange,
handleBlur,
values,
errors,
touched,
handleSubmit,
...formProps
}) => {
return (
<Form>
<Modal
open={openModal}
handleClose={handleCloseModal}
userAction={() => console.log("user iz modala ", modalUser)}
modalHeader={"Update user"}
modalText={
"Are you shure you want to update this user's info?"
}
/>
<TextField
margin="normal"
type="text"
fullWidth
label="<NAME>"
name="first_name"
onChange={handleChange}
onBlur={handleBlur}
value={values.first_name}
error={
(errors.first_name && touched.first_name) || ""
? true
: false
}
/>
{(errors.first_name && touched.first_name) || "" ? (
<span className="text-danger">
{errors.first_name || ""}
</span>
) : null}
<TextField
margin="normal"
type="text"
fullWidth
label="Last Name"
name="last_name"
onChange={handleChange}
onBlur={handleBlur}
value={values.last_name}
error={
(errors.last_name && touched.last_name) || ""
? true
: false
}
/>
{(errors.last_name && touched.last_name) || "" ? (
<span className="text-danger">
{errors.last_name || ""}
</span>
) : null}
<TextField
margin="normal"
type="email"
fullWidth
label="Email Address"
name="email"
onChange={handleChange}
onBlur={handleBlur}
value={values.email}
error={(errors.email && touched.email) || "" ? true : false}
/>
{(errors.email && touched.email) || "" ? (
<span className="text-danger">{errors.email || ""}</span>
) : null}
<TextField
margin="normal"
type="text"
fullWidth
label="Phone Number"
name="phone_number"
onChange={handleChange}
onBlur={handleBlur}
value={values.phone_number}
error={
(errors.phone_number && touched.phone_number) || ""
? true
: false
}
/>
{(errors.phone_number && touched.phone_number) || "" ? (
<span className="text-danger">
{errors.phone_number || ""}
</span>
) : null}
<TextField
margin="normal"
type="text"
fullWidth
label="City"
name="city"
onChange={handleChange}
onBlur={handleBlur}
value={values.city}
error={(errors.city && touched.city) || "" ? true : false}
/>
{(errors.city && touched.city) || "" ? (
<span className="text-danger">{errors.city || ""}</span>
) : null}
<TextField
margin="normal"
type="text"
fullWidth
label="Address"
name="address"
onChange={handleChange}
onBlur={handleBlur}
value={values.address}
error={
(errors.address && touched.address) || "" ? true : false
}
/>
{(errors.address && touched.address) || "" ? (
<span className="text-danger">{errors.address || ""}</span>
) : null}
{/* OVDE MODAL */}
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
margin="normal"
>
Edit User's Info
</Button>
</Form>
);
}}
</Formik>
<p className="text-right">
<Link to="/admin/users">
{" "}
<Button variant="outlined" color="default">
Go Back
</Button>
</Link>
</p>
</Container>
) : Object.keys(props.match.params).length &&
props.match.params.userId ? (
<CircularProgress />
) : null}
{/* Ako nema parametara u ruteru da se ne vrti spinner */}
</>
);
};
//
export default EditUser;
<file_sep>/fe/src/services/http/endpoints/promotions.js
import http from "../index";
import toResponse from "@helpers/toResponse";
export const getPromotions = () => {
return toResponse(http.get("/promotions"));
};
//http://api.quantox-hotel.local/v1/promotions?page=2
export const getPromotionsPerPage = page => {
return toResponse(http.get(`/promotions?page=${page}`));
};
export const getPromotionById = id => {
return toResponse(
http.get(`/promotions/${id}?include=roomTypes,file,services,facilities`)
);
};
export const createPromotion = credentials => {
return toResponse(http.post("/promotions", credentials));
};
export const deletePromotion = id => {
return toResponse(http.delete(`/promotions/${id}`));
};
export const updatePromotion = (credentials, id) => {
return toResponse(http.patch(`/promotions/${id}`, credentials));
};
<file_sep>/fe/src/components/admin/gallery/CreateGallery.js
import React, { useState, useEffect } from "react";
import { useDropzone } from "react-dropzone";
import { Button, TextField } from "@material-ui/core";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import { createGallery } from "@endpoints/gallery";
import {
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper
} from "@material-ui/core";
const Gallery = () => {
const [files, setFiles] = useState([]);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const { getRootProps, getInputProps } = useDropzone({
accept: "image/*",
onDrop: acceptedFiles => {
console.log("on drop", acceptedFiles);
setFiles(
files.concat(
acceptedFiles.map(file =>
Object.assign(file, {
preview: URL.createObjectURL(file)
})
)
)
);
}
});
console.log("Slike", files);
const createSingleGallery = async credentials => {
console.log("credentials", credentials.files);
const fd = new FormData();
fd.append("files", credentials.files);
console.log("fd", fd);
const { data, error } = await createGallery(fd);
if (data) {
console.log("Gallery created", data.data);
} else if (error) {
console.log("gallery error", error.response);
}
};
useEffect(
() => () => {
// Make sure to revoke the data uris to avoid memory leaks
files.forEach(file => URL.revokeObjectURL(file.preview));
},
[files]
);
const initialValues = {
name: name ? name : "",
description: description ? description : "",
files: [...files]
};
const gallerySchema = Yup.object().shape({
name: Yup.string()
.min(2)
.max(50)
.required("Gallery Name is required"),
description: Yup.string()
.min(2)
.max(50)
.required("Description is required"),
files: Yup.array()
});
return (
<section style={{ marginTop: "30px" }}>
<div className="from-top" />
<Formik
enableReinitialize
onSubmit={values => {
console.log("Gallery", values);
createSingleGallery(values);
}}
initialValues={initialValues}
validationSchema={gallerySchema}
>
{({ handleChange, handleBlur, values, errors, touched, ...props }) => {
if (values.name !== "") {
setName(values.name);
}
if (values.description !== "") {
setDescription(values.description);
}
console.log("files value", values.files);
return (
<Form>
<div
{...getRootProps({
className:
"h-24 bg-gray-200 mb-8 border-4 border-gray-400 border-dashed rounded flex justify-center items-center"
})}
>
{" "}
<input
{...getInputProps()}
ae=""
name="files"
// value={values.files}
// onChange={handleChange}
type="file"
/>
<p className="">
FIRST Drag 'n' drop some files here, or click to select files
</p>
</div>
{/* <input
name="files"
value={values.files}
onChange={handleChange}
type="file"
/>{" "} */}
<TextField
// disabled={files.length ? false : true}
margin="normal"
type="text"
fullWidth
label="Gallery Name"
name="name"
onChange={handleChange}
onBlur={handleBlur}
value={values.name}
error={(errors.name && touched.name) || "" ? true : false}
/>
{(errors.name && touched.name) || "" ? (
<span className="text-danger">{errors.name || ""}</span>
) : null}
<TextField
// disabled={files.length ? false : true}
margin="normal"
type="text"
fullWidth
label="Gallery Description"
name="description"
onChange={handleChange}
onBlur={handleBlur}
value={values.description}
error={
(errors.description && touched.description) || ""
? true
: false
}
/>
{(errors.description && touched.description) || "" ? (
<span className="text-danger">{errors.description || ""}</span>
) : null}
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
margin="normal"
>
Submit
</Button>
</Form>
);
}}
</Formik>
<aside className="">
{files.length ? (
<Paper>
<Table>
<TableHead>
<TableRow>
<TableCell>Img</TableCell>
<TableCell>Img Name</TableCell>
<TableCell align="right">Delete Img</TableCell>
</TableRow>
</TableHead>
<TableBody>
{files.length
? files.map((file, index) => (
<TableRow key={file.path}>
<TableCell component="th" scope="row">
<img
src={file.preview}
alt="preview"
className="h-8"
/>
</TableCell>
<TableCell component="th" scope="row">
{file.path} - {file.size} bytes
</TableCell>
<TableCell align="right">
{" "}
<Button
onClick={() =>
setFiles(
files.filter(
(item, indexItem) => indexItem !== index
)
)
}
variant="contained"
color="secondary"
>
Remove
</Button>
</TableCell>
</TableRow>
))
: null}
</TableBody>
</Table>
</Paper>
) : null}
</aside>
</section>
);
};
export default Gallery;
<file_sep>/fe/src/components/admin/rooms/CreateOrEditRoom.js
import React, { useState, useEffect } from "react";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import {
Button,
TextField,
Container,
Checkbox,
Select,
MenuItem,
FormControl,
InputLabel,
FormControlLabel,
FormGroup,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper
} from "@material-ui/core";
import {
createRoom,
getRoomTypes,
getFacilities,
getRoom
} from "@endpoints/rooms";
import { useDropzone } from "react-dropzone";
//initial values formik
const createOrEditRoomSchema = Yup.object().shape({
pictures: Yup.array(),
room_number: Yup.number()
.min(1, "Minimum number of characters is 1")
.max(5000)
.required("Room Number is required"),
room_type_id: Yup.string().required("Room Type is required"),
facilities: Yup.array()
});
const CreateOrEditRoom = props => {
const [roomTypeId, setRoomTypeId] = useState("");
const [roomNumber, setRoomNumber] = useState("");
const [files, setFiles] = useState([]); //from dropzone
const [editRoom, setEditRoom] = useState({}); //store room for edit
const [roomTypes, setRoomTypes] = useState([]); //from api
const [roomFacilities, setRoomFacilities] = useState([]); //from api
const [selectedFacilities, setSelectedFacilities] = useState([]); //checkboxes
const createSingleRoom = async credentials => {
const fd = new FormData();
console.log("credentials passed", credentials);
fd.append("pictures", credentials.pictures);
fd.append("room_type_id", credentials.room_type_id);
fd.append("room_number", credentials.room_number);
fd.append("facilities", credentials.facilities);
const { data, error } = await createRoom(fd);
if (data) {
console.log("Room created", data.data);
} else if (error) {
console.log(error.response);
}
};
const getSingleRoom = async id => {
const { data, error } = await getRoom(id);
if (data) {
setEditRoom(data.data.data);
console.log("Single room fetched", data.data);
} else if (error) {
console.log(error.response);
}
};
const getAllRoomTypes = async (page = 1) => {
const { data, error } = await getRoomTypes(page);
if (data) {
setRoomTypes(data.data.data);
console.log("Room Types fetched", data.data.data);
} else if (error) {
console.log(error.response);
}
};
const getRoomFacilities = async (page = 1) => {
const { data, error } = await getFacilities(page);
if (data) {
setRoomFacilities(data.data.data);
console.log("Room Facilities fetched", data.data.data);
} else if (error) {
console.log(error.response);
}
};
const initialValues = {
pictures: [...files],
room_number: roomNumber
? roomNumber
: Object.keys(editRoom).length
? editRoom.room_number
: "",
room_type_id: roomTypeId ? roomTypeId : "",
facilities: [...selectedFacilities]
};
const { getRootProps, getInputProps } = useDropzone({
accept: "image/*",
onDrop: acceptedFiles => {
setFiles(
files.concat(
acceptedFiles.map(file =>
Object.assign(file, {
preview: URL.createObjectURL(file)
})
)
)
);
}
});
useEffect(
() => () => {
// Make sure to revoke the data uris to avoid memory leaks
files.forEach(file => URL.revokeObjectURL(file.preview));
},
[files]
);
useEffect(() => {
if (Object.keys(props.match.params).length && props.match.params.roomId) {
getSingleRoom(props.match.params.roomId);
}
// eslint-disable-next-line
getAllRoomTypes();
// eslint-disable-next-line
getRoomFacilities();
// eslint-disable-next-line
}, [props.match.params]);
console.log("edit room props", props);
return (
<>
<div style={{ marginTop: "60px" }} />
<Container maxWidth="md" style={{ marginTop: "42px" }}>
<h1 className="large text-primary">Add or edit room </h1>
<Formik
enableReinitialize
onSubmit={(values, actions) => {
console.log("Edit or create Room", values);
createSingleRoom(values);
// if (Object.keys(type).length && type.id) {
// handleClickOpenModal();
// setModalInfo1(values);
// setModalInfo2(type.id);
// } else {
// createType(values);
// actions.resetForm();
// }
}}
initialValues={initialValues}
validationSchema={createOrEditRoomSchema}
>
{({
handleChange,
handleBlur,
values,
errors,
touched,
handleSubmit,
resetForm,
...formProps
}) => {
if (values.room_number !== "") {
let number = values.room_number;
let strToNum = parseInt(number, 10);
setRoomNumber(strToNum);
}
if (values.room_type_id !== "") {
setRoomTypeId(values.room_type_id);
}
return (
<Form>
{/* <Modal
open={openModal}
handleClose={handleCloseModal}
// props.setTypeForEdit();
userAction={() => {
return Object.keys(type).length && type.id
? updateType(modalInfo1, modalInfo2)
: null;
}}
additionAction={() => props.setTypeForEdit({})} //da resetuje formu
modalHeader={"Update type"}
modalText={"Are you shure you want to update this type?"}
/> */}
<div
{...getRootProps({
className:
"h-24 bg-gray-200 mb-8 border-4 border-gray-400 border-dashed rounded flex justify-center items-center"
})}
>
{" "}
<input
{...getInputProps()}
ae=""
name="pictures"
type="file"
/>
<p className="">
FIRST Drag 'n' drop some files here, or click to select
files
</p>
</div>
<TextField
margin="normal"
type="text"
fullWidth
label=" Room Number"
name="room_number"
onChange={handleChange}
onBlur={handleBlur}
value={values.room_number}
error={
(errors.room_number && touched.room_number) || ""
? true
: false
}
/>
{(errors.room_number && touched.room_number) || "" ? (
<span className="text-danger">
{errors.room_number || ""}
</span>
) : null}
<FormControl className="w-full ">
<InputLabel htmlFor="age-simple">Select Room Type</InputLabel>
<Select
className="mb-8"
value={values.room_type_id}
onChange={handleChange}
onBlur={handleBlur}
inputProps={{
name: "room_type_id",
id: "age-simple"
}}
error={
(errors.room_type_id && touched.room_type_id) || ""
? true
: false
}
>
{roomTypes.length
? roomTypes.map(type => {
return (
<MenuItem value={type.id} key={type.id}>
{type.name}
</MenuItem>
);
})
: null}
</Select>
{(errors.room_type_id && touched.room_type_id) || "" ? (
<span className="text-danger">
{errors.room_type_id || ""}
</span>
) : null}{" "}
</FormControl>
{/* end select */}
<FormGroup row name="facilities" value={values.facilities}>
{roomFacilities.length
? roomFacilities.map(facility => {
return (
<FormControlLabel
key={facility.id}
control={
<Checkbox
name={facility.name}
//checked={true}
onChange={() =>
setSelectedFacilities([
...selectedFacilities,
facility.id
])
}
value={facility.id}
/>
}
label={facility.name}
/>
);
})
: null}
</FormGroup>
{/* CHECKBOXES */}
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
margin="normal"
>
Submit
</Button>
</Form>
);
}}
</Formik>
</Container>
{/* ) : <CircularProgress /> ? (
//Object.keys(props.match).length && props.match.params.userId
<CircularProgress />
) : null} */}
{/* Ako nema parametara u ruteru da se ne vrti spinner */}
<aside className="">
{files.length ? (
<Paper>
<Table>
<TableHead>
<TableRow>
<TableCell>Img</TableCell>
<TableCell>Img Name</TableCell>
<TableCell align="right">Delete Img</TableCell>
</TableRow>
</TableHead>
<TableBody>
{files.length
? files.map((file, index) => (
<TableRow key={file.path}>
<TableCell component="th" scope="row">
<img src={file.preview} className="h-8" alt="test" />
</TableCell>
<TableCell component="th" scope="row">
{file.path} - {file.size} bytes
</TableCell>
<TableCell align="right">
{" "}
<Button
onClick={() =>
setFiles(
files.filter(
(item, indexItem) => indexItem !== index
)
)
}
variant="contained"
color="secondary"
>
Remove
</Button>
</TableCell>
</TableRow>
))
: null}
</TableBody>
</Table>
</Paper>
) : null}
</aside>
</>
);
};
//
export default CreateOrEditRoom;
<file_sep>/fe/src/components/rooms/components/Room.js
import React, { useState } from "react";
import room1 from "@assets/images/rooms/room1.jpg";
import { Link } from "react-router-dom";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import { useSelector, useDispatch } from "react-redux";
import moment from "moment";
import DateFnsUtils from "@date-io/date-fns";
import { DatePicker, MuiPickersUtilsProvider } from "@material-ui/pickers";
import Checkbox from "@material-ui/core/Checkbox";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Alert from "react-s-alert";
import Modal from "@common/modal";
import ModalContent from "./ModalContent";
import { WidthContext } from "@components/common/context/ContextProvider";
import { getServices } from "@endpoints/services";
import {
Card,
CardContent,
CardMedia,
Typography,
Button,
Fab
} from "@material-ui/core";
const useStyles = makeStyles({
card: {},
media: {
height: 300
},
fab: {
left: "50%",
transform: "translate(-50%,-50%)"
}
});
const Room = ({ data, fullWidth, close }) => {
const [modalIsOpen, setModalIsOpen] = useState(false);
const [adultNum, setAdultNum] = useState("");
const [childrenNum, setChildrenNum] = useState("");
const [maxPersons, setMaxPersons] = useState("");
const [services, setServices] = React.useState([]);
const [selectedServices, setSelectedServices] = useState([]);
const [state, setState] = React.useState({
checkIn: new Date(),
checkOut: new Date()
});
React.useEffect(() => {
window.scrollTo(0, 0);
// eslint-disable-next-line
getAllServices();
// eslint-disable-next-line
setMaxPersons(data.roomType ? data.roomType.data.max_persons : 4);
// eslint-disable-next-line
}, []);
const { windowWidth } = React.useContext(WidthContext);
const isAuthenticated = useSelector(state => state.user.isAuthenticated);
const classes = useStyles();
const dispatch = useDispatch();
const handleChange = id => {
if (!selectedServices.includes(id)) {
setSelectedServices([...selectedServices, id]);
} else {
let newArr = [...selectedServices];
let index = newArr.indexOf(id);
newArr.splice(index, 1);
setSelectedServices(newArr);
}
};
async function getAllServices() {
const { data, error } = await getServices();
if (data) {
console.log(data);
setServices(data.data.data);
} else if (error) {
console.log(error.response);
}
}
const handleSubmit = () => {
if (!isAuthenticated) {
setModalIsOpen(true);
} else {
let room = {};
room.started_at = moment(state.checkIn).format("YYYY-MM-DD");
room.ended_at = moment(state.checkOut).format("YYYY-MM-DD");
room.services = selectedServices;
room.adults = adultNum;
room.children = childrenNum;
room.room_id = data.id;
dispatch({
type: "ADD_ROOM",
payload: room
});
Alert.success(<i className="fas fa-check" />, {
effect: "slide",
timeout: 2000
});
console.log(room);
if (close) close();
}
};
const servicesList = services.length
? services.map(item => {
return (
<FormControlLabel
key={item.id}
control={
<Checkbox
onChange={() => handleChange(item.id)}
color="primary"
inputProps={{
"aria-label": "secondary checkbox"
}}
/>
}
label={item.name}
/>
);
})
: null;
const facilitiesList =
Object.keys(data).length > 0
? data.facilities.data.map(item => {
return (
<span
key={item.id}
className="border-r border-gray-400 px-4 px-2 text-gray-600 italic"
>
{item.name}
</span>
);
})
: null;
return (
<>
<div
className={`${
fullWidth ? "w-full" : "md:w-6/12"
} room-item w-full justify-between px-0 mt-16`}
>
<Card className={`${classes.card} hover:shadow-2xl`}>
<CardMedia
className={`${classes.media} relative `}
image={room1}
title="Room 1"
/>
<Fab
variant="extended"
aria-label="Add"
color="primary"
className={`${classes.fab} absolute mx-auto p-6`}
>
<Link to="# ">
{`${
Object.keys(data).length > 0
? data.roomType.data.price_adult
: null
}`}
$ /Night
</Link>
</Fab>
<CardContent>
<Typography gutterBottom variant="h5" component="h2" align="center">
{Object.keys(data).length > 0 ? data.roomType.data.name : null}
</Typography>
<div>
<p className="text-center italic mt-4 text-gray-600 text-xl">
Facilities
</p>
<div className="flex flex-wrap justify-center text-center mt-4">
{facilitiesList}
</div>
</div>
<div className="mt-8">
<div>
<p className="italic text-gray-600">Select services:</p>
<div className="text-center">
<div className="flex flex-wrap justify-center ">
{servicesList}
</div>
</div>
</div>
</div>
<div className="mt-4">
<p className="italic text-gray-600 mb-4">Period:</p>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<div className="flex justify-around flex-col md:flex-row">
<DatePicker
value={state.checkIn}
label="Check In"
onChange={value => setState({ ...state, checkIn: value })}
/>
<DatePicker
value={state.checkOut}
style={{ marginTop: windowWidth > 768 ? null : "20px" }}
label="Check Out"
onChange={value => setState({ ...state, checkOut: value })}
/>
</div>
</MuiPickersUtilsProvider>
</div>
<div className="mt-6">
<p className="italic text-gray-600">
Guests number:
<span className="font-semibold">{` (Max. ${
maxPersons ? maxPersons : " - "
})`}</span>
</p>
<div className="flex justify-around flex-col md:flex-row">
<TextField
id="standard-name"
label="Adults"
type="number"
value={adultNum}
onChange={e => setAdultNum(e.target.value)}
/>
<TextField
id="standard-name"
label="Chldren"
type="number"
value={childrenNum}
onChange={e => setChildrenNum(e.target.value)}
/>
</div>
</div>
<div className="mt-8 w-full flex flex-end">
{close ? (
<div className="">
<Button
variant="contained"
color="secondary"
onClick={close}
style={{ marginRight: "10px" }}
>
CLOSE
</Button>
<Button
variant="contained"
color="primary"
disabled={
Number(maxPersons) <
Number(adultNum) + Number(childrenNum) ||
adultNum === "" ||
childrenNum === ""
? true
: false
}
onClick={handleSubmit}
>
ADD TO CART
</Button>
</div>
) : (
<Button
variant="contained"
color="primary"
fullWidth
disabled={
Number(maxPersons) <
Number(adultNum) + Number(childrenNum) ||
adultNum === "" ||
childrenNum === ""
? true
: false
}
onClick={handleSubmit}
>
ADD TO CART
</Button>
)}
</div>
</CardContent>
</Card>
<Alert />
</div>
<Modal open={modalIsOpen} close={setModalIsOpen}>
<ModalContent close={() => setModalIsOpen(false)} />
</Modal>
</>
);
};
export default Room;
<file_sep>/fe/src/components/events/Events.js
import React, { useState } from "react";
import Event from "./components/Event";
import { useSelector } from "react-redux";
import { Link } from "react-router-dom";
import { makeStyles } from "@material-ui/core/styles";
import CircularProgress from "@material-ui/core/CircularProgress";
import { getAllEvents } from "../../services/http/endpoints/events";
const useStyles = makeStyles(theme => ({
progress: {
position: "fixed",
top: "50%",
zIndex: "100",
left: 0,
right: 0,
margin: "0 auto",
transform: "translateY(-50%)"
}
}));
const Events = () => {
const [events, setEvents] = React.useState([]);
const [loader, setLoader] = useState(true);
React.useEffect(() => {
document.title = "Quantox Hotel - Events";
}, []);
React.useEffect(() => {
window.scrollTo(0, 0);
getData();
}, []);
const user = useSelector(state => state.user);
async function getData() {
const { data, error } = await getAllEvents();
if (data) {
console.log(data.data);
console.log(new Date());
setEvents(data.data.data);
setLoader(false);
} else if (error) {
console.log(error.response);
}
}
const classes = useStyles();
const eventsList =
events.length > 0
? events.map((item, index) => {
return (
<div key={index} className="mb-16">
<Event event={item} join={true} />
</div>
);
})
: null;
return (
<div>
{loader ? <CircularProgress className={classes.progress} /> : null}
<div className="header-image" />
<h1 className="home-header text-center text-5xl text-gray-600 z-50">
<i className="fas fa-user-friends" />
<br />
Events
</h1>
{user.isAuthenticated ? null : (
<h1 className="text-2xl text-center italic text-gray-500">
<Link to="/register" className="underline">
Register
</Link>{" "}
or{" "}
<Link to="/login" className="underline">
Login
</Link>{" "}
to join the events
</h1>
)}
<div className="container mx-auto mt-32">
<div className=" w-full justify-between">{eventsList}</div>
</div>
</div>
);
};
export default Events;
<file_sep>/fe/src/services/http/endpoints/locations.js
import http from "../index";
import toResponse from "@helpers/toResponse";
export const getAllLocations = page => {
return toResponse(http.get(`/locations?page=${page}`));
};
<file_sep>/fe/src/components/admin/dashboard/NewsletterChart.js
import React, { PureComponent } from "react";
import {
Radar,
RadarChart,
PolarGrid,
PolarAngleAxis,
PolarRadiusAxis
} from "recharts";
import { Card, CardContent, Typography } from "@material-ui/core";
const data = [
{
subject: "Mon",
A: 120,
B: 110,
fullMark: 150
},
{
subject: "Tue",
A: 98,
B: 130,
fullMark: 150
},
{
subject: "Wed",
A: 86,
B: 130,
fullMark: 150
},
{
subject: "Thu",
A: 99,
B: 100,
fullMark: 150
},
{
subject: "Fri",
A: 85,
B: 90,
fullMark: 150
},
{
subject: "Sat",
A: 65,
B: 85,
fullMark: 150
},
{
subject: "Sun",
A: 65,
B: 85,
fullMark: 150
}
];
export default class DashboardNewsletter extends PureComponent {
render() {
return (
<Card className=" w-full">
<CardContent>
<Typography variant="body2" color="textSecondary" component="h3">
Stats for newsletter
</Typography>
{/* <Divider /> */}
</CardContent>
<RadarChart
cx="50%"
cy="50%"
width={400}
height={250}
data={data}
className=" mx-auto shadow-md"
>
<PolarGrid />
<PolarAngleAxis dataKey="subject" />
<PolarRadiusAxis />
<Radar
name="Mike"
dataKey="A"
stroke="#8884d8"
fill="#8884d8"
fillOpacity={0.5}
/>
</RadarChart>
</Card>
);
}
}
<file_sep>/fe/src/components/home/About.js
import React from "react";
import bgImage from "@assets/images/about.jpg";
const About = () => {
return (
<div
className="about pb-32 w-full relative z-50 mt-16 md:mt-32 bg-fixed"
style={{ height: "60vh", backgroundImage: `url(${bgImage})` }}
>
<div
className="absolute w-full h-full left-0 top-0 bg-contain z-10 pt-4 md:pt-16"
style={{ background: "rgba(0, 0, 0, 0.5)" }}
>
<h1 className="home-header text-center text-2xl md:text-5xl text-white z-50 italic">
About Us
</h1>
<div className="container mx-auto px-2">
<p className="text-center mt-6 md:mt-16 text-white z-50 ">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Esse
dolorum optio, quod consequatur eos nobis rem nostrum aliquid illo
rerum? Magnam voluptate modi dolor nulla repudiandae minus possimus.
Debitis, perferendis? Lorem ipsum dolor sit amet consectetur
adipisicing elit. Esse dolorum optio, quod consequatur eos nobis rem
nostrum aliquid illo rerum? Magnam voluptate modi dolor nulla
repudiandae minus possimus. Debitis, perferendis
</p>
<div className="flex justify-center text-white mt-4 md:mt-16 text-xl md:text-4xl ">
<i className="fas fa-wifi p-4" />
<i className="fas fa-parking p-4" />
<i className="fas fa-swimming-pool p-4" />
<i className="fas fa-cocktail p-4" />
<i className="fas fa-dumbbell p-4" />
<i className="fas fa-paw p-4" />
</div>
</div>
</div>
</div>
);
};
export default About;
<file_sep>/fe/src/components/gallery/Gallery.js
import React, { useState, useCallback } from "react";
import Gallery from "react-photo-gallery";
import Carousel, { Modal, ModalGateway } from "react-images";
function GalleryBox() {
const [currentImage, setCurrentImage] = useState(0);
const [viewerIsOpen, setViewerIsOpen] = useState(false);
React.useEffect(() => {
document.title = "Quantox Hotel - Gallery";
}, []);
React.useEffect(() => {
window.scrollTo(0, 0);
}, []);
const openLightbox = useCallback((event, { photo, index }) => {
setCurrentImage(index);
setViewerIsOpen(true);
}, []);
const closeLightbox = () => {
setCurrentImage(0);
setViewerIsOpen(false);
};
const photos = [
{
src: "https://source.unsplash.com/2ShvY8Lf6l0/800x599",
width: 4,
height: 3
},
{
src: "https://source.unsplash.com/Dm-qxdynoEc/800x799",
width: 1,
height: 1
},
{
src: "https://source.unsplash.com/qDkso9nvCg0/600x799",
width: 3,
height: 4
},
{
src: "https://source.unsplash.com/iecJiKe_RNg/600x799",
width: 3,
height: 4
},
{
src: "https://source.unsplash.com/epcsn8Ed8kY/600x799",
width: 3,
height: 4
},
{
src: "https://source.unsplash.com/NQSWvyVRIJk/800x599",
width: 4,
height: 3
},
{
src: "https://source.unsplash.com/zh7GEuORbUw/600x799",
width: 3,
height: 4
},
{
src: "https://source.unsplash.com/PpOHJezOalU/800x599",
width: 4,
height: 3
},
{
src: "https://source.unsplash.com/I1ASdgphUH4/800x599",
width: 4,
height: 3
}
];
return (
<div>
<div className="header-image" />
<h1 className="home-header text-center text-5xl text-gray-600 z-50">
<i className="far fa-images" />
<br />
Gallery
</h1>
<div className="container mx-auto mt-16 mb-16 px-2">
<Gallery photos={photos} onClick={openLightbox} />
<ModalGateway>
{viewerIsOpen ? (
<Modal onClose={closeLightbox}>
<Carousel
currentIndex={currentImage}
views={photos.map(x => ({
...x,
srcset: x.srcSet,
caption: x.title
}))}
/>
</Modal>
) : null}
</ModalGateway>
</div>
</div>
);
}
export default GalleryBox;
<file_sep>/fe/src/components/home/components/Slide2.js
import React from "react";
const Slide2 = () => {
return (
<div className="text-center">
<h1 className="slide1-header text-center text-3xl md:text-6xl">
Golden Autumn Offer
</h1>
<div className="flex justify-center">
<div className="p-4">
<i className="fas fa-wifi text-lg md:text-4xl pb-4" />
<br />
<p className="text-xs">FREE WIFI</p>
</div>
<div className="p-4">
<i className="fas fa-parking text-xl md:text-4xl pb-4" />
<br />
<p className="text-xs">FREE PARKING</p>
</div>
<div className="p-4">
<i className="fas fa-coffee text-xl md:text-4xl pb-4" />
<br />
<p className="text-xs">BREAKFAST</p>
</div>
</div>
</div>
);
};
export default Slide2;
<file_sep>/fe/src/App.js
import React from "react";
import "./assets/styles/main.scss";
import { Router, Switch, Route } from "react-router-dom";
import history from "@helpers/history";
// Components
import Admin from "@components/admin/Admin";
import Main from "@components/main/Main";
function App() {
const [showScrollToTop, setShowScrollToTop] = React.useState(false);
React.useEffect(() => {
window.addEventListener("scroll", handleScroll);
}, []);
function handleScroll() {
if (window.scrollY > 200) setShowScrollToTop(true);
else if (window.scrollY < 200) setShowScrollToTop(false);
}
return (
<div className="App">
<button
onClick={() =>
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth"
})
}
className={`${
showScrollToTop ? "visible" : "invisible"
} fixed text-3xl`}
style={{
bottom: "20px",
right: "20px",
zIndex: "300",
transition: "all 0.3s"
}}
>
<i className="fas fa-chevron-circle-up" style={{ color: "#1975D2" }} />
</button>
<div>
<Router history={history}>
<Switch>
<Route path="/admin" component={Admin} />
<Route path="/" component={Main} />
</Switch>
</Router>
</div>
</div>
);
}
export default App;
<file_sep>/fe/src/components/home/Promotions.js
import React from "react";
import Alert from "react-s-alert";
import AliceCarousel from "react-alice-carousel";
import "react-alice-carousel/lib/alice-carousel.css";
import { getPromotions } from "../../services/http/endpoints/promotions";
// Components
import PromotionCard from "./components/PromotionCard";
import PromotionModal from "./components/PromotionModal";
const Promotions = () => {
const [promotions, setPromotions] = React.useState([]);
const [modalIsOpen, setModalIsOpen] = React.useState(false);
const [modalId, setModalId] = React.useState("");
React.useEffect(() => {
getData();
}, []);
const handleOnDragStart = e => e.preventDefault();
async function getData() {
const { data, error } = await getPromotions();
if (data) {
setPromotions(data.data.data);
} else if (error) {
console.log(error);
}
}
const openModal = id => {
setModalIsOpen(true);
console.log(id);
setModalId(id);
};
const handleCloseModal = id => {
setModalIsOpen(false);
console.log(id);
};
const responsive = {
0: { items: 1 },
1024: { items: 2 }
};
const cardList =
promotions.length > 0
? promotions.map(item => {
return (
<PromotionCard
onDragStart={handleOnDragStart}
item={item}
key={item.id}
openModal={openModal}
className="item"
/>
);
})
: null;
return (
<div className="promotionSlider container mx-auto w-full mt-2 md:mt-32">
<Alert />
<h1 className="text-center text-3xl md:text-5xl text-gray-700 home-header italic">
Promotions
</h1>
<div className="mt-16 ">
<AliceCarousel
responsive={responsive}
autoPlayInterval={3000}
autoPlayDirection="ltr"
autoPlay={true}
fadeOutAnimation={true}
mouseDragEnabled={true}
disableAutoPlayOnAction={true}
>
{cardList}
</AliceCarousel>
</div>
{modalIsOpen ? (
<PromotionModal
modalIsOpen={modalIsOpen}
handleCloseModal={handleCloseModal}
modalId={modalId}
Alert={Alert}
/>
) : null}
</div>
);
};
export default Promotions;
<file_sep>/fe/src/services/http/index.js
import axios from "axios";
import { authRequest, authResponse } from "./interceptors/authentication";
const url = "http://api.quantox-hotel.local/v1";
const http = axios.create({
baseURL: url
});
http.interceptors.request.use(authRequest);
http.interceptors.response.use(...authResponse);
export default http;
<file_sep>/fe/src/components/admin/rooms/CreateOrEditFacilities.js
import React from "react";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import {
Button,
TextField,
Container,
CircularProgress
} from "@material-ui/core";
import { createFacility, updateFacility } from "@endpoints/rooms";
import Modal from "../Modal";
//initial values formik
const facilitiesSchema = Yup.object().shape({
name: Yup.string()
.min(2, "Minimum number of characters is 2")
.max(5000)
.required("Name is required"),
price: Yup.number()
.min(0, "Minimum number of characters is 1")
.max(5000)
.required("Price for Facilities is required")
});
const CreateOrEditFacilities = ({ facility, ...props }) => {
const [openModal, setOpenModal] = React.useState(false);
const [modalInfo1, setModalInfo1] = React.useState();
const [modalInfo2, setModalInfo2] = React.useState();
function handleClickOpenModal() {
setOpenModal(true);
}
function handleCloseModal() {
setOpenModal(false);
}
const createSignleFacility = async credentials => {
const { data, error } = await createFacility(credentials);
if (data) {
props.getAllFacilities();
console.log("facility created", data.data);
} else if (error) {
console.log(error.response);
}
};
const updateSingleFacility = async (credentials, id) => {
const { data, error } = await updateFacility(credentials, id);
if (data) {
props.getAllFacilities();
console.log("facility updated", data.data);
} else if (error) {
console.log(error.response);
}
};
//component only recives props
const initialValues = {
name: facility.name ? facility.name : "",
price: facility.price ? facility.price : ""
};
console.log("edit facility props", facility);
return (
<>
{Object.keys(facility).length || true ? (
<Container maxWidth="md">
<h1 className="large text-primary">Add or edit room type</h1>
<Formik
enableReinitialize
onSubmit={(values, actions) => {
console.log("Edit or create facility", values);
if (Object.keys(facility).length && facility.id) {
handleClickOpenModal();
setModalInfo1(values);
setModalInfo2(facility.id);
} else {
createSignleFacility(values);
actions.resetForm();
}
}}
initialValues={initialValues}
validationSchema={facilitiesSchema}
>
{({
handleChange,
handleBlur,
values,
errors,
touched,
handleSubmit,
resetForm,
...formProps
}) => {
return (
<Form>
<Modal
open={openModal}
handleClose={handleCloseModal}
// props.setTypeForEdit();
userAction={() => {
return Object.keys(facility).length && facility.id
? updateSingleFacility(modalInfo1, modalInfo2)
: null;
}}
additionAction={() => props.setFacilityForEdit({})} //da resetuje formu
modalHeader={"Update type"}
modalText={"Are you shure you want to update this type?"}
/>
<TextField
margin="normal"
type="text"
fullWidth
label=" Name"
name="name"
onChange={handleChange}
onBlur={handleBlur}
value={values.name}
error={(errors.name && touched.name) || "" ? true : false}
/>
{(errors.name && touched.name) || "" ? (
<span className="text-danger">{errors.name || ""}</span>
) : null}
<TextField
margin="normal"
type="text"
fullWidth
label="Facility Price"
name="price"
onChange={handleChange}
onBlur={handleBlur}
value={values.price}
error={(errors.price && touched.price) || "" ? true : false}
/>
{(errors.price && touched.price) || "" ? (
<span className="text-danger">{errors.price || ""}</span>
) : null}
{/* OVDE MODAL */}
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
margin="normal"
>
Submit
</Button>
</Form>
);
}}
</Formik>
</Container>
) : <CircularProgress /> ? (
<CircularProgress />
) : null}
{/* Ako nema parametara u ruteru da se ne vrti spinner */}
</>
);
};
//
export default CreateOrEditFacilities;
<file_sep>/fe/src/components/admin/rooms/EditRoomType.js
import React from "react";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import {
Button,
TextField,
Container,
CircularProgress
} from "@material-ui/core";
import { createRoomType, updateRoomType } from "@endpoints/rooms";
import Modal from "../Modal";
//initial values formik
const editUserSchema = Yup.object().shape({
name: Yup.string()
.min(2, "Minimum number of characters is 2")
.max(5000)
.required("Name is required"),
bed_count: Yup.number()
.min(1, "Minimum number of characters is 1")
.max(5000)
.required("Bed count is required"),
max_persons: Yup.number()
.min(1, "Minimum number of characters is 1")
.max(5000)
.required("Maximum number of persons is required"),
price_adult: Yup.number()
.min(1, "Minimum number of characters is 1")
.max(5000)
.required("Price for Adults is required"),
price_child: Yup.number()
.min(1, "Minimum number of characters is 1")
.max(5000)
.required("Price for Children is required")
});
const EditRoomType = ({ type, ...props }) => {
// const [type, setType] = useState({});
const [openModal, setOpenModal] = React.useState(false);
const [modalInfo1, setModalInfo1] = React.useState();
const [modalInfo2, setModalInfo2] = React.useState();
function handleClickOpenModal(userId) {
setOpenModal(true);
}
function handleCloseModal() {
setOpenModal(false);
}
const createType = async credentials => {
const { data, error } = await createRoomType(credentials);
if (data) {
props.getAllRoomTypes();
console.log("type created", data.data);
} else if (error) {
console.log(error.response);
}
};
const updateType = async (credentials, id) => {
const { data, error } = await updateRoomType(credentials, id);
if (data) {
props.getAllRoomTypes();
console.log("type updated", data.data);
} else if (error) {
console.log(error.response);
}
};
const initialValues = {
name: type.name ? type.name : "",
bed_count: type.bed_count ? type.bed_count : "",
max_persons: type.max_persons ? type.max_persons : "",
price_adult: type.price_adult ? type.price_adult : "",
price_child: type.price_child ? type.price_child : ""
};
console.log("edit types props", type);
return (
<>
{Object.keys(type).length || true ? (
<Container maxWidth="md">
<h1 className="large text-primary">Add or edit room type</h1>
<Formik
enableReinitialize
onSubmit={(values, actions) => {
console.log("Edit or create type", values);
if (Object.keys(type).length && type.id) {
handleClickOpenModal();
setModalInfo1(values);
setModalInfo2(type.id);
} else {
createType(values);
actions.resetForm();
}
}}
initialValues={initialValues}
validationSchema={editUserSchema}
>
{({
handleChange,
handleBlur,
values,
errors,
touched,
handleSubmit,
resetForm,
...formProps
}) => {
return (
<Form>
<Modal
open={openModal}
handleClose={handleCloseModal}
// props.setTypeForEdit();
userAction={() => {
return Object.keys(type).length && type.id
? updateType(modalInfo1, modalInfo2)
: null;
}}
additionAction={() => props.setTypeForEdit({})} //da resetuje formu
modalHeader={"Update type"}
modalText={"Are you shure you want to update this type?"}
/>
<TextField
margin="normal"
type="text"
fullWidth
label=" Name"
name="name"
onChange={handleChange}
onBlur={handleBlur}
value={values.name}
error={(errors.name && touched.name) || "" ? true : false}
/>
{(errors.name && touched.name) || "" ? (
<span className="text-danger">{errors.name || ""}</span>
) : null}
<TextField
margin="normal"
type="text"
fullWidth
label="Bed Count"
name="bed_count"
onChange={handleChange}
onBlur={handleBlur}
value={values.bed_count}
error={
(errors.bed_count && touched.bed_count) || ""
? true
: false
}
/>
{(errors.bed_count && touched.bed_count) || "" ? (
<span className="text-danger">
{errors.bed_count || ""}
</span>
) : null}
<TextField
margin="normal"
type="text"
fullWidth
label="Maximum Persons"
name="max_persons"
onChange={handleChange}
onBlur={handleBlur}
value={values.max_persons}
error={
(errors.max_persons && touched.max_persons) || ""
? true
: false
}
/>
{(errors.max_persons && touched.max_persons) || "" ? (
<span className="text-danger">
{errors.max_persons || ""}
</span>
) : null}
<TextField
margin="normal"
type="text"
fullWidth
label="Price for Adults"
name="price_adult"
onChange={handleChange}
onBlur={handleBlur}
value={values.price_adult}
error={
(errors.price_adult && touched.price_adult) || ""
? true
: false
}
/>
{(errors.price_adult && touched.price_adult) || "" ? (
<span className="text-danger">
{errors.price_adult || ""}
</span>
) : null}
<TextField
margin="normal"
type="text"
fullWidth
label="Price for Children"
name="price_child"
onChange={handleChange}
onBlur={handleBlur}
value={values.price_child}
error={
(errors.price_child && touched.price_child) || ""
? true
: false
}
/>
{(errors.price_child && touched.price_child) || "" ? (
<span className="text-danger">
{errors.price_child || ""}
</span>
) : null}
{/* OVDE MODAL */}
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
margin="normal"
>
Submit
</Button>
</Form>
);
}}
</Formik>
</Container>
) : <CircularProgress /> ? (
//Object.keys(props.match).length && props.match.params.userId
<CircularProgress />
) : null}
{/* Ako nema parametara u ruteru da se ne vrti spinner */}
</>
);
};
//
export default EditRoomType;
<file_sep>/fe/src/components/admin/dashboard/NewUsers.js
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import {
makeStyles,
Button,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper,
CircularProgress,
Card,
Divider,
CardContent,
Typography
} from "@material-ui/core";
import { getUsersPerPage } from "@endpoints/users";
import "@zendeskgarden/react-pagination/dist/styles.css";
const useStyles = makeStyles(theme => ({
root: {
backgroundColor: theme.palette.background.paper
}
}));
function NewUsers() {
const [totalPages, setTotalPages] = useState(null);
const [users, setUsers] = useState([]);
const classes = useStyles();
const setPages = async (page = 1) => {
const { data, error } = await getUsersPerPage(page);
if (data) {
console.log("users fetched", data.data);
// setUsers(data.data.data);
await setTotalPages(data.data.meta.pagination.total_pages);
} else if (error) {
console.log(error.response);
}
};
const getUsersPerPageHandle = async page => {
const { data, error } = await getUsersPerPage(page);
if (data) {
console.log("users fetched", data.data);
setUsers(data.data.data);
// setTotalPages(data.data.meta.pagination.total_pages);
} else if (error) {
console.log(error.response);
}
};
//Inicijalno ucitavanje s tim da ucitava poslednju stranicu
useEffect(() => {
if (!users.length) setPages(1);
}, [users]);
useEffect(() => {
if (totalPages) getUsersPerPageHandle(totalPages);
}, [totalPages]);
return (
<div className="text-center w-full">
{users.length ? (
<>
<div className="from-top " />
<Card className="md:w-11/12 w-full mx-auto">
<Paper className={classes.root}>
<CardContent className="flex justify-end items-center">
<Typography
variant="body2"
color="textSecondary"
component="p"
style={{ marginRight: "auto" }}
>
latest registered users
</Typography>
<Link to="/admin/users">
<Button variant="contained">
Users
<i className="pl-4 text-lg far fa-arrow-alt-circle-right " />
</Button>
</Link>
<Divider style={{ marginTop: "10px" }} />
</CardContent>
<Table className="">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell align="left">Lastname</TableCell>
<TableCell align="left">Email</TableCell>
</TableRow>
</TableHead>
<TableBody>
{users.map(user => (
<TableRow key={user.id}>
<TableCell component="th" scope="row">
{user.first_name}
</TableCell>
<TableCell align="left">{user.last_name}</TableCell>
<TableCell align="left">{user.email}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
</Card>
</>
) : (
<CircularProgress />
)}
</div>
);
}
export default NewUsers;
<file_sep>/fe/src/components/layout/responsiveHeader/Navbar.js
import React from "react";
import { NavLink, Link } from "react-router-dom";
import Logo from "@assets/images/logo.png";
import { useSelector, useDispatch } from "react-redux";
const Navbar = ({ menuIsActive, setMenuIsActive }) => {
const isAdmin = useSelector(state => state.user.isAdmin);
const isAuthenticated = useSelector(state => state.user.isAuthenticated);
const dispatch = useDispatch();
let menuPosition;
if (menuIsActive) {
menuPosition = "0px";
} else {
menuPosition = "-100%";
}
const handleLogout = () => {
setMenuIsActive();
dispatch({ type: "LOGOUT_USER" });
};
return (
<>
<div
className="h-screen lg:hidden left-0 fixed p-4 top-0 w-full "
style={{
transition: "all 0s",
left: menuPosition,
zIndex: "190",
background: "rgba(0,0,0,0.6)",
overflow: "hidden"
}}
onClick={setMenuIsActive}
/>
<div
className="h-screen lg:hidden bg-gray-800 left-0 fixed p-4 top-0 w-2/3 sm:w-1/2 md:w-1/3"
style={{ transition: "all 0.5s", left: menuPosition, zIndex: "200" }}
>
<div className="flex justify-between text-white text-2xl">
<Link onClick={setMenuIsActive} to="/user">
<i className="fas fa-user mr-4" />
</Link>
<div className="self-center">
<img
src={Logo}
alt="quantox logo"
className=""
style={{
margin: "0 auto",
width: "50%"
}}
/>
</div>
<button onClick={setMenuIsActive}>
<i className="fas fa-chevron-left" />
</button>
</div>
<nav className="w-full text-gray-200" style={{ margin: "0 auto" }}>
<div className="flex flex-col mt-4">
<NavLink
onClick={setMenuIsActive}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/"
>
HOME
</NavLink>
<NavLink
onClick={setMenuIsActive}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/booking"
>
BOOKING
</NavLink>
{/* <NavLink
onClick={setMenuIsActive}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/rooms"
>
ROOMS
</NavLink> */}
<NavLink
onClick={setMenuIsActive}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/events"
>
EVENTS
</NavLink>
<NavLink
onClick={setMenuIsActive}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/services"
>
SERVICES
</NavLink>
<NavLink
onClick={setMenuIsActive}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/gallery"
>
GALLERY
</NavLink>
<NavLink
onClick={setMenuIsActive}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/reviews"
>
REVIEWS
</NavLink>
<NavLink
onClick={setMenuIsActive}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/contact-us"
>
CONTACT US
</NavLink>
{isAuthenticated ? (
<>
<NavLink
onClick={handleLogout}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/"
>
LOGOUT
</NavLink>
{isAdmin ? (
<NavLink
onClick={setMenuIsActive}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/admin"
>
ADMIN PANEL
</NavLink>
) : null}
</>
) : (
<>
<NavLink
onClick={setMenuIsActive}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/login"
>
LOGIN
</NavLink>
<NavLink
onClick={setMenuIsActive}
className="w-full mr-4 font-semibold border-b border-white hover:border-white py-4 navlink-transition tracking-widest"
to="/register"
>
REGISTER
</NavLink>
</>
)}
</div>
</nav>
</div>
</>
);
};
export default Navbar;
<file_sep>/fe/src/components/layout/responsiveHeader/Header.js
import React from "react";
import Button from "@material-ui/core/Button";
import MenuIcon from "@material-ui/icons/Menu";
import Logo from "@assets/images/logo.png";
import IconButton from "@material-ui/core/IconButton";
import Badge from "@material-ui/core/Badge";
import { withStyles } from "@material-ui/core/styles";
import ShoppingCartIcon from "@material-ui/icons/ShoppingCart";
import { useSelector } from "react-redux";
import { NavLink } from "react-router-dom";
// Components
import Navbar from "./Navbar";
const StyledBadge = withStyles(theme => ({
badge: {
top: "50%",
right: -3,
// The border color match the background color.
border: `2px solid ${
theme.palette.type === "light"
? theme.palette.grey[200]
: theme.palette.grey[900]
}`
}
}))(Badge);
const Header = () => {
const [menuIsActive, setMenuIsActive] = React.useState(false);
const promotions = useSelector(state => state.cart.promotions);
const rooms = useSelector(state => state.cart.rooms);
let cartItems = promotions.length + rooms.length;
return (
<>
<div
className="flex justify-between md:hidden fixed top-0 left-0 w-full"
style={{ zIndex: "150", background: "rgba(0,0,0,0.6)" }}
>
<div className="self-center">
<Button onClick={() => setMenuIsActive(true)}>
<MenuIcon style={{ color: "#fff", fontSize: "3rem" }} />
</Button>
</div>
<div className="text-center self-center">
<img
src={Logo}
alt="quantox logo"
className=""
style={{
margin: "0 auto",
width: "60%"
}}
/>
</div>
<div className="self-center">
<NavLink
className="font-semibold hover:text-gray-300 mr-2"
to="/cart"
>
<IconButton
aria-label="Cart"
className="text-white"
style={{ color: "#fff" }}
>
<StyledBadge badgeContent={cartItems} color="primary">
<ShoppingCartIcon />
</StyledBadge>
</IconButton>
</NavLink>
</div>
</div>
<Navbar
menuIsActive={menuIsActive}
setMenuIsActive={() => setMenuIsActive(false)}
/>
</>
);
};
export default Header;
<file_sep>/fe/src/components/common/context/ContextProvider.js
import React from "react";
import withSizes from "react-sizes";
export const WidthContext = React.createContext();
const WindowWidthProvider = props => {
return (
<WidthContext.Provider value={{ windowWidth: props.windowWidth }}>
{props.children}
</WidthContext.Provider>
);
};
const mapSizesToProps = props => {
return {
windowWidth: props.width
};
};
export default withSizes(mapSizesToProps)(WindowWidthProvider);
<file_sep>/fe/src/services/http/endpoints/rooms.js
import http from "../index";
import toResponse from "@helpers/toResponse";
export const getAllRooms = pageNum => {
return toResponse(http.get(`/rooms?page=${pageNum}&include=facilities`));
};
export const getRoomById = id => {
return toResponse(
http.get(`/rooms/${id}?include=roomType,facilities,gallery`)
);
};
export const createRoom = credentials => {
return toResponse(http.post("/rooms", credentials));
};
export const deleteRoom = roomId => {
return toResponse(http.delete(`/rooms/${roomId}`));
};
export const getRoom = roomId => {
return toResponse(http.get(`/rooms/${roomId}`));
};
export const updateRoom = (credentials, roomId) => {
return toResponse(http.patch(`/rooms/${roomId}`, credentials));
};
// ROOM TYPES
export const createRoomType = credentials => {
return toResponse(http.post(`/roomtypes`, credentials));
};
export const updateRoomType = (credentials, id) => {
return toResponse(http.patch(`/roomtypes/${id}`, credentials));
};
export const getRoomTypes = roomTypePage => {
return toResponse(http.get(`/roomtypes?page=${roomTypePage}`));
};
export const deleteRoomType = roomTypeId => {
return toResponse(http.delete(`/roomtypes/${roomTypeId}`));
};
//ROOM FACILITIES
//facilities?page=2"
export const getFacilities = page => {
return toResponse(http.get(`/facilities?page=${page}`));
};
//single
export const getFacilitiy = facilityId => {
return toResponse(http.get(`/facilities/${facilityId}`));
};
export const createFacility = credentials => {
return toResponse(http.post(`/facilities`, credentials));
};
export const deleteFacilitiy = facilityId => {
return toResponse(http.delete(`/facilities/${facilityId}`));
};
export const updateFacility = (credentials, facilityId) => {
return toResponse(http.patch(`/facilities/${facilityId}`, credentials));
};
<file_sep>/fe/src/components/admin/Newsletter.js
import React from "react";
const Newsletter = () => {
return (
<>
<div>NEWSLETTER</div>
</>
);
};
export default Newsletter;
<file_sep>/fe/src/services/http/endpoints/services.js
//http://api.quantox-hotel.loc/v1/services
import http from "../index";
import toResponse from "@helpers/toResponse";
export const getServices = () => {
return toResponse(http.get(`/services`));
};
<file_sep>/fe/src/components/admin/subscribers/components/NewCampaign.js
import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
import { createNewCapmpaign } from "@endpoints/subscribe";
const NewCampaign = ({ Alert }) => {
const [subject, setSubject] = useState("");
const [template, setTemplate] = useState("");
const handleSubmit = async e => {
e.preventDefault();
const { data, error } = await createNewCapmpaign({
subject,
html: template
});
if (data) {
console.log(data.data);
Alert.success(<i className="fas fa-check" />, {
effect: "slide",
timeout: 2000,
position: "bottom-right"
});
} else if (error) {
console.log(error.response);
}
};
return (
<div>
<h1 className="text-gray-600 text-center text-xl italic my-8">
Create and send new campaign to subscribers
</h1>
<form onSubmit={handleSubmit}>
<TextField
id="standard-name"
fullWidth
label="Subject"
className=""
onChange={e => setSubject(e.target.value)}
/>
<TextField
id="standard-name"
multiline
fullWidth
label="Paste HTML here"
className="mt-8"
style={{ marginTop: "60px" }}
onChange={e => setTemplate(e.target.value)}
/>
<br />
<div className="flex justify-end">
<Button
variant="contained"
color="primary"
type="submit"
style={{ marginTop: "30px" }}
>
Send
</Button>
</div>
</form>
</div>
);
};
export default NewCampaign;
<file_sep>/fe/src/components/login/Login.js
import React, { useEffect } from "react";
import { Link } from "react-router-dom";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import { useSelector, useDispatch } from "react-redux";
import { login, getProfile } from "@actions/authActions";
import { Button, TextField, Container } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles(theme => ({
submit: {
padding: 10,
margin: theme.spacing(3, 0, 2)
}
}));
const Login = props => {
useEffect(() => {
document.title = "Quantox Hotel - Login";
}, []);
// const responseErrors = useSelector(state => state.user.responseErrors);
// const dispatch = useDispatch();
const errors = useSelector(state => state.user.serverErrors);
const dispatch = useDispatch();
const initialValues = {
email: "",
password: ""
};
const loginSchema = Yup.object().shape({
email: Yup.string()
.label("Email")
.email()
.required(),
password: Yup.string()
.required("Password <PASSWORD>")
.min(5, "Password must be at least 6 characters")
.max(50, "Too LONG!.")
});
// useEffect(() => {
// if (Object.keys(responseErrors).length) {
// if (responseErrors.email) {
// set""(responseErrors.email);
// }
// if (responseErrors.password) {
// set""(responseErrors.password);
// }
// }
// }, [responseErrors]);
const classes = useStyles();
return (
<>
<div className="header-image" />
<h1 className="home-header text-center text-2xl text-gray-600 z-50 mb-16">
<i className="fas fa-user mr-4" /> Sign into Your Account
</h1>
<Container maxWidth="md">
{errors.login ? (
<h1 className="py-4 text-red-800 text-center">{errors.login}</h1>
) : null}
<Formik
onSubmit={async values => {
try {
await dispatch(login(values, props.history));
await dispatch(getProfile());
} catch (err) {
console.log(err.response);
}
}}
initialValues={initialValues}
validationSchema={loginSchema}
>
{({
handleChange,
handleBlur,
values,
errors,
touched,
...props
}) => {
return (
<Form>
<TextField
margin="normal"
type="email"
fullWidth
label="Email Address"
name="email"
onChange={handleChange}
onBlur={handleBlur}
value={values.email}
error={(errors.email && touched.email) || "" ? true : false}
/>
{(errors.email && touched.email) || "" ? (
<span className="text-danger">{errors.email || ""}</span>
) : null}
<TextField
type="password"
name="password"
margin="normal"
fullWidth
label="Password"
onChange={handleChange}
onBlur={handleBlur}
value={values.password}
error={
(errors.password && touched.password) || "" ? true : false
}
/>
{(errors.password && touched.password) || "" ? (
<span className="text-danger">{errors.password || ""}</span>
) : null}
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
margin="normal"
className={classes.submit}
>
Log In
</Button>
</Form>
);
}}
</Formik>
<p className="text-right">
Don't have an account?{" "}
<Link to="/register">
<Button variant="outlined" color="default">
Sign Up
</Button>
</Link>
</p>
</Container>
<div className="w-full h-32" />
</>
);
};
export default Login;
<file_sep>/fe/src/components/admin/promotions/Promotions.js
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
import CreateOrEditPromotion from "./CreatePromotions";
import AppBar from "@material-ui/core/AppBar";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import {
makeStyles,
Button,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper,
CircularProgress,
Typography
} from "@material-ui/core";
import { getPromotionsPerPage, deletePromotion } from "@endpoints/promotions";
import "@zendeskgarden/react-pagination/dist/styles.css";
import { ThemeProvider } from "@zendeskgarden/react-theming";
import { Pagination } from "@zendeskgarden/react-pagination";
import Modal from "../Modal";
function TabContainer(props) {
return (
<Typography component="div" style={{ padding: 8 * 3 }}>
{props.children}
</Typography>
);
}
TabContainer.propTypes = {
children: PropTypes.node.isRequired
};
function LinkTab(props) {
return (
<Tab
component="a"
onClick={event => {
event.preventDefault();
}}
{...props}
/>
);
}
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
backgroundColor: theme.palette.background.paper
}
}));
// PROMOTIONS PANEL
const PromotionsComponent = props => {
const [totalPages, setTotalPages] = useState("");
const [promotions, setPromotions] = useState([]);
const [currentPage, setCurrentPage] = useState(1); //for api
const [openModal, setOpenModal] = React.useState(false);
const [modalPromotion, setModalPromotion] = React.useState("");
React.useEffect(() => {
document.title = "Quantox Hotel - Admin Panel - Promotions";
}, []);
//per page
const getAllPromotions = async page => {
const { data, error } = await getPromotionsPerPage(page);
if (data) {
setPromotions(data.data.data);
setTotalPages(data.data.meta.pagination.total_pages);
console.log("Promotions fetched", data.data);
} else if (error) {
console.log(error.response);
}
};
// Delete PROMOTION
const deleteSinglePromotion = async id => {
const { data, error } = await deletePromotion(id);
if (promotions.length === 1) {
setCurrentPage(currentPage - 1);
console.log("ostao jos jedan");
}
if (data) {
if (props.getAll && promotions.length > 1) {
getAllPromotions(currentPage);
}
console.log("Review Deleted", data);
} else if (error) {
console.log(error.response);
}
};
//Kada se menja strana paginacije
useEffect(() => {
if (promotions.length) {
if (props.getAll) {
getAllPromotions(currentPage);
}
}
}, [currentPage, promotions.length, props.getAll]);
//Inicijalno ucitavanje, zavisno od taba
useEffect(() => {
if (props.getAll) {
getAllPromotions(currentPage);
}
}, [currentPage, props.getAll]);
function handleClickOpenModal(id) {
setModalPromotion(id);
setOpenModal(true);
}
function handleCloseModal() {
setOpenModal(false);
}
return (
<>
{promotions.length ? (
<>
<Modal
open={openModal}
handleClose={handleCloseModal}
userAction={() => deleteSinglePromotion(modalPromotion)}
modalHeader={"Delete Promotion"}
modalText={"Are you shure you want to delete this room promotion?"}
/>
<Paper>
<Table>
<TableHead>
<TableRow>
<TableCell>Promotion Name</TableCell>
<TableCell align="left">Promotion Description</TableCell>
<TableCell size="small" align="left">
{" "}
Discount
</TableCell>
<TableCell align="left">Discount for Children</TableCell>
<TableCell align="left">Price</TableCell>
<TableCell align="left">Price for Children</TableCell>
<TableCell align="left">Starting At</TableCell>
<TableCell align="left">Ending At</TableCell>
<TableCell align="left">Active</TableCell>
<TableCell align="left">Edit</TableCell>
<TableCell align="left">Delete</TableCell>
</TableRow>
</TableHead>
<TableBody>
{promotions.map(promotion => (
<TableRow key={promotion.id}>
<TableCell align="left">{promotion.name}</TableCell>
<TableCell align="left" padding="none">
{" "}
{promotion.description}{" "}
</TableCell>
<TableCell>{promotion.discount}</TableCell>
<TableCell>{promotion.discount_children}</TableCell>
<TableCell>{promotion.price}</TableCell>
<TableCell>{promotion.price_children}</TableCell>
<TableCell>{promotion.starting_at}</TableCell>
<TableCell>{promotion.ending_at}</TableCell>
<TableCell>{promotion.active}</TableCell>
<TableCell align="left">
{" "}
<Link to="#">
<Button
// onClick={() => approveSingleReview(review.id)}
variant="contained"
color="primary"
>
Edit
</Button>
</Link>
</TableCell>
<TableCell align="left">
{" "}
<Button
onClick={() => handleClickOpenModal(promotion.id)}
variant="contained"
color="secondary"
>
Delete
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
{totalPages > 1 ? (
<ThemeProvider>
<Pagination
totalPages={totalPages}
currentPage={currentPage}
onChange={currentPage => {
console.log("current page", currentPage);
return setCurrentPage(currentPage);
}}
/>
</ThemeProvider>
) : null}
</>
) : (
<CircularProgress />
)}
</>
);
};
//CREATE OR EDIT PROMOTION
const Promotions = () => {
const classes = useStyles();
const [value, setValue] = React.useState(0);
function handleChange(event, newValue) {
setValue(newValue);
}
return (
<div className={classes.root} style={{ marginTop: "50px" }}>
<AppBar position="static">
<Tabs variant="fullWidth" value={value} onChange={handleChange}>
<LinkTab label="All Promotions" href="/drafts" />
<LinkTab
label="*NEXT VERSION FEATURE* - Create or Edit Promotion "
href="/trash"
disabled
/>
</Tabs>
</AppBar>
{value === 0 && (
<TabContainer>
{/* Reviwes on Hold */}
<PromotionsComponent getAll />
</TabContainer>
)}
{value === 1 && (
<TabContainer>
{" "}
<CreateOrEditPromotion />
</TabContainer>
)}
</div>
);
};
export default Promotions;
<file_sep>/fe/src/components/admin/events/Events.js
import React, { useState, useEffect } from "react";
import { getAllEvents, deleteEvent } from "@endpoints/events";
import { makeStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Tabs from "@material-ui/core/Tabs";
import TabContainer from "../subscribers/components/TabContainer";
import LinkTab from "../subscribers/components/LinkTab";
import CreateEvent from "./components/CreateEvent";
import {
Button,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper,
CircularProgress
} from "@material-ui/core";
import "@zendeskgarden/react-pagination/dist/styles.css";
import { ThemeProvider } from "@zendeskgarden/react-theming";
import { Pagination } from "@zendeskgarden/react-pagination";
import Modal from "../Modal";
import Alert from "react-s-alert";
const useStyles = makeStyles(theme => ({
root: {
backgroundColor: theme.palette.background.paper,
input: {
marginLeft: 8,
flex: 1
},
root2: {
flexGrow: 1,
backgroundColor: theme.palette.background.paper
},
iconButton: {
padding: 5
},
divider: {
width: 1,
height: 28,
margin: 4
}
}
}));
const Events = () => {
const [openModal, setOpenModal] = React.useState(false);
const [value, setValue] = React.useState(0);
const [currentPage, setCurrentPage] = useState(1); //for api
const [totalPages, setTotalPages] = useState(1);
const [events, setEvents] = useState([]);
const [eventId, setEventId] = useState("");
const [editId, setEditid] = useState("");
React.useEffect(() => {
document.title = "Quantox Hotel - Admin Panel - Events";
}, []);
useEffect(() => {
setEditid("");
getData(currentPage);
}, [value, currentPage]);
async function getData(page) {
const { data, error } = await getAllEvents(page);
if (data) {
console.log(data.data);
setEvents(data.data.data);
setTotalPages(data.data.meta.pagination.total_pages);
} else if (error) {
console.log(error.response);
}
}
const deleteEventById = async id => {
const { data, error } = await deleteEvent(id);
if (data) {
console.log(data.data);
getData(currentPage);
} else if (error) {
console.log(error.response);
}
};
function handleChange(event, newValue) {
setValue(newValue);
}
function handleClickOpenModal(id) {
setEventId(id);
setOpenModal(true);
}
function handleCloseModal() {
setOpenModal(false);
}
const handleEdit = id => {
setValue(1);
setEditid(id);
};
const classes = useStyles();
return (
<div className={classes.root2} style={{ marginTop: "55px" }}>
<Alert />
<AppBar position="static">
<Tabs variant="fullWidth" value={value} onChange={handleChange}>
<LinkTab label="All events" href="/drafts" />
<LinkTab label="Create new event" href="/trash" />
</Tabs>
</AppBar>
{value === 0 && (
<TabContainer>
<div className="text-center">
<Modal
open={openModal}
handleClose={handleCloseModal}
userAction={() => deleteEventById(eventId)}
modalHeader={"Remove event"}
modalText={"Are you shure you want to delete this event?"}
/>
{events.length ? (
<>
<Paper className={classes.root}>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell>Title</TableCell>
<TableCell align="right" className=" cell-sm">
Edit
</TableCell>
<TableCell align="right" className="cell-sm">
Delete
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{events.map(event => (
<TableRow key={event.id}>
<TableCell component="th" scope="row">
<span className="italic font-semibold text-gray-600 text-lg">
{event.title}
</span>
</TableCell>
<TableCell align="right" className="cell-md">
<Button
onClick={() => handleEdit(event.id)}
variant="contained"
color="primary"
className={classes.button}
>
EDIT
</Button>
</TableCell>
<TableCell align="right" className="cell-md">
<Button
onClick={() => handleClickOpenModal(event.id)}
variant="contained"
color="secondary"
className={`${classes.button}`}
>
DELETE
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
{totalPages > 1 ? (
<div className="mt-8 mb-16">
<ThemeProvider>
<Pagination
totalPages={totalPages}
currentPage={currentPage}
onChange={currentPage => {
console.log("current page", currentPage);
return setCurrentPage(currentPage);
}}
/>
</ThemeProvider>
</div>
) : null}
</>
) : (
<CircularProgress />
)}
</div>
</TabContainer>
)}
{value === 1 && (
<TabContainer>
<CreateEvent Alert={Alert} id={editId} setValue={() => setValue(0)} />
</TabContainer>
)}
</div>
);
};
export default Events;
<file_sep>/fe/craco.config.js
const path = require("path");
module.exports = {
webpack: {
alias: {
"@": path.resolve(__dirname, "src"),
"@assets": path.resolve(__dirname, "src/assets"),
"@components": path.resolve(__dirname, "src/components"),
"@common": path.resolve(__dirname, "src/components/common"),
"@store": path.resolve(__dirname, "src/store"),
"@actions": path.resolve(__dirname, "src/store/actions"),
"@helpers": path.resolve(__dirname, "src/helpers"),
"@endpoints": path.resolve(__dirname, "src/services/http/endpoints")
}
}
};
<file_sep>/fe/src/components/reviews/Review.js
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Card, CardContent, Typography, Divider } from "@material-ui/core";
const useStyles = makeStyles({
card: {
// maxWidth: "100%"
},
media: {
height: 210
},
fab: {
left: "50%",
transform: "translate(-50%,-50%)"
}
});
const Review = ({
hotel_rate,
room_rate,
accommodation_rate,
comment,
user
}) => {
const classes = useStyles();
// console.log("REVIEW PROPS", hotel_rate, room_rate, accommodation_rate);
const averageRating = (hotel_rate + room_rate + accommodation_rate) / 3;
// console.log(averageRating);
return (
<Card className={`${classes.card} hover:shadow-2xl mb-6`}>
<CardContent className="flex justify-between">
<Typography variant="h6" component="h2" align="left">
{user ? user.data.first_name : "No name"}
</Typography>
<Typography
variant="h6"
color="textSecondary"
component="h2"
align="right"
gutterBottom
>
Average rating : {Math.ceil(averageRating * 100) / 100}
</Typography>
</CardContent>
<Divider variant="middle" />
<CardContent className="flex flex-col justify-between">
<div className="flex justify-between items-center">
<Typography variant="h6" component="h2" align="left">
Hotel Rate
</Typography>
<meter
min="0"
max="10"
optimum="10"
low="4"
high="7"
value={hotel_rate * 2}
className="w-9/12"
/>
</div>
<div className="flex justify-between items-center">
<Typography variant="h6" component="h2" align="left">
Room Rate
</Typography>
<meter
min="0"
max="10"
optimum="10"
low="4"
high="7"
value={room_rate * 2}
className="w-9/12"
/>
</div>
<div className="flex justify-between items-center">
<Typography
variant="h6"
component="h2"
align="left"
style={{ overflowWrap: "break-word" }}
>
Acomodation Rate
</Typography>
<meter
min="0"
max="10"
optimum="10"
low="4"
high="7"
value={accommodation_rate * 2}
className="w-9/12"
/>
</div>
</CardContent>
<Divider variant="middle" />
<CardContent className="flex flex-wrap justify-between">
<Typography variant="h6" component="h2" align="left">
Comment :
</Typography>
<Typography
variant="body2"
color="textSecondary"
component="p"
className="w-full mt-0 mt-4 md:w-9/12 text-justify"
>
{comment}
</Typography>
</CardContent>
<Divider variant="fullWidth" />
</Card>
);
};
export default Review;
<file_sep>/fe/src/components/user/components/InputModal.js
import React from "react";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogTitle from "@material-ui/core/DialogTitle";
import { updateUserInfo } from "../../../services/http/endpoints/users";
const InputModal = ({ open, close, infoField, userId, getUserData }) => {
const [editValue, setEditValue] = React.useState("");
const handleSubmit = async () => {
console.log(infoField);
const { data, error } = await updateUserInfo(
{ [infoField]: editValue },
userId
);
if (data) {
console.log(data);
getUserData();
} else if (error) {
console.log(error.response);
}
close();
};
return (
<div>
<Dialog open={open} onClose={close} aria-labelledby="form-dialog-title">
<DialogTitle id="form-dialog-title">
Edit {infoField && infoField}
</DialogTitle>
<DialogContent>
<TextField
autoFocus
margin="dense"
type="text"
onChange={e => setEditValue(e.target.value)}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={close} color="primary">
Close
</Button>
<Button onClick={handleSubmit} color="primary">
Submit
</Button>
</DialogActions>
</Dialog>
</div>
);
};
export default InputModal;
<file_sep>/fe/src/components/admin/rooms/Rooms.js
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import {
makeStyles,
Button,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper,
CircularProgress
} from "@material-ui/core";
import { getAllRooms, deleteRoom } from "@endpoints/rooms";
import "@zendeskgarden/react-pagination/dist/styles.css";
import { ThemeProvider } from "@zendeskgarden/react-theming";
import { Pagination } from "@zendeskgarden/react-pagination";
import Modal from "../Modal";
import Alert from "react-s-alert";
const useStyles = makeStyles(theme => ({
root: {
backgroundColor: theme.palette.background.paper
}
}));
//DISABLE ON CLICK RIPPLE
function Rooms() {
const classes = useStyles();
const [currentPage, setCurrentPage] = useState(1); //for api
const [totalPages, setTotalPages] = useState(1);
const [rooms, setRooms] = useState([]);
const [openModal, setOpenModal] = React.useState(false);
const [modalRoom, setModalRoom] = React.useState(""); //stores data of current room id for modal
React.useEffect(() => {
document.title = "Quantox Hotel - Admin Panel - Rooms";
}, []);
function handleClickOpenModal(id) {
setModalRoom(id);
setOpenModal(true);
}
function handleCloseModal() {
setOpenModal(false);
}
const getRooms = async page => {
const { data, error } = await getAllRooms(page);
if (data) {
console.log("Rooms fetched", data.data);
setRooms(data.data.data);
setTotalPages(data.data.meta.pagination.total_pages);
} else if (error) {
console.log(error.response);
}
};
const deleteSingleRoom = async roomId => {
const { data, error } = await deleteRoom(roomId);
if (data) {
Alert.success("Room Deleted!");
getRooms(currentPage);
handleCloseModal();
} else if (error) {
console.log(error.response);
}
};
//Kada se menja strana paginacije
useEffect(() => {
if (rooms.length) getRooms(currentPage);
}, [currentPage, rooms]);
//Inicijalno ucitavanje
useEffect(() => {
if (!rooms.length) getRooms(currentPage);
}, [rooms, currentPage]);
console.log("room id", modalRoom);
return (
<div className="text-center" style={{ marginTop: "42px" }}>
<Alert />
<Modal
open={openModal}
handleClose={handleCloseModal}
userAction={() => deleteSingleRoom(modalRoom)}
modalHeader={"Delete Room Type"}
modalText={"Are you shure you want to delete this room type?"}
/>
<div className="from-top" />
{rooms.length ? (
<>
<Paper className={`${classes.root} table-container`}>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell className="cell-md" align="left">
Room No
</TableCell>
<TableCell className="cell-sm" align="left">
Usable
</TableCell>
<TableCell size="small" align="left">
Edit Room
</TableCell>
<TableCell align="left">Delete Room</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rooms.map(room => (
<TableRow key={room.id}>
<TableCell className="cell-sm" align="left">
{room.room_number}
</TableCell>
<TableCell className="cell-sm" align="left">
{room.usable ? "true" : "false"}
</TableCell>
<TableCell align="left">
{" "}
<Link to={`/admin/rooms/edit/${room.id}`}>
<Button
onClick={() => {
// setTypeForEdit(type);
}}
variant="contained"
color="primary"
className={classes.button}
>
Edit Room
</Button>
</Link>
</TableCell>
<TableCell align="left">
{" "}
<Button
onClick={() => handleClickOpenModal(room.id)}
variant="contained"
color="secondary"
className={classes.button}
>
Delete Room
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
<ThemeProvider>
<Pagination
totalPages={totalPages}
currentPage={currentPage}
onChange={currentPage => {
console.log("current page", currentPage);
return setCurrentPage(currentPage);
}}
/>
</ThemeProvider>{" "}
</>
) : (
<CircularProgress />
)}
</div>
);
}
export default Rooms;
<file_sep>/fe/src/components/admin/dashboard/DashboardPromotions.js
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
Button,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper,
CircularProgress,
Card,
CardContent,
Badge,
Typography
} from "@material-ui/core";
import { getPromotionsPerPage } from "@endpoints/promotions";
import "@zendeskgarden/react-pagination/dist/styles.css";
// PROMOTIONS PANEL
const DashboardPromotions = () => {
const [totalPages, setTotalPages] = useState(null);
const [promotions, setPromotions] = useState([]);
//per page
const setPages = async page => {
const { data, error } = await getPromotionsPerPage(page);
if (data) {
setTotalPages(data.data.meta.pagination.total_pages);
console.log("Promotions fetched", data.data);
} else if (error) {
console.log(error.response);
}
};
const getAllPromotions = async page => {
const { data, error } = await getPromotionsPerPage(page);
if (data) {
setPromotions(data.data.data);
console.log("Promotions fetched", data.data);
} else if (error) {
console.log(error.response);
}
};
useEffect(() => {
setPages();
}, []);
useEffect(() => {
if (totalPages) {
getAllPromotions(totalPages);
}
}, [totalPages]);
return (
<div className="text-center w-full">
<>
<div className="from-top " />
{promotions.length ? (
<Card className="md:w-11/12 w-full mx-auto">
<Paper>
<CardContent className="flex justify-end">
<Typography
variant="body2"
color="textSecondary"
component="p"
style={{ marginRight: "auto" }}
>
latest promotions
</Typography>
<Link to="/admin/promotions">
<Button variant="contained">
Promotions
<i className="pl-4 text-lg far fa-arrow-alt-circle-right " />
</Button>
</Link>
</CardContent>
<Table>
<TableHead>
<TableRow>
<TableCell className="cell-md">Promotion Name</TableCell>
<TableCell className="cell-sm" align="left">
Starting At
</TableCell>
<TableCell className="cell-xs" align="left">
Ending At
</TableCell>
<TableCell className="cell-xs" align="left">
Active
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{promotions.map(promotion => (
<TableRow key={promotion.id}>
<TableCell align="left">{promotion.name}</TableCell>
<TableCell className="cell-sm">
{promotion.starting_at}
</TableCell>
<TableCell className="cell-sm">
{promotion.ending_at}
</TableCell>
<TableCell className="cell-xs">
{promotion.active ? (
<Badge color="primary" variant="dot" />
) : (
<Badge color="secondary" variant="dot" />
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
</Card>
) : (
<CircularProgress />
)}
</>
</div>
);
};
//CREATE OR EDIT PROMOTION
export default DashboardPromotions;
<file_sep>/fe/src/components/layout/header/TopHeader.js
import React from "react";
import Logo from "@assets/images/logo.png";
import { NavLink } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { Link } from "react-router-dom";
import IconButton from "@material-ui/core/IconButton";
import Badge from "@material-ui/core/Badge";
import { withStyles } from "@material-ui/core/styles";
import ShoppingCartIcon from "@material-ui/icons/ShoppingCart";
const StyledBadge = withStyles(theme => ({
badge: {
top: "50%",
right: -3,
// The border color match the background color.
border: `2px solid ${
theme.palette.type === "light"
? theme.palette.grey[200]
: theme.palette.grey[900]
}`
}
}))(Badge);
const TopHeader = () => {
const user = useSelector(state => state.user);
const promotions = useSelector(state => state.cart.promotions);
const rooms = useSelector(state => state.cart.rooms);
const dispatch = useDispatch();
let cartItems = promotions.length + rooms.length;
return (
<div className="pt-16 bg-blue w-full flex absolute t-0 left-0 z-50 px-8 ">
<div className="text-white w-1/4 text-left">
<p>
<i className="mr-2 fas fa-phone-alt" />
+31 (0) 20 507 0000
</p>
<div className="text-left mt-4">
<a href="/" className="mr-4">
<i className="fab fa-facebook-square" />
</a>
<a href="/" className="mr-4">
<i className="fab fa-linkedin" />
</a>
<a href="/" className="mr-4">
<i className="fab fa-twitter-square" />
</a>
<a href="/">
<i className="fab fa-instagram" />
</a>
</div>
</div>
<div className="w-2/4 text-center">
<img
src={Logo}
alt="quantox logo"
className=""
style={{
margin: "0 auto"
}}
/>
</div>
<div className="text-white w-1/4 text-right">
{user.isAuthenticated ? (
<div>
<div>
<button
className="font-semibold hover:text-gray-300 mr-2"
onClick={() => dispatch({ type: "LOGOUT_USER" })}
>
LOGOUT
</button>
<Link to="/user">
<i className="fas fa-user mx-4 " />
</Link>
<NavLink
className="font-semibold hover:text-gray-300"
to="/cart"
>
<IconButton
aria-label="Cart"
className="text-white"
style={{ color: "#fff" }}
>
<StyledBadge badgeContent={cartItems} color="primary">
<ShoppingCartIcon />
</StyledBadge>
</IconButton>
</NavLink>
</div>
</div>
) : (
<>
<NavLink
className="mr-4 font-semibold hover:text-gray-300"
to="/login"
>
LOGIN
</NavLink>
<NavLink
className="font-semibold hover:text-gray-300 mr-4"
to="/register"
>
REGISTER
</NavLink>
<NavLink className="font-semibold hover:text-gray-300" to="/cart">
<IconButton
aria-label="Cart"
className="text-white"
style={{ color: "#fff" }}
>
<StyledBadge badgeContent={cartItems} color="primary">
<ShoppingCartIcon />
</StyledBadge>
</IconButton>
</NavLink>
</>
)}
</div>
</div>
);
};
export default TopHeader;
<file_sep>/fe/src/components/admin/reservations/Reservations.js
import React, { useState, useEffect } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Moment from "react-moment";
import {
Button,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper,
CircularProgress
} from "@material-ui/core";
import "@zendeskgarden/react-pagination/dist/styles.css";
import { ThemeProvider } from "@zendeskgarden/react-theming";
import { Pagination } from "@zendeskgarden/react-pagination";
import Modal from "../Modal";
import { getAllReservations, deleteReservation } from "@endpoints/reservations";
const useStyles = makeStyles(theme => ({
root: {
backgroundColor: theme.palette.background.paper,
input: {
marginLeft: 8,
flex: 1
},
root2: {
flexGrow: 1,
backgroundColor: theme.palette.background.paper
},
iconButton: {
padding: 10
},
divider: {
width: 1,
height: 28,
margin: 4
}
}
}));
function Reservations() {
const [openModal, setOpenModal] = React.useState(false);
const [id, setId] = React.useState("");
const [currentPage, setCurrentPage] = useState(1); //for api
const [totalPages, setTotalPages] = useState(1);
const [reservations, setReservations] = useState("");
React.useEffect(() => {
document.title = "Quantox Hotel - Admin Panel - Reservations";
getReservations(currentPage);
}, [currentPage]);
useEffect(() => {
if (reservations.length) getReservations(currentPage);
}, [currentPage, reservations]);
function handleClickOpenModal(id) {
setId(id);
setOpenModal(true);
}
function handleCloseModal() {
setOpenModal(false);
}
const classes = useStyles();
const getReservations = async page => {
const { data, error } = await getAllReservations(page);
if (data) {
console.log(" fetched", data.data);
setReservations(data.data.data);
setTotalPages(data.data.meta.pagination.total_pages);
} else if (error) {
console.log(error.response);
}
};
const deleteReservationById = async id => {
const { data, error } = await deleteReservation(id);
if (data) {
console.log(data);
handleCloseModal();
getReservations(currentPage);
} else if (error) {
console.log(error.response);
}
};
return (
<div className={classes.root2} style={{ marginTop: "82px" }}>
<div className="text-center">
<Modal
open={openModal}
handleClose={handleCloseModal}
userAction={() => deleteReservationById(id)}
modalHeader={"Remove subscriber"}
modalText={"Are you shure you want to delete this subscriber?"}
/>
{reservations.length ? (
<>
<Paper className={`${classes.root} responsive`}>
<Table className="asdasdasdas">
<TableHead>
<TableRow>
<TableCell className="cell-md" align="left">
Created At
</TableCell>
<TableCell className="cell-sm" align="left">
Rooms
</TableCell>
<TableCell align="left">Client</TableCell>
<TableCell align="left">Phone</TableCell>
<TableCell className="cell-sm" align="right">
Delete
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{reservations.map(item => (
<TableRow key={item.real_id}>
<TableCell
align="left"
style={{
fontWeight: "bold",
fontSize: "1rem",
fontStyle: "italic"
}}
>
<Moment format="MM/DD/YYYY">
{item.created_at.date}
</Moment>
</TableCell>
<TableCell>
{item.rooms
? item.rooms.data.map(room => {
return <span> {room.room_number} </span>;
})
: null}
</TableCell>
<TableCell>
{item.user.data.first_name} {item.user.data.last_name}
</TableCell>
<TableCell>{item.user.data.phone_number}</TableCell>
<TableCell align="right">
<Button
onClick={() => handleClickOpenModal(item.id)}
variant="contained"
color="secondary"
className={classes.button}
title="Delete reservation"
>
X
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
{totalPages > 1 ? (
<div className="mt-8 mb-16">
<ThemeProvider>
<Pagination
totalPages={totalPages}
currentPage={currentPage}
onChange={currentPage => {
console.log("current page", currentPage);
return setCurrentPage(currentPage);
}}
/>
</ThemeProvider>
</div>
) : null}
</>
) : (
<CircularProgress />
)}
</div>
</div>
);
}
export default Reservations;
<file_sep>/fe/src/store/reducers/cartReducer.js
const initialState = {
promotions: [],
rooms: []
};
export const cartReducer = (state = initialState, action) => {
switch (action.type) {
case "ADD_PROMOTION":
return {
...state,
promotions: [...state.promotions, action.payload]
};
case "ADD_ROOM":
return {
...state,
rooms: [...state.rooms, action.payload]
};
case "DELETE_ROOM":
let roomId = action.payload;
let newArr = state.rooms.filter(item => {
return item.room_id !== roomId;
});
return {
...state,
rooms: newArr
};
case "DELETE_PROMOTION":
let promotionId = action.payload;
let newArr1 = state.promotions.filter(item => {
return item.promotion_id !== promotionId;
});
return {
...state,
promotions: newArr1
};
case "RESERVATION_COMPLETED":
return {
...state,
promotions: [],
rooms: []
};
default:
return state;
}
};
<file_sep>/fe/src/components/admin/Admin.js
import React, { useEffect } from "react";
import clsx from "clsx";
import ExpandLess from "@material-ui/icons/ExpandLess";
import ExpandMore from "@material-ui/icons/ExpandMore";
import { makeStyles, useTheme } from "@material-ui/core/styles";
import { deepOrange, deepPurple, grey } from "@material-ui/core/colors";
import Dashboard from "./dashboard/Dashboard";
import Users from "./users/Users";
import Gallery from "./gallery/Gallery";
import CreateGallery from "./gallery/CreateGallery";
import Newsletter from "./Newsletter";
import AdminReviews from "./AdminReviews";
import EditUser from "./users/EditUser";
import Rooms from "./rooms/Rooms";
import RoomTypes from "./rooms/RoomTypes";
import CreateOrEditRoom from "./rooms/CreateOrEditRoom";
import Facilities from "./rooms/Facilities";
import Profile from "./myProfile/Profile";
import Subscribers from "./subscribers/Subscribers";
import Songs from "./songs/Songs";
import Events from "./events/Events";
import EventTypes from "./events/EventTypes";
import Reservations from "./reservations/Reservations";
import { useSelector, useDispatch } from "react-redux";
import Promotions from "./promotions/Promotions";
import {
Avatar,
Collapse,
ListItemText,
ListItemIcon,
ListItem,
List,
Divider,
Icon,
AppBar,
Toolbar,
Drawer
} from "@material-ui/core";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import { WidthContext } from "@components/common/context/ContextProvider";
import { Switch, Route, NavLink, Link, Redirect } from "react-router-dom";
const drawerWidth = 240;
const useStyles = makeStyles(theme => ({
avatar: {},
orangeAvatar: {
margin: 0,
color: "#fff",
backgroundColor: deepOrange[500]
},
purpleAvatar: {
margin: 0,
padding: 0,
color: "#fff",
backgroundColor: deepPurple[500]
},
nested: {
paddingLeft: 20,
backgroundColor: grey[400]
},
submenu: { backgroundColor: grey[300] },
appBar: {
transition: theme.transitions.create(["margin", "width"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
})
},
appBarShift: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
transition: theme.transitions.create(["margin", "width"], {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen
})
},
menuButton: {
marginRight: theme.spacing(2)
},
hide: {
display: "none"
},
drawer: {
width: drawerWidth,
flexShrink: 0
},
drawerPaper: {
width: drawerWidth
},
drawerHeader: {
display: "flex",
alignItems: "center",
padding: "0 8px",
...theme.mixins.toolbar,
justifyContent: "flex-end"
},
content: {
flexGrow: 1,
padding: theme.spacing(3),
transition: theme.transitions.create("margin", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
}),
marginLeft: -drawerWidth
},
contentShift: {
transition: theme.transitions.create("margin", {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen
}),
marginLeft: 0
}
}));
const Admin = props => {
const classes = useStyles();
const theme = useTheme();
const [open, setOpen] = React.useState(true);
const [openProfile, setOpenProfile] = React.useState(false);
const [openUsers, setOpenUsers] = React.useState(false);
const [openGallery, setOpenGallery] = React.useState(false);
const [openRooms, setOpenRooms] = React.useState(false);
const [openEvents, setOpenEvents] = React.useState(false);
const { windowWidth } = React.useContext(WidthContext);
const dispatch = useDispatch();
const isAdmin = useSelector(state => state.user.isAdmin);
const userName = useSelector(state => state.user.info.data.first_name);
//for nav menu
useEffect(() => {
if (props.location.pathname === "/admin") {
props.history.push("/admin/dashboard");
}
if (windowWidth < 768) {
setOpen(false);
} else {
setOpen(true);
}
}, [windowWidth, props.history, props.location.pathname]);
function handleDrawerOpen() {
setOpen(true);
}
function handleDrawerClose() {
setOpen(false);
}
console.log("admin props", props);
return (
<>
{isAdmin ? (
<>
<div className="h-screen flex">
{/* <CssBaseline /> */}
<AppBar
// position="fixed"
className={clsx(classes.appBar, {
[classes.appBarShift]: open
})}
>
<Toolbar className="flex justify-between">
<IconButton
color="inherit"
aria-label="Open drawer"
onClick={handleDrawerOpen}
edge="start"
className={clsx(classes.menuButton, open && classes.hide)}
>
<MenuIcon />
</IconButton>
<ListItem>
<ListItemIcon>
<Avatar className={classes.purpleAvatar}>
<i className="fas fa-user" />
</Avatar>
</ListItemIcon>
<ListItemText primary={userName} />
</ListItem>
<div className="hidden md:block w-2/12">
<p
style={{ transition: "all 0.1s" }}
className="mx-4 py-2 rounded-lg w-20"
>
v-1.0.3
</p>
</div>
<div className="hidden md:block w-2/12">
<Link
style={{ transition: "all 0.1s" }}
to="/"
className="flex px-2 flex-no-wrap items-center justify-center text-center py-2 bg-red-600 hover:bg-red-400"
>
<p className="">CLOSE PANEL</p>
</Link>
</div>
</Toolbar>
</AppBar>
<Drawer
className={classes.drawer}
variant="persistent"
anchor="left"
open={open}
classes={{
paper: classes.drawerPaper
}}
>
<div className={classes.drawerHeader}>
<IconButton onClick={handleDrawerClose}>
{theme.direction === "ltr" ? (
<ChevronLeftIcon />
) : (
<ChevronRightIcon />
)}
</IconButton>
</div>
<Divider />
{/* odavde krece lista nav menija */}
<List
component="nav"
aria-labelledby="nested-list-subheader"
className={classes.root}
>
<ListItem button onClick={() => setOpenProfile(!openProfile)}>
<ListItemIcon>
<Avatar className={classes.purpleAvatar}>
<i className="fas fa-user" />
</Avatar>
</ListItemIcon>
<ListItemText primary={userName} />
{openProfile ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Divider component="li" variant="middle" />
<Collapse
in={openProfile}
timeout="auto"
unmountOnExit
className={classes.nested}
>
<NavLink to="/admin/myprofile">
<List component="div" className={classes.submenu}>
<ListItem button>
<ListItemText primary="My Profile" />
</ListItem>
</List>
</NavLink>
</Collapse>
{/* ///////////////////////////////////////////////// profile */}
<NavLink to="/admin/dashboard">
<ListItem button>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "fas fa-columns")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Dashboard" />
</ListItem>
</NavLink>
{/* //////////////////////////// end dashboard ///////////////////////////// */}
<Divider component="li" variant="middle" />
<ListItem button onClick={() => setOpenUsers(!openUsers)}>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "fas fa-users")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Users " />
{openUsers ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Divider component="li" variant="middle" />
<Collapse
in={openUsers}
timeout="auto"
unmountOnExit
className={classes.nested}
>
<List component="div" className={classes.submenu}>
<NavLink to="/admin/users" activeClassName="admin-link">
<ListItem button>
<ListItemText primary="Users" />
</ListItem>
</NavLink>
{/* <NavLink
to="/admin/users/edit"
activeClassName="admin-link"
>
<ListItem button>
<ListItemText primary="Edit User" />
</ListItem>
</NavLink> */}
</List>
</Collapse>
{/* end users */}
<ListItem button onClick={() => setOpenRooms(!openRooms)}>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "far fa-building")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Rooms" />
{openRooms ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Divider component="li" variant="middle" />
<Collapse
in={openRooms}
timeout="auto"
unmountOnExit
className={classes.nested}
>
<List component="div" className={classes.submenu}>
<NavLink
exact
to="/admin/rooms"
activeClassName="admin-link"
>
<ListItem button>
<ListItemText primary="All Rooms" />
</ListItem>
</NavLink>
<NavLink
to="/admin/rooms/create"
activeClassName="admin-link"
>
<ListItem button>
<ListItemText primary="Create Room" />
</ListItem>
</NavLink>
<NavLink
to="/admin/rooms/types"
activeClassName="admin-link"
>
<ListItem button>
<ListItemText primary="Room Types" />
</ListItem>
</NavLink>
<NavLink
to="/admin/rooms/facilities"
activeClassName="admin-link"
>
<ListItem button>
<ListItemText primary="Room Facilities" />
</ListItem>
</NavLink>
</List>
</Collapse>
{/* ////////////////////// end ROOMS ///////////////////////////*/}
<NavLink
exact
to="/admin/promotions"
activeClassName="admin-link"
>
<ListItem button>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "fas fa-ad")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Promotions" />
</ListItem>
</NavLink>
<Divider component="li" variant="middle" />
{/* //////////////////////// END PROMOTIONS//////////////////// */}
<ListItem button onClick={() => setOpenGallery(!openGallery)}>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "far fa-images")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Gallery" />
{openGallery ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Divider component="li" variant="middle" />
<Collapse
in={openGallery}
timeout="auto"
unmountOnExit
className={classes.nested}
>
<List component="div" className={classes.submenu}>
{/* <NavLink
exact
to="/admin/gallery"
activeClassName="admin-link"
>
<ListItem button>
<ListItemText primary="All galleries" />
</ListItem>
</NavLink> */}
<NavLink
to="/admin/gallery/create"
activeClassName="admin-link"
>
<ListItem button>
<ListItemText
primary="Create Gallery"
secondary="Beta Feature"
/>{" "}
</ListItem>
</NavLink>
{/* <ListItem button>
<ListItemText primary="Edit Gallery" />
</ListItem> */}
</List>
</Collapse>
{/* ////////////////////// end gallery ///////// */}
<ListItem button onClick={() => setOpenEvents(!openEvents)}>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "far fa-calendar-alt")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Events" />
{openEvents ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Divider component="li" variant="middle" />
<Collapse
in={openEvents}
timeout="auto"
unmountOnExit
className={classes.nested}
>
<List component="div" className={classes.submenu}>
<NavLink
exact
to="/admin/events"
activeClassName="admin-link"
>
<ListItem button>
<ListItemText primary="All Events" />
</ListItem>
</NavLink>
<NavLink
to="/admin/events/types"
activeClassName="admin-link"
>
<ListItem button>
<ListItemText primary="Event Types" />
</ListItem>
</NavLink>
</List>
</Collapse>
<NavLink
exact
to="/admin/reservations"
activeClassName="admin-link"
>
<ListItem button>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "far fa-calendar-check")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Reservations" />
</ListItem>
</NavLink>
{/* ///////// end events//////// */}
<NavLink
exact
to="/admin/subscribers"
activeClassName="admin-link"
>
<ListItem button>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "fas fa-mail-bulk")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Newsletter" />
</ListItem>
</NavLink>
{/* END NEWSLETTER */}
<NavLink exact to="/admin/reviews" activeClassName="admin-link">
<ListItem button>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "fas fa-star")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Reviews" />
</ListItem>
</NavLink>
{/* END REVIEWS */}
<NavLink exact to="/admin/songs" activeClassName="admin-link">
<ListItem button>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "fas fa-music")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Songs" />
</ListItem>
</NavLink>
{/* END SONGS */}
<ListItem
button
onClick={() => {
dispatch({ type: "LOGOUT_USER" });
props.history.replace("/");
}}
>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "fas fa-sign-out-alt")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Logout" />
</ListItem>
{windowWidth < 768 ? (
<>
<ListItem
button
onClick={() => {
props.history.push("/");
}}
>
<ListItemIcon>
<Icon
className={clsx(classes.icon, "fas fa-outdent")}
color="action"
/>
</ListItemIcon>
<ListItemText primary="Close panel" />
</ListItem>
<p className="text-center ">v-1.0.3</p>
</>
) : null}
</List>
<Divider />
</Drawer>
<main
className={`${clsx(classes.content, {
[classes.contentShift]: open
})} responsive`}
>
<div
style={{
flex: 1,
flexDirection: "column",
textAlign: "center"
}}
>
<Switch>
<Route exact path={`/admin/myprofile`} component={Profile} />
<Route
exact
path={`/admin/dashboard`}
component={Dashboard}
/>
<Route exact path={`/admin/users`} component={Users} />
<Route
exact
path={`/admin/users/edit`}
component={EditUser}
/>
<Route
exact
path={`/admin/users/edit/:userId`}
component={EditUser}
/>
<Route exact path={`/admin/rooms`} component={Rooms} />
<Route
exact
path={`/admin/rooms/create`}
component={CreateOrEditRoom}
/>
<Route
exact
path={`/admin/rooms/edit/:roomId`}
component={CreateOrEditRoom}
/>
<Route
exact
path={`/admin/rooms/types`}
component={RoomTypes}
/>
<Route
exact
path={`/admin/rooms/facilities`}
component={Facilities}
/>
<Route exact path={`/admin/gallery`} component={Gallery} />
<Route
exact
path={`/admin/gallery/create`}
component={CreateGallery}
/>
<Route
exact
path={`/admin/newsletter`}
component={Newsletter}
/>
<Route
exact
path={`/admin/reviews`}
component={AdminReviews}
/>
<Route
exact
path={`/admin/promotions`}
component={Promotions}
/>
<Route
exact
path={`/admin/subscribers`}
component={Subscribers}
/>
<Route exact path={`/admin/events`} component={Events} />
<Route
exact
path={`/admin/reservations`}
component={Reservations}
/>
<Route
exact
path={`/admin/events/types`}
component={EventTypes}
/>
<Route exact path={`/admin/songs`} component={Songs} />
</Switch>
</div>
</main>
</div>
</>
) : (
<Redirect to="/login" />
)}
</>
);
};
export default Admin;
<file_sep>/fe/src/components/contactUs/components/ContactForm.js
import React from "react";
import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import { Field, Formik, Form, ErrorMessage } from "formik";
import * as Yup from "yup";
const useStyles = makeStyles(theme => ({
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: "100%"
}
}));
const ContactForm = () => {
const classes = useStyles();
const Schema = Yup.object().shape({
name: Yup.string()
.label("Name")
.min(3, "Name is to short")
.max(20, "Too LONG!.")
.required("Name is required"),
email: Yup.string()
.email("Must be a vaild email")
.required("Email is required"),
message: Yup.string()
.required("Message is required")
.min(5, "Message to short")
.max(200, "Too LONG!.")
});
const initialValues = {
name: "",
message: "",
email: ""
};
return (
<div>
<h1 className="home-header text-3xl text-gray-600 text-center">
Send Us A Message
</h1>
<Formik
initialValues={initialValues}
validationSchema={Schema}
onSubmit={values => {
console.log(values);
}}
render={props => (
<Form>
<Field name="name">
{({ field }) => (
<TextField
id="standard-textarea"
label="Your Name"
className={classes.textField}
margin="normal"
{...field}
/>
)}
</Field>
<ErrorMessage name="name">
{mssg => (
<small className="block text-center text-red-600">{mssg}</small>
)}
</ErrorMessage>
<Field name="email">
{({ field }) => (
<TextField
id="standard-textarea"
label="Your Email"
className={classes.textField}
margin="normal"
{...field}
/>
)}
</Field>
<ErrorMessage name="email">
{mssg => (
<small className="block text-center text-red-600">{mssg}</small>
)}
</ErrorMessage>
<Field name="message">
{({ field }) => (
<TextField
id="standard-textarea"
label="Message..."
className={classes.textField}
multiline
margin="normal"
{...field}
/>
)}
</Field>
<ErrorMessage name="message">
{mssg => (
<small className="block text-center text-red-600">{mssg}</small>
)}
</ErrorMessage>
<div className="mt-4 flex justify-end">
<Button
variant="contained"
color="primary"
type="submit"
className="mt-4"
>
Send
</Button>
</div>
</Form>
)}
/>
</div>
);
};
export default ContactForm;
<file_sep>/fe/src/components/admin/AdminReviews.js
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
import AppBar from "@material-ui/core/AppBar";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import {
makeStyles,
Button,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper,
CircularProgress,
Typography
} from "@material-ui/core";
import {
getReviewsOnHold,
getReviewsApproved,
getPage,
approveReview,
deleteReview
} from "@endpoints/reviews";
import "@zendeskgarden/react-pagination/dist/styles.css";
import { ThemeProvider } from "@zendeskgarden/react-theming";
import { Pagination } from "@zendeskgarden/react-pagination";
function TabContainer(props) {
return (
<Typography component="div" style={{ padding: 8 * 3 }}>
{props.children}
</Typography>
);
}
TabContainer.propTypes = {
children: PropTypes.node.isRequired
};
function LinkTab(props) {
return (
<Tab
component="a"
onClick={event => {
event.preventDefault();
}}
{...props}
/>
);
}
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
backgroundColor: theme.palette.background.paper
}
}));
// REVIEWS ON HOLD ////////////////////////////////
const ReviewsComponent = props => {
const [totalPages, setTotalPages] = useState("");
const [reviews, setReviews] = useState([]);
const [currentPage, setCurrentPage] = useState(1); //for api
//per page
const getAllReviews = async page => {
const { data, error } = await getPage(page);
if (data) {
setReviews(data.data.data);
setTotalPages(data.data.meta.pagination.total_pages);
console.log("Reviews fetched", data.data);
} else if (error) {
console.log(error.response);
}
};
// REVIEWS ON HOLD
const getAllReviewsOnHold = async page => {
const { data, error } = await getReviewsOnHold(page);
if (data) {
setReviews(data.data.data);
setTotalPages(data.data.meta.pagination.total_pages);
console.log("Reviews on hold fetched", data.data);
} else if (error) {
console.log(error.response);
}
};
// REVIEWS approved
const getAllReviewsApproved = async page => {
const { data, error } = await getReviewsApproved(page);
if (data) {
setReviews(data.data.data);
setTotalPages(data.data.meta.pagination.total_pages);
console.log("Reviews APPROVED fetched", data.data);
} else if (error) {
console.log(error.response);
}
};
// Approve Review
const approveSingleReview = async id => {
const { data, error } = await approveReview(id);
if (data) {
if (props.onHold) {
getAllReviewsOnHold(currentPage);
}
console.log("Review Approved", data);
} else if (error) {
console.log(error.response);
}
};
// Delete review
const deleteSingleReview = async id => {
const { data, error } = await deleteReview(id);
if (reviews.length === 1) {
setCurrentPage(currentPage - 1);
console.log("ostao jos jedan");
}
if (data) {
if (props.onHold && reviews.length > 1) {
getAllReviewsOnHold(currentPage);
}
if (props.approved && reviews.length > 1) {
console.log("ovo ME ZEZA ", reviews.length);
getAllReviewsApproved(currentPage);
}
if (props.allReviews && reviews.length > 1) {
getAllReviews(currentPage);
}
console.log("Review Deleted", data);
} else if (error) {
console.log(error.response);
}
};
//Kada se menja strana paginacije
useEffect(() => {
if (reviews.length) {
if (props.onHold) {
getAllReviewsOnHold(currentPage);
} else if (props.approved) {
getAllReviewsApproved(currentPage);
} else if (props.allReviews) {
getAllReviews(currentPage);
}
}
}, [
currentPage,
props.onHold,
props.allReviews,
reviews.length,
props.approved
]);
//Inicijalno ucitavanje, zavisno od taba
useEffect(() => {
if (props.onHold) {
getAllReviewsOnHold(currentPage);
} else if (props.approved) {
getAllReviewsApproved(currentPage);
} else if (props.allReviews) {
getAllReviews(currentPage);
}
}, [props.onHold, currentPage, props.approved, props.allReviews]);
//ako je na poslednjoj strani obrisan poslednji unos, da ucita stranicu ispred
// useEffect(() => {
// if (reviews.length === 0 && currentPage !== 1) {
// getAllReviewsOnHold(currentPage);
// }
// }, [reviews]);
console.log("karent pejdz", currentPage);
console.log("duzina reviews niza", reviews.length);
return (
<>
{reviews.length ? (
<>
<Paper>
<Table>
<TableHead>
<TableRow>
<TableCell>Comment</TableCell>
<TableCell align="left">Hotel Rate </TableCell>
<TableCell size="small" align="left">
Room Rate
</TableCell>
<TableCell align="left">Accomodation Rate</TableCell>
{props.onHold ? (
<TableCell align="left">Approve Review</TableCell>
) : null}
<TableCell align="left">Decline Review</TableCell>
</TableRow>
</TableHead>
<TableBody>
{reviews.map(review => (
<TableRow key={review.id}>
<TableCell align="left">{review.comment}</TableCell>
<TableCell align="left" padding="none">
<meter
min="0"
max="10"
optimum="10"
low="4"
high="7"
value={review.hotel_rate * 2}
className="w-9/12"
/>
<span className="pl-2 pr-6"> {review.hotel_rate} |</span>
</TableCell>
<TableCell align="left" padding="none">
<meter
min="0"
max="10"
optimum="10"
low="4"
high="7"
value={review.room_rate * 2}
className="w-9/12"
/>
<span className="pl-2 pr-6"> {review.room_rate} |</span>
</TableCell>
<TableCell align="left">
<meter
min="0"
max="10"
optimum="10"
low="4"
high="7"
value={review.accommodation_rate * 2}
className="w-9/12"
/>
<span className="pl-2 pr-6">
{" "}
{review.accommodation_rate} |
</span>
</TableCell>
{/* Ako postoji onHold prop da renderuje approve dugme inace ne treba */}
{props.onHold ? (
<TableCell align="left">
{" "}
<Link to="#">
<Button
onClick={() => approveSingleReview(review.id)}
variant="contained"
color="primary"
>
Approve Review
</Button>
</Link>
</TableCell>
) : null}
<TableCell align="left">
{" "}
<Button
// onClick={() => handleClickOpenModal(facility.id)}
onClick={() => deleteSingleReview(review.id)}
variant="contained"
color="secondary"
>
Decline Review
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
{totalPages > 1 ? (
<ThemeProvider>
<Pagination
totalPages={totalPages}
currentPage={currentPage}
onChange={currentPage => {
console.log("current page", currentPage);
return setCurrentPage(currentPage);
}}
/>
</ThemeProvider>
) : null}
</>
) : (
<CircularProgress />
)}
</>
);
};
const AdminReviews = () => {
const classes = useStyles();
const [value, setValue] = React.useState(0);
function handleChange(event, newValue) {
setValue(newValue);
}
return (
<div className={classes.root} style={{ marginTop: "50px" }}>
<AppBar position="static">
<Tabs variant="fullWidth" value={value} onChange={handleChange}>
<LinkTab label="Reviews on HOLD" href="/drafts" />
<LinkTab label="Approved Reviews" href="/trash" />
<LinkTab label="All Reviews" href="/spam" />
</Tabs>
</AppBar>
{value === 0 && (
<TabContainer>
{/* Reviwes on Hold */}
<ReviewsComponent onHold />
</TabContainer>
)}
{value === 1 && (
<TabContainer>
{" "}
{/* Approved Reviews */}
<ReviewsComponent approved />
</TabContainer>
)}
{value === 2 && (
<TabContainer>
{/* All Reviews */}
<ReviewsComponent allReviews />
</TabContainer>
)}
</div>
);
};
export default AdminReviews;
<file_sep>/fe/src/components/home/components/CheckBar.js
import React from "react";
import DateFnsUtils from "@date-io/date-fns";
import { DatePicker, MuiPickersUtilsProvider } from "@material-ui/pickers";
import { Link } from "react-router-dom";
import { WidthContext } from "@components/common/context/ContextProvider";
const CheckBar = () => {
const [state, setState] = React.useState({
checkIn: new Date(),
checkOut: new Date()
});
const { windowWidth } = React.useContext(WidthContext);
const handleSubmit = e => {
e.preventDefault();
console.log(state);
};
return (
<div
className="bg-white flex absolute shadow-lg py-6 w-11/12 md:block md:w-2/3 text-center"
style={{
height: windowWidth < 768 ? "auto" : "100px",
bottom: "-52px",
zIndex: "100",
left: "10px",
right: "10px",
margin: "0 auto"
}}
>
<form className="self-center" onSubmit={handleSubmit}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<div className="md:flex justify-around px-4">
<DatePicker
value={state.checkIn}
fullWidth={windowWidth < 768 ? true : false}
label="Check In"
onChange={value => setState({ ...state, checkIn: value })}
/>
<DatePicker
value={state.checkOut}
fullWidth={windowWidth < 768 ? true : false}
label="Check Out"
onChange={value => setState({ ...state, checkOut: value })}
style={{
marginBottom: windowWidth < 768 ? "40px" : "",
marginTop: windowWidth < 768 ? "20px" : ""
}}
/>
{windowWidth < 768 ? <br /> : null}
<Link
to={{
pathname: "/booking",
state
}}
className="self-center px-4 py-2 border border-gray-400 rounded-lg"
style={{
lineHeight: "18px"
}}
>
SEARCH
</Link>
</div>
</MuiPickersUtilsProvider>
</form>
</div>
);
};
export default CheckBar;
<file_sep>/fe/src/store/reducers/rootReducer.js
import { combineReducers } from "redux";
import { authReducer } from "./authReducer";
import { cartReducer } from "./cartReducer";
export default combineReducers({
user: authReducer,
cart: cartReducer
});
<file_sep>/fe/src/components/layout/navbar/Navbar.js
import React from "react";
import { NavLink } from "react-router-dom";
const Navbar = () => {
return (
<div
className="navbar text-white z-50 absolute w-full "
style={{ marginTop: "150px" }}
>
<nav className="w-full text-center" style={{ margin: "0 auto" }}>
<NavLink
exact
activeClassName="home-link"
className="mr-4 font-semibold border-b border-transparent hover:border-white pb-4 navlink-transition tracking-widest"
to="/"
>
HOME
</NavLink>
<NavLink
exact
activeClassName="home-link"
className="mr-4 font-semibold border-b border-transparent hover:border-white pb-4 navlink-transition tracking-widest"
to="/booking"
>
BOOKING
</NavLink>
{/* <NavLink
exact
activeClassName="home-link"
className="mr-4 font-semibold border-b border-transparent hover:border-white pb-4 navlink-transition tracking-widest"
to="/rooms"
>
ROOMS
</NavLink> */}
<NavLink
exact
activeClassName="home-link"
className="mr-4 font-semibold border-b border-transparent hover:border-white pb-4 navlink-transition tracking-widest"
to="/events"
>
EVENTS
</NavLink>
<NavLink
exact
activeClassName="home-link"
className="mr-4 font-semibold border-b border-transparent hover:border-white pb-4 navlink-transition tracking-widest"
to="/services"
>
SERVICES
</NavLink>
<NavLink
exact
activeClassName="home-link"
className="mr-4 font-semibold border-b border-transparent hover:border-white pb-4 navlink-transition tracking-widest"
to="/gallery"
>
GALLERY
</NavLink>
<NavLink
exact
activeClassName="home-link"
className="mr-4 font-semibold border-b border-transparent hover:border-white pb-4 navlink-transition tracking-widest"
to="/reviews"
>
REVIEWS
</NavLink>
<NavLink
exact
activeClassName="home-link"
className="mr-4 font-semibold border-b border-transparent hover:border-white pb-4 navlink-transition tracking-widest"
to="/contact-us"
>
CONTACT US
</NavLink>
</nav>
</div>
);
};
export default Navbar;
<file_sep>/fe/src/components/home/components/PromotionModal.js
import React, { useState } from "react";
import Button from "@material-ui/core/Button";
import Dialog from "@material-ui/core/Dialog";
import Typography from "@material-ui/core/Typography";
import DialogTitle from "@material-ui/core/DialogTitle";
import TextField from "@material-ui/core/TextField";
import { useDispatch } from "react-redux";
import DateFnsUtils from "@date-io/date-fns";
import { DatePicker, MuiPickersUtilsProvider } from "@material-ui/pickers";
import { getPromotionById } from "../../../services/http/endpoints/promotions";
const PromotionModal = ({ handleCloseModal, modalIsOpen, modalId, Alert }) => {
const [promoDetails, setPromoDetails] = React.useState({});
const [state, setState] = React.useState({
checkIn: new Date(),
checkOut: new Date()
});
const [adultNum, setAdultNum] = useState("");
const [childrenNum, setChildrenNum] = useState("");
React.useEffect(() => {
getData();
// eslint-disable-next-line
}, []);
const dispatch = useDispatch();
const handleSubmit = e => {
let promotion = {};
promotion.id = promoDetails.id;
promotion.started_at = state.checkIn;
promotion.ended_at = state.checkOut;
promotion.count = "1";
promotion.adults = adultNum;
promotion.children = childrenNum;
dispatch({
type: "ADD_PROMOTION",
payload: promotion
});
Alert.success(<i className="fas fa-check" />, {
effect: "slide",
timeout: 2000
});
handleCloseModal();
};
async function getData() {
const { data, error } = await getPromotionById(modalId);
if (data) {
setPromoDetails(data.data.data);
console.log(data);
} else if (error) {
console.log(error);
}
}
return (
<div>
{promoDetails.active === 1 ? (
<Dialog
onClose={handleCloseModal}
aria-labelledby="customized-dialog-title"
open={modalIsOpen}
>
<div style={{ padding: "20px" }}>
<DialogTitle id="form-dialog-title">
{promoDetails.name}
</DialogTitle>
<Typography gutterBottom>{promoDetails.description}</Typography>
</div>
<div className="px-4 md:px-0">
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<div className="flex flex-col md:flex-row justify-around">
<DatePicker
value={state.checkIn}
label="Check In"
onChange={value => setState({ ...state, checkIn: value })}
/>
<DatePicker
value={state.checkOut}
label="Check Out"
onChange={value => setState({ ...state, checkOut: value })}
/>
</div>
</MuiPickersUtilsProvider>
</div>
<div className="mt-6">
<p className="italic text-gray-600 pl-4">Guests number:</p>
<div className="flex flex-col md:flex-row justify-around px-4 md:px-0">
<TextField
id="standard-name"
label="Adults"
type="number"
value={adultNum}
onChange={e => setAdultNum(e.target.value)}
/>
<TextField
id="standard-name"
label="Chldren"
type="number"
value={childrenNum}
onChange={e => setChildrenNum(e.target.value)}
/>
</div>
</div>
<h1 className="text-red-400 italic text-center mt-8">
Next version feature
</h1>
<div className="mt-4 p-8">
<Button
onClick={handleCloseModal}
color="secondary"
variant="contained"
style={{ marginRight: "10px" }}
>
Close
</Button>
<Button
onClick={handleSubmit}
color="primary"
variant="contained"
disabled
>
Add to cart
</Button>
</div>
</Dialog>
) : null}
</div>
);
};
export default PromotionModal;
<file_sep>/fe/src/components/user/UserProfile.js
import React, { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { Button } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import InputModal from "./components/InputModal";
import AppBar from "@material-ui/core/AppBar";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import Moment from "react-moment";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";
// Components
import TabContainer from "./components/TabContainer";
import { Redirect } from "react-router-dom";
import { getLogedUser } from "@endpoints/users";
import { getAllReservations } from "@endpoints/reservations";
const useStyles = makeStyles(theme => ({
submit: {
padding: 10,
margin: theme.spacing(3, 0, 2),
root: {
flexGrow: 1,
backgroundColor: theme.palette.background.paper
}
},
root: {
width: "100%",
marginTop: theme.spacing(3),
overflowX: "auto"
},
table: {
minWidth: 650
}
}));
const UserProfile = ({ adminPanel }) => {
const user = useSelector(state => state.user.info.data);
const [modalIsOpen, setModalIsOpen] = useState(false);
const [value, setValue] = useState(0);
const [reservations, setReservations] = useState([]);
const [infoField, setInfoField] = useState("");
const [userInfo, setUserInfo] = useState({});
const classes = useStyles();
useEffect(() => {
// eslint-disable-next-line
getUserData();
// eslint-disable-next-line
getReservations();
// eslint-disable-next-line
window.scrollTo(0, 0);
// eslint-disable-next-line
}, []);
async function getUserData() {
const { data, error } = await getLogedUser();
if (data) {
console.log(data);
setUserInfo(data.data.data);
} else if (error) {
console.log(error);
}
}
async function getReservations() {
const { data, error } = await getAllReservations(user.id);
if (data) {
console.log(data);
let userReservations = data.data.data.length
? data.data.data.filter(item => {
return user.id === item.user.data.id;
})
: [];
setReservations(userReservations);
} else if (error) {
console.log(error.response);
}
}
function handleChange(event, newValue) {
setValue(newValue);
}
const handleEdit = e => {
setInfoField(e.target.id);
setModalIsOpen(true);
};
const reservationList =
reservations.length > 0 ? (
<Paper className={classes.root}>
<h1 className="p-2 italic">Reservations</h1>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell>ID</TableCell>
<TableCell align="left">Booked</TableCell>
<TableCell align="right">Total price</TableCell>
</TableRow>
</TableHead>
<TableBody>
{reservations
? reservations.map((item, index) => (
<TableRow key={index}>
<TableCell align="left">{item.real_id}</TableCell>
<TableCell align="left">
<Moment format="YYYY/MM/DD">
{item.created_at.date}
</Moment>
</TableCell>
<TableCell align="right">{item.total_price}</TableCell>
</TableRow>
))
: null}
</TableBody>
</Table>
</Paper>
) : null;
return (
<>
{user ? (
<>
{adminPanel ? null : <div className="header-image" />}
<div className="container mx-auto mt-16 px-4 pb-32">
{adminPanel ? null : (
<h1 className="">
<span className="text-4xl text-gray-600 font-semibold mr-6">
DASHBOARD
</span>
<br />
<i className="fas fa-user mr-4" />
<span>{user.first_name}</span>
</h1>
)}
<div className="mt-16 w-12/12 md:w-8/12 mx-auto">
{adminPanel ? null : (
<h1 className="text-center italic text-gray-600 my-8">
Update Your Profile
</h1>
)}
<div />
</div>
<div>
<div className={classes.root}>
<AppBar position="static">
<Tabs value={value} onChange={handleChange}>
<Tab label="User Info" />
<Tab label="User Reservations" />
</Tabs>
</AppBar>
{value === 0 && (
<TabContainer>
<div className="mt-8">
<div className="flex py-4 border-b-2 justify-between pl-2">
<p className="italic text-gray-600 leading-normal pt-2">
First Name:{" "}
<span className="font-semibold ml-4 text-lg md:text-2xl">
{userInfo.first_name
? userInfo.first_name
: "no data"}
</span>
</p>
<Button onClick={handleEdit}>
<i
id="first_name"
className="fas fa-edit text-xl leading-normal text-gray-600"
/>
</Button>
</div>
<div className="flex py-4 border-b-2 justify-between pl-2">
<p className="italic text-gray-600 leading-normal pt-2">
Last Name:{" "}
<span className="font-semibold ml-4 text-lg md:text-2xl">
{userInfo.last_name
? userInfo.last_name
: "no data"}
</span>
</p>
<Button onClick={e => handleEdit(e)}>
<i
id="last_name"
className="fas fa-edit text-xl leading-normal text-gray-600"
/>
</Button>
</div>
<div className="flex py-4 border-b-2 justify-between pl-2">
<p className="italic text-gray-600 leading-normal pt-2">
Email:{" "}
<span className="font-semibold ml-4 text-lg md:text-2xl">
{userInfo.email ? userInfo.email : "no data"}
</span>
</p>
<Button onClick={e => handleEdit(e)}>
<i
id="email"
className="fas fa-edit text-xl leading-normal text-gray-600"
/>
</Button>
</div>
<div className="flex py-4 border-b-2 justify-between pl-2">
<p className="italic text-gray-600 leading-normal pt-2">
Phone Number:{" "}
<span className="font-semibold ml-4 text-lg md:text-2xl">
{userInfo.phone_number
? userInfo.phone_number
: "no data"}
</span>
</p>
<Button onClick={e => handleEdit(e)}>
<i
id="phone_number"
className="fas fa-edit text-xl leading-normal text-gray-600"
/>
</Button>
</div>
<div className="flex py-4 border-b-2 justify-between pl-2">
<p className="italic text-gray-600 leading-normal pt-2">
Address:{" "}
<span className="font-semibold ml-4 text-lg md:text-2xl">
{userInfo.address ? userInfo.address : "no data"}
</span>
</p>
<Button onClick={e => handleEdit(e)}>
<i
id="address"
className="fas fa-edit text-xl leading-normal text-gray-600"
/>
</Button>
</div>
<div className="flex py-4 border-b-2 justify-between pl-2">
<p className="italic text-gray-600 leading-normal pt-2">
City:{" "}
<span className="font-semibold ml-4 text-lg md:text-2xl">
{userInfo.city ? userInfo.city : "no data"}
</span>
</p>
<Button onClick={e => handleEdit(e)}>
<i
id="city"
className="fas fa-edit text-xl leading-normal text-gray-600"
/>
</Button>
</div>
</div>
</TabContainer>
)}
{value === 1 && <TabContainer>{reservationList}</TabContainer>}
</div>
</div>
<InputModal
infoField={infoField}
open={modalIsOpen}
getUserData={getUserData}
userId={user.id && user.id}
close={() => setModalIsOpen(false)}
/>
</div>
</>
) : (
<Redirect to="/login" />
)}
</>
);
};
export default UserProfile;
<file_sep>/fe/src/components/booking/components/RoomDetails.js
import React, { useState, useEffect } from "react";
import Room from "@components/rooms/components/Room";
import Drawer from "@material-ui/core/Drawer";
// import Dialog from "@material-ui/core/Dialog";
import { getRoomById } from "../../../services/http/endpoints/rooms";
const RoomDetails = ({ id, open, close }) => {
const [data, setData] = useState({});
useEffect(() => {
getData(id);
}, [id]);
async function getData(id) {
const { data, error } = await getRoomById(id);
if (data) {
console.log(data);
setData(data.data.data);
} else if (error) {
console.log(error.response);
}
}
return (
<div>
{/* <Dialog
open={open}
fullWidth
onClose={close}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<div>
<Room data={data} fullWidth close={close} />
</div>
</Dialog> */}
<Drawer anchor="right" open={open} onClose={close}>
<div style={{ maxWidth: "600px", margin: "0 auto" }}>
<Room data={data} fullWidth close={close} />
</div>
</Drawer>
</div>
);
};
export default RoomDetails;
<file_sep>/fe/src/components/events/components/Event.js
import React from "react";
import { useSelector } from "react-redux";
import { joinToEvent } from "../../../services/http/endpoints/events";
import room1 from "@assets/images/rooms/room1.jpg";
import Alert from "react-s-alert";
import "react-s-alert/dist/s-alert-default.css";
import "react-s-alert/dist/s-alert-css-effects/slide.css";
import { makeStyles } from "@material-ui/core/styles";
import { WidthContext } from "@components/common/context/ContextProvider";
import {
Card,
CardActions,
CardContent,
CardMedia,
Typography,
Button
} from "@material-ui/core";
const useStyles = makeStyles({
card: {
display: "flex"
},
media: {
height: "100%",
width: "30vw"
},
content: {
paddin: "20px 20px"
}
});
const Event = ({ event, join }) => {
const { windowWidth } = React.useContext(WidthContext);
const user = useSelector(state => state.user);
const joinUserToEvent = async () => {
const { data, error } = await joinToEvent(event.id);
if (data) {
console.log("joined to event", data);
handleSuccess();
} else if (error) {
console.log(error);
}
};
const classes = useStyles();
const handleSuccess = () => {
Alert.success(<i className="fas fa-check" />, {
effect: "slide",
timeout: 2000
});
};
return (
<div className="px-4 md:px-0">
<Card
className={`${classes.card} hover:shadow-2xl`}
style={{ flexDirection: windowWidth < 1024 ? "column" : "row" }}
>
<div>
<CardMedia
className={`${classes.media} relative `}
image={room1}
title={event.title}
style={{
width: windowWidth < 1024 ? "100vw" : "30vw",
height: windowWidth < 1024 ? "260px" : "100%"
}}
/>
</div>
<div className={join ? "md:pl-16 pb-8" : null}>
<CardContent className={classes.content}>
<Typography gutterBottom variant="h5" component="h2" align="center">
{event.title}
</Typography>
<Typography
variant="body2"
color="textSecondary"
component="p"
className="py-8"
>
{event.description}
</Typography>
<br />
<div className="flex w-full justify-between">
<div>
<Typography variant="body2" color="textSecondary" component="p">
Starting at:
<br />
<span className="font-semibold">{event.started_at}</span>
<br />
</Typography>
</div>
<div>
<Typography variant="body2" color="textSecondary" component="p">
Capacity: <br />
<span className="font-semibold">{event.capacity}</span>
</Typography>
</div>
</div>
</CardContent>
{join && user.isAuthenticated ? (
<CardActions>
<Button
variant="contained"
color="primary"
onClick={joinUserToEvent}
>
JOIN
</Button>
</CardActions>
) : null}
</div>
</Card>
<Alert />
</div>
);
};
export default Event;
|
357b6867ec7f1bf3eef4a5835792d678a8826adb
|
[
"JavaScript"
] | 61 |
JavaScript
|
Bangula/hotel
|
cc51714dad99e6677453fb566484ebf5589e730e
|
98f434b3a5e1e269aecf2b5103001eed6ee0a153
|
refs/heads/master
|
<file_sep>import numpy as np
import math
import matplotlib.pyplot as plt
import random
import time
class gift_wrapping:
def __init__(self, data, data_name=""):
self.data = np.array(data)
self.data_name = data_name
# Returns the point with lowest y coordinate and highest x coordinate
def find_lowest_right(self):
lower_y = float("inf")
for point in self.data:
if point[1] < lower_y:
lower_y = point[1]
lower = point
return list(lower)
# Returns the target point with the lowest angle from the line c-b
def lowest_angle(self, b, c):
low_angle = float("inf")
for a in self.data:
if a[0] != b[0] or a[1] != b[1]:
if a[0] != c[0] or a[1] != c[1]:
u = [c[0] - b[0], c[1] - b[1]]
v = [a[0] - b[0], a[1] - b[1]]
mag_u = math.sqrt((u[0]) ** 2 + (u[1]) ** 2)
mag_v = math.sqrt((v[0]) ** 2 + (v[1]) ** 2)
u = [u[0] / mag_u, u[1] / mag_u]
v = [v[0] / mag_v, v[1] / mag_v]
angle = math.acos(u[0] * v[0] + u[1] * v[1])
orient = b[0] * c[1] + b[1] * a[0] + c[0] * a[1] - a[0] * c[1] - a[1] * b[0] - c[0] * b[1]
if orient < 0:
angle = 2 * math.pi - angle
if angle < low_angle:
low_angle = angle
low_point = a
return list(low_point)
# Main function for the convex hull algorithm
def convex_hull(self):
a = self.find_lowest_right()
b = self.lowest_angle(a, [1, a[1]])
init = a
hull = [a]
while b[0] != init[0] or b[1] != init[1]:
hull.append(b)
a = b
b = self.lowest_angle(a, hull[-2])
return hull
# Ploting the algorithm results
def plot_hull(self):
fig, ax = plt.subplots()
ax.set_title(self.data_name)
ax.scatter(self.data[:, 0], self.data[:, 1])
hull = self.convex_hull()
for i in range(len(hull)):
if i != len(hull) - 1:
plt.plot([hull[i][0], hull[i + 1][0]], [hull[i][1], hull[i + 1][1]], color="red")
else:
plt.plot([hull[i][0], hull[0][0]], [hull[i][1], hull[0][1]], color="red")
plt.show()
# Returns the points indexes related to each hull element
def get_indexes(self):
indexes = []
for element in self.convex_hull():
j = 0
while element[0] != self.data[j][0] or element[1] != self.data[j][1]:
j += 1
indexes.append(j)
return(indexes)
if __name__ == '__main__':
data1 = gift_wrapping(np.loadtxt("nuvem1.txt"), "Nuvem_1")
data2 = gift_wrapping(np.loadtxt("nuvem2.txt"), "Nuvem_2")
data1.plot_hull()
with open('fecho1.txt', 'w') as f:
for item in data1.get_indexes():
f.write("%s\n" % item)
data2.plot_hull()
with open('fecho2.txt', 'w') as f:
for item in data2.get_indexes():
f.write("%s\n" % item)
N = 1000
x = np.random.standard_normal(N)
y = np.random.standard_normal(N)
P = []
for i in range(N):
P.append([x[i], y[i]])
P = gift_wrapping(P)
P.plot_hull()
# Ploting Runtime
sizes = [50, 100, 500, 1000, 2000, 5000, 10000]
run_time = []
h = []
for N in sizes:
x = np.random.standard_normal(N)
y = np.random.standard_normal(N)
P = []
for i in range(N):
P.append([x[i], y[i]])
P = gift_wrapping(P)
start = time.time()
P.convex_hull()
end = time.time()
run_time.append(end - start)
h.append(len(P.convex_hull()))
for i in range(len(h)):
h[i] = h[i] * sizes[i]
plt.plot(sizes, run_time, "r")
plt.plot(sizes, [x / 150000 for x in h], "b")
plt.xlabel('Input size')
plt.ylabel('time (s)')
plt.legend(["Gift_Wrapping", "n*h"])
plt.grid(True)
plt.show()<file_sep># Fecho Convexo
## Objetivo
O objetivo deste projeto é detalhar os conceitos teóricos e a abordagem prática usada para resolver o problema de definição do fecho mínimo de uma nuvem de pontos através do algoritmo “Gift Wrapping”. Assim, veremos como são feitos os cálculos para a definição dos pontos dos fechos, sua implementação em linguagem Python e uma análise da complexidade do tempo de execução de acordo com o tamanho da entrada.
## Método
A descrição teórica do método utilizado pode ser encontrada no relatório neste repositório.
## Implementação
Implementando o algoritmo em linguagem Python, e usando como entrada conjuntos de pontos pré-definidos, obtemos os seguintes resultados:


Também é possível implementar o algoritmo para um conjunto de pontos criados de forma aleatória, com distribuição normal. Abaixo vemos o resultado para uma nuvem de 1000 pontos:

Abaixo podemos analisar o tempo de execução para diferentes tamanhos de entrada:

## Conclusão
O algoritmo “Gift Wrapping” para identificação do fecho convexo fornece uma solução relativamente simples comparado à outros algoritmos de mesma função. Conforme esperado, o tempo de execução do algoritmo proposto de acordo com a entrada é proporcional a〖 O〗_((nh)). Isso pode resultar em um algoritmo muito eficiente, principalmente para conjuntos com muitos pontos e poucos pontos situados no feche. É também uma boa alternativa ao algoritmo “força bruta”, que resultaria em uma complexidade〖 O〗_((n^2)). Porém, para casos especiais onde existem muitos pontos no feche, o algoritmo “Gift Wrapping” pode não ser a melhor alternativa.
|
674c1fe4a6cca57a1ac6d4040f5754eef4d95b8e
|
[
"Markdown",
"Python"
] | 2 |
Python
|
gustavomccoelho/Fecho-Convexo
|
54344d6d4af6e6da9ae1f1ed03859e491fdc1928
|
94c772299f96c2a0f7cbbf0a58682d54df168630
|
refs/heads/master
|
<repo_name>Mariemnoui/mqtt-servo-client<file_sep>/MQTT_client.servo.ino
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>
Servo myservo;
const char* ssid = "LDV-CPP";
const char* password = "<PASSWORD>++";
const char* mqtt_server = "ajax-der-kleine.clients.ldv.ei.tum.de"; ///broker MQTT
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
Serial.begin(115200);
myservo.attach(2); // attach your servo to pin D4
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
String string;
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
// Serial.print((char)payload[i]);
string+=((char)payload[i]); // converting the message received to a string
}
Serial.print(string);
if (topic ="servo")
Serial.print(" ");
int resultado = string.toInt(); // converting the string to integer
int pos = map(resultado, 1, 100, 32, 165); // converting the integer to an Angle for the servo motor
Serial.println(pos);
myservo.write(pos);
delay(15);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("servo");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
delay(100);
}
<file_sep>/README.md
# mqtt-servo-client
|
4e97f0ffcd10ef72a6a2953b3e8b78e58e243642
|
[
"Markdown",
"C++"
] | 2 |
C++
|
Mariemnoui/mqtt-servo-client
|
1f392ab06318d15dd502144b8a2b33e5799fbf54
|
cd932914f04c11b5bde16007e14988e0d179b4b7
|
refs/heads/main
|
<repo_name>VaibhavJogdand/Portfolio<file_sep>/src/components/topbar/topbar.js
import React from 'react';
import './topbar.css'
import { FaInstagram } from 'react-icons/fa';
import { FaGithub } from 'react-icons/fa';
import { FaTwitter } from 'react-icons/fa';
import { FaFacebookF } from 'react-icons/fa';
export default function Topbar(){
return(
<>
<div className='topbar'>
<div className='left'>
<ul className='topbarIcons'>
<a href='https://www.instagram.com/i.am_vaibhav_/'><li className='topbarIconslist'><FaInstagram className='reactIcons'/></li></a>
<a href='https://github.com/VaibhavJogdand'><li className='topbarIconslist'><FaGithub className='reactIcons'/></li></a>
<a href='https://twitter.com/vrjogdand708'><li className='topbarIconslist'><FaTwitter className='reactIcons'/></li></a>
<a href='https://www.facebook.com/profile.php?id=100008846442286'><li className='topbarIconslist'><FaFacebookF className='reactIcons'/></li></a>
</ul>
</div>
<div className='right'>
<ul>
<a href='#about'><li className='menuItems'>About</li></a>
<a href='#project'><li className='menuItems'>Projects</li></a>
<a href='#experties'><li className='menuItems'>Technologies</li></a>
<a href='#contact'><li className='menuItems'>Contact</li></a>
</ul>
</div>
</div>
</>
)
}<file_sep>/src/components/projects/project.js
import React from 'react';
import './project.css'
import blogImg from '../../images/blog.png';
import tindogImg from '../../images/tindog.png';
import gymImg from '../../images/gym.png'
import Carousel from 'react-bootstrap/Carousel'
export default function Project(){
return(
<div className='project' id='project'>
<h2 className='projectHeading'>Things I have Created</h2>
<Carousel>
<Carousel.Item>
<img
className="d-block w-100"
src={blogImg}
alt="First slide"
/>
<Carousel.Caption className='Caption'>
<a href='https://blog-28.netlify.app/'><h3 className='projHead'>Blog Website</h3></a>
<p className='projDesc'>This is blog website developed using MERN Stack.Created RestAPI in nodeJS.ContextAPI is used for propdrilling and hosted on Netlify & Heroku.</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block w-100"
src={gymImg}
alt="Second slide"
/>
<Carousel.Caption className='Caption'>
<a href='https://muscletrainer-vrj.netlify.app/'><h3 className='projHead'>GYM Website</h3></a>
<p className='projDesc'>This is GYM website developed using ReactJS.Created beautiful animations using aos library.EmailJS is used for communication and hosted on Netlify</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block w-100"
src={tindogImg}
alt="Third slide"
/>
<Carousel.Caption className='Caption'>
<a href='https://tindog-vrj.netlify.app/'><h3 className='projHead'>Tindog</h3></a>
<p className='projDesc'>This is simple front-end project which contain HTML & CSS as mainstream languages.</p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</div>
);
}
|
3ac7edd51b8607cda38569c6aebc4f4c8aa61d26
|
[
"JavaScript"
] | 2 |
JavaScript
|
VaibhavJogdand/Portfolio
|
aa0caa42e3a96a4c12a698f7f4f6de04e185d336
|
5e09818ed4d8612b9adfe8ee0cc6fc5859f36584
|
refs/heads/master
|
<repo_name>sun40/T1Contacts<file_sep>/T1Contacts/src/com/task1/contacts/contact/ContactAction.java
package com.task1.contacts.contact;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.task1.contacts.ContactListActivity;
public class ContactAction {
public static final int SEND_SMS = 0;
public static final int DIAL = 1;
public static final int MAILTO = 2;
public static void make(int actionID, String number){
switch (actionID){
case SEND_SMS :
Uri sms = Uri.parse("smsto:" + number);
Intent intent_sms = new Intent(Intent.ACTION_SENDTO, sms);
ContactListActivity.getAppContext().startActivity(intent_sms);
break;
case DIAL :
Uri dial = Uri.parse("tel:" + number);
Intent intent_dial = new Intent(Intent.ACTION_DIAL, dial);
ContactListActivity.getAppContext().startActivity(intent_dial);
break;
case MAILTO :
Uri mailto = Uri.parse("mailto:"+ number);
Intent intent_mail = new Intent(Intent.ACTION_SENDTO, mailto);
ContactListActivity.getAppContext().startActivity(intent_mail);
break;
default :
Log.e("CTag", "Wrong actionID");
break;
}
}
}
<file_sep>/T1Contacts/src/com/task1/contacts/ContactListFragment.java
package com.task1.contacts;
import com.task1.contacts.binder.ContactsBinder;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
public class ContactListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>{
public static final String STATE_ACTIVATED_POSITION = "activated_position";
private int _activatedPosition = ListView.INVALID_POSITION;
private SimpleCursorAdapter _adapter;
/**
* Used when this fragment do not attached to activity
*/
private ICallback _dummyCallback = new ICallback(){
@Override
public void onItemSelected(String id) {}
};
private ICallback _callback = _dummyCallback;
public ContactListFragment(){}
/**
* This method overrides from ListFragment(Activity) and makes query to contacts database to select
* data for SimpleCursorAdapter, which fills ListView.
* Adapter uses custom binder to set default icons to contacts without photo.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoaderManager _loaderManager = getLoaderManager();
Log.d("CTag", "sdk " + android.os.Build.VERSION.SDK_INT);
String[] from = {Contacts._ID, Contacts.DISPLAY_NAME};
int[] to = {R.id.ivContactImg, R.id.tvContactName};
_adapter = new SimpleCursorAdapter(getActivity(), R.layout.contact_item, null, from, to, 0);
ContactsBinder cb = new ContactsBinder(getActivity().getContentResolver());
_adapter.setViewBinder(cb);
setListAdapter(_adapter);
_loaderManager.initLoader(1, null, this);
}
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// View view = inflater.inflate(R.layout.activity_contact_list, container, false);
//// ListView contact_list = (ListView)view.findViewById(R.id.contact_list);
////
//// if(contact_list == null){
//// Log.e("CTag", "ListView is null");
//// this.setListShown(false);
//// }
// return view;
// }
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION))
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof ICallback)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
_callback = (ICallback) activity;
}
@Override
public void onDetach() {
super.onDetach();
_callback = _dummyCallback;
}
/**
* Calls on item click event.
* Uses callback method to call activity method.
*/
@Override
public void onListItemClick(ListView listView, View view, int position,long id) {
super.onListItemClick(listView, view, position, id);
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
String idContact = cursor.getString(cursor.getColumnIndex(Contacts._ID));
_callback.onItemSelected(idContact);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (_activatedPosition != ListView.INVALID_POSITION) {
outState.putInt(STATE_ACTIVATED_POSITION, _activatedPosition);
}
}
public void setActivateOnItemClick(boolean activateOnItemClick) {
getListView().setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE);
}
private void setActivatedPosition(int pos) {
if (pos == ListView.INVALID_POSITION) {
getListView().setItemChecked(_activatedPosition, false);
} else {
getListView().setItemChecked(pos, true);
}
_activatedPosition = pos;
}
@Override
public Loader<Cursor> onCreateLoader(int arg, Bundle bundle) {
CursorLoader _cursorLoader = new CursorLoader(getActivity(),
ContactsContract.Contacts.CONTENT_URI,
new String[] {Contacts._ID, Contacts.DISPLAY_NAME},
null,
null,
"DISPLAY_NAME ASC");
return _cursorLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if(_adapter != null && cursor != null)
_adapter.swapCursor(cursor);
else
Log.e("CTag", "Adapter is null");
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
if(_adapter != null)
_adapter.swapCursor(null);
else
Log.e("CTag", "Adapter is null");
}
}
<file_sep>/T1Contacts/src/com/task1/contacts/contact/ContactData.java
package com.task1.contacts.contact;
import java.util.ArrayList;
import com.task1.contacts.ContactListActivity;
import com.task1.contacts.R;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.view.ViewGroup;
/**
* This class contains contact data and
* initializes views
* @author <NAME>
*
*/
public class ContactData {
private String _id = "";
private String _name = "";
private String _displayName = "";
private ArrayList<String> _phone = new ArrayList<String>();
private ArrayList<String> _phoneLabel = new ArrayList<String>();
private ArrayList<String> _email = new ArrayList<String>();
private ArrayList<String> _emailLabel = new ArrayList<String>();
private ArrayList<String> _chat = new ArrayList<String>();
private ArrayList<String> _chatLabel = new ArrayList<String>();
private String _nick = "";
private String _sipAddress = "";
private String _webSite = "";
private ArrayList<String> _address = new ArrayList<String>();
private ArrayList<String> _addressLabel = new ArrayList<String>();
private ArrayList<String> _date = new ArrayList<String>();
private ArrayList<String> _dateLabel = new ArrayList<String>();
private String _note = "";
private Uri _imgUri = null;
private ContentResolver _cr;
//-----------------------------------------------------
//-----------------------------------------------------
public String getID(){
return _id;
}
public Uri getPhotoUri(){
return _imgUri;
}
public String getNote(){
return _note;
}
public ArrayList<String> getDatesLabel(){
return _dateLabel;
}
public ArrayList<String> getDates(){
return _date;
}
public ArrayList<String> getAddressLabel(){
return _addressLabel;
}
public ArrayList<String> getAddress(){
return _address;
}
public String getWebSite(){
return _webSite;
}
public String getSipAddress(){
return _sipAddress;
}
public String getNick(){
return _nick;
}
public ArrayList<String> getChatsLabel(){
return _chatLabel;
}
public ArrayList<String> getChats(){
return _chat;
}
public ArrayList<String> getEmailsLabel(){
return _emailLabel;
}
public ArrayList<String> getEmails(){
return _email;
}
public ArrayList<String> getPhonesLabel(){
return _phoneLabel;
}
public ArrayList<String> getPhones(){
return _phone;
}
public String getDisplayName(){
return _displayName;
}
public String getName(){
return _name;
}
//-----------------------------------------------------
//-----------------------------------------------------
ContactData(String id){
_id = id;
_cr = ContactListActivity.getAppContext().getContentResolver();
initData();
}
/**
* This method initialize contact data
*/
private void initData(){
setDisplayName();
setPhone();
setEmail();
setChat();
setNick();
setSipAddress();
setWebSite();
setAdress();
setDate();
setNote();
setImage();
setName();
}
/**
* This method sets contact image data
*/
private void setImage() {
if (android.os.Build.VERSION.SDK_INT >= 11){
String img = null;
Cursor curPhoto = _cr.query(
ContactsContract.Contacts.CONTENT_URI,
new String[] {ContactsContract.Contacts.PHOTO_URI},
ContactsContract.Contacts._ID + " = ?",
new String[] {_id},
null);
while(curPhoto.moveToNext()){
img = curPhoto.getString(curPhoto.getColumnIndex(ContactsContract.Contacts.PHOTO_URI));
}
// if(new File(img).exists()){
// Log.d("CTag", "file exists");
// }
// else
// Log.d("CTag", "file no exists");
//
if(img != null)
_imgUri = Uri.parse(img);
curPhoto.close();
}
else
_imgUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(_id));
}
/**
* This method sets name if it does not match with phone number,
* email or nick
*/
private void setName() {
boolean ownname = true;
for(String phone : _phone){
if (phone.equals(_displayName))
ownname = false;
}
for(String email : _email){
if (email.equals(_displayName))
ownname = false;
}
if(_nick.equals(_displayName))
ownname = false;
if (ownname) _name = _displayName;
}
/**
* This method sets contact note data
*/
private void setNote() {
Cursor curNote = _cr.query(
ContactsContract.Data.CONTENT_URI,
new String[] {ContactsContract.CommonDataKinds.Note.NOTE},
ContactsContract.CommonDataKinds.Note.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {_id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE},
null);
while(curNote.moveToNext()){
_note = curNote.getString(curNote.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
}
curNote.close();
}
/**
* This method sets contact date data
*/
private void setDate() {
Cursor curDate = _cr.query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.LABEL},
ContactsContract.CommonDataKinds.Event.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {_id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE},
null);
while(curDate.moveToNext()){
String date = curDate.getString(curDate.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
int dateType = curDate.getInt(curDate.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE));
String label;
switch(dateType){
case ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY :
label = ContactListActivity.getAppContext().getResources().getString(R.string.anniversary);
break;
case ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY :
label = ContactListActivity.getAppContext().getResources().getString(R.string.birthday);
break;
default :
label = ContactListActivity.getAppContext().getResources().getString(R.string.other_date);
break;
}
_date.add(date);
_dateLabel.add(label);
}
curDate.close();
}
/**
* This method sets contact address data
*/
private void setAdress() {
Cursor curAdr = _cr.query(
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
new String[] {ContactsContract.CommonDataKinds.StructuredPostal.LABEL, ContactsContract.CommonDataKinds.StructuredPostal.STREET,
ContactsContract.CommonDataKinds.StructuredPostal.TYPE},
ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ?",
new String[] {_id},
null);
while(curAdr.moveToNext()){
String adr = curAdr.getString(curAdr.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String customLabel = curAdr.getString(curAdr.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.LABEL));
int adrType = curAdr.getInt(curAdr.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
String adrLabel = (String) ContactsContract.CommonDataKinds.StructuredPostal.getTypeLabel(ContactListActivity.getAppContext().getResources(), adrType, customLabel);
_address.add(adr);
_addressLabel.add(adrLabel);
}
curAdr.close();
}
/**
* This method sets contact web site data
*/
private void setWebSite() {
Cursor curWeb = _cr.query(
ContactsContract.Data.CONTENT_URI,
new String[] {ContactsContract.CommonDataKinds.Website.URL},
ContactsContract.CommonDataKinds.Website.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {_id, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE},
null);
while(curWeb.moveToNext()){
_webSite = curWeb.getString(curWeb.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
}
curWeb.close();
}
/**
* This method sets contact sip address data
*/
private void setSipAddress() {
Cursor curSip = _cr.query(
ContactsContract.Data.CONTENT_URI,
new String[] {ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS},
ContactsContract.CommonDataKinds.SipAddress.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {_id, ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE},
null);
while(curSip.moveToNext()){
_sipAddress = curSip.getString(curSip.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS));
}
curSip.close();
}
/**
* This method sets contact nick data
*/
private void setNick() {
Cursor curNick = _cr.query(
ContactsContract.Data.CONTENT_URI,
new String[] {ContactsContract.CommonDataKinds.Nickname.NAME},
ContactsContract.CommonDataKinds.Nickname.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {_id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE},
null);
while(curNick.moveToNext()){
_nick = curNick.getString(curNick.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME));
}
curNick.close();
}
/**
* This method sets contact chat data
*/
private void setChat() {
Cursor curChat = _cr.query(
ContactsContract.Data.CONTENT_URI,
new String[] {ContactsContract.CommonDataKinds.Im.PROTOCOL, ContactsContract.CommonDataKinds.Im.DATA,
ContactsContract.CommonDataKinds.Im.LABEL},
ContactsContract.CommonDataKinds.Im.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {_id, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE},
null);
while(curChat.moveToNext()){
String imId = curChat.getString(curChat.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
String customLabel = curChat.getString(curChat.getColumnIndex(ContactsContract.CommonDataKinds.Im.LABEL));
int chatType = curChat.getInt(curChat.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL));
String chatLabel = (String) ContactsContract.CommonDataKinds.Im.getProtocolLabel(ContactListActivity.getAppContext().getResources(), chatType, customLabel);
_chat.add(imId);
_chatLabel.add(chatLabel);
}
curChat.close();
}
/**
* This method sets contact email data
*/
private void setEmail() {
Cursor curEmail = _cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[] {ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.LABEL},
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[] {_id},
null);
while(curEmail.moveToNext()){
_email.add(curEmail.getString(curEmail.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS)));
String customLabel = curEmail.getString(curEmail.getColumnIndex(ContactsContract.CommonDataKinds.Email.LABEL));
int emailType = curEmail.getInt(curEmail.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String emailLabel = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(ContactListActivity.getAppContext().getResources(), emailType, customLabel);
_emailLabel.add(emailLabel);
}
curEmail.close();
}
/**
* This method sets contact phone numbers data
*/
private void setPhone() {
Cursor curPhone = _cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[] {_id},
null);
while(curPhone.moveToNext()){
String number = curPhone.getString(curPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
_phone.add(number);
String customLabel = curPhone.getString(curPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));
int phoneType = curPhone.getInt(curPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String phoneLabel = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(ContactListActivity.getAppContext().getResources(), phoneType, customLabel);
_phoneLabel.add(phoneLabel);
}
curPhone.close();
}
/**
* This method sets contact display name data
*/
private void setDisplayName() {
Cursor curName = _cr.query(
ContactsContract.Contacts.CONTENT_URI,
null,
ContactsContract.Contacts._ID + " = ?",
new String[] {_id},
null);
while(curName.moveToNext()){
_displayName = curName.getString(curName.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
curName.close();
}
}
<file_sep>/T1Contacts/src/com/task1/contacts/ContactListActivity.java
package com.task1.contacts;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
/**
* Fragment activity which shows contact list and contact details in two
* pane mode on tablet devices
* @author <NAME>
*
*/
public class ContactListActivity extends FragmentActivity implements ICallback {
private boolean _tablet = false;
private static ContactListActivity APPCONTEXT;
public static Context getAppContext(){
return APPCONTEXT;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
if(findViewById(R.id.contact_detail_container) != null){
Log.d("CTag", "This is tablet device");
_tablet = true;
((ContactListFragment) getSupportFragmentManager().findFragmentById(R.id.contact_list)).setActivateOnItemClick(true);
}
else{
Log.d("CTag", "This is handset device");
}
APPCONTEXT = this;
}
/**
* ICallback interface method which allows to use callbacks from ContactListFragment
* and adds new fragment on tablet devices and launching new activity on handsets
*/
@Override
public void onItemSelected(String id){
if(_tablet){
Bundle args = new Bundle();
args.putString(ContactDetailsFragment.CONTACT_ID, id);
ContactDetailsFragment detailFragment = new ContactDetailsFragment();
detailFragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.contact_detail_container, detailFragment).commit();
}
else{
Intent detailIntent = new Intent(this, ContactDetailsActivity.class);
detailIntent.putExtra(ContactDetailsFragment.CONTACT_ID, id);
startActivity(detailIntent);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpTo(this, new Intent(this, ContactListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>/README.md
T1Contacts
==========
T1Contacts
|
f15aa279bb47192720010103ffea0000ba28b6b9
|
[
"Markdown",
"Java"
] | 5 |
Java
|
sun40/T1Contacts
|
375d93a92dfb93365fc0ddc8be9696810c931d33
|
5694ba3c8aab70849370c14a29f92a957ca9534e
|
refs/heads/master
|
<repo_name>dterracino/asimov<file_sep>/Demo/Program.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Asimov;
namespace Asimov
{
/// <summary>
///
/// </summary>
/// <remarks>
/// <![CDATA[
/// [IN]: Bill comes into the room
/// [OUT]: draw sword
/// [IN]: You drew your sword from the sheath
/// [OUT]: kill bill
/// [IN]: Bill dodged
/// [OUT]: Try again
/// [OUT]: kill bill
/// [IN]: Bill comes into the room
/// [IN]: you are hit
/// [OUT]: run Forest run!
/// [OUT]: State: Hit: True, Thirsty: False
/// [IN]: you are thirsty
/// [OUT]: drink water baby
/// [OUT]: State: Hit: True, Thirsty: True
/// [IN]: Bill dodged
/// [OUT]: Try again
/// [OUT]: kill bill
/// [IN]: Bill dodged
/// [OUT]: Try again
/// [OUT]: kill bill
/// [IN]: Bill is killed
/// [OUT]: Good! Bill is killed!
/// [OUT]: unwield sword
/// [OUT]: rest
/// ]]>
/// </remarks>
class Program
{
static void Main(string[] args)
{
Engine.Instance
.Configure(config => config.ReadLine = ReadLine)
.Configure(config => config.Send = config.Send = x => Console.WriteLine($"[OUT]: {x}"));
var p = new Player();
p.MonitorHit(); // the created task is hot
p.MonitorThirsty(); // the created task is hot
p.KillBill();
Engine.Instance.Run();
}
private static string ReadLine()
{
Console.Write("[IN]: ");
return Console.ReadLine();
}
}
class Player
{
public bool IsThirsty;
public bool IsHit;
/// <summary>
/// Demo forked conditions
/// </summary>
public async void KillBill()
{
await "^Bill comes into the room".Wait();
"draw sword".Send();
await "^You drew your sword from the sheath".Wait();
bool killed = false;
while (!killed)
{
"kill bill".Send();
if ((await new[] { "^Bill is killed", "^Bill dodged" }.Wait()).Condition == 0)
{
"Good! Bill is killed!".Send();
"unwield sword".Send();
killed = true;
}
else
{
"Try again".Send();
}
}
"rest".Send();
}
public async void MonitorHit()
{
while (true)
{
await "^you are hit".Wait();
IsHit = true;
"run Forest run!".Send();
$"State: {this}".Send();
}
}
public async void MonitorThirsty()
{
while (true)
{
await "^you are thirsty".Wait();
IsThirsty = true;
"drink water baby".Send();
$"State: {this}".Send();
}
}
public override string ToString()
{
return $"Hit: {IsHit}, Thirsty: {IsThirsty}";
}
}
}
<file_sep>/asimov/Context.cs
using System;
namespace Asimov
{
public class Context
{
public int Condition;
}
}<file_sep>/asimov/RobotBase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Asimov
{
class RobotBase : IRobot
{
readonly Guid id = Guid.NewGuid();
Engine engine;
public RobotBase(Engine engine)
{
this.engine = engine;
}
public Task RunAsync()
{
throw new NotImplementedException();
}
public void Stop()
{
throw new NotImplementedException();
}
protected async Task<Context> For(params string[] patterns)
{
return await engine.Pattern(patterns);
}
}
}
<file_sep>/asimov/Engine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Asimov
{
public class Engine
{
public class Configuration
{
public Func<string> ReadLine;
public Action<string> Send;
}
static Engine instance = new Engine();
public static Engine Instance
{
get
{
return instance;
}
}
private object sync = new object();
private Configuration config = new Configuration();
public Engine Configure(Action<Configuration> configure)
{
lock (sync)
{
configure(this.config);
return this;
}
}
List<Trigger> TriggerBag = new List<Trigger>();
Dictionary<Guid, List<Trigger>> TriggerGroup = new Dictionary<Guid, List<Trigger>>();
public void Run()
{
string line;
while (null != (line = config.ReadLine()))
{
Trigger triggered = MatchWith(line);
if (triggered != null)
{
triggered.Source.SetResult(new Context { Condition = triggered.ConditionIndex });
}
}
}
public Task<Context> Pattern(params string[] vs)
{
return Pattern(Guid.NewGuid(), vs);
}
public async Task<Context> Pattern(Guid groupId, params string[] vs)
{
Guid condId = Guid.NewGuid();
List<Trigger> triggers = new List<Trigger>();
List<Task<Context>> tasks = new List<Task<Context>>();
for (int i = 0; i < vs.Length; i++)
{
string v = vs[i];
var src = new TaskCompletionSource<Context>();
triggers.Add(new Trigger { Source = src, Pattern = new Regex(v), ConditionId = condId, ConditionIndex = i, GroupId = groupId });
tasks.Add(src.Task);
}
TriggerBag.AddRange(triggers);
TriggerGroup[condId] = triggers;
var x = await await Task.WhenAny(tasks);
foreach (var trig in TriggerGroup[condId])
{
TriggerBag.Remove(trig);
trig.Source.TrySetCanceled();
TriggerGroup.Remove(condId);
}
return x;
}
public void Send(string line)
{
config.Send(line);
}
private Trigger MatchWith(string line)
{
foreach (var item in TriggerBag)
{
var res = item.Pattern.Match(line);
if (res.Success) return item;
}
return null;
}
}
public static class EngineExtentions
{
public static Task<Context> Wait(this string s)
{
return Engine.Instance.Pattern(s);
}
public static Task<Context> Wait(this IEnumerable<string> vs)
{
return Engine.Instance.Pattern(vs.ToArray());
}
public static void Send(this string line)
{
Engine.Instance.Send(line);
}
}
}
<file_sep>/asimov/Trigger.cs
using System;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Asimov
{
internal class Trigger
{
public TaskCompletionSource<Context> Source;
public Regex Pattern;
public Guid ConditionId;
public int ConditionIndex;
public Guid GroupId;
}
}<file_sep>/asimov/IRobot.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Asimov
{
interface IRobot
{
Task RunAsync();
void Stop();
}
}
|
c203adfc873a117fba996af69b1c9d3835549c23
|
[
"C#"
] | 6 |
C#
|
dterracino/asimov
|
8ff1285e7885282b23632fcdd71cf002b8b2a758
|
964293b61ab24f7c12fe4f6e1bf2945ba50ee7ca
|
refs/heads/master
|
<repo_name>crcsaenz/coolc<file_sep>/README.md
coolc
=====
CS-143: Compilers
<file_sep>/pa3/semant.h
#ifndef SEMANT_H_
#define SEMANT_H_
#include <assert.h>
#include <iostream>
#include "cool-tree.h"
#include "stringtab.h"
#include "symtab.h"
#include "list.h"
#include <map>
#include <set>
#define TRUE 1
#define FALSE 0
class ClassTable;
typedef ClassTable *ClassTableP;
// This is a structure that may be used to contain the semantic
// information such as the inheritance graph. You may use it or not as
// you like: it is only here to provide a container for the supplied
// methods.
class ClassTable {
private:
int semant_errors;
void install_basic_classes();
ostream& error_stream;
public:
ClassTable(Classes);
int errors() { return semant_errors; }
ostream& semant_error();
ostream& semant_error(Class_ c);
ostream& semant_error(Symbol filename, tree_node *t);
// maps child to parent
std::map<Symbol, Symbol> *inheritanceMap;
// maps class name to class data
std::map<Symbol, class__class> *classEnv;
// maps class name to methods map, which maps method name to method data
std::map<Symbol, std::map<Symbol, method_class> > *methodEnv;
// maps class name to attributes map, which maps attribute name to attribute data
std::map<Symbol, std::map<Symbol, attr_class> > *attrEnv;
};
#endif
<file_sep>/pa4/cgen.cc
//**************************************************************
//
// Code generator SKELETON
//
// Read the comments carefully. Make sure to
// initialize the base class tags in
// `CgenClassTable::CgenClassTable'
//
// Add the label for the dispatch tables to
// `IntEntry::code_def'
// `StringEntry::code_def'
// `BoolConst::code_def'
//
// Add code to emit everyting else that is needed
// in `CgenClassTable::code'
//
//
// The files as provided will produce code to begin the code
// segments, declare globals, and emit constants. You must
// fill in the rest.
//
//**************************************************************
#include "cgen.h"
#include "cgen_gc.h"
extern void emit_string_constant(ostream& str, char *s);
extern int cgen_debug;
int CgenNode::labelIndex = 0;
//
// Three symbols from the semantic analyzer (semant.cc) are used.
// If e : No_type, then no code is generated for e.
// Special code is generated for new SELF_TYPE.
// The name "self" also generates code different from other references.
//
//////////////////////////////////////////////////////////////////////
//
// Symbols
//
// For convenience, a large number of symbols are predefined here.
// These symbols include the primitive type and method names, as well
// as fixed names used by the runtime system.
//
//////////////////////////////////////////////////////////////////////
Symbol
arg,
arg2,
Bool,
concat,
cool_abort,
copy,
Int,
in_int,
in_string,
IO,
length,
Main,
main_meth,
No_class,
No_type,
Object,
out_int,
out_string,
prim_slot,
self,
SELF_TYPE,
Str,
str_field,
substr,
type_name,
val;
//
// Initializing the predefined symbols.
//
static void initialize_constants(void)
{
arg = idtable.add_string("arg");
arg2 = idtable.add_string("arg2");
Bool = idtable.add_string("Bool");
concat = idtable.add_string("concat");
cool_abort = idtable.add_string("abort");
copy = idtable.add_string("copy");
Int = idtable.add_string("Int");
in_int = idtable.add_string("in_int");
in_string = idtable.add_string("in_string");
IO = idtable.add_string("IO");
length = idtable.add_string("length");
Main = idtable.add_string("Main");
main_meth = idtable.add_string("main");
// _no_class is a symbol that can't be the name of any
// user-defined class.
No_class = idtable.add_string("_no_class");
No_type = idtable.add_string("_no_type");
Object = idtable.add_string("Object");
out_int = idtable.add_string("out_int");
out_string = idtable.add_string("out_string");
prim_slot = idtable.add_string("_prim_slot");
self = idtable.add_string("self");
SELF_TYPE = idtable.add_string("SELF_TYPE");
Str = idtable.add_string("String");
str_field = idtable.add_string("_str_field");
substr = idtable.add_string("substr");
type_name = idtable.add_string("type_name");
val = idtable.add_string("_val");
}
static char *gc_init_names[] =
{ "_NoGC_Init", "_GenGC_Init", "_ScnGC_Init" };
static char *gc_collect_names[] =
{ "_NoGC_Collect", "_GenGC_Collect", "_ScnGC_Collect" };
// BoolConst is a class that implements code generation for operations
// on the two booleans, which are given global names here.
BoolConst falsebool(FALSE);
BoolConst truebool(TRUE);
//*********************************************************
//
// Define method for code generation
//
// This is the method called by the compiler driver
// `cgtest.cc'. cgen takes an `ostream' to which the assembly will be
// emmitted, and it passes this and the class list of the
// code generator tree to the constructor for `CgenClassTable'.
// That constructor performs all of the work of the code
// generator.
//
//*********************************************************
void program_class::cgen(ostream &os)
{
// spim wants comments to start with '#'
if (cgen_debug) os << "# start of generated code\n";
initialize_constants();
CgenClassTable *codegen_classtable = new CgenClassTable(classes,os);
if (cgen_debug) os << "\n# end of generated code\n";
}
//////////////////////////////////////////////////////////////////////////////
//
// emit_* procedures
//
// emit_X writes code for operation "X" to the output stream.
// There is an emit_X for each opcode X, as well as emit_ functions
// for generating names according to the naming conventions (see emit.h)
// and calls to support functions defined in the trap handler.
//
// Register names and addresses are passed as strings. See `emit.h'
// for symbolic names you can use to refer to the strings.
//
//////////////////////////////////////////////////////////////////////////////
static void emit_load(char *dest_reg, int offset, char *source_reg, ostream& s)
{
s << LW << dest_reg << " " << offset * WORD_SIZE << "(" << source_reg << ")"
<< endl;
}
static void emit_store(char *source_reg, int offset, char *dest_reg, ostream& s)
{
s << SW << source_reg << " " << offset * WORD_SIZE << "(" << dest_reg << ")"
<< endl;
}
static void emit_load_imm(char *dest_reg, int val, ostream& s)
{ s << LI << dest_reg << " " << val << endl; }
static void emit_load_address(char *dest_reg, char *address, ostream& s)
{ s << LA << dest_reg << " " << address << endl; }
static void emit_partial_load_address(char *dest_reg, ostream& s)
{ s << LA << dest_reg << " "; }
static void emit_load_bool(char *dest, const BoolConst& b, ostream& s)
{
emit_partial_load_address(dest,s);
b.code_ref(s);
s << endl;
}
static void emit_load_string(char *dest, StringEntry *str, ostream& s)
{
emit_partial_load_address(dest,s);
str->code_ref(s);
s << endl;
}
static void emit_load_int(char *dest, IntEntry *i, ostream& s)
{
emit_partial_load_address(dest,s);
i->code_ref(s);
s << endl;
}
static void emit_move(char *dest_reg, char *source_reg, ostream& s)
{ s << MOVE << dest_reg << " " << source_reg << endl; }
static void emit_neg(char *dest, char *src1, ostream& s)
{ s << NEG << dest << " " << src1 << endl; }
static void emit_add(char *dest, char *src1, char *src2, ostream& s)
{ s << ADD << dest << " " << src1 << " " << src2 << endl; }
static void emit_addu(char *dest, char *src1, char *src2, ostream& s)
{ s << ADDU << dest << " " << src1 << " " << src2 << endl; }
static void emit_addiu(char *dest, char *src1, int imm, ostream& s)
{ s << ADDIU << dest << " " << src1 << " " << imm << endl; }
static void emit_div(char *dest, char *src1, char *src2, ostream& s)
{ s << DIV << dest << " " << src1 << " " << src2 << endl; }
static void emit_mul(char *dest, char *src1, char *src2, ostream& s)
{ s << MUL << dest << " " << src1 << " " << src2 << endl; }
static void emit_sub(char *dest, char *src1, char *src2, ostream& s)
{ s << SUB << dest << " " << src1 << " " << src2 << endl; }
static void emit_sll(char *dest, char *src1, int num, ostream& s)
{ s << SLL << dest << " " << src1 << " " << num << endl; }
static void emit_jalr(char *dest, ostream& s)
{ s << JALR << "\t" << dest << endl; }
static void emit_jal(char *address,ostream &s)
{ s << JAL << address << endl; }
static void emit_return(ostream& s)
{ s << RET << endl; }
static void emit_gc_assign(ostream& s)
{ s << JAL << "_GenGC_Assign" << endl; }
static void emit_disptable_ref(Symbol sym, ostream& s)
{ s << sym << DISPTAB_SUFFIX; }
static void emit_init_ref(Symbol sym, ostream& s)
{ s << sym << CLASSINIT_SUFFIX; }
static void emit_label_ref(int l, ostream &s)
{ s << "label" << l; }
static void emit_protobj_ref(Symbol sym, ostream& s)
{ s << sym << PROTOBJ_SUFFIX; }
static void emit_method_ref(Symbol classname, Symbol methodname, ostream& s)
{ s << classname << METHOD_SEP << methodname; }
static void emit_label_def(int l, ostream &s)
{
emit_label_ref(l,s);
s << ":" << endl;
}
static void emit_beqz(char *source, int label, ostream &s)
{
s << BEQZ << source << " ";
emit_label_ref(label,s);
s << endl;
}
static void emit_beq(char *src1, char *src2, int label, ostream &s)
{
s << BEQ << src1 << " " << src2 << " ";
emit_label_ref(label,s);
s << endl;
}
static void emit_bne(char *src1, char *src2, int label, ostream &s)
{
s << BNE << src1 << " " << src2 << " ";
emit_label_ref(label,s);
s << endl;
}
static void emit_bleq(char *src1, char *src2, int label, ostream &s)
{
s << BLEQ << src1 << " " << src2 << " ";
emit_label_ref(label,s);
s << endl;
}
static void emit_blt(char *src1, char *src2, int label, ostream &s)
{
s << BLT << src1 << " " << src2 << " ";
emit_label_ref(label,s);
s << endl;
}
static void emit_blti(char *src1, int imm, int label, ostream &s)
{
s << BLT << src1 << " " << imm << " ";
emit_label_ref(label,s);
s << endl;
}
static void emit_bgti(char *src1, int imm, int label, ostream &s)
{
s << BGT << src1 << " " << imm << " ";
emit_label_ref(label,s);
s << endl;
}
static void emit_branch(int l, ostream& s)
{
s << BRANCH;
emit_label_ref(l,s);
s << endl;
}
//
// Push a register on the stack. The stack grows towards smaller addresses.
//
static void emit_push(char *reg, ostream& str)
{
emit_store(reg,0,SP,str);
emit_addiu(SP,SP,-4,str);
}
//
// Pop a value off of the stack into a register. Stack address increases.
//
static void emit_pop(char *reg, ostream& str)
{
emit_load(reg,1,SP,str);
emit_addiu(SP,SP,4,str);
}
//
// Fetch the integer value in an Int object.
// Emits code to fetch the integer value of the Integer object pointed
// to by register source into the register dest
//
static void emit_fetch_int(char *dest, char *source, ostream& s)
{ emit_load(dest, DEFAULT_OBJFIELDS, source, s); }
//
// Emits code to store the integer value contained in register source
// into the Integer object pointed to by dest.
//
static void emit_store_int(char *source, char *dest, ostream& s)
{ emit_store(source, DEFAULT_OBJFIELDS, dest, s); }
static void emit_test_collector(ostream &s)
{
emit_push(ACC, s);
emit_move(ACC, SP, s); // stack end
emit_move(A1, ZERO, s); // allocate nothing
s << JAL << gc_collect_names[cgen_Memmgr] << endl;
emit_addiu(SP,SP,4,s);
emit_load(ACC,0,SP,s);
}
static void emit_gc_check(char *source, ostream &s)
{
if (source != (char*)A1) emit_move(A1, source, s);
s << JAL << "_gc_check" << endl;
}
///////////////////////////////////////////////////////////////////////////////
//
// coding strings, ints, and booleans
//
// Cool has three kinds of constants: strings, ints, and booleans.
// This section defines code generation for each type.
//
// All string constants are listed in the global "stringtable" and have
// type StringEntry. StringEntry methods are defined both for String
// constant definitions and references.
//
// All integer constants are listed in the global "inttable" and have
// type IntEntry. IntEntry methods are defined for Int
// constant definitions and references.
//
// Since there are only two Bool values, there is no need for a table.
// The two booleans are represented by instances of the class BoolConst,
// which defines the definition and reference methods for Bools.
//
///////////////////////////////////////////////////////////////////////////////
//
// Strings
//
void StringEntry::code_ref(ostream& s)
{
s << STRCONST_PREFIX << index;
}
//
// Emit code for a constant String.
// You should fill in the code naming the dispatch table.
//
void StringEntry::code_def(ostream& s, int stringclasstag)
{
IntEntryP lensym = inttable.add_int(len);
// Add -1 eye catcher
s << WORD << "-1" << endl;
code_ref(s); s << LABEL // label
<< WORD << stringclasstag << endl // tag
<< WORD << (DEFAULT_OBJFIELDS + STRING_SLOTS + (len+4)/4) << endl // size
<< WORD;
/***** Add dispatch information for class String ******/
s << "String_dispTab" << endl; // dispatch table
s << WORD; lensym->code_ref(s); s << endl; // string length
emit_string_constant(s,str); // ascii string
s << ALIGN; // align to word
}
//
// StrTable::code_string
// Generate a string object definition for every string constant in the
// stringtable.
//
void StrTable::code_string_table(ostream& s, int stringclasstag)
{
for (List<StringEntry> *l = tbl; l; l = l->tl())
l->hd()->code_def(s,stringclasstag);
}
//
// Ints
//
void IntEntry::code_ref(ostream &s)
{
s << INTCONST_PREFIX << index;
}
//
// Emit code for a constant Integer.
// You should fill in the code naming the dispatch table.
//
void IntEntry::code_def(ostream &s, int intclasstag)
{
// Add -1 eye catcher
s << WORD << "-1" << endl;
code_ref(s); s << LABEL // label
<< WORD << intclasstag << endl // class tag
<< WORD << (DEFAULT_OBJFIELDS + INT_SLOTS) << endl // object size
<< WORD;
/***** Add dispatch information for class Int ******/
s << "Int_dispTab" << endl; // dispatch table
s << WORD << str << endl; // integer value
}
//
// IntTable::code_string_table
// Generate an Int object definition for every Int constant in the
// inttable.
//
void IntTable::code_string_table(ostream &s, int intclasstag)
{
for (List<IntEntry> *l = tbl; l; l = l->tl())
l->hd()->code_def(s,intclasstag);
}
//
// Bools
//
BoolConst::BoolConst(int i) : val(i) { assert(i == 0 || i == 1); }
void BoolConst::code_ref(ostream& s) const
{
s << BOOLCONST_PREFIX << val;
}
//
// Emit code for a constant Bool.
// You should fill in the code naming the dispatch table.
//
void BoolConst::code_def(ostream& s, int boolclasstag)
{
// Add -1 eye catcher
s << WORD << "-1" << endl;
code_ref(s); s << LABEL // label
<< WORD << boolclasstag << endl // class tag
<< WORD << (DEFAULT_OBJFIELDS + BOOL_SLOTS) << endl // object size
<< WORD;
/***** Add dispatch information for class Bool ******/
s << "Bool_dispTab" << endl; // dispatch table
s << WORD << val << endl; // value (0 or 1)
}
//////////////////////////////////////////////////////////////////////////////
//
// CgenClassTable methods
//
//////////////////////////////////////////////////////////////////////////////
//***************************************************
//
// Emit code to start the .data segment and to
// declare the global names.
//
//***************************************************
void CgenClassTable::code_global_data()
{
Symbol main = idtable.lookup_string(MAINNAME);
Symbol string = idtable.lookup_string(STRINGNAME);
Symbol integer = idtable.lookup_string(INTNAME);
Symbol boolc = idtable.lookup_string(BOOLNAME);
str << "\t.data\n" << ALIGN;
//
// The following global names must be defined first.
//
str << GLOBAL << CLASSNAMETAB << endl;
str << GLOBAL; emit_protobj_ref(main,str); str << endl;
str << GLOBAL; emit_protobj_ref(integer,str); str << endl;
str << GLOBAL; emit_protobj_ref(string,str); str << endl;
str << GLOBAL; falsebool.code_ref(str); str << endl;
str << GLOBAL; truebool.code_ref(str); str << endl;
str << GLOBAL << INTTAG << endl;
str << GLOBAL << BOOLTAG << endl;
str << GLOBAL << STRINGTAG << endl;
//
// We also need to know the tag of the Int, String, and Bool classes
// during code generation.
//
str << INTTAG << LABEL
<< WORD << intclasstag << endl;
str << BOOLTAG << LABEL
<< WORD << boolclasstag << endl;
str << STRINGTAG << LABEL
<< WORD << stringclasstag << endl;
}
//***************************************************
//
// Emit code to start the .text segment and to
// declare the global names.
//
//***************************************************
void CgenClassTable::code_global_text()
{
str << GLOBAL << HEAP_START << endl
<< HEAP_START << LABEL
<< WORD << 0 << endl
<< "\t.text" << endl
<< GLOBAL;
emit_init_ref(idtable.add_string("Main"), str);
str << endl << GLOBAL;
emit_init_ref(idtable.add_string("Int"),str);
str << endl << GLOBAL;
emit_init_ref(idtable.add_string("String"),str);
str << endl << GLOBAL;
emit_init_ref(idtable.add_string("Bool"),str);
str << endl << GLOBAL;
emit_method_ref(idtable.add_string("Main"), idtable.add_string("main"), str);
str << endl;
}
void CgenClassTable::code_bools(int boolclasstag)
{
falsebool.code_def(str,boolclasstag);
truebool.code_def(str,boolclasstag);
}
void CgenClassTable::code_select_gc()
{
//
// Generate GC choice constants (pointers to GC functions)
//
str << GLOBAL << "_MemMgr_INITIALIZER" << endl;
str << "_MemMgr_INITIALIZER:" << endl;
str << WORD << gc_init_names[cgen_Memmgr] << endl;
str << GLOBAL << "_MemMgr_COLLECTOR" << endl;
str << "_MemMgr_COLLECTOR:" << endl;
str << WORD << gc_collect_names[cgen_Memmgr] << endl;
str << GLOBAL << "_MemMgr_TEST" << endl;
str << "_MemMgr_TEST:" << endl;
str << WORD << (cgen_Memmgr_Test == GC_TEST) << endl;
}
//********************************************************
//
// Emit code to reserve space for and initialize all of
// the constants. Class names should have been added to
// the string table (in the supplied code, is is done
// during the construction of the inheritance graph), and
// code for emitting string constants as a side effect adds
// the string's length to the integer table. The constants
// are emmitted by running through the stringtable and inttable
// and producing code for each entry.
//
//********************************************************
void CgenClassTable::code_constants()
{
//
// Add constants that are required by the code generator.
//
stringtable.add_string("");
inttable.add_string("0");
stringtable.code_string_table(str,stringclasstag);
inttable.code_string_table(str,intclasstag);
code_bools(boolclasstag);
}
// emit code for the global class name table
void CgenClassTable::code_class_name_table()
{
if (cgen_debug) str << "# start of class name table code\n";
str << CLASSNAMETAB << LABEL;
code_class_name_table(root());
if (cgen_debug) str << "# end of class name table code\n\n";
}
void CgenClassTable::code_class_name_table(CgenNodeP nd)
{
// get string constant entry
StringEntry *strEnt = stringtable.lookup_string(nd->name->get_string());
str << WORD;
strEnt->code_ref(str);
str << endl;
// store class in global map for dispatch
classNameMap.insert(std::pair<Symbol, CgenNodeP>(nd->name, nd));
// recurse
for (List<CgenNode> *l = nd->get_children(); l; l = l->tl())
code_class_name_table(l->hd());
}
// emit code for the global class object table
void CgenClassTable::code_class_obj_table()
{
if (cgen_debug) str << "# start of class obj table code\n";
str << CLASSOBJTAB << LABEL;
code_class_obj_table(root());
if (cgen_debug) str << "# end of class obj table code\n\n";
}
void CgenClassTable::code_class_obj_table(CgenNodeP nd)
{
// emit prototype object reference
str << WORD;
emit_protobj_ref(nd->name, str);
str << endl;
// emit object initializer reference
str << WORD;
emit_init_ref(nd->name, str);
str << endl;
// recurse
for (List<CgenNode> *l = nd->get_children(); l; l = l->tl())
code_class_obj_table(l->hd());
}
// emit code for the class dispatch tables
void CgenClassTable::code_dispatch_tables()
{
if (cgen_debug) str << "# start of dispatch tables code\n";
code_dispatch_table(root());
if (cgen_debug) str << "# end of dispatch tables code\n\n";
}
void CgenClassTable::code_dispatch_table(CgenNodeP nd)
{
emit_disptable_ref(nd->name, str);
str << LABEL;
// set up vector of nd's inherited classes (including itself)
if (cgen_debug)
cout << nd->name->get_string() << " inherited classes:" << endl;
std::vector<CgenNodeP> inherited;
for (CgenNodeP currNode = nd; currNode->name != No_class; currNode = currNode->get_parentnd()) {
inherited.push_back(currNode);
if (cgen_debug)
cout << "\t" << currNode->name->get_string() << endl;
}
// inherited.back() should be Object in all cases
if (cgen_debug)
cout << "\tgreatest ancestor: " << inherited.back()->name->get_string() << endl;
// add all inherited class methods to dispatch table
int methodIndex = 0;
for (int i = inherited.size()-1; i >= 0; i--) {
CgenNodeP node = inherited[i];
Features features = node->features;
// check if feature is a method, then emit reference
for (int j = features->first(); features->more(j); j = features->next(j)) {
if (features->nth(j)->featureType == FEATURE_TYPE_METHOD) {
method_class *m = (method_class *)features->nth(j);
str << WORD;
emit_method_ref(node->name, m->name, str);
str << endl;
nd->methodIndexMap.insert(std::pair<Symbol, int>(m->name, methodIndex));
if (cgen_debug)
cout << nd->name->get_string() << " method index: " << methodIndex << endl;
methodIndex++;
}
}
}
// recurse
for (List<CgenNode> *l = nd->get_children(); l; l = l->tl())
code_dispatch_table(l->hd());
}
// emit code for all class' prototype objects
void CgenClassTable::code_proto_objects()
{
if (cgen_debug) str << "# start of prototype objects code\n";
code_proto_object(root());
if (cgen_debug) str << "# end of prototype objects code\n\n";
}
void CgenClassTable::code_proto_object(CgenNodeP nd)
{
// garbage collection
str << WORD << "-1" << endl;
// emit the label
emit_protobj_ref(nd->name, str);
str << LABEL;
// set up vector of nd's inherited classes (including itself)
std::vector<CgenNodeP> inherited;
for (CgenNodeP currNode = nd; currNode->name != No_class; currNode = currNode->get_parentnd())
inherited.push_back(currNode);
// set up vector of nd's inherited attributes (including its own)
std::vector<attr_class*> attrs;
for (int i = inherited.size()-1; i >= 0; i--) {
CgenNodeP node = inherited[i];
Features features = node->features;
// check if feature is an attr, then add to vector
for (int j = features->first(); features->more(j); j = features->next(j)) {
if (features->nth(j)->featureType == FEATURE_TYPE_ATTR) {
attr_class *a = (attr_class *)features->nth(j);
attrs.push_back(a);
}
}
}
// emit class tag, object size, and dispatch table reference
str << WORD << nd->classTag << endl;
str << WORD << (attrs.size() + 3) << endl;
str << WORD;
emit_disptable_ref(nd->name, str);
str << endl;
if (cgen_debug)
cout << nd->name->get_string() << " attribute indices:" << endl;
// emit all attributes
for (unsigned int i = 0; i < attrs.size(); i++) {
attr_class *a = attrs[i];
str << WORD;
// emit default value based on type
if (a->type_decl == Int) {
IntEntry *intEnt = inttable.lookup_string("0");
intEnt->code_ref(str);
} else if (a->type_decl == Bool) {
falsebool.code_ref(str);
} else if (a->type_decl == Str) {
StringEntry *strEnt = stringtable.lookup_string("");
strEnt->code_ref(str);
} else {
// default of all other classes is void (null char or "0"?)
str << 0;
}
str << endl;
nd->attrIndexMap.insert(std::pair<Symbol, int>(a->name, i+3));
if (cgen_debug)
cout << "\t" << a->name->get_string() << ": " << (i+3) << endl;
}
// recurse
for (List<CgenNode> *l = nd->get_children(); l; l = l->tl())
code_proto_object(l->hd());
}
// emit code for all class' object initializers
void CgenClassTable::code_initializers()
{
if (cgen_debug) str << "# start of initializers code\n";
code_initializer(root());
if (cgen_debug) str << "# end of initializers code\n\n";
}
void CgenClassTable::code_initializer(CgenNodeP nd)
{
// emit the label
emit_init_ref(nd->name, str);
str << LABEL;
// push the frame pointer, self reg, and return address
emit_push(FP, str);
emit_push(SELF, str);
emit_push(RA, str);
// new frame pointer and store accum before parent call
emit_addiu(FP, SP, WORD_SIZE, str);
emit_move(SELF, ACC, str);
// call parent's init method (handles inherited attr inits)
if (nd->name != Object) {
std::string parentName = nd->get_parentnd()->name->get_string();
emit_jal((char *)(parentName + CLASSINIT_SUFFIX).c_str(), str);
}
// attribute initializers if present and not a basic class
if (!nd->basic()) {
Features features = nd->features;
if (cgen_debug)
cout << nd->name->get_string() << " attr inits:" << endl;
for (int i = features->first(); features->more(i); i = features->next(i)) {
if (features->nth(i)->featureType == FEATURE_TYPE_ATTR) {
attr_class *a = (attr_class *)features->nth(i);
// code initializer expression
// if not present, no_expr::code() still does nothing
a->init->code(str, nd);
// store result (from accum) at attr offset
std::map<Symbol, int>::iterator ind = nd->attrIndexMap.find(a->name);
if (ind != nd->attrIndexMap.end()) {
emit_store(ACC, ind->second, SELF, str);
if (cgen_debug)
cout << "\t" << a->name->get_string() << ": " << ind->second << endl;
}
}
}
}
// restore state and return to caller
emit_move(ACC, SELF, str);
emit_pop(RA, str);
emit_pop(SELF, str);
emit_pop(FP, str);
emit_return(str);
// recurse
for (List<CgenNode> *l = nd->get_children(); l; l = l->tl())
code_initializer(l->hd());
}
// emit code for all class' methods
void CgenClassTable::code_methods()
{
if (cgen_debug) str << "# start of methods code\n";
code_methods(root());
if (cgen_debug) str << "# end of methods code\n\n";
}
void CgenClassTable::code_methods(CgenNodeP nd)
{
// ignore basic classes, already in runtime environment
if (!nd->basic()) {
Features features = nd->features;
if (cgen_debug)
cout << nd->name->get_string() << " methods:" << endl;
for (int i = features->first(); features->more(i); i = features->next(i)) {
if (features->nth(i)->featureType == FEATURE_TYPE_METHOD) {
method_class *m = (method_class *)features->nth(i);
// emit the label
emit_method_ref(nd->name, m->name, str);
str << LABEL;
// push the frame pointer, self reg, and return address
emit_push(FP, str);
emit_push(SELF, str);
emit_push(RA, str);
// new frame pointer and store accum before method call
emit_addiu(FP, SP, WORD_SIZE, str);
emit_move(SELF, ACC, str);
// set up formals offsets
if (cgen_debug)
cout << "\t" << m->name->get_string() << " formals:" << endl;
Formals formals = m->formals;
for (int j = formals->first(); formals->more(j); j = formals->next(j)) {
formal_class *f = (formal_class *)formals->nth(j);
if (cgen_debug)
cout << "\t\t" << f->name->get_string() << ": " << j << endl;
}
// code the method body
m->expr->code(str, nd);
// restore state and return to caller
emit_move(ACC, SELF, str);
emit_pop(RA, str);
emit_pop(SELF, str);
emit_pop(FP, str);
emit_return(str);
}
}
}
// recurse
for (List<CgenNode> *l = nd->get_children(); l; l = l->tl())
code_methods(l->hd());
}
CgenClassTable::CgenClassTable(Classes classes, ostream& s) : nds(NULL) , str(s)
{
stringclasstag = 4 /* Change to your String class tag here */;
intclasstag = 2 /* Change to your Int class tag here */;
boolclasstag = 3 /* Change to your Bool class tag here */;
// counter for setting class tags
currClassTag = 0;
enterscope();
if (cgen_debug) cout << "Building CgenClassTable" << endl << endl;
install_basic_classes();
install_classes(classes);
build_inheritance_tree();
// set up unique class tags correctly for use in typecase
set_class_tags();
code();
exitscope();
}
void CgenClassTable::install_basic_classes()
{
// The tree package uses these globals to annotate the classes built below.
//curr_lineno = 0;
Symbol filename = stringtable.add_string("<basic class>");
//
// A few special class names are installed in the lookup table but not
// the class list. Thus, these classes exist, but are not part of the
// inheritance hierarchy.
// No_class serves as the parent of Object and the other special classes.
// SELF_TYPE is the self class; it cannot be redefined or inherited.
// prim_slot is a class known to the code generator.
//
addid(No_class,
new CgenNode(class_(No_class,No_class,nil_Features(),filename),
Basic,this));
addid(SELF_TYPE,
new CgenNode(class_(SELF_TYPE,No_class,nil_Features(),filename),
Basic,this));
addid(prim_slot,
new CgenNode(class_(prim_slot,No_class,nil_Features(),filename),
Basic,this));
//
// The Object class has no parent class. Its methods are
// cool_abort() : Object aborts the program
// type_name() : Str returns a string representation of class name
// copy() : SELF_TYPE returns a copy of the object
//
// There is no need for method bodies in the basic classes---these
// are already built in to the runtime system.
//
install_class(
new CgenNode(
class_(Object,
No_class,
append_Features(
append_Features(
single_Features(method(cool_abort, nil_Formals(), Object, no_expr())),
single_Features(method(type_name, nil_Formals(), Str, no_expr()))),
single_Features(method(copy, nil_Formals(), SELF_TYPE, no_expr()))),
filename),
Basic,this));
//
// The IO class inherits from Object. Its methods are
// out_string(Str) : SELF_TYPE writes a string to the output
// out_int(Int) : SELF_TYPE " an int " " "
// in_string() : Str reads a string from the input
// in_int() : Int " an int " " "
//
install_class(
new CgenNode(
class_(IO,
Object,
append_Features(
append_Features(
append_Features(
single_Features(method(out_string, single_Formals(formal(arg, Str)),
SELF_TYPE, no_expr())),
single_Features(method(out_int, single_Formals(formal(arg, Int)),
SELF_TYPE, no_expr()))),
single_Features(method(in_string, nil_Formals(), Str, no_expr()))),
single_Features(method(in_int, nil_Formals(), Int, no_expr()))),
filename),
Basic,this));
//
// The Int class has no methods and only a single attribute, the
// "val" for the integer.
//
install_class(
new CgenNode(
class_(Int,
Object,
single_Features(attr(val, prim_slot, no_expr())),
filename),
Basic,this));
//
// Bool also has only the "val" slot.
//
install_class(
new CgenNode(
class_(Bool, Object, single_Features(attr(val, prim_slot, no_expr())),filename),
Basic,this));
//
// The class Str has a number of slots and operations:
// val ???
// str_field the string itself
// length() : Int length of the string
// concat(arg: Str) : Str string concatenation
// substr(arg: Int, arg2: Int): Str substring
//
install_class(
new CgenNode(
class_(Str,
Object,
append_Features(
append_Features(
append_Features(
append_Features(
single_Features(attr(val, Int, no_expr())),
single_Features(attr(str_field, prim_slot, no_expr()))),
single_Features(method(length, nil_Formals(), Int, no_expr()))),
single_Features(method(concat,
single_Formals(formal(arg, Str)),
Str,
no_expr()))),
single_Features(method(substr,
append_Formals(single_Formals(formal(arg, Int)),
single_Formals(formal(arg2, Int))),
Str,
no_expr()))),
filename),
Basic,this));
}
// CgenClassTable::install_class
// CgenClassTable::install_classes
//
// install_classes enters a list of classes in the symbol table.
//
void CgenClassTable::install_class(CgenNodeP nd)
{
Symbol name = nd->get_name();
if (probe(name))
{
return;
}
// The class name is legal, so add it to the list of classes
// and the symbol table.
nds = new List<CgenNode>(nd,nds);
addid(name,nd);
}
void CgenClassTable::install_classes(Classes cs)
{
for(int i = cs->first(); cs->more(i); i = cs->next(i))
install_class(new CgenNode(cs->nth(i),NotBasic,this));
}
//
// CgenClassTable::build_inheritance_tree
//
void CgenClassTable::build_inheritance_tree()
{
for(List<CgenNode> *l = nds; l; l = l->tl())
set_relations(l->hd());
}
//
// CgenClassTable::set_relations
//
// Takes a CgenNode and locates its, and its parent's, inheritance nodes
// via the class table. Parent and child pointers are added as appropriate.
//
void CgenClassTable::set_relations(CgenNodeP nd)
{
CgenNode *parent_node = probe(nd->get_parent());
nd->set_parentnd(parent_node);
parent_node->add_child(nd);
}
void CgenNode::add_child(CgenNodeP n)
{
children = new List<CgenNode>(n,children);
}
void CgenNode::set_parentnd(CgenNodeP p)
{
assert(parentnd == NULL);
assert(p != NULL);
parentnd = p;
}
//
// CgenClassTable::set_class_tags
//
// wrapper for recursive inheritance graph traversal
void CgenClassTable::set_class_tags()
{
if (cgen_debug)
cout << "The root is: " << root()->name->get_string() << endl; // sanity check
set_class_tag(root());
}
void CgenClassTable::set_class_tag(CgenNodeP nd)
{
nd->classTag = currClassTag++;
if (cgen_debug)
cout << nd->name->get_string() << " class tag: " << nd->classTag << endl;
for (List<CgenNode> *l = nd->get_children(); l != NULL; l = l->tl())
set_class_tag(l->hd());
// store tag of lowest child for case set-up
nd->lastChildTag = currClassTag-1;
if (cgen_debug)
cout << "lastChild(" << nd->name->get_string() << "): " << nd->lastChildTag << endl;
}
void CgenClassTable::code()
{
if (cgen_debug) cout << "#### coding global data ####" << endl << endl;
code_global_data();
if (cgen_debug) cout << "#### choosing gc ####" << endl << endl;
code_select_gc();
if (cgen_debug) cout << "#### coding constants ####" << endl << endl;
code_constants();
// code global table stuffs
if (cgen_debug) cout << "#### coding class name table ####" << endl << endl;
code_class_name_table();
if (cgen_debug) cout << "#### coding class obj table ####" << endl << endl;
code_class_obj_table();
if (cgen_debug) cout << "#### coding dispatch tables ####" << endl << endl;
code_dispatch_tables();
if (cgen_debug) cout << "#### coding prototype objects ####" << endl << endl;
code_proto_objects();
if (cgen_debug) cout << "#### coding global text ####" << endl << endl;
code_global_text();
// code object initializers and methods
if (cgen_debug) cout << "#### coding initializers ####" << endl << endl;
code_initializers();
if (cgen_debug) cout << "#### coding methods ####" << endl << endl;
code_methods();
}
CgenNodeP CgenClassTable::root()
{
return probe(Object);
}
///////////////////////////////////////////////////////////////////////
//
// CgenNode methods
//
///////////////////////////////////////////////////////////////////////
CgenNode::CgenNode(Class_ nd, Basicness bstatus, CgenClassTableP ct) :
class__class((const class__class &) *nd),
parentnd(NULL),
children(NULL),
basic_status(bstatus)
{
stringtable.add_string(name->get_string()); // Add class name to string table
}
//******************************************************************
//
// Fill in the following methods to produce code for the
// appropriate expression. You may add or remove parameters
// as you wish, but if you do, remember to change the parameters
// of the declarations in `cool-tree.h' Sample code for
// constant integers, strings, and booleans are provided.
//
//*****************************************************************
// stores current formal params when entering a method call
// -- index of param = offset from FP
std::vector<Expression> params;
// stores current local variables, scope enforced by order (closest scope near end)
// -- index of var = offset from FP
std::vector<Symbol> locals;
void assign_class::code(ostream &s, CgenNodeP nd) {
// evaluate expression
expr->code(s, nd);
// check for object name in local variables
for (int i = locals.size() - 1; i >= 0; i--) {
if (locals[i] == name) {
int offset = i;
emit_store(ACC, offset+3, FP, s);
return;
}
}
// check for object name in formals
for (int i = params.size() - 1; i >= 0; i--) {
// ???
}
// otherwise, attribute
int offset = nd->attrIndexMap.find(name)->second;
emit_store(ACC, offset, SELF, s);
}
void static_dispatch_class::code(ostream &s, CgenNodeP nd) {
// evaluate parameters in reverse order, storing each on the stack
for (int i = actual->first(); actual->more(i); i = actual->next(i))
params.push_back(actual->nth(i));
for (int i = params.size() - 1; i >= 0; i--) {
params[i]->code(s, nd);
emit_push(ACC, s);
}
int validLabel = CgenNode::labelIndex++;
int endLabel = CgenNode::labelIndex++;
// branch if object is valid (not void)
expr->code(s, nd);
emit_bne(ACC, ZERO, validLabel, s);
// expr was void, dispatch abort
emit_load_string(ACC, stringtable.lookup_string(nd->filename->get_string()), s);
emit_load_imm(T1, get_line_number(), s);
emit_jal("_dispatch_abort", s);
emit_branch(endLabel, s);
// expr was not void, perform the dispatch
emit_label_def(validLabel, s);
std::string dispTab = type_name->get_string();
dispTab += DISPTAB_SUFFIX;
emit_load_address(T1, (char *)dispTab.c_str(), s);
// find method index for type_name class
CgenNodeP node = classNameMap.find(type_name)->second;
int offset = node->methodIndexMap.find(name)->second;
emit_load(T1, offset, T1, s);
// call method and fall through
emit_jalr(T1, s);
emit_label_def(endLabel, s);
// clear params
params.clear();
}
void dispatch_class::code(ostream &s, CgenNodeP nd) {
// evaluate parameters in reverse order, storing each on the stack
for (int i = actual->first(); actual->more(i); i = actual->next(i))
params.push_back(actual->nth(i));
for (int i = params.size() - 1; i >= 0; i--) {
params[i]->code(s, nd);
emit_push(ACC, s);
}
int validLabel = CgenNode::labelIndex++;
int endLabel = CgenNode::labelIndex++;
// branch if object is valid (not void)
expr->code(s, nd);
emit_bne(ACC, ZERO, validLabel, s);
// expr was void, dispatch abort
emit_load_string(ACC, stringtable.lookup_string(nd->filename->get_string()), s);
emit_load_imm(T1, get_line_number(), s);
emit_jal("_dispatch_abort", s);
emit_branch(endLabel, s);
// expr was not void, perform the dispatch
emit_label_def(validLabel, s);
emit_load(T1, DISPTABLE_OFFSET, ACC, s); // ACC holds expr's return object
// find method index for expr's class
CgenNodeP node = classNameMap.find(expr->type)->second;
int offset = node->methodIndexMap.find(name)->second;
emit_load(T1, offset, T1, s);
// call method and fall through
emit_jalr(T1, s);
emit_label_def(endLabel, s);
params.clear();
}
void cond_class::code(ostream &s, CgenNodeP nd) {
// evaluate predicate, store result on stack
pred->code(s, nd);
emit_push(ACC, s);
int elseLabel = CgenNode::labelIndex++;
int endLabel = CgenNode::labelIndex++;
// branch on pred's boolean (int) value
emit_pop(T1, s); // contains pred's Bool object
emit_fetch_int(T1, T1, s);
emit_beqz(T1, elseLabel, s);
// here e1 was true, so execute then branch and jump to end
then_exp->code(s, nd);
emit_branch(endLabel, s);
// otherwise pred was false, so execute else branch and fall through
emit_label_def(elseLabel, s);
else_exp->code(s, nd);
emit_label_def(endLabel, s);
}
void loop_class::code(ostream &s, CgenNodeP nd) {
int startLabel = CgenNode::labelIndex++;
int endLabel = CgenNode::labelIndex++;
// branch on pred's boolean (int) value
emit_label_def(startLabel, s);
pred->code(s, nd);
emit_fetch_int(T1, ACC, s);
emit_beqz(T1, endLabel, s);
// here pred was true, so execute the body and jump back to start
body->code(s, nd);
emit_branch(startLabel, s);
// otherwise pred was false, so fall through and return void
emit_label_def(endLabel, s);
emit_load_imm(ACC, 0, s);
}
void typcase_class::code(ostream &s, CgenNodeP nd) {
// evaluate the expression, store result on stack
expr->code(s, nd);
int startCaseLabel = CgenNode::labelIndex++;
int endCaseLabel = CgenNode::labelIndex++;
// check for valid object (non-void)
emit_bne(ACC, ZERO, startCaseLabel, s);
emit_load_string(ACC, stringtable.lookup_string(nd->filename->get_string()), s);
emit_load_imm(T1, get_line_number(), s);
emit_jal("_case_abort2", s);
emit_branch(endCaseLabel, s);
// sort cases by decreasing class tag
std::vector<std::pair<int, int> > branchSortingMap; // class tag -> caselist index
for (int i = cases->first(); cases->more(i); i = cases->next(i)) {
branch_class *b = (branch_class *)cases->nth(i);
CgenNodeP node = classNameMap.find(b->type_decl)->second;
branchSortingMap.push_back(std::pair<int, int>(node->classTag, i));
}
std::sort(branchSortingMap.begin(), branchSortingMap.end());
emit_label_def(startCaseLabel, s);
// TODO: iterate through branchSortingMap, emitting code for each case branch
emit_label_def(endCaseLabel, s);
}
void block_class::code(ostream &s, CgenNodeP nd) {
// code each expression
for (int i = body->first(); body->more(i); i = body->next(i))
body->nth(i)->code(s, nd);
}
void let_class::code(ostream &s, CgenNodeP nd) {
// if no initialization, create prototype object
if (init->exprType == EXPR_TYPE_NO_EXPR) {
// get class tag
if (type_decl == SELF_TYPE) {
emit_load(T1, TAG_OFFSET, SELF, s);
} else {
CgenNodeP node = classNameMap.find(type_decl)->second;
emit_load_imm(T1, node->classTag, s);
}
// load object table address
emit_load_address(T2, CLASSOBJTAB, s);
// create new class prototype object
emit_load_imm(T3, 8, s); // each class uses 2 words (8 bytes) in objTab
emit_mul(T1, T1, T3, s); // now holds offset into objTab
emit_addu(ACC, T2, T1, s); // now ACC holds address to class_protObj
emit_jal("Object.copy", s);
// call class' init function (one word after protObj)
emit_load(T1, 1, ACC, s);
emit_jal(T1, s);
} else {
init->code(s, nd);
}
// store local var on stack and put in scope
emit_push(ACC, s);
locals.push_back(identifier);
// emit code for the body
body->code(s, nd);
// restore stack and remove the local var from scope
emit_pop(T1, s);
locals.pop_back();
}
void plus_class::code(ostream &s, CgenNodeP nd) {
// evaluate first expr, store result on stack
e1->code(s, nd);
emit_push(ACC, s);
// evaluate second expr, store result on stack
e2->code(s, nd);
emit_push(ACC, s);
// create new Int prototype object
std::string intProtObj = "Int";
intProtObj += PROTOBJ_SUFFIX;
emit_load_address(ACC, (char *)intProtObj.c_str(), s);
emit_jal("Object.copy", s);
// compute sum
emit_pop(T2, s); // contains e2's Int object
emit_pop(T1, s); // contains e1's Int object
emit_fetch_int(T2, T2, s);
emit_fetch_int(T1, T1, s);
emit_add(T3, T1, T2, s); // T3 contains result value
// store value in object
emit_store(T3, DEFAULT_OBJFIELDS, ACC, s);
}
void sub_class::code(ostream &s, CgenNodeP nd) {
// evaluate first expr, store result on stack
e1->code(s, nd);
emit_push(ACC, s);
// evaluate second expr, store result on stack
e2->code(s, nd);
emit_push(ACC, s);
// create new Int prototype object
std::string intProtObj = "Int";
intProtObj += PROTOBJ_SUFFIX;
emit_load_address(ACC, (char *)intProtObj.c_str(), s);
emit_jal("Object.copy", s);
// compute difference
emit_pop(T2, s); // contains e2's Int object
emit_pop(T1, s); // contains e1's Int object
emit_fetch_int(T2, T2, s);
emit_fetch_int(T1, T1, s);
emit_sub(T3, T1, T2, s); // T3 contains result value
// store value in object
emit_store(T3, DEFAULT_OBJFIELDS, ACC, s);
}
void mul_class::code(ostream &s, CgenNodeP nd) {
// evaluate first expr, store result on stack
e1->code(s, nd);
emit_push(ACC, s);
// evaluate second expr, store result on stack
e2->code(s, nd);
emit_push(ACC, s);
// create new Int prototype object
std::string intProtObj = "Int";
intProtObj += PROTOBJ_SUFFIX;
emit_load_address(ACC, (char *)intProtObj.c_str(), s);
emit_jal("Object.copy", s);
// compute product
emit_pop(T2, s); // contains e2's Int object
emit_pop(T1, s); // contains e1's Int object
emit_fetch_int(T2, T2, s);
emit_fetch_int(T1, T1, s);
emit_mul(T3, T1, T2, s); // T3 contains result value
// store value in object
emit_store(T3, DEFAULT_OBJFIELDS, ACC, s);
}
void divide_class::code(ostream &s, CgenNodeP nd) {
// evaluate first expr, store result on stack
e1->code(s, nd);
emit_push(ACC, s);
// evaluate second expr, store result on stack
e2->code(s, nd);
emit_push(ACC, s);
// create new Int prototype object
std::string intProtObj = "Int";
intProtObj += PROTOBJ_SUFFIX;
emit_load_address(ACC, (char *)intProtObj.c_str(), s);
emit_jal("Object.copy", s);
// compute division
emit_pop(T2, s); // contains e2's Int object
emit_pop(T1, s); // contains e1's Int object
emit_fetch_int(T2, T2, s);
emit_fetch_int(T1, T1, s);
emit_div(T3, T1, T2, s); // T3 contains result value
// store value in object
emit_store(T3, DEFAULT_OBJFIELDS, ACC, s);
}
void neg_class::code(ostream &s, CgenNodeP nd) {
// evaluate expr, store result on stack
e1->code(s, nd);
emit_push(ACC, s);
// create new Int prototype object
std::string intProtObj = "Int";
intProtObj += PROTOBJ_SUFFIX;
emit_load_address(ACC, (char *)intProtObj.c_str(), s);
emit_jal("Object.copy", s);
// compute negation
emit_pop(T1, s); // contains e1's Int object
emit_fetch_int(T1, T1, s);
emit_neg(T1, T1, s); // T1 contains result value
// store value in object
emit_store(T1, DEFAULT_OBJFIELDS, ACC, s);
}
void lt_class::code(ostream &s, CgenNodeP nd) {
// evaluate first expr, store result on stack
e1->code(s, nd);
emit_push(ACC, s);
// evaluate second expr, store result on stack
e2->code(s, nd);
emit_push(ACC, s);
int lessThanLabel = CgenNode::labelIndex++;
int endLabel = CgenNode::labelIndex++;
// branch on e1 and e2's value
emit_pop(T2, s);
emit_fetch_int(T2, T2, s);
emit_pop(T1, s);
emit_fetch_int(T1, T1, s);
emit_blt(T1, T2, lessThanLabel, s);
// here e1 ~< e2, so emit a falsebool and jump to end
emit_load_bool(ACC, falsebool, s);
emit_branch(endLabel, s);
// otherwise e1 < e2, so emit a truebool and fall through
emit_label_def(lessThanLabel, s);
emit_load_bool(ACC, truebool, s);
emit_label_def(endLabel, s);
}
void eq_class::code(ostream &s, CgenNodeP nd) {
// evaluate first expr, store result on stack
e1->code(s, nd);
emit_push(ACC, s);
// evaluate second expr, store result on stack
e2->code(s, nd);
emit_push(ACC, s);
int equalLabel = CgenNode::labelIndex++;
int endLabel = CgenNode::labelIndex++;
// branch on e1 and e2's pointers
emit_pop(T2, s);
emit_pop(T1, s);
emit_beq(T1, T2, equalLabel, s);
// here e1 ~= e2, so emit a falsebool, test primitive equality, then jump to end
emit_load_bool(ACC, falsebool, s);
emit_jal("equality_test", s);
emit_branch(endLabel, s);
// otherwise e1 = e2, so emit a truebool and fall through
emit_label_def(equalLabel, s);
emit_load_bool(ACC, truebool, s);
emit_label_def(endLabel, s);
}
void leq_class::code(ostream &s, CgenNodeP nd) {
// evaluate first expr, store result on stack
e1->code(s, nd);
emit_push(ACC, s);
// evaluate second expr, store result on stack
e2->code(s, nd);
emit_push(ACC, s);
int lessThanEqLabel = CgenNode::labelIndex++;
int endLabel = CgenNode::labelIndex++;
// branch on e1 and e2's value
emit_pop(T2, s);
emit_fetch_int(T2, T2, s);
emit_pop(T1, s);
emit_fetch_int(T1, T1, s);
emit_bleq(T1, T2, lessThanEqLabel, s);
// here e1 ~<= e2, so emit a falsebool and jump to end
emit_load_bool(ACC, falsebool, s);
emit_branch(endLabel, s);
// otherwise e1 <= e2, so emit a truebool and fall through
emit_label_def(lessThanEqLabel, s);
emit_load_bool(ACC, truebool, s);
emit_label_def(endLabel, s);
}
void comp_class::code(ostream &s, CgenNodeP nd) {
// evaluate expr, store result on stack
e1->code(s, nd);
emit_push(ACC, s);
int falseLabel = CgenNode::labelIndex++;
int endLabel = CgenNode::labelIndex++;
// branch on e1's boolean (int) value
emit_pop(T1, s); // contains e1's Bool object
emit_fetch_int(T1, T1, s);
emit_beqz(T1, falseLabel, s);
// here e1 was true, so emit a falsebool and jump to end
emit_load_bool(ACC, falsebool, s);
emit_branch(endLabel, s);
// otherwise e1 was false, so emit a truebool and fall through
emit_label_def(falseLabel, s);
emit_load_bool(ACC, truebool, s);
emit_label_def(endLabel, s);
}
void int_const_class::code(ostream& s, CgenNodeP nd)
{
//
// Need to be sure we have an IntEntry *, not an arbitrary Symbol
//
emit_load_int(ACC,inttable.lookup_string(token->get_string()),s);
}
void string_const_class::code(ostream& s, CgenNodeP nd)
{
emit_load_string(ACC,stringtable.lookup_string(token->get_string()),s);
}
void bool_const_class::code(ostream& s, CgenNodeP nd)
{
emit_load_bool(ACC, BoolConst(val), s);
}
void new__class::code(ostream &s, CgenNodeP nd) {
// get class tag
if (type_name == SELF_TYPE) {
emit_load(T1, TAG_OFFSET, SELF, s);
} else {
CgenNodeP node = classNameMap.find(type_name)->second;
emit_load_imm(T1, node->classTag, s);
}
// load object table address
emit_load_address(T2, CLASSOBJTAB, s);
// create new class prototype object
emit_load_imm(T3, 8, s); // each class uses 2 words (8 bytes) in objTab
emit_mul(T1, T1, T3, s); // now holds offset into objTab
emit_addu(ACC, T2, T1, s); // now ACC holds address to class_protObj
emit_jal("Object.copy", s);
// call class' init function (one word after protObj)
emit_load(T1, 1, ACC, s);
emit_jal(T1, s);
}
void isvoid_class::code(ostream &s, CgenNodeP nd) {
// evaluate expr, store result on stack
e1->code(s, nd);
emit_push(ACC, s);
int voidLabel = CgenNode::labelIndex++;
int endLabel = CgenNode::labelIndex++;
// branch on e1's void-ness
emit_pop(T1, s); // contains e1's object
emit_beqz(T1, voidLabel, s); // if object is 0, void
// here e1 was not void, so emit a falsebool and jump to end
emit_load_bool(ACC, falsebool, s);
emit_branch(endLabel, s);
// otherwise e1 was void, so emit a truebool and fall through
emit_label_def(voidLabel, s);
emit_load_bool(ACC, truebool, s);
emit_label_def(endLabel, s);
}
void no_expr_class::code(ostream &s, CgenNodeP nd) {
// nothing emitted here
}
void object_class::code(ostream &s, CgenNodeP nd) {
if (name == self) {
emit_move(ACC, SELF, s);
} else {
// check for object name in local variables
for (int i = locals.size() - 1; i >= 0; i--) {
if (locals[i] == name) {
int offset = i;
emit_store(ACC, offset+3, FP, s);
return;
}
}
// check for object name in formals
for (int i = params.size() - 1; i >= 0; i--) {
// ???
}
// otherwise, attribute
int offset = nd->attrIndexMap.find(name)->second;
emit_store(ACC, offset, SELF, s);
}
}
<file_sep>/pa3/semant.cc
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include "semant.h"
#include "utilities.h"
extern int semant_debug;
extern char *curr_filename;
//////////////////////////////////////////////////////////////////////
//
// Symbols
//
// For convenience, a large number of symbols are predefined here.
// These symbols include the primitive type and method names, as well
// as fixed names used by the runtime system.
//
//////////////////////////////////////////////////////////////////////
static Symbol
arg,
arg2,
Bool,
concat,
cool_abort,
copy,
Int,
in_int,
in_string,
IO,
length,
Main,
main_meth,
No_class,
No_type,
Object,
out_int,
out_string,
prim_slot,
self,
SELF_TYPE,
Str,
str_field,
substr,
type_name,
val;
//
// Initializing the predefined symbols.
//
static void initialize_constants(void)
{
arg = idtable.add_string("arg");
arg2 = idtable.add_string("arg2");
Bool = idtable.add_string("Bool");
concat = idtable.add_string("concat");
cool_abort = idtable.add_string("abort");
copy = idtable.add_string("copy");
Int = idtable.add_string("Int");
in_int = idtable.add_string("in_int");
in_string = idtable.add_string("in_string");
IO = idtable.add_string("IO");
length = idtable.add_string("length");
Main = idtable.add_string("Main");
main_meth = idtable.add_string("main");
// _no_class is a symbol that can't be the name of any
// user-defined class.
No_class = idtable.add_string("_no_class");
No_type = idtable.add_string("_no_type");
Object = idtable.add_string("Object");
out_int = idtable.add_string("out_int");
out_string = idtable.add_string("out_string");
prim_slot = idtable.add_string("_prim_slot");
self = idtable.add_string("self");
SELF_TYPE = idtable.add_string("SELF_TYPE");
Str = idtable.add_string("String");
str_field = idtable.add_string("_str_field");
substr = idtable.add_string("substr");
type_name = idtable.add_string("type_name");
val = idtable.add_string("_val");
}
ClassTable::ClassTable(Classes classes) : semant_errors(0) , error_stream(cerr)
{
inheritanceMap = new std::map<Symbol, Symbol>();
classEnv = new std::map<Symbol, class__class>();
methodEnv = new std::map<Symbol, std::map<Symbol, method_class> >();
attrEnv = new std::map<Symbol, std::map<Symbol, attr_class> >();
// 1. Look at all classes and build the inheritance graph and class table
for (int i = classes->first(); classes->more(i); i = classes->next(i))
{
class__class *c = (class__class *)classes->nth(i);
Symbol cName = c->getName();
Symbol cParent = c->getParent();
// check for base class re-definition
if (cName == Object || cName == Int || cName == Bool || cName == Str || cName == IO)
semant_error(c) << "Redefinition of basic class " << cName->get_string() << endl;
// check for duplicate class definition)
else if (inheritanceMap->count(cName) != 0)
semant_error(c) << "Class " << cName->get_string() << " was previously defined" << endl;
else {
inheritanceMap->insert(std::pair<Symbol, Symbol>(cName, cParent));
classEnv->insert(std::pair<Symbol, class__class>(cName, *c));
}
}
// check for Main class
if (inheritanceMap->count(Main) == 0) {
semant_error() << "Class Main is not defined" << endl;
}
// add base classes to graph and class table
install_basic_classes();
}
void ClassTable::install_basic_classes() {
// The tree package uses these globals to annotate the classes built below.
// curr_lineno = 0;
Symbol filename = stringtable.add_string("<basic class>");
// The following demonstrates how to create dummy parse trees to
// refer to basic Cool classes. There's no need for method
// bodies -- these are already built into the runtime system.
// IMPORTANT: The results of the following expressions are
// stored in local variables. You will want to do something
// with those variables at the end of this method to make this
// code meaningful.
//
// The Object class has no parent class. Its methods are
// abort() : Object aborts the program
// type_name() : Str returns a string representation of class name
// copy() : SELF_TYPE returns a copy of the object
//
// There is no need for method bodies in the basic classes---these
// are already built in to the runtime system.
Class_ Object_class =
class_(Object,
No_class,
append_Features(
append_Features(
single_Features(method(cool_abort, nil_Formals(), Object, no_expr())),
single_Features(method(type_name, nil_Formals(), Str, no_expr()))),
single_Features(method(copy, nil_Formals(), SELF_TYPE, no_expr()))),
filename);
inheritanceMap->insert(std::pair<Symbol, Symbol>(Object, No_class));
classEnv->insert(std::pair<Symbol, class__class>(Object, *(class__class *)Object_class));
//
// The IO class inherits from Object. Its methods are
// out_string(Str) : SELF_TYPE writes a string to the output
// out_int(Int) : SELF_TYPE " an int " " "
// in_string() : Str reads a string from the input
// in_int() : Int " an int " " "
//
Class_ IO_class =
class_(IO,
Object,
append_Features(
append_Features(
append_Features(
single_Features(method(out_string, single_Formals(formal(arg, Str)),
SELF_TYPE, no_expr())),
single_Features(method(out_int, single_Formals(formal(arg, Int)),
SELF_TYPE, no_expr()))),
single_Features(method(in_string, nil_Formals(), Str, no_expr()))),
single_Features(method(in_int, nil_Formals(), Int, no_expr()))),
filename);
inheritanceMap->insert(std::pair<Symbol, Symbol>(IO, Object));
classEnv->insert(std::pair<Symbol, class__class>(IO, *(class__class *)IO_class));
//
// The Int class has no methods and only a single attribute, the
// "val" for the integer.
//
Class_ Int_class =
class_(Int,
Object,
single_Features(attr(val, prim_slot, no_expr())),
filename);
inheritanceMap->insert(std::pair<Symbol, Symbol>(Int, Object));
classEnv->insert(std::pair<Symbol, class__class>(Int, *(class__class *)Int_class));
//
// Bool also has only the "val" slot.
//
Class_ Bool_class =
class_(Bool, Object, single_Features(attr(val, prim_slot, no_expr())),filename);
inheritanceMap->insert(std::pair<Symbol, Symbol>(Bool, Object));
classEnv->insert(std::pair<Symbol, class__class>(Bool, *(class__class *)Bool_class));
//
// The class Str has a number of slots and operations:
// val the length of the string
// str_field the string itself
// length() : Int returns length of the string
// concat(arg: Str) : Str performs string concatenation
// substr(arg: Int, arg2: Int): Str substring selection
//
Class_ Str_class =
class_(Str,
Object,
append_Features(
append_Features(
append_Features(
append_Features(
single_Features(attr(val, Int, no_expr())),
single_Features(attr(str_field, prim_slot, no_expr()))),
single_Features(method(length, nil_Formals(), Int, no_expr()))),
single_Features(method(concat,
single_Formals(formal(arg, Str)),
Str,
no_expr()))),
single_Features(method(substr,
append_Formals(single_Formals(formal(arg, Int)),
single_Formals(formal(arg2, Int))),
Str,
no_expr()))),
filename);
inheritanceMap->insert(std::pair<Symbol, Symbol>(Str, Object));
classEnv->insert(std::pair<Symbol, class__class>(Str, *(class__class *)Str_class));
}
bool program_class::inheritanceCheck(ClassTable *classTable)
{
bool wellFormed = true;
// check inheritance of each class separately
std::map<Symbol, Symbol>::iterator it;
for (it = classTable->inheritanceMap->begin(); it != classTable->inheritanceMap->end(); ++it)
{
Symbol child = (Symbol)it->first;
Symbol parent = (Symbol)it->second;
// walk up inheritance path to check for cycles or errors
std::set<Symbol> seen;
seen.insert(child);
while (true)
{
// if is Object, or inherits from Object, done and on to the next one
if (child == Object || parent == Object)
break;
// check for inheritance from base class other than Object or IO
if (parent == Int || parent == Str || parent == Bool) {
classTable->semant_error(&classTable->classEnv->find(child)->second) << "Class " << child->get_string() << " cannot inherit class " << parent->get_string() << endl;
wellFormed = false;
break;
}
// check for existance of inherited class
if (classTable->inheritanceMap->count(parent) == 0) {
classTable->semant_error(&classTable->classEnv->find(child)->second) << "Class " << child->get_string() << " inherits from an undefined class " << parent->get_string() << endl;
wellFormed = false;
break;
}
// repeated class in path = cycle
if (seen.count(parent) != 0) {
classTable->semant_error(&classTable->classEnv->find(child)->second) << "Class " << parent->get_string() << ", or an ancestor of " << parent->get_string() << ", is involved in an inheritance cycle" << endl;
wellFormed = false;
break;
}
child = parent;
seen.insert(child);
parent = classTable->inheritanceMap->find(parent)->second;
}
}
return wellFormed;
}
/////////////////////////////////////
// Declaration-gathering functions //
/////////////////////////////////////
void program_class::gatherDeclarations(ClassTable *classTable)
{
// first pass to populate method/attr maps
for (int i = classes->first(); classes->more(i); i = classes->next(i)) {
class__class *c = (class__class *)classes->nth(i);
c->gatherDeclarations(classTable);
}
// second pass to check for inherited method/attr errors
for (int i = classes->first(); classes->more(i); i = classes->next(i)) {
class__class *c = (class__class *)classes->nth(i);
c->checkDeclarations(classTable);
}
}
void class__class::gatherDeclarations(ClassTable *classTable)
{
for (int i = features->first(); features->more(i); i = features->next(i)) {
Feature_class *f = features->nth(i);
f->gatherDeclarations(classTable, this);
}
}
void class__class::checkDeclarations(ClassTable *classTable)
{
for (int i = features->first(); features->more(i); i = features->next(i)) {
Feature_class *f = features->nth(i);
f->checkDeclarations(classTable, this);
}
}
void method_class::gatherDeclarations(ClassTable *classTable, class__class *c)
{
std::map<Symbol, method_class> methods;
// retrieve current methods for current class if available
if (classTable->methodEnv->count(c->getName()))
methods = classTable->methodEnv->find(c->getName())->second;
// report error if method is redefined
if (methods.count(name))
classTable->semant_error(c) << "Method " << name->get_string() << " is multiply defined" << endl;
// otherwise, insert the new method
else
methods.insert(std::pair<Symbol, method_class>(name, *this));
// update method environment
classTable->methodEnv->insert(std::pair<Symbol, std::map<Symbol, method_class> >(c->getName(), methods));
}
void method_class::checkDeclarations(ClassTable *classTable, class__class *c)
{
// walk up the inheritance path of the class c, checking for redefinition
// of an inherited method
// if inherited method redefined, check for same formals and return type
// otherwise, error
}
void attr_class::gatherDeclarations(ClassTable *classTable, class__class *c)
{
std::map<Symbol, attr_class> attributes;
// retrieve current attributes for current class if available
if (classTable->attrEnv->count(c->getName()))
attributes = classTable->attrEnv->find(c->getName())->second;
// report error if attribute is redefined
if (attributes.count(name) != 0)
classTable->semant_error(c) << "Attribute " << name->get_string() << " is multiply defined" << endl;
// otherwise insert the new attribute
else
attributes.insert(std::pair<Symbol, attr_class>(name, *this));
// update attribute environment
classTable->attrEnv->insert(std::pair<Symbol, std::map<Symbol, attr_class> >(c->getName(), attributes));
}
void attr_class::checkDeclarations(ClassTable *classTable, class__class *c)
{
// walk up the inheritance path of the class c, checking for redefinition
// of an inherited attribute
// if inherited attribute, error
}
/////////////////////////////
// Type-checking functions //
/////////////////////////////
void program_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
for (int i = classes->first(); classes->more(i); i = classes->next(i)) {
class__class *c = (class__class *)classes->nth(i);
c->typecheck(classT, methods, objects);
}
}
void class__class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
for (int i = features->first(); features->more(i); i = features->next(i)) {
Feature_class *f = (Feature_class *)features->nth(i);
f->typecheck(classT, methods, objects);
}
}
void method_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
for (int i = formals->first(); formals->more(i); i = formals->next(i)) {
formal_class *f = (formal_class *)formals->nth(i);
f->typecheck(classT, methods, objects);
}
expr->typecheck(classT, methods, objects);
}
void attr_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
init->typecheck(classT, methods, objects);
}
void formal_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
// check declared types are all actual types
}
Symbol branch_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
return expr->typecheck(classT, methods, objects);
}
Symbol assign_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
Symbol s = expr->typecheck(classT, methods, objects);
set_type(s);
return s;
}
Symbol static_dispatch_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
expr->typecheck(classT, methods, objects);
for (int i = actual->first(); actual->more(i); i = actual->next(i))
{
Expression_class *e = actual->nth(i);
e->typecheck(classT, methods, objects);
}
// return should be return type of method looked up
// in methods table - which I haven't yet populated :(
set_type(Object);
return Object;
}
Symbol dispatch_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
expr->typecheck(classT, methods, objects);
for (int i = actual->first(); actual->more(i); i = actual->next(i))
{
Expression_class *e = actual->nth(i);
e->typecheck(classT, methods, objects);
}
// return should be return type of method looked up
// in methods table - which I haven't yet populated :(
set_type(Object);
return Object;
}
Symbol cond_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
pred->typecheck(classT, methods, objects);
then_exp->typecheck(classT, methods, objects);
else_exp->typecheck(classT, methods, objects);
// return LUB of the type of then_exp and else_exp
set_type(Object);
return Object;
}
Symbol loop_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
pred->typecheck(classT, methods, objects);
body->typecheck(classT, methods, objects);
set_type(Object);
return Object;
}
Symbol typcase_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
return expr->typecheck(classT, methods, objects);
}
Symbol block_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
Symbol s;
for (int i = body->first(); body->more(i); i = body->next(i)) {
Expression_class *e = body->nth(i);
s = e->typecheck(classT, methods, objects);
}
// return last expression's type
set_type(s);
return s;
}
Symbol let_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
init->typecheck(classT, methods, objects);
Symbol s = body->typecheck(classT, methods, objects);
set_type(s);
return s;
}
Symbol plus_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
e1->typecheck(classT, methods, objects);
e2->typecheck(classT, methods, objects);
// check that e1 and e2 are type Int, error if not
set_type(Int);
return Int;
}
Symbol sub_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
e1->typecheck(classT, methods, objects);
e2->typecheck(classT, methods, objects);
// check that e1 and e2 are type Int, error if not
set_type(Int);
return Int;
}
Symbol mul_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
e1->typecheck(classT, methods, objects);
e2->typecheck(classT, methods, objects);
// check that e1 and e2 are type Int, error if not
set_type(Int);
return Int;
}
Symbol divide_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
e1->typecheck(classT, methods, objects);
e2->typecheck(classT, methods, objects);
// check that e1 and e2 are type Int, error if not
set_type(Int);
return Int;
}
Symbol neg_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
e1->typecheck(classT, methods, objects);
// check that e1 is type Int, error if not
set_type(Int);
return Int;
}
Symbol lt_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
e1->typecheck(classT, methods, objects);
e2->typecheck(classT, methods, objects);
// check that e1 and e2 are type Int, error if not
set_type(Bool);
return Bool;
}
Symbol eq_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
e1->typecheck(classT, methods, objects);
e2->typecheck(classT, methods, objects);
// check that e1 and e2 are same type, error if not
set_type(Bool);
return Bool;
}
Symbol leq_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
e1->typecheck(classT, methods, objects);
e2->typecheck(classT, methods, objects);
// check that e1 and e2 are type Int, error if not
set_type(Bool);
return Bool;
}
Symbol comp_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
e1->typecheck(classT, methods, objects);
// check that e1 is type Bool, error if not
set_type(Bool);
return Bool;
}
Symbol int_const_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
set_type(Int);
return Int;
}
Symbol bool_const_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
set_type(Bool);
return Bool;
}
Symbol string_const_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
set_type(Str);
return Str;
}
Symbol new__class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
// check that the class exists
// if not, error
// otherwise, the type
set_type(getTypeName());
return getTypeName();
}
Symbol isvoid_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
e1->typecheck(classT, methods, objects);
set_type(Bool);
return Bool;
}
Symbol no_expr_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
set_type(No_type);
return No_type;
}
Symbol object_class::typecheck(ClassTable *classT,
SymbolTable<Symbol, method_class> *methods,
SymbolTable<Symbol, Symbol> *objects)
{
// check for object in objects table - not populated :(
// if not found, error
// otherwise, return the found type
set_type(getName());
return getName();
}
////////////////////////////////////////////////////////////////////
//
// semant_error is an overloaded function for reporting errors
// during semantic analysis. There are three versions:
//
// ostream& ClassTable::semant_error()
//
// ostream& ClassTable::semant_error(Class_ c)
// print line number and filename for `c'
//
// ostream& ClassTable::semant_error(Symbol filename, tree_node *t)
// print a line number and filename
//
///////////////////////////////////////////////////////////////////
ostream& ClassTable::semant_error(Class_ c)
{
return semant_error(c->get_filename(),c);
}
ostream& ClassTable::semant_error(Symbol filename, tree_node *t)
{
error_stream << filename << ":" << t->get_line_number() << ": ";
return semant_error();
}
ostream& ClassTable::semant_error()
{
semant_errors++;
return error_stream;
}
/* This is the entry point to the semantic checker.
Your checker should do the following two things:
1) Check that the program is semantically correct
2) Decorate the abstract syntax tree with type information
by setting the `type' field in each Expression node.
(see `tree.h')
You are free to first do 1), make sure you catch all semantic
errors. Part 2) can be done in a second stage, when you want
to build mycoolc.
*/
void program_class::semant()
{
initialize_constants();
/* ClassTable constructor may do some semantic analysis */
ClassTable *classtable = new ClassTable(classes);
if (inheritanceCheck(classtable))
{
gatherDeclarations(classtable);
SymbolTable<Symbol, method_class> *methods = new SymbolTable<Symbol, method_class>();
SymbolTable<Symbol, Symbol> *objects = new SymbolTable<Symbol, Symbol>();
typecheck(classtable, methods, objects);
}
if (classtable->errors()) {
cerr << "Compilation halted due to static semantic errors." << endl;
exit(1);
}
}
|
f9e2ee5ba07f3ddec62ef7d337d5f42e1e8adb42
|
[
"Markdown",
"C++"
] | 4 |
Markdown
|
crcsaenz/coolc
|
f906e7694537c6faaa1f3279586f8f9c3588bdee
|
9b0a8f64c9000519f434c1e9c396554a5533beeb
|
refs/heads/master
|
<file_sep>import unittest
import StringCalculator
class testStringCalculator(unittest.TestCase):
def testEmpty(self):
self.assertEqual(StringCalculator.Add(''), 0, 'Should return 0')
def testAdd(self):
self.assertEqual(StringCalculator.Add('1,4,6'), 11, 'Should return 11')
def testNewLine(self):
self.assertEqual(StringCalculator.Add('1\n,4,10'), 15, 'Should return 15')
self.assertEqual(StringCalculator.Add('1,\n4,10'), 15, 'Should return 15')
def testDelimiter(self):
self.assertEqual(StringCalculator.Add('//;\n7;8;9'), 24, 'Should return 24')
self.assertNotEqual(StringCalculator.Add('//&\n4&5&6'), 0, 'Should not return 0')
def testNegatives(self):
with self.assertRaises(Exception):
StringCalculator.Add('4,-6,8')
with self.assertRaises(Exception):
StringCalculator.Add('//*\n1*2*-3')
def testAbove1000(self):
self.assertEqual(StringCalculator.Add('3,5000,6'), 9, "Should return 12")
self.assertNotEqual(StringCalculator.Add('4,1001'), 1005, "Should not return 1005")
def testDelimiterLength(self):
self.assertEqual(StringCalculator.Add('//xxx\n7xxx8xxx9'), 24, 'Should return 24')
self.assertNotEqual(StringCalculator.Add('//abc\n4abc5abc6'), 0, 'Should not return 0')
def testMultipleDelimiters(self):
self.assertEqual(StringCalculator.Add('//@,;,v\n7@8;9v4'), 28, 'Should return 28')
self.assertNotEqual(StringCalculator.Add('//?,@,#\n4?5@6#7'), 0, 'Should not return 0')
def testMultipleDelimiterLengths(self):
self.assertEqual(StringCalculator.Add('//xxx,abc\n5xxx6abc7'), 18, 'Should return 18')
self.assertNotEqual(StringCalculator.Add('//***,axy\n5***6axy7'), 0, 'Should not return 0')
if __name__ == '__main__':
unittest.main()
<file_sep>import re
def Add(numberString):
if not numberString:
return 0
if numberString.startswith('//'):
splitString = numberString.split('\n')
delimiter = createDelimiter(splitString[0][2:])
numberList = re.split(delimiter, splitString[1])
else:
numberList = numberString.split(',')
numberList = list(map(int, numberList))
if any(x < 0 for x in numberList):
raise Exception('Negatives not allowed')
numberList = removeNumbersOverLimit(numberList)
return sum(numberList)
def removeNumbersOverLimit(numberList):
for number in numberList:
if number > 1000:
numberList.remove(number)
return numberList
def createDelimiter(delimiter):
# re.split works well for splitting with multiple given characters, but has issues with special characters.
# Added this code to manage them
specialChars = ['.', '^', '$', '*', '+', '?', '{', '}', '[', ']', '|', '(', ')']
for char in specialChars:
if char in delimiter:
delimiter = delimiter.replace(char, '\\' + char)
# ensures the comma is used to separate delimiters, and is not the delimiter itself.
if len(delimiter) > 1:
delimiter = delimiter.replace(',', '|')
return delimiter
|
ebabc1736e34128d167aa53304d1f66b402a4254
|
[
"Python"
] | 2 |
Python
|
TimKeding/StringCalculator
|
19126def42a98e909630d4bba8c33e06b81d3ace
|
4c6f9d8e274351fe98361c45087c9f34fc9d6b0b
|
refs/heads/master
|
<file_sep><?php
$array = [1, 1, 2, 3, 4, -51, 12, 12, 12, -51];
function getPair($array)
{
$pairCount = 0;
for ($i = 1; $i <= count($array) - 1; $i++) {
if ($array[$i] == $array[$i - 1]) {
$pairCount++;
}
}
echo $pairCount;
}
getPair($array);
|
7138ea0fff111dd02d8a580dd699f52129783ca2
|
[
"PHP"
] | 1 |
PHP
|
teaguru/test2
|
cfca60ccf2ae7a043ed3cc53936408dfa265fa04
|
27986a08ec1fe156c9424c7b4acb872515b5d0c6
|
refs/heads/master
|
<repo_name>eileenguoo/GoFor100<file_sep>/README.md
# GoFor100
12B_PA8
<file_sep>/src/Violation.java
/**
* @author <NAME>
* @email <EMAIL>
* this class checks the violation types and print the violation
*/
public class Violation {
private int lineNumber;
private String name;
private String type;
private boolean include;
/**
* constructor
* @param lineNumber violaton line num
* @param name name of TA
* @param type vioaltion type
*/
public Violation(int lineNumber, String name, String type) {
this.lineNumber = lineNumber;
this.name = name;
this.type = type;
include = true;
}
/**
* get tyoe
* @return type type of violation
*/
public String getType() {
return type;
}
/**
* set the include boolean
* @param include boolean
*/
public void setInclude(boolean include) {
this.include = include;
}
/**
* print violation contents
*/
public void print() {
if (include) {
System.out.println(lineNumber + ";" + name + ";" + type);
}
}
}
|
238ec4906263539ca9d3aa25b14087f5b6cabe2a
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
eileenguoo/GoFor100
|
7086dd1f741c51bba47229d63ace792d1ef09eb2
|
4ee8fb56fe98c91e07b2614d69a7ca7fe3b912d0
|
refs/heads/master
|
<file_sep>#include "problem.hpp"
#include "heuristik.hpp"
//#include <iostream>
//#include <string>
//#include <iomanip>
//#include <math.h>
#include <fstream>
#ifndef __GNUC__
#include <conio.h>
#else
#define _getch()
#endif
using namespace std;
int main ()
{
Problem problem;
problem.einlesen();
problem.calc_distances();
Heuristik heuristik;
heuristik.set_problem(problem);
heuristik.orig_matrix();
heuristik.sort_matrix();
heuristik.find_nachbar();
return 0;
}
<file_sep>
FLAGS := -O2 -DNDEBUG -ftree-vectorize -Wall
OBJECTS := projekt3.o problem.o heuristik.o
a.out: $(OBJECTS)
g++ $(FLAGS) $(OBJECTS) -o a.out
projekt3.o: projekt3.cpp
g++ $(FLAGS) -c projekt3.cpp
problem.o: problem.cpp
g++ $(FLAGS) -c problem.cpp
heuristik.o: heuristik.cpp
g++ $(FLAGS) -c heuristik.cpp
clean:
rm -rf *o a.out
<file_sep>### TSP Problem mit nearest neighbor heuristic algorithm
**Input:**
* in6.txt (6 Knoten)
* dj38.txt (38 Knoten)
**Output**
* output.txt
<file_sep>## Heuristik
* gegeben: Distanz der Entfernungen in einer Matrix i/j
**Schleife für jeden Standort i:**
* Sortiere die Entfernungen für i zum Standort j aufsteigend
* wähle den Standort für das nächste Ziel, welcher die geringste Entferung zu i besitzt, und noch nicht angefahren wurde
* addiere nun die Distanz des angefahrenen Standortes auf den Gesamtweg
* speichere den gewählten Weg in Array für die Reihenfolge (int path[MAX_KNOTEN])
* setze den Status des angefahrenen Standortes auf angefahren (bool visited[MAX_KNOTEN])
* Zähle die Anzahl der angefahrenen Codes um 1 nach oben
**Abbruch:**
* Anzahl der angefahrenen Städte = Anzahl der geg. Städte aus der Importdatei
* Anschließend Rückfahrt zum Ausgangsstandort (entspreched Addieren des zugehörigen Weges)
**Ausgabe:**
* Ausgabe der Reihenfolge der Knoten (aufsteigend) -> Route
* Ausgabe der Gesamtdistanz
verwenden von:
* Distanzmatrix mit Sturktur die die jeweiligen Entfernungen und Indexes
* einen Array für besuchten Standorte
* einen Array für die Reihenfolge der angefahrenden Städte
* counter für die Anzahl der bereits angefahrenen Städte
* double für die Addition der angefahrenen Wege
<file_sep>#include "problem.hpp"
#include <string.h>
#include <fstream>
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
void Problem::einlesen()
{
// Eingabe, ggf. Abbruch mit return
cout << "\nWelche Datei soll eingelesen werden? \n";
cout << "\nbitte geb den Dateinamen an 1 (dj38.txt) oder 2 (in6.txt) \n";
cin >> d;
if (d <1|| d >2) // Check Eingabe, wenn ungueltig: Fehler ausgeben
{
cout << "\nParameter ungueltig\n!";
//_getch();
exit(1);}
char files[2][9]={"dj38.txt", "in6.txt"}; // Array bilden für die Dateinamen
cout << "\noeffne Datei " << files[d-1] << "\n"; // Datei 1-3, Index 0-2
ifstream datei_input; // Inputstream definieren
datei_input.open(files[d-1]);
if (datei_input.bad()) // Wenn Inputstream fehlerhaft, Fehlermeldung ausgeben
{
cout << "\nDatei konnten nicht gelesen werden \n!";
}
string dummy; // ersten 11 Zeilen der Inputdatei überspringen
for(int i=0; i < 11;++i)
{
getline(datei_input, dummy);
}
datei_input >> anzahl;
cout << "\n Knotenanzahl:" << anzahl << "\n";
// Knotenlisten initialisieren mit Knotendaten
for(int i=0; i<anzahl; i++)
{
datei_input >> knotenliste[i].index;
datei_input >> knotenliste[i].x_coord;
datei_input >> knotenliste[i].y_coord;
}
// Ausgabe zum Debuggen
for(int i=0; i<anzahl; i++)
{
cout <<"\n" <<knotenliste[i].index << "\t" << knotenliste[i].x_coord << "\t" << knotenliste[i].y_coord;
} cout <<"\n";
}
void Problem::calc_distances()
{
// Berechnen der Matrix
//Phytagoras
for(int i = 0; i < anzahl;i++)
{
for(int j = 0; j < anzahl;j++)
// Knoten ID initialisieren in der Struktur distance_matrix.index
{
if(i==j) // Diagonale befüllen
{
distance_matrix[i][j].weg = 0; // Distanz befüllen
distance_matrix[i][j].index = knotenliste[j].index; // Index befüllen
}
else
{
double distance_x = (knotenliste[i].x_coord-knotenliste[j].x_coord);
double distance_y = (knotenliste[i].y_coord-knotenliste[j].y_coord);
distance_matrix[i][j].weg = sqrt((distance_x*distance_x)+(distance_y*distance_y));
distance_matrix[i][j].index = knotenliste[j].index;
}
}
}
// Ausgabe der Berechneten Entfernungen & zugehörigen Indexes
cout << "\n Entfernungsmatrix:" << "\n ";
for(int i = 0; i < anzahl; i++)
{
for(int j = 0; j < anzahl; j++)
{
cout << distance_matrix[i][j].weg << "|" << distance_matrix[i][j].index << " ";
}
cout << "\n";
}
}
int Problem::getanzahl()
{
return anzahl;
}
<file_sep>#include "problem.hpp"
#include "heuristik.hpp"
#include <string.h>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
//using namespace std;
// Konstruktor für Heuristikklasse
Heuristik::Heuristik()
{
for (int i=0; i<problem.getanzahl(); i++){
statusliste[i].index = i+1; // Status.k inistalisieren mit Nr des Knotens
statusliste[i].angefahren = 0;
statusliste[i].full_distance = 0;
}
}
void Heuristik::set_problem(Problem problem){
this->problem = problem;
}
void Heuristik::orig_matrix()
{
for (int i = 0; i < problem.getanzahl(); i++)
for (int j = 0; j<problem.getanzahl(); j++)
oldmatrix[i][j] = problem.distance_matrix[i][j].weg;
}
void Heuristik::sort_matrix()
{
cout << "\n sortiere Entfernungsmatrix:" << "\n ";
for (int i = 0; i < problem.getanzahl(); i++)
{
sort(problem.distance_matrix[i], problem.distance_matrix[i]+problem.getanzahl(), [](Distance1 const &a, Distance1 const &b) { return a.weg < b.weg; });
for (int j = 0; j<problem.getanzahl(); j++)
{
cout << "\t" << problem.distance_matrix[i][j].weg << "|" << problem.distance_matrix[i][j].index << " ";
}
cout << "\n";
// find nächsten nachbarn der noch nicht besichtigt wurde
}
}
void Heuristik::find_nachbar()
{
int city_count = problem.getanzahl();
double weg_laenge = 0;
bool visited[MAX_KNOTEN]; // Array mit Status (angefahrenen oder nicht)
fill_n(visited, city_count, false);
int path[MAX_KNOTEN]; // Array mit Reihenfolge der angefahrenen Städte
// Starten bei Stadt 1
int city = 1;
// suche nach dem nächsten Nachbarn (der noch nicht besucht wurde)
bool finished = false;
int weg_index = 0;
path[weg_index]=city;
while (!finished)
{
finished = true;
for (int i = 1; i < city_count; i++) // überspringe sortierte erste Spalte, da dies die Hauptdiagonalen Elemente schreibende
{
if (!visited[problem.distance_matrix[city-1][i].index])
{
finished = false;
weg_laenge += problem.distance_matrix[city-1][i].weg;
visited[city] = true;
city = problem.distance_matrix[city-1][i].index;
weg_index++; // gewählter Knotenanzahl hochzählen
path[weg_index] = city;
break;
}
}
}
// Rückfahrt zu 1
weg_laenge += oldmatrix[city-1][0];
weg_index++; // gewählter Knotenanzahl hochzählen
// Ergebnis ausgeben
// als Datei & im Terminal
ofstream datei_output("output.txt"); // Outputstream definieren
if (datei_output.bad()) // Wenn Outputstream fehlerhaft, Fehlermeldung ausgeben
{
cout << "\nDatei konnten nicht geschrieben werden \n!";
}
cout << "\n Weglänge: " << weg_laenge << "\n" << endl;
datei_output << "\n Weglänge: " << weg_laenge << "\n" << endl;
cout << "\n Weg:\n ";
datei_output << "\n Weg: \n ";
int h=0;
for (int i = 0; i < city_count; i++)
{
cout << path[i];
datei_output << path[i];
h = h+1;
if(h==9)
{
cout << "\n";
datei_output << "\n";
h=0;
}
if (i != city_count -1)
{
cout << " -> ";
datei_output << " -> ";
} else
{
cout << " -> 1" << endl;
datei_output << " -> 1 \n" << endl;
}
}
}
<file_sep>// Headerdatei problem.h
#ifndef _INC_problem_
#define _INC_problem_
#define strcpy_s strcpy
#define MAX_KNOTEN 100
typedef struct
{
int index;
double x_coord;
double y_coord;
} Knoten;
typedef struct
{
int index;
double weg;
} Distance1;
class Problem
{
public:
void einlesen();
void calc_distances();
double ** getdistance_matrix();
int getanzahl();
Distance1 distance_matrix[MAX_KNOTEN][MAX_KNOTEN]; // Matrix definieren
private:
int d; // welche Datei soll eingelesen werden
int anzahl;
Knoten knotenliste[MAX_KNOTEN]; // Pointer auf knotenliste
};
#endif // #define _INC_problem_
<file_sep>#Augabenstellung
**Projekt 3: Heuristiken für das Travelling Salesman Problem**
Im Projekt 3 sind verschiedene heuristische Verfahren zur Berechnung des (symmetrischen) Travelling Salesman Problems (TSP) objektorientiert zu programmieren und zu testen. Anschließend werden fünf Themen (mit Literaturhinweisen) gestellt. Es folgen Hinweise zur Realisierung sowie organisatorische Hinweise.
##Thema 1: Nächster-Nachbar-Heuristik
Gegeben sei ein vollständiger, bewerteter, ungerichteter Graph G = [V, E, c]. Zu bestimmen ist eine Rundreise mit kürzester Länge. Dabei ist unter einer Rundreise ein geschlossener Kantenzug zu verstehen, der durch jeden Knoten des Graphen genau einmal führt. Die Länge der Rundreise ergibt sich als die Summe der Bewertungen (c) aller enthaltenen Kanten. Die Knoten werden bei dem TSP als Städte (Orte) interpretiert, die Kanten als Verbindungen und ihre Gewichte als Distanzen, Zeiten o.ä. In Thema 1 ist eine Näherungslösung für das TSP mittels der Nächster-Nachbar-Heuristik (auch Nearest-Neighbour) zu berechnen.
**Eingabe:** Anzahl der Knoten n (Knotenmenge sei die Menge {1,...,n}); pro Knoten i sind ebene Koordinaten xi und yi gegeben (i = 1,...,n). Aus den Koordinaten der Knoten sind dann die Kantengewichte als euklidische Entfernungen cij ≥ 0 (i,j = 1,...,n) zu bestimmen. Beachte cii = H.V. (i = 1,...,n) und cij = cji (1 ≤ i < j ≤ n), d.h. die Entfernungen sind symmetrisch.
**Ausgabe:** Länge der ermittelten Rundreise, Folge der Orte beginnend und endend bei einem beliebig festgelegten Startort (der zugleich Zielort ist).
Literaturhinweis: Grötschel, M.: <NAME>: Das Travelling Salesman-Problem, ZIB-Report 05-57 (November 2005).
**Hinweise zur Realisierung**
Bei der Bearbeitung Ihres Themas sollten Sie sich zuerst mit dem zu programmierenden Algorithmus anhand der Literatur vertraut machen. Daraufhin ist ein Pseudocode des jeweiligen Algorithmus anzufertigen. Das Programm ist auf der Basis von zwei Klassen zu erstellen. Die eine Klasse soll das zu lösende Problem (TSP-Instanz) speichern, die andere Klasse die im Aufbau befindliche Lösung. Führen Sie sinnvolle Datenstrukturen und Operationen für jede Klasse ein. Bei einem Lauf des Programms sind mindestens zwei Objekte, d.h. pro Klasse ein Objekt, zu nutzen. Globale Variablen sind nicht zu verwenden. Realisieren Sie die Eingabe und Ausgabe mittels Dateien (eine Eingabedatei, eine Ausgabedatei).
Das Programm ist anhand von zwei Instanzen zu testen:
* 1) Instanz I6 mit sechs Orten, File wird z. V. gestellt.
* 2) Instanz DJ38 mit 38 Orten in Djibouti, File wird z. V. gestellt.
**Abgabeumfang**
* Pseudocode der Heuristik und Sourcecode (*.h, *.cpp) der beiden Klassen sowie des Hauptmoduls.
* Je eine Eingabedatei und Ausgabedatei (mit Lösung) für beide Instanzen.<file_sep>// Headerdatei heuristik.h
// Dateien einfügen
#ifndef _INC_heuristik_
#define _INC_heuristik_
#define MAX_KNOTEN 100
typedef struct {
int index; //Nr des Knotens
bool angefahren; // 0 nicht angefahren, 1 angefahren
double full_distance;
} Status;
struct City {
double x;
double y;
};
struct Distance {
int index;
double distance;
};
class Heuristik
{
public:
Heuristik(); // Konstruktor für Heuristiklasse
void set_problem(Problem problem); // Übergebe Problem
void orig_matrix();
void sort_matrix();
void find_nachbar();
private:
Problem problem; // Zugriff auf bishere Instanz
Status statusliste[MAX_KNOTEN];
double oldmatrix[MAX_KNOTEN][MAX_KNOTEN];
};
#endif // #define _INC_heuristik_
|
0df325a1dd47e4bf428ca2fd8875a2ad7eef9524
|
[
"Markdown",
"Makefile",
"C++"
] | 9 |
C++
|
eriu/cpp
|
507449ced566f096d212ffd89f57154fe622238f
|
e992e3e20127279fce15123d4b7adb7fbd7b7e29
|
refs/heads/master
|
<repo_name>JRocks1092/Project72<file_sep>/Screens/ReadStoryScreen.js
import React, { Component } from 'react';
import { View, TouchableOpacity, Text, StyleSheet, ImageBackground, Image } from 'react-native';
export default class ReadStoryScreen extends Component {
render() {
return (
<View>
<Text style = { styles.heading }>ReadStoryScreen</Text>
</View >
)
}
}
const styles = StyleSheet.create({
touchableOpacity: {
alignSelf: 'center',
backgroundColor: "pink",
width: 100,
height: 50,
alignItems: 'center',
justifyContent: 'center',
marginTop: 50,
borderRadius: 50
},
heading: {
color: "pink",
alignSelf: "center",
fontSize: 40,
},
textInput: {
borderWidth: 3,
borderRadius: 20,
borderColor:"#99FF99",
width: 200,
marginTop: 50,
alignSelf: "center",
textAlign: "center",
},
bg: {
flex: 1,
resizeMode: 'cover'
},
text: {
color: "#000000",
fontSize: 20,
textAlign: 'center',
justifyContent: 'center'
}
})
|
5a1b47dab3fbc82b94a123e6e066df68f18a941b
|
[
"JavaScript"
] | 1 |
JavaScript
|
JRocks1092/Project72
|
2a5b4ca8dc8da912bc393e2762b17d168277d0d5
|
65f4e595a481d6d436957da2a7ea38cabef9d3f1
|
refs/heads/master
|
<file_sep>package com.example.user.vandrova;
public interface Constants {
String LAT_LNG = "latLng";
String PLACE_ID = "placeId";
String PLACE_NAME = "placeName";
String BASE_URL = "https://api.foursquare.com/v2/";
String CLIENT_ID = "YPKP3PJOYNVPZQHGXYDD3KSBKPWUICDBFPZZ2SEPAEFXCFVM";
String CLIENT_SECRET = "<KEY>";
}
<file_sep>package com.example.user.vandrova.model;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
@Entity(tableName = "REVIEWS")
public class Review {
@PrimaryKey(autoGenerate = true)
private Integer id;
private String placeId;
private String email;
private String name;
private String reviewText;
private Integer rating;
public Review(String placeId, String email, String name, String reviewText, Integer rating) {
this.placeId = placeId;
this.email = email;
this.name = name;
this.reviewText = reviewText;
this.rating = rating;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getReviewText() {
return reviewText;
}
public void setReviewText(String reviewText) {
this.reviewText = reviewText;
}
public Integer getRating() {
return rating;
}
public void setRating(Integer rating) {
this.rating = rating;
}
}
<file_sep>package com.example.user.vandrova;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationProvider;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
@RuntimePermissions
public class MainActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, LocationListener {
private static final int REQUEST_CHECK_SETTINGS = 0x1;
private GoogleMap mMap;
protected static final String TAG = "MainActivity";
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private GoogleApiClient mGoogleApiClient;
FusedLocationProviderClient mCurrentLocation;
private boolean PermissionOK = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mCurrentLocation = LocationServices.getFusedLocationProviderClient(this);
buildGoogleApiClient();
createLocationRequest();
buildLocationSettingsRequest();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// NOTE: delegate the permission handling to generated method
MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
@NeedsPermission(Manifest.permission.ACCESS_FINE_LOCATION)
void getPosition() {
Log.e(TAG, "Есть разрешение");
startLocationUpdates();
}
@OnShowRationale(Manifest.permission.ACCESS_FINE_LOCATION)
void showRationaleForLocation(final PermissionRequest request) {
new AlertDialog.Builder(this)
.setMessage(R.string.permission_location_rationale)
.setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
request.proceed();
}
})
.setNegativeButton(R.string.button_deny, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
request.cancel();
}
})
.show();
}
@OnPermissionDenied(Manifest.permission.ACCESS_FINE_LOCATION)
void showDeniedForLocation() {
Toast.makeText(this, R.string.permission_location_denied, Toast.LENGTH_SHORT).show();
}
@OnNeverAskAgain(Manifest.permission.ACCESS_FINE_LOCATION)
void showNeverAskForLocation() {
Toast.makeText(this, R.string.permission_location_neverask, Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
Log.e(TAG, "onResume mRequestingLocationUpdates");
// Within {@code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
MainActivityPermissionsDispatcher.getPositionWithCheck(MainActivity.this);
}
@Override
protected void onStart() {
super.onStart();
Log.e(TAG, "onStart");
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
Log.e(TAG, "onStop");
/*if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}*/
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
FeedbackBottomSheetDialog dialog = new FeedbackBottomSheetDialog();
Bundle bundle = new Bundle();
bundle.putParcelable(Constants.LAT_LNG, latLng);
dialog.setArguments(bundle);
dialog.show(getSupportFragmentManager(), FeedbackBottomSheetDialog.class.getSimpleName());
}
});
LatLng sydney = new LatLng(-34, 151);
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000); //Этот метод устанавливает скорость в миллисекундах, в течение которых ваше приложение предпочитает получать обновления местоположения
mLocationRequest.setFastestInterval(5000); //Этот метод устанавливает самую высокую скорость в миллисекундах, в течение которых ваше приложение может обрабатывать обновления местоположения.
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
protected void buildLocationSettingsRequest() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
}
protected void startLocationUpdates() {
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
mLocationSettingsRequest
).setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(@NonNull LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates lss = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// Всё хорошо, настройки пользователя совпадают с требуемыми
Log.i(TAG, "All location settings are satisfied.");
try {
mCurrentLocation.getLastLocation()
.addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations, this can be null.
if (location != null) {
toMoveCamera(location);
}
}
});
} catch (SecurityException e) {
Log.e(TAG, "Ошибка доступа, разрешения нет.");
}
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
//настройки не удовлетворительны, но можно исправить
Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
"location settings ");
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
MainActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Настройки не удовлетворительны, но исправить нельзя
String errorMessage = "Location settings are inadequate, and cannot be " +
"fixed here. Fix in Settings.";
Log.e(TAG, errorMessage);
Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
// mRequestingLocationUpdates = false;
break;
}
}
});
}
public void toMoveCamera(Location location) {
Log.e(TAG, String.valueOf(location.getLatitude()));
Log.e(TAG, String.valueOf(location.getLongitude()));
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17), 1000, null);
}
@Override
public void onLocationChanged(Location location) {
toMoveCamera(location);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
//MainActivityPermissionsDispatcher.getPositionWithCheck(MainActivity.this);
}
@Override
public void onConnectionSuspended(int i) {
if(!mGoogleApiClient.isConnected())
mGoogleApiClient.connect();
Log.i(TAG, "onConnectionSuspended");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
}<file_sep>package com.example.user.vandrova;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.user.vandrova.dao.AppDatabase;
import com.example.user.vandrova.model.Review;
public class FeedbackScreenActivity extends AppCompatActivity {
Button sendFeedbackButton;
TextView placeNameTextView;
ImageView placeImageView;
EditText feedbackEditText, emailEditText, nameEditText;
RatingBar rating;
public static void show(Context context, String placeId, String placeName) {
Intent intent = new Intent(context, FeedbackScreenActivity.class);
intent.putExtra(Constants.PLACE_ID, placeId);
intent.putExtra(Constants.PLACE_NAME, placeName);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feedback_screen);
Intent intent = getIntent();
final String placeId = intent.getStringExtra(Constants.PLACE_ID);
final String placeName = intent.getStringExtra(Constants.PLACE_NAME);
rating = findViewById(R.id.ratingBar);
placeNameTextView = findViewById(R.id.placeNameTextView);
placeNameTextView.setText(placeName);
placeImageView = findViewById(R.id.placeImage);
feedbackEditText = findViewById(R.id.feedbackEditText);
emailEditText = findViewById(R.id.emailEditText);
nameEditText = findViewById(R.id.userNameEditText);
sendFeedbackButton = findViewById(R.id.sendFeedback);
sendFeedbackButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(feedbackEditText.getText()!=null && emailEditText.getText()!=null && nameEditText.getText()!=null && rating.getRating()!=0.0){
Review review = new Review(placeId, emailEditText.getText().toString(), nameEditText.getText().toString(), feedbackEditText.getText().toString(), (int) rating.getRating());
AppDatabase.getAppDatabase(FeedbackScreenActivity.this).reviewDao().insertAll(review);
Intent newIntent = new Intent(FeedbackScreenActivity.this, MainActivity.class);
Toast.makeText(FeedbackScreenActivity.this, "Thank you for feedback!", Toast.LENGTH_SHORT).show();
startActivity(newIntent);
}
else
Toast.makeText(FeedbackScreenActivity.this, "Please type the data ", Toast.LENGTH_SHORT).show();
}
});
}
}
<file_sep>package com.example.user.vandrova.dao;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
import com.example.user.vandrova.model.Review;
@Database(entities = {Review.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
private static volatile AppDatabase singleton;
private static final String DATABASE_NAME = "ReviewDb.db";
public abstract ReviewDao reviewDao();
public static AppDatabase getAppDatabase(Context context) {
if (singleton == null) {
synchronized (AppDatabase.class) {
if (singleton == null) {
singleton = Room.databaseBuilder(
context.getApplicationContext(),
AppDatabase.class,
DATABASE_NAME)
// allow queries on the main thread.
// Don't do this on a real app! See PersistenceBasicSample for an example.
.allowMainThreadQueries()
.build();
}
}
}
return singleton;
}
}
|
a55530aca3b7c33ebdb54ae95db1261354247c89
|
[
"Java"
] | 5 |
Java
|
arzumanyasha/VandroVa
|
4eddad35db941feb92765b614c12c440b775c4de
|
44e1d4050c8b3f02767f15ff2eeaeff57a186c1f
|
refs/heads/master
|
<repo_name>aclodic/install-sot<file_sep>/README.md
install-sot
===========
[](https://travis-ci.org/stack-of-tasks/install-sot)
This script install automatically the Stack of Tasks and its
dependencies.
Quick Start
-----------
To start the installation, you should:
1. Set your version of ROS
1. Set your private repositories account (optional)
1. Call:
```sh
install_sot.sh ros_subdir installation_level
```
If ROS is installed, as well as Git and Doxygen, you can start with
`installation_level=3`.
Otherwise you can set `install_level` to 0 to install the required
dependencies.
This will install a ROS workspace in `$HOME/devel/ros_subdir/`.
The stacks will be installed in `$HOME/devel/ros_subdir/stacks`.
The repositories will be cloned in: `$HOME/devel/ros_subdir/src`
The installation will then done in: `$HOME/devel/ros_subdir/install`
Usage
-----
```
Usage: `basename $0` [-h] ros_subdir installation_level
ros_subdir: The sub directory where to install the ros workspace.
The script creates a variable ros_install_path from ros_subdir:
ros_install_path=$HOME/devel/$ros_subdir
The git repositories are cloned in ros_install_path/src and
installed in ros_install_path/install.
installation_level: Specifies at which step the script should start
the installation.
Options:
-h : Display help.
-r ros_release : Specifies the ros release to use.
-l : Display the steps where the script can be started for installing.
This also display the internal instructions run by the script.
To use -l you HAVE TO specify ros_install_path and installation_level.
With -l the instructions are displayed but not run.
-g : OpenHRP 3.0.7 has a priority than OpenHRP 3.1.0. Default is the reverse.
-m : Compile the sources without updating them
-u : Update the sources without compiling them
Environment variables:
GITHUB_ACCOUNT: If you have a github user account you should set the environment variable
GITHUB_ACCOUNT to have read-write rights on the repositories
otherwise they will be uploaded with read-only rights.
PRIVATE_URI: If you have access to the private repositories for the HRP2.
Please uncomment the line defining PRIVATE_URI.
IDH_PRIVATE_URI: If you have access to the private repositories for the HRP4.
Please uncomment the line defining IDH_PRIVATE_URI.
```
Deployment:
-----------
```sh
rsync -avz $HOME/devel/ros_subdir username@robotc:./devel/
```
will copy the overall control architecture in
the home directory of username in computer robotc (could be hrp2c).
3rd party dependencies:
-----------------------
The following external software are required (and will be installed
automatically by step 0):
- gfortran
- lapack
- ros-pr2-controllers
- omniidl
<file_sep>/.travis/build
#!/bin/sh
set -ev
# Directories.
root_dir=`pwd`
build_dir="$root_dir/_travis/build"
install_dir="$root_dir/_travis/install"
# Shortcuts.
git_clone="git clone --quiet --recursive"
# Create layout.
rm -rf "$build_dir" "$install_dir"
mkdir -p "$build_dir"
mkdir -p "$install_dir"
# Setup environment variables.
export LD_LIBRARY_PATH="$install_dir/lib:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$install_dir/lib/`dpkg-architecture -qDEB_BUILD_MULTIARCH`:$LD_LIBRARY_PATH"
export PKG_CONFIG_PATH="$install_dir/lib/pkgconfig:$PKG_CONFIG_PATH"
export PKG_CONFIG_PATH="$install_dir/lib/`dpkg-architecture -qDEB_BUILD_MULTIARCH`/pkgconfig:$PKG_CONFIG_PATH"
# Launch the script while making sure we don't produce too much output.
(($root_dir/scripts/install_sot.sh -r hydro $build_dir 0 2>&1) \
| tee $build_dir/install.log) | head -c 3000 || tail -c 900 $build_dir/install.log
|
ffce1638ab101f9ea32b6c76ddab5aab40883501
|
[
"Markdown",
"Shell"
] | 2 |
Markdown
|
aclodic/install-sot
|
3dc92cb0bd4b6712b6299f234400c4c9b2096dbc
|
8e5e8f30ec6e7e5cdf9d0f8622cb6e03b5b796e6
|
refs/heads/master
|
<repo_name>GolovchenkoA/RESTfulExample<file_sep>/src/main/java/ua/golovchenko/artem/rest/JSONService.java
package ua.golovchenko.artem.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import ua.golovchenko.artem.User;
import java.util.LinkedList;
import java.util.List;
/*@Path("/users")*/
public class JSONService {
private static List<User> users = new LinkedList();
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers() {
users.add(1,new User(1,"ManyUserName","ManyUserSurname"));
return users;
}
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public User getUser() {
User user = new User();
user.setName("OneUserName");
user.setSurname("OneUserSurname");
return user;
}
@POST
@Path("/post")
//@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(User user) {
String result = "User saved : " + user;
users.add(user.getId(), user);
return Response.status(201).entity(result).build();
}
}
|
84911811b405b30aed650f73ebbb837c91846d16
|
[
"Java"
] | 1 |
Java
|
GolovchenkoA/RESTfulExample
|
6d875f23c6234c72e6c71d51ede048941ead46e5
|
d1b791fc780cc9e0f2b0dc0340e901d78a2c06e4
|
refs/heads/main
|
<file_sep># fingerspace
A fully responsive website made with react.
|
b0626d0f54fe1738aae77a60ec13e0d86c70ae54
|
[
"Markdown"
] | 1 |
Markdown
|
JuniorBaymax/fingerspace
|
2c2a75dbd9880d4a1ee0ae4591dca164bd64d5ae
|
5e7c33e19a5ef6aae13f36e92804ec176bd6d0a6
|
refs/heads/master
|
<repo_name>iRyanBell/VolumeNotchUI<file_sep>/README.md
# VolumeNotchUI
An intentionally bad volume controller UI.

Hosted demo:
https://iryanbell.github.io/VolumeNotchUI/NotchedVolume/
<file_sep>/Assets/ColorSetting.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColorSetting : MonoBehaviour
{
Renderer r;
public GameObject ball;
void Start()
{
r = GetComponent<Renderer>();
r.material.color = Color.gray;
}
void Update()
{
if (ball.transform.position.x > transform.position.x)
{
r.material.color = Color.green;
}
else
{
r.material.color = Color.gray;
}
}
}
<file_sep>/Assets/MouseInteractivity.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseInteractivity : MonoBehaviour
{
private float _sensitivity;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private bool _isRotating;
public GameObject notches;
void Start()
{
_sensitivity = 0.1f;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
_mouseReference = Input.mousePosition;
_isRotating = true;
}
if (Input.GetMouseButtonUp(0))
{
_isRotating = false;
}
if (_isRotating)
{
_mouseOffset = (Input.mousePosition - _mouseReference);
float rot = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity;
rot = Mathf.Max(rot, -30);
rot = Mathf.Min(rot, 30);
Quaternion q = notches.transform.rotation;
notches.transform.rotation = Quaternion.Slerp(q, Quaternion.Euler(0, 0, rot), Time.time * 0.25f);
}
else
{
Quaternion r = notches.transform.rotation;
r.z *= 0.9f;
notches.transform.rotation = r;
}
}
}<file_sep>/Assets/Vol.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Vol : MonoBehaviour
{
public Text volDisplay;
void Update()
{
GameObject[] notches = GameObject.FindGameObjectsWithTag("notch");
int vol = 0;
for (int i = 0; i < notches.Length; i++)
{
Color notchColor = notches[i].GetComponent<Renderer>().material.color;
if (notchColor == Color.green)
{
vol += 1;
}
}
volDisplay.text = vol > 0 ? "Volume: " + vol : "Volume: Muted";
}
}
<file_sep>/Assets/Catch.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Catch : MonoBehaviour
{
void Update()
{
if (transform.position.y < -3)
{
Vector3 pos = transform.position;
pos.y = 3;
pos.x = -3;
transform.position = pos;
}
}
}
|
4991f78d1af8efaa6c60e2ba4bf4f1dff6639a3d
|
[
"Markdown",
"C#"
] | 5 |
Markdown
|
iRyanBell/VolumeNotchUI
|
c9caa3e1ecb9f3e9ff718ef6c7bb5f42d4efd214
|
305002a688ba0b6bd780ff4586d5646aa648de07
|
refs/heads/main
|
<file_sep>package main
import (
"io/ioutil"
"log"
"net/http"
"github.com/labstack/echo"
)
//const url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?"
func main() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.GET("/users/:id", getUser)
e.GET("/coWin/getSlot/:age/:districtID/:date", getSlot)
e.Logger.Fatal(e.Start(":1323"))
}
func getUser(c echo.Context) error {
// User ID from path `users/:id`
// id := c.Param("id")
// return c.String(http.StatusOK, id)
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
log.Fatalln(err)
}
//We Read the response body on the line below.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
//Convert the body to type string
sb := string(body)
//log.Printf(sb)
return c.String(http.StatusOK, sb)
}
func getSlot(c echo.Context) error {
a := c.Param("age")
dst := c.Param("districtID")
dt := c.Param("date")
URL := "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?district_id=" + dst + "&date=" + dt
resp, err := http.Get(URL)
if err != nil {
log.Fatalln(err)
}
//We Read the response body on the line below.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
//Convert the body to type string
sb := string(body)
log.Printf(a)
return c.String(http.StatusOK, sb)
}
<file_sep>## CoWin Slot Fetcher
Run the server.go in your local can call the API
## TODO
Update Readme file
Add URI parameters
Filter results with AGE
Add more district codes
Host it and make free APPS in Ionic / React Native
|
86fd855481750f15f1fb57d8c05b5b12907051b8
|
[
"Markdown",
"Go"
] | 2 |
Go
|
vishalkprabhu/cowin-slot-fetcher
|
a3e9f99360c56c9bf3a8c4bfab88437cc07b9c6a
|
1fb5138a9849dd01f3b9d324f963db691fafeac7
|
refs/heads/master
|
<file_sep># ud036_StarterCode
Source code for a Movie Trailer website. This website incluces several movie titles. Each movie title will have a box art and a link to the trailer.
## Generating the HTML
To generate website run entertainment_center.py
## Adding a new movie
1. Create an instance of the media.movie class in entertainment_center.py
2. Add the instace to the movies list in entertainment_center.py
<file_sep>class Video():
"""
Class: Video
Parent: None
Description: Stores all info about a video
Attributes: title - name of video
youtube_url - url to video
"""
def __init__(self, title, video):
self.title = title
self.youtube_url = video
class Movie(Video):
"""
Class: Move
Parent: Video
Description: Stores all info about a movie
Attributes: poster_image_url - url to movie poster image
"""
def __init__(self, title, art, trailer):
Video.__init__(self, title, trailer)
self.poster_image_url = art
<file_sep>import media
import fresh_tomatoes
# make Toy Story movie class
toy_story_trailer = "https://www.youtube.com/watch?v=KYz2wyBy3kc"
toy_story_art = "https://lumiere-a.akamaihd.net/v1/images" \
"/open-uri20150422-20810-m8zzyx_5670999f.jpeg?" \
"region=0,0,300,450"
toy_story = media.Movie("Toy Story", toy_story_art, toy_story_trailer)
# make Avatar movie class
avatar_trailer = "https://www.youtube.com/watch?v=5PSNL1qE6VY"
avatar_art = "https://resizing.flixster.com/86CQQH9RKDumbcyHqzMQGixO_XI=" \
"/206x305/v1.bTsxMTE3Njc5MjtqOzE3NTQ0OzEyMDA7ODAwOzEyMDA"
avatar = media.Movie("avatar", avatar_art, avatar_trailer)
# make Avatar movie class
starship_troopers_trailer = "https://www.youtube.com/watch?v=Y07I_KER5fE"
starship_troopers_art = "https://upload.wikimedia.org/wikipedia/en/d/df" \
"/Starship_Troopers_-_movie_poster.jpg"
starship_troopers = media.Movie("Starship Troopers",
starship_troopers_art,
starship_troopers_trailer)
movies = [toy_story, avatar, starship_troopers]
fresh_tomatoes.open_movies_page(movies)
|
f4454f0e05a7612801b1d00e0e4ea2dc4d0e0d47
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
CodeFish29/ud036_StarterCode
|
3d0dff82cdd40d795baddc6ee7a30f88d5dc9e77
|
8720bd46d5524b75864b2fcf3b8d549c3b4e01da
|
refs/heads/master
|
<file_sep>[SuiteResult context=Account Management System]<file_sep>package com.SDETtraining.Intro;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Introduction {
// Example Testing script using SDETtraining.com
public static void main(String[] args){
// START: Generate the test outline
// Step 1. Configure the WebDriver object
// 1a. Declare the driver
WebDriver driver;
// 1b. Set the driver properties
System.setProperty("webdriver.gecko.driver", "C:\\JARs\\geckodriver.exe");
// 1c. Instantiate the driver
driver = new FirefoxDriver();
// 1d. Open the browser
driver.get("https://www.google.com/");
// Step 2. Navigated to the Projects Page >> http://www.sdettraining.com/projects/
driver.navigate().to("http://www.sdettraining.com/projects/");
// Step 3. Clicked on the Account Management Link
// 3a. Locate the element (Locate by... linkText, ID, class, xPath, etc.)
// 3b. Perform the action (clicking in this case)
driver.findElement(By.linkText("Account Management System")).click();
// Step 4. Fill in test fields (in this case, login info
// 4a. Enter email address into email text box
// Determine the by.method >> ID in this case
// Perform the action >> sendKeys in this case
driver.findElement(By.id("MainContent_txtUserName")).sendKeys("<EMAIL>");
// 4b. Enter password into password text box
driver.findElement(By.id("MainContent_txtPassword")).sendKeys("<PASSWORD>");
// Step 5. Click login
driver.findElement(By.id("MainContent_btnLogin")).click();
// Step 6. We should get confirmation of successful login
String result = driver.findElement(By.id("MainContent_lblid")).getText();
if (result.contains("Welcome back!") == true) {
result = "PASS";
} else {
result = "FAIL";
}
System.out.println(result);
driver.close();
//driver.quit() >> Closes all instances of the safe mode browser
}
}
<file_sep>package com.SDETtraining.demo;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestNGDataProvider {
@Test(dataProvider = "getData")
public void ExcelTest(String email, String name, String number) {
System.out.println("NEW RECORD: [" + name + ", " + email + ", " + number + "]");
}
@DataProvider
public String[][] getData() {
return datadriven.Excel.get("C:/Users/Alec/Google Drive/Work/SDET Training/Test Data/dataset.xls");
}
}
<file_sep>package com.SDETtraining.ams;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import utilities.DriverFactory;
public class Login {
// Initialization of static parameters
WebDriver driver;
String baseUrl = "http://sdettraining.com/trguitransactions/Account.aspx";
@Test(dataProvider = "getLoginData")
public void testLogin(String email, String password) {
// Enters login data and attempts to login
driver.findElement(By.id("MainContent_txtUserName")).clear();
driver.findElement(By.id("MainContent_txtUserName")).sendKeys(email);
driver.findElement(By.id("MainContent_txtPassword")).clear();
driver.findElement(By.id("MainContent_txtPassword")).sendKeys(password);
driver.findElement(By.id("MainContent_btnLogin")).click();
// Checks for successful login
String result = driver.findElement(By.id("MainContent_lblid")).getText();
if (result.contains("Welcome back!")) {
System.out.println("TEST PASSED");
} else {
Assert.fail("Could not find element");
}
}
@BeforeMethod
public void beforeMethod() {
System.out.println("Running test");
String driverType = "chrome";
new utilities.DriverFactory();
driver = DriverFactory.newDriver(driverType);
driver.get(baseUrl);
smoketests.Window.testPageTitle(driver, "SDET Training");
}
@AfterMethod
public void afterMethod() {
smoketests.Window.testPageTitle(driver, "SDET Training");
System.out.println("Closing test");
driver.quit();
}
@DataProvider
public String[][] getLoginData() {
return datadriven.Excel.get("C:/Users/Alec/Google Drive/Work/SDET Training/Test Data/logindata.xls");
}
}
<file_sep>package smoketests;
import org.openqa.selenium.WebDriver;
import junit.framework.Assert;
@SuppressWarnings("deprecation")
public class Window {
// This method tests the page title
public static void testPageTitle(WebDriver driver, String expected) {
String actual = driver.getTitle();
System.out.println("PAGE TITLE: " + actual);
if (!actual.contains(expected)) {
Assert.fail("PAGE TITLE TEST FAILED");
}
}
}
<file_sep>package com.SDETtraining.Intro;
import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
public class CreateAccountTest {
WebDriver driver;
String baseURL = "http://www.sdettraining.com/";
String firstName = "Alec";
String lastName = "Millar";
String email = "<EMAIL>";
String password = "<PASSWORD>";
String phone = "703-975-7323";
String country = "Australia";
@Test
public void createNewAccount() {
/*System.out.print("What browser would you like to use? Chrome, Firefox, or IE: ");
Scanner in = new Scanner(System.in);
String browserType = in.next();*/
String browserType = "firefox";
//Instantiate driver
driver = utilities.DriverFactory.newDriver(browserType);
driver.get(baseURL + "projects/");
driver.findElement(By.linkText("Account Management System")).click();
driver.findElement(By.linkText("Create Account")).click();
driver.findElement(By.id("MainContent_txtFirstName")).sendKeys(firstName);
driver.findElement(By.id("MainContent_txtLastName")).sendKeys(lastName);
driver.findElement(By.id("MainContent_Male")).click();
driver.findElement(By.id("MainContent_txtEmail")).sendKeys(email);
driver.findElement(By.id("MainContent_txtPassword")).sendKeys(password);
driver.findElement(By.id("MainContent_txtVerifyPassword")).sendKeys(password);
driver.findElement(By.xpath(".//*[@id='MainContent_txtHomePhone']")).sendKeys(phone);
driver.findElement(By.xpath(".//*[@id='MainContent_txtCellPhone']")).sendKeys(phone);
new Select(driver.findElement(By.id("MainContent_menuCountry"))).selectByValue(country);
// Ensures that emails are checked and updates is unchecked.
if (!(driver.findElement(By.id("MainContent_checkWeeklyEmail")).isSelected())){
System.out.println("Checking Weekly Emails.");
driver.findElement(By.id("MainContent_checkWeeklyEmail")).click();
}
if (!(driver.findElement(By.id("MainContent_checkMonthlyEmail")).isSelected())){
driver.findElement(By.id("MainContent_checkMonthlyEmail")).click();
System.out.println("Checking Monthly Emails.");
}
if ((driver.findElement(By.id("MainContent_checkUpdates")).isSelected())){
driver.findElement(By.id("MainContent_checkUpdates")).click();
System.out.println("Unchecking Updates.");
}
driver.findElement(By.id("MainContent_txtInstructions")).sendKeys("Automatically filled by Selenium for testing purposes.");
}
@After
public void tearDown() {
System.out.println("Closing the browser, writing results to file, generally ending test.");
utilities.Screenshot.snap(driver, "CreateAccountTest", email);
driver.quit();
}
}
<file_sep>package utilities;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class Screenshot {
// This method takes a screenshot of the browser and saves as a file
public static void snap(WebDriver driver, String filename, String suffix) {
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // Creates a file from the screenshot of the driver instance
try {
FileUtils.copyFile(screenshotFile, new File ("C:/Users/Alec/Google Drive/Work/TestScreenshots/" + filename + "_" + suffix + ".jpg"));
} catch (IOException e) {
System.out.println("Could not save file");
e.printStackTrace();
}
}
}
<file_sep>package utilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class DriverFactory {
// This method will return a WebDriver
// Default browser is Chrome
public static WebDriver newDriver() {
System.setProperty("webdriver.chrome.driver", "C:\\JARs\\chromedriver.exe");
return new ChromeDriver();
}
// User determines browser through overloading by passing browser type
public static WebDriver newDriver(String browserType) {
if (browserType.equalsIgnoreCase("firefox")) {
System.out.println("Using Firefox");
System.setProperty("webdriver.gecko.driver", "C:\\JARs\\geckodriver.exe");
return new FirefoxDriver();
}
else if (browserType.equalsIgnoreCase("chrome")) {
System.out.println("Using Chrome");
System.setProperty("webdriver.chrome.driver", "C:\\JARs\\chromedriver.exe");
return new ChromeDriver();
}
else {
System.out.println("Using Internet Explorer");
System.setProperty("webdriver.ie.driver", "C:\\JARs\\IEDriverServer.exe");
return new InternetExplorerDriver();
}
}
}
<file_sep>package com.SDETtraining.Intro;
import java.util.Scanner;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
/*
/ Code looks great, very clean and well organized.
/ Probably should add comments at each block/section to tell others (like me) what you are doing.
/ You are using JUnit framework for your tests. Try using Assert methods to validate your tests.
*/
public class LoginNewUserTest {
// Initialize Static Properties
WebDriver driver;
//emails: <EMAIL>, <EMAIL>, <EMAIL>
//passwords: <PASSWORD>, <PASSWORD>, <PASSWORD>
String[] firstNames = {"Alec", "Scott", "Jacob"};
String[] lastNames = {"Millar", "Hale", "Marron"};
String[] emails = {"<EMAIL>", "<EMAIL>", "<EMAIL>"};
String[] passwords = {"<PASSWORD>", "<PASSWORD>", "<PASSWORD>"};
String[] phones = {"123-456-7890", "987-654-3210", "434-334-1423"};
String[] countries = {"Australia", "China", "Denmark"};
int records = emails.length;
String baseURL = "http://sdettraining.com/trguitransactions/Account.aspx";
@Test
public void testLogin() {
for (int i=0; i<records; i++) {
System.out.print("What browser would you like to use? Chrome, Firefox, or IE: ");
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
String browserType = in.next();
driver = utilities.DriverFactory.newDriver(browserType);
driver.get(baseURL);
driver.findElement(By.id("MainContent_txtUserName")).sendKeys(emails[i]);
driver.findElement(By.id("MainContent_txtPassword")).sendKeys(passwords[i]);
driver.findElement(By.id("MainContent_btnLogin")).click();
String result = driver.findElement(By.id("MainContent_lblid")).getText();
if (result.contains("Welcome back!") == true) {
result = "PASS";
} else {
result = "FAIL";
}
System.out.println(result);
System.out.println("Closing the browser and sending screenshot to file.");
String filename = "LoginTest" + Integer.toString(i+1);
utilities.Screenshot.snap(driver, filename, emails[i]);
driver.findElement(By.xpath(".//*[@id='MainContent_loggedinlinks']/ul/li[4]/a")).click();
driver.quit();
}
}
@Test
public void testNewUser() {
for (int i=0; i<records; i++) {
System.out.print("What browser would you like to use? Chrome, Firefox, or IE: ");
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
String browserType = in.next();
driver = utilities.DriverFactory.newDriver(browserType);
driver.get(baseURL);
driver.findElement(By.id("createaccount")).click();
driver.findElement(By.id("MainContent_txtFirstName")).sendKeys(firstNames[i]);
driver.findElement(By.id("MainContent_txtLastName")).sendKeys(lastNames[i]);
driver.findElement(By.id("MainContent_Male")).click();
driver.findElement(By.id("MainContent_txtEmail")).sendKeys(emails[i]);
driver.findElement(By.id("MainContent_txtPassword")).sendKeys(passwords[i]);
driver.findElement(By.id("MainContent_txtVerifyPassword")).sendKeys(passwords[i]);
driver.findElement(By.xpath(".//*[@id='MainContent_txtHomePhone']")).sendKeys(phones[i]);
driver.findElement(By.xpath(".//*[@id='MainContent_txtCellPhone']")).sendKeys(phones[i]);
new Select(driver.findElement(By.id("MainContent_menuCountry"))).selectByValue(countries[i]);
// Ensures that emails are checked and updates is unchecked.
if (!(driver.findElement(By.id("MainContent_checkWeeklyEmail")).isSelected())){
System.out.println("Checking Weekly Emails.");
driver.findElement(By.id("MainContent_checkWeeklyEmail")).click();
}
if (!(driver.findElement(By.id("MainContent_checkMonthlyEmail")).isSelected())){
driver.findElement(By.id("MainContent_checkMonthlyEmail")).click();
System.out.println("Checking Monthly Emails.");
}
if ((driver.findElement(By.id("MainContent_checkUpdates")).isSelected())){
driver.findElement(By.id("MainContent_checkUpdates")).click();
System.out.println("Unchecking Updates.");
}
driver.findElement(By.id("MainContent_txtInstructions")).sendKeys("Automatically filled by Selenium for testing purposes.");
System.out.println("Closing browser & ending test.");
driver.quit();
}
}
}
<file_sep>package com.SDETtraining.demo;
import java.util.List;
public class ReadCSV {
public static void main(String[] args) {
List<String[]> newUsers = datadriven.CSV.get("C:/Users/Alec/Google Drive/Work/SDET Training/Test Data/dataset.csv");
for (String[] user : newUsers) {
System.out.println("NEW USER");
System.out.println("----------");
for (int i=0; i<user.length; i++) {
System.out.print(user[i] + ", ");
}
System.out.println("\n");
}
}
}<file_sep>package com.SDETtraining.demo;
public class ReadExcel {
public static void main(String[] args) {
String[][] data = datadriven.Excel.get("C:/Users/Alec/Google Drive/Work/SDET Training/Test Data/dataset.xls");
for (String[] row : data) {
System.out.print("[");
for (String element : row) {
System.out.print(element + " ");
}
System.out.println("]");
}
}
}
<file_sep>package tests;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pagefactory.LoginPage;
public class LoginTestPageFactory {
WebDriver driver;
LoginPage LoginPage;
public String email = "<EMAIL>";
public String password = "<PASSWORD>";
public String baseUrl = "http://sdettraining.com/trguitransactions/Account.aspx";
@Test
public void LoginTestCase() {
LoginPage.loginToAccount(email, password);
}
@BeforeMethod
public void setUp() {
driver = utilities.DriverFactory.newDriver("chrome");
driver.get(baseUrl);
LoginPage = new LoginPage(driver);
}
@AfterMethod
public void tearDown() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.quit();
}
}
|
6dd823639f63ae6af1c5da47052d7f3ad6590477
|
[
"Java",
"INI"
] | 12 |
INI
|
AlecMillar/SeleniumTraining
|
183db48d9ce59b731561c2e61f8dd58db36b2ea2
|
d3d63dbf4482b7cb1fb40d1cb56339b3de23388b
|
refs/heads/master
|
<file_sep>import { Update } from '@ngrx/entity';
import { createAction, props } from '@ngrx/store';
import { Customer } from '../../models/customer.model';
export enum CustomerActionsType {
LOAD_CUSTOMERS_ALL = '[CUSTOMER] Load Customers All',
LOAD_CUSTOMERS_ALL_SUCCESS = '[CUSTOMER] Load Customers All Success',
LOAD_CUSTOMERS_ALL_FAIL = '[CUSTOMER] Load Customers All Fail',
LOAD_CUSTOMER = '[CUSTOMER] Load Customer',
LOAD_CUSTOMER_SUCCESS = '[CUSTOMER] Load Customer Success',
LOAD_CUSTOMER_FAIL = '[CUSTOMER] Load Customer Fail',
CREATE_CUSTOMER = '[CUSTOMER] Create Customer',
CREATE_CUSTOMER_SUCCESS = '[CUSTOMER] Create Customer Success',
CREATE_CUSTOMER_FAIL = '[CUSTOMER] Create Customer Fail',
UPDATE_CUSTOMER = '[CUSTOMER] Update Customer',
UPDATE_CUSTOMER_SUCCESS = '[CUSTOMER] Update Customer Success',
UPDATE_CUSTOMER_FAIL = '[CUSTOMER] Update Customer Fail',
DELETE_CUSTOMER = '[CUSTOMER] Delete Customer',
DELETE_CUSTOMER_SUCCESS = '[CUSTOMER] Delete Customer Success',
DELETE_CUSTOMER_FAIL = '[CUSTOMER] Delete Customer Fail',
}
export const LOAD_CUSTOMERS_ALL_ACTION = createAction(CustomerActionsType.LOAD_CUSTOMERS_ALL);
export const LOAD_CUSTOMERS_ALL_SUCCESS_ACTION = createAction(
CustomerActionsType.LOAD_CUSTOMERS_ALL_SUCCESS,
props<{ loadedCustomers: Customer[] }>()
);
export const LOAD_CUSTOMERS_ALL_FAIL_ACTION = createAction(
CustomerActionsType.LOAD_CUSTOMERS_ALL_FAIL,
props<{ err: string }>()
);
export const LOAD_CUSTOMER_ACTION = createAction(
CustomerActionsType.LOAD_CUSTOMER,
props<{ customerId: number }>()
);
export const LOAD_CUSTOMER_SUCCESS_ACTION = createAction(
CustomerActionsType.LOAD_CUSTOMER_SUCCESS,
props<{ loadedCustomer: Customer }>()
);
export const LOAD_CUSTOMER_FAIL_ACTION = createAction(
CustomerActionsType.LOAD_CUSTOMER_FAIL,
props<{ err: string }>()
);
export const CREATE_CUSTOMER_ACTION = createAction(
CustomerActionsType.CREATE_CUSTOMER,
props<{ newCustomer: Customer }>()
);
export const CREATE_CUSTOMER_SUCCESS_ACTION = createAction(
CustomerActionsType.CREATE_CUSTOMER_SUCCESS,
props<{ newCustomer: Customer }>()
);
export const CREATE_CUSTOMER_FAIL_ACTION = createAction(
CustomerActionsType.CREATE_CUSTOMER_FAIL,
props<{ err: string }>()
);
export const UPDATE_CUSTOMER_ACTION = createAction(
CustomerActionsType.UPDATE_CUSTOMER,
props<{ customer: Customer }>()
);
export const UPDATE_CUSTOMER_SUCCESS_ACTION = createAction(
CustomerActionsType.UPDATE_CUSTOMER_SUCCESS,
props<{ update: Update<Customer> }>()
);
export const UPDATE_CUSTOMER_FAIL_ACTION = createAction(
CustomerActionsType.UPDATE_CUSTOMER_FAIL,
props<{ err: string }>()
);
export const DELETE_CUSTOMER_ACTION = createAction(
CustomerActionsType.DELETE_CUSTOMER,
props<{ customerId: number }>()
);
export const DELETE_CUSTOMER_SUCCESS_ACTION = createAction(
CustomerActionsType.DELETE_CUSTOMER_SUCCESS,
props<{ customerId: number }>()
);
export const DELETE_CUSTOMER_FAIL_ACTION = createAction(
CustomerActionsType.DELETE_CUSTOMER_FAIL,
props<{ err: string }>()
);
<file_sep>import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { CustomerService } from '../../services/customer.service';
import * as customerActions from './customer.actions';
import { catchError, mergeMap, map } from 'rxjs/operators';
import { of } from 'rxjs';
import { Customer } from '../../models/customer.model';
@Injectable()
export class CustomerEffects {
constructor(
private actions$: Actions,
private customerService: CustomerService,
) {}
loadCustomersAll$ = createEffect(() =>
this.actions$.pipe(
ofType(customerActions.LOAD_CUSTOMERS_ALL_ACTION),
mergeMap(() => {
return this.customerService.getCustomers().pipe(
map((customers: Customer[]) => {
return customerActions.LOAD_CUSTOMERS_ALL_SUCCESS_ACTION({ loadedCustomers: customers });
})
);
}),
catchError(error => of(customerActions.LOAD_CUSTOMERS_ALL_FAIL_ACTION({ err: error}))
)
)
);
loadCustomer$ = createEffect(() =>
this.actions$.pipe(
ofType(customerActions.LOAD_CUSTOMER_ACTION),
mergeMap((action: { type: string, customerId: number}) => {
return this.customerService.getCustomerById(action.customerId).pipe(
map((customer: Customer) => {
return customerActions.LOAD_CUSTOMER_SUCCESS_ACTION({ loadedCustomer: customer });
})
);
}),
catchError(error => of(customerActions.LOAD_CUSTOMER_FAIL_ACTION({ err: error}))
)
)
);
createCustomer$ = createEffect(() =>
this.actions$.pipe(
ofType(customerActions.CREATE_CUSTOMER_ACTION),
mergeMap((action: { type: string, newCustomer: Customer }) => {
return this.customerService.createCustomer(action.newCustomer).pipe(
map((customer: Customer) => {
return customerActions.CREATE_CUSTOMER_SUCCESS_ACTION({ newCustomer: customer });
})
);
}),
catchError(error => of(customerActions.LOAD_CUSTOMER_FAIL_ACTION({ err: error}))
)
)
);
updateCustomer$ = createEffect(() =>
this.actions$.pipe(
ofType(customerActions.UPDATE_CUSTOMER_ACTION),
mergeMap((action: { type: string, customer: Customer }) => {
return this.customerService.updateCustomer(action.customer).pipe(
map((updatedCustomer: Customer) => {
return customerActions.UPDATE_CUSTOMER_SUCCESS_ACTION({
update: {
id: updatedCustomer.id,
changes: updatedCustomer,
}
});
})
);
}),
catchError(error => of(customerActions.UPDATE_CUSTOMER_FAIL_ACTION({ err: error}))
)
)
);
deleteCustomer$ = createEffect(() =>
this.actions$.pipe(
ofType(customerActions.DELETE_CUSTOMER_ACTION),
mergeMap((action: { type: string, customerId: number }) => {
return this.customerService.deleteCustomer(action.customerId).pipe(
map(() => customerActions.DELETE_CUSTOMER_SUCCESS_ACTION({ customerId: action.customerId }))
);
}),
catchError(error => of(customerActions.DELETE_CUSTOMER_FAIL_ACTION({ err: error}))
)
)
);
}
<file_sep>import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity';
import { Customer } from '../../models/customer.model';
export interface CustomerState extends EntityState<Customer> {
selectedCustomerId: number;
loading: boolean;
loaded: boolean;
error: string;
}
export const CUSTOMER_ADAPTER: EntityAdapter<Customer> = createEntityAdapter<Customer>();
export const DEFAULT_CUSTOMER_STATE: CustomerState = {
ids: [],
entities: {},
selectedCustomerId: null,
loading: false,
loaded: true,
error: null,
};
export const INITIAL_CUSTOMER_STATE = CUSTOMER_ADAPTER.getInitialState(DEFAULT_CUSTOMER_STATE);
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormsModule} from '@angular/forms';
import { CustomerComponent } from './customer/customer.component';
import { CustomerAddComponent } from './customer-add/customer-add.component';
import { CustomerEditComponent } from './customer-edit/customer-edit.component';
import { CustomerListComponent } from './customer-list/customer-list.component';
import { CustomersRoutingModule } from './customers-routing.module';
import { StoreModule } from '@ngrx/store';
import { reducer } from '../shared/stores/customer/customer.reducer';
import { EffectsModule } from '@ngrx/effects';
import { CustomerEffects } from '../shared/stores/customer/customer.effects';
@NgModule({
declarations: [CustomerComponent, CustomerAddComponent, CustomerEditComponent, CustomerListComponent],
imports: [
CommonModule,
ReactiveFormsModule,
FormsModule,
CustomersRoutingModule,
StoreModule.forFeature('customers', reducer),
EffectsModule.forFeature([CustomerEffects]),
]
})
export class CustomersModule { }
<file_sep>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Customer } from '../models/customer.model';
@Injectable({
providedIn: 'root'
})
export class CustomerService {
constructor(private http: HttpClient) { }
private customersUrl = 'http://localhost:3000/customers';
getCustomers(): Observable<Customer[]> {
return this.http.get<Customer[]>(`${this.customersUrl}`);
}
getCustomerById(id: number): Observable<Customer> {
return this.http.get<Customer>(`${this.customersUrl}/${id}`);
}
createCustomer(newCustomer: Customer): Observable<Customer> {
return this.http.post<Customer>(this.customersUrl, newCustomer);
}
updateCustomer(customer: Customer): Observable<Customer> {
return this.http.patch<Customer>(`${this.customersUrl}/${customer.id}`, customer);
}
deleteCustomer(id: number): Observable<void> {
return this.http.delete<void>(`${this.customersUrl}/${id}`);
}
}
<file_sep>import { createSelector, createFeatureSelector} from '@ngrx/store';
import { CustomerState, CUSTOMER_ADAPTER } from './customer.state';
export const FEATURE_KEY = 'customers';
export const SELECT_CUSTOMER_FEATURE = createFeatureSelector<CustomerState>(
FEATURE_KEY
);
export const GET_CUSTOMERS_SELECTOR = createSelector(
SELECT_CUSTOMER_FEATURE,
CUSTOMER_ADAPTER.getSelectors().selectAll
);
export const GET_CUSTOMERS_LOADING_SELECTOR = createSelector(
SELECT_CUSTOMER_FEATURE,
(state: CustomerState) => state.loading
);
export const GET_CUSTOMERS_LOADED_SELECTOR = createSelector(
SELECT_CUSTOMER_FEATURE,
(state: CustomerState) => state.loaded
);
export const GET_CUSTOMERS_ERROR_SELECTOR = createSelector(
SELECT_CUSTOMER_FEATURE,
(state: CustomerState) => state.error
);
export const GET_SELECTED_CUSTOMER_ID = createSelector(
SELECT_CUSTOMER_FEATURE,
(state: CustomerState) => state.selectedCustomerId
);
export const GET_CURRENT_CUSTOMER = createSelector(
SELECT_CUSTOMER_FEATURE,
GET_SELECTED_CUSTOMER_ID,
(state: CustomerState) => state.entities[state.selectedCustomerId]
);
<file_sep>import { CustomerState } from './customer/customer.state';
export interface AppState {
customers: CustomerState;
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';
import { Customer } from 'src/app/shared/models/customer.model';
import { AppState } from 'src/app/shared/stores/app.state';
import { DELETE_CUSTOMER_ACTION, LOAD_CUSTOMERS_ALL_ACTION, LOAD_CUSTOMER_ACTION } from 'src/app/shared/stores/customer/customer.actions';
import * as fromCustomer from '../../shared/stores/customer/customer.selector';
@Component({
selector: 'app-customer-list',
templateUrl: './customer-list.component.html',
styleUrls: ['./customer-list.component.scss']
})
export class CustomerListComponent implements OnInit {
customers$: Observable<Customer[]>;
error$: Observable<string>;
constructor(private store: Store<AppState>) { }
ngOnInit(): void {
this.store.dispatch(LOAD_CUSTOMERS_ALL_ACTION());
this.customers$ = this.store.pipe(select(fromCustomer.GET_CUSTOMERS_SELECTOR));
this.error$ = this.store.pipe(select(fromCustomer.GET_CUSTOMERS_ERROR_SELECTOR));
}
deleteCustomer(customer: Customer): void {
if (confirm('Are you sure you want to delete the customer?')) {
this.store.dispatch(DELETE_CUSTOMER_ACTION({ customerId: customer.id }));
}
}
editCustomer(customer: Customer): void {
this.store.dispatch(LOAD_CUSTOMER_ACTION({ customerId: customer.id }));
}
}
<file_sep>import { Action, createReducer, on } from '@ngrx/store';
import * as CustomerStateActions from './customer.actions';
import { CustomerState, CUSTOMER_ADAPTER, INITIAL_CUSTOMER_STATE } from './customer.state';
const customerReducer = createReducer(
INITIAL_CUSTOMER_STATE,
on(CustomerStateActions.LOAD_CUSTOMERS_ALL_ACTION, state => ({
...state,
loading: true,
loaded: false,
})),
on(CustomerStateActions.LOAD_CUSTOMERS_ALL_SUCCESS_ACTION, (state, { loadedCustomers }) => {
return CUSTOMER_ADAPTER.setAll(loadedCustomers, {
...state,
loading: false,
loaded: true,
});
}),
on(CustomerStateActions.LOAD_CUSTOMERS_ALL_FAIL_ACTION, (state, { err }) => ({
...state,
entities: {},
loading: false,
loaded: false,
error: err,
})),
on(CustomerStateActions.LOAD_CUSTOMER_SUCCESS_ACTION, (state, { loadedCustomer }) => {
return CUSTOMER_ADAPTER.addOne(loadedCustomer, {
...state,
selectedCustomerId: loadedCustomer.id,
});
}),
on(CustomerStateActions.LOAD_CUSTOMER_FAIL_ACTION, (state, { err }) => ({
...state,
error: err,
})),
on(CustomerStateActions.CREATE_CUSTOMER_SUCCESS_ACTION, (state, { newCustomer }) => {
return CUSTOMER_ADAPTER.addOne(newCustomer, state);
}),
on(CustomerStateActions.CREATE_CUSTOMER_FAIL_ACTION, (state, { err }) => ({
...state,
error: err,
})),
on(CustomerStateActions.UPDATE_CUSTOMER_SUCCESS_ACTION, (state, { update }) => {
return CUSTOMER_ADAPTER.updateOne(update, state);
}),
on(CustomerStateActions.UPDATE_CUSTOMER_FAIL_ACTION, (state, { err }) => ({
...state,
error: err,
})),
on(CustomerStateActions.DELETE_CUSTOMER_SUCCESS_ACTION, (state, { customerId }) => {
return CUSTOMER_ADAPTER.removeOne(customerId, state);
}),
on(CustomerStateActions.DELETE_CUSTOMER_FAIL_ACTION, (state, { err }) => ({
...state,
error: err,
})),
);
export function reducer(state: CustomerState, action: Action) {
return customerReducer(state, action);
}
|
583138d1d13538c9a18b96f47d29304460aecbd4
|
[
"TypeScript"
] | 9 |
TypeScript
|
PavelAsadchy/NgRx-app
|
68efd69f117d838546c9e1101fa95e9e92470969
|
01f89234d0c80408df9c09bc8349da40800c03b6
|
refs/heads/master
|
<repo_name>praveenbanoth/space<file_sep>/src/App.js
import React, { useEffect, useState } from "react";
import "./App.css";
import Launches from "./Launches";
import { BASE_URL } from "./constants";
function getLaunchColor(launch, state) {
return launch === state ? "text-blue-500" : "";
}
function getCallApi(launch, status) {
let callApi;
switch (launch) {
case "all":
callApi = `${BASE_URL}/launches`;
break;
case "upcoming":
callApi = `${BASE_URL}/launches/upcoming`;
break;
case "past":
callApi = `${BASE_URL}/launches/past`;
break;
default:
callApi = `${BASE_URL}/launches`;
}
if (status === "all") return callApi;
return `${callApi}?launch_success=${status === "successful"}`;
}
function App() {
const [launch, setLaunch] = useState("all");
const [launchStatus, setLaunchStatus] = useState("successful");
useEffect(() => {
const addMouseClass = function () {
document.body.classList.add("using-mouse");
};
document.body.addEventListener("mousedown", addMouseClass);
// Re-enable focus styling when Tab is pressed
const removeMouseClass = function (event) {
if (event.keyCode === 9) {
document.body.classList.remove("using-mouse");
}
};
document.body.addEventListener("keydown", removeMouseClass);
return () => {
document.body.removeEventListener("mousedown", addMouseClass);
document.body.removeEventListener("keydown", removeMouseClass);
};
}, []);
return (
<>
<header className="fixed text-gray-500 body-font h-screen">
<div className="container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center">
<button
type="button"
className="flex title-font font-medium items-center text-white mb-4 md:mb-0"
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
className="w-10 h-10 text-white p-2 bg-blue-500 rounded-full"
viewBox="0 0 24 24"
>
<path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />
</svg>
<span className="ml-3 text-xl">SpaceX Launches</span>
</button>
<nav className="md:mr-auto md:ml-4 md:py-1 md:pl-4 md:border-l md:border-gray-700 flex flex-wrap items-center text-base justify-center">
<button
type="button"
className={`mr-5 hover:text-white cursor-pointer ${getLaunchColor(
launch,
"all"
)}`}
onClick={() => setLaunch("all")}
>
All Launches
</button>
<button
type="button"
className={`mr-5 hover:text-white cursor-pointer ${getLaunchColor(
launch,
"upcoming"
)}`}
onClick={() => setLaunch("upcoming")}
>
Upcoming Launches
</button>
<button
type="button"
className={`mr-5 hover:text-white cursor-pointer ${getLaunchColor(
launch,
"past"
)}`}
onClick={() => setLaunch("past")}
>
Past Launches
</button>
</nav>
<div className="flex ml-6 items-center">
<span className="mr-3">Launch Status</span>
<div className="relative">
<select
value={launchStatus}
className="rounded border border-gray-700 bg-gray-800 appearance-none py-2 focus:outline-none focus:border-blue-500 text-white pl-3 pr-10"
onChange={(e) =>
setLaunchStatus(e.target.value)
}
>
<option value="all">All</option>
<option value="successful">Successful</option>
<option value="unsuccessful">
Unsuccessful
</option>
</select>
<span className="absolute right-0 top-0 h-full w-10 text-center text-gray-600 pointer-events-none flex items-center justify-center">
{/* <svg
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
className="w-4 h-4"
viewBox="0 0 24 24"
>
<path d="M6 9l6 6 6-6" />
</svg> */}
</span>
</div>
</div>
</div>
</header>
<Launches callApi={getCallApi(launch, launchStatus)} />
</>
);
}
export default App;
|
a4e9f46b3d725cb04634fdfc8703a8846c1aeb05
|
[
"JavaScript"
] | 1 |
JavaScript
|
praveenbanoth/space
|
a096256eedca541071b00396232ef9e56811c036
|
540cdc6029665f25ef3031217fbbb7b0ed4bccf2
|
refs/heads/main
|
<repo_name>Hoikmaster/p25newnew<file_sep>/sketch.js
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
var ground,box1, box2, box3,paper;
var myEngine,myWorld;
var trashimg,trashcan;
function preload()
{
trashimg = loadImage("trashcan.png")
}
function setup() {
createCanvas(1000,400);
myEngine = Engine.create();
myWorld = myEngine.world;
//Create the Bodies Here.
ground = new Ground(600,height,1200,20);
box1 = new Box(800,390,100,10);
box2 = new Box(750,380,10,40);
box3 = new Box(850,380,10,200);
paper = new Paper(200,300,70);
trashcan=createSprite(800,316,10,10)
trashcan.scale=0.5
trashcan.addImage("trash",trashimg)
Engine.run(myEngine);
}
function draw() {
rectMode(CENTER);
background("white");
Engine.update(myEngine);
paper.display();
box1.display();
box2.display();
box3.display();
ground.display();
trashcan.display();
}
function keyPressed(){
if (keyCode === UP_ARROW){
Matter.Body.applyForce(paper.body,paper.body.position,{x:190,y:-140})
}
}
|
48495a58ff2127a5f16b68138088d5acf18a92a3
|
[
"JavaScript"
] | 1 |
JavaScript
|
Hoikmaster/p25newnew
|
c69bcf9dbcb862f0c1b2b83e14df70d199fb6698
|
f964326cc35ebeb52f50fc769b37cea8ca5879ca
|
refs/heads/master
|
<repo_name>karenparente/guessing-game<file_sep>/guessinggame.sh
n_files=$(ls ~/Documents/Guess | wc -l)
echo "How many files do you think there are in here?"
function user_guess {
read guess
while [[ $guess -ne $n_files ]]
do
if [[ $guess -lt $n_files ]]
then
echo "You guessed too low"
else
echo "You guessed too high"
fi
echo "Try again"
read guess
done
}
user_guess
echo "You guessed right!"
<file_sep>/README.md
# Karen's Guessing Game
Date and time it was run:
Tue Jun 9 12:47:36 -03 2020
Number of lines in the script:
24
<file_sep>/makefile
all: readme
readme:
touch README.md
echo "# Karen's Guessing Game" >> README.md
echo " " >> README.md
(echo "Date and time it was run:" && date) >> README.md
echo " " >> README.md
(echo "Number of lines in the script:" && (cat guessinggame.sh | wc -l)) >> README.md
|
c54c1c54fe4aad42afffdcf826407f49f5be8db8
|
[
"Markdown",
"Makefile",
"Shell"
] | 3 |
Shell
|
karenparente/guessing-game
|
613e26f655af1edbdb3ce62350a6031f8a72b337
|
fe79a925c77d5fe8a3791e7af8246c04d3e313e3
|
refs/heads/master
|
<file_sep><?php
// use Newsletter;
Route::get('/test', function () {
return App\Tag::find(4)->posts;
});
Route::view('/', 'welcome');
Route::get('/result', function() {
return view('result')->with('posts', \App\Post::where('title', 'like', '%' . request('query') . '%')->get())
->with('tags', \App\Tag::all())
->with('title', request('query'))
->with('categories', \App\Category::all());
});
Route::post('/subscribe', function() {
$email = request('email');
Newsletter::subscribe($email);
return back();
});
Route::get('/', 'FrontEndController@index')->name('welcome');
Route::get('posts/{post}', 'FrontEndController@show')->name('show.post');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::resource('/post', 'PostsController');
// Route::get('/post', 'PostsController@')
Route::delete('post/{post}/delete', 'PostsController@destroy')->name('post.delete');
Route::resource('category', 'CategoriesController');
Route::delete('category/{category}/delete', 'CategoriesController@destroy')->name('category.delete');
Route::get('category2/{category}', 'FrontEndController@showCategory');
Route::resource('tag', 'TagsController');
Route::delete('tag/{tag}/delete', 'TagsController@destroy')->name('tag.delete');
Route::resource('user', 'UsersController');
Route::delete('user/{user}/delete', 'UsersController@destroy')->name('user.delete');
Route::get('user/admin/{user}', 'AdminsController@update')->middleware('admin');
Route::get('user/unadmin/{user}', 'AdminsController@destroy')->middleware('admin');
Route::get('profile', 'ProfilesController@edit');
Route::patch('profile/{user}', 'ProfilesController@update');<file_sep><?php
use App\User;
use App\Profile;
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$user = User::create([
'name' => 'JohnDoe',
'email' => '<EMAIL>',
'password' => <PASSWORD>('<PASSWORD>'),
'admin' => 1,
]);
Profile::create([
'user_id' => $user->id,
'avatar' => 'uploads/avatars/default.png',
'about' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla quasi, nemo molestiae, velit voluptatem vel sed, commodi amet laudantium esse et? Labore perspiciatis, quaerat voluptatem repellendus libero sunt eius provident.',
'facebook' => 'facebook.com',
'youtube' => 'youtube.com',
]);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Tag;
use App\Post;
use App\Category;
use Illuminate\Http\Request;
class FrontEndController extends Controller
{
public function index()
{
return view('welcome')->with('categories', Category::take(5)->get())
->with('first_post', Post::latest()->first())
->with('second_post', Post::latest()->skip(1)->take(1)->get()->first())
->with('third_post', Post::latest()->skip(2)->take(1)->get()->first())
->with('career', Category::find(6))
->with('tutorial', Category::find(5));
}
public function show(Post $post)
{
$next_id = Post::where('id', '>', $post->id)->min('id');
$prev_id= Post::where('id', '<', $post->id)->max('id');
return view('single')->with('post', $post)
->with('categories', Category::take(5)->get())
->with('tags', Tag::take(5)->get())
->with('next', Post::find($next_id))
->with('prev', Post::find($prev_id));
}
public function showCategory(Category $category)
{
return view('category')->with('category', $category)
->with('categories', Category::take(5)->get())
->with('posts', Post::where('category_id', $category->id)->get())
->with('tags', Tag::take(5)->get());
}
}
<file_sep>console.log('hello hter');
@if ( Session::has('success'))
toastr.success(" Session::get('success') ")
@endif
<file_sep><?php
namespace App\Http\Controllers;
use App\Post; use App\Category;
use App\Tag;
use Illuminate\Http\Request; use App\Http\Requests\PostValidation; use Illuminate\Support\Facades\Session;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.posts.index')->with('posts', Post::all());
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$categories = Category::all();
$tags = Tag::all();
if(count($categories) == 0 || count($tags) == 0) {
Session::flash('info', "You must have at least one category created!");
return back();
}
return view('admin.posts.create', compact('categories', 'tags'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(PostValidation $request)
{
$image = $request->image_post;
$image_new = time() . '_'. $image->getClientOriginalName();
$image->move('uploads/posts', $image_new);
$post = Post::forceCreate([
'category_id' => $request['category_id'],
'title' => $request['title'],
'body' => $request['body'],
'image_post' => 'uploads/posts/' . $image_new,
'slug' => str_slug($request->title),
'user_id' => auth()->id()
]);
$post->tags()->attach($request->tags);
Session::flash('success', 'Post Created successfully!');
return redirect('/post');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
return view('admin.posts.edit', compact('post'))
->with('categories', Category::all())
->with('tags', Tag::all());
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'body' => 'required',
'category_id' => 'required',
'tags' => 'required'
]);
if($request->image_post) {
$image = $request->image_post;
$image_new = time() . '_'. $image->getClientOriginalName();
$image->move('uploads/posts', $image_new);
$post->image_post = 'uploads/posts/' . $image_new;
}
$post->title = $request->title;
$post->body = $request->body;
$post->category_id = $request->category_id;
$post->tags()->sync($request->tags);
$post->save();
Session::flash('success', 'Post Updated successfully!');
return redirect('/post');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
$post->delete();
Session::flash('success', 'The Post was just trashed!');
return redirect('/post');
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostValidation extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required',
'body' => 'required',
'image_post' => 'required|image',
'category_id' => 'required',
'tags' => 'required'
];
}
public function messages()
{
return [
'title.required' => 'The (Title) field is required!',
'body.required' => 'The (Body) field is required!',
'image_post.required' => 'The (Image) field is required!',
'image_post.image' => 'The (Image) field must be an image!',
'category_id.required' => 'The (Category) field is required',
'tags.required' => 'The (Tags) field is required!'
];
}
}
<file_sep><?php
namespace App;
use App\Tag;
use App\User;
use App\Category;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $guarded = [];
protected $with = ['category', 'creator'];
protected $dates = ['deleted_at'];
public function getImagePostAttribute($image_post)
{
return asset($image_post);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
public function creator()
{
return $this->belongsTo('App\User' ,'user_id');
}
public function getRouteKeyName()
{
return 'slug';
}
}
|
8a59b490e91b2df03156a112289775d0786099f1
|
[
"JavaScript",
"PHP"
] | 7 |
PHP
|
MosaabMuhammed/Laravel-s-Blog
|
9601a92df38271757b2f755b9db8b098d7b15fbf
|
907dc7c780cb67273606abb26e9dfa4ce12f1a22
|
refs/heads/master
|
<repo_name>pinkfluid/crt<file_sep>/crt2.c
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <ev.h>
typedef struct crt crt_t;
#define CRT_STACK_DEPTH 32
#define CRT_OK 0 /* Status OK */
#define CRT_ERROR (CRT_OK - 1) /* General ERROR */
#define CRT_ERROR_CANCEL (CRT_OK - 2) /* Cancelled */
#define CRT_ERROR_STACK_OVERFLOW (CRT_OK - 3) /* Stack too small */
#define CRT_ERROR_INVALID_DEPTH (CRT_OK - 4) /* Used "return" from inside CRT context */
#define CRT_ERROR_RUNTIME (CRT_OK - 5) /* Invalid line */
struct crt
{
int crt_depth; /* Current stack depth */
int crt_stack[CRT_STACK_DEPTH]; /* CRT stack */
void *crt_data; /* Random data */
};
#define CRT_INIT(C) \
do \
{ \
memset(C, 0, sizeof(crt_t)); \
(C)->crt_depth = 0 - 1; \
} \
while (0)
#define CRT(C) \
{ \
crt_t *__crt = (C); \
int __crt_depth = ++__crt->crt_depth; \
int __crt_line = __crt->crt_stack[__crt_depth]; \
\
/* XXX Handle stack overflow here */ \
\
switch (__crt_line) \
{ \
default: \
if (__crt_line > 0) \
{ \
/* Jump to invalid line -- hard error */ \
CRT_EXIT(CRT_ERROR_RUNTIME); \
} \
\
case CRT_OK:;
#define CRT_END \
/* Co-routine terminated successfully */ \
CRT_EXIT(CRT_OK); \
break; \
case CRT_ERROR_CANCEL: \
goto __crt_exit; \
} \
__crt_exit: \
\
if (__crt->crt_depth != __crt_depth) \
{ \
assert(!"RETURN FROM CRT"); \
} \
__crt->crt_depth--; \
}
#define CRT_SET_STATUS(C, code) ((C)->crt_stack[__crt_depth+1] = (code))
#define CRT_STATUS(C) ((C)->crt_stack[(C)->crt_depth + 1])
#define CRT_RUNNING(C) (CRT_STATUS(C) > 0)
#define CRT_CANCELLED(C) (CRT_STATUS(C) == CRT_ERROR_CANCEL)
#define CRT_YIELD(...) \
do \
{ \
__crt->crt_stack[__crt->crt_depth--] = __LINE__; \
return __VA_ARGS__; \
case __LINE__:; \
} \
while (0)
#define CRT_EXPAND(...) __VA_ARGS__
#define CRT_AWAIT_NC(expr, ...) \
do \
{ \
CRT_SET_STATUS(__crt, CRT_OK); \
CRT_SET(); \
\
{ \
expr; \
} \
\
if (CRT_RUNNING(__crt)) \
{ \
CRT_RETURN(__VA_ARGS__); \
} \
} \
while (0)
#define CRT_AWAIT(expr, ...) \
do \
{ \
CRT_AWAIT_NC(expr, __VA_ARGS__); \
/* Propagate cancellations */ \
if (CRT_CANCELLED(__crt)) CRT_EXIT(CRT_ERROR_CANCEL); \
} \
while (0)
#define CRT_EXIT(code) \
do \
{ \
__crt->crt_stack[__crt->crt_depth] = (code); \
goto __crt_exit; \
} \
while (0)
#define CRT_CANCEL(C) \
do \
{ \
int __crti; \
\
/* Find end of stack */ \
for (__crti = 0; __crti < CRT_STACK_DEPTH; __crti++) \
{ \
if ((C)->crt_stack[__crti] == 0) break; \
} \
\
if (__crti > 0) __crti--; \
\
(C)->crt_stack[__crti] = CRT_ERROR_CANCEL; \
} \
while (0)
/**
* Rarely used
*/
#define CRT_SET() \
do \
{ \
case __LINE__:; \
__crt->crt_stack[__crt->crt_depth] = __LINE__; \
} \
while (0)
#define CRT_RETURN(...) \
do \
{ \
__crt->crt_depth--; \
return __VA_ARGS__; \
} \
while (0)
typedef int async_main_t(crt_t *crt, void *arg);
typedef struct async_task async_task_t;
struct async_task
{
crt_t at_crt; /* Main co-routine object */
async_main_t *at_main; /* Async task body function */
void *at_main_data; /* Task body function context */
bool at_done; /* True if task completed */
int at_returncode; /* Exit status */
ev_timer at_timer; /* Generic sleep/timeout watcher */
void *at_what_scheduled; /* What scheduled this task */
};
static void async_task_run(async_task_t *self);
void async_task_start(async_task_t *self, async_main_t *task_main, void *data)
{
memset(self, 0, sizeof(*self));
self->at_main = task_main;
self->at_main_data = data;
CRT_INIT(&self->at_crt);
async_task_run(self);
}
void async_task_run(async_task_t *self)
{
if (!self->at_done)
{
/* Run coroutine */
self->at_returncode = self->at_main(&self->at_crt, self->at_main_data);
self->at_done = !CRT_RUNNING(&self->at_crt);
}
}
void async_task_cancel(async_task_t *self)
{
CRT_CANCEL(&self->at_crt);
async_task_run(self);
}
void async_task_ev_generic_fn(struct ev_loop *loop, ev_watcher *watcher, int revents)
{
(void)revents;
(void)loop;
async_task_t *self = watcher->data;
self->at_what_scheduled = watcher;
async_task_run(self);
}
/**
* Sleep for @p timeout seconds
*/
void async_task_sleep(crt_t *crt, double timeout)
{
async_task_t *self = (async_task_t *)crt;
CRT(crt)
{
self->at_timer.data = self;
ev_timer_init(&self->at_timer, (void *)async_task_ev_generic_fn, timeout, 0.0);
ev_timer_start(EV_DEFAULT, &self->at_timer);
do
{
CRT_YIELD();
}
while (self->at_what_scheduled != &self->at_timer);
}
CRT_END;
ev_timer_stop(EV_DEFAULT, &self->at_timer);
}
async_task_t t1;
async_task_t t2;
int task_t(crt_t *crt, void *data)
{
(void)data;
static int ii = 0;
CRT(crt)
{
for (ii = 0; ii < 3; ii++)
{
printf("T1 = %d\n", ii);
CRT_AWAIT(async_task_sleep(crt, 1.0), -1);
}
}
CRT_END;
printf("t1 ENDED = %d\n", CRT_STATUS(crt));
printf("t1 will cancel t2 now\n");
async_task_cancel(&t2);
return 1;
}
int task_t2(crt_t *crt, void *data)
{
(void)data;
static int ii = 0;
CRT(crt)
{
for (ii = 0; ii < 10; ii++)
{
printf("T2 = %d\n", ii);
CRT_AWAIT(async_task_sleep(crt, 1.0), -1);
}
}
CRT_END;
if (CRT_CANCELLED(crt))
{
printf("t2 was cancelled\n");
}
else
{
printf("t2 ENDED: %d\n", CRT_STATUS(crt));
}
return 2;
}
int main(void)
{
async_task_start(&t1, task_t, NULL);
async_task_start(&t2, task_t2, NULL);
ev_run(EV_DEFAULT, 0);
printf("MAIN EXIT: t1 = %d, t2 = %d\n", t1.at_returncode, t2.at_returncode);
return 0;
}
<file_sep>/async.c
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <ev.h>
#include "crt.h"
typedef int async_main_t(crt_t *crt, void *arg);
typedef struct async_task async_task_t;
struct async_task
{
crt_t at_crt; /* Main co-routine object */
async_main_t *at_main; /* Async task body function */
void *at_main_data; /* Task body function context */
bool at_done; /* True if task completed */
int at_returncode; /* Exit status */
ev_timer at_timer; /* Generic sleep/timeout watcher */
void *at_what_scheduled; /* What scheduled this task */
};
static void async_task_run(async_task_t *self);
void async_task_start(async_task_t *self, async_main_t *task_main, void *data)
{
memset(self, 0, sizeof(*self));
self->at_main = task_main;
self->at_main_data = data;
CRT_INIT(&self->at_crt);
async_task_run(self);
}
void async_task_run(async_task_t *self)
{
if (!self->at_done)
{
/* Run coroutine */
self->at_returncode = self->at_main(&self->at_crt, self->at_main_data);
self->at_done = !CRT_RUNNING(&self->at_crt);
}
}
void async_task_cancel(async_task_t *self)
{
CRT_CANCEL(&self->at_crt);
async_task_run(self);
}
void async_task_ev_generic_fn(struct ev_loop *loop, ev_watcher *watcher, int revents)
{
(void)revents;
(void)loop;
async_task_t *self = watcher->data;
self->at_what_scheduled = watcher;
async_task_run(self);
}
/**
* Sleep for @p timeout seconds
*/
void async_task_sleep(crt_t *crt, double timeout)
{
async_task_t *self = (async_task_t *)crt;
CRT(crt)
{
self->at_timer.data = self;
ev_timer_init(&self->at_timer, (void *)async_task_ev_generic_fn, timeout, 0.0);
ev_timer_start(EV_DEFAULT, &self->at_timer);
do
{
CRT_YIELD();
}
while (self->at_what_scheduled != &self->at_timer);
}
CRT_END;
ev_timer_stop(EV_DEFAULT, &self->at_timer);
}
async_task_t t1;
async_task_t t2;
int task_t(crt_t *crt, void *data)
{
(void)data;
static int ii = 0;
CRT(crt)
{
for (ii = 0; ii < 3; ii++)
{
printf("T1 = %d\n", ii);
CRT_AWAIT(async_task_sleep(crt, 1.0), -1);
}
}
CRT_END;
printf("t1 ENDED = %d\n", CRT_STATUS(crt));
printf("t1 will cancel t2 now\n");
async_task_cancel(&t2);
return 1;
}
int task_t2(crt_t *crt, void *data)
{
(void)data;
static int ii = 0;
CRT(crt)
{
for (ii = 0; ii < 10; ii++)
{
printf("T2 = %d\n", ii);
CRT_AWAIT(async_task_sleep(crt, 1.0), -1);
}
}
CRT_END;
if (CRT_CANCELLED(crt))
{
printf("t2 was cancelled\n");
}
else
{
printf("t2 ENDED: %d\n", CRT_STATUS(crt));
}
return 2;
}
int main(void)
{
async_task_start(&t1, task_t, NULL);
async_task_start(&t2, task_t2, NULL);
ev_run(EV_DEFAULT, 0);
printf("MAIN EXIT: t1 = %d, t2 = %d\n", t1.at_returncode, t2.at_returncode);
return 0;
}
<file_sep>/generator.c
#include <stdio.h>
#include "crt.h"
/*
* Example of a generator using co-routines
*/
int primes(crt_t *crt)
{
/* Return list of prime numbers */
CRT(crt)
{
CRT_YIELD(2);
CRT_YIELD(3);
CRT_YIELD(5);
CRT_YIELD(7);
CRT_YIELD(11);
CRT_YIELD(13);
}
CRT_END;
return 0;
}
int main(void)
{
crt_t c;
int n;
CRT_INIT(&c);
/* Print all numbers yielded by primes() */
while ((n = primes(&c)) > 0)
{
printf("Number = %d\n", n);
}
}
|
cd42040296622704eaaece239ada88d426880aee
|
[
"C"
] | 3 |
C
|
pinkfluid/crt
|
f45208adb2d82bae641d2a8192fa2d25603773ca
|
3fbc360a9f5a8391541cabcd4fdfc9db2482b329
|
refs/heads/master
|
<file_sep>using UnityEngine;
using System.Collections;
public class NavigatePosition : MonoBehaviour
{
[SerializeField]
private NavMeshAgent agent;
// Use this for initialization
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
public void NavigateTo(Vector3 position)
{
agent.SetDestination(position);
}
void Update()
{
GetComponent<Animator>().SetFloat("Distance", agent.remainingDistance);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class NetworkMove : MonoBehaviour
{
#region Injected Components
[SerializeField]
private GameObject networkManager;
#endregion
private Network network;
// Use this for initialization
void Start()
{
network = networkManager.GetComponent<Network>();
}
public void OnMove(Vector3 position)
{
Debug.Log("Sending position to node." + position);
network.RequestMove();
}
}
<file_sep>using UnityEngine;
using System.Collections;
using SocketIO;
public class Network : MonoBehaviour
{
#region public properties
[SerializeField]
private GameObject playerPrefab;
#endregion
private static SocketIOComponent socket;
// Use this for initialization
void Start ()
{
Debug.Log("Client started");
socket = GetComponent<SocketIOComponent>();
socket.On("open", OnConnected);
socket.On("spawn", OnSpawn);
}
public void RequestMove()
{
socket.Emit("move");
}
private void OnSpawn(SocketIOEvent ev)
{
Debug.Log("Spawned.");
Instantiate(playerPrefab);
}
private void OnConnected(SocketIOEvent ev)
{
Debug.Log("connected");
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class ClickMove : MonoBehaviour
{
#region injectable properties
[SerializeField]
private GameObject player;
#endregion
// Update is called once per frame
public void OnClick (Vector3 position)
{
var navPosition = player.GetComponent<NavigatePosition>();
var netMove = player.GetComponent<NetworkMove>();
navPosition.NavigateTo(position);
netMove.OnMove(position);
}
}
<file_sep># unity-node-mmo<file_sep>/// <reference path="./typings/tsd.d.ts" />
import * as io from 'socket.io';
const server: SocketIO.Server = io(process.env.PORT || 3000);
console.log('server started');
const connectionListener = (socket: SocketIO.Socket) => {
let playerCount = 0;
const moveListener = (position) => {
console.log('move event received', JSON.stringify(position));
socket.broadcast.emit('move', position);
};
const disconnectListener = () => {
console.log('client disconnected');
playerCount--;
};
console.log('client connected, broadcasting spawn');
socket.broadcast.emit('spawn');
playerCount++;
for(var i=0; i < playerCount; i++) {
socket.emit('spawn');
console.log('sending spawn to new player');
}
socket.on('move', moveListener);
socket.on('disconnect', disconnectListener);
};
server.on('connection', connectionListener);
|
3088e69a99131fcfe8be191614743834e16ed93f
|
[
"Markdown",
"C#",
"TypeScript"
] | 6 |
C#
|
martin-fabbri/unity-node-mmo
|
09bfd0e0eabb5de3e63df4b00172614c8d6291ee
|
d8a59ad85cbc9e27f0f2c62b76d8db4272886bb9
|
refs/heads/master
|
<repo_name>getziadz/CVP<file_sep>/README.md
# CVP Infrastructure
## Examples & Tracks
See Simulator options:
`./cvp`
Running the simulator on `trace.gz`:
`./cvp trace.gz`
Running with value prediction (`-v`) and predict all instructions (first track, `-t 0`):
`./cvp -v -t 0 trace.gz`
Running with value prediction (`-v`) and predict only loads (second track, `-t 1`):
`./cvp -v -t 1 trace.gz`
Running with value prediction (`-v`) and predict only loads but with hit/miss information (third track, `-t 2`):
`./cvp -v -t 2 trace.gz`
Baseline (no arguments) is equivalent to (prefetcher (`-P`), 512-window (`-w 512`), 8 LDST (`-M 8`), 16 ALU (`-A 16`), 16-wide fetch (`16`) with 16 branches max per cycle (`16`), stop fetch at cond taken (`1`), stop fetch at indirect (`1`), model ICache (`1`)):
`./cvp -P -w 512 -M 8 -A 16 -F 16,16,1,1,1`
## Notes
Run `make clean && make` to ensure your changes are taken into account.
## Value Predictor Interface
See [cvp.h](./cvp.h) header.
## Getting Traces
135 30M Traces @ [TAMU ](http://hpca23.cse.tamu.edu/CVP-1/public_traces/)
2013 100M Traces @ [TAMU ](http://hpca23.cse.tamu.edu/CVP-1/secret_traces/)
## Sample Output
```
VP_ENABLE = 1
VP_PERFECT = 0
VP_TRACK = LoadsOnly
WINDOW_SIZE = 512
FETCH_WIDTH = 16
FETCH_NUM_BRANCH = 16
FETCH_STOP_AT_INDIRECT = 1
FETCH_STOP_AT_TAKEN = 1
FETCH_MODEL_ICACHE = 1
PERFECT_BRANCH_PRED = 0
PERFECT_INDIRECT_PRED = 0
PIPELINE_FILL_LATENCY = 5
NUM_LDST_LANES = 8
NUM_ALU_LANES = 16
MEMORY HIERARCHY CONFIGURATION---------------------
STRIDE Prefetcher = 1
PERFECT_CACHE = 0
WRITE_ALLOCATE = 1
Within-pipeline factors:
AGEN latency = 1 cycle
Store Queue (SQ): SQ size = window size, oracle memory disambiguation, store-load forwarding = 1 cycle after store's or load's agen.
* Note: A store searches the L1$ at commit. The store is released
* from the SQ and window, whether it hits or misses. Store misses
* are buffered until the block is allocated and the store is
* performed in the L1$. While buffered, conflicting loads get
* the store's data as they would from the SQ.
I$: 64 KB, 4-way set-assoc., 64B block size
L1$: 64 KB, 8-way set-assoc., 64B block size, 3-cycle search latency
L2$: 1 MB, 8-way set-assoc., 64B block size, 12-cycle search latency
L3$: 8 MB, 16-way set-assoc., 128B block size, 60-cycle search latency
Main Memory: 150-cycle fixed search time
STORE QUEUE MEASUREMENTS---------------------------
Number of loads: 8278928
Number of loads that miss in SQ: 7456870 (90.07%)
Number of PFs issued to the memory system 639484
MEMORY HIERARCHY MEASUREMENTS----------------------
I$:
accesses = 31414867
misses = 683314
miss ratio = 2.18%
pf accesses = 0
pf misses = 0
pf miss ratio = -nan%
L1$:
accesses = 11380235
misses = 352104
miss ratio = 3.09%
pf accesses = 639484
pf misses = 10547
pf miss ratio = 1.65%
L2$:
accesses = 1035418
misses = 217593
miss ratio = 21.01%
pf accesses = 10547
pf misses = 5096
pf miss ratio = 48.32%
L3$:
accesses = 217593
misses = 28693
miss ratio = 13.19%
pf accesses = 5096
pf misses = 1576
pf miss ratio = 30.93%
BRANCH PREDICTION MEASUREMENTS---------------------
Type n m mr mpki
All 31414867 28863 0.09% 0.92
Branch 4202035 22366 0.53% 0.71
Jump: Direct 664629 0 0.00% 0.00
Jump: Indirect 706742 6497 0.92% 0.21
Jump: Return 0 0 -nan% 0.00
Not control 25841461 0 0.00% 0.00
ILP LIMIT STUDY------------------------------------
instructions = 31414867
cycles = 21670415
IPC = 1.450
Prefetcher------------------------------------------
Num Trainings :8278928
Num Prefetches generated :640803
Num Prefetches issued :1352783
Num Prefetches filtered by PF queue :49713
Num untimely prefetches dropped from PF queue :1319
Num prefetches not issued LDST contention :713299
Num prefetches not issued stride 0 :2719377
CVP STUDY------------------------------------------
prediction-eligible instructions = 19841790
correct predictions = 885532 (4.46%)
incorrect predictions = 21692 (0.11%)
Read 30002325 instrs
```
<file_sep>/lib/ittage.h
/*Copyright (c) <2018>, INRIA : Institut National de Recherche en Informatique
et en Automatique (French National Research Institute for Computer Science and
Applied Mathematics) All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/
#include <assert.h>
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#ifndef _ITTAGE_H
#define _ITTAGE_H
// Fast implementation of the ITTAGE predictor: probably not optimal, but not
// that far
class ientry // ITTAGE global table entry
{
public:
uint64_t target;
int8_t ctr;
uint tag;
int8_t u;
ientry() {
target = 0xdeadbeef;
ctr = 0;
u = 0;
tag = 0;
}
};
class IPREDICTOR {
public:
#define NHIST 8
#define MINHIST 2
#define MAXHIST 300
#define LOGG 10 /* logsize of the banks in the tagged ITTAGE tables */
#define TBITS 11 // tag width
#define NNN \
1 // number of extra entries allocated on an ITTAGE misprediction (1+NNN)
#define PHISTWIDTH 27 // width of the path history used in ITTAGE
#define UWIDTH 2 // u counter width on ITTAGE
#define CWIDTH 3 // predictor counter width on the ITTAGE tagged tables
// the counter to chose between longest match and alternate prediction on
// ITTAGE when weak confidence counters
int8_t use_alt_on_na;
long long GHIST;
int TICK; // for the reset of the u counter
uint8_t ghist[HISTBUFFERLENGTH];
int ptghist;
long long phist; // path history
folded_history ch_i[NHIST + 1]; // utility for computing ITTAGE indices
folded_history ch_t[2][NHIST + 1]; // utility for computing ITTAGE tags
ientry *itable[NHIST + 1];
int m[NHIST + 1];
int TB[NHIST + 1];
int logg[NHIST + 1];
int GI[NHIST + 1]; // indexes to the different tables are computed only once
uint GTAG[NHIST + 1]; // tags for the different tables are computed only once
uint64_t pred_target; // prediction
uint64_t alt_target; // alternate TAGEprediction
uint64_t tage_target; // TAGE prediction
uint64_t LongestMatchPred;
int HitBank; // longest matching bank
int AltBank; // alternate matching bank
int Seed; // for the pseudo-random number generator
uint64_t target_inter;
IPREDICTOR(void) { reinit(); }
void reinit() {
m[0] = 0;
m[1] = MINHIST;
m[NHIST] = MAXHIST;
for (int i = 2; i <= NHIST; i++) {
m[i] = (int)(((double)MINHIST * pow((double)(MAXHIST) / (double)MINHIST,
(double)(i) / (double)NHIST)) +
0.5);
}
for (int i = 0; i <= NHIST; i++) {
TB[i] = TBITS;
logg[i] = LOGG;
}
for (int i = 0; i <= NHIST; i++)
itable[i] = new ientry[(1 << LOGG)];
for (int i = 0; i <= NHIST; i++) {
ch_i[i].init(m[i], (logg[i]));
ch_t[0][i].init(ch_i[i].OLENGTH, TB[i]);
ch_t[1][i].init(ch_i[i].OLENGTH, TB[i] - 1);
}
Seed = 0;
TICK = 0;
phist = 0;
Seed = 0;
for (int i = 0; i < HISTBUFFERLENGTH; i++)
ghist[0] = 0;
ptghist = 0;
use_alt_on_na = 0;
GHIST = 0;
ptghist = 0;
phist = 0;
}
// F serves to mix path history: not very important impact
int F(long long A, int size, int bank) {
int A1, A2;
A = A & ((1 << size) - 1);
A1 = (A & ((1 << logg[bank]) - 1));
A2 = (A >> logg[bank]);
if (bank < logg[bank])
A2 = ((A2 << bank) & ((1 << logg[bank]) - 1)) +
(A2 >> (logg[bank] - bank));
A = A1 ^ A2;
if (bank < logg[bank])
A = ((A << bank) & ((1 << logg[bank]) - 1)) + (A >> (logg[bank] - bank));
return (A);
}
// gindex computes a full hash of PC, ghist and phist
int gindex(unsigned int PC, int bank, long long hist, folded_history *ch_i) {
int index;
int M = (m[bank] > PHISTWIDTH) ? PHISTWIDTH : m[bank];
index = PC ^ (PC >> (abs(logg[bank] - bank) + 1)) ^ ch_i[bank].comp ^
F(hist, M, bank);
return (index & ((1 << (logg[bank])) - 1));
}
// tag computation
uint16_t gtag(unsigned int PC, int bank, folded_history *ch0,
folded_history *ch1) {
int tag = (PC) ^ ch0[bank].comp ^ (ch1[bank].comp << 1);
return (tag & ((1 << (TB[bank])) - 1));
}
// up-down saturating counter
void ctrupdate(int8_t &ctr, bool taken, int nbits) {
if (taken) {
if (ctr < ((1 << (nbits - 1)) - 1))
ctr++;
} else {
if (ctr > -(1 << (nbits - 1)))
ctr--;
}
}
// just a simple pseudo random number generator: use available information
// to allocate entries in the loop predictor
int MYRANDOM() {
Seed++;
Seed ^= phist;
Seed = (Seed >> 21) + (Seed << 11);
Seed ^= ptghist;
Seed = (Seed >> 10) + (Seed << 22);
return (Seed);
};
// ITTAGE PREDICTION: same code at fetch or retire time but the index and
// tags must recomputed
uint64_t GetPrediction(uint64_t PC) {
HitBank = -1;
AltBank = -1;
for (int i = 0; i <= NHIST; i++) {
GI[i] = gindex(PC, i, phist, ch_i);
GTAG[i] = gtag(PC, i, ch_t[0], ch_t[1]);
}
alt_target = 0;
tage_target = 0;
LongestMatchPred = 0;
int AltConf = -4;
int HitConf = -4;
// Look for the bank with longest matching history
for (int i = NHIST; i >= 0; i--) {
if (itable[i][GI[i]].tag == GTAG[i]) {
HitBank = i;
HitConf = itable[HitBank][GI[HitBank]].ctr;
LongestMatchPred = itable[HitBank][GI[HitBank]].target;
break;
}
}
// Look for the alternate bank
for (int i = HitBank - 1; i >= 0; i--) {
if (itable[i][GI[i]].tag == GTAG[i]) {
alt_target = itable[i][GI[i]].target;
AltBank = i;
AltConf = itable[AltBank][GI[AltBank]].ctr;
break;
}
}
// computes the prediction and the alternate prediction
if (HitBank > 0) {
bool Huse_alt_on_na = (use_alt_on_na >= 0);
if ((!Huse_alt_on_na) || (HitConf > 0) || (HitConf >= AltConf))
tage_target = LongestMatchPred;
else
tage_target = alt_target;
}
if (AltBank < 0)
tage_target = LongestMatchPred;
return (tage_target);
}
void HistoryUpdate(uint64_t PC, uint64_t target, long long &X, int &Y,
folded_history *H, folded_history *G, folded_history *J) {
int maxt = 3;
int T = (PC >> 2) ^ (PC >> 6);
int PATH = (target >> 2) ^ (target >> 6);
for (int t = 0; t < maxt; t++) {
bool DIR = (T & 1);
T >>= 1;
int PATHBIT = (PATH & 127);
PATH >>= 1;
// update history
Y--;
ghist[Y & (HISTBUFFERLENGTH - 1)] = DIR;
X = (X << 1) ^ PATHBIT;
for (int i = 1; i <= NHIST; i++) {
H[i].update(ghist, Y);
G[i].update(ghist, Y);
J[i].update(ghist, Y);
}
}
X = (X & ((1 << PHISTWIDTH) - 1));
// END UPDATE HISTORIES
}
void TrackOtherInst(uint64_t PC, uint64_t branchTarget) {
HistoryUpdate(PC, branchTarget, phist, ptghist, ch_i, ch_t[0], ch_t[1]);
}
// PREDICTOR UPDATE
void UpdatePredictor(uint64_t PC, uint64_t branchTarget) {
// TAGE UPDATE
bool ALLOC = ((tage_target != branchTarget) & (HitBank < NHIST));
// do not allocate too often if the overall prediction is correct
if (HitBank > 0)
if (AltBank >= 0) {
// Manage the selection between longest matching and alternate matching
// for "pseudo"-newly allocated longest matching entry
// this is extremely important for TAGE only, not that important when
// the overall predictor is implemented
bool PseudoNewAlloc = (itable[HitBank][GI[HitBank]].ctr <= 0);
// an entry is considered as newly allocated if its prediction counter
// is weak
if (PseudoNewAlloc) {
if (LongestMatchPred == branchTarget)
ALLOC = false;
// if it was delivering the correct prediction, no need to allocate a
// new entry
// even if the overall prediction was false
if (LongestMatchPred != alt_target)
if ((LongestMatchPred == branchTarget) ||
(alt_target == branchTarget)) {
ctrupdate(use_alt_on_na, (alt_target == branchTarget), ALTWIDTH);
}
}
}
if (ALLOC) {
int T = NNN;
int A = 1;
if ((MYRANDOM() & 127) < 32)
A = 2;
int Penalty = 0;
int NA = 0;
int DEP = HitBank + A;
for (int i = DEP; i <= NHIST; i++) {
if (itable[i][GI[i]].u == 0) {
itable[i][GI[i]].tag = GTAG[i];
itable[i][GI[i]].target = branchTarget;
itable[i][GI[i]].ctr = 0;
NA++;
if (T <= 0) {
break;
}
i += 1;
T -= 1;
}
else {
Penalty++;
}
}
TICK += (Penalty - 2 * NA);
// just the best formula for the Championship:
// In practice when one out of two entries are useful
if (TICK < 0)
TICK = 0;
if (TICK >= BORNTICK) {
for (int i = 0; i <= NHIST; i++)
for (int j = 0; j < (1 << LOGG); j++)
itable[i][j].u >>= 1;
TICK = 0;
}
}
// update predictions
if (HitBank >= 0) {
if (itable[HitBank][GI[HitBank]].ctr <= 0)
if (LongestMatchPred != branchTarget)
{
if (alt_target == branchTarget)
if (AltBank >= 0) {
ctrupdate(itable[AltBank][GI[AltBank]].ctr,
(alt_target == branchTarget), CWIDTH);
}
}
ctrupdate(itable[HitBank][GI[HitBank]].ctr,
(LongestMatchPred == branchTarget), CWIDTH);
if (LongestMatchPred != branchTarget)
if (itable[HitBank][GI[HitBank]].ctr < 0)
itable[HitBank][GI[HitBank]].target = branchTarget;
}
if (LongestMatchPred != alt_target)
if (LongestMatchPred == branchTarget) {
if (itable[HitBank][GI[HitBank]].u < (1 << UWIDTH) - 1)
itable[HitBank][GI[HitBank]].u++;
}
// END TAGE UPDATE
HistoryUpdate(PC, branchTarget, phist, ptghist, ch_i, ch_t[0], ch_t[1]);
// END PREDICTOR UPDATE
}
#undef NHIST
#undef MINHIST
#undef MAXHIST
#undef LOGG
#undef TBITS
#undef NNN
#undef PHISTWIDTH
#undef UWIDTH
#undef CWIDTH
};
#endif
<file_sep>/mypredictor.h
/*Copyright (c) <2018>, INRIA : Institut National de Recherche en Informatique et en Automatique (French National Research Institute for Computer Science and Applied Mathematics)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/
/* Same predictor for the 3 tracks, but with different parameters*/
#include <vector>
#include <deque>
#define PREDSTRIDE
#define PREDVTAGE
// 32KB //
#define K32
#ifdef K32
// 4.202 //3.729 for stride only //3.570 for VTAGE only
// 262018 bits
#define UWIDTH 2
#define LOGLDATA 9
#define LOGBANK 7
#define TAGWIDTH 11
#define NBBANK 49
#define NHIST 8
int HL[NHIST + 1] = { 0, 0, 3, 7, 15, 31, 63, 90, 127 };
#define LOGSTR 4
#define NBWAYSTR 3
#define TAGWIDTHSTR 14
#define LOGSTRIDE 20
#endif
//END 32 KB//
// 8KB //
//#define K8
#ifdef K8
// 8KB
// 4.026 //3.729 Stride only // 3.437 for TAGE only
// 65378 bits
#define UWIDTH 2
#define LOGLDATA 7
#define LOGBANK 5
#define TAGWIDTH 11
#define NBBANK 47
#define NHIST 7
int HL[NHIST + 1] = { 0, 0, 1, 3, 6, 12, 18, 30 };
#define LOGSTR 4
#define NBWAYSTR 3
#define TAGWIDTHSTR 14
#define LOGSTRIDE 20
#endif
//END 8KB //
//UNLIMITED//
//#define LIMITSTUDY
#ifdef LIMITSTUDY
// 4.408 //3.730 Stride only // 3.732 for TAGE only
#define UWIDTH 1
#define LOGLDATA 20
#define LOGBANK 20
#define TAGWIDTH 15
#define NBBANK 63
#define NHIST 14
int HL[NHIST + 1] =
{ 0, 0, 1, 3, 7, 15, 31, 47, 63, 95, 127, 191, 255, 383, 511 };
#define LOGSTR 20
#define TAGWIDTHSTR 15
#define LOGSTRIDE 30
#define NBWAYSTR 3
#endif
//END UNLIMITED //
#define WIDTHCONFID 3
#define MAXCONFID ((1<< WIDTHCONFID)-1)
#define WIDTHCONFIDSTR 5
#define MAXCONFIDSTR ((1<< WIDTHCONFIDSTR)-1)
#define MAXU ((1<< UWIDTH)-1)
#define BANKDATA (1<<LOGLDATA)
#define MINSTRIDE -(1<<(LOGSTRIDE-1))
#define MAXSTRIDE (-MINSTRIDE-1)
#define BANKSIZE (1<<LOGBANK)
#define PREDSIZE (NBBANK*BANKSIZE)
// Global path history
static uint64_t gpath[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
/* using up to 512 bits of path history was found to result in some performance benefit : essentially in the unlimited case. I did not explore longer histories */
static uint64_t gtargeth = 0;
/* history of the targets : limited to 64 bits*/
// The E-Stride predictor
//entry in the stride predictor
struct strdata
{
uint64_t LastValue; //64 bits
uint64_t Stride; // LOGSTRIDE bits
uint8_t conf; // WIDTHCONFIDSTR bits
uint16_t tag; //TAGWIDTHSTR bits
uint16_t NotFirstOcc; //1 bits
int u; // 2 bits
//67 + LOGSTRIDE + WIDTHCONFIDSTR + TAGWIDTHSTR bits
};
static strdata STR[NBWAYSTR * (1 << LOGSTR)];
static int SafeStride = 0; // 16 bits
/////////////////////////////////// For E-VTAGE
//the data values
struct longdata
{
uint64_t data;
uint8_t u;
};
static longdata LDATA[3 * BANKDATA];
// managed as a a skewed associative array
//each entry is 64-LOGLDATA bits for the data (since the other bits can be deduced from the index) + 2 bits for u
//VTAGE
struct vtentry
{
uint64_t hashpt; // hash of the value + number of way in the value array ; LOGLDATA + 2 bits
uint8_t conf; //WIDTHCONFID bits
uint16_t tag; // TAGWIDTH bits
uint8_t u; //2 bits
//LOGLDATA +4 +WIDTHCONFID +TAGWIDTH bits
};
static vtentry Vtage[PREDSIZE];
#define MAXTICK 1024
static int TICK; //10 bits // for managing replacement on the VTAGE entries
static int LastMispVT = 0; //8 bits //for tracking the last misprediction on VTAGE
//index function for VTAGE (use the global path history): just a complex hash function
uint32_t
gi (int i, uint64_t pc)
{
int hl = (HL[i] < 64) ? (HL[i] % 64) : 64;
uint64_t inter = (hl < 64) ? (((1 << hl) - 1) & gpath[0]) : gpath[0];
uint64_t res = 0;
inter ^= (pc >> (i)) ^ (pc);
for (int t = 0; t < 8; t++)
{
res ^= inter;
inter ^= ((inter & 15) << 16);
inter >>= (LOGBANK - ((NHIST - i + LOGBANK - 1) % (LOGBANK - 1)));
}
hl = (hl < (HL[NHIST] + 1) / 2) ? hl : ((HL[NHIST] + 1) / 2);
inter ^= (hl < 64) ? (((1 << hl) - 1) & gtargeth) : gtargeth;
for (int t = 0; t <= hl / LOGBANK; t++)
{
res ^= inter;
inter ^= ((inter & 15) << 16);
inter >>= LOGBANK;
}
if (HL[i] >= 64)
{
int REMAIN = HL[i] - 64;
hl = REMAIN;
int PT = 1;
while (REMAIN > 0)
{
inter ^= ((hl < 64) ? (((1 << hl) - 1) & gpath[PT]) : gpath[PT]);
for (int t = 0; t < 8; t++)
{
res ^= inter;
inter ^= ((inter & 15) << 16);
inter >>= (LOGBANK -
((NHIST - i + LOGBANK - 1) % (LOGBANK - 1)));
}
REMAIN = REMAIN - 64;
PT++;
}
}
return ((uint32_t) res & (BANKSIZE - 1));
}
//tags for VTAGE: just another complex hash function "orthogonal" to the index function
uint32_t
gtag (int i, uint64_t pc)
{
int hl = (HL[i] < 64) ? (HL[i] % 64) : 64;
uint64_t inter = (hl < 64) ? (((1 << hl) - 1) & gpath[0]) : gpath[0];
uint64_t res = 0;
inter ^= ((pc >> (i)) ^ (pc >> (5 + i)) ^ (pc));
for (int t = 0; t < 8; t++)
{
res ^= inter;
inter ^= ((inter & 31) << 14);
inter >>= (LOGBANK - ((NHIST - i + LOGBANK - 2) % (LOGBANK - 1)));
}
hl = (hl < (HL[NHIST] + 1) / 2) ? hl : ((HL[NHIST] + 1) / 2);
inter ^= ((hl < 64) ? (((1 << hl) - 1) & gtargeth) : gtargeth);
for (int t = 0; t <= hl / TAGWIDTH; t++)
{
res ^= inter;
inter ^= ((inter & 15) << 16);
inter >>= TAGWIDTH;
}
if (HL[i] >= 64)
{
int REMAIN = HL[i] - 64;
hl = REMAIN;
int PT = 1;
while (REMAIN > 0)
{
inter ^= ((hl < 64) ? (((1 << hl) - 1) & gpath[PT]) : gpath[PT]);
for (int t = 0; t < 8; t++)
{
res ^= inter;
inter ^= ((inter & 31) << 14);
inter >>= (TAGWIDTH - (NHIST - i - 1));
}
REMAIN = REMAIN - 64;
PT++;
}
}
return ((uint32_t) res & ((1 << TAGWIDTH) - 1));
}
////// for managing speculative state and forwarding information to the back-end
struct ForUpdate
{
bool predvtage;
bool predstride;
bool prediction_result;
uint8_t todo;
uint64_t pc;
uint32_t GI[NHIST + 1];
uint32_t GTAG[NHIST + 1];
int B[NBWAYSTR];
int TAGSTR[NBWAYSTR];
int STHIT;
int HitBank;
int8_t INSTTYPE;
int8_t NbOperand;
};
#define MAXINFLIGHT 512
static ForUpdate Update[MAXINFLIGHT]; // there may be 512 instructions inflight
<file_sep>/lib/resource_schedule.h
/*
Copyright (c) 2019, North Carolina State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Author: <NAME> (<EMAIL>)
#define SCHED_DEPTH_INCREMENT 256
#define MOD_S(x,y) ((x) & ((y)-1))
constexpr uint64_t MAX_CYCLE = ~0lu;
class resource_schedule {
private:
uint64_t *sched;
uint64_t depth;
uint64_t width;
uint64_t base_cycle;
void resize(uint64_t new_depth);
public:
resource_schedule(uint64_t width);
~resource_schedule();
uint64_t schedule(uint64_t start_cycle, uint64_t max_delta = MAX_CYCLE);
uint64_t try_schedule(uint64_t try_cycle);
void advance_base_cycle(uint64_t new_base_cycle);
};
<file_sep>/lib/resource_schedule.cc
/*
Copyright (c) 2019, North Carolina State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Author: <NAME> (<EMAIL>)
#include <inttypes.h>
#include <assert.h>
#include "resource_schedule.h"
resource_schedule::resource_schedule(uint64_t width) {
base_cycle = 0;
this->width = width;
depth = SCHED_DEPTH_INCREMENT;
sched = new uint64_t[depth];
for (uint64_t i = 0; i < depth; i++)
sched[i] = 0;
}
resource_schedule::~resource_schedule() {
}
void resource_schedule::resize(uint64_t new_depth) {
uint64_t old_depth;
uint64_t *old;
uint64_t increments;
uint64_t i;
old_depth = depth;
old = sched;
increments = (new_depth/SCHED_DEPTH_INCREMENT);
if (new_depth % SCHED_DEPTH_INCREMENT)
increments++;
depth = increments*SCHED_DEPTH_INCREMENT;
assert(depth >= new_depth);
sched = new uint64_t[depth];
for (i = 0; i < old_depth; i++)
sched[i] = old[i];
for (i = old_depth; i < depth; i++)
sched[i] = 0;
delete old;
}
uint64_t resource_schedule::schedule(uint64_t start_cycle, uint64_t max_delta)
{
assert(start_cycle >= base_cycle);
uint64_t i;
uint64_t limit_cycle = max_delta == MAX_CYCLE ? MAX_CYCLE : start_cycle + max_delta;
bool found = false;
while (!found) {
if ((start_cycle - base_cycle + 1) > depth)
resize(start_cycle - base_cycle + 1);
if (sched[MOD_S(start_cycle,depth)] < width) {
found = true;
sched[MOD_S(start_cycle,depth)]++;
}
else {
start_cycle++;
if(start_cycle > limit_cycle)
{
return MAX_CYCLE;
}
}
}
assert(found);
return(start_cycle);
}
uint64_t resource_schedule::try_schedule(uint64_t try_cycle)
{
// Calling this assumes all previous events to schedule have been scheduled.
assert(try_cycle >= base_cycle);
uint64_t i;;
bool found = false;
while (!found) {
if ((try_cycle - base_cycle + 1) > depth)
resize(try_cycle - base_cycle + 1);
if (sched[MOD_S(try_cycle,depth)] < width) {
found = true;
}
else {
try_cycle++;
}
}
assert(found);
return(try_cycle);
}
void resource_schedule::advance_base_cycle(uint64_t new_base_cycle) {
assert(new_base_cycle >= base_cycle);
for (uint64_t i = base_cycle; i < new_base_cycle; i++)
sched[MOD_S(i,depth)] = 0;
base_cycle = new_base_cycle;
}
<file_sep>/lib/parameters.cc
/*
Copyright (c) 2019, North Carolina State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Author: <NAME> (<EMAIL>)
#include <inttypes.h>
bool VP_ENABLE = false;
bool VP_PERFECT = false;
uint64_t VP_TRACK = 0;
uint64_t WINDOW_SIZE = 512;
uint64_t FETCH_WIDTH = 16;
uint64_t FETCH_NUM_BRANCH = 16; // 0: unlimited; >0: finite
bool FETCH_STOP_AT_INDIRECT = true;
bool FETCH_STOP_AT_TAKEN = true;
bool FETCH_MODEL_ICACHE = true;
bool PERFECT_BRANCH_PRED = false;
bool PERFECT_INDIRECT_PRED = false;
uint64_t PIPELINE_FILL_LATENCY = 5;
uint64_t NUM_LDST_LANES = 8;
uint64_t NUM_ALU_LANES = 16;
bool PREFETCHER_ENABLE = true;
bool PERFECT_CACHE = false;
bool WRITE_ALLOCATE = true;
uint64_t IC_SIZE = (1 << 17);
uint64_t IC_ASSOC = 8;
uint64_t IC_BLOCKSIZE = 64;
uint64_t L1_SIZE = (1 << 16);
uint64_t L1_ASSOC = 8;
uint64_t L1_BLOCKSIZE = 64;
uint64_t L1_LATENCY = 3;
uint64_t L2_SIZE = (1 << 20);
uint64_t L2_ASSOC = 8;
uint64_t L2_BLOCKSIZE = 64;
uint64_t L2_LATENCY = 12;
uint64_t L3_SIZE = (1 << 23);
uint64_t L3_ASSOC = 16;
uint64_t L3_BLOCKSIZE = 128;
uint64_t L3_LATENCY = 60;
uint64_t MAIN_MEMORY_LATENCY = 150;
<file_sep>/lib/fifo.h
/*
Copyright (c) 2019, North Carolina State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Author: <NAME> (<EMAIL>)
template <class T>
class fifo_t {
private:
T *q;
uint64_t size;
uint64_t head;
uint64_t tail;
uint64_t length;
public:
fifo_t(uint64_t size);
~fifo_t();
bool empty(); // returns true if empty, false otherwise
bool full(); // returns true if full, false otherwise
T pop(); // pop and return head entry
void push(T value); // push value at tail entry
T peektail(); // examine value at tail entry
T peekhead(); // examine value at head entry
};
template <class T>
fifo_t<T>::fifo_t(uint64_t size) {
q = ((size > 0) ? (new T[size]) : ((T *)NULL));
this->size = size;
head = 0;
tail = 0;
length = 0;
}
template <class T>
fifo_t<T>::~fifo_t() {
}
template <class T>
bool fifo_t<T>::empty() {
return(length == 0);
}
template <class T>
bool fifo_t<T>::full() {
return(length == size);
}
// pop and return head entry
template <class T>
T fifo_t<T>::pop() {
T ret = q[head];
assert(length > 0);
length--;
head++;
if (head == size)
head = 0;
return(ret);
}
// push value at tail entry
template <class T>
void fifo_t<T>::push(T value) {
assert(length < size);
length++;
q[tail] = value;
tail++;
if (tail == size)
tail = 0;
}
// examine value at tail entry
template <class T>
T fifo_t<T>::peektail() {
// Tail actually points to next free entry for push, so examine previous entry w.r.t. tail.
uint64_t prev = ((tail > 0) ? (tail - 1) : (size - 1));
return(q[prev]);
}
// examine value at head entry
template <class T>
T fifo_t<T>::peekhead() {
return(q[head]);
}
<file_sep>/lib/bp.h
/*
Copyright (c) 2019, North Carolina State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Author: <NAME> (<EMAIL>)
// Modified by <NAME> (<EMAIL>) to include TAGE-SC-L predictor and the ITTAGE indirect branch predictor
#include "tage_sc_l.h"
#include "ittage.h"
class ras_t {
private:
uint64_t *ras;
uint64_t size;
uint64_t tos;
public:
ras_t(uint64_t size) {
this->size = ((size > 0) ? size : 1);
ras = new uint64_t[this->size];
tos = 0;
}
~ras_t() {
}
inline void push(uint64_t x) {
ras[tos] = x;
tos++;
if (tos == size)
tos = 0;
}
inline uint64_t pop() {
tos = ((tos > 0) ? (tos - 1) : (size - 1));
return(ras[tos]);
}
};
class bp_t {
private:
// Conditional branch predictor based on CBP-5 TAGE-SC-L
PREDICTOR *TAGESCL;
// Indirect target predictor based on ITTAGE
IPREDICTOR *ITTAGE;
// Return address stack for predicting return targets.
ras_t ras;
// Check for link register (x1) or alternate link register (x5)
bool is_link_reg(uint64_t x);
// Measurements.
uint64_t meas_branch_n; // # branches
uint64_t meas_branch_m; // # mispredicted branches
uint64_t meas_jumpdir_n; // # jumps, direct
uint64_t meas_jumpind_n; // # jumps, indirect
uint64_t meas_jumpind_m; // # mispredicted jumps, indirect
uint64_t meas_jumpret_n; // # jumps, return
uint64_t meas_jumpret_m; // # mispredicted jumps, return
uint64_t meas_notctrl_n; // # non-control transfer instructions
uint64_t meas_notctrl_m; // # non-control transfer instructions for which: next_pc != pc + 4
public:
bp_t(uint64_t cb_pc_length, uint64_t cb_bhr_length,
uint64_t ib_pc_length, uint64_t ib_bhr_length,
uint64_t ras_size);
~bp_t();
// Returns true if instruction is a mispredicted branch.
// Also updates all branch predictor structures as applicable.
bool predict(InstClass insn, uint64_t pc, uint64_t next_pc);
// Output all branch prediction measurements.
void output();
};
<file_sep>/lib/uarchsim.cc
/*
Copyright (c) 2019, North Carolina State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Author: <NAME> (<EMAIL>)
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <assert.h>
#include "cvp.h"
#include "cvp_trace_reader.h"
#include "fifo.h"
#include "cache.h"
#include "bp.h"
#include "resource_schedule.h"
#include "uarchsim.h"
#include "parameters.h"
//uarchsim_t::uarchsim_t():window(WINDOW_SIZE),
uarchsim_t::uarchsim_t():BP(20,16,20,16,64),window(WINDOW_SIZE),
L3(L3_SIZE, L3_ASSOC, L3_BLOCKSIZE, L3_LATENCY, (cache_t *)NULL),
L2(L2_SIZE, L2_ASSOC, L2_BLOCKSIZE, L2_LATENCY, &L3),
L1(L1_SIZE, L1_ASSOC, L1_BLOCKSIZE, L1_LATENCY, &L2),
IC(IC_SIZE, IC_ASSOC, IC_BLOCKSIZE, 0, &L2) {
assert(WINDOW_SIZE);
//assert(FETCH_WIDTH);
//setup logger
// Set this to "spdlog::level::debug" for verbose debug prints
spdlog::set_level(spdlog::level::info);
spdlog::set_pattern("[%l] %v");
ldst_lanes = ((NUM_LDST_LANES > 0) ? (new resource_schedule(NUM_LDST_LANES)) : ((resource_schedule *)NULL));
alu_lanes = ((NUM_ALU_LANES > 0) ? (new resource_schedule(NUM_ALU_LANES)) : ((resource_schedule *)NULL));
for (int i = 0; i < RFSIZE; i++)
RF[i] = 0;
num_fetched = 0;
num_fetched_branch = 0;
fetch_cycle = 0;
num_inst = 0;
cycle = 0;
// CVP measurements
num_eligible = 0;
num_correct = 0;
num_incorrect = 0;
// stats
num_load = 0;
num_load_sqmiss = 0;
}
uarchsim_t::~uarchsim_t() {
}
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MIN(a, b) (((a) > (b)) ? (b) : (a))
PredictionRequest uarchsim_t::get_prediction_req_for_track(uint64_t cycle, uint64_t seq_no, uint8_t piece, db_t *inst)
{
PredictionRequest req;
req.seq_no = seq_no;
req.pc = inst->pc;
req.piece = piece;
req.cache_hit = HitMissInfo::Invalid;
switch(VPTracks(VP_TRACK)){
case VPTracks::ALL:
req.is_candidate = true;
break;
case VPTracks::LoadsOnly:
req.is_candidate = inst->is_load;
break;
case VPTracks::LoadsOnlyHitMiss:
{
req.is_candidate = inst->is_load;
if(req.is_candidate)
{
req.cache_hit = HitMissInfo::Miss;
uint64_t exec_cycle = get_load_exec_cycle(inst);
if(L1.is_hit(exec_cycle, inst->addr))
{
req.cache_hit = HitMissInfo::L1DHit;
}
else if(L2.is_hit(exec_cycle, inst->addr))
{
req.cache_hit = HitMissInfo::L2Hit;
}
else if(L3.is_hit(exec_cycle, inst->addr))
{
req.cache_hit = HitMissInfo::L3Hit;
}
}
break;
}
default:
assert(false && "Invalid Track\n");
break;
}
return req;
}
uint64_t uarchsim_t::get_load_exec_cycle(db_t *inst) const
{
uint64_t exec_cycle = fetch_cycle;
// No need to re-access ICache because fetch_cycle has already been updated
exec_cycle = exec_cycle + PIPELINE_FILL_LATENCY;
if (inst->A.valid) {
assert(inst->A.log_reg < RFSIZE);
exec_cycle = MAX(exec_cycle, RF[inst->A.log_reg]);
}
if (inst->B.valid) {
assert(inst->B.log_reg < RFSIZE);
exec_cycle = MAX(exec_cycle, RF[inst->B.log_reg]);
}
if (inst->C.valid) {
assert(inst->C.log_reg < RFSIZE);
exec_cycle = MAX(exec_cycle, RF[inst->C.log_reg]);
}
if (ldst_lanes) exec_cycle = ldst_lanes->try_schedule(exec_cycle);
// AGEN takes 1 cycle.
exec_cycle = (exec_cycle + 1);
return exec_cycle;
}
void uarchsim_t::step(db_t *inst)
{
spdlog::debug("Stepping, FC: {}",fetch_cycle);
// Preliminary step: determine which piece of the instruction this is.
static uint8_t piece = 0;
static uint64_t prev_pc = 0xdeadbeef;
piece = ((inst->pc == prev_pc) ? (piece + 1) : 0);
prev_pc = inst->pc;
/////////////////////////////
// Manage window: retire.
/////////////////////////////
while (!window.empty() && (fetch_cycle >= window.peekhead().retire_cycle)) {
window_t w = window.pop();
if (VP_ENABLE && !VP_PERFECT)
updatePredictor(w.seq_no, w.addr, w.value, w.latency);
}
// CVP variables
uint64_t seq_no = num_inst;
bool predictable = (inst->D.valid && (inst->D.log_reg != RFFLAGS));
PredictionResult pred;
bool squash = false;
uint64_t latency;
//
// Schedule the instruction's execution cycle.
//
uint64_t i;
uint64_t addr;
uint64_t exec_cycle;
if (FETCH_MODEL_ICACHE)
fetch_cycle = IC.access(fetch_cycle, true, inst->pc); // Note: I-cache hit latency is "0" (above), so fetch cycle doesn't increase on hits.
// Predict at fetch time
if (VP_ENABLE)
{
if (VP_PERFECT)
{
PredictionRequest req = get_prediction_req_for_track(fetch_cycle, seq_no, piece, inst);
pred.predicted_value = inst->D.value;
pred.speculate = predictable && req.is_candidate;
predictable &= req.is_candidate;
}
else
{
PredictionRequest req = get_prediction_req_for_track(fetch_cycle, seq_no, piece, inst);
pred = getPrediction(req);
speculativeUpdate(seq_no, predictable, ((predictable && pred.speculate && req.is_candidate) ? ((pred.predicted_value == inst->D.value) ? 1 : 0) : 2),
inst->pc, inst->next_pc, (InstClass)inst->insn, piece,
(inst->A.valid ? inst->A.log_reg : 0xDEADBEEF),
(inst->B.valid ? inst->B.log_reg : 0xDEADBEEF),
(inst->C.valid ? inst->C.log_reg : 0xDEADBEEF),
(inst->D.valid ? inst->D.log_reg : 0xDEADBEEF));
// Override any predictor attempting to predict an instruction that is not candidate.
pred.speculate &= req.is_candidate;
predictable &= req.is_candidate;
}
}
else {
pred.speculate = false;
}
exec_cycle = fetch_cycle + PIPELINE_FILL_LATENCY;
if (inst->A.valid) {
assert(inst->A.log_reg < RFSIZE);
exec_cycle = MAX(exec_cycle, RF[inst->A.log_reg]);
}
if (inst->B.valid) {
assert(inst->B.log_reg < RFSIZE);
exec_cycle = MAX(exec_cycle, RF[inst->B.log_reg]);
}
if (inst->C.valid) {
assert(inst->C.log_reg < RFSIZE);
exec_cycle = MAX(exec_cycle, RF[inst->C.log_reg]);
}
//
// Schedule an execution lane.
//
if (inst->is_load || inst->is_store) {
if (ldst_lanes) exec_cycle = ldst_lanes->schedule(exec_cycle);
}
else {
if (alu_lanes) exec_cycle = alu_lanes->schedule(exec_cycle);
}
if (inst->is_load) {
latency = exec_cycle; // record start of execution
// AGEN takes 1 cycle.
exec_cycle = (exec_cycle + 1);
// Train the prefetcher when the load finds out its outcome in the L1D
if (PREFETCHER_ENABLE)
{
// Generate prefetches ahead of time as in "Effective Hardware-Based Data Prefetching for High-Performance Processors"
// Instruction PC will be 4B aligned.
prefetcher.lookahead((inst->pc >> 2), fetch_cycle);
// Train the prefetcher
const bool hit = L1.is_hit(exec_cycle, inst->addr);
PrefetchTrainingInfo info{inst->pc >> 2, inst->addr, 0, hit};
prefetcher.train(info);
}
// Search D$ using AGEN's cycle.
uint64_t data_cache_cycle;
if (PERFECT_CACHE)
data_cache_cycle = exec_cycle + L1_LATENCY;
else
data_cache_cycle = L1.access(exec_cycle, true, inst->addr);
// Search of SQ takes 1 cycle after AGEN cycle.
exec_cycle = (exec_cycle + 1);
bool inc_sqmiss = false;
uint64_t temp_cycle = 0;
for (i = 0, addr = inst->addr; i < inst->size; i++, addr++) {
if ((SQ.find(addr) != SQ.end()) && (exec_cycle < SQ[addr].ret_cycle)) {
// SQ hit: the byte's timestamp is the later of load's execution cycle and store's execution cycle
temp_cycle = MAX(temp_cycle, MAX(exec_cycle, SQ[addr].exec_cycle));
}
else {
// SQ miss: the byte's timestamp is its availability in L1 D$
temp_cycle = MAX(temp_cycle, data_cache_cycle);
inc_sqmiss = true;
}
}
num_load++; // stat
num_load_sqmiss += (inc_sqmiss ? 1 : 0); // stat
assert(temp_cycle >= exec_cycle);
exec_cycle = temp_cycle;
latency = (exec_cycle - latency); // end of execution minus start of execution
assert(latency >= 2); // 2 cycles if all bytes hit in SQ
}
else {
// Determine the fixed execution latency based on ALU type.
if (inst->insn == InstClass::fpInstClass)
latency = 3;
else if (inst->insn == InstClass::slowAluInstClass)
latency = 4;
else
latency = 1;
// Account for execution latency.
exec_cycle += latency;
}
// Drain prefetches from PF Queue
// The idea is that a prefetch can go only if there is a free LDST slot "this" cycle
// Here, "this" means all the cycles between the previous fetch cycle and the current one since all fetched ld/st will have been
// scheduled and prefetch can correctly "steal" ld/st slots.
if(PREFETCHER_ENABLE)
{
uint64_t tmp_previous_fetch_cycle;
Prefetch p;
bool issued;
while(prefetcher.issue(p, fetch_cycle))
{
tmp_previous_fetch_cycle = MAX(previous_fetch_cycle, p.cycle_generated);
issued = false;
while(tmp_previous_fetch_cycle <= fetch_cycle)
{
spdlog::debug("Issuing prefetch:{}", p);
uint64_t cycle_pf_exec = tmp_previous_fetch_cycle;
if(ldst_lanes) cycle_pf_exec = ldst_lanes->schedule(cycle_pf_exec, 0);
if(cycle_pf_exec != MAX_CYCLE)
{
L1.access(cycle_pf_exec, true, p.address, true);
++stat_pfs_issued_to_mem;
issued = true;
break;
}
else
{
tmp_previous_fetch_cycle++;
spdlog::debug("Could not find empty LDST slot for PF this cycle, increasing");
}
}
if(!issued)
{
prefetcher.put_back(p);
break;
}
}
}
// Update the instruction count and simulation cycle (max. completion cycle among all scheduled instructions).
num_inst += 1;
cycle = MAX(cycle, exec_cycle);
// Update destination register timestamp.
if (inst->D.valid) {
assert(inst->D.log_reg < RFSIZE);
if (inst->D.log_reg != RFFLAGS)
{
squash = (pred.speculate && (pred.predicted_value != inst->D.value));
RF[inst->D.log_reg] = ((pred.speculate && (pred.predicted_value == inst->D.value)) ? fetch_cycle : exec_cycle);
}
}
// Update SQ byte timestamps.
if (inst->is_store) {
uint64_t data_cache_cycle;
if (!WRITE_ALLOCATE || PERFECT_CACHE)
data_cache_cycle = exec_cycle;
else
data_cache_cycle = L1.access(exec_cycle, true, inst->addr);
// uint64_t ret_cycle = MAX(exec_cycle, (window.empty() ? 0 : window.peektail().retire_cycle));
uint64_t ret_cycle = MAX(data_cache_cycle, (window.empty() ? 0 : window.peektail().retire_cycle));
for (i = 0, addr = inst->addr; i < inst->size; i++, addr++) {
SQ[addr].exec_cycle = exec_cycle;
SQ[addr].ret_cycle = ret_cycle;
}
}
// CVP measurements
num_eligible += (predictable ? 1 : 0);
num_correct += ((predictable && pred.speculate && !squash) ? 1 : 0);
num_incorrect += ((predictable && pred.speculate && squash) ? 1 : 0);
/////////////////////////////
// Manage window: dispatch.
/////////////////////////////
window.push({MAX(exec_cycle, (window.empty() ? 0 : window.peektail().retire_cycle)),
seq_no,
((inst->is_load || inst->is_store) ? inst->addr : 0xDEADBEEF),
((inst->D.valid && (inst->D.log_reg != RFFLAGS)) ? inst->D.value : 0xDEADBEEF),
latency});
/////////////////////////////
// Manage fetch cycle.
/////////////////////////////
previous_fetch_cycle = fetch_cycle;
if (squash) { // control dependency on the retire cycle of the value-mispredicted instruction
num_fetched = 0; // new fetch bundle
assert(!window.empty() && (fetch_cycle < window.peektail().retire_cycle));
fetch_cycle = window.peektail().retire_cycle;
}
else if (window.full()) {
if (fetch_cycle < window.peekhead().retire_cycle) {
num_fetched = 0; // new fetch bundle
fetch_cycle = window.peekhead().retire_cycle;
}
}
else { // fetch bundle constraints
bool stop = false;
bool cond_branch = ((InstClass) inst->insn == InstClass::condBranchInstClass);
bool uncond_direct = ((InstClass) inst->insn == InstClass::uncondDirectBranchInstClass);
bool uncond_indirect = ((InstClass) inst->insn == InstClass::uncondIndirectBranchInstClass);
// Finite fetch bundle.
if (FETCH_WIDTH > 0) {
num_fetched++;
if (num_fetched == FETCH_WIDTH)
stop = true;
}
// Finite branch throughput.
if ((FETCH_NUM_BRANCH > 0) && (cond_branch || uncond_direct || uncond_indirect)) {
num_fetched_branch++;
if (num_fetched_branch == FETCH_NUM_BRANCH)
stop = true;
}
// Indirect branch constraint.
if (FETCH_STOP_AT_INDIRECT && uncond_indirect)
stop = true;
// Taken branch constraint.
if (FETCH_STOP_AT_TAKEN && (uncond_direct || uncond_indirect || (cond_branch && (inst->next_pc != (inst->pc + 4)))))
stop = true;
if (stop) {
// new fetch bundle
num_fetched = 0;
num_fetched_branch = 0;
fetch_cycle++;
}
}
// Account for the effect of a mispredicted branch on the fetch cycle.
if (!PERFECT_BRANCH_PRED && BP.predict((InstClass) inst->insn, inst->pc, inst->next_pc))
fetch_cycle = MAX(fetch_cycle, exec_cycle);
spdlog::debug("Updating base_cycle to {}", MIN(fetch_cycle, prefetcher.get_oldest_pf_cycle()));
// Attempt to advance the base cycles of resource schedules.
// Note : We may have some prefetches to issue still that are older than the fetch cycle.
if (ldst_lanes) ldst_lanes->advance_base_cycle(MIN(fetch_cycle, prefetcher.get_oldest_pf_cycle()));
if (alu_lanes) alu_lanes->advance_base_cycle(MIN(fetch_cycle, prefetcher.get_oldest_pf_cycle()));
// DEBUG
//printf("%d,%d\n", num_inst, cycle);
}
#define KILOBYTE (1<<10)
#define MEGABYTE (1<<20)
#define SCALED_SIZE(size) ((size/KILOBYTE >= KILOBYTE) ? (size/MEGABYTE) : (size/KILOBYTE))
#define SCALED_UNIT(size) ((size/KILOBYTE >= KILOBYTE) ? "MB" : "KB")
void uarchsim_t::output() {
auto get_track_name = [] (uint64_t track){
static std::string track_names [] = {
"ALL",
"LoadsOnly",
"LoadsOnlyHitMiss",
};
//return track_names[static_cast<std::underlying_type<VPTracks>::type>(t)].c_str();
return track_names[track].c_str();
};
printf("VP_ENABLE = %d\n", (VP_ENABLE ? 1 : 0));
printf("VP_PERFECT = %s\n", (VP_ENABLE ? (VP_PERFECT ? "1" : "0") : "n/a"));
printf("VP_TRACK = %s\n", (VP_ENABLE ? get_track_name(VP_TRACK) : "n/a"));
printf("WINDOW_SIZE = %ld\n", WINDOW_SIZE);
printf("FETCH_WIDTH = %ld\n", FETCH_WIDTH);
printf("FETCH_NUM_BRANCH = %ld\n", FETCH_NUM_BRANCH);
printf("FETCH_STOP_AT_INDIRECT = %s\n", (FETCH_STOP_AT_INDIRECT ? "1" : "0"));
printf("FETCH_STOP_AT_TAKEN = %s\n", (FETCH_STOP_AT_TAKEN ? "1" : "0"));
printf("FETCH_MODEL_ICACHE = %s\n", (FETCH_MODEL_ICACHE ? "1" : "0"));
printf("PERFECT_BRANCH_PRED = %s\n", (PERFECT_BRANCH_PRED ? "1" : "0"));
printf("PERFECT_INDIRECT_PRED = %s\n", (PERFECT_INDIRECT_PRED ? "1" : "0"));
printf("PIPELINE_FILL_LATENCY = %ld\n", PIPELINE_FILL_LATENCY);
printf("NUM_LDST_LANES = %ld%s", NUM_LDST_LANES, ((NUM_LDST_LANES > 0) ? "\n" : " (unbounded)\n"));
printf("NUM_ALU_LANES = %ld%s", NUM_ALU_LANES, ((NUM_ALU_LANES > 0) ? "\n" : " (unbounded)\n"));
//BP.output();
printf("MEMORY HIERARCHY CONFIGURATION---------------------\n");
printf("STRIDE Prefetcher = %s\n", PREFETCHER_ENABLE ? "1" : "0");
printf("PERFECT_CACHE = %s\n", (PERFECT_CACHE ? "1" : "0"));
printf("WRITE_ALLOCATE = %s\n", (WRITE_ALLOCATE ? "1" : "0"));
printf("Within-pipeline factors:\n");
printf("\tAGEN latency = 1 cycle\n");
printf("\tStore Queue (SQ): SQ size = window size, oracle memory disambiguation, store-load forwarding = 1 cycle after store's or load's agen.\n");
printf("\t* Note: A store searches the L1$ at commit. The store is released\n");
printf("\t* from the SQ and window, whether it hits or misses. Store misses\n");
printf("\t* are buffered until the block is allocated and the store is\n");
printf("\t* performed in the L1$. While buffered, conflicting loads get\n");
printf("\t* the store's data as they would from the SQ.\n");
if (FETCH_MODEL_ICACHE) {
printf("I$: %ld %s, %ld-way set-assoc., %ldB block size\n",
SCALED_SIZE(IC_SIZE), SCALED_UNIT(IC_SIZE), IC_ASSOC, IC_BLOCKSIZE);
}
printf("L1$: %ld %s, %ld-way set-assoc., %ldB block size, %ld-cycle search latency\n",
SCALED_SIZE(L1_SIZE), SCALED_UNIT(L1_SIZE), L1_ASSOC, L1_BLOCKSIZE, L1_LATENCY);
printf("L2$: %ld %s, %ld-way set-assoc., %ldB block size, %ld-cycle search latency\n",
SCALED_SIZE(L2_SIZE), SCALED_UNIT(L2_SIZE), L2_ASSOC, L2_BLOCKSIZE, L2_LATENCY);
printf("L3$: %ld %s, %ld-way set-assoc., %ldB block size, %ld-cycle search latency\n",
SCALED_SIZE(L3_SIZE), SCALED_UNIT(L3_SIZE), L3_ASSOC, L3_BLOCKSIZE, L3_LATENCY);
printf("Main Memory: %ld-cycle fixed search time\n", MAIN_MEMORY_LATENCY);
printf("STORE QUEUE MEASUREMENTS---------------------------\n");
printf("Number of loads: %ld\n", num_load);
printf("Number of loads that miss in SQ: %ld (%.2f%%)\n", num_load_sqmiss, 100.0*(double)num_load_sqmiss/(double)num_load);
printf("Number of PFs issued to the memory system %ld\n", stat_pfs_issued_to_mem);
printf("MEMORY HIERARCHY MEASUREMENTS----------------------\n");
if (FETCH_MODEL_ICACHE) {
printf("I$:\n"); IC.stats();
}
printf("L1$:\n"); L1.stats();
printf("L2$:\n"); L2.stats();
printf("L3$:\n"); L3.stats();
BP.output();
printf("ILP LIMIT STUDY------------------------------------\n");
printf("instructions = %ld\n", num_inst);
printf("cycles = %ld\n", cycle);
printf("IPC = %.3f\n", ((double)num_inst/(double)cycle));
printf("Prefetcher------------------------------------------\n");
prefetcher.print_stats();
printf("CVP STUDY------------------------------------------\n");
printf("prediction-eligible instructions = %ld\n", num_eligible);
printf("correct predictions = %ld (%.2f%%)\n", num_correct, (100.0*(double)num_correct/(double)num_eligible));
printf("incorrect predictions = %ld (%.2f%%)\n", num_incorrect, (100.0*(double)num_incorrect/(double)num_eligible));
}
<file_sep>/mypredictor.cc
#include <inttypes.h>
#include "cvp.h"
#include "mypredictor.h"
#include <iostream>
int seq_commit;
#define NOTLLCMISS (actual_latency < 150)
#define NOTL2MISS (actual_latency < 60)
#define NOTL1MISS (actual_latency < 12)
#define FASTINST (actual_latency ==1)
#define MFASTINST (actual_latency <3)
void
getPredVtage (ForUpdate * U, uint64_t & predicted_value)
{
bool predvtage = false;
uint64_t pc = U->pc;
uint64_t PCindex = ((pc) ^ (pc >> 2) ^ (pc >> 5)) % PREDSIZE;
uint64_t PCbank = (PCindex >> LOGBANK) << LOGBANK;
for (int i = 1; i <= NHIST; i++)
{
U->GI[i] = (gi (i, pc) + (PCbank + (i << LOGBANK))) % PREDSIZE;
U->GTAG[i] = gtag (i, pc);
}
U->GTAG[0] = (pc ^ (pc >> 4) ^ (pc >> TAGWIDTH)) & ((1 << TAGWIDTH) - 1);
U->GI[0] = PCindex;
U->HitBank = -1;
for (int i = NHIST; i >= 0; i--)
{
if (Vtage[U->GI[i]].tag == U->GTAG[i])
{
U->HitBank = i;
break;
}
}
if (LastMispVT >= 128)
// when a misprediction is encountered on VTAGE, we do not predict with VTAGE for 128 instructions;
// does not bring significant speed-up, but reduces the misprediction number significantly: mispredictions tend to be clustered
if (U->HitBank >= 0)
{
int index = Vtage[U->GI[U->HitBank]].hashpt;
if (index < 3 * BANKDATA)
{
// the hash and the data are both present
predicted_value = LDATA[index].data;
predvtage = ((Vtage[U->GI[U->HitBank]].conf >= MAXCONFID));
}
}
U->predvtage = predvtage;
}
void
getPredStride (ForUpdate * U, uint64_t & predicted_value, uint64_t seq_no)
{
bool predstride = false;
int B[NBWAYSTR];
int TAG[NBWAYSTR];
uint64_t pc = U->pc;
//use a 3-way skewed-associative structure for the stride predictor
for (int i = 0; i < NBWAYSTR; i++)
{
//B[i] index in way i ; TAG[i] tag in way i;
B[i] = ((((pc) ^ (pc >> (2 * LOGSTR - i)) ^
(pc >> (LOGSTR - i)) ^
(pc >> (3 * LOGSTR - i))) * NBWAYSTR) +
i) % (NBWAYSTR * (1 << LOGSTR));
int j = (NBWAYSTR - i);
if (j < 0)
j = 0;
TAG[i] =
((pc >> (LOGSTR - j)) ^ (pc >> (2 * LOGSTR - j)) ^
(pc >> (3 * LOGSTR - j)) ^ (pc >> (4 * LOGSTR - j))) & ((1 <<
TAGWIDTHSTR)
- 1);
U->B[i] = B[i];
U->TAGSTR[i] = TAG[i];
}
int STHIT = -1;
for (int i = 0; i < NBWAYSTR; i++)
{
if (STR[B[i]].tag == TAG[i])
{
STHIT = B[i];
break;
}
}
U->STHIT = STHIT;
if (STHIT >= 0)
if (SafeStride >= 0)
{ // hit
uint64_t LastCommitedValue = STR[STHIT].LastValue;
if (STR[STHIT].conf >= MAXCONFIDSTR / 4)
{
int inflight = 0;
// compute the number of inflight instances of the instruction
for (uint64_t i = seq_commit + 1; i < seq_no; i++)
{
inflight += (Update[i & (MAXINFLIGHT - 1)].pc == pc);
}
predicted_value =
(uint64_t) ((int64_t) LastCommitedValue +
((inflight + 1) * ((int64_t) STR[STHIT].Stride)));
predstride = true;
}
}
U->predstride = predstride;
}
PredictionResult getPrediction(const PredictionRequest& req)
{
PredictionResult result;
ForUpdate *U;
U = &Update[req.seq_no & (MAXINFLIGHT - 1)];
U->pc = req.pc + req.piece;
U->predvtage = false;
U->predstride = false;
#ifdef PREDSTRIDE
getPredStride (U, result.predicted_value, req.seq_no);
#endif
#ifdef PREDVTAGE
getPredVtage (U, result.predicted_value);
#endif
// the two predictions are very rarely both high confidence; when they are pick the VTAGE prediction
result.speculate = (U->predstride || U->predvtage);
return result;
}
// Update of the Stride predictor
// function determining whether to update or not confidence on a correct prediction
bool
strideupdateconf (ForUpdate * U, uint64_t actual_value, int actual_latency,
int stride)
{
#define UPDATECONFSTR2 (((!U->prediction_result) || (U->predstride)) && ((random () & ((1 << (NOTLLCMISS + NOTL2MISS + NOTL1MISS + 2*MFASTINST + 2*(U->INSTTYPE!=loadInstClass))) - 1)) == 0))
#define UPDATECONFSTR1 (abs (stride >= 8) ? (UPDATECONFSTR2 || UPDATECONFSTR2) : (UPDATECONFSTR2))
#define UPDATECONFSTR (abs (stride >= 64) ? (UPDATECONFSTR1 || UPDATECONFSTR1) : (UPDATECONFSTR1))
return (UPDATECONFSTR &
((abs (stride) > 1) || (U->INSTTYPE != loadInstClass)
|| ((stride == -1) & ((random () & 1) == 0))
|| ((stride == 1) & ((random () & 3) == 0))));
//All strides are not equal: the smaller the stride the smaller the benefit (not huge :-))
}
//Allocate or not if instruction absent from the predictor
bool
StrideAllocateOrNot (ForUpdate * U, uint64_t actual_value, int actual_latency)
{
#ifndef LIMITSTUDY
bool X = false;
#define LOGPBINVSTR 4
switch (U->INSTTYPE)
{
case aluInstClass:
case storeInstClass:
X = ((random () & ((1 << (LOGPBINVSTR + 2)) - 1)) == 0);
break;
case fpInstClass:
X = ((random () & ((1 << (LOGPBINVSTR)) - 1)) == 0);
break;
case slowAluInstClass:
X = ((random () & ((1 << (LOGPBINVSTR)) - 1)) == 0);
break;
case loadInstClass:
X =
((random () &
((1 << (NOTLLCMISS + NOTL2MISS + NOTL1MISS + MFASTINST)) - 1)) ==
0);
break;
};
return (X);
#else
return (true);
#endif
}
void
UpdateStridePred (ForUpdate * U, uint64_t actual_value, int actual_latency)
{
int B[NBWAYSTR];
int TAG[NBWAYSTR];
for (int i = 0; i < NBWAYSTR; i++)
{
B[i] = U->B[i];
TAG[i] = U->TAGSTR[i];
}
int STHIT = -1;
for (int i = 0; i < NBWAYSTR; i++)
{
if (STR[B[i]].tag == TAG[i])
{
STHIT = B[i];
break;
}
}
if (STHIT >= 0)
{
uint64_t LastValue = STR[STHIT].LastValue;
uint64_t Value =
(uint64_t) ((int64_t) LastValue + (int64_t) STR[STHIT].Stride);
int64_t INTER =
abs (2 * ((int64_t) actual_value - (int64_t) LastValue) - 1);
uint64_t stridetoalloc =
(INTER <
(1 << LOGSTRIDE)) ? (uint64_t) ((int64_t) actual_value -
(int64_t) LastValue) : 0;
STR[STHIT].LastValue = actual_value;
//special case when the stride is not determined
if (STR[STHIT].NotFirstOcc > 0)
{
if (Value == actual_value)
{
if (STR[STHIT].conf < MAXCONFIDSTR)
{
if (strideupdateconf
(U, actual_value, actual_latency, (int) stridetoalloc))
STR[STHIT].conf++;
}
if (STR[STHIT].u < 3)
if (strideupdateconf
(U, actual_value, actual_latency, (int) stridetoalloc))
STR[STHIT].u++;
if (STR[STHIT].conf >= MAXCONFIDSTR / 4)
STR[STHIT].u = 3;
}
else
{
//misprediction
{
if (STR[STHIT].conf > (1 << (WIDTHCONFIDSTR - 3)))
{
STR[STHIT].conf -= (1 << (WIDTHCONFIDSTR - 3));
}
else
{
STR[STHIT].conf = 0;
STR[STHIT].u = 0;
}
}
// this allows to restart a new sequence with a different stride
STR[STHIT].NotFirstOcc = 0;
}
}
else
{
//First occurence
// if (STR[STHIT].NotFirstOcc == 0)
if (stridetoalloc != 0)
// if ((stridetoalloc != 0) && (stridetoalloc!=1) && (((int64_t) stridetoalloc) != -1))
// we do not waste the stride predictor storage for stride zero
{
STR[STHIT].Stride = stridetoalloc;
}
else
{
// do not pollute the stride predictor with constant data or with invalid strides
STR[STHIT].Stride = 0xffff;
STR[STHIT].conf = 0;
STR[STHIT].u = 0;
}
STR[STHIT].NotFirstOcc++;
}
}
else // the address was not present and is not predicted by VTAGE
if (!U->prediction_result)
{
if (StrideAllocateOrNot (U, actual_value, actual_latency))
{ // try to allocate
int X = random () % NBWAYSTR;
bool done = false;
// the target entry is not a stride candidate
for (int i = 0; i < NBWAYSTR; i++)
{
STHIT = B[X];
if (STR[STHIT].conf == 0)
{
STR[STHIT].conf = 1; //just to allow not to ejected before testing if possible stride candidate
STR[STHIT].u = 0;
STR[STHIT].tag = TAG[X];
STR[STHIT].Stride = 0;
STR[STHIT].NotFirstOcc = 0;
STR[STHIT].LastValue = actual_value;
done = true;
break;
}
X = (X + 1) % NBWAYSTR;
}
// the target entry has not been useful recently
if (!done)
for (int i = 0; i < NBWAYSTR; i++)
{
STHIT = B[X];
if (STR[STHIT].u == 0)
{
STR[STHIT].conf = 1;
STR[STHIT].u = 0;
STR[STHIT].tag = TAG[X];
STR[STHIT].Stride = 0;
STR[STHIT].NotFirstOcc = 0;
STR[STHIT].LastValue = actual_value;
done = true;
break;
}
X = (X + 1) % NBWAYSTR;
}
//if unable to allocate: age some target entry
if (!done)
{
if ((random () &
((1 <<
(2 + 2 * (STR[STHIT].conf > (MAXCONFIDSTR) / 8) +
2 * (STR[STHIT].conf >= MAXCONFIDSTR / 4))) - 1)) == 0)
STR[STHIT].u--;
}
}
}
//////////////////////////////
}
/////////Update of VTAGE
// function determining whether to update or not confidence on a correct prediction
bool
vtageupdateconf (ForUpdate * U, uint64_t actual_value, int actual_latency)
{
#define LOWVAL ((abs (2*((int64_t) actual_value)+1)<(1<<16))+ (actual_value==0))
#ifdef K8
#define updateconf ((random () & (((1 << (LOWVAL+NOTLLCMISS+2*FASTINST+NOTL2MISS+NOTL1MISS + ((U->INSTTYPE!=loadInstClass) ||NOTL1MISS) + (U->HitBank > 1) ))- 1)))==0)
#else
#define updateconf ((random () & (((1 << (LOWVAL+NOTLLCMISS+2*FASTINST+NOTL2MISS+NOTL1MISS + ((U->INSTTYPE!=loadInstClass) ||NOTL1MISS) ))- 1)))==0)
#endif
#ifdef LIMITSTUDY
#define UPDATECONF2 ((U->HitBank<=1) ? (updateconf || updateconf ) || (updateconf || updateconf ) : (updateconf || updateconf ))
#define UPDATECONF (UPDATECONF2 || UPDATECONF2)
#else
#ifdef K32
#define UPDATECONF (((U->HitBank<=1) ? (updateconf || updateconf) : updateconf))
#else
// K8
#define UPDATECONF updateconf
#endif
#endif
switch (U->INSTTYPE)
{
case aluInstClass:
case fpInstClass:
case slowAluInstClass:
case undefInstClass:
case loadInstClass:
case storeInstClass:
return (UPDATECONF);
break;
case uncondIndirectBranchInstClass:
return (true);
break;
default:
return (false);
};
}
// Update of the U counter or not
bool
VtageUpdateU (ForUpdate * U, uint64_t actual_value, int actual_latency)
{
#define UPDATEU ((!U->prediction_result) && ((random () & ((1<<( LOWVAL + 2*NOTL1MISS + (U->INSTTYPE!=loadInstClass) + FASTINST + 2*(U->INSTTYPE==aluInstClass)*(U->NbOperand<2)))-1)) == 0))
switch (U->INSTTYPE)
{
case aluInstClass:
case fpInstClass:
case slowAluInstClass:
case undefInstClass:
case loadInstClass:
case storeInstClass:
return (UPDATEU);
break;
case uncondIndirectBranchInstClass:
return (true);
break;
default:
return (false);
};
}
bool
VtageAllocateOrNot (ForUpdate * U, uint64_t actual_value, int actual_latency,
bool MedConf)
{
bool X = false;
switch (U->INSTTYPE)
{
case undefInstClass:
case aluInstClass:
case storeInstClass:
#ifndef LIMITSTUDY
if (((U->NbOperand >= 2)
& ((random () & 15) == 0))
|| ((U->NbOperand < 2) & ((random () & 63) == 0)))
#endif
case fpInstClass:
case slowAluInstClass:
case loadInstClass:
#ifndef LIMITSTUDY
X = (((random () &
#ifdef K8
((4 <<
#else
//K32
((2 <<
#endif
(
#ifdef K32
((U->INSTTYPE != loadInstClass) || (NOTL1MISS)) *
#endif
LOWVAL + NOTLLCMISS + NOTL2MISS +
#ifdef K8
2 *
#endif
NOTL1MISS + 2 * FASTINST)) - 1)) == 0) ||
#ifdef K8
(((random () & 3) == 0) && MedConf));
#else
(MedConf));
#endif
#else
X = true;
#endif
break;
case uncondIndirectBranchInstClass:
X = true;
break;
default:
X = false;
};
return (X);
}
void
UpdateVtagePred (ForUpdate * U, uint64_t actual_value, int actual_latency)
{
bool MedConf = false;
uint64_t HashData = ((actual_value ^ (actual_value >> 7) ^
(actual_value >> 13) ^ (actual_value >> 21) ^
(actual_value >> 29) ^ (actual_value >> 34) ^
(actual_value >> 43) ^ (actual_value >> 52) ^
(actual_value >> 57)) & (BANKDATA - 1)) +
3 * BANKDATA;
bool ShouldWeAllocate = true;
if (U->HitBank != -1)
{
// there was an hitting entry in VTAGE
uint64_t index = U->GI[U->HitBank];
// the entry may have dissappeared in the interval between the prediction and the commit
if (Vtage[index].tag == U->GTAG[U->HitBank])
{
// update the prediction
uint64_t indindex = Vtage[index].hashpt;
ShouldWeAllocate =
((indindex >= 3 * BANKDATA) && (indindex != HashData))
|| ((indindex < 3 * BANKDATA) &&
(LDATA[indindex].data != actual_value));
if (!ShouldWeAllocate)
{
// the predicted result is satisfactory: either a good hash without data, or a pointer on the correct data
ShouldWeAllocate = false;
if (Vtage[index].conf < MAXCONFID)
if (vtageupdateconf (U, actual_value, actual_latency))
Vtage[index].conf++;
if (Vtage[index].u < MAXU)
if ((VtageUpdateU (U, actual_value, actual_latency))
|| (Vtage[index].conf == MAXCONFID))
Vtage[index].u++;
if (indindex < 3 * BANKDATA)
if (LDATA[indindex].u < 3)
if (Vtage[index].conf == MAXCONFID)
LDATA[indindex].u++;
if (indindex >= 3 * BANKDATA)
{
//try to allocate an effective data entry when the confidence has reached a reasonable level
if (Vtage[index].conf >= MAXCONFID - 1)
{
int X[3];
for (int i = 0; i < 3; i++)
X[i] =
(((actual_value) ^
(actual_value >> (LOGLDATA + (i + 1))) ^
(actual_value >> (3 * (LOGLDATA + (i + 1)))) ^
(actual_value >> (4 * (LOGLDATA + (i + 1)))) ^
(actual_value >> (5 * (LOGLDATA + (i + 1)))) ^
(actual_value >> (6 * (LOGLDATA + (i + 1)))) ^
(actual_value >> (2 * (LOGLDATA + (i + 1))))) &
((1 << LOGLDATA) - 1)) + i * (1 << LOGLDATA);
bool done = false;
for (int i = 0; i < 3; i++)
{
if (LDATA[X[i]].data == actual_value)
{
//the data is already present
Vtage[index].hashpt = X[i];
done = true;
break;
}
}
if (!done)
if ((random () & 3) == 0)
{
//data absent: let us try try to steal an entry
int i = (((uint64_t) random ()) % 3);
bool done = false;
for (int j = 0; j < 3; j++)
{
if ((LDATA[X[i]].u == 0))
{
LDATA[X[i]].data = actual_value;
LDATA[X[i]].u = 1;
Vtage[index].hashpt = X[i];
done = true;
break;
}
i++;
i = i % 3;
}
if (U->INSTTYPE == loadInstClass)
if (!done)
{
if ((LDATA[X[i]].u == 0))
{
LDATA[X[i]].data = actual_value;
LDATA[X[i]].u = 1;
Vtage[index].hashpt = X[i];
}
else
#ifdef K8
if ((random () & 31) == 0)
#else
if ((random () & 3) == 0)
#endif
LDATA[X[i]].u--;
}
}
}
}
}
else
{
// misprediction: reset
Vtage[index].hashpt = HashData;
if ((Vtage[index].conf > MAXCONFID / 2)
|| ((Vtage[index].conf == MAXCONFID / 2) &
(Vtage[index].u == 3))
|| ((Vtage[index].conf > 0) &
(Vtage[index].conf < MAXCONFID / 2)))
MedConf = true;
if (Vtage[index].conf == MAXCONFID)
{
Vtage[index].u = (Vtage[index].conf == MAXCONFID);
Vtage[index].conf -= (MAXCONFID + 1) / 4;
}
else
{
Vtage[index].conf = 0;
Vtage[index].u = 0;
}
}
}
}
if (!U->prediction_result)
//Don't waste your time allocating if it is predicted by the other component
if (ShouldWeAllocate)
{
// avoid allocating too often
if (VtageAllocateOrNot (U, actual_value, actual_latency, MedConf))
{
int ALL = 0;
int NA = 0;
int DEP = (U->HitBank + 1) + ((random () & 7) == 0);
if (U->HitBank == 0)
DEP++;
if (U->HitBank == -1)
{
if (random () & 7)
DEP = random () & 1;
else
DEP = 2 + ((random () & 7) == 0);
}
if (DEP > 1)
{
for (int i = DEP; i <= NHIST; i++)
{
int index = U->GI[i];
if ((Vtage[index].u == 0)
&& ((Vtage[index].conf == MAXCONFID / 2)
|| (Vtage[index].conf <=
(random () & MAXCONFID))))
//slightly favors the entries with real confidence
{
Vtage[index].hashpt = HashData;
Vtage[index].conf = MAXCONFID / 2; //set to 3 for faster warming to high confidence
Vtage[index].tag = U->GTAG[i];
ALL++;
break;
}
else
{
NA++;
}
}
}
else
{
for (int j = 0; j <= 1; j++)
{
int i = (j + DEP) & 1;
int index = U->GI[i];
if ((Vtage[index].u == 0)
&& ((Vtage[index].conf == MAXCONFID / 2)
|| (Vtage[index].conf <=
(random () & MAXCONFID))))
{
Vtage[index].hashpt = HashData;
Vtage[index].conf = MAXCONFID / 2;
if (U->NbOperand == 0)
if (U->INSTTYPE == aluInstClass)
Vtage[index].conf = MAXCONFID;
Vtage[index].tag = U->GTAG[i];
ALL++;
break;
}
else
{
NA++;
}
}
}
#ifdef K8
TICK += NA - (3 * ALL);
#else
TICK += (NA - (5 * ALL));
#endif
if (TICK < 0)
TICK = 0;
if (TICK >= MAXTICK)
{
for (int i = 0; i < PREDSIZE; i++)
if (Vtage[i].u > 0)
Vtage[i].u--;
TICK = 0;
}
}
}
}
void
updatePredictor (uint64_t
seq_no,
uint64_t
actual_addr, uint64_t actual_value, uint64_t actual_latency)
{
ForUpdate *U;
U = &Update[seq_no & (MAXINFLIGHT - 1)];
if (U->todo == 1)
{
#ifdef LIMITSTUDY
//just to force allocations and update on both predictors
U->prediction_result = 0;
#endif
#ifdef PREDVTAGE
UpdateVtagePred (U, actual_value, (int) actual_latency);
#endif
#ifdef PREDSTRIDE
UpdateStridePred (U, actual_value, (int) actual_latency);
#endif
U->todo = 0;
}
seq_commit = seq_no;
}
void
speculativeUpdate (uint64_t seq_no, // dynamic micro-instruction # (starts at 0 and increments indefinitely)
bool eligible, // true: instruction is eligible for value prediction. false: not eligible.
uint8_t prediction_result, // 0: incorrect, 1: correct, 2: unknown (not revealed)
// Note: can assemble local and global branch history using pc, next_pc, and insn.
uint64_t
pc, uint64_t next_pc, InstClass insn, uint8_t piece,
// Note: up to 3 logical source register specifiers, up to 1 logical destination register specifier.
// 0xdeadbeef means that logical register does not exist.
// May use this information to reconstruct architectural register file state (using log. reg. and value at updatePredictor()).
uint64_t src1, uint64_t src2, uint64_t src3, uint64_t dst)
{
// the framework does not really allow to filter the predictions, so we predict every instruction
ForUpdate *U;
U = &Update[seq_no & (MAXINFLIGHT - 1)];
LastMispVT++;
if (eligible)
{
U->NbOperand =
(src1 != 0xdeadbeef) + (src2 != 0xdeadbeef) + (src3 != 0xdeadbeef);
U->todo = 1;
U->INSTTYPE = insn;
U->prediction_result = (prediction_result == 1);
if (SafeStride < (1 << 15) - 1)
SafeStride++;
if (prediction_result != 2)
{
if (prediction_result)
{
if (U->predstride)
if (SafeStride < (1 << 15) - 1)
SafeStride += 4 * (1 + (insn == loadInstClass));
}
else
{
if (U->predvtage)
LastMispVT = 0;
if (U->predstride)
SafeStride -= 1024;
}
}
}
bool isCondBr = insn == condBranchInstClass;
bool isUnCondBr = insn == uncondIndirectBranchInstClass
|| insn == uncondDirectBranchInstClass;
//path history
// just to have a longer history without (software) management
if ((isCondBr) || (isUnCondBr))
if (pc != next_pc - 4)
{
for (int i = 7; i > 0; i--)
gpath[i] = (gpath[i] << 1) ^ ((gpath[i - 1] >> 63) & 1);
gpath[0] = (gpath[0] << 1) ^ (pc >> 2);
gtargeth = (gtargeth << 1) ^ (next_pc >> 2);
}
}
void
beginPredictor (int argc_other, char **argv_other)
{
}
void
endPredictor ()
{
#ifndef LIMITSTUDY
int SIZE = 0;
SIZE = NBWAYSTR * (1 << LOGSTR) * (67 + LOGSTRIDE + TAGWIDTHSTR + WIDTHCONFIDSTR) + 16; //the SafeStride counter
printf ("STORAGE SIZE: STRIDE (%d bits)", SIZE);
int INTER = (((64 - LOGLDATA) + 2) * 3 << LOGLDATA); //the 64 bits data words - LOGLDATA implicits bits + 2 u bits
printf (" |Value array: (%d bits)", INTER);
SIZE += INTER;
INTER = BANKSIZE * NBBANK * (TAGWIDTH + (LOGLDATA + 2) + WIDTHCONFID + UWIDTH) //the VTAGE entries
+ 8 // the LastMispVT counter
+ 10; // the TICK counter
printf (" |VTAGE: (%d bits)", INTER);
SIZE += INTER;
printf (" ||| TOTAL SIZE: %d bits\n", SIZE);
#endif
}
<file_sep>/lib/bp.cc
/*
Copyright (c) 2019, North Carolina State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Author: <NAME> (<EMAIL>)
// Modified by <NAME> (<EMAIL>) to include TAGE-SC-L predictor and the ITTAGE indirect branch predictor
#include <stdio.h>
#include <inttypes.h>
#include <assert.h>
#include "cvp.h"
#include "bp.h"
#include "parameters.h"
#include "parameters.h"
bp_t::bp_t(uint64_t cb_pc_length, uint64_t cb_bhr_length,
uint64_t ib_pc_length, uint64_t ib_bhr_length,
uint64_t ras_size)
/* <NAME>: introduction of TAGE-SC-L and ITTAGE*/
: TAGESCL(new PREDICTOR())
, ITTAGE(new IPREDICTOR())
, ras(ras_size) {
// Initialize measurements.
meas_branch_n = 0;
meas_branch_m = 0;
meas_jumpdir_n = 0;
meas_jumpind_n = 0;
meas_jumpind_m = 0;
meas_jumpret_n = 0;
meas_jumpret_m = 0;
meas_notctrl_n = 0;
meas_notctrl_m = 0;
}
bp_t::~bp_t() {
}
// Returns true if instruction is a mispredicted branch.
// Also updates all branch predictor structures as applicable.
bool bp_t::predict(InstClass insn, uint64_t pc, uint64_t next_pc) {
bool taken;
bool pred_taken;
uint64_t pred_target;
bool misp;
if (insn == InstClass::condBranchInstClass) {
// CONDITIONAL BRANCH
// Determine the actual taken/not-taken outcome.
taken = (next_pc != (pc + 4));
// Make prediction.
pred_taken= TAGESCL->GetPrediction (pc);
// Determine if mispredicted or not.
misp = (pred_taken != taken);
/* <NAME>: uodate TAGE-SC-L*/
TAGESCL-> UpdatePredictor (pc , 1, taken, pred_taken, next_pc);
// Update measurements.
meas_branch_n++;
meas_branch_m += misp;
}
else if (insn == InstClass::uncondDirectBranchInstClass) {
// CALL OR JUMP DIRECT
// Target of JAL or J (rd=x0) will be available in either the fetch stage (BTB hit)
// or the pre-decode/decode stage (BTB miss), so these are not predicted.
// Never mispredicted.
misp = false;
/* <NAME>: update branch histories for TAGE-SC-L and ITTAGE */
TAGESCL->TrackOtherInst(pc , 0, true,next_pc);
ITTAGE->TrackOtherInst(pc , next_pc);
#if 0
// If the destination register is the link register (x1) or alternate link register (x5),
// then the instruction is a call instruction by software convention.
// Push the RAS in this case.
if (is_link_reg(insn.rd()))
ras.push(pc + 4);
#endif
// Update measurements.
meas_jumpdir_n++;
}
else if (insn == InstClass::uncondIndirectBranchInstClass) {
#if 0
// RISCV ISA spec, Table 2.1, explains rules for inferring a return instruction.
if (is_link_reg(insn.rs1()) && (!is_link_reg(insn.rd()) || (insn.rs1() != insn.rd()))) {
// RETURN
// Make prediction.
pred_target = ras.pop();
// Determine if mispredicted or not.
misp = (pred_target != next_pc);
// Update measurements.
meas_jumpret_n++;
if (misp) meas_jumpret_m++;
}
else {
// NOT RETURN
#endif
if (PERFECT_INDIRECT_PRED) {
misp = false;
// Update measurements.
meas_jumpind_n++;
}
else {
// Make prediction.
pred_target= ITTAGE->GetPrediction (pc);
// Determine if mispredicted or not.
misp = (pred_target != next_pc);
/* <NAME>: update ITTAGE*/
ITTAGE-> UpdatePredictor (pc , next_pc);
// Update measurements.
meas_jumpind_n++;
meas_jumpind_m += misp;
}
/* <NAME>: update history for TAGE-SC-L */
TAGESCL->TrackOtherInst(pc , 2, true,next_pc);
#if 0
}
// RISCV ISA spec, Table 2.1, explains rules for inferring a call instruction.
if (is_link_reg(insn.rd()))
ras.push(pc + 4);
#endif
}
else {
// not a control-transfer instruction
misp = (next_pc != pc + 4);
// Update measurements.
meas_notctrl_n++;
meas_notctrl_m+=misp;
}
return(misp);
}
inline bool bp_t::is_link_reg(uint64_t x) {
return((x == 1) || (x == 5));
}
#define BP_OUTPUT(str, n, m, i) \
printf("%s%10ld %10ld %5.2lf%% %5.2lf\n", (str), (n), (m), 100.0*((double)(m)/(double)(n)), 1000.0*((double)(m)/(double)(i)))
void bp_t::output() {
uint64_t num_inst = (meas_branch_n + meas_jumpdir_n + meas_jumpind_n + meas_jumpret_n + meas_notctrl_n);
uint64_t num_misp = (meas_branch_m + meas_jumpind_m + meas_jumpret_m + meas_notctrl_m);
printf("BRANCH PREDICTION MEASUREMENTS---------------------\n");
printf("Type n m mr mpki\n");
BP_OUTPUT("All ", num_inst, num_misp, num_inst);
BP_OUTPUT("Branch ", meas_branch_n, meas_branch_m, num_inst);
BP_OUTPUT("Jump: Direct ", meas_jumpdir_n, (uint64_t)0, num_inst);
BP_OUTPUT("Jump: Indirect ", meas_jumpind_n, meas_jumpind_m, num_inst);
BP_OUTPUT("Jump: Return ", meas_jumpret_n, meas_jumpret_m, num_inst);
BP_OUTPUT("Not control ", meas_notctrl_n, meas_notctrl_m, num_inst);
}
<file_sep>/lib/cvp.cc
/*
Copyright (c) 2019, North Carolina State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Author: <NAME> (<EMAIL>)
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <assert.h>
#include <string.h>
#include "cvp.h"
#include "cvp_trace_reader.h"
#include "fifo.h"
#include "cache.h"
#include "bp.h"
#include "resource_schedule.h"
#include "uarchsim.h"
#include "parameters.h"
uarchsim_t *sim;
int parseargs(int argc, char ** argv) {
int i = 1;
// read optional flags
while (i < argc)
{
if (!strcmp(argv[i], "-v"))
{
VP_ENABLE = true;
i++;
}
else if (!strcmp(argv[i], "-p"))
{
VP_PERFECT = true;
i++;
}
else if (!strcmp(argv[i], "-t"))
{
i++;
if (i < argc)
{
VP_TRACK = stoul(argv[i]);
assert(VP_TRACK < static_cast<std::underlying_type<VPTracks>::type>(VPTracks::NumTracks));
i++;
}
else
{
printf("Usage: missing track number : -t <track_number>.\n");
exit(0);
}
}
else if (!strcmp(argv[i], "-d"))
{
PERFECT_CACHE = true;
i++;
}
else if (!strcmp(argv[i], "-b"))
{
PERFECT_BRANCH_PRED = true;
i++;
}
else if (!strcmp(argv[i], "-i"))
{
PERFECT_INDIRECT_PRED = true;
i++;
}
else if (!strcmp(argv[i], "-P"))
{
PREFETCHER_ENABLE = true;
i++;
}
else if (!strcmp(argv[i], "-f"))
{
i++;
if (i < argc)
{
PIPELINE_FILL_LATENCY = atoi(argv[i]);
i++;
}
else
{
printf("Usage: missing pipeline fill latency: -f <pipeline_fill_latency>.\n");
exit(0);
}
}
else if (!strcmp(argv[i], "-M"))
{
i++;
if (i < argc)
{
NUM_LDST_LANES = atoi(argv[i]);
i++;
}
else
{
printf("Usage: missing # load/store lanes: -M <num_ldst_lanes>.\n");
exit(0);
}
}
else if (!strcmp(argv[i], "-A"))
{
i++;
if (i < argc)
{
NUM_ALU_LANES = atoi(argv[i]);
i++;
}
else
{
printf("Usage: missing # alu lanes: -A <num_alu_lanes>.\n");
exit(0);
}
}
//else if (!strcmp(argv[i], "-s")) {
// WRITE_ALLOCATE = true;
// i++;
//}
else if (!strcmp(argv[i], "-F"))
{
i++;
if (i < argc)
{
unsigned int temp1, temp2, temp3, temp4, temp5;
if (sscanf(argv[i], "%d,%d,%d,%d,%d", &temp1, &temp2, &temp3, &temp4, &temp5) == 5)
{
FETCH_WIDTH = (uint64_t)temp1;
FETCH_NUM_BRANCH = (uint64_t)temp2;
FETCH_STOP_AT_INDIRECT = (temp3 ? true : false);
FETCH_STOP_AT_TAKEN = (temp4 ? true : false);
FETCH_MODEL_ICACHE = (temp5 ? true : false);
}
else
{
printf("Usage: missing one or more fetch bundle constraints: -F <fetch_width>,<fetch_num_branch>,<fetch_stop_at_indirect>,<fetch_stop_at_taken>,<fetch_model_icache>.\n");
exit(0);
}
i++;
}
else
{
printf("Usage: missing one or more fetch bundle constraints: -F <fetch_width>,<fetch_num_branch>,<fetch_stop_at_indirect>,<fetch_stop_at_taken>,<fetch_model_icache>.\n");
exit(0);
}
}
else if (!strcmp(argv[i], "-I"))
{
i++;
if (i < argc)
{
unsigned int temp1, temp2, temp3;
if (sscanf(argv[i], "%d,%d,%d", &temp1, &temp2, &temp3) == 3)
{
IC_SIZE = (uint64_t)(1 << temp1);
IC_ASSOC = (uint64_t)temp2;
IC_BLOCKSIZE = (uint64_t)temp3;
}
else
{
printf("Usage: missing one or more I$ parameters: -I <log2_size>,<assoc>,<blocksize>.\n");
exit(0);
}
i++;
}
else
{
printf("Usage: missing I$ parameters: -I <log2_size>,<assoc>,<blocksize>.\n");
exit(0);
}
}
else if (!strcmp(argv[i], "-D"))
{
i++;
if (i < argc)
{
unsigned int temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10, temp11, temp12, temp13;
if (sscanf(argv[i], "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
&temp1, &temp2, &temp3, &temp4,
&temp5, &temp6, &temp7, &temp8,
&temp9, &temp10, &temp11, &temp12,
&temp13) == 13)
{
L1_SIZE = (uint64_t)(1 << temp1);
L1_ASSOC = (uint64_t)temp2;
L1_BLOCKSIZE = (uint64_t)temp3;
L1_LATENCY = (uint64_t)temp4;
L2_SIZE = (uint64_t)(1 << temp5);
L2_ASSOC = (uint64_t)temp6;
L2_BLOCKSIZE = (uint64_t)temp7;
L2_LATENCY = (uint64_t)temp8;
L3_SIZE = (uint64_t)(1 << temp9);
L3_ASSOC = (uint64_t)temp10;
L3_BLOCKSIZE = (uint64_t)temp11;
L3_LATENCY = (uint64_t)temp12;
MAIN_MEMORY_LATENCY = (uint64_t)temp13;
}
else
{
printf("Usage: missing one or more L1$, L2$, and L3$ parameters: -D <log2_L1_size>,<L1_assoc>,<L1_blocksize>,<L1_latency>,<log2_L2_size>,<L2_assoc>,<L2_blocksize>,<L2_latency>,<log2_L3_size>,<L3_assoc>,<L3_blocksize>,<L3_latency>,<main_memory_latency>.\n");
exit(0);
}
i++;
}
else
{
printf("Usage: missing L1$, L2$, and L3$ parameters: -D <log2_L1_size>,<L1_assoc>,<L1_blocksize>,<L1_latency>,<log2_L2_size>,<L2_assoc>,<L2_blocksize>,<L2_latency>,<log2_L3_size>,<L3_assoc>,<L3_blocksize>,<L3_latency>,<main_memory_latency>.\n");
exit(0);
}
}
else if (!strcmp(argv[i], "-w"))
{
i++;
if (i < argc)
{
WINDOW_SIZE = atoi(argv[i]);
i++;
}
else
{
printf("Usage: missing window size: -w <window_size>.\n");
exit(0);
}
}
else
{
break;
}
}
if (i < argc) {
return(i);
}
else {
printf("usage:\t%s\n\t[optional: -v to enable value prediction]\n\t[optional: -p to enable perfect value prediction (if -v also specified)]\n\t[optional: -d to enable perfect data cache]\n\t[optional: -b to enable perfect branch prediction (all branch types)]\n\t[optional: -i to enable perfect indirect-branch prediction]\n\t[optional: -P to enable stride prefetcher in L1D]\n\t[optional: -f <pipeline_fill_latency>]\n\t[optional: -M <num_ldst_lanes>\n\t[optional: -A <num_alu_lanes>\n\t[optional: -F <fetch_width>,<fetch_num_branch>,<fetch_stop_at_indirect>,<fetch_stop_at_taken>,<fetch_model_icache>]\n\t[optional: -I <log2_ic_size>,<ic_assoc>,<ic_blocksize>]\n\t[optional: -D <log2_L1_size>,<L1_assoc>,<L1_blocksize>,<L1_latency>,<log2_L2_size>,<L2_assoc>,<L2_blocksize>,<L2_latency>,<log2_L3_size>,<L3_assoc>,<L3_blocksize>,<L3_latency>,<main_memory_latency>]\n\t[optional: -w <window_size>]\n\t[REQUIRED: .gz trace file]\n\t[optional: contestant's arguments]\n", argv[0]);
exit(0);
}
}
int main(int argc, char ** argv)
{
int i = parseargs(argc, argv);
CVPTraceReader reader(argv[i]);
// Need to create simulator after parsing arguments (for global parameters).
sim = new uarchsim_t;
// Get to next (optional) argument after trace filename.
i++;
if (i < argc)
beginPredictor((argc - i), &(argv[i]));
else
beginPredictor(0, (char **)NULL);
db_t *inst = nullptr;
while (inst = reader.get_inst()) {
sim->step(inst);
delete inst;
}
endPredictor();
sim->output();
}
<file_sep>/lib/cache.h
/*
Copyright (c) 2019, North Carolina State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Author: <NAME> (<EMAIL>)
struct block_t {
bool valid;
//bool dirty; // TO DO
uint64_t tag;
uint64_t timestamp;
uint64_t lru;
};
#define IsPow2(x) (((x) & (x-1)) == 0)
#define TAG(addr) ((addr) >> (num_index_bits + num_offset_bits))
#define INDEX(addr) (((addr) >> num_offset_bits) & index_mask)
class cache_t {
private:
block_t **C;
uint64_t num_index_bits;
uint64_t num_offset_bits;
uint64_t index_mask;
uint64_t assoc;
// latency to search this cache for requested block
uint64_t latency;
// pointer to next cache level if applicable
cache_t *next_level;
// measurements
uint64_t accesses;
uint64_t pf_accesses;
uint64_t misses;
uint64_t pf_misses;
void update_lru(uint64_t index, uint64_t mru_way);
public:
cache_t(uint64_t size, uint64_t assoc, uint64_t blocksize, uint64_t latency, cache_t *next_level);
~cache_t();
uint64_t access(uint64_t cycle, bool read, uint64_t addr, bool pf = false);
bool is_hit(uint64_t cycle, uint64_t addr) const;
void stats();
};
<file_sep>/lib/uarchsim.h
/*
Copyright (c) 2019, North Carolina State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Author: <NAME> (<EMAIL>)
#include <map>
#include "spdlog/spdlog.h"
#include "spdlog/fmt/ostr.h"
#include "cvp.h"
#include "stride_prefetcher.h"
using namespace std;
#ifndef _RISCV_UARCHSIM_H
#define _RISCV_UARCHSIM_H
#define RFSIZE 65 // integer: r0-r31. fp/simd: r32-r63. flags: r64.
#define RFFLAGS 64 // flags register is r64 (65th register)
struct window_t {
uint64_t retire_cycle;
uint64_t seq_no;
uint64_t addr;
uint64_t value;
uint64_t latency;
};
struct store_queue_t {
uint64_t exec_cycle; // store's execution cycle
uint64_t ret_cycle; // store's commit cycle
};
// Class for a microarchitectural simulator.
class uarchsim_t {
private:
// Add your class member variables here to facilitate your limit study.
// register timestamps
uint64_t RF[RFSIZE];
// store queue byte timestamps
map<uint64_t, store_queue_t> SQ;
// memory block timestamps
cache_t L1;
cache_t L2;
cache_t L3;
// fetch timestamp
uint64_t fetch_cycle;
uint64_t previous_fetch_cycle = 0;
// Modeling resources: (1) finite fetch bundle, (2) finite window, and (3) finite execution lanes.
uint64_t num_fetched;
uint64_t num_fetched_branch;
fifo_t<window_t> window;
resource_schedule *alu_lanes;
resource_schedule *ldst_lanes;
// Branch predictor.
bp_t BP;
// Instruction cache.
cache_t IC;
//Prefetcher
StridePrefetcher prefetcher;
// Instruction and cycle counts for IPC.
uint64_t num_inst;
uint64_t cycle;
// CVP measurements
uint64_t num_eligible;
uint64_t num_correct;
uint64_t num_incorrect;
// stats
uint64_t num_load;
uint64_t num_load_sqmiss;
uint64_t stat_pfs_issued_to_mem = 0;
// Helper for oracle hit/miss information
uint64_t get_load_exec_cycle(db_t *inst) const;
public:
uarchsim_t();
~uarchsim_t();
//void set_funcsim(processor_t *funcsim);
void step(db_t *inst);
void output();
PredictionRequest get_prediction_req_for_track(uint64_t cycle, uint64_t seq_no, uint8_t piece, db_t *inst);
};
#endif
<file_sep>/lib/cache.cc
/*
Copyright (c) 2019, North Carolina State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Author: <NAME> (<EMAIL>)
#include <math.h>
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include "parameters.h"
#include "cache.h"
cache_t::cache_t(uint64_t size, uint64_t assoc, uint64_t blocksize, uint64_t latency, cache_t *next_level) {
uint64_t num_sets;
assert(IsPow2(blocksize));
this->num_offset_bits = log2(blocksize);
num_sets = size/(assoc*blocksize);
assert(IsPow2(num_sets));
this->num_index_bits = log2(num_sets);
this->index_mask = (num_sets - 1);
this->assoc = assoc;
C = new block_t *[num_sets];
for (uint64_t i = 0; i < num_sets; i++) {
C[i] = new block_t[assoc];
for (uint64_t j = 0; j < assoc; j++) {
C[i][j].valid = false;
C[i][j].lru = j;
}
}
this->latency = latency;
this->next_level = next_level;
accesses = 0;
misses = 0;
}
cache_t::~cache_t() {
}
bool cache_t::is_hit(uint64_t cycle, uint64_t addr) const {
uint64_t tag = TAG(addr);
uint64_t index = INDEX(addr);
for (uint64_t way = 0; way < assoc; way++) {
if (C[index][way].valid && (C[index][way].tag == tag)) {
auto avail = ((C[index][way].timestamp > (cycle + latency)) ? C[index][way].timestamp : (cycle + latency));
return (cycle + latency >= avail);
}
}
return false;
}
uint64_t cache_t::access(uint64_t cycle, bool read, uint64_t addr, bool pf) {
uint64_t avail; // return value: cycle that requested block is available
uint64_t tag = TAG(addr);
uint64_t index = INDEX(addr);
bool hit = false;
uint64_t way; // if hit, this is the corresponding way
uint64_t max_lru_ctr = 0; // for finding lru block
uint64_t victim_way; // if miss, this is the lru/victim way
accesses+=!pf;
pf_accesses += pf;
for (way = 0; way < assoc; way++)
{
if (C[index][way].valid && (C[index][way].tag == tag))
{
hit = true;
break;
}
else if (C[index][way].lru >= max_lru_ctr)
{
max_lru_ctr = C[index][way].lru;
victim_way = way;
}
}
if (hit) { // hit
// determine when the requested block will be available
avail = ((C[index][way].timestamp > (cycle + latency)) ? C[index][way].timestamp : (cycle + latency));
update_lru(index, way); // make "way" the MRU way
}
else { // miss
misses+= !pf;
pf_misses += pf;
assert(max_lru_ctr == (assoc - 1));
assert(victim_way < assoc);
// TO DO: model writebacks (evictions of dirty blocks)
// determine when the requested block will be available
avail = (next_level ? next_level->access((cycle + latency), read, addr, pf) : (cycle + latency + MAIN_MEMORY_LATENCY));
// replace the victim block with the requested block
C[index][victim_way].valid = true;
C[index][victim_way].tag = tag;
C[index][victim_way].timestamp = avail;
update_lru(index, victim_way); // make "victim_way" the MRU way
}
return(avail);
}
void cache_t::update_lru(uint64_t index, uint64_t mru_way) {
for (uint64_t way = 0; way < assoc; way++) {
if (C[index][way].lru < C[index][mru_way].lru) {
C[index][way].lru++;
assert(C[index][way].lru < assoc);
}
}
C[index][mru_way].lru = 0;
}
void cache_t::stats() {
printf("\taccesses = %lu\n", accesses);
printf("\tmisses = %lu\n", misses);
printf("\tmiss ratio = %.2f%%\n", 100.0*((double)misses/(double)accesses));
printf("\tpf accesses = %lu\n", pf_accesses);
printf("\tpf misses = %lu\n", pf_misses);
printf("\tpf miss ratio = %.2f%%\n", 100.0*((double)pf_misses/(double)pf_accesses));
}
<file_sep>/lib/cvp_trace_reader.h
// CVP1 Trace Reader
// Author: <NAME> (<EMAIL>)
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org>
This project relies on https://www.cs.unc.edu/Research/compgeom/gzstream/ (LGPL) to stream from compressed traces.
For ease of use, gzstream.h and gzstream.C are provided with minor modifications (include paths) with the reader.
*/
// Compilation : Don't forget to add gzstream.C in the source list and to link with zlib (-lz).
//
// Usage : CVPTraceReader reader("./my_trace.tar.gz")
// while(reader.readInstr())
// reader.mInstr.printInstr();
// ...
// Note that this is an exemple file (that was used for CVP).
// Given the trace format below, you can write your own trace reader that
// populates the instruction format in the way you like.
//
// Trace Format :
// Inst PC - 8 bytes
// Inst Type - 1 byte
// If load/storeInst
// Effective Address - 8 bytes
// Access Size (one reg) - 1 byte
// If branch
// Taken - 1 byte
// If Taken
// Target - 8 bytes
// Num Input Regs - 1 byte
// Input Reg Names - 1 byte each
// Num Output Regs - 1 byte
// Output Reg Names - 1 byte each
// Output Reg Values
// If INT (0 to 31) or FLAG (64) - 8 bytes each
// If SIMD (32 to 63) - 16 bytes each
#include <fstream>
#include <iostream>
#include <vector>
#include <cassert>
#include "./gzstream.h"
#if 0
enum InstClass : uint8_t
{
aluInstClass = 0,
loadInstClass = 1,
storeInstClass = 2,
condBranchInstClass = 3,
uncondDirectBranchInstClass = 4,
uncondIndirectBranchInstClass = 5,
fpInstClass = 6,
slowAluInstClass = 7,
undefInstClass = 8
};
#endif
// This structure is used by CVP1's simulator.
// Adapt for your own needs.
struct db_operand_t
{
bool valid;
bool is_int;
uint64_t log_reg;
uint64_t value;
void print() const
{
std::cout << " (int: " << is_int << ", idx: " << log_reg << " val: " << std::hex << value << std::dec << ") ";
}
};
// This structure is used by CVP1's simulator.
// Adapt for your own needs.
struct db_t
{
uint8_t insn;
uint64_t pc;
uint64_t next_pc;
db_operand_t A;
db_operand_t B;
db_operand_t C;
db_operand_t D;
bool is_load;
bool is_store;
uint64_t addr;
uint64_t size;
void printInst() const
{
static constexpr const char * cInfo[] = {"aluOp", "loadOp", "stOp", "condBrOp", "uncondDirBrOp", "uncondIndBrOp", "fpOp", "slowAluOp" };
std::cout << "[PC: 0x" << std::hex << pc <<std::dec << " type: " << cInfo[insn];
if(insn == InstClass::loadInstClass || insn == InstClass::storeInstClass)
{
assert(is_load || is_store);
std::cout << " ea: 0x" << std::hex << addr << std::dec << " size: " << size;
}
if(insn == InstClass::condBranchInstClass || insn == InstClass::uncondDirectBranchInstClass || insn == InstClass::uncondIndirectBranchInstClass)
std::cout << " ( tkn:" << (next_pc != pc + 4) << " tar: 0x" << std::hex << next_pc << ") " << std::dec;
if(A.valid)
{
std::cout << " 1st input: ";
A.print();
}
if(B.valid)
{
std::cout << "2nd input: ";
B.print();
}
if(C.valid)
{
std::cout << "3rd input: ";
C.print();
}
if(D.valid)
{
std::cout << " output: ";
D.print();
}
std::cout << " ]" << std::endl;
std::fflush(stdout);
}
};
// INT registers are registers 0 to 31. SIMD/FP registers are registers 32 to 63. Flag register is register 64
enum Offset
{
vecOffset = 32,
ccOffset = 64
};
// Trace reader class.
// Format assumes that instructions have at most three inputs and at most one input.
// If the trace contains an instruction that has more than three inputs, they are ignored.
// If the trace contains an instruction that has more than one outputs, one instruction object will be created for each output,
// For instance, for a multiply, two objects with same PC will be created through two subsequent calls to get_inst(). Each will have the same
// inputs, but one will have the low part of the product as output, and one will have the high part of the product as output.
// Other instructions subject to this are (list not exhaustive): load pair and vector inststructions.
struct CVPTraceReader
{
struct Instr
{
uint64_t mPc;
uint8_t mType; // Type is InstClass
bool mTaken;
uint64_t mTarget;
uint64_t mEffAddr;
uint8_t mMemSize; // In bytes
uint8_t mNumInRegs;
std::vector<uint8_t> mInRegs;
uint8_t mNumOutRegs;
std::vector<uint8_t> mOutRegs;
std::vector<uint64_t> mOutRegsValues;
Instr()
{
reset();
}
void reset()
{
mPc = mTarget = 0xdeadbeef;
mEffAddr = 0xdeadbeef;
mMemSize = 0;
mType = undefInstClass;
mTaken = false;
mNumInRegs = mNumOutRegs = 0;
mInRegs.clear();
mOutRegs.clear();
mOutRegsValues.clear();
}
void printInstr()
{
static constexpr const char * cInfo[] = {"aluOp", "loadOp", "stOp", "condBrOp", "uncondDirBrOp", "uncondIndBrOp", "fpOp", "slowAluOp" };
std::cout << "[PC: 0x" << std::hex << mPc << std::dec << " type: " << cInfo[mType];
if(mType == InstClass::loadInstClass || mType == InstClass::storeInstClass)
std::cout << " ea: 0x" << std::hex << mEffAddr << std::dec << " size: " << (uint64_t) mMemSize;
if(mType == InstClass::condBranchInstClass || mType == InstClass::uncondDirectBranchInstClass || mType == InstClass::uncondIndirectBranchInstClass)
std::cout << " ( tkn:" << mTaken << " tar: 0x" << std::hex << mTarget << ") ";
std::cout << std::dec << " InRegs : { ";
for(unsigned elt : mInRegs)
{
std::cout << elt << " ";
}
std::cout << " } OutRegs : { ";
for(unsigned i = 0, j = 0; i < mOutRegs.size(); i++)
{
if(mOutRegs[i] >= Offset::vecOffset && mOutRegs[i] != Offset::ccOffset)
{
assert(j+1 < mOutRegsValues.size());
std::cout << std::dec << (unsigned) mOutRegs[i] << std::hex << " (hi:" << mOutRegsValues[j+1] << " lo:" << mOutRegsValues[j] << ") ";
j += 2;
}
else
{
assert(j < mOutRegsValues.size());
std::cout << std::dec << (unsigned) mOutRegs[i] << std::hex << " (" << mOutRegsValues[j++] << ") ";
}
}
std::cout << ") ]" << std::endl;
std::fflush(stdout);
}
};
gz::igzstream * dpressed_input;
// Buffer to hold trace instruction information
Instr mInstr;
// There are bookkeeping variables for trace instructions that necessitate the creation of several objects.
// Specifically, load pair yields two objects with different register outputs, but SIMD instructions also yield
// multiple objects but they have the same register output, although one has the low 64-bit and one has the high 64-bit.
// Thus, for load pair, first piece will have mCrackRegIdx 0 (first output of trace instruction) and second will have mCrackRegIdx 1
// (second output of trace instruction). However, in both cases, since outputs are 64-bit, mCrackValIdx will remain 0.
// Conversely, both pieces of a SIMD instruction will have mCrackRegIdx 0 (since SIMD instruction has a single 128-bit output), but first piece
// will have mCrackValIdx 0 (low 64-bit) and second piece will have mCrackValIdx 1 (high 64-bit).
uint8_t mCrackRegIdx;
uint8_t mCrackValIdx;
// How many pieces left to generate for the current trace instruction being processed.
uint8_t mRemainingPieces;
// Inverse of memory size multiplier for each piece. E.g., a 128-bit access will have size 16, and each piece will have size 8 (16 * 1/2).
uint8_t mSizeFactor;
// Number of instructions processed so far.
uint64_t nInstr;
// This simply tracks how many lanes one SIMD register have been processed.
// In this case, since SIMD is 128 bits and pieces output 64 bits, if it is pair and we are creating an instruction object from a trace instruction, this means that
// the output of the instruction object will contain the low order bits of the SIMD register.
// If it is odd, it means that it will contain the high order bits of the SIMD register.
uint8_t start_fp_reg;
// Note that there is no check for trace existence, so modify to suit your needs.
CVPTraceReader(const char * trace_name)
{
dpressed_input = new gz::igzstream();
dpressed_input->open(trace_name, std::ios_base::in | std::ios_base::binary);
mCrackRegIdx = mCrackValIdx = mRemainingPieces = mSizeFactor = nInstr = start_fp_reg = 0;
}
~CVPTraceReader()
{
if(dpressed_input)
delete dpressed_input;
std::cout << " Read " << nInstr << " instrs " << std::endl;
}
// This is the main API function
// There is no specific reason to call the other functions from without this file.
// Idiom is : while(instr = get_inst())
// ... process instr
db_t *get_inst()
{
// If we are creating several pieces from a single trace instructions and some are left to create,
// mRemainingPieces will be != 0
if(mRemainingPieces)
return populateNewInstr();
// If there is a single piece to create
else if(readInstr())
return populateNewInstr();
// If the trace is done
else
return nullptr;
}
// Creates a new object and populate it with trace information.
// Subsequent calls to populateNewInstr() will take care of creating multiple pieces for a trace instruction
// that has several outputs or 128-bit output.
// Number of calls is decided by mRemainingPieces from get_inst().
db_t *populateNewInstr()
{
db_t * inst = new db_t();
inst->insn = mInstr.mType;
inst->pc = mInstr.mPc;
inst->next_pc = mInstr.mTarget;
if(mInstr.mNumInRegs >= 1)
{
inst->A.valid = true;
inst->A.is_int = mInstr.mInRegs.at(0) < Offset::vecOffset || mInstr.mInRegs[0] == Offset::ccOffset;
inst->A.log_reg = mInstr.mInRegs[0];
inst->A.value = 0xdeadbeef;
}
else
inst->A.valid = false;
if(mInstr.mNumInRegs >= 2)
{
inst->B.valid = true;
inst->B.is_int = mInstr.mInRegs.at(1) < Offset::vecOffset || mInstr.mInRegs[1] == Offset::ccOffset;
inst->B.log_reg = mInstr.mInRegs[1];
inst->B.value = 0xdeadbeef;
}
else
inst->B.valid = false;
if(mInstr.mNumInRegs >= 3)
{
inst->C.valid = true;
inst->C.is_int = mInstr.mInRegs.at(2) < Offset::vecOffset || mInstr.mInRegs[2] == Offset::ccOffset;
inst->C.log_reg = mInstr.mInRegs[2];
inst->C.value = 0xdeadbeef;
}
else
inst->C.valid = false;
// We'll ignore that some ARM instructions have more than 3 inputs
// assert(mInstr.mNumInRegs <= 3);
if(mInstr.mNumOutRegs >= 1)
{
inst->D.valid = true;
// Flag register is considered to be INT
inst->D.is_int = mInstr.mOutRegs.at(mCrackRegIdx) < Offset::vecOffset || mInstr.mOutRegs.at(mCrackRegIdx) == Offset::ccOffset;
inst->D.log_reg = mInstr.mOutRegs[mCrackRegIdx];
inst->D.value = mInstr.mOutRegsValues.at(mCrackValIdx);
// if SIMD register, we processed one more 64-bit lane.
if(!inst->D.is_int)
start_fp_reg++;
else
start_fp_reg = 0;
}
else
{
inst->D.valid = false;
start_fp_reg = 0;
}
inst->is_load = mInstr.mType == InstClass::loadInstClass;
inst->is_store = mInstr.mType == InstClass::storeInstClass;
inst->addr = mInstr.mEffAddr + ((mSizeFactor - mRemainingPieces) * 4);
inst->size = std::max(1, mInstr.mMemSize / mSizeFactor);
assert(inst->size || !(inst->is_load || inst->is_store));
assert(mRemainingPieces != 0);
// At this point, if mRemainingPieces is 0, the next statements will have no effect.
mRemainingPieces--;
// If there are more output registers to be processed and they are SIMD
if(mInstr.mNumOutRegs > mCrackRegIdx && mInstr.mOutRegs.at(mCrackRegIdx) >= Offset::vecOffset && mInstr.mOutRegs[mCrackRegIdx] != Offset::ccOffset)
{
// Next output value is in the next 64-bit lane
mCrackValIdx++;
// If we processed the high-order bits of the current SIMD register, the next output is a different register
if(start_fp_reg % 2 == 0)
mCrackRegIdx++;
}
// If there are more output INT registers, go to next value and next register name
else
{
mCrackValIdx++;
mCrackRegIdx++;
}
return inst;
}
// Read bytes from the trace and populate a buffer object.
// Returns true if something was read from the trace, false if we the trace is over.
bool readInstr()
{
// Trace Format :
// Inst PC - 8 bytes
// Inst Type - 1 byte
// If load/storeInst
// Effective Address - 8 bytes
// Access Size (one reg) - 1 byte
// If branch
// Taken - 1 byte
// If Taken
// Target - 8 bytes
// Num Input Regs - 1 byte
// Input Reg Names - 1 byte each
// Num Output Regs - 1 byte
// Output Reg Names - 1 byte each
// Output Reg Values
// If INT (0 to 31) or FLAG (64) - 8 bytes each
// If SIMD (32 to 63) - 16 bytes each
mInstr.reset();
start_fp_reg = 0;
dpressed_input->read((char*) &mInstr.mPc, sizeof(mInstr.mPc));
if(dpressed_input->eof())
return false;
mRemainingPieces = 1;
mSizeFactor = 1;
mCrackRegIdx = 0;
mCrackValIdx = 0;
mInstr.mTarget = mInstr.mPc + 4;
dpressed_input->read((char*) &mInstr.mType, sizeof(mInstr.mType));
assert(mInstr.mType != undefInstClass);
if(mInstr.mType == InstClass::loadInstClass || mInstr.mType == InstClass::storeInstClass)
{
dpressed_input->read((char*) &mInstr.mEffAddr, sizeof(mInstr.mEffAddr));
dpressed_input->read((char*) &mInstr.mMemSize, sizeof(mInstr.mMemSize));
}
if(mInstr.mType == InstClass::condBranchInstClass || mInstr.mType == InstClass::uncondDirectBranchInstClass || mInstr.mType == InstClass::uncondIndirectBranchInstClass)
{
dpressed_input->read((char*) &mInstr.mTaken, sizeof(mInstr.mTaken));
if(mInstr.mTaken)
dpressed_input->read((char*) &mInstr.mTarget, sizeof(mInstr.mTarget));
}
dpressed_input->read((char*) &mInstr.mNumInRegs, sizeof(mInstr.mNumInRegs));
for(auto i = 0; i != mInstr.mNumInRegs; i++)
{
uint8_t inReg;
dpressed_input->read((char*) &inReg, sizeof(inReg));
mInstr.mInRegs.push_back(inReg);
}
dpressed_input->read((char*) &mInstr.mNumOutRegs, sizeof(mInstr.mNumOutRegs));
mRemainingPieces = std::max(mRemainingPieces, mInstr.mNumOutRegs);
for(auto i = 0; i != mInstr.mNumOutRegs; i++)
{
uint8_t outReg;
dpressed_input->read((char*) &outReg, sizeof(outReg));
mInstr.mOutRegs.push_back(outReg);
}
for(auto i = 0; i != mInstr.mNumOutRegs; i++)
{
uint64_t val;
dpressed_input->read((char*) &val, sizeof(val));
mInstr.mOutRegsValues.push_back(val);
if(mInstr.mOutRegs[i] >= Offset::vecOffset && mInstr.mOutRegs[i] != Offset::ccOffset)
{
dpressed_input->read((char*) &val, sizeof(val));
mInstr.mOutRegsValues.push_back(val);
if(val != 0)
mRemainingPieces++;
}
}
// Memsize has to be adjusted as it is giving only the access size for one register.
mInstr.mMemSize = mInstr.mMemSize * std::max(1lu, (long unsigned) mInstr.mNumOutRegs);
mSizeFactor = mRemainingPieces;
// Trace INT instructions with 0 outputs are generally CMP, so we mark them as producing the flag register
// The trace does not have the value of the flag register, though
if(mInstr.mType == aluInstClass && mInstr.mOutRegs.size() == 0)
{
mInstr.mOutRegs.push_back(Offset::ccOffset);
mInstr.mOutRegsValues.push_back(0xdeadbeef);
mInstr.mNumOutRegs++;
}
else if(mInstr.mType == condBranchInstClass && mInstr.mInRegs.size() == 0)
{
mInstr.mInRegs.push_back(Offset::ccOffset);
mInstr.mNumInRegs++;
}
nInstr++;
if(nInstr % 100000 == 0)
std::cout << nInstr << " instrs " << std::endl;
return true;
}
};
<file_sep>/lib/stride_prefetcher.h
#pragma once
#include <cassert>
#include <deque>
#include <array>
#include <algorithm>
#define DEF_ENUM(ENUM, NAME) _DEF_ENUM(ENUM, NAME)
#define _DEF_ENUM(ENUM, NAME) \
case ENUM::NAME: \
stream << #NAME ; \
break;
//Ref: Effective Hardware-Based Data Prefetching for High-Performance Processors
// https://ieeexplore.ieee.org/document/381947/
struct PrefetchTrainingInfo
{
uint64_t pc;
uint64_t address;
uint64_t size;
bool miss;
friend std::ostream &operator<<(std::ostream &stream, const PrefetchTrainingInfo &info)
{
stream << "PC: "<< std::hex << info.pc << " Address: "<< std::hex << info.address << " Size: "<< std::hex << info.size << " Miss? " << info.miss;
return stream;
}
};
enum class PrefetcherState
{
Invalid,
Initial,
Transient,
SteadyState,
NoPrediction,
NumPrefetcherStates
};
static std::ostream& operator<<(std::ostream& stream, const PrefetcherState& s)
{
switch(s){
DEF_ENUM(PrefetcherState, Invalid)
DEF_ENUM(PrefetcherState, Initial)
DEF_ENUM(PrefetcherState, Transient)
DEF_ENUM(PrefetcherState, SteadyState)
DEF_ENUM(PrefetcherState, NoPrediction)
};
return stream;
}
constexpr uint64_t NUM_RPT_ENTRIES = 1024;
constexpr uint64_t PREFETCH_MULTIPLIER = 2; // 2 because when we lookahead, we are 1 behind, so need next(next(access))
constexpr int PF_QUEUE_SIZE = 32;
constexpr uint64_t CACHE_LINE_MASK = ~63lu;
constexpr uint64_t PF_MUST_ISSUE_BEFORE_CYCLES = 8;
struct RPTEntry
{
PrefetcherState state = PrefetcherState::Invalid;
uint64_t tag = 0xdeadbeef;
uint64_t prev_address = 0xdeadbeef;
uint64_t current_address = 0xdeadbeef;
int64_t stride = -1;
uint64_t lru= 0;
uint64_t index = -1;
RPTEntry() =default;
RPTEntry(PrefetcherState st_, uint64_t t_ , uint64_t p_ , uint64_t c_ , int64_t s_, uint64_t l_, uint64_t i_)
:state(st_)
,tag(t_)
,prev_address(p_)
,current_address(c_)
,stride(s_)
,lru(l_)
,index(i_)
{}
friend std::ostream& operator<<(std::ostream& stream, const RPTEntry& e)
{
stream << "Index:" <<std::hex << e.index << " State " << e.state << " Tag: " << std::hex << e.tag << " Prev: " << std::hex << e.prev_address << " Cur: " << std::hex << e.current_address << " Stride: " << std::hex << e.stride << " LRU: " << e.lru;
return stream;
}
};
enum class CacheLevel
{
Invalid,
L1,
L2,
L3
};
struct Prefetch
{
explicit Prefetch(uint64_t a_, uint64_t cycle)
: address(a_)
, cycle_generated(cycle)
{}
Prefetch() = default;
friend std::ostream &operator<<(std::ostream &stream, const Prefetch& pf)
{
stream << "[PF: Address: "<< std::hex << pf.address << std::dec << ", cyclegen: " << pf.cycle_generated << "]";
return stream;
}
uint64_t address = 0xdeadbeef;
uint64_t cycle_generated = ~0lu;
//CacheLevel level;
};
class StridePrefetcher
{
public:
void init(const uint64_t n)
{
for(auto i = 0; i < n; i++)
{
//Initialize LRU
rpt[i].index = i;
rpt[i].lru = i;
}
//Clear queue of generated prefetches
queue.clear();
}
StridePrefetcher()
{
init(NUM_RPT_ENTRIES);
}
uint64_t victim_way()
{
auto entry = std::find_if(rpt.begin(), rpt.end(), [](RPTEntry& e){ return !e.lru; });
assert((entry != rpt.end()) && "Must find a valid victim way ");
spdlog::debug("Prefetch: Found victim entry : {}", *entry);
return entry->index;
}
void update_lru(uint64_t index)
{
spdlog::debug("Updating LRU Index: {}", index);
auto& lru_way = rpt[index];
std::for_each(rpt.begin(), rpt.end(), [&lru_way](RPTEntry &e) { if(e.lru > lru_way.lru){ --e.lru;} });
lru_way.lru = (NUM_RPT_ENTRIES - 1);
}
// Prefetches will be generated when the load is fetched as in "Effective Hardware-Based Data Prefetching for High-Performance Processors"
// However because we train immediately, there is no need for a count variable.
void lookahead(uint64_t la_pc, uint64_t cycle)
{
auto entry = std::find_if(rpt.begin(), rpt.end(), [la_pc](RPTEntry& e){ return e.tag == la_pc; });
if(entry == rpt.end())
{
return;
}
else if(entry->state == PrefetcherState::SteadyState)
{
generate(*entry, cycle);
}
}
void train(const PrefetchTrainingInfo & info)
{
spdlog::debug("Prefetcher: Training on LD {}", info);
auto entry = std::find_if(rpt.begin(), rpt.end(), [&info](RPTEntry& e){ return e.tag == info.pc; });
if(entry == rpt.end())
{
//Establish a new entry
auto victim_index = victim_way();
auto& victim_entry = rpt[victim_index];
victim_entry.state = PrefetcherState::Initial;
victim_entry.tag = info.pc;
victim_entry.prev_address = 0xdeadbeef;
victim_entry.current_address = info.address;
victim_entry.stride = 0;
spdlog::debug("Prefetcher: Overwriting entry now in Initial STate : {}", victim_entry);
update_lru(victim_index);
}
else
{
switch(entry->state){
case PrefetcherState::Initial:
{
int64_t stride = info.address - entry->current_address;
if (stride == entry->stride)
{
entry->state = PrefetcherState::SteadyState;
entry->prev_address = entry->current_address;
entry->current_address = info.address;
spdlog::debug("Prefetcher: Initial->SteadyState: {}", *entry);
}else{
entry->stride = stride;
entry->state = PrefetcherState::Transient;
entry->prev_address = entry->current_address;
entry->current_address = info.address;
spdlog::debug("Prefetcher: Initial->Transient: {}", *entry);
}
}
break;
case PrefetcherState::Transient:
{
int64_t stride = info.address - entry->current_address;
if (stride == entry->stride)
{
entry->state = PrefetcherState::SteadyState;
entry->prev_address = entry->current_address;
entry->current_address = info.address;
spdlog::debug("Prefetcher: Transient->SteadyState: {}", *entry);
}
else
{
entry->state = PrefetcherState::NoPrediction;
entry->stride = stride;
entry->prev_address = entry->current_address;
entry->current_address = info.address;
spdlog::debug("Prefetcher: Transient->NoPrediction: {}", *entry);
}
}
break;
case PrefetcherState::SteadyState:
{
int64_t stride = info.address - entry->current_address;
if (stride == entry->stride)
{
entry->state = PrefetcherState::SteadyState;
entry->prev_address = entry->current_address;
entry->current_address = info.address;
}else{
entry->state = PrefetcherState::Initial;
entry->prev_address = entry->current_address;
entry->current_address = info.address;
spdlog::debug("Prefetcher: SteadyState->Initial: {}", *entry);
}
}
break;
case PrefetcherState::NoPrediction:
{
int64_t stride = info.address - entry->current_address;
if (stride == entry->stride)
{
entry->state = PrefetcherState::Transient;
entry->prev_address = entry->current_address;
entry->current_address = info.address;
spdlog::debug("Prefetcher: NoPrediction->Transient: {}", *entry);
}
else
{
entry->state = PrefetcherState::NoPrediction;
entry->stride = stride;
entry->prev_address = entry->current_address;
entry->current_address = info.address;
spdlog::debug("Prefetcher: NoPrediction->NoPrediction: {}", *entry);
}
}
break;
case PrefetcherState::Invalid:
{
assert(false && "Unpexted state");
}
break;
};
if(entry->stride != 0)
{
// Let entries with stride 0 age out
update_lru(entry->index);
}
}
//Update stats
++stat_trainings;
}
void generate(RPTEntry& entry, uint64_t cycle)
{
if(entry.stride == 0)
{
++stat_stride_zero;
return;
}
Prefetch pf{entry.current_address + entry.stride * PREFETCH_MULTIPLIER, cycle};
spdlog::debug("Prefetcher: Queuing a new prefetch: {} Entry {}", pf, entry);
auto it = std::find_if(queue.begin(), queue.end(), [&](const Prefetch & qpf)
{
return (qpf.address & CACHE_LINE_MASK) == (pf.address & CACHE_LINE_MASK);
});
if(it == queue.end())
{
queue.push_back(pf);
// Make extra sure PF are sorted by generation order from oldest to youngest
std::sort(queue.begin(), queue.end(), [](const Prefetch & lhs, const Prefetch & rhs)
{
return lhs.cycle_generated < rhs.cycle_generated;
});
++stat_generated;
}
else
{
spdlog::debug("Prefetcher: Dropping pf: {} because already in pf queue", pf);
++stat_duplicate_pf_filtered;
}
}
bool issue(Prefetch& p, uint64_t cycle)
{
while(!queue.empty() && (queue.front().cycle_generated + PF_MUST_ISSUE_BEFORE_CYCLES) < cycle)
{
spdlog::debug("Dropping pf because too old (created at cycle {}, current fetch cycle {})", queue.front().cycle_generated, cycle);
++stat_dropped_untimely_pf;
queue.pop_front();
}
if(!queue.empty())
{
p = queue.front();
if(p.cycle_generated <= cycle)
{
queue.pop_front();
++stat_issued;
return true;
}
spdlog::debug("Giving up for now because not created yet (created at cycle {}, current fetch cycle {})", p.cycle_generated, cycle);
return false;
}
return false;
}
void put_back(const Prefetch & p)
{
++stat_put_back;
queue.push_front(p);
}
uint64_t get_oldest_pf_cycle() const
{
if(queue.empty())
{
return MAX_CYCLE;
}
else
{
return queue.front().cycle_generated;
}
}
void print_stats()
{
std::cout << "Num Trainings :" << std::dec << stat_trainings <<std::endl;
std::cout << "Num Prefetches generated :" << stat_generated << std::endl;
std::cout << "Num Prefetches issued :" << stat_issued << std::endl;
std::cout << "Num Prefetches filtered by PF queue :" << stat_duplicate_pf_filtered << std::endl;
std::cout << "Num untimely prefetches dropped from PF queue :" << stat_dropped_untimely_pf << std::endl;
std::cout << "Num prefetches not issued LDST contention :" << stat_put_back << std::endl;
std::cout << "Num prefetches not issued stride 0 :" << stat_stride_zero << std::endl;
}
private:
std::array<RPTEntry, NUM_RPT_ENTRIES> rpt;
uint64_t lru_info;
//Queue to store generated prefetches
std::deque<Prefetch> queue;
//Stats
uint64_t stat_trainings = 0;
uint64_t stat_generated = 0;
uint64_t stat_issued = 0;
uint64_t stat_duplicate_pf_filtered = 0;
uint64_t stat_dropped_untimely_pf = 0;
uint64_t stat_put_back = 0;
uint64_t stat_stride_zero = 0;
};
<file_sep>/lib/Makefile
# /*
#
# Copyright (c) 2019, North Carolina State University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#
# 3. The names “North Carolina State University”, “NCSU” and any trade-name, personal name,
# trademark, trade device, service mark, symbol, image, icon, or any abbreviation, contraction or
# simulation thereof owned by North Carolina State University must not be used to endorse or promote products derived from this software without prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# */
#
# // Author: <NAME> (<EMAIL>)
CC = g++
OPT = -O3
TOP = ..
INC = -I$(TOP) -I$(TOP)/lib
LIBS =
DEFINES = -DGZSTREAM_NAMESPACE=gz
FLAGS = -std=c++11 $(INC) $(LIBS) $(OPT) $(DEFINES)
ifeq ($(DEBUG), 1)
CC += -ggdb3
endif
OBJ = cvp.o parameters.o uarchsim.o cache.o bp.o resource_schedule.o gzstream.o
DEPS = $(TOP)/cvp.h cvp_trace_reader.h fifo.h parameters.h uarchsim.h cache.h bp.h resource_schedule.h gzstream.h
all: libcvp.a
libcvp.a: $(OBJ)
ar r $@ $^
%.o: %.cc $(DEPS)
$(CC) $(FLAGS) -c -o $@ $<
.PHONY: clean
clean:
rm -f *.o libcvp.a
|
5d0a0e8fa6e66b7a227e060b93a6bd0b78c2d084
|
[
"Markdown",
"Makefile",
"C++"
] | 18 |
Markdown
|
getziadz/CVP
|
2e19be02ec3591cf2c5fef4947b4a3c772b5f9b1
|
9b6f4e2c23f0695581ee40fbe28063a513671c52
|
refs/heads/master
|
<repo_name>hungryangie/fhquiz<file_sep>/app/controllers/notes_controller.rb
class NotesController < ApplicationController
def index
@note = Note.order("RANDOM()").first
end
def new
@note = Note.new
end
def create
Note.create(note_params)
redirect_to root_path
end
private
def note_params
params.require(:note).permit(:message, :name)
end
end
|
b0d0295e9bf49cfc7833f40a48de698906efd67c
|
[
"Ruby"
] | 1 |
Ruby
|
hungryangie/fhquiz
|
0d9affe3f6902cf17c17e94dfec42edba696aa26
|
bd1757ec1a199c1198cb4f9288b0938907641b9d
|
refs/heads/master
|
<repo_name>derekdileo/java-practice<file_sep>/src/Parenthesis.java
/*
* "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing."
* Write a method that, given a sentence like the one above,
* along with the position of an opening parenthesis,
* finds the corresponding closing parenthesis.
* */
public class Parenthesis {
// String variable to keep test clean
public static String validString1 = "(Max)";
public static String invalidString1 = "(Max";
public static String validString2 = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing.";
public static String invalidString2 = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing.";
public static void main(String[] args) {
// Short Test
System.out.println(findParen(0, validString1) == 4);
System.out.println(findParen(0, invalidString1) == -1);
// Long Test
System.out.println(findParen(10, validString2) == 79);
System.out.println(findParen(10, invalidString2) == -1);
}
// As method traverses string, a counter increments with each traversal
// Second counter to track open and closed parentheses. When counter == 0, index is found. Return first counter
public static int findParen(int indexOpen, String str) {
int count = 0;
for(int i = indexOpen; i < str.length(); i++) {
if(str.charAt(i) == '(') {
count++;
}
if(str.charAt(i) == ')') {
count--;
if(count == 0) {
return i;
}
}
}
return -1;
}
}
|
e4cccfd0a53ffd3cbb5061cde048d18685fda146
|
[
"Java"
] | 1 |
Java
|
derekdileo/java-practice
|
f026cc07d97109882664095d9f955a2c84cc2de4
|
d01681220e2e7dc1adebfb28112e0f499d8ea0f8
|
refs/heads/master
|
<repo_name>ottenokLeshi/ya-first<file_sep>/js/script.js
const lecturers = require('./lecturers.js');
const $ = require('jquery');
require('../css/normalize.css');
require('../css/common.blocks/header.css');
require('../css/common.blocks/school-select.css');
require('../css/common.blocks/schedule.css');
require('../css/common.blocks/schedule-popup.css');
$(document).ready(function(){
const $lecturersLinks = $(".schedule-item__lecturer").find("a");
const $schoolBoxes = $(".school-select__input");
const $allLinks = $(".schedule-item__link_notavail, .schedule-item__lecturer");
const $popup = $(".schedule-popup");
const $popupCloseButton = $(".popup_close_yes");
const $popupLecturer = $(".schedule-popup__lecturer");
const $popupDescription = $(".schedule-popup__description");
const $popupImg = $(".schedule-popup__img");
setDefaulToLinks($allLinks);
setPopupListeners($popup, $popupCloseButton);
setLinksListeners($popup, $lecturersLinks, {
$popupLecturer,
$popupDescription,
$popupImg
});
setListenersToSchoolNames($schoolBoxes);
})
/*
* Запрещение всплытия при нажатии на пустую ссылку
*
* @param {Object} $allLinks - Массив ссылок
*
*/
const setDefaulToLinks = function($allLinks) {
$allLinks.on('click', function(event) {
event.preventDefault();
})
};
/**
* Функция, проверяющая, скрыт ли блок
*
* @param {Object} $block - Элемент DOM
*
*/
const blockIsHidden = function($block){
return $($block).hasClass("schedule-item_hidden");
}
/**
* Функция, скрывающая блок
*
* @param {Object} $block - Элемент DOM
*
*/
const hideBlock = function($block){
$($block).addClass("schedule-item_hidden");
};
/**
* Функция, восстанавливающая видимость блока
*
* @param {Object} $block - Элемент DOM
*
*/
const showBlock = function($block){
$($block).removeClass("schedule-item_hidden");
}
/**
* Выставление слушателей на закрытие высплывающего окна
*
* @param {Object} $popup - Элемент DOM всплывающего окна
* @param {Object} $popupCloseButton - Элемент DOM кнопки, закрывающей окно
*
*/
const setPopupListeners = function($popup, $popupCloseButton){
$popup.click(function(event){
$target = $(event.target)
if ($target.hasClass("popup_close_yes") || $target.hasClass("schedule-popup") || $target.hasClass("popup_close-icon")){
hideBlock($popup);
$("html").css("overflow", "auto");
}
});
$('')
};
/**
* Выставление слушателей на лекторов
*
* @param {Object} $popup - Элемент DOM всплывающего окна
* @param {Object} $lecturersLinks - Массив ссылок, при нажатии на который должна появляться информация о лекторе
* @param {Object} lecturerObj - Объект, хранящий элементы DOM всплывающего окна, который нужно будет заполнить
*
*/
const setLinksListeners = function($popup, $lecturersLinks, lecturerObj) {
$lecturersLinks.on('click', function(event) {
const lecturersId = $(event.target).attr("class").split(' ')[0];
setTextToPopup($popup, lecturersId, lecturerObj);
showBlock($popup);
$("html").css("overflow", "hidden");
})
};
/**
* Занесение информации о лекторе во всплывающее окно
*
* @param {Object} $popup - Элемент DOM всплывающего окна
* @param {Object} $lecturersLinks - Массив ссылок, при нажатии на который должна появляться информация о лекторе
* @param {Object} lecturerObj.$popupLecturer - Элемент DOM, в котором должно находиться имя лектора
* @param {Object} lecturerObj.$popupDescription - Элемент DOM, в котором должно быть описание лектора
* @param {Object} lecturerObj.$popupImg - Элемент DOM, в котором должно быть изображение
*
*/
const setTextToPopup = function($popup, lecturersId, lecturerObj) {
const lector = lecturers[lecturersId - 1];
const lectorName = lector.name;
const lectorDescr = lector.description;
const lectorImgSrc = lector.img_sourse;
lecturerObj.$popupLecturer.html(lectorName);
lecturerObj.$popupDescription.html(lectorDescr);
lecturerObj.$popupImg.attr("src", "img/" + lectorImgSrc);
};
/**
* Выставление слушателей для фильтрации по школам
*
* @param {Object} $schoolBoxes - Чекбоксы для школ
*
*/
const setListenersToSchoolNames = function($schoolBoxes) {
$schoolBoxes.on('click', function() {
const $checkedBoxes = $(".school-select__input:checked");
const $uncheckedBoxes = $(".school-select__input:not(:checked)");
for (let i = 0; i < $uncheckedBoxes.length; i++){
const unvisibleSchoolName = $($uncheckedBoxes[i]).attr("class").split(" ")[2];
const $unvisibleSchoolBlocks = $("." + unvisibleSchoolName).parent("li");
for (let i = 0; i < $unvisibleSchoolBlocks.length; i++){
hideBlock($($unvisibleSchoolBlocks[i]));
}
}
for (let i = 0; i < $checkedBoxes.length; i++){
const visibleSchoolName = $($checkedBoxes[i]).attr("class").split(" ")[2];
const $visibleSchoolBlocks = $("." + visibleSchoolName).parent("li");
for (let i = 0; i < $visibleSchoolBlocks.length; i++){
showBlock($($visibleSchoolBlocks[i]));
}
}
})
};
<file_sep>/README.md
# Задание 1
[gh-link](https://ottenokleshi.github.io/ya-first/)
Мы хотим узнать, насколько хорошо вы применяете на практике языки HTML и CSS и разбираетесь в особенностях работы разных браузеров. Для этого мы предлагаем вам сверстать расписание лекций проекта «Мобилизация». В качестве примера можно использовать прошлогодние данные:
* [Школа разработки интерфейсов](https://academy.yandex.ru/events/frontend/shri_msk-2016/);
* [Школа мобильной разработки](https://academy.yandex.ru/events/mobdev/msk-2016/);
* [Школа мобильного дизайна](https://academy.yandex.ru/events/design/msk-2016/).
Страница должна быть адаптирована для мобильных браузеров и работать в современных версиях Яндекс.Браузера, Google Chrome, Edge, Firefox, Safari и Opera. По возможности используйте приёмы постепенной деградации CSS.
Помимо того, как вы оформите расписание, нам важно оценить, как вы организуете код и сможете оптимизировать результат.
### В расписании нужно указать данные для всех трёх школ, а именно:
* школу, для которой читается лекция (или несколько школ для общих лекций);
* тему лекции;
* имя лектора (должна быть возможность получить дополнительную информацию о лекторе, например во всплывающем окне);
* дату и место проведения лекции.
Добавьте в программу 2–3 общие для всех школ лекции и также отобразите их в расписании. Лекции, которые уже прошли, должны быть помечены соответствующим образом. Для них должна быть доступна ссылка на материалы и видеозапись.
## Комментарий
Использовал Javascript для реализации всплывающего окна, а также для фильтрации по школам.<file_sep>/js/lecturers.js
/**
* Массив данных о лекторах
*
*/
const lecturers = [
{
id: 1,
name: "<NAME>",
description: "В Яндексе с 2014 года. Ведущий дизайнер продукта в сервисах Переводчик, Расписания и Видео.",
img_sourse: "anton_ten.jpg",
link: "https://events.yandex.ru/lib/people/8953757/"
},
{
id: 2,
name: "<NAME>",
description: "Пришёл в Яндекс в 2014 году. Дизайнер продукта в музыкальных сервисах компании, участник команды разработки Яндекс.Радио.",
img_sourse: "nikolay_vasiunin.jpg",
link: "https://events.yandex.ru/lib/people/9123538/"
},
{
id: 3,
name: "<NAME>",
description: "Пришёл в компанию дизайнером мобильных приложений в 2013-м. Три года занимался музыкальными сервисами Яндекса, сейчас руководит дизайном турецкого направления. Считает что дизайнера должна отличать любовь к людям.",
img_sourse: "sergey_kalabin.jpg",
link: "https://events.yandex.ru/lib/people/9295914/"
},
{
id: 4,
name: "<NAME>",
description: "Профессионально занимается дизайном с 2009 года. В 2010 году переключился на работу исключительно над интерфейсами, по большей части мобильными. В Яндекс пришёл в 2011 году. Участвовал в создании разных продуктов Поиска, Диска, Фоток и Музыки для всех популярных платформ.",
img_sourse: "sergey_tomilov.jpg",
link: "https://events.yandex.ru/lib/people/3530628/"
},
{
id: 5,
name: "<NAME>",
description: "Дизайнер мобильных продуктов. До прихода в компанию занималась интерфейсами мобильных игр. В Яндексе делает Браузер под все платформы. Также успела поработать над экспериментальными голосовыми интерфейсами и мобильной версией главной страницы Яндекса.",
img_sourse: "daria_starizina.jpg",
link: "https://events.yandex.ru/lib/people/9664312/"
},
{
id: 6,
name: "<NAME>",
description: "<NAME> is a product designer. “I like to create and work on products that have a positive impact in the world. The thing that attracts me most in doing what I do at Framer, and did before at other companies, is changing the way a lot of people work, live and consume on a daily basis with just the push of a button.",
img_sourse: "rijshouwer_krijn.jpg",
link: "https://events.yandex.ru/lib/people/9664406/"
},
{
id: 7,
name: "<NAME>",
description: "<NAME> is a software developer. “I am a creative software developer with experience working on a variety of projects, from small prototypes to large apps for some well-known Dutch clients.”",
img_sourse: "treub_jonas.jpg",
link: "https://events.yandex.ru/lib/people/9664416/"
},
{
id: 8,
name: "<NAME>",
description: "В конце 2013 года команда сервиса Яндекс.Музыка начала разработку новой версии. Новой получилась не только «шкурка», то есть дизайн, но и сами возможности. Мы переосмыслили поведение пользователей на сайте и в приложении и иначе оценили потребность людей в новой музыке. В результате этого получилась нынешняя версия music.yandex.ru и её мобильные клиенты. В докладе я расскажу о том, как шёл процесс переосмысления, почему мы сделали именно так, как сделали, и что из этого всего вышло.",
img_sourse: "andrey_gevak.jpg",
link: "https://events.yandex.ru/lib/people/664322/"
},
{
id: 9,
name: "<NAME>",
description: "Занимается исследованиями интерфейсов в Яндексе больше 5 лет. За это время поработал с десятками продуктов Поиска, Карт, Маркета, Почты и других сервисов компании. Заинтересовался интерфейсами в 2005 году, по образованию специалист по защите информации.",
img_sourse: "alex_kondratiev.jpg",
link: "https://events.yandex.ru/lib/people/10090355/"
},
{
id: 10,
name: "<NAME>",
description: "Руководитель службы разработки мобильных геоинформационных сервисов «Яндекса». Работает над «Яндекс.Картами» и «Яндекс.Метро». Занимается мобильной разработкой более восьми лет.",
img_sourse: "yuri_podorognii.jpg",
link: "https://events.yandex.ru/lib/people/10270070/"
},
{
id: 11,
name: "<NAME>",
description: "Работал дизайнером в студии «Трансформер», с 2014 года — дизайнер систем идентификации в Яндексе.",
img_sourse: "dmitrii_moruz.jpg",
link: "https://events.yandex.ru/lib/people/10446351/"
},
{
id: 12,
name: "<NAME>",
description: "Арт-директор коммуникаций Яндекса. В прошлом — арт-директор журналов «CitizenK», «Эрмитаж», «<NAME>», «Top-Flight», сотрудник «Мастерской Димы Барбанеля». Занимался макетной работой для компаний Readymag, Aliexpress, ONY, Charmer, MINI, Grohe и Мосметрострой.",
img_sourse: "jdan_filippov.jpg",
link: "https://events.yandex.ru/lib/people/10446382/"
},
{
id: 13,
name: "<NAME>",
description: "Кандидат технических наук, научный сотрудник ИПУ РАН с 2008 по 2013. Пришёл в Яндекс.Картинки в 2014 году, отвечал за мобильную версию и рост производительности сервиса. В 2016 перешёл в Yandex Data Factory, где разрабатывает интерфейсы и дизайн веб-приложений для B2B.",
img_sourse: "dmitri_dushkin.jpg",
link: "https://events.yandex.ru/lib/people/9000962/"
},
{
id: 14,
name: "<NAME>",
description: "Во фронтенд-разработке с 2007 года. До 2013-го, когда пришёл в Яндекс, работал технологом в студии Лебедева и других компаниях.",
img_sourse: "maksim_vasiliev.jpg",
link: "https://events.yandex.ru/lib/people/9348837/"
},
{
id: 15,
name: "<NAME>",
description: "Веб-разработчик в Яндексе с 2005 года. Успел поработать над Поиском, Почтой, Поиском по блогам, Я.ру, Картинками, Видео. Помимо этого, активно занимается развитием внутренних инструментов для создания сайтов.",
img_sourse: "sergey_berejnoy.jpg",
link: "https://events.yandex.ru/lib/people/34/"
},
{
id: 16,
name: "<NAME>",
description: "Окончил радиофизический факультет Киевского Национального Университета. Автор трёх патентных заявок. В Яндексе с 2014 года, разрабатывает интерфейсы Яндекс.Карт.",
img_sourse: "andey_morozov.jpg",
link: "https://events.yandex.ru/lib/people/9727130/"
},
{
id: 17,
name: "<NAME>",
description: "Окончил факультет ВМК (вычислительной математики и кибернетики) МГУ им. М.В. Ломоносова, занимается веб-программированием с 2007 года. Сначала делал админки для системы фильтрации трафика, затем — интерфейсы онлайн-карт для проекта Космоснимки. В Яндексе начинал с Народа и Я.ру, последние два года занимался главной страницей. В настоящее время специализируется на вопросах производительности: от серверного JS до оптимизации загрузки страницы на клиенте.",
img_sourse: "ivan_karev.jpg",
link: "https://events.yandex.ru/lib/people/143952/"
},
{
id: 18,
name: "<NAME>",
description: "В 2008 году впечатлился веб-разработкой из-за скорости воплощения идей и лёгкость их донесения до пользователей. В Яндексе с 2014 года, разрабатывает страницу поисковой выдачи. Любит сложные задачи, интересуется аналитикой, тестированием и новыми способами автоматизировать рутину.",
img_sourse: "andrey_prokopiuk.jpg",
link: "https://events.yandex.ru/lib/people/10135442/"
},
{
id: 19,
name: "<NAME>",
description: "Разрабатываю приложения для Android с 2010 года. В 2014 делал высоконагруженное финансовое приложение. Тогда же начал осваивать АОП, внедряя язык в продакшн. В 2015 разрабатывал инструменты для Android Studio, позволяющие использовать aspectJ в своих проектах. В Яндексе занят на проекте Авто.ру.",
img_sourse: "eduard_mazukov.jpg",
link: "https://events.yandex.ru/lib/people/3768719/"
},
{
id: 20,
name: "<NAME>",
description: "Окончил факультет ИТ Московского Технического Университета. В Яндексе с 2015 года, разрабатывает приложение Auto.ru для Android.",
img_sourse: "dmitrii_ckladnov.jpg",
link: "https://events.yandex.ru/lib/people/8979250/"
},
{
id: 21,
name: "<NAME>",
description: "Окончил Самарский университет. Разрабатывает приложения для Android с 2010 года. В Яндексе — с 2012-го. Руководит разработкой мобильных клиентов Яндекс.Диска.",
img_sourse: "roman_grigoriev.jpg",
link: "https://events.yandex.ru/lib/people/9149820/"
},
{
id: 22,
name: "<NAME>",
description: "Профессионал с глубокими познаниями в графической части Android и всего, что с ней связано. Любит нестандартные задачи и решает их в команде мобильного Яндекс Браузера.",
img_sourse: "aleksey_sherbin.jpg",
link: "https://events.yandex.ru/lib/people/9320769/"
},
{
id: 23,
name: "<NAME>",
description: "Выпускник Московского Института Электронной Техники. Android- и Python-разработчик. В команде мобильного Яндекс.Браузера с 2015 года.",
img_sourse: "aleksey_makarov.jpg",
link: "https://events.yandex.ru/lib/people/9513302/"
},
{
id: 24,
name: "<NAME>",
description: "Энтузиаст разработки под Android, в Яндексе занимается оптимизацией и разработкой мобильного приложения Карт.",
img_sourse: "vladimir_tagakov.jpg",
link: "https://events.yandex.ru/lib/people/9513351/"
},
{
id: 25,
name: "<NAME>",
description: "Учится в магистратуре на факультете информатики и вычислительной техники Московского института радиотехники, электроники и автоматики. С 2005 года занимается разработкой приложений (игры, бизнес-приложения) для мобильных устройств на платформах J2ME, Windows Mobile, Android, Symbian, участвовал в разработке веб-приложений на Java EE. В Яндексе с 2010 года, занимается разработкой для мобильных устройств на платформах J2ME и Android.",
img_sourse: "maksim_hromzov.jpg",
link: "https://events.yandex.ru/lib/people/417/"
},
{
id: 26,
name: "<NAME>",
description: "Окончил факультет ВМК МГУ им. Ломоносова. Занимается разработкой приложений и игр с 2011 года, в 2012-м сконцентрировался на мобильных платформах Android и iOS. В Яндексе разрабатывает приложения для Android.",
img_sourse: "denis_zagaevski.jpg",
link: "https://events.yandex.ru/lib/people/10113492/"
},
{
id: 27,
name: "<NAME>",
description: "Окончил факультет ПМТ Вятского государственного университета в 2012 году. В Яндексе с 2015-го, занимается разработкой продуктов медийных сервисов.",
img_sourse: "dmitri_popov.jpg",
link: "https://events.yandex.ru/lib/people/10291395/"
},
{
id: 28,
name: "<NAME>",
description: "Разрабатывает приложения под мобильные платформы с 2009 года. За это время принял участие более чем в 30 законченных проектах под Android, iOS, и Windows Phone. В Яндексе с 2015 года, занимается разработкой КиноПоиска под Android и iOS.",
img_sourse: "ilia_sergeev.jpg",
link: "https://events.yandex.ru/lib/people/10682529/"
}
];
module.exports = lecturers;
|
9c37ad1d309a4e6d591a49e70301d39ef1bdba9d
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
ottenokLeshi/ya-first
|
92ec72a6af71b925d498d50de1250c4006caaa48
|
a0bfcd7ad06e0a8c268738cfdc675b23117ef37e
|
refs/heads/master
|
<repo_name>BvE-HU/HotelApp<file_sep>/README.md
HotelApp
===================================
Clone dit project met de command-line of IntelliJ ([instructies](https://www.jetbrains.com/help/idea/manage-projects-hosted-on-github.html#clone-from-GitHub)).
Open het project met IntelliJ, en de applicatie kan gestart worden door klasse **hotel.HotelApp** uit te voeren. <file_sep>/src/hotel/model/KamerType.java
package hotel.model;
public class KamerType {
private String typeNaam;
private int aantalBedden;
private double prijsPerNacht;
public KamerType(String tN, int aB, double prijs) {
typeNaam = tN;
aantalBedden = aB;
prijsPerNacht = prijs;
}
public String getTypeNaam() {
return typeNaam;
}
public int getAantalBedden() {
return aantalBedden;
}
public double getPrijsPerNacht() {
return prijsPerNacht;
}
public boolean equals(Object obj) {
boolean gelijk = obj instanceof KamerType;
gelijk = gelijk && ((KamerType)obj).typeNaam.equals(typeNaam);
gelijk = gelijk && ((KamerType)obj).aantalBedden == aantalBedden;
gelijk = gelijk && ((KamerType)obj).prijsPerNacht == prijsPerNacht;
return gelijk;
}
public String toString() {
String s = typeNaam + ", bedden: " + aantalBedden;
s += ", € " + prijsPerNacht + " p.n.";
return s;
}
}
|
e2a5678cf4b2ea40561a1252ddec2b85ead04cb4
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
BvE-HU/HotelApp
|
397925759eab453dae11be337655bea62aa745d7
|
77bd46d4cdf5df794cd21ab5aa48928549f4d174
|
refs/heads/master
|
<repo_name>cran/useful<file_sep>/R/loadPackages.r
#' @title load_packages
#' @description Loads multiple packages
#' @details Allows the user to load multiple packages with one line of code. Delivers a message saying which packages have been loaded. If a user requests packages that are not installed there is an error.
#' @author <NAME>
#' @param packages A `character` vector of packages to be installed
#' @return Nothing, loads packages
#' @export
#' @examples
#'
#' load_packages('ggplot2')
#' load_packages(c('ggplot2', 'dplyr'))
load_packages <- function(packages)
{
# be sure it is a character vector
assertthat::assert_that(is.character(packages))
## check that the packages are installed
# get list of installed packages
installedPackages <- rownames(utils::installed.packages())
# see which of our packages are installed
installedIndex <- packages %in% installedPackages
# get the installed ones
installedPackages <- packages[installedIndex]
# get the not installed ones
notInstalledPackages <- packages[!installedIndex]
# warn which packages are installed
if(length(notInstalledPackages))
{
stop(
sprintf(
'The following packages are not installed: {%s}',
paste(notInstalledPackages, collapse=', ')
)
)
}
purrr::walk(installedPackages, .f=library, character.only=TRUE)
message(
sprintf(
'The following packages were loaded: {%s}',
paste(installedPackages, collapse=', ')
)
)
}
<file_sep>/tests/testthat/test-reclass.r
context('Checking that reclass sets the class accordingly')
# create data.frames and lists to test with
df1 <- data.frame(A=1:10, B=1:10)
list1 <- list(A=1:3, B=2)
class(list1) <- c('Special', 'list')
df2 <- df1
list2 <- list1
# reclass them using both methods
reclass(df1) <- 'NewClass'
df2 <- reclass(df2, 'NewClass')
reclass(list1) <- 'NewClass'
list2 <- reclass(list2, 'NewClass')
test_that('reclass returns the appropriate number of classes', {
expect_equal(length(class(df1)), 2)
expect_equal(length(class(df2)), 2)
expect_equal(length(class(list1)), 3)
expect_equal(length(class(list2)), 3)
})
test_that('reclass returns the correct classes', {
expect_equal(class(df1), c('NewClass', 'data.frame'))
expect_equal(class(df2), c('NewClass', 'data.frame'))
expect_equal(class(list1), c('NewClass', 'Special', 'list'))
expect_equal(class(list2), c('NewClass', 'Special', 'list'))
})<file_sep>/NEWS.md
# Version 1.2.6
Changed `multiple` to no longer depend on the `scales` package since its behavior changed.
Added `load_packages()` so that people can load multiple packages with one line of code.
# Version 1.2.5
Using `autoplot()` to plot `acf` objects.
# Version 1.2.4
Complete unit test coverage.
Added point size option in `plot.kmeans()`.
Added function for computing a single time difference with an informative message.
# Version 1.2.3
Added support for sparce matrices in `build.x()`
# Version 1.2.2
Adjusted `build.x()` so that it works appropriately when only one categorical variable is specified.
Added tests for building matrices.
Changed code to accomodate new changes in `dplyr`.
# Version 1.2.1
Added function, `uniqueBidirection()` to return unique rows of a `data.frame` regardless of their order.
Fixed test failures due to new version of `testthat`.
# Version 1.2.0
Explicitly calling functions from `grid` and `scales` rather than importing the entire packages.
The function `subVector()` now returns the original text `x` if `toSub` is not supplied.
# Version 1.1.9
New function for checking the class of each column in a data.frame.
New functions for simple imputation of missing data.
New functions for check the case of strings.
New function to add a new class to an object in addition to existing classes.
New functions for mapping polar coordinates to cartesian and back.
New functions for mapping matrix index to position and position to index.
New functions for regex substitution of multiple items.
# Version 1.1.8
Added functionality to `build.x()` to control contrasts.
Fixed bug in `build.x()` where it never returned the intercept.
# Version 1.1.7
Scale formatters for ggplot2.
Functions to build x and y matrices based on a formula.
Function to ensure data in `build.x()` and `build.y()` is not a matrix or array.
Function to check interval membership.
# Version 1.1.6
Updated to reflect ggplot2_0.9.2 changes.
# Version 1.1.5
New function to flip 0's to 1's and 1's to 0's.
New function to shift columns up or down in a data.frame.
New function to knit Rnw files to TeX only if the TeX doesn't exist or is older than the Rnw.
New functions for plotting the results of a kmeans fit.
New functions for plotting ts and acf objects.
# Version 1.1.4
New function for building formulas from vectors of characters.
# Version 1.1.3
Added function for comparing two lists element by element.
# Version 1.1.2
FitKMeans uses match.arg for determing algorithmchoice.
The loop in FitKMeans now fits each partitioning once and reuses it rather than calculating twice.
# Version 1.1.1
Fixed corner so that it handles showing the bottom of data correctly.
# Version 1.0
First Build.
A collection of handy functions.
subOut, subSpecials, MapToInterval, corner, FitKMeans, PlotHartigan.
|
a2eec2ac0031397469ac9d3842aacff9a873082d
|
[
"Markdown",
"R"
] | 3 |
R
|
cran/useful
|
1b9831ddb97ec68066c8cdf1eaa8b9f9f9eaa605
|
53f392ae3195e7ee964a6825010e6c0ace603637
|
refs/heads/master
|
<file_sep>import * as config from "../config.json";
export class Country {
//Get all countries
getCountries(){
return config.countryList;
}
}<file_sep>const expect = require('chai').expect;
const {Country} = require("../services/country");
const getCountries = new Country();
describe("Contry Testing Set", () => {
//Get list of countries
it("Get all countries", () => {
const countriesList = getCountries.getCountries();
expect(typeof countriesList).to.equal('object');
});
});
|
a88e7c7c45e5372a4b508adb6f26bc75341e3826
|
[
"JavaScript"
] | 2 |
JavaScript
|
blarzHernandez/youtube-trends
|
b7ca5557630fcbfd9ee789b82a694faa3ad64f1e
|
dcf61d72340abad57f4cac49c393b6e5e387478e
|
refs/heads/master
|
<repo_name>mustyzod/react-advance-dropdown<file_sep>/src/App.js
import Default from './themes/default'
const App = () => {
return (
<Default />
);
}
export default App<file_sep>/src/themes/default/header/index.jsx
import React from 'react'
import NavItem from './NavItem'
import DropDownMenu from './dropdown/DropDownMenu'
import PlusMenu from './plusmenu/PlusMenu'
import Navbar from './Navbar'
import {
BellIcon,
MessengerIcon,
CaretIcon,
PlusIcon
} from '../zodicons'
const index = () => {
return (
<Navbar>
<NavItem icon={<PlusIcon />}>
<PlusMenu />
</NavItem>
<NavItem icon={<BellIcon />} />
<NavItem icon={<MessengerIcon />} />
<NavItem icon={<CaretIcon />}>
{/* Dropdown goes here */}
<DropDownMenu />
</NavItem>
</Navbar>
)
}
export default index
|
561ddd029eb1d5c4d026d6c0f998c9b8d5a82a9a
|
[
"JavaScript"
] | 2 |
JavaScript
|
mustyzod/react-advance-dropdown
|
7f48b2ada18ee14dcbbf3437f1f90135f50e925a
|
afc3912985c2430b7a14aa6d631cf9936fd40e33
|
refs/heads/master
|
<repo_name>xiemeigongzi/Cpp-primer-5th-Chinese-version-answer-<file_sep>/test 1.9.cpp
#include <iostream>
int main()
{
int sum=0, val=50;
while(val<=100){
sum=sum+val;
val=val+1;
}
std::cout<<"The sum of 50-100 is"<<sum<<std::endl;
return 0;
}
<file_sep>/test 1.10- standard.cpp
#include <iostream>
int main()
{
int i=10;
while(i>=1){
i=i-1;
std::cout<<"the numbers between 0 and 10 are: "<<i<<std::endl;
}
return 0;
}
<file_sep>/test 1.12.cpp
#include <iostream>
using namespace std;
int main()
{
int sum=0;
for(int i= -100;i<=100;++i)
sum+=i;
cout<<sum;
return 0;
}
<file_sep>/1.4.4-3.cpp
#include <iostream>
using namespace std;
int main()
{
int a=0;
int b=0;
if(cin>>a){
int cnt=1;
while(cin>>b){
if(a==b)
++cnt;
else{
cout<<a<<" occurs "<<cnt<<endl;
int a=b;
int cnt=1;
}
}
cout<<a<<" occurs"<<cnt<<endl;
}
return 0;
}
<file_sep>/test 1.13-1.11-1.cpp
#include <iostream>
using namespace std;
int main()
{
int a=0,b=0;
cin>>a;
cin>>b;
for(cout<<a<<endl;a<b;++a)
for(cout<<b<<endl;a>b;++b)
return 0;
}
<file_sep>/test 1.4-1.cpp
#include <iostream>
using namespace std;
int main()
{
cout<<"Enter two nunbers:"<<endl;
int v1=0, v2=0;
cin>>v1>>v2;
cout<<"The product of two numbers is "<<v1*v2<<endl;
return 0;
<file_sep>/test 1.13-1.11-3.cpp
#include <iostream>
int main()
{
int low=0;
int high=0;
std::cout<<"Enter low number and Enter low number:"<<std::endl;
std::cin>>low;
std::cin>>high;
for(int i=low+1;i<high;++i)
std::cout<<i<<std::endl;
return 0;
}
<file_sep>/test 1.6-1.cpp
#include <iostream>
using namespace std;
int main()
{
cout<<"enter two numbers:";
cout<<endl;
int v1=0, v2=0;
cin>>v1;
cin>>v2;
cout<<"the sum is "<<v1*v2<<endl;
return 0;
}
<file_sep>/test 1.9-1.cpp
#include <iostream>
using namespace std;
int main()
{
int sum=0, i=50;
while(i<=100){
sum+=i;
++i;
}
cout<<"sum is "<< sum ;
return 0;
}
<file_sep>/test 1.11-1.cpp
#include <iostream>
using namespace std;
int main()
{
int v1=0, v2=0, a=0;
cout<<"Enter two numbers: ";
cin>>v1;
cin>>v2;
while(v1>v2+1){
a=v2+1;
++v2;
cout<<"The requested number is:"<<a;
}
while(v1<(v2-1)){
a=v1+1;
++v1;
cout<<"The requested number is:\n"<<a;
}
return 0;
}
<file_sep>/1.10-again-3.cpp
#include <iostream>
using namespace std;
int main()
{
int vul=10;
while(vul>0){
--vul;
cout<<vul<<endl;
}
return 0;
}
<file_sep>/1.4.4-2.cpp
#include <iostream>
using namespace std;
int main()
{
int a=0,b=0;
if(cin>>a){
int cnt=1;
while(cin>>b){
if(a==b)
++cnt;
else{
cout<<"The repeat number of "<<a<<"is "<<cnt<<endl;
a=b;
int cnt=1;
}
}
cout<<a<<" occurs "<<cnt<<" times"<<endl;
}
return 0;
}
<file_sep>/test 1.13-1.9-2.cpp
#include <iostream>
using namespace std;
int main()
{
for(int i=10;i>1;--i)
cout<<i-1<<endl;
return 0;
}
<file_sep>/1.4.3.cpp
#include <iostream>
int main()
{
int sum=0,val=0;
while(std::cin>>val)
sum+=val;
std::cout<<"The sum is "<<sum<<std::endl;
return 0;
}
<file_sep>/README.md
# Cpp-primer-5th-Chinese-version-answer-
C++primer 第五版 自己给出的答案
<file_sep>/1.4.1-3.cpp
#include <iostream>
int main()
{
int sum=0, val=1;
while(val<=10){
sum=sum+val;
val=val+1;
}
std::cout<<"The sum is "<<sum<<std::endl;
return 0;
}
<file_sep>/1.10-again-2.cpp
#include <iostream>
int main()
{
int vul=10;
while(vul>0){
--vul;
std::cout<<vul<<std::endl;
}
return 0;
}
<file_sep>/1.10-again-1.cpp
#include <iostream>
using namespace std;
int main()
{
int vul=10;
while(vul>=1){
vul=vul-1;
cout<<vul;
}
return 0;
}
<file_sep>/1.4.2 for.cpp
#include <iostream>
int main()
{
int sum=0;
for (int val=1;val<=10;++val)
sum+=val;
std::cout<<"Sum of 1 to 10 is "
<< sum<<std::endl;
return 0;
}
<file_sep>/test 1.6-4.cpp
#include <iostream>
int main()
{
std::cout<<"Enter two numbers: ";
std::cout<<std::endl;
int v1=0;
int v2=0;
std::cin>>v1;
std::cin>>v2;
std::cout<<"The sum of";
std::cout<<std::endl;
std::cout<<v1;
std::cout<<v2;
std::cout<<" is ";
std::cout<<std::endl;
std::cout<<v1+v2;
return 0;
}
<file_sep>/1.4.3-1.cpp
#include <iostream>
int main()
{
int sum=0;
int value=0;
while(std::cin>>value)
sum+=value;
std::cout<<"Sum is: "<<sum<<std::endl;
return 0;
}
<file_sep>/test 1.13-1.10-1.cpp
#include <iostream>
using namespace std;
int main()
{
int sum=0;
for(int a=50;a<=100;++a)
sum+=a;
cout<<sum<<endl;
return 0;
}
<file_sep>/test 1.4-3.cpp
#include <iostream>
int main()
{
int sum =0, val=1;
while (val<=10){
sum+=val;
++val;
}
std::cout<<"Sum of 1 to 10 is "<<sum<<std::endl;
return 0;
}
<file_sep>/1.4.1-4.cpp
#include <iostream>
using namespace std;
int main()
{
int a=0,b=0;
cout<<"Input the numbers, it will compute the sum:";
while(cin>>b){
a+=b;
}
cout<<"Sum is "<<a<<endl;
return 0;
}
<file_sep>/1.4.2-for sentence.cpp
#include <iostream>
using namespace std;
int main()
{
int sum =0;
for(int vul=0;vul<=10;++vul)
sum+=vul;
cout<<sum<<endl;
return 0;
}
<file_sep>/1.9-again-1.cpp
#include <iostream>
using namespace std;
int main()
{
int sum=0,vul=50;
while(vul<=100){
sum+=vul;
++vul;
}
cout<<"The sum 50 to 100 is: "<<sum;
return 0;
}
<file_sep>/test 1.11-2.cpp
#include <iostream>
using namespace std;
int main()
{
int v1=0, v2=0;
cout<<"Enter two numbers: "<<endl;
cin>>v1;
cin>>v2;
while(v1>(v2+1)){
++v2;
cout<<"the numbers between"<<v1<<" and "<<v2<<" are "<<v2<<endl;
}
while(v1<(v2-1)){
cout<<"the numbers between"<<v1<<" and "<<v2<<" are "<<v1+1<<endl;
++v1;
}
return 0;
}
<file_sep>/test 1.9 standard.cpp
#include <iostream>
int main()
{
int sum=0, i=50;
while(i<=100){
sum=sum=i;
i=i+1;
}
std::cout<<"sum is "<< sum <<std::endl;
return 0;
}
<file_sep>/test 1.10-1.cpp
#include <iostream>
int main()
{
int a=0, b=10;
while(b>a){
b=b-1;
std::cout<<"the numbers between 0 and 10 are"<<b<<std::endl;
}
return 0;
}
|
61939a8cad29dc0c461a4d7404bd6f2eef2b00fb
|
[
"Markdown",
"C++"
] | 29 |
C++
|
xiemeigongzi/Cpp-primer-5th-Chinese-version-answer-
|
e5e7b0693f8bf6a839bdb6dbacbce73d09b419f1
|
f21e0eebed467ec32fb9e049fc58c38d90621fdc
|
refs/heads/master
|
<repo_name>mozgovoyandrey/test-groozgo<file_sep>/models/Users.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "users".
*
* @property int $id
* @property string $lastname
* @property string $firstname
* @property string $birthday
*
* @property Addresses[] $addresses
*/
class Users extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'users';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['lastname', 'firstname', 'birthday'], 'required'],
[['birthday'], 'safe'],
[['lastname', 'firstname'], 'string', 'max' => 100],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'lastname' => 'Lastname',
'firstname' => 'Firstname',
'birthday' => 'Birthday',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getAddresses()
{
return $this->hasMany(Addresses::className(), ['user_id' => 'id'])->inverseOf('user');
}
/**
* @inheritdoc
* @return \app\models\query\UsersQuery the active query used by this AR class.
*/
public static function find()
{
return new \app\models\query\UsersQuery(get_called_class());
}
}
<file_sep>/views/user/_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Users */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="users-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'lastname')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'firstname')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'birthday')->textInput() ?>
<?php if (!$model->isNewRecord) { ?>
<div class="form-group addresses-list">
<div class="row">
<div class="col-md-6">Address</div>
<div class="col-md-5">Comment</div>
<div class="col-md-1"><a href="#" class="j_add-row btn">Добавить</a> </div>
</div>
<?php
foreach ($model->addresses as $address) {
?>
<div class="row">
<div class="col-md-6">
<?= Html::activeHiddenInput($address, 'id', ['name'=>'Addresses[id][]']) ?>
<?= $form->field($address, 'address')->textarea(['name'=>'Addresses[address][]'])->label(false) ?></div>
<div class="col-md-5"><?= $form->field($address, 'comment')->textarea(['name'=>'Addresses[comment][]'])->label(false) ?></div>
<div class="col-md-1"><a href="#" class="j_delete-row btn">Удалить</a></div>
</div>
<?php
}
?>
</div>
<?php } ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
<script>
$(document).ready(function () {
$(document).on('click', '.j_delete-row', function () {
$(this).closest('div.row').remove();
});
$('.j_add-row').on('click', function () {
$addressList = $(this).closest('.addresses-list');
$addressList.append('<div class="row">'+
'<div class="col-md-6">'+
'<input type="hidden" id="addresses-id" name="Addresses[id][]">'+
'<div class="form-group field-addresses-address required has-success">'+
'<textarea id="addresses-address" class="form-control" name="Addresses[address][]" aria-required="true" aria-invalid="false"></textarea>'+
'<div class="help-block"></div>'+
'</div></div>'+
'<div class="col-md-5"><div class="form-group field-addresses-comment">'+
'<textarea id="addresses-comment" class="form-control" name="Addresses[comment][]"></textarea>'+
'<div class="help-block"></div>'+
'</div></div>'+
'<div class="col-md-1"><a href="#" class="j_delete-row btn">Удалить</a></div>'+
'</div>');
});
});
</script>
</div>
|
c9b76c0715aa598a40951736a6a4c4a943a6f509
|
[
"PHP"
] | 2 |
PHP
|
mozgovoyandrey/test-groozgo
|
052a958ea93c248582718d9359df0288c4bbf8b0
|
a3702d5f59acbb15721bdcc1d7e4492a60db7260
|
refs/heads/master
|
<file_sep>#define ShiftOut 8
#define Clock 12
// when Control is H input is loaded by parallel inputs
// when Control is L the shift is allowed
#define Control 13
//asynchronous
void Load()
{
digitalWrite(Control, HIGH);
delay(50);
digitalWrite(Control, LOW);
delay(50);
}
void ShiftByOne()
{
digitalWrite(Clock, HIGH);
delay(50);
digitalWrite(Clock, LOW);
delay(50);
}
void setup()
{
pinMode(ShiftOut, INPUT);
pinMode(Clock, OUTPUT);
pinMode(Control, OUTPUT);
Serial.begin(9600);
Load();
Serial.print("Shift Data: ");
}
int count = 0;
void loop()
{
if(count < 8)
{
Serial.print(digitalRead(ShiftOut));
ShiftByOne();
count++;
}
}
<file_sep>struct ledCoord_t {int cathode; int anode;};
typedef struct ledCoord_t led;
int movePin = 6;
int selectPin = 7;
int cathodePin1 = 8;
int cathodePin2 = 12;
int cathodePin3 = 13;
int anodePin1 = 11;
int anodePin2 = 10;
int anodePin3 = 9;
led startup = {0,0};
int leds[3][3];
void setup()
{
pinMode(movePin, INPUT_PULLUP);
pinMode(selectPin, INPUT_PULLUP);
pinMode(anodePin1, OUTPUT);
pinMode(anodePin2, OUTPUT);
pinMode(anodePin3, OUTPUT);
pinMode(cathodePin1, OUTPUT);
pinMode(cathodePin2, OUTPUT);
pinMode(cathodePin3, OUTPUT);
Serial.begin(9600);
// lights up the first led at start
leds[startup.cathode][startup.anode] = 1;
leds[1][1] = 1;
leds[2][2] = 1;
}
void loop()
{
LightSelected();
CheckMovePin(); // if moved -> 0 the current pos and puts 1 to the next posssible pos
CheckSelectPin();
}
int CheckSelectPin()
{
int period = 10;
int timeNow = millis();
int selectPrevious = digitalRead(selectPin);
while(millis() < timeNow + period)
{
LightSelected();
int selectNow = digitalRead(selectPin);
if(selectNow == LOW && selectNow != selectPrevious) //if pressed select
{
led lastLed = {2,2};
startup = next(lastLed);
break;
}
selectPrevious = selectNow;
}
}
int CheckMovePin()
{
int period = 10;
int timeNow = millis();
int movePrevious = digitalRead(movePin);
while(millis() < timeNow + period) // delay that ensures taht the leds will glow with full capacity
{
LightSelected();
}
int moveNow = digitalRead(movePin);
if(moveNow == LOW && moveNow != movePrevious) //if pressed move
{
leds[startup.cathode][startup.anode] = 0;
startup = next(startup);
leds[startup.cathode][startup.anode] = 1;
}
}
led next(led current) //check next acessible led array
{
led next;
for(int c = current.cathode; c < 3; c++)
{
for(int a = current.anode + 1; a < 3; a++) //alwas work for the next
{
if(leds[c][a] == 0)
{
next.anode = a;
next.cathode = c;
return next;
}
}
current.anode = -1;
if(c == 2)
{
c = -1;
}
}
}
void LightUp(led current)
{
switch(current.cathode)
{
case 0: current.cathode = cathodePin1; break;
case 1: current.cathode = cathodePin2; break;
case 2: current.cathode = cathodePin3; break;
default: Serial.println("ERR: incorrect led Coord (cathode)");//print
}
switch(current.anode)
{
case 0: current.anode = anodePin1; break;
case 1: current.anode = anodePin2; break;
case 2: current.anode = anodePin3; break;
default: Serial.println("ERR: incorrect led Coord (anode)");//print
}
ClearAll();
digitalWrite(current.anode, HIGH);
digitalWrite(current.cathode, LOW);
}
int LightSelected() //lights up the pins with 1 at start of the loop
{
int selectedNum = 0;
for(int c = 0; c < 3; c++)
{
for(int a = 0; a < 3; a++)
{
if(leds[c][a] == 1)
{
selectedNum++;
led led = {c, a};
LightUp(led);
}
}
}
return selectedNum;
}
void ClearAll()
{
digitalWrite(anodePin1, LOW);
digitalWrite(anodePin2, LOW);
digitalWrite(anodePin3, LOW);
digitalWrite(cathodePin1, HIGH);
digitalWrite(cathodePin2, HIGH);
digitalWrite(cathodePin3, HIGH);
}
void printLeds()
{
for(int c = 0; c < 3; c++)
{
for(int a = 0; a < 3; a++)
{
Serial.print(leds[c][a]);
}
Serial.println();
}
Serial.println();
}
<file_sep>#define movePin 6
#define selectPin 7
//=============================================================================================================================================
int movePrevious = HIGH;
int moveNow = HIGH;
unsigned int lastexec;
void initMove() {
pinMode(movePin, INPUT_PULLUP);
}
int isPressedMove() {
moveNow = digitalRead(movePin);
if(moveNow == LOW && moveNow != movePrevious) {
Serial.println("Pressed: MOVE");
movePrevious = moveNow;
delay(500);
return 1;
}
movePrevious = moveNow;
return 0;
}
//=============================================================================================================================================
int selectPrevious = HIGH;
int selectNow = HIGH;
void initSelect () {
pinMode(selectPin, INPUT_PULLUP);
}
int isPressedSelect() {
selectNow = digitalRead(selectPin);
if(selectNow == LOW && selectNow != selectPrevious) {
Serial.println("Pressed: SELECT");
selectPrevious = selectNow;
delay(500);
return 1;
}
selectPrevious = selectNow;
return 0;
}
//=============================================================================================================================================
void refreshLeds()
void LightUp(led current)
{
switch(current.cathode)
{
case 0: current.cathode = cathodePin1; break;
case 1: current.cathode = cathodePin2; break;
case 2: current.cathode = cathodePin3; break;
default: Serial.println("ERR: incorrect led Coord (cathode)");//print
}
switch(current.anode)
{
case 0: current.anode = anodePin1; break;
case 1: current.anode = anodePin2; break;
case 2: current.anode = anodePin3; break;
default: Serial.println("ERR: incorrect led Coord (anode)");//print
}
ClearAll();
digitalWrite(current.anode, HIGH);
digitalWrite(current.cathode, LOW);
}
void ClearAll()
{
digitalWrite(anodePin1, LOW);
digitalWrite(anodePin2, LOW);
digitalWrite(anodePin3, LOW);
digitalWrite(cathodePin1, HIGH);
digitalWrite(cathodePin2, HIGH);
digitalWrite(cathodePin3, HIGH);
}
int RefreshLeds() //lights up the pins with 1 at start of the loop
{
int selectedNum = 0;
for(int c = 0; c < 3; c++)
{
for(int a = 0; a < 3; a++)
{
if(leds[c][a] == 1)
{
selectedNum++;
led led = {c, a};
LightUp(led);
}
}
}
return selectedNum;
}
//=============================================================================================================================================
void setup() {
Serial.begin(115200);
initMove();
initSelect();
}
void loop() {
if(isPressedMove()) {
}
if(isPressedSelect()) {
}
refreshLeds();
}
/*
struct ledCoord_t {int cathode; int anode;};
typedef struct ledCoord_t led;
int cathodePin1 = 8;
int cathodePin2 = 12;
int cathodePin3 = 13;
int anodePin1 = 11;
int anodePin2 = 10;
int anodePin3 = 9;
led startup = {0,0};
int leds[3][3];
int time1 = 0;
int time2 = 0;
void setup()
{
pinMode(anodePin1, OUTPUT);
pinMode(anodePin2, OUTPUT);
pinMode(anodePin3, OUTPUT);
pinMode(cathodePin1, OUTPUT);
pinMode(cathodePin2, OUTPUT);
pinMode(cathodePin3, OUTPUT);
Serial.begin(9600);
// lights up the first led at start
leds[startup.cathode][startup.anode] = 1;
leds[1][1] = 1;
leds[2][2] = 1;
}
void loop()
{
LightSelected();
CheckMovePin(); // if moved -> 0 the current pos and puts 1 to the next posssible pos
CheckSelectPin();
}
int CheckSelectPin()
{
int period = 10;
int timeNow = millis();
int selectPrevious = digitalRead(selectPin);
while(millis() < timeNow + period)
{
LightSelected();
int selectNow = digitalRead(selectPin);
if(selectNow == LOW && selectNow != selectPrevious) //if pressed select
{
led lastLed = {2,2};
startup = next(lastLed);
break;
}
selectPrevious = selectNow;
}
}
int CheckMovePin()
{
int period = 10;
int timeNow = millis();
while(millis() < timeNow + period) // delay that ensures taht the leds will glow with full capacity
{
LightSelected();
}
if(moveNow == LOW && moveNow != movePrevious) //if pressed move
{
leds[startup.cathode][startup.anode] = 0;
startup = next(startup);
leds[startup.cathode][startup.anode] = 1;
}
}
led next(led current) //check next acessible led array
{
led next;
for(int c = current.cathode; c < 3; c++)
{
for(int a = current.anode + 1; a < 3; a++) //alwas work for the next
{
if(leds[c][a] == 0)
{
next.anode = a;
next.cathode = c;
return next;
}
}
current.anode = -1;
if(c == 2)
{
c = -1;
}
}
}
void printLeds()
{
for(int c = 0; c < 3; c++)
{
for(int a = 0; a < 3; a++)
{
Serial.print(leds[c][a]);
}
Serial.println();
}
Serial.println();
}
*/
<file_sep>#include <MIDI.h>
#define Button 7
#define Led 8
byte Pitch = 51;
MIDI_CREATE_DEFAULT_INSTANCE();
void setup()
{
MIDI.begin();
Serial.begin(115200);
pinMode(Button, INPUT_PULLUP);
pinMode(Led, OUTPUT);
}
void loop()
{
readButton();
}
int Previous = HIGH;
void readButton()
{
int Status = digitalRead(Button);
if(Status == LOW && Status != Previous)
{
digitalWrite(Led, HIGH);
Serial.write(0x90);
Serial.write(51);
Serial.write(100);
//MIDI.sendNoteOn(1, 51, 100);
}
if(Status == HIGH && Status != Previous)
{
digitalWrite(Led, LOW);
Serial.write(0x80);
Serial.write(51);
Serial.write(0);
//MIDI.sendNoteOff(1, 51, 100);
}
Previous = Status;
delay(50);
}
<file_sep>int latchPin = 8;
int dataPin = 9;
int clockPin = 7;
byte current = 0;
byte previous = 0;
byte mainPitch = 50;
void setup()
{
Serial.begin(115200);
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, INPUT);
}
void loop()
{
digitalWrite(latchPin, HIGH);
delayMicroseconds(0.01);
digitalWrite(latchPin, LOW);
current = shiftIn(dataPin, clockPin);
if(current != previous)
{
SendNotes();
}
previous = current;
delay(50);
}
byte shiftIn(int myDataPin, int myClockPin)
{
int temp = 0;
byte myDataIn = 0;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, INPUT);
for (int i = 7; i >= 0; i--)
{
digitalWrite(myClockPin, LOW);
delayMicroseconds(0.02);
temp = digitalRead(myDataPin);
if(temp)
{
myDataIn = myDataIn | (1 << i);
}
digitalWrite(myClockPin, HIGH);
}
return myDataIn;
}
void MidiNoteOn(int pitch)
{
Serial.write(0x90);
Serial.write(pitch);
Serial.write(100);
}
void MidiNoteOff(int pitch)
{
Serial.write(0x80);
Serial.write(pitch);
Serial.write(100);
}
void SendNotes()
{
int diff = previous ^ current;
/*Serial.print("previous: ");
Serial.println(previous, BIN);
Serial.print("current: ");
Serial.println(current, BIN);
Serial.print("diff(xor): ");
Serial.println(diff, BIN);*/
//noteon
for(int i = 0; i < 8; i++)
{
if((current & diff) & (1 << i))
{
MidiNoteOn(mainPitch + i);
}
}
//noteoff
for(int i = 0; i < 8; i++)
{
if((previous & diff) & (1 << i))
{
MidiNoteOff(mainPitch + i);
}
}
}
|
f97184a9ab7b9358d9c64b7683ab71aaa55fdd66
|
[
"C++"
] | 5 |
C++
|
IvoKara/Arduino
|
b7ae7109df1f98c0443a034d39fd60ca64d89343
|
0b40a72dc92ec09970bba4f08fe02a5a85b3a788
|
refs/heads/master
|
<repo_name>Enigmatrix/vuepress-plugin-blog<file_sep>/README.md
# @vuepress/plugin-blog
> Official blog plugin for VuePress.
Note that this plugin has been deeply integrated into [@vuepress/theme-blog](https://github.com/ulivz/vuepress-theme-blog).
## Install
```bash
yarn add -D @vuepress/plugin-blog
# OR npm install -D @vuepress/plugin-blog
```
## Usage
```javascript
module.exports = {
plugins: ['@vuepress/blog']
// Please head documentation to see the available options.
}
```
## Author
**@vuepress/theme-blog** © [ULIVZ](https://github.com/ulivz), Released under the [MIT](./LICENSE) License.<br>
> [github.com/ulivz](https://github.com/ulivz) · GitHub [@ULIVZ](https://github.com/ulivz) · Twitter [@_ulivz](https://twitter.com/_ulivz)
<file_sep>/src/client/init.js
export Pagination from '../components/Pagination'
export SimplePagination from '../components/SimplePagination'
<file_sep>/CHANGELOG.md
# [1.0.0](https://github.com/ulivz/vuepress-plugin-blog/compare/v1.0.0-alpha.50...v1.0.0) (2019-06-09)
### Bug Fixes
* build failed when creating new markdown pages ([89dbddb](https://github.com/ulivz/vuepress-plugin-blog/commit/89dbddb))
# [1.0.0-alpha.50](https://github.com/ulivz/vuepress-plugin-blog/compare/v0.0.2...v1.0.0-alpha.50) (2019-06-03)
### Features
* some enhancements (debug / api name) ([ab57080](https://github.com/ulivz/vuepress-plugin-blog/commit/ab57080))
## [0.0.2](https://github.com/ulivz/vuepress-plugin-blog/compare/v0.0.1...v0.0.2) (2019-06-03)
<file_sep>/src/interface/Classifier.ts
export enum ClassifierTypeEnum {
Directory = 'Directory',
Frontmatter = 'Frontmatter',
}
export enum DefaultLayoutEnum {
FrontmatterPagination = 'FrontmatterPagination',
DirectoryPagination = 'DirectoryPagination',
}
<file_sep>/docs/config/README.md
---
sidebar: auto
---
# Config
## directories
- Type: `DirectoryClassifier[]`
- Default: `[]`
Create one or more [directory classifiers](../README.md#directory-classifier), all available options in
`DirectoryClassifier` are as
follows.
### id
- Type: `string`
- Default: `undefined`
- Required: `true`
Unique id for current classifier, e.g. `post`.
### dirname
- Type: `string`
- Default: `undefined`
- Required: `true`
Matched directory name, e.g. `_post`.
### path
- Type: `string`
- Default: `/${id}/`
- Required: `false`
Entry page for current classifier, e.g. `/` or `/post/`.
If you set `DirectoryClassifier.path` to `/`, it means that you want to access the matched pages list at `/`. set
to `/post/` is the same.
### layout
- Type: `string`
- Default: `'IndexPost' || 'Layout'`
- Required: `false`
Layout component name for entry page.
### frontmatter
- Type: `Record<string, any>`
- Default: `{}`
- Required: `false`
[Frontmatter](https://v1.vuepress.vuejs.org/guide/frontmatter.html) for entry page.
### itemLayout
- Type: `string`
- Default: `'Post'`
- Required: `false`
Layout for matched pages.
### itemPermalink
- Type: `string`
- Default: `'/:year/:month/:day/:slug'`
- Required: `false`
Permalink for matched pages.
For example, if you set up a directory classifier with dirname equals to `_post`, and have following pages:
```
.
└── _posts
├── 2018-4-4-intro-to-vuepress.md
└── 2019-6-8-intro-to-vuepress-next.md
```
With the default `itemPermalink`, you'll get following output paths:
```
/2018/04/04/intro-to-vuepress/
/2019/06/08/intro-to-vuepress-next/
```
For more details about permalinks, please head to [Permalinks](https://v1.vuepress.vuejs.org/guide/permalinks.html) section at VuePress's documentation.
### pagination
- Type: `Pagination`
- Default: `{ perPagePosts: 10 }`
- Required: `false`
All available options of pagination are as follows:
- pagination.perPagePosts: Maximum number of posts per page.
- pagination.pagesSorter: Maximum number of posts per page.
## frontmatters
> TODO, contribution welcome.
<file_sep>/docs/.vuepress/config.js
module.exports = {
title: '@vuepress/plugin-blog',
description: 'Offical blog plugin for VuePress',
themeConfig: {
repo: 'ulivz/vuepress-plugin-blog',
nav: [
{ text: 'Config', link: '/config/' }
]
}
}
<file_sep>/src/interface/VuePress.ts
import Vue from 'vue'
import { FrontmatterClassificationPage } from './Frontmatter'
import { SerializedPagination } from './Pagination'
export interface Page {
key: string;
regularPath: string;
frontmatter: Record<string, string>;
}
export interface AppContext {
pages: Page[];
themeAPI: {
layoutComponentMap: Record<string, Vue>
};
addPage: any;
}
export interface AppContext {
frontmatterClassificationPages: FrontmatterClassificationPage[];
serializedPaginations: SerializedPagination[];
pageFilters: any;
pageSorters: any;
getLayout: (name?: string, fallback?: string) => string | undefined;
}
|
d68c2fcd6b988e1c9cff21147d238c5e511ea97d
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 7 |
Markdown
|
Enigmatrix/vuepress-plugin-blog
|
f1353a4f73b20e60d69c557ed24ee8fc82b6c5db
|
278fdd6cc6ef6620ef5957bdd468ef64bdf64c34
|
refs/heads/master
|
<repo_name>okubo-0921/git-app<file_sep>/app/models/article.rb
class Article < ApplicationRecord
calidates :title, presence: true
end
|
b1ee56945c814631c50073229067b788c8052522
|
[
"Ruby"
] | 1 |
Ruby
|
okubo-0921/git-app
|
ee9384228e6d5b3b9f25b872f2b19a1bc751ba92
|
f9a241ccaab85732b5ee4622ee38dd73ae2722bf
|
refs/heads/master
|
<file_sep>// Permet d'obtenir la hauteur de la fenêtre pour assigner une min-height au header pour un bon affichage de l'image
var x = $(window).height();
$("header").css("min-height", x + "px");
// Effet parralax entre le header et le h1
function parallax(){
var scrolltop = window.pageYOffset;
$("h1").css("top", scrolltop * 0.3 + "px");
$(".header-bg").css("top", scrolltop * 0.5 + "px");
}
$(window).scroll(function() {
parallax();
});
// Disparition de l'élément scrollDown du header quand scroll mobile
$(window).bind("touchmove", function(){
window.pageYOffset != 0 ? $(".scrollDown").addClass("hide") : $(".scrollDown").removeClass("hide");
});
// Ouverture et fermeture du menu mobile
function menuToggle() {
$(".navbar-collapse").toggleClass("show");
}
$(".navbar-toggler").on("touchstart", function(){
menuToggle();
});
// Fermeture quand clic sur lien de la nav ou scroll quand sur mobile
$(".nav-link").bind("touchstart", (function() {
setTimeout(menuToggle, 200);
}));
$(window).bind("touchmove", function() {
if($(".navbar-collapse").hasClass("show")){
setTimeout(menuToggle, 200);
}
});
// Provoquer un scroll amenant à la section
$(".scrollDown, .nav-link, .navbar-brand").click(function() {
var $this = $(this).attr("href");
$("body").animate({
scrollTop: $($this).offset().top
},
800);
});
// Affichage du message prévenant de scroll ou click pour voir le contenu dans le header
function checkHidden() {
if(!$(".scroll-msg").hasClass("hidden")){
$(".scroll-msg").addClass("hidden");
};
}
var scrollClick = false;
$(window).scroll(function(){
scrollClick = true;
checkHidden();
});
$(".scrollDown").click(function(){
scrollClick = true;
checkHidden();
});
setTimeout(function(){
if(!scrollClick) {
$(".scroll-msg").removeClass("hidden");
}
}, 5000);
// slider références
// Init
var quotesTotal = 0, quotesNum = 1;
$(".quote:first-child, .square:first-child").addClass("selected");
// Obtenir le nombre de quotes
$(".quote").each(function(){
quotesTotal ++;
});
function slide(num, total, direction){
if(direction === "left"){
if(num === 1){
$(".quote:last-child, .square:last-child").addClass("selected");
return num = total;
}
else{
num--;
$(".quote[data-value="+num+"], .square[data-target="+num+"]").addClass("selected");
return num;
}
}
else{
if(num === total){
$(".quote:first-child, .square:first-child").addClass("selected");
return num = 1;
}
else{
num++;
$(".quote[data-value="+num+"], .square[data-target="+num+"]").addClass("selected");
return num;
}
}
}
//Changement de quote via les arrows
$(".arrow").bind("touchstart click", function(){
// Empêcher le ghost click sur mobile
$(this).on("touchend", function(){
event.preventDefault();
});
// Retrait des classes selected
$(".quote.selected, .square.selected").removeClass("selected");
// Gestion de l'ordre croissant ou décroissant
if ($(this).attr("data-direction") === "left") {
quotesNum = slide(quotesNum, quotesTotal, "left");
}
else {
quotesNum = slide(quotesNum, quotesTotal);
}
});
// Changement de quote via clic des squares
$(".square").bind("touchstart click", function(){
var $this = $(this).attr("data-target");
$(".quote.selected, .square.selected").removeClass("selected")
$(".quote[data-value="+$this+"]").addClass("selected");
$(this).addClass("selected");
quotesNum = Number($this);
});
|
76cdd0a5b1e7cf0c191cb161a884cbf771043665
|
[
"JavaScript"
] | 1 |
JavaScript
|
Allandrow/allandrow.github.io
|
7995f5533443aff20080e257d993b5853f7f0f2b
|
3e3b1c0e05ed67d9bcb226b1ab4ef131d8734483
|
refs/heads/master
|
<file_sep># Field Labels
##### Defines a label for fields that is used for displaying content which can be different than the form label.
<file_sep><?php
namespace Drupal\field_labels;
use Drupal\Core\Entity\EntityInterface;
use Drupal\field_ui\FieldConfigListBuilder;
/**
* Provides lists of field config entities.
*/
class FieldLabelsFieldConfigListBuilder extends FieldConfigListBuilder {
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $field_config) {
/** @var \Drupal\field\FieldConfigInterface $field_config */
$row = parent::buildRow($field_config);
$definition = $field_config->getThirdPartySettings('field_labels');
$row['data']['label'] = [
'data' => [
'name' => [
'#markup' => '<strong> ' . $row['data']['label'] . '</strong>',
],
],
];
if (!empty($definition)) {
if (!empty($definition['form_label'])) {
$row['data']['label']['data']['form_label']['#markup'] = '<br><small>Form Label: <em>' . $definition['form_label'] . '</em></small>';
}
if (!empty($definition['display_label'])) {
$row['data']['label']['data']['display_label']['#markup'] = '<br><small>Display Label: <em>' . $definition['display_label'] . '</em></small>';
}
}
return $row;
}
}
|
ce47ad001f1714c68c44fe7fe225cbf22b154317
|
[
"Markdown",
"PHP"
] | 2 |
Markdown
|
jacerider/field_labels
|
56a72f86278642e3cdf1854216cf3d6be0e9a7b1
|
cd41523889c9e4bb55c83f61cce29d9a312ad8d8
|
refs/heads/master
|
<repo_name>anweledig/PluginLoadSample<file_sep>/SomePlugin/Test.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomePlugin
{
public class Test: MyApp.SDK.Plugin
{
public override void Loaded()
{
Console.WriteLine("Loaded");
}
public override void Unload()
{
Console.WriteLine("Unloaded");
}
}
}
<file_sep>/MyApp.SDK/Plugin.cs
using System;
namespace MyApp.SDK
{
public abstract class Plugin
{
public abstract void Loaded();
public abstract void Unload();
}
}
<file_sep>/MyApp.SDK/PluginInvoker.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MyApp.SDK
{
public static class PluginInvoker
{
public static void InvokePlugin()
{
var pluginAssembly = Assembly.Load("SomePlugin");
var pluginType = pluginAssembly.GetTypes().Where(t => typeof(Plugin).IsAssignableFrom(t)).Single();
Plugin plugin = (Plugin)pluginType.GetConstructor(new Type[0]).Invoke(null);
plugin.Loaded();
}
}
}
<file_sep>/MyApp/Program.cs
using MyApp.SDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = @"C:\Users\Pavel\Documents\visual studio 2013\Projects\MyApp\SomePlugin\bin\Debug\";
AppDomain pluginDomain = AppDomain.CreateDomain("plugin", null, setup);
pluginDomain.DoCallBack(PluginInvoker.InvokePlugin);
}
}
}
|
ccc29cb4ad2ede99710eddde27a54aac5dfd3c5f
|
[
"C#"
] | 4 |
C#
|
anweledig/PluginLoadSample
|
1293df35f396c6cb87aa5c2a4de804b984ed7797
|
9b409497f00a806fb4ac9bcce449005b491aa891
|
refs/heads/master
|
<file_sep>import java.util.Arrays;
public class TransitCalculator {
private int numOfDays = 0; // up to 30 days
private int numOfRides = 0; // individual rides the person expects to take
private static double[] prices;
// Pay-per-ride
// 7-day Unlimited Rides
// 30-day Unlimited Rides
private static double[] fareOption = { 2.75, 33.00, 127.00 };
public TransitCalculator() {
}
public TransitCalculator(int days, int rides) {
numOfDays = days;
numOfRides = rides;
String bestFareMethod = getBestFare(numOfDays, numOfRides);
System.out.println(bestFareMethod);
}
private static double unlimited7Price(int days, int rides) {
double newDays = Math.ceil((double) days / 7);
double fare = newDays * fareOption[1];
double result = fare / rides;
return result;
}
private static double unlimited30Price(int days, int rides) {
double newDays = Math.ceil((double) days / 30);
double fare = newDays * fareOption[2];
double result = fare / rides;
return result;
}
private static double payPerRide(int days, int rides) {
return fareOption[0] * rides;
}
private static double[] getRidePrices(int days, int rides) {
double[] values = new double[3];
prices = values;
values[0] = payPerRide(days, rides);
values[1] = unlimited7Price(days, rides);
values[2] = unlimited30Price(days, rides);
return values;
}
public static String getBestFare(int days, int rides) {
prices = getRidePrices(days, rides);
Arrays.sort(prices);
double min = prices[0];
String bestFare = "";
for (int i = 0; i < 3; i++) {
if (min == prices[i]) {
if (i == 0) {
bestFare = "\nYou should get the Pay-per-day option at " + min + " per ride.";
} else if (i == 1) {
bestFare = "\nYou should get the 7-day Unlimited option at " + min + " per ride.";
} else {
bestFare = "\nYou should get the 30-day Unlimited option at " + min + " per ride.";
}
}
}
return bestFare;
}
public static void main(String[] args) {
TransitCalculator obj;
obj = new TransitCalculator(5, 12);
}
}<file_sep> A Java program that determines the best fare option for someone visiting New York City who plans to use the NYC transit system.
|
39e8e8f833e2a8eff3f5df015eb7a2f3c07abf6c
|
[
"Markdown",
"Java"
] | 2 |
Java
|
AbdulelahAdam/Best-Fare-Calculator
|
0a3d9d421e85e6af49178c3fd92005d71845dd16
|
f4a237a2cf8aca3456032ce1e1a5945f628c4aa1
|
refs/heads/master
|
<repo_name>sherpal8/volunteering_for_all<file_sep>/README.md
# volunteering_for_all
A team at CTC17 focusing on creating greater awareness around volunteering, and making it easier to match skilled volunteers to organisations
# Matching volunteers and charities needing tech skills
There are a few existing solutions working on the model of charity has an opening for something and theylist it on the site. Potential volunteers browse through (possibly with signing up for notifications for some things), and then contact charity for things they might be interested in.
Local one for Aberdeen: https://www.volunteeraberdeen.org.uk
Run as part of https://www.volunteerscotland.net
They have a salesforce system that SCVO can add things to. Aberdeen site is pulling from that to get back the Aberdeen specific.
Is presented as a big list (with some search/filter features). Possibly could do with a better front end. Volunteer Glasgow has different front end to the same system.
## VollyApp
http://vollyapp.com
One Ian pointed out that was built at a hackathon at Calgary.
## Univerity volunteering opportunities
Universities have their own lists of volunteer opportunities for students.
Could possibly do a better job of tying in to this so that things are cross posted to these and volunteer Aberdeen.
# Do things the other way round
We think it would be useful to have the mirror version of the above listings where people with tech skills can register their interest in helping out charities, and then when charities need such help they can search and match to volunteers.
# Progress over the hack weekend
Draft [user stories](https://github.com/CodeTheCity/volunteering_for_all/blob/master/user_stories.md) were created to describe the scenario we were attempting to address.
A prototype website and database were created to allow the input and retrieval of charities and individuals needs.
Upon entering the homepage the user presses a button to say if they are an individual volunteering their services or a charity to looking for digital skills.
The user is then direct to a page:
- for an individual - they are requested to say what type of services they can provide and which type of charities they would prefer to assist.
- for a charity - they select the skills they need and state which sector(s) their charity is within.
Once the user has completed the webform they are directed to a page which acknowledges their submission.
The system then searches for a match between the charities and individuals. If a match is found, the charity is directed to a page which shows the matches and allows the charity to contact the individual.
<file_sep>/app/web.py
from flask import request, jsonify, Response, json, redirect, abort, render_template, session
from flask import send_file
from app import app, db, Volunteer, Charity, Category, Skill, Task, Match
@app.route('/')
def homepage():
return render_template("home.html")
@app.route('/volunteer', methods=['GET', 'POST'])
def volunteer():
if request.method == 'GET':
return render_template("volunteer.html")
else:
# save details
v = Volunteer(
email=request.form["email"],
bio=request.form["message"]
)
db.session.add(v)
db.session.commit()
# TODO: save skills and category interest
return render_template("thanks.html")
@app.route('/search', methods=['GET', 'POST'])
def search():
if request.method == 'POST':
# Do search
return render_template("results.html")
else:
return render_template("search.html")
@app.route('/contact', methods=['POST'])
def contact():
# send email
# register contact
return render_template('contact_done.html')
#Horrible hack to save me setting up proper static file serving:
@app.route('/table.css')
def table():
return send_file('templates/table.css')
@app.route('/art-dark-ethnic-1038041copy1.jpg')
def image():
return send_file('templates/art-dark-ethnic-1038041copy1.jpg')
@app.route('/static/style.css')
def style():
return send_file('templates/style.css')
<file_sep>/app/app.py
from settings import *
import os
from flask_sqlalchemy import SQLAlchemy
project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir, "volunteer.db"))
# Web API
from flask import Flask
app = Flask(__name__)
app.secret_key = SECRET_KEY
app.debug = True
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
db = SQLAlchemy(app)
volunteer_skills = db.Table('volunteer_skills',
db.Column('volunteer_id', db.Integer, db.ForeignKey('volunteer.id'), primary_key=True),
db.Column('skill_id', db.Integer, db.ForeignKey('skill.id'), primary_key=True)
)
volunteer_interest = db.Table("volunteer_interest",
db.Column('volunteer_id', db.Integer, db.ForeignKey('volunteer.id'), primary_key=True),
db.Column('category_id', db.Integer, db.ForeignKey('category.id'), primary_key=True)
)
charity_category = db.Table('charity_category',
db.Column('charity_id', db.Integer, db.ForeignKey('charity.id'), primary_key=True),
db.Column('category_id', db.Integer, db.ForeignKey('category.id'), primary_key=True)
)
class Volunteer(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(80), unique=True, nullable=False)
bio = db.Column(db.Text)
paused = db.Column(db.Boolean, default=False)
skills = db.relationship('Skill', secondary=volunteer_skills, lazy='subquery',
backref=db.backref('volunteers', lazy=True))
interested = db.relationship('Category', secondary=volunteer_interest, lazy='subquery',
backref=db.backref('volunteers', lazy=True))
class Charity(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(80), unique=True, nullable=False)
name = db.Column(db.String(80), nullable=False)
description = db.Column(db.Text)
categories = db.relationship('Category', secondary=charity_category, lazy='subquery',
backref=db.backref('charities', lazy=True))
def __repr(self):
return "<Charity: {}>".format(self.name)
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False)
def __repr__(self):
return "<Category: {}>".format(self.name)
class Skill(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False)
def __repr__(self):
return "<Skill: {}>".format(self.name)
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
owner = db.Column(db.Integer, db.ForeignKey("charity.id"), nullable=False)
description = db.Column(db.Text)
class Match(db.Model):
id = db.Column(db.Integer, primary_key=True)
task = db.Column(db.Integer, db.ForeignKey("task.id"), nullable=False)
volunteer = db.Column(db.Integer, db.ForeignKey("volunteer.id"), nullable=False)
from web import *
if __name__ == "__main__":
app.run(host="0.0.0.0")
<file_sep>/app/settings.py
SQLITE_DB = "app.db"
# Swap/override this to be an actual secret
SECRET_KEY = "<PASSWORD>"
<file_sep>/user_stories.md
# Volunteer
Alice is interested in volunteering and has some tech skills.
She comes to our site, clicks the "Interested in volunteering" button on the home page then fills in details of her bio, what she could help with and which categories of charity she wants to help.
Later she is matched with a charity looking for help, and receives an email from our system with details of what they want help with and a link to confirm she is interested in that.
She is interested so clicks the link and we pass her contact details to the charity, they get in touch and they arrange to get things done.
If she wasn't interested she could just ignore the email.
## Pause
Later Alice is busier with other stuff and doesn't want to be getting emails from us for a while so she comes back to the site, goes to her profile and clicks the pause button.
# Charity
Barry runs a charity and has a need for some help with tech stuff.
He comes to our site and clicks the "I need a volunteer" button, picks categories for what he needs help with and what his charity is, he gets a list of volunteers that match and can select one (or more) to contact.
He then enters details of what he's looking for, if there are any time restrictions etc. to send to potential volunteers.
That gets sent out to potential volunteers.
Some time later a volunteer responds that they are interested and we send Barry their contact details, he gets in touch with them and they arrange to get things done.
Barry clicks a link from his contact details email to let us know that he's got a volunteer.
<file_sep>/Acknowledge-sign-up.html
<<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Acknowledgement</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body style="padding-top:60px;">
<div class=" d-flex justify-content-center">
<div class="container colour">
<header>
<h2>Acknowledgement</h2>
<br>
</header>
<main>
<p>Thanks you for offering your skills. </p>
<br>
<p>Once we receive a match, the charity will send you an email.</p>
<br>
<p>It is then entirely up to you to decide whether or not to take discussions forward.</p>
<br>
<p>All the best with any volunteering you undertake!</p>
<a href="index.html"><p>Return to homepage</p></a>
</main>
</div>
</div>
</body>
</html>
|
e616fd27056aa513d3f2f563fe4cf69ca894e4ad
|
[
"Markdown",
"Python",
"HTML"
] | 6 |
Markdown
|
sherpal8/volunteering_for_all
|
73cd704adb503c31ff0a7fadd5662034cd249c1e
|
e9be54c84241dda462d25d8bdc820ce52598ffc5
|
refs/heads/master
|
<repo_name>AugustoEA/Bamazon<file_sep>/bamazonCustomer.js
require("dotenv").config();
var mysql = require("mysql");
var inquirer = require("inquirer");
var Table = require("cli-table2");
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: <PASSWORD>,
database: "bamazon"
});
connection.connect(function(err) {
if (err) throw err;
console.log("connected as id " + connection.threadId);
});
y
var displayItems = function(){
var query = "Select * FROM products";
connection.query(query, function(err, res){
if(err) throw err;
var displayTable = new Table ({
head: ["Item ID", "Product", "Department", "Price", "Quantity"],
});
for(var i = 0; i < res.length; i++){
displayTable.push(
[res[i].item_id,res[i].product_name, res[i].department_name, res[i].price, res[i].stock_quantity]
);
}
console.log(displayTable.toString());
buyProduct();
});
}
displayItems();
function buyProduct() {
inquirer.prompt([
{
type: "input",
name: "item",
message: "Please enter product ID",
},
{
type: "input",
name: "quantity",
message: "Please enter quantity",
},
])
.then(function (answers) {
var itemRequested = answers.item;
var quantityRequested = answers.quantity;
orderItems(itemRequested, quantityRequested);
});
};
function orderItems(item, quantity) {
connection.query("SELECT * FROM products WHERE ?" , [{item_id: item}], function (err,res) {
console.log(res);
var update = res[0]
console.log(quantity);
console.log(update.stock_quantity);
if(err){console.log(err)};
if(quantity <= update.stock_quantity){
var total = update.price * quantity;
console.log("Product available!");
console.log("Total for " + quantity + " " + update.product_name + " is " + total);
var newQuantity = update.stock_quantity - quantity;
connection.query("UPDATE products SET ? WHERE ?" , [{stock_quantity: newQuantity}, {item_id: item}], function(err){
if(err){console.log(err)};
console.log("Thank you for buying with us!")
displayItems();
});
}
else{
console.log("Oops! out of stock!");
displayItems();
};
});
};
<file_sep>/README.md
# Bamazon
## Overview
This is a "Amazon copycat" using SQL as database. The app take orders from customers and as the orders are completed, it reduces the stock total. If an attempt to buy an product out of stock, or purchase more items that are exist in stock at the moment, the order will not be completed and a message will appear showing that is not possible to complete the order.
## Images




## Built using
* VS Code
* JavasSript
* Node.js
* Inquirer
* MySQL
* Cli-table
## Developer
<NAME>
<file_sep>/bamazonSchema.sql
DROP DATABASE IF EXISTS bamazon;
CREATE DATABASE bamazon;
USE bamazon;
CREATE TABLE products (
item_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(100) NOT NULL,
department_name VARCHAR(100) NOT NULL,
price DECIMAL(10,2) NOT NULL,
stock_quantity INT NOT NULL
);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Chubbs Wooden Hand", "Memorabilia", 149.99, 01),
("Infinity Gauntlet", "Universal Weapons", 499.99, 03),
("Captain Crunch's Wooden Leg", "Memorabilia", 149.99, 02),
("Silver Surfers Silver Surfboard" , "Universal Weapons", 299.99, 01),
("Water Bottle", "Supplies", 4.99, 97),
("Salt Shaker", "Home Goods", 1.99, 457),
("Flying Broom", "Witchcraft Supplies", 299.99, 13);
SELECT * FROM products
/*DELETE * FROM products*/
|
cc01ca7299ce15a2e4f80068e40227f6b13b0f0a
|
[
"JavaScript",
"SQL",
"Markdown"
] | 3 |
JavaScript
|
AugustoEA/Bamazon
|
5bc3f22cc116a1c4e71683140a0deebb23b4ebc2
|
46d7263e9fbe89f1745c8f3a7f6cc96cccf9616b
|
refs/heads/master
|
<repo_name>xiaotujiChen/LeetCode<file_sep>/src/com/xiaode/EasySolutions/TwoSumII.java
package com.xiaode.EasySolutions;
/**
* Created by leonard on 27/02/2017.
*/
public class TwoSumII {
/**
* 167. Two Sum II - Input array is sorted
* Given an array of integers that is already sorted in ascending order, find two numbers
* such that they add up to a specific target number.The function twoSum should return indices
* of the two numbers such that they add up to the target, where index1 must be less than index2.
* Please note that your returned answers (both index1 and index2) are not zero-based.
* You may assume that each input would have exactly one solution and you may not use the same element twice.
*/
public int[] twoSum(int[] numbers, int target){
int head =0 ;
int tail = numbers.length-1;
int[] result = new int[2];
while(head<tail){
long temp = numbers[head]+numbers[tail];
if(temp < target) head++;
if(temp> target) tail++;
if(temp == target ) {
result[0] = head+1;
result[1] = tail+1;
break;
}
}
return result;
}
}
<file_sep>/src/com/xiaode/EasySolutions/RelativeRanks.java
package com.xiaode.EasySolutions;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by leonard on 25/02/2017.
*/
public class RelativeRanks {
/**
* 506. Relatives Ranks
* Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will
* be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".
*/
public String[] fingRelativeRanks(int[] nums){
String[] strings = {"Gold Medal","Silver Medal","Bronze Medal"};
String[] result = new String[nums.length];
Arrays.sort(nums);
for (int i = 0;i<nums.length;i++){
if(i<=2){
result[i] = strings[i];
}else {
result[i] = String.valueOf(nums[i]);
}
}
return result;
}
}
<file_sep>/src/com/xiaode/Main.java
package com.xiaode;
import com.xiaode.EasySolutions.*;
import com.xiaode.HardSolutions.MedianOfTwoSortedArrays;
import com.xiaode.MediumSolutions.CountingBits;
import com.xiaode.MediumSolutions.ContainerWithMostWater;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
private static final Logger myLogger = Logger.getLogger("com.xiaode");
public static void main(String[] args) {
//myLogger.getGlobal().setLevel(Level.OFF);
// myLogger.getGlobal().info("begin");
// Scanner in = new Scanner(System.in);
// int maxQps= Integer.valueOf(in.nextLine());
// final String[] rtList = in.nextLine().split(",");
// final int requestNum = Integer.valueOf(in.nextLine());
// final int threadNum = Integer.valueOf(in.nextLine());
// System.out.println(doneTime(maxQps, rtList, requestNum, threadNum));
System.out.println(ValidParentheses.isValid("[])"));
}
/**
* 如果使用最优的最大吞吐量负载均衡算法,按照最优模型多久能够处理完所有请求,单位毫秒。
* @return
*/
static long doneTime(int maxQps,String[] rtList,int requestNum,int threadNum) {
//TODO
long totaltime = 0;
totaltime = (long)(requestNum/(maxQps * rtList.length)) * threadNum;
return totaltime;
}
}
//
//输入:
// 输入数据包含5行数字: 第一行是每台broker的极限QPS 第二行是broker rt列表,用逗号分割,几个rt表示几个broker 第三行是消息生产请求总数 第四行是最大并发线程数
// 输出:
// 按照最大吞吐量执行完所有请求,需要耗时多少毫秒
// 输入范例:
// 200
// 1,1,1,10,10
// 5000
// 10
// 输出范例:
// 5000
|
cd53ad512059983d461616c39392722b5413054b
|
[
"Java"
] | 3 |
Java
|
xiaotujiChen/LeetCode
|
73db8b6ad1215b9045e875ff49e6c3635c6bcff0
|
9b82cec3c8ba2d6d6a2b95bd10e66a60913a26fd
|
refs/heads/master
|
<file_sep>memo={}
def maxVal(w, v, i, ws):
try:
return memo[(i,ws)]
except KeyError:
if i == 0:
if w[i] <= ws:
memo[(i, ws)] = v[i]
return v[i]
else:
memo[(i, ws)] = 0
return 0
without_i = maxVal(w, v, i-1, ws)
if w[i] > ws:
memo[(i, ws)] = without_i
return without_i
else:
with_i = maxVal(w, v, i-1, ws-w[i]) + v[i]
res = max(without_i, with_i)
memo[(i, ws)] = res
return res
w = [5, 3, 2]
v = [9, 7, 8]
val = maxVal(w, v, 2, 5)
print(val)<file_sep>from atexit import register
from time import ctime, sleep
from threading import Thread, Lock, BoundedSemaphore
from random import randrange
lock = Lock()
MAX = 5 #信号量大小
candytray = BoundedSemaphore(MAX)
def refull():
with lock:
print('refulling...')
try:
candytray.release()
except ValueError:
print('Is Full!')
else:
print('OK')
def buy():
with lock:
print('buying...')
if candytray.acquire(False): #加入False参数,如果信号量为空,则不阻塞,而是返回错误,
print('OK')
else:
print('empty')
def consumer(loops):
for i in range(loops):
refull()
sleep(randrange(3)) #睡眠时间尽量长于creater的概率尽量大,
def creater(loops):
for i in range(loops):
buy()
sleep(randrange(5))
def main():
print('starting...')
n = randrange(2,6)
print('the candy mechine full with {0}'.format(MAX))
Thread(target=creater,args=(randrange(n,n+MAX+2),)).start()
Thread(target=consumer, args=(randrange(n,n+MAX+2),)).start()
@register
def atexitt():
print('The end!')
if __name__ == '__main__':
main()
<file_sep>class MyBaseClass:
def __init__(self, value):
self.value = value
class TimesFive(MyBaseClass):
def __init__(self, value):
super(TimesFive, self).__init__(value)
self.value *= 5
class PlusTwo(MyBaseClass):
def __init__(self, value):
super(PlusTwo, self).__init__(value)
self.value += 2
class GoodWay(TimesFive, PlusTwo):
def __init__(self, value):
super(GoodWay, self).__init__(value)
foo = GoodWay(5)
print('Should be 5*(5+2) and is ', foo.value)
print(GoodWay.mro())<file_sep>class SkipIterator:
def __init__(self, wrapped):
self.wrapped = wrapped
self.offset = 0
def __next__(self):
if self.offset >= len(self.wrapped):
raise StopIteration
else:
item = self.wrapped[self.offset]
self.offset+=2
return item
class SkipObject:
def __init__(self, wrapped):
self.wrapped = wrapped
def __iter__(self):
return SkipIterator(self.wrapped)
if __name__ == '__main__':
hhh = 'hahaha'
skipper = SkipObject(hhh)
for i in skipper:
print(i)
I = iter(skipper)
print(next(I), next(I), next(I))
<file_sep>def sum(t):
tmp=0
for k in t:
if not isinstance(k,list):
tmp+=k
else:
tmp+=sum(k)
return tmp
if __name__=='__main__':
x=[1,[2,[3,4,5,[6,7,[8,9]]]]]
t=sum(x)
print(t)
<file_sep>from collections import defaultdict
def xor(l):
tmp = 0
for item in l:
tmp ^= item
return tmp
def odd(arr):
status = defaultdict(int)
for i in arr:
if status[i] == 1:
del status[i]
else:
status[i] = 1
res = [i for i in status.keys()]
return res
l = [1,2,3,4,5,4,3,2,1]
t = xor(l)
print(t)
res = odd(l)
print(res)<file_sep>from threading import Thread
from time import ctime, sleep
loops = [4, 2]
def loop(nloop, nsec):
print('loops ', nloop, 'starting at:', ctime())
sleep(nsec)
print('loop', nloop, 'end at:', ctime())
def main():
print('starting at:', ctime())
threads = []
for i in range(len(loops)):
t = Thread(target=loop, args=(i,loops[i]))
threads.append(t)
for i in range(len(loops)):
threads[i].start()
for i in range(len(loops)):
threads[i].join()
print('all done at:', ctime())
if __name__ == '__main__':
main()<file_sep>def consumer():
while True:
line = yield
print(line.upper())
def productor():
with open('text.txt') as file:
for i, line in enumerate(file):
yield line
print("{0} lines".format(i))
c = consumer()
c.__next__()
for i in productor():
c.send(i)<file_sep>def maxVal(w, v, i, ws):
if i == 0:
if w[i] <= ws:
return v[i]
else:
return 0
without_i = maxVal(w, v, i-1, ws)
if w[i] > ws:
return without_i
else:
with_i = maxVal(w, v, i-1, ws-w[i]) + v[i]
return max(without_i, with_i)
w = [5, 3, 2]
v = [9, 7, 8]
val = maxVal(w, v, 2, 5)
print(val)<file_sep>class leak(object):
def __init__(self):
print("object with {0} was born".format(id(self)))
while(True):
A = leak()
B = leak()
A.b = B
B.a = A
A = None
B = None<file_sep>from functools import wraps
def tracer(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
print('%s(%r,%r)->%r'%(func.__name__,args,kwargs,result))
return result
return wrapper
@tracer
def fibonacci(n):
if n in (0,1):
return n
return (fibonacci(n-1)+fibonacci(n-2))
fibonacci(3)
print(fibonacci)
print('help:')
help(fibonacci)<file_sep>def index_words1(text):
result = []
if text:
result.append(0)
for index, letter in enumerate(text):
if letter == ' ':
result.append(index+1)
return result
def index_words2(text):
if text:
yield 0
for index, letter in enumerate(text):
if letter == ' ':
yield index+1
if __name__ == '__main__':
hhh = 'Every dog has its day!'
result = index_words1(hhh)
print('result1', result)
result = list(index_words2(hhh))
print('result2:', result)
<file_sep>def play2(l):
try:
for i in l:
for num in play2(i):
yield num
except TypeError:
yield l
def play(l):
res = []
for i in l:
if isinstance(i, list):
t=list(play(i))
for j in t:
res.append(j)
else:
res.append(i)
return res
def sum(l):
res = 0
for i in l:
if not isinstance(i, list):
res+=i
else:
res+=sum(i)
return res
def play3(l):
try:
try: l+''
except TypeError: pass
else: raise TypeError
for i in l:
for s in play3(i):
yield s
except TypeError:
yield l
if __name__ == '__main__':
l = [1,[2,[3,4,[5,6]]]]
l2=['abs',['de','fg',['hi','jk']]]
print(sum(l))
print('play',list(play(l2)))
print('play2',list(play2(l2)))
print('play3',list(play3(l2)))<file_sep>import sys
def solution(array):
second = -10000000
st = []
for num in array[::-1]:
if num<second:
return True
elif st and num>st[-1]:
second=st.pop()
st.append(num)
return False
if __name__=='__main__':
s=[3,1,4,2]
print(solution(s))
<file_sep>from random import randint
from threading import Thread
from queue import Queue
from time import sleep
def writeq(queue):
print('starting put queue...')
queue.put('hahaha', 1)
print('size now', queue.qsize())
def readq(queue):
print('starting get queue...')
val = queue.get(1)
print('consume from queu...size now', queue.qsize())
def writer(queue, loops):
for i in range(loops):
writeq(queue)
sleep(randint(1, 3))
def reader(queue, loops):
for i in range(loops):
readq(queue)
sleep(randint(2, 5))
funcs = [writer, reader]
def main():
nloops = randint(2, 5)
q = Queue(32)
threads = []
for i in range(len(funcs)):
t = Thread(target=funcs[i], args=(q, nloops))
threads.append(t)
for i in range(len(funcs)):
threads[i].start()
for i in range(len(funcs)):
threads[i].join()
print('all done')
if __name__ == '__main__':
main()<file_sep>def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
l = len(nums)
if l < 3:
return []
res = []
nums.sort()
start = 0;
end = l - 1
flag = 0
while start < end - 1:
tmp = nums[start] + nums[end]
target = 0 - tmp
mid = (start + end) // 2
tstart = start;
tend = end
while tstart < mid < tend and nums[tstart] <= target <= nums[tend]:
if nums[mid] == target:
flag = 1
res.append([nums[start], nums[mid], nums[end]])
break
elif nums[mid] > target:
t = mid
mid = (tstart + mid) // 2
tend = t
else:
t = mid
mid = (mid + tend) // 2
tstart = t
if flag == 1:
flag = 0
subnums = nums[start:end]
res.append(threeSum(subnums))
subnums = nums[start + 1:end+1]
res.append(threeSum(subnums))
t = start
while start < end and nums[t] == nums[start]:
start += 1
t = end
while start < end and nums[t] == nums[end]:
end -= 1
else:
if tmp < 0:
start += 1
else:
end -= 1
return res
if __name__ == '__main__':
res=threeSum([-2,0,1,1,2])
print(res)<file_sep>def quicksort(array):
smaller=[];larger=[]
if len(array)<1:
return array
pv=array.pop()
for num in array:
if num>pv:
larger.append(num)
else:
smaller.append(num)
return quicksort(smaller)+[pv]+quicksort(larger)
if __name__=='__main__':
numarray=[5,4,3,6,7,2,9,1,2,9]
numarray=quicksort(numarray)
sarray=['hahahahah','heheheheh','abc','every dog has its lucky day']
sarray=quicksort(sarray)
print(numarray,'\n',sarray)<file_sep>class MyBaseClass:
def __init__(self, value):
self.value = value
class TimesFive(MyBaseClass):
def __init__(self, value):
MyBaseClass.__init__(self, value)
self.value *= 2
class PlusTwo(MyBaseClass):
def __init__(self, value):
MyBaseClass.__init__(self, value)
self.value += 2
class ThisWay(TimesFive, PlusTwo):
def __init__(self, value):
TimesFive.__init__(self, value)
PlusTwo.__init__(self, value)
foo = ThisWay(5)
print('Should be (5*5)+2 but is ', foo.value)
<file_sep>class MyBaseClass:
def __init__(self, value):
self.value = value
class TimesTwo:
def __init__(self):
self.value *= 2
class PlusFive:
def __init__(self):
self.value += 5
class OneWay(MyBaseClass, TimesTwo, PlusFive):
def __init__(self,value):
MyBaseClass.__init__(self, value)
TimesTwo.__init__(self)
PlusFive.__init__(self)
class AnotherWay(MyBaseClass, PlusFive, TimesTwo):
def __init__(self,value):
MyBaseClass.__init__(self, value)
TimesTwo.__init__(self)
PlusFive.__init__(self)
foo = OneWay(5)
print('OneWay (5*2)+5=', foo.value)
foo = AnotherWay(5)
print('AnotherWay:', foo.value)<file_sep># practice
这里都是我平时用python做题的源代码<file_sep>from random import randint
from time import ctime, sleep
from queue import Queue
from
<file_sep>from atexit import register
from time import sleep, ctime
from threading import currentThread, Thread, Lock
from random import randrange
class cleanOutput(list):
def __str__(self):
return ','.join(self)
loops = [randrange(2, 5) for x in range(randrange(3, 7))]
remaining = cleanOutput()
lock = Lock()
def loop(nsec):
myname = currentThread().name
with lock:
remaining.append(myname)
print('{0} starting at {1}'.format(myname, ctime()))
sleep(nsec)
with lock:
remaining.remove(myname)
print('{0} end at {1}'.format(myname, ctime()))
print('remaining {0}'.format(remaining))
def main():
for i in loops:
Thread(target=loop, args=(i,)).start()
@register
def _atexit():
print("end!")
if __name__ == '__main__':
main()
<file_sep>from random import randint
def makeDict(text):
#替换换行符和引号
text = text.replace('\n', ' ')
text = text.replace('\“', '')
text = text.replace('\”', '')
punc = [',', '。', '?', ';', ':', '!']
for symbol in punc:
text = text.replace(symbol, ' '+symbol+' ')
words = [word for word in text if word != '']
wordict = {}
for i in range(1, len(text)):
if words[i-1] not in wordict:
wordict[words[i-1]] = {}
if words[i] not in wordict[words[i-1]]:
wordict[words[i-1]][words[i]] = 0
wordict[words[i-1]][words[i]] += 1
return wordict
def wordLen(wordict):
sum = 0
for key, value in wordict.items():
sum += value
return sum
def retriveRandomWord(wordict):
"""
感觉这个函数计算每个单词的机率的思路太帅了
:param wordict:
:return:
"""
randindex = randint(1, wordLen(wordict))
for key, value in wordict.items():
randindex -= value
if randindex <= 0:
return key
with open('test.txt','r') as f:
t = f.read()
text = str(t)
wordict = makeDict(text)
length = 200
chain = ''
currentword = '想'
for i in range(0, length):
chain += currentword
currentword = retriveRandomWord(wordict[currentword])
with open("res.txt",'w') as file:
file.write(chain)
print(chain)
|
ec90be4ec0f8acfbdcc5eb20b440d46c36e52219
|
[
"Markdown",
"Python"
] | 23 |
Python
|
ZmN5/practice
|
c5a109e42bd7f0984f77a3f1a90e06d467295846
|
7adfba260d91875b42ff639839781a2a6c68ff81
|
refs/heads/master
|
<repo_name>Hemanth4188/pythonp<file_sep>/testp.py
print("This HemanthKumar")
print("fuck off")
|
170f94ecb2afada9c10ca93b850e9ee302c52a42
|
[
"Python"
] | 1 |
Python
|
Hemanth4188/pythonp
|
4f21c03bae995a224947231460830342cbf82c55
|
7f73e6f98daade3fcf05bd84677f81cfac2806e2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.