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/main | <repo_name>idkjs/ppx-install-test<file_sep>/src/MonadPpxLetExample.bs.js
// Generated by ReScript, PLEASE EDIT WITH CARE
'use strict';
var Curry = require("rescript/lib/js/curry.js");
var Printf = require("rescript/lib/js/printf.js");
function $$return(x) {
return x;
}
function bind(x, f) {
return Curry._1(f, x);
}
function map(x, f) {
return Curry._1(f, x);
}
function both(x, y) {
return [
x,
y
];
}
var Open_on_rhs = {
$$return: $$return
};
var Let_syntax = {
$$return: $$return,
bind: bind,
map: map,
both: both,
Open_on_rhs: Open_on_rhs
};
var Let_syntax$1 = {
$$return: $$return,
Let_syntax: Let_syntax
};
var X = {
Let_syntax: Let_syntax$1
};
function _mf(a) {
return a + 1 | 0;
}
function _mf$p(a, b, c) {
var param_1 = [
b,
c
];
var match = param_1;
var match$1 = match[1];
return (a + match[0] | 0) + Math.imul(match$1[0], match$1[1]) | 0;
}
function _mg(a) {
return a + 1 | 0;
}
function _mg$p(a, b, c) {
var param_1 = [
b,
c
];
var match = param_1;
var match$1 = match[1];
return (a + match[0] | 0) + Math.imul(match$1[0], match$1[1]) | 0;
}
function _mh(a) {
return a === 0;
}
function _mi(a) {
return a === 0;
}
function _mif(a) {
if (a) {
return true;
} else {
return false;
}
}
function _mif$p(a) {
if (a) {
return true;
} else {
return false;
}
}
var Monad_example = {
X: X,
_mf: _mf,
_mf$p: _mf$p,
_mg: _mg,
_mg$p: _mg$p,
_mh: _mh,
_mi: _mi,
_mif: _mif,
_mif$p: _mif$p
};
function map2(a, b, f) {
return Curry._2(f, a, b);
}
function map3(a, b, c, f) {
return map2([
a,
b
], c, (function (param, c) {
return Curry._3(f, param[0], param[1], c);
}));
}
function map4(a, b, c, d, f) {
return map2([
a,
b
], [
c,
d
], (function (param, param$1) {
return Curry._4(f, param[0], param[1], param$1[0], param$1[1]);
}));
}
var Let_syntax$2 = {
$$return: $$return,
bind: bind,
map: map,
both: both,
Open_on_rhs: Open_on_rhs,
map2: map2,
map3: map3,
map4: map4
};
var Let_syntax$3 = {
$$return: $$return,
Let_syntax: Let_syntax$2
};
var _x = map4(1, "hi", 2.34, true, (function (a, b, c, d) {
return Curry._4(Printf.sprintf(/* Format */{
_0: {
TAG: /* Int */4,
_0: /* Int_d */0,
_1: /* No_padding */0,
_2: /* No_precision */0,
_3: {
TAG: /* Char_literal */12,
_0: /* ' ' */32,
_1: {
TAG: /* String */2,
_0: /* No_padding */0,
_1: {
TAG: /* Char_literal */12,
_0: /* ' ' */32,
_1: {
TAG: /* Float */8,
_0: /* Float_f */0,
_1: /* No_padding */0,
_2: /* No_precision */0,
_3: {
TAG: /* Char_literal */12,
_0: /* ' ' */32,
_1: {
TAG: /* Bool */9,
_0: /* No_padding */0,
_1: /* End_of_format */0
}
}
}
}
}
}
},
_1: "%d %s %f %b"
}), a, b, c, d);
}));
var Example_with_mapn = {
Let_syntax: Let_syntax$3,
_x: _x
};
exports.Monad_example = Monad_example;
exports.Example_with_mapn = Example_with_mapn;
/* _x Not a pure module */
<file_sep>/README.md
# ppx-install test
The only official ReScript starter template.
## Installation
```sh
npm install
```
## Build
- Build ppx: `npm run build:ppx`
- Build: `npm run build`
- Clean: `npm run clean`
- Build & watch: `node src/FooBindBar.bs.js`
## match%sub is not supported
```sh
rescript: [2/10] src/Test.ast
FAILED: src/Test.ast
We've found a bug for you!
/Users/mando/Github/ppx-install-test/src/Test.res:272:7-275:7
270 ┆ let _arrow_example_1 = (a): X.c<_> =>
271 ┆ %sub(
272 ┆ switch a {
273 ┆ | 0 => return(X.return_v(true))
274 ┆ | _ => return(X.return_v(false))
275 ┆ }
276 ┆ )
277 ┆
match%sub is not supported
rescript: [3/10] src/TestRe.ast
FAILED: src/TestRe.ast
We've found a bug for you!
/Users/mando/Github/ppx-install-test/lib/bs
match%sub is not supported
```
<file_sep>/src/FooBindBar.bs.js
// Generated by ReScript, PLEASE EDIT WITH CARE
'use strict';
var Curry = require("rescript/lib/js/curry.js");
console.log("Hello, ReScript!");
function $$return(x) {
return x;
}
function bind(x, f) {
return Curry._1(f, x);
}
function map(x, f) {
return Curry._1(f, x);
}
function both(x, y) {
return [
x,
y
];
}
var Open_on_rhs = {
$$return: $$return
};
var Let_syntax = {
$$return: $$return,
bind: bind,
map: map,
both: both,
Open_on_rhs: Open_on_rhs
};
var Let_syntax$1 = {
$$return: $$return,
Let_syntax: Let_syntax
};
var X = {
Let_syntax: Let_syntax$1
};
function _mf(a) {
return a + 1 | 0;
}
function _mf$p(a, b, c) {
var param_1 = [
b,
c
];
var match = param_1;
var match$1 = match[1];
return (a + match[0] | 0) + Math.imul(match$1[0], match$1[1]) | 0;
}
function _mg(a) {
return a + 1 | 0;
}
function _mg$p(a, b, c) {
var param_1 = [
b,
c
];
var match = param_1;
var match$1 = match[1];
return (a + match[0] | 0) + Math.imul(match$1[0], match$1[1]) | 0;
}
function _mh(a) {
return a === 0;
}
function _mi(a) {
return a === 0;
}
function _mif(a) {
if (a) {
return true;
} else {
return false;
}
}
function _mif$p(a) {
if (a) {
return true;
} else {
return false;
}
}
var Monad_example = {
X: X,
_mf: _mf,
_mf$p: _mf$p,
_mg: _mg,
_mg$p: _mg$p,
_mh: _mh,
_mi: _mi,
_mif: _mif,
_mif$p: _mif$p
};
function $$return$1(x) {
return x;
}
function map$1(x, f) {
return Curry._1(f, x);
}
function both$1(x, y) {
return [
x,
y
];
}
var Open_on_rhs$1 = {
flag: 66,
anon: 77
};
var Let_syntax$2 = {
$$return: $$return$1,
map: map$1,
both: both$1,
Open_on_rhs: Open_on_rhs$1
};
var Let_syntax$3 = {
$$return: $$return$1,
Let_syntax: Let_syntax$2
};
var X$1 = {
Let_syntax: Let_syntax$3
};
function _ag(a) {
return a + 1 | 0;
}
function _ag$p(a, b, c) {
var param_1 = [
b,
c
];
var match = param_1;
var match$1 = match[1];
return (a + match[0] | 0) + Math.imul(match$1[0], match$1[1]) | 0;
}
function _ai(a) {
return a === 0;
}
var Applicative_example = {
X: X$1,
_ag: _ag,
_ag$p: _ag$p,
_ai: _ai
};
function _ag$1(a) {
return a + 1 | 0;
}
var Example_without_open = {
_ag: _ag$1
};
function map2(a, b, f) {
return Curry._2(f, a, b);
}
function map3(a, b, c, f) {
return map2([
a,
b
], c, (function (param, c) {
return Curry._3(f, param[0], param[1], c);
}));
}
function map4(a, b, c, d, f) {
return map2([
a,
b
], [
c,
d
], (function (param, param$1) {
return Curry._4(f, param[0], param[1], param$1[0], param$1[1]);
}));
}
var Let_syntax$4 = {
$$return: $$return,
bind: bind,
map: map,
both: both,
Open_on_rhs: Open_on_rhs,
map2: map2,
map3: map3,
map4: map4
};
var Let_syntax$5 = {
$$return: $$return,
Let_syntax: Let_syntax$4
};
var _x = map4(1, "hi", 2.34, true, (function (a, b, c, d) {
console.log(a, b, c, d);
}));
var Example_with_mapn = {
Let_syntax: Let_syntax$5,
_x: _x
};
console.log("Example_with_mapn!");
console.log(_x);
var xta = 2;
console.log("Example_without_open!");
console.log(xta + 1 | 0);
exports.Monad_example = Monad_example;
exports.Applicative_example = Applicative_example;
exports.Example_without_open = Example_without_open;
exports.Example_with_mapn = Example_with_mapn;
exports.xta = xta;
/* Not a pure module */
| 2e23c61bd4ddb021d63ef9132f16932e9e44094d | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | idkjs/ppx-install-test | e3843ad6b56599dbad705eefeb0fbc2a32e99c69 | 5b37c18cf5def25ec59afbba50cd989ee6d23c62 |
refs/heads/master | <file_sep>using IBSApps.Web.Areas.Lottery.Data.Entities;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.Lottery.Models
{
public class HourViewModel : LottHour
{
[Display(Name = "Banking ")]
[Range(1, int.MaxValue, ErrorMessage = "You must select a Zona.")]
public int IdBanking { get; set; }
[Display(Name = "Time")]
public string Timer { get; set; }
public IEnumerable<SelectListItem> ListBanking { get; set; }
}
}
<file_sep>using IBSApps.Web.Areas.Lottery.Data.Entities;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
namespace IBSApps.Web.Areas.Lottery.Models
{
public class CollectorViewModel : LottCollector
{
public IEnumerable<SelectListItem> ListCollector { get; set; }
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.Lottery.Data.Entities
{
public class LottStation : IEntity
{
public int IdType { get; set; }
public int Id { get; set; }
[Display(Name = "Estación")]
[MaxLength(60, ErrorMessage = "The field {0} only can contain {1} characters length.")]
[Required]
public string Name { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Fecha Ultimo Ticket")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? FechaUltimoTicket { get; set; }
public LottBanking LottBanking { get; set; }
public LottCollector LottCollector { get; set; }
[Display(Name = "ReImprimir Ticket")]
public bool ReImprimirTicket { get; set; }
[Display(Name = "Copiar de Ticket")]
public bool CopiarTicket { get; set; }
[Display(Name = "Venta Futura de Ticket")]
public bool VentaFuturaTicket { get; set; }
// Activar Jugada
[Display(Name = "Activar Quiniela")]
public bool ActivarQuiniela { get; set; }
[Display(Name = "Activar Pale")]
public bool ActivarPale { get; set; }
[Display(Name = "Activar Super Pale")]
public bool ActivarSuperPale { get; set; }
[Display(Name = "Activar Tripleta")]
public bool ActivarTripleta { get; set; }
[Display(Name = "Activar Cash3 Straight")]
public bool ActivarCash3Straight { get; set; }
[Display(Name = "Activar Cash3 Box")]
public bool ActivarCash3Box { get; set; }
[Display(Name = "Activar Play4 Straight")]
public decimal ActivarPlay4Straight { get; set; }
[Display(Name = "Activar Play4 Box")]
public bool ActivarPlay4Box { get; set; }
[Display(Name = "Activar Pick5 Straight")]
public bool ActivarPick5Straight { get; set; }
[Display(Name = "Activar Pick5 Box")]
public bool ActivarPick5Box { get; set; }
//// Monto Maxima Jugada
//[Display(Name = "Valor Maximo Quiniela")]
//public decimal ValorMaximoQuiniela { get; set; }
//[Display(Name = "Valor Maximo Pale")]
//public decimal ValorMaximoPale { get; set; }
//[Display(Name = "Valor Maximo Super Pale")]
//public decimal ValorMaximoSuperPale { get; set; }
//[Display(Name = "Valor Maximo Tripleta")]
//public decimal ValorMaximoTripleta { get; set; }
//[Display(Name = "Valor Maximo Cash3 Straight")]
//public decimal ValorMaximoCash3Straight { get; set; }
//[Display(Name = "Valor Maximo Cash3 Box")]
//public decimal ValorMaximoCash3Box { get; set; }
//[Display(Name = "Valor Maximo Play4 Straight")]
//public decimal ValorMaximoPlay4Straight { get; set; }
//[Display(Name = "Valor Maximo Play4 Box")]
//public decimal ValorMaximoPlay4Box { get; set; }
//[Display(Name = "Valor Maximo Pick5 Straight")]
//public decimal ValorMaximoPick5Straight { get; set; }
//[Display(Name = "Valor Maximo Pick5 Box")]
//public decimal ValorMaximoPick5Box { get; set; }
//// Encabezado y Pie de Ticket
//[Display(Name = "Encabezado Ticket")]
//[MaxLength(60)]
//public string EncabezadoTicket01 { get; set; }
//[MaxLength(60)]
//public string EncabezadoTicket02 { get; set; }
//[MaxLength(60)]
//public string EncabezadoTicket03 { get; set; }
//[MaxLength(60)]
//public string EncabezadoTicket04 { get; set; }
//[Display(Name = "Pie Ticket")]
//[MaxLength(60)]
//public string PieTicket01 { get; set; }
//[MaxLength(60)]
//public string PieTicket02 { get; set; }
//[MaxLength(60)]
//public string PieTicket03 { get; set; }
//[MaxLength(60)]
//public string EPieTicket04 { get; set; }
public User User { get; set; }
public DateTime? FechaHora { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System.Collections.Generic;
namespace IBSApps.Web.Areas.Lottery.Data.Entities
{
public class LottRuleNumber : IEntity
{
public int IdType { get; set; }
public int Id { get; set; }
public ICollection<LottBanking> LottBankings { get; set; }
public ICollection<LottRuleNumberType> LottRuleNumberTypes { get; set; }
public int Number01 { get; set; }
public int Number02 { get; set; }
public int Number03 { get; set; }
public int Number04 { get; set; }
public int Number05 { get; set; }
public int Number06 { get; set; }
public int Number07 { get; set; }
public int Number08 { get; set; }
public int Number09 { get; set; }
public int Number10 { get; set; }
public int Number11 { get; set; }
public int Number12 { get; set; }
public int Number13 { get; set; }
public int Number14 { get; set; }
public int Number15 { get; set; }
public int Number16 { get; set; }
public int Number17 { get; set; }
public int Number18 { get; set; }
public int Number19 { get; set; }
public int Number20 { get; set; }
public int Number21 { get; set; }
public int Number22 { get; set; }
public int Number23 { get; set; }
public int Number25 { get; set; }
}
}
<file_sep>using IBSApps.Web.Areas.CuentasCobrar.Data.Entities;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.CuentasCobrar.Models
{
public class CustomerViewModel : CxcCustomer
{
[Display(Name = "Tipo CtaCobrar")]
[Range(1, int.MaxValue, ErrorMessage = "You must select a Tipo CtaCobrar.")]
public int IdTipo { get; set; }
[Display(Name = "Estado Civil")]
[Range(1, int.MaxValue, ErrorMessage = "You must select a Estado Civil.")]
public int IdeCivil { get; set; }
[Display(Name = "Tipo de NCF")]
[Range(1, int.MaxValue, ErrorMessage = "You must select a NCF.")]
public int IdNcf { get; set; }
[Display(Name = "Sexo")]
[Range(1, int.MaxValue, ErrorMessage = "You must select a Sexo.")]
public int IdSexo { get; set; }
public IEnumerable<SelectListItem> Tiposcxc { get; set; }
public IEnumerable<SelectListItem> ListeCivil { get; set; }
public IEnumerable<SelectListItem> ListNcf { get; set; }
public IEnumerable<SelectListItem> ListSexo { get; set; }
}
}
<file_sep>using IBSApps.Web.Areas.CuentasCobrar.Data.Entities;
using IBSApps.Web.Areas.Lottery.Data.Entities;
using IBSApps.Web.Data.Entities;
using IBSApps.Web.Helpers;
using Microsoft.AspNetCore.Identity;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace IBSApps.Web.Data
{
public class SeedDb
{
private readonly DataContext _context;
private readonly IUserHelper _userHelper;
private readonly Random _random;
public SeedDb(DataContext context, IUserHelper userHelper)
{
_context = context;
_userHelper = userHelper;
_random = new Random();
}
public async Task SeedAsync()
{
await _context.Database.EnsureCreatedAsync();
if (!_context.CxcCities.Any())
{
await this.AddProvinciasAndProvinciasAsync();
}
var user = await _userHelper.GetUserByEmailAsync("<EMAIL>");
if (user == null)
{
user = new User
{
FirstName = "Enrique",
LastName = "Paulino",
Email = "<EMAIL>",
UserName = "<EMAIL>",
PhoneNumber = "809-710-5012"
};
var result = await _userHelper.AddUserAsync(user, "123456");
if (result != IdentityResult.Success)
{
throw new InvalidOperationException("Could not create the user in seeder");
}
}
if (!_context.Companies.Any())
{
this.AddCompany("Banca IBS");
await _context.SaveChangesAsync();
}
if (!_context.CxcTypes.Any())
{
this.AddTipocxc("Cuenta Cobrar Socios", user);
this.AddTipocxc("Cuenta Cobrar Empleados", user);
await _context.SaveChangesAsync();
}
if (!_context.CxcNcf.Any())
{
this.AddTipoNcf("Con Valor Fiscal");
this.AddTipoNcf("Para Consumidor Final");
this.AddTipoNcf("Gubernamental");
this.AddTipoNcf("Regimenes Especiales");
await _context.SaveChangesAsync();
}
if (!_context.CxcCustomers.Any())
{
this.AddCustomer("Enrique", user);
await _context.SaveChangesAsync();
}
if (!_context.CxcRegions.Any())
{
this.AddRegion("Cibao Central");
this.AddRegion("Nordeste");
this.AddRegion("Norte");
this.AddRegion("Este");
this.AddRegion("Noroeste");
this.AddRegion("Sur");
await _context.SaveChangesAsync();
}
if (!_context.LottBankings.Any())
{
this.AddBanking("Banca IBS", user);
await _context.SaveChangesAsync();
}
if (!_context.LottRuleNumberTypes.Any())
{
this.AddRuleNumberType("L - Linea", user);
this.AddRuleNumberType("N - Normal", user);
this.AddRuleNumberType("O - Oreja", user);
await _context.SaveChangesAsync();
}
}
private async Task AddProvinciasAndProvinciasAsync()
{
this.AddProvincia("Distrito Nacional", new string[] { "Santo Domingo de Guzmán" });
this.AddProvincia("Azua de Compostela", new string[] { "Azua", "Estebanía", "Guayabal", "Las Charcas", "Las Yayas de Viajama", "Padre Las Casas", "Peralta", "Pueblo Viejo", "Sabana Yegua", "Tábara Arriba" });
this.AddProvincia("Baoruco, Neiba", new string[] { "Neiba", "Galván", "Los Ríos", "Tamayo", "Villa Jaragua" });
this.AddProvincia("Barahona, Santa Cruz", new string[] { "Barahona", "Cabral", "El Peñón", "Enriquillo", "Fundación", "Jaquimeyes", "La Ciénaga", "Las Salinas", "Paraíso", "Polo", "Vicente Noble" });
this.AddProvincia("Dajabón", new string[] { "Dajabón", "El Pino", "Loma de Cabrera", "Partido", "Restauración" });
this.AddProvincia("Duarte", new string[] { "San Francisco de Macorís", "Arenoso", "Castillo", "Eugenio <NAME>", "Las Guáranas", "Pimentel", "Villa Riva" });
this.AddProvincia("El<NAME>", new string[] { "Comendador", "Bánica", "El Llano", "<NAME>", "<NAME>", "<NAME>" });
this.AddProvincia("El Seibo, Santa Cruz", new string[] { "El Seibo", "Miches" });
this.AddProvincia("Espaillat", new string[] { "Moca", "<NAME>", "<NAME>", "Jamao Al Norte" });
this.AddProvincia("Independencia", new string[] { "Jimaní", "Cristóbal", "Duvergé", "La Descubierta", "Mella", "Postrer Río" });
this.AddProvincia("La Altagracia", new string[] { "Higüey", "San Rafael del Yuma" });
this.AddProvincia("La Romana", new string[] { "La Romana", "Guaymate", "Villa Hermosa" });
this.AddProvincia("La Vega", new string[] { "Concepción de La Vega", "Constanza", "Jarabacoa", "Jima Abajo" });
this.AddProvincia("María Trinidad Sánchez", new string[] { "Nagua", "Cabrera", "El Factor", "Río San Juan" });
this.AddProvincia("Monte Cristi", new string[] { "San Fernando Monte Cristi", "Castañuelas", "Guayubín", "Las Matas de Santa Cruz", "Pep<NAME>", "Villa Vásquez" });
this.AddProvincia("Pedernales", new string[] { "Oviedo", "Pedernales" });
this.AddProvincia("Peravia", new string[] { "Baní", "Matanzas", "Nizao" });
this.AddProvincia("Puerto Plata", new string[] { "San Felipe de Puerto Plata", "Altamira", "Guananico", "Imbert", "Los Hidalgos", "Luperón", "Sosúa", "Villa Isabela", "Villa Montellano" });
this.AddProvincia("Hermanas Mirabal", new string[] { "Salcedo", "Tenares", "Villa Tapia" });
this.AddProvincia("Samaná", new string[] { "Santa Bárbara de Samaná", "Las Terrenas", "Sánchez" });
this.AddProvincia("San Cristóbal", new string[] { "Bajos de Haina", "Cambita Garabitos", "Los Cacaos", "Sabana Grande de Palenque", "San Cristóbal", "San Gregorio de Nigua", "Villa Altagracia", "Yaguate" });
this.AddProvincia("San Juan de la Maguana", new string[] { "Bohechío", "El Cercado", "Juan de Herrera", "Las Matas de Farfán", "San Juan", "Vallejuelo" });
this.AddProvincia("San Pedro de Macorís", new string[] { "Consuelo", "Guayacanes", "Los Llanos", "Quisquey", "La Mata" });
this.AddProvincia("S<NAME>", new string[] { "Cotuí", "Cevicos", "Fantino", "La Mata" });
this.AddProvincia("Santiago", new string[] { "Santiago de los Caballeros", "Bisonó", "Jánico", "Licey al Medio", "Puñal", "Sabana Iglesia", "San José de Las Matas", "Tamboril", "Villa González" });
this.AddProvincia("<NAME>", new string[] { "San Ignacio de Sabaneta", "Monción", "Villa Los Almácigos" });
this.AddProvincia("Valverde", new string[] { "Mao Valverde", "Esperanza", "Laguna Salada" });
this.AddProvincia("Monseñor Nouel", new string[] { "Bonao", "Maimón", "Piedra Blanca" });
this.AddProvincia("Monte Plata", new string[] { "Monte Plata", "Bayaguana", "Peralvillo", "Sabana Grande de Boyá", "Yamasá" });
this.AddProvincia("Hato Mayor del Rey", new string[] { "El Valle", "Hato Mayor", "Sabana de la Mar" });
this.AddProvincia("San José de Ocoa", new string[] { "San José de Ocoa", "Rancho Arriba", "Sabana Larga" });
this.AddProvincia("Santo Domingo", new string[] { "Boca Chica", "Los Alcarrizos", "<NAME>", "San Antonio de Guerra", "Santo Domingo Este", "Santo Domingo Norte", "Santo Domingo Oeste" });
await _context.SaveChangesAsync();
}
private void AddCompany(string name)
{
_context.Companies.Add(new Company
{
IdType = 1,
Name = name,
Address = "Calle Exiterre Edif. Altagracia III, Apt. 4A",
City = "Santiago, Republica Dominicana",
PhoneOne = "809-710-5012",
PhoneTwo = "",
Rnc = "03100480015",
Status = 1
});
}
private void AddCustomer(string name, User user)
{
_context.CxcCustomers.Add(new CxcCustomer
{
IdType = 1,
IdSucursal = 1,
IdModulo = 44,
FirstName = name,
LastName = "Paulino",
User = user
});
}
private void AddTipocxc(string name, User user)
{
_context.CxcTypes.Add(new CxcType
{
IdType = 1,
IdModulo = 44,
Descripcion = name,
CuentaContable = "",
IdEmpleado = 0,
Status = true
});
}
private void AddTipoNcf(string name)
{
_context.CxcNcf.Add(new CxcNcf
{
Descripcion = name,
Status = true
});
}
private void AddRegion(string name)
{
_context.CxcRegions.Add(new CxcRegion
{
Name = name,
Status = true
});
}
private void AddProvincia(string city, string[] municipality)
{
var theMmunicipalities = municipality.Select(c => new CxcMunicipality { Name = c }).ToList();
_context.CxcCities.Add(new CxcCity
{
Name = city
});
}
private void AddBanking(string name, User user)
{
_context.LottBankings.Add(new LottBanking
{
Name = name,
Address = "Calle Exiterre Edif. Altagracia III Apt. 4A",
PhoneNumber = "809-710-5012",
User = user,
Status = true
});
}
private void AddRuleNumberType(string name, User user)
{
_context.LottRuleNumberTypes.Add(new LottRuleNumberType
{
Name = name,
User = user,
FechaHora = DateTime.UtcNow,
Status = true
});
}
}
}
<file_sep>using IBSApps.Web.Areas.Lottery.Data.Entities;
using IBSApps.Web.Data;
using IBSApps.Web.Data.Repositories;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.Linq;
namespace IBSApps.Web.Areas.Lottery.Data.Repositories
{
public class BankingRepository : GenericRepository<LottBanking>, IBankingRepository
{
private readonly DataContext context;
public BankingRepository(DataContext context) : base(context)
{
this.context = context;
}
public IEnumerable<SelectListItem> GetComboBancas()
{
var list = this.context.LottBankings.Select(c => new SelectListItem
{
Text = c.Name,
Value = c.Id.ToString()
}).OrderBy(l => l.Text).ToList();
list.Insert(0, new SelectListItem
{
Text = "(Seleciona una Banca...)",
Value = "0"
});
return list;
}
public IEnumerable<SelectListItem> GetComboZonas()
{
var list = this.context.CxcZones.Select(c => new SelectListItem
{
Text = c.Name,
Value = c.Id.ToString()
}).OrderBy(l => l.Text).ToList();
list.Insert(0, new SelectListItem
{
Text = "(Seleciona una Zona...)",
Value = "0"
});
return list;
}
public IEnumerable<SelectListItem> GetComboZonas(int zonaId)
{
throw new System.NotImplementedException();
}
}
}
<file_sep>using IBSApps.Web.Areas.Lottery.Data.Entities;
using IBSApps.Web.Data.Repositories;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IBSApps.Web.Areas.Lottery.Data.Repositories
{
public interface ICollectorRepository : IGenericRepository<LottCollector>
{
IEnumerable<SelectListItem> GetComboCollector();
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IBSApps.Web.Areas.Lottery.Data.Entities
{
public class LottHour : IEntity
{
public int IdType { get; set; }
public int Id { get; set; }
public LottBanking LottBanking { get; set; }
//Hora de Apertura
public DateTime? AperturaLunes { get; set; }
public DateTime? AperturaMartes { get; set; }
public DateTime? AperturaMiercoles { get; set; }
public DateTime? AperturaJueves { get; set; }
public DateTime? AperturaViernes { get; set; }
public DateTime? AperturaSabado { get; set; }
public DateTime? AperturaDomingo { get; set; }
//Hora de Cierre
public DateTime? CierraLunes { get; set; }
public DateTime? CierraMartes { get; set; }
public DateTime? CierraMiercoles { get; set; }
public DateTime? CierraJueves { get; set; }
public DateTime? CierraViernes { get; set; }
public DateTime? CierraSabado { get; set; }
public DateTime? CierraDomingo { get; set; }
public User User { get; set; }
public DateTime? FechaHora { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Areas.CuentasCobrar.Data.Entities;
using IBSApps.Web.Areas.CuentasCobrar.Models;
using IBSApps.Web.Data.Repositories;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IBSApps.Web.Areas.CuentasCobrar.Data.Repositories
{
public interface ICityRepository : IGenericRepository<CxcCity>
{
IQueryable GetCitiesWithMunicipalities();
Task<CxcCity> GetCityWithMunicipalitiesAsync(int id);
Task<CxcMunicipality> GetMunicipalityAsync(int id);
Task AddMunicipalityAsync(MunicipalityViewModel model);
Task<int> UpdateMunicipalityAsync(CxcMunicipality municipality);
Task<int> DeleteMunicipalityAsync(CxcMunicipality municipality);
IEnumerable<SelectListItem> GetComboCities();
IEnumerable<SelectListItem> GetComboMunicipalities(int cityId);
Task<CxcCity> GetCityAsync(CxcMunicipality municipality);
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.Lottery.Data.Entities
{
public class LottMaxPlayStation : IEntity
{
public int IdType { get; set; }
public int Id { get; set; }
public LottStation LottStation { get; set; }
public LottBanking LottBanking { get; set; }
public LottCollector LottCollector { get; set; }
// Monto Maxima Jugada
[Display(Name = "Valor Maximo Quiniela")]
public decimal ValorMaximoQuiniela { get; set; }
[Display(Name = "Valor Maximo Pale")]
public decimal ValorMaximoPale { get; set; }
[Display(Name = "Valor Maximo Super Pale")]
public decimal ValorMaximoSuperPale { get; set; }
[Display(Name = "Valor Maximo Tripleta")]
public decimal ValorMaximoTripleta { get; set; }
[Display(Name = "Valor Maximo Cash3 Straight")]
public decimal ValorMaximoCash3Straight { get; set; }
[Display(Name = "Valor Maximo Cash3 Box")]
public decimal ValorMaximoCash3Box { get; set; }
[Display(Name = "Valor Maximo Play4 Straight")]
public decimal ValorMaximoPlay4Straight { get; set; }
[Display(Name = "Valor Maximo Play4 Box")]
public decimal ValorMaximoPlay4Box { get; set; }
[Display(Name = "Valor Maximo Pick5 Straight")]
public decimal ValorMaximoPick5Straight { get; set; }
[Display(Name = "Valor Maximo Pick5 Box")]
public decimal ValorMaximoPick5Box { get; set; }
// Encabezado y Pie de Ticket
[Display(Name = "Encabezado Ticket")]
[MaxLength(60)]
public string EncabezadoTicket01 { get; set; }
[MaxLength(60)]
public string EncabezadoTicket02 { get; set; }
[MaxLength(60)]
public string EncabezadoTicket03 { get; set; }
[MaxLength(60)]
public string EncabezadoTicket04 { get; set; }
[Display(Name = "Pie Ticket")]
[MaxLength(60)]
public string PieTicket01 { get; set; }
[MaxLength(60)]
public string PieTicket02 { get; set; }
[MaxLength(60)]
public string PieTicket03 { get; set; }
[MaxLength(60)]
public string EPieTicket04 { get; set; }
public User User { get; set; }
public DateTime? FechaHora { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Areas.Lottery.Data.Entities;
using IBSApps.Web.Data.Repositories;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
namespace IBSApps.Web.Areas.Lottery.Data.Repositories
{
public interface IBankingRepository : IGenericRepository<LottBanking>
{
IEnumerable<SelectListItem> GetComboBancas();
IEnumerable<SelectListItem> GetComboZonas();
IEnumerable<SelectListItem> GetComboZonas(int zonaId);
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.CuentasCobrar.Data.Entities
{
public class CxcCompany : IEntity
{
public int IdType { get; set; }
public int Id { get; set; }
public int IdSucursal { get; set; }
[Display(Name = "Name")]
[MaxLength(50, ErrorMessage = "The field {0} only can contain {1} characters length.")]
[Required]
public string Name { get; set; }
[MaxLength(100, ErrorMessage = "The {0} field can not have more than {1} characters.")]
public string Address { get; set; }
[Display(Name = "Company Phone")]
[MaxLength(20, ErrorMessage = "The {0} field can not have more than {1} characters.")]
public string CompanyPhone { get; set; }
[Display(Name = "Email")]
public string Email { get; set; }
[Display(Name = "Company Phone")]
[MaxLength(15, ErrorMessage = "The {0} field can not have more than {1} characters.")]
public int Rnc { get; set; }
public bool StatusCxc { get; set; }
}
}
<file_sep>namespace IBSApps.Web.Areas.CuentasCobrar.Data.Entities
{
using IBSApps.Web.Data.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
public class CxcNcf : IEntity
{
public int Id { get; set; }
[MaxLength(50)]
[Required]
public string Descripcion { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using System;
namespace IBSApps.UIClassic
{
public class Class1
{
}
}
<file_sep>using IBSApps.Web.Areas.Lottery.Data.Entities;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace IBSApps.Web.Areas.Lottery.Models
{
public class BankingViewModel : LottBanking
{
//[Display(Name = "Zona")]
//[Range(1, int.MaxValue, ErrorMessage = "You must select a Zona.")]
//public int IdZona { get; set; }
public IEnumerable<SelectListItem> ListZone { get; set; }
public IEnumerable<SelectListItem> ListBanking { get; set; }
}
}
<file_sep>
using IBSApps.Web.Areas.CuentasCobrar.Data.Entities;
using IBSApps.Web.Areas.CuentasCobrar.Models;
using IBSApps.Web.Data;
using IBSApps.Web.Data.Repositories;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IBSApps.Web.Areas.CuentasCobrar.Data.Repositories
{
public class CityRepository : GenericRepository<CxcCity>, ICityRepository
{
private readonly DataContext _context;
public CityRepository(DataContext context) : base(context)
{
_context = context;
}
public async Task AddMunicipalityAsync(MunicipalityViewModel model)
{
var city = await this.GetCityWithMunicipalitiesAsync(model.CxcCityId);
if (city == null)
{
return;
}
city.CxcMunicipalities.Add(new CxcMunicipality { Name = model.Name });
_context.CxcCities.Update(city);
await _context.SaveChangesAsync();
}
public async Task<int> DeleteMunicipalityAsync(CxcMunicipality municipality)
{
var city = await _context.CxcCities.Where(c => c.CxcMunicipalities.Any(ci => ci.Id == municipality.Id)).FirstOrDefaultAsync();
if (city == null)
{
return 0;
}
_context.CxcMunicipalities.Remove(municipality);
await _context.SaveChangesAsync();
return city.Id;
}
public IQueryable GetCitiesWithMunicipalities()
{
return _context.CxcCities
.Include(c => c.CxcMunicipalities)
.OrderBy(c => c.Name);
}
public async Task<Entities.CxcCity> GetCityWithMunicipalitiesAsync(int id)
{
return await _context.CxcCities
.Include(c => c.CxcMunicipalities)
.Where(c => c.Id == id)
.FirstOrDefaultAsync();
}
public async Task<int> UpdateMunicipalityAsync(CxcMunicipality city)
{
var country = await _context.CxcCities.Where(c => c.CxcMunicipalities.Any(ci => ci.Id == city.Id)).FirstOrDefaultAsync();
if (country == null)
{
return 0;
}
_context.CxcMunicipalities.Update(city);
await _context.SaveChangesAsync();
return country.Id;
}
public async Task<CxcMunicipality> GetMunicipalityAsync(int id)
{
return await _context.CxcMunicipalities.FindAsync(id);
}
public IEnumerable<SelectListItem> GetComboCities()
{
var list = _context.CxcCities.Select(c => new SelectListItem
{
Text = c.Name,
Value = c.Id.ToString()
}).OrderBy(l => l.Text).ToList();
list.Insert(0, new SelectListItem
{
Text = "(Select a country...)",
Value = "0"
});
return list;
}
public IEnumerable<SelectListItem> GetComboMunicipalities(int cityId)
{
var city = _context.CxcCities.Find(cityId);
var list = new List<SelectListItem>();
if (city != null)
{
list = city.CxcMunicipalities.Select(c => new SelectListItem
{
Text = c.Name,
Value = c.Id.ToString()
}).OrderBy(l => l.Text).ToList();
}
list.Insert(0, new SelectListItem
{
Text = "(Select a Municipality...)",
Value = "0"
});
return list;
}
public async Task<CxcCity> GetCityAsync(CxcMunicipality municipality)
{
return await _context.CxcCities
.Where(c => c.CxcMunicipalities.Any(ci => ci.Id == municipality.Id))
.FirstOrDefaultAsync();
}
}
}
<file_sep>namespace IBSApps.Web.Data.Repositories
{
using Entities;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public interface ICompanyRepository : IGenericRepository<Company>
{
//IEnumerable<Company> GetCompany();
Task<Company> GetCompany(int id);
//Task<Company> GetDatos();
}
}
<file_sep>using IBSApps.Web.Areas.Lottery.Data.Entities;
using IBSApps.Web.Areas.Lottery.Data.Repositories;
using IBSApps.Web.Areas.Lottery.Models;
using IBSApps.Web.Data.Repositories;
using IBSApps.Web.Helpers;
using IBSApss.Web.Helpers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IBSApps.Web.Areas.Lottery.Controllers
{
[Area("Lottery")]
public class CollectorsController : Controller
{
private readonly IUserHelper _userHelper;
private readonly ICollectorRepository _collectorRepository;
private readonly ICompanyRepository _companyRepository;
public CollectorsController (
IUserHelper userHelper,
ICollectorRepository collectorRepository,
ICompanyRepository companyRepository)
{
_userHelper = userHelper;
_collectorRepository = collectorRepository;
_companyRepository = companyRepository;
}
// GET: Collectors
public IActionResult Index()
{
return View(_collectorRepository.GetAll());
}
// GET: Collectors/Create
public IActionResult Create()
{
var model = new CollectorViewModel
{
};
return View(model);
}
// POST: Collectors/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(LottCollector collector)
{
if (ModelState.IsValid)
{
var company = await _companyRepository.GetCompany(1);
// TODO: Pending to change to: this.User.Identity.Name
collector.User = await _userHelper.GetUserByEmailAsync("<EMAIL>");
collector.IdType = company.IdType;
collector.FechaHora = DateTime.UtcNow;
await _collectorRepository.CreateAsync(collector);
return RedirectToAction(nameof(Index));
}
return View(collector);
}
// GET: Collectors/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return new NotFoundViewResult("CollectorNotFound");
}
var collector = await _collectorRepository.GetByIdAsync(id.Value);
if (collector == null)
{
return new NotFoundViewResult("CollectorNotFound");
}
var view = this.ToCollectorViewModel(collector);
return View(view);
}
// POST: Collectors/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(LottCollector collector)
{
if (ModelState.IsValid)
{
try
{
var company = await _companyRepository.GetCompany(1);
// TODO: Pending to change to: this.User.Identity.Name
collector.User = await _userHelper.GetUserByEmailAsync("<EMAIL>");
collector.IdType = company.IdType;
collector.FechaHora = DateTime.UtcNow;
await _collectorRepository.UpdateAsync(collector);
}
catch (DbUpdateConcurrencyException)
{
if (!await _collectorRepository.ExistAsync(collector.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(collector);
}
private CollectorViewModel ToCollectorViewModel(LottCollector collector)
{
return new CollectorViewModel
{
IdType = collector.IdType,
FirstName = collector.FirstName,
LastName = collector.LastName,
FixedPhone = collector.FixedPhone,
CellPhone = collector.CellPhone,
Address = collector.Address,
User = collector.User,
FechaHora = collector.FechaHora,
Status = collector.Status
};
}
public IActionResult CollectorNotFound()
{
return this.View();
}
}
}
<file_sep>namespace IBSApps.Web.Data.Repositories
{
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Data.Entities;
using IBSApps.Web.Data;
using IBSApps.Web.Data.Repositories;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
public class CompanyRepository : GenericRepository<Company>, ICompanyRepository
{
private readonly DataContext context;
public CompanyRepository(DataContext context) : base(context)
{
this.context = context;
}
public async Task<Company> GetCompany(int id)
{
return await this.context.Companies.FindAsync(id);
}
//Task<Company> ICompanyRepository.GetDatos()
//{
// return this.context.Company.OrderBy(p => p.Name);
//}
//public IEnumerable<Company> GetCompany()
//{
// return this.context.Company.OrderBy(p => p.Name);
//}
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.CuentasCobrar.Data.Entities
{
public class CxcType : IEntity
{
public int IdType { get; set; }
public int IdModulo { get; set; }
public int Id { get; set; }
[MaxLength(50)]
[Required]
public string Descripcion { get; set; }
[MaxLength(25)]
[Required]
public string CuentaContable { get; set; }
public int IdEmpleado { get; set; }
public bool Status { get; set; }
}
}
<file_sep>namespace IBSApps.Web
{
using Data;
using Data.Entities;
using Helpers;
using Areas.CuentasCobrar.Data.Repositories;
using Areas.Lottery.Data.Repositories;
using Data.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<User, IdentityRole>(cfg =>
{
cfg.User.RequireUniqueEmail = true;
cfg.Password.RequireDigit = false;
cfg.Password.RequiredUniqueChars = 0;
cfg.Password.RequireLowercase = false;
cfg.Password.RequireNonAlphanumeric = false;
cfg.Password.RequireUppercase = false;
cfg.Password.RequiredLength = 6;
})
.AddEntityFrameworkStores<DataContext>();
services.AddDbContext<DataContext>(cfg =>
{
cfg.UseSqlServer(Configuration.GetConnectionString("dbConnection"));
});
services.AddTransient<SeedDb>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<IUserHelper, UserHelper>();
services.AddScoped<ICompanyRepository, CompanyRepository>();
services.AddScoped<IBankingRepository, BankingRepository>();
services.AddScoped<ICollectorRepository, CollectorRepository>();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.Configure<RazorViewEngineOptions>(options =>
{
options.AreaViewLocationFormats.Clear();
options.AreaViewLocationFormats.Add("/CuentasCobrar/{2}/Views/{1}/{0}.cshtml");
options.AreaViewLocationFormats.Add("/Lottery/{2}/Views/{1}/{0}.cshtml");
});
services.AddMvc().AddRazorPagesOptions(options =>
{
options.AllowAreas = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Account}/{action=Login}/{id?}");
//template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
<file_sep>using IBSApps.Web.Areas.CuentasCobrar.Data.Entities;
using IBSApps.Web.Areas.CuentasCobrar.Data.Repositories;
using IBSApps.Web.Areas.CuentasCobrar.Models;
using IBSApps.Web.Data.Repositories;
using IBSApps.Web.Helpers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
namespace IBSApps.Web.Areas.CuentasCobrar.Controllers
{
[Area("CuentasCobrar")]
public class CustomersController : Controller
{
private readonly ICustomerRepository _customerRepository;
private readonly IUserHelper _userHelper;
private readonly ICompanyRepository _companyRepository;
public CustomersController(
ICustomerRepository customerRepository,
IUserHelper userHelper,
ICompanyRepository companyRepository)
{
_customerRepository = customerRepository;
_userHelper = userHelper;
_companyRepository = companyRepository;
}
// GET: Clientes
public IActionResult Index()
{
return View(_customerRepository.GetAll());
}
// GET: Clientes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var Cliente = await _customerRepository.GetByIdAsync(id.Value);
if (Cliente == null)
{
return NotFound();
}
return View(Cliente);
}
// GET: Clientes/Create
public IActionResult Create()
{
var model = new CustomerViewModel
{
Tiposcxc = _customerRepository.GetComboTipos(),
ListeCivil = _customerRepository.GetComboEstadoCivil(),
ListNcf = _customerRepository.GetComboNcf(),
ListSexo = _customerRepository.GetComboSexo()
};
return this.View(model);
}
// POST: Clientes/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CxcCustomer Customer)
{
if (ModelState.IsValid)
{
var company = await _companyRepository.GetCompany(1);
// TODO: Pending to change to: this.User.Identity.Name
Customer.User = await _userHelper.GetUserByEmailAsync("<EMAIL>");
Customer.IdType = company.IdType;
await _customerRepository.CreateAsync(Customer);
return RedirectToAction(nameof(Index));
}
return View(Customer);
}
// GET: Clientes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var customer = await _customerRepository.GetByIdAsync(id.Value);
if (customer == null)
{
return NotFound();
}
return View(customer);
}
// POST: Clientes/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(CxcCustomer Customer)
{
if (ModelState.IsValid)
{
try
{
// TODO: Pending to change to: this.User.Identity.Name
Customer.User = await _userHelper.GetUserByEmailAsync("<EMAIL>");
Customer.IdSex = 1;
Customer.BirthDate = DateTime.UtcNow;
await _customerRepository.UpdateAsync(Customer);
}
catch (DbUpdateConcurrencyException)
{
if (!await _customerRepository.ExistAsync(Customer.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(Customer);
}
// GET: Clientes/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var Cliente = await _customerRepository.GetByIdAsync(id.Value);
if (Cliente == null)
{
return NotFound();
}
return View(Cliente);
}
// POST: Clientes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var Cliente = await _customerRepository.GetByIdAsync(id);
await _customerRepository.DeleteAsync(Cliente);
return RedirectToAction(nameof(Index));
}
}
}
<file_sep>namespace IBSApps.Web.Data.Entities
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
public class Company : IEntity
{
[Required]
public int IdType { get; set; }
public int Id { get; set; }
[MaxLength(100)]
[Required]
public string Name { get; set; }
[MaxLength(100)]
[Required]
public string Address { get; set; }
[MaxLength(50)]
[Required]
public string City { get; set; }
[MaxLength(12)]
[Required]
public string PhoneOne { get; set; }
[MaxLength(12)]
[Required]
public string PhoneTwo { get; set; }
[MaxLength(50)]
[Required]
public string Rnc { get; set; }
public int Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.CuentasCobrar.Data.Entities
{
public class CxcRegion : IEntity
{
public int Id { get; set; }
[Display(Name = "Region")]
[MaxLength(60)]
[Required]
public string Name { get; set; }
public ICollection<CxcCity> CxcCity { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.CuentasCobrar.Data.Entities
{
public class CxcMunicipality : IEntity
{
public int Id { get; set; }
[Display(Name = "Municipio")]
[MaxLength(60)]
[Required]
public string Name { get; set; }
public CxcCity CxcCities { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.CuentasCobrar.Data.Entities
{
public class CxcCity : IEntity
{
public int Id { get; set; }
[Required]
[Display(Name = "Ciudad")]
[MaxLength(50, ErrorMessage = "The field {0} only can contain {1} characters length.")]
public string Name { get; set; }
public ICollection<CxcMunicipality> CxcMunicipalities { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Areas.CuentasCobrar.Data.Entities;
using IBSApps.Web.Data.Repositories;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
namespace IBSApps.Web.Areas.CuentasCobrar.Data.Repositories
{
public interface ICustomerRepository : IGenericRepository<CxcCustomer>
{
IEnumerable<SelectListItem> GetComboTipos();
IEnumerable<SelectListItem> GetComboEstadoCivil();
IEnumerable<SelectListItem> GetComboNcf();
IEnumerable<SelectListItem> GetComboSexo();
}
}
<file_sep>namespace IBSApps.Web.Areas.CuentasCobrar.Models
{
using IBSApps.Web.Areas.CuentasCobrar.Data.Entities;
using System.ComponentModel.DataAnnotations;
public class MunicipalityViewModel : CxcMunicipality
{
public int CxcCityId { get; set; }
public int CxcMunicipalityId { get; set; }
[Required]
[Display(Name = "Municipio")]
[MaxLength(50, ErrorMessage = "The field {0} only can contain {1} characters length.")]
public string Name { get; set; }
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.CuentasCobrar.Data.Entities
{
public class CxcZone : IEntity
{
public int Id { get; set; }
[Display(Name = "Region")]
[MaxLength(60)]
[Required]
public string Name { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Areas.Lottery.Data.Entities;
using IBSApps.Web.Data;
using IBSApps.Web.Data.Repositories;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IBSApps.Web.Areas.Lottery.Data.Repositories
{
public class CollectorRepository : GenericRepository<LottCollector>, ICollectorRepository
{
private readonly DataContext _context;
public CollectorRepository(DataContext context) : base(context)
{
_context = context;
}
public IEnumerable<SelectListItem> GetComboCollector()
{
throw new NotImplementedException();
}
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.Lottery.Data.Entities
{
public class LottPrize : IEntity
{
public int IdType { get; set; }
public int Id { get; set; }
[Display(Name = "Premio")]
[MaxLength(60, ErrorMessage = "The field {0} only can contain {1} characters length.")]
[Required]
public string Name { get; set; }
public Lottery Lottery { get; set; }
// Pago Premios Directo
[Display(Name = "Pago Primera")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpdPrimera { get; set; }
[Display(Name = "Pago Segunda")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpdSegunda { get; set; }
[Display(Name = "Pago Tercera")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpdTercera { get; set; }
[Display(Name = "Pago Dobles")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpdDobles { get; set; }
// Pago Premios Pale
[Display(Name = "Primera Pago")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PppPrimera { get; set; }
[Display(Name = "Segundo Pago")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PppSegunda { get; set; }
[Display(Name = "Tercer Pago")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PppTercera { get; set; }
[Display(Name = "Todos en Secuencia")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PppSecuencia { get; set; }
// Pago Premios Super Pale
[Display(Name = "Primer Pago")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpspPrimera { get; set; }
// Pago Premios Tripleta
[Display(Name = "Pago Primera")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PptPrimera { get; set; }
[Display(Name = "Pago Segundo")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PptSegunda { get; set; }
// Pago Premios Cash3 Straight
[Display(Name = "Pago Todos en Secuencia")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpCash3StraightSecuenia { get; set; }
[Display(Name = "Pago Dobles")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpCash3StraightDobles { get; set; }
// Pago Premios Cash3 Box
[Display(Name = "3-Way; 2 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpCash3Box3Way2Identicos { get; set; }
[Display(Name = "6-Way; 3 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpCash3Box6Way3Identicos { get; set; }
// Pago Premios Palay4 Straight
[Display(Name = "Pago Todos en Secuencia")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPlay4StraightSecuencia { get; set; }
[Display(Name = "Pago Dobles")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPlay4StraightDobles { get; set; }
// Pago Premios Palay4 Box
[Display(Name = "Pago 4-Way; 3 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPlay4Box4Way3Identicos { get; set; }
[Display(Name = "Pago 6-Way; 2 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPlay4Box6Way6Identicos { get; set; }
[Display(Name = "Pago 12-Way; 2 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPlay4Box12Way2Identicos { get; set; }
[Display(Name = "Pago 24-Way; 4 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPlay24Box24Way4Unicos { get; set; }
// Pago Premios Play4 Straight
[Display(Name = "Pago Todos en Secuencia")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPick5StraightSecuencia { get; set; }
[Display(Name = "Pago Dobles")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPick5StraightDobles { get; set; }
// Pago Premios Pick5 Box
[Display(Name = "Pago 5-Way; 4 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPick5Box5Way4Identicos { get; set; }
[Display(Name = "Pago 10-Way; 4 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPick5Box10Way3Identicos { get; set; }
[Display(Name = "Pago 20-Way; 3 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPick5Box20Way3Identicos { get; set; }
[Display(Name = "Pago 30-Way; 2 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPick5Box30Way2Identicos { get; set; }
[Display(Name = "Pago 60-Way; 2 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPick5Box60Way2Identicos { get; set; }
[Display(Name = "Pago 120-Way; 5 Unicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPick5Box120Way5Unicos { get; set; }
// Pago Premios Pick2
[Display(Name = "Primer Pago")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPick2Primer { get; set; }
[Display(Name = "Pago Dobles")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PpPick2Dobles { get; set; }
[Display(Name = "Domingo")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? HoraInicioDomingo { get; set; }
[Display(Name = "Lunes")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? HoraInicioLunes { get; set; }
[Display(Name = "Martes")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? HoraInicioMartes { get; set; }
[Display(Name = "Miercoles")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? HoraInicioMierles { get; set; }
[Display(Name = "Juves")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? HoraInicioJueves { get; set; }
[Display(Name = "Viernes")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? HoraInicioViernes { get; set; }
[Display(Name = "Sabado")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? HoraInicioSabado { get; set; }
public User User { get; set; }
public DateTime? FechaHora { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.Lottery.Data.Entities
{
public class Lottery : IEntity
{
public int IdType { get; set; }
public int Id { get; set; }
[Display(Name = "Loteria")]
[MaxLength(60, ErrorMessage = "The field {0} only can contain {1} characters length.")]
[Required]
public string Name { get; set; }
[Display(Name = "Loteria del")]
public bool VentaDomingo { get; set; }
public bool VentaLunes { get; set; }
public bool VentaMartes { get; set; }
public bool VentaMiercoles { get; set; }
public bool VentaJueves { get; set; }
public bool VentaViernes { get; set; }
public bool VentaSabado { get; set; }
// Venta Jugada
[Display(Name = "Venta Quiniela")]
public bool VentaQuiniela { get; set; }
[Display(Name = "Venta Pale")]
public bool VentaPale { get; set; }
[Display(Name = "Venta Super Pale")]
public bool VentaSuperPale { get; set; }
[Display(Name = "Venta Tripleta")]
public bool VentaTripleta { get; set; }
[Display(Name = "Venta Cash3 Straight")]
public bool VentaCash3Straight { get; set; }
[Display(Name = "Venta Cash3 Box")]
public bool VentaCash3Box { get; set; }
[Display(Name = "Venta Play4 Straight")]
public decimal VentaPlay4Straight { get; set; }
[Display(Name = "Venta Play4 Box")]
public bool VentaPlay4Box { get; set; }
[Display(Name = "Venta Pick5 Straight")]
public bool VentaPick5Straight { get; set; }
[Display(Name = "Venta Pick5 Box")]
public bool VentaPick5Box { get; set; }
public User User { get; set; }
public DateTime? FechaHora { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.CuentasCobrar.Data.Entities
{
public class CxcCustomer : IEntity
{
public int IdType { get; set; }
public int IdSucursal { get; set; }
public int IdModulo { get; set; }
public int Id { get; set; }
[Display(Name = "First Name")]
[MaxLength(50, ErrorMessage = "The field {0} only can contain {1} characters length.")]
[Required]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[MaxLength(50, ErrorMessage = "The field {0} only can contain {1} characters length.")]
[Required]
public string LastName { get; set; }
public int IdSex { get; set; }
[Display(Name = "Fixed Phone")]
[MaxLength(20, ErrorMessage = "The {0} field can not have more than {1} characters.")]
public string FixedPhone { get; set; }
[Display(Name = "Cell Phone")]
[MaxLength(20, ErrorMessage = "The {0} field can not have more than {1} characters.")]
public string CellPhone { get; set; }
[Display(Name = "Document")]
[MaxLength(14)]
public string Document { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Fecha Nacimiento")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? BirthDate { get; set; }
[Display(Name = "City")]
public CxcCity CxcCity { get; set; }
[Display(Name = "Municipio")]
public CxcMunicipality CxcMunicipality { get; set; }
[MaxLength(100, ErrorMessage = "The {0} field can not have more than {1} characters.")]
public string Address { get; set; }
[Display(Name = "Full Name")]
public string FullName => $"{FirstName} {LastName}";
public User User { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Admission Date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? AdmissionDate { get; set; }
[Display(Name = "Email")]
public string Email { get; set; }
public int IdCompany { get; set; }
public CxcType CxcType { get; set; }
[Display(Name = "Cuenta Bancaria")]
[MaxLength(20)]
public string CuentaBancaria { get; set; }
public CxcNcf CxcNcf { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Areas.CuentasCobrar.Data.Entities;
using IBSApps.Web.Areas.Lottery.Data.Entities;
using IBSApps.Web.Data.Entities;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace IBSApps.Web.Data
{
public class DataContext : IdentityDbContext<User>
{
public DbSet<Company> Companies { get; set; }
public DbSet<CxcCustomer> CxcCustomers { get; set; }
public DbSet<CxcType> CxcTypes { get; set; }
public DbSet<CxcNcf> CxcNcf { get; set; }
public DbSet<CxcRegion> CxcRegions { get; set; }
public DbSet<CxcCity> CxcCities { get; set; }
public DbSet<CxcMunicipality> CxcMunicipalities { get; set; }
public DbSet<CxcZone> CxcZones { get; set; }
public DbSet<CxcCompany> CxcCompanies { get; set; }
public DbSet<LottBanking> LottBankings { get; set; }
public DbSet<LottStation> LottStations { get; set; }
public DbSet<Lottery> Lotteries { get; set; }
public DbSet<LottCommission> LottCommissions { get; set; }
public DbSet<LottPrize> LottPrizes { get; set; }
public DbSet<LottCollector> LottCollectors { get; set; }
public DbSet<LottHour> LottHours { get; set; }
public DbSet<LottRuleNumber> LottRuleNumbers { get; set; }
public DbSet<LottRuleNumberType> LottRuleNumberTypes { get; set; }
public DbSet<LottMaxPlayStation> LottMaxPlayStations { get; set; }
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
}
}
<file_sep>namespace IBSApps.Web.Areas.CuentasCobrar.Data.Repositories
{
internal interface IMunicipalityRepository
{
}
}<file_sep>using IBSApps.Web.Data.Entities;
using System;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.Lottery.Data.Entities
{
public class LottCommission : IEntity
{
public int IdType { get; set; }
public int Id { get; set; }
[Display(Name = "Comision")]
[MaxLength(60, ErrorMessage = "The field {0} only can contain {1} characters length.")]
[Required]
public string Name { get; set; }
// Comision Jugada
[Display(Name = "Quiniela")]
public bool ComisionQuiniela { get; set; }
[Display(Name = "Pale")]
public bool ComisionPale { get; set; }
[Display(Name = "Super Pale")]
public bool ComisionSuperPale { get; set; }
[Display(Name = "Tripleta")]
public bool ComisionTripleta { get; set; }
[Display(Name = "Cash3 Straight")]
public bool ComisionCash3Straight { get; set; }
[Display(Name = "Cash3 Box")]
public bool ComisionCash3Box { get; set; }
[Display(Name = "Play4 Straight")]
public decimal ComisionPlay4Straight { get; set; }
[Display(Name = "Play4 Box")]
public bool ComisionPlay4Box { get; set; }
[Display(Name = "Pick5 Straight")]
public bool ComisionPick5Straight { get; set; }
[Display(Name = "Pick5 Box")]
public bool ComisionPick5Box { get; set; }
public User User { get; set; }
public DateTime? FechaHora { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Areas.CuentasCobrar.Data.Entities;
using IBSApps.Web.Data;
using IBSApps.Web.Data.Repositories;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.Linq;
namespace IBSApps.Web.Areas.CuentasCobrar.Data.Repositories
{
public class CustomerRepository : GenericRepository<CxcCustomer>, ICustomerRepository
{
private readonly DataContext context;
public CustomerRepository(DataContext context) : base(context)
{
this.context = context;
}
public IEnumerable<SelectListItem> GetComboEstadoCivil()
{
List<SelectListItem> eCivil = new List<SelectListItem>
{
new SelectListItem { Text = "(Seleciona un Tipo CtaCobrar...)", Value = "0" },
new SelectListItem { Text = "Soltero (A)", Value = "1" },
new SelectListItem { Text = "Casado (A)", Value = "2" },
new SelectListItem { Text = "Union Libre", Value = "3" }
};
return eCivil;
}
public IEnumerable<SelectListItem> GetComboTipos()
{
var list = this.context.CxcTypes.Select(c => new SelectListItem
{
Text = c.Descripcion,
Value = c.Id.ToString()
}).OrderBy(l => l.Text).ToList();
list.Insert(0, new SelectListItem
{
Text = "(Seleciona un Tipo CtaCobrar...)",
Value = "0"
});
return list;
}
public IEnumerable<SelectListItem> GetComboNcf()
{
var list = this.context.CxcNcf.Select(c => new SelectListItem
{
Text = c.Descripcion,
Value = c.Id.ToString()
}).OrderBy(l => l.Text).ToList();
list.Insert(0, new SelectListItem
{
Text = "(Seleciona un Tipo de NCF...)",
Value = "0"
});
return list;
}
public IEnumerable<SelectListItem> GetComboSexo()
{
List<SelectListItem> Sexo = new List<SelectListItem>
{
new SelectListItem { Text = "(Seleciona Tipo de Sexo...)", Value = "0" },
new SelectListItem { Text = "Masculino", Value = "1" },
new SelectListItem { Text = "Femenino", Value = "2" }
};
return Sexo;
}
}
}
<file_sep>using IBSApps.Web.Data.Entities;
using System;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.Lottery.Data.Entities
{
public class LottRuleNumberType : IEntity
{
public int IdType { get; set; }
public int Id { get; set; }
[Display(Name = "Type Rule Number")]
[MaxLength(60, ErrorMessage = "The field {0} only can contain {1} characters length.")]
[Required]
public string Name { get; set; }
public LottRuleNumber LottRuleNumber { get; set; }
public User User { get; set; }
public DateTime? FechaHora { get; set; }
public bool Status { get; set; }
}
}
<file_sep>using IBSApps.Web.Areas.CuentasCobrar.Data.Entities;
using IBSApps.Web.Data.Entities;
using System;
using System.ComponentModel.DataAnnotations;
namespace IBSApps.Web.Areas.Lottery.Data.Entities
{
public class LottBanking : IEntity
{
public int IdType { get; set; }
public int Id { get; set; }
[Display(Name = "Banca")]
[MaxLength(60, ErrorMessage = "The field {0} only can contain {1} characters length.")]
[Required]
public string Name { get; set; }
[Display(Name = "Direccion")]
[MaxLength(100, ErrorMessage = "The field {0} only can contain {1} characters length.")]
[Required]
public string Address { get; set; }
[Display(Name = "Telefono")]
[MaxLength(100, ErrorMessage = "The field {0} only can contain {1} characters length.")]
[Required]
public string PhoneNumber { get; set; }
public CxcCity CxcCity { get; set; }
[Display(Name = "Dia Maxino Pago Ticket")]
public int DiaMaxPagoTcket { get; set; }
public CxcZone CxcZone { get; set; }
// Pago Premios Directo
[Display(Name = "Pago Primera")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvdPrimera { get; set; }
[Display(Name = "Pago Segunda")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvdSegunda { get; set; }
[Display(Name = "Pago Tercera")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvdTercera { get; set; }
[Display(Name = "Pago Dobles")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvdDobles { get; set; }
// Pago Premios Pale
[Display(Name = "Primera Pago")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvpPrimera { get; set; }
[Display(Name = "Segundo Pago")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvpSegunda { get; set; }
[Display(Name = "Tercer Pago")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvpTercera { get; set; }
[Display(Name = "Todos en Secuencia")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvpSecuencia { get; set; }
// Pago Premios Super Pale
[Display(Name = "Primer Pago")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvspPrimera { get; set; }
// Pago Premios Tripleta
[Display(Name = "Pago Primera")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvtPrimera { get; set; }
[Display(Name = "Pago Segundo")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvtSegunda { get; set; }
// Pago Premios Cash3 Straight
[Display(Name = "Pago Todos en Secuencia")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvCash3StraightSecuenia { get; set; }
[Display(Name = "Pago Dobles")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvCash3StraightDobles { get; set; }
// Pago Premios Cash3 Box
[Display(Name = "3-Way; 2 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvCash3Box3Way2Identicos { get; set; }
[Display(Name = "6-Way; 3 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvCash3Box6Way3Identicos { get; set; }
// Pago Premios Palay4 Straight
[Display(Name = "Pago Todos en Secuencia")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPlay4StraightSecuencia { get; set; }
[Display(Name = "Pago Dobles")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPlay4StraightDobles { get; set; }
// Pago Premios Palay4 Box
[Display(Name = "Pago 4-Way; 3 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPlay4Box4Way3Identicos { get; set; }
[Display(Name = "Pago 6-Way; 2 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPlay4Box6Way6Identicos { get; set; }
[Display(Name = "Pago 12-Way; 2 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPlay4Box12Way2Identicos { get; set; }
[Display(Name = "Pago 24-Way; 4 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPlay24Box24Way4Unicos { get; set; }
// Pago Premios Play4 Straight
[Display(Name = "Pago Todos en Secuencia")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPick5StraightSecuencia { get; set; }
[Display(Name = "Pago Dobles")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPick5StraightDobles { get; set; }
// Pago Premios Pick5 Box
[Display(Name = "Pago 5-Way; 4 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPick5Box5Way4Identicos { get; set; }
[Display(Name = "Pago 10-Way; 4 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPick5Box10Way3Identicos { get; set; }
[Display(Name = "Pago 20-Way; 3 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPick5Box20Way3Identicos { get; set; }
[Display(Name = "Pago 30-Way; 2 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPick5Box30Way2Identicos { get; set; }
[Display(Name = "Pago 60-Way; 2 Identicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPick5Box60Way2Identicos { get; set; }
[Display(Name = "Pago 120-Way; 5 Unicos")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPick5Box120Way5Unicos { get; set; }
// Pago Premios Pick2
[Display(Name = "Primer Pago")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPick2Primer { get; set; }
[Display(Name = "Pago Dobles")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal PvPick2Dobles { get; set; }
public LottRuleNumber LottRuleNumber { get; set; }
public User User { get; set; }
public DateTime? FechaHora { get; set; }
public bool Status { get; set; }
}
}
| 8075cbb3cc29e102cf15f09cffc6b1530215d41a | [
"C#"
] | 40 | C# | EnriquePaulino/IBSApps | ffe055fa275bfd8dd349fde72371953c3c804c3e | c766286a0ea475af3b59c1ace7e46525017372c1 |
refs/heads/master | <repo_name>matthewricecampbell/ReactNativeUserAuthBoilerplate<file_sep>/src/routes.js
export default Routes = () => {
return(
{
Login: {
screen: LoginScreen
},
Home: {
screen: HomeScreen
}
}
)
} | eb9b23536fe6c05524ec5ff62728a438d9c598cd | [
"JavaScript"
] | 1 | JavaScript | matthewricecampbell/ReactNativeUserAuthBoilerplate | fa181ec3877c6c68dabd4ccf28d80ad8964e7d23 | 5e39c9b59b17478f5898401059a5216d5435008b |
refs/heads/master | <repo_name>jfjessup/node-cloudfront-invalidate-cli<file_sep>/README.md
# node-cloudfront-invalidate-cli
A CLI for creating invalidations on CloudFront, that's a bit easier to use than the
official AWS CLI.
## Install
```shell
npm install cloudfront-invalidate-cli -g
```
## Use
```shell
cf-invalidate [--wait] [--config <AWS config .ini file> --accessKeyId <keyId> --secretAccessKey <key>] -- <distribution> <path>...
# Examples:
cf-invalidate -- ABCDEFGHIJK index.html
cf-invalidate --wait -- ABCDEFGHIJK file1 file2 file3
```
Use either config ini file or send access and secret keys. If you omit `--config`, `--accessKeyId` and `--secretAccessKey`, it'll use the default method of
finding credentials (Environment, INI File, EC2 Metadata Service), which is documented here:
[docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html](http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html#Using_Profiles_with_the_SDK).
If you use the `--wait` option, the command will not exit until the invalidation is complete. It does
this by polling `GetInvalidation` after min(60000, 1000ms * 2^iterationCycle) (e.g. it increases the timeout between polls exponentially).
If you use `--config`, set path to .ini file in format:
```
[default]
access_key =
secret_key =
```
This tool needs permission for `cloudfront:CreateInvalidation` and `cloudfront:GetInvalidation`.
If there is an error, it `exit(1)`s, and prints the error message to stderr.
It's not intended to be used programmatically, but if you want:
```shell
require("node-cloudfront-invalidate-cli")("ABCDEFGHIJK", ["file1", "file2", "file3"], {wait: true}, function (err) {
console.log(err || "Success");
});
```
<file_sep>/index.js
#!/usr/bin/env node
(function () {
"use strict";
var usageString =
"cf-invalidate [--wait] [--accessKeyId <keyId> --secretAccessKey <key>] -- <distribution> <path>...";
var exampleString =
"cf-invalidate -- myDistribution file1 file2 file3";
var AWS = require("aws-sdk");
var yargs = require("yargs");
var fs = require("fs");
var ini = require("ini");
var log = function () {};
var error = function () {};
/**
* Function: randomDigits
*
* Returns a random string of 4 digits.
*/
function randomDigits() {
var n = Math.floor(Math.random() * 1000);
return "" + ({
"0": "0000",
"1": "000",
"2": "00",
"3": "0",
"4": "",
}[("" + n).length]) + n;
}
/**
* Function: loadConfigFile
*
* Wrapper around invalidate(). Adds AWS sercet and access from .ini config file if its set with --config.
*/
function loadConfigFile(dist, paths, options, callback) {
if (options.config) {
fs.readFile(options.config, {encoding: 'utf8'}, function(err, contents) {
if (err) {
callback(err);
return;
}
var config = ini.parse(contents);
if (config && config.default) {
options.accessKeyId = config.default.access_key;
options.secretAccessKey = config.default.secret_key;
}
if (!options.secretAccessKey || !options.accessKeyId) {
callback("Config file missing access_key or secret_key");
return;
}
invalidate(dist, paths, options, callback);
});
} else {
invalidate(dist, paths, options, callback);
}
}
/**
* Function: invalidate
*
* Invalidates objects on cloudfront.
*
* Parameters:
* dist - Cloudfront distribution ID
* paths - An array of pathnames to invalidate
* options - Options object
* wait - If true, wait until the invalidation is complete.
* accessKeyId - If set, use this as the AWS key ID
* secretAccessKey - The AWS secret key
* callback - Callback
*/
function invalidate(dist, paths, options, callback) {
var cloudfront = new AWS.CloudFront();
if (options.accessKeyId) {
cloudfront.config.update({
accessKeyId: options.accessKeyId,
secretAccessKey: options.secretAccessKey,
});
}
paths = paths.map(function (v) {
if (v.charAt(0) === "/") {
return v;
} else {
return "/" + v;
}
});
var callerReference = "cf-invalidate-" + Date.now() + "_" + randomDigits();
cloudfront.createInvalidation({
DistributionId: dist,
InvalidationBatch: {
CallerReference: callerReference,
Paths: {
Quantity: paths.length,
Items: paths,
},
},
}, function (err, res) {
if (err) {return callback(err);}
var invalidationId = res.Invalidation.Id;
if (options.wait) {
var i = 0;
var iteration = function () {
cloudfront.getInvalidation({
DistributionId: dist,
Id: invalidationId
}, function (err, res) {
if (err) {return callback(err);}
if (res.Invalidation.Status === "Completed") {
return callback();
} else {
var nextTry = Math.min(60000, 1000 * Math.pow(2, i++));
log('Invalidation not done yet, next try in ' + nextTry + 'ms.');
setTimeout(function () {
iteration();
}, nextTry);
}
});
};
iteration();
} else {
callback();
}
});
}
if (module === require.main) {
log = console.log.bind(console);
error = console.error.bind(console);
var argv = yargs
.usage(usageString)
.example(exampleString)
.demand(2)
.option("accessKeyId", {
alias: "i",
describe: "AWS Key Id override",
})
.option("secretAccessKey", {
alias: "k",
describe: "AWS Secret Key override",
})
.implies("accessKeyId", "secretAccessKey")
.implies("secretAccessKey", "accessKeyId")
.option("wait", {
alias: "w",
describe: "If set, wait til the invalidation completes",
})
.option("config", {
alias: "c",
describe: "AWS .ini config file path",
})
.argv;
loadConfigFile(argv._[0], argv._.slice(1), argv, function (err) {
if (err) {
error(err);
process.exit(1);
}
if (argv.wait) {
log("Invalidation Complete");
} else {
log("Invalidation Created");
}
});
} else {
module.exports = invalidate;
}
}()); | b05f2ac62f0d96b5069a0ac28004bfd6ba071135 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | jfjessup/node-cloudfront-invalidate-cli | 7b286a9912dab923d6221cae79a41cad6e591ae0 | f6c6fc7b341d1bf710d31d459edc9aca958bb94f |
refs/heads/master | <file_sep># PrettyParadiseAdminUi
This project is one of many microservices. This microservice serves the purpose of being a front end to the pretty-paradise-admin microservice. Other microservices and links to their github repositories are listed below:
1. [pretty-paradise-admin](https://github.com/PrettyParadise/pretty-paradise-admin)
2. [pretty-paradise-infrastructure](https://github.com/PrettyParadise/pretty-paradise-infrastructure)
3. [pretty-paradise-bom](https://github.com/PrettyParadise/pretty-paradise-bom)
4. [pretty-paradise-client](https://github.com/PrettyParadise/pretty-paradise-client)
The development branch contains the latest development code, everything explained in the README is relevant to the development branch.
## Starting the Project
This microservice depends on the _pretty_paradise_bom_, _pretty-paradise-admin_ and _pretty-paradise-infrastructure_ microservices.
To get started we need the BOM (Bill of Material) for both the _pretty-paradise-admin_ and _pretty-paradise-infrastructure_ microservices. The BOM exists in the _master_ branch of the _pretty-paradise-bom_ microservice, pull its code and run _mvn install_ in the directory containing the _pom.xml_ file. This will install all necessary dependencies for the microservices onto your local machine
Next, download the latest _development_ branch content on the _pretty-paradise-infrastructure_ microservice. Ensure you have _docker-compose_ installed on your system and navigate to the _docker_ folder and run _docker-compose up_ which will start a MySQL database (to stop the docker containers defined in the _docker-compose.yml_ file, run _docker-compose down_ in the same directory)
Next we need to start our service discovery application (Eureka server). Open the project in your favourite IDE and navigate to the _eureka_server_ sub module. Find and run the main class (_PrettyParadiseEurekaServer_).
Now we are able to start our backend microservice. Download the latest content on the _development_ branch of the _pretty-paradise-admin_ microservice. Launch it by again openeing it up in your favourite IDE and running the main application (_PrettyParadiseAdminApplication_).
Lastly we can launch the front end application (this microservice) for the admin backend microservice. Navigate to the _development_ branch of this microservice and pull the latest content. Navigate to the location of the _package.json_ file and run _npm start_ in a terminal to have the UI started on port 4200. Navigate to _localhost:4200_ in your browser to view the UI.
<file_sep>import {HttpClient} from "@angular/common/http";
import {ProductModel} from "../core/models/product.model";
import {Injectable} from "@angular/core";
import {Subject} from "rxjs";
@Injectable({providedIn: 'root'})
export class ProductsBackendHttpRequestsService {
private backendAdminProductBaseUrl = 'prettyparadise/products'
updatedProducts = new Subject<ProductModel[]>();
constructor(private http: HttpClient) {
}
getAllProducts(){
return this.http.get<ProductModel[]>(this.backendAdminProductBaseUrl);
}
getProduct(id: number){
return this.http.get<ProductModel>(this.backendAdminProductBaseUrl+ '/' +id);
}
addNewProduct(productDetails: ProductModel, productImage: File) {
let formData = new FormData();
formData.append('productDetails', new Blob([JSON.stringify(productDetails)], {type : 'application/json'}));
formData.append('productImage', productImage);
return this.http.post(this.backendAdminProductBaseUrl, formData);
}
deleteProduct(id: number) {
return this.http.delete(this.backendAdminProductBaseUrl + '/' + id);
}
}
<file_sep>export class ErrorModel{
title: string;
status: number;
detail: string
}
<file_sep>export class ProductModel {
public id: number
public name: string
public price: number
public encodedImage: string
}
<file_sep>import {Component, OnInit} from '@angular/core';
import {NgForm} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {ProductModel} from "../../core/models/product.model";
import {ProductsBackendHttpRequestsService} from "../products-backend-http-requests.service";
import {ErrorModel} from "../../core/models/error.model";
import {HttpErrorResponse} from "@angular/common/http";
@Component({
selector: 'app-product',
templateUrl: './new-product.component.html',
styleUrls: ['./new-product.component.scss']
})
export class NewProductComponent implements OnInit {
productImage: File;
productDetails: ProductModel = new ProductModel();
errorModel: ErrorModel = null;
constructor(private backendHttpRequestsService: ProductsBackendHttpRequestsService,
private router: Router,
private route: ActivatedRoute) { }
ngOnInit(): void {
}
onCreateNewProduct(form: NgForm) {
this.productDetails.name = form.value.name;
this.productDetails.price = form.value.price;
this.backendHttpRequestsService.addNewProduct(this.productDetails, this.productImage).subscribe(
()=>{
this.backendHttpRequestsService.getAllProducts().subscribe(
(updatedProducts) => {
this.backendHttpRequestsService.updatedProducts.next(updatedProducts);
}
);
this.router.navigate(['..'], {relativeTo: this.route});
},
(error: HttpErrorResponse) => {
this.errorModel = error.error;
}
);
}
onNewProductImage(event: Event) {
this.productImage = (<HTMLFormElement>event.target).files[0];
}
}
<file_sep>import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';
import {HeaderComponent} from './core/components/header/header.component';
import {RouterModule, Routes} from '@angular/router';
import {ProductsComponent} from './products/products.component';
import {HomeComponent} from './home/home.component';
import {NewProductComponent} from './products/new-product/new-product.component';
import {ProductDetailsComponent} from './products/product-details/product-details.component';
import {ProductStartComponent} from './products/product-start/product-start.component';
import {ProductEditComponent} from './products/product-edit/product-edit.component';
import {FormsModule} from '@angular/forms';
import {HttpClientModule} from "@angular/common/http";
const appRoutes: Routes = [
{path: '', component: HomeComponent},
{
path: 'products', component: ProductsComponent, children: [
{path: '', component: ProductStartComponent},
{path: 'new', component: NewProductComponent},
{path: ':id', component: ProductDetailsComponent},
{path: ':id/edit', component: ProductEditComponent}
]
}
];
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
ProductsComponent,
HomeComponent,
NewProductComponent,
ProductDetailsComponent,
ProductStartComponent,
ProductEditComponent,
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes),
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
<file_sep>import {Component, OnInit, ViewChild} from '@angular/core';
import {ProductModel} from '../../core/models/product.model';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {FormGroup, NgForm} from '@angular/forms';
import {ProductsBackendHttpRequestsService} from "../products-backend-http-requests.service";
@Component({
selector: 'app-product-edit',
templateUrl: './product-edit.component.html',
styleUrls: ['./product-edit.component.scss']
})
export class ProductEditComponent implements OnInit {
product: ProductModel = new ProductModel();
@ViewChild('form', {static: true})editForm: NgForm;
constructor(private route: ActivatedRoute,
private productsBackendHttpRequestsService: ProductsBackendHttpRequestsService,
private router: Router) {
}
ngOnInit(): void {
this.route.params.subscribe((params: Params) => {
this.productsBackendHttpRequestsService.getProduct(params.id).subscribe(
(product) =>{
this.product = product;
this.editForm.setValue({
productName: product.name,
productPrice: product.price
})
});
});
}
onSubmit(form: NgForm) {
}
onFileSelect(event) {
}
onDeleteProduct() {
const confirmMessage = "Are you sure you want to delete this product "
if (confirm(confirmMessage)){
this.productsBackendHttpRequestsService.deleteProduct(this.product.id).subscribe(
() => {
this.productsBackendHttpRequestsService.getAllProducts().subscribe(
(updatedProducts) => {
this.productsBackendHttpRequestsService.updatedProducts.next(updatedProducts);
}
)
}
)
this.router.navigate(['../../'], {relativeTo: this.route});
console.log(this.route)
}
}
}
<file_sep>import {Component, OnDestroy, OnInit} from '@angular/core';
import {ProductModel} from '../core/models/product.model';
import {ProductsBackendHttpRequestsService} from "./products-backend-http-requests.service";
import {Router} from "@angular/router";
import {Subscription} from "rxjs";
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.scss'],
providers: []
})
export class ProductsComponent implements OnInit, OnDestroy {
products: ProductModel[] = [];
newProductsSubscription: Subscription;
constructor(private productsBackendHttpRequestsService: ProductsBackendHttpRequestsService) { }
ngOnInit(): void {
this.productsBackendHttpRequestsService.getAllProducts().subscribe(
(products) => {
this.products = products
}
);
this.newProductsSubscription = this.productsBackendHttpRequestsService.updatedProducts.subscribe(
(updatedProducts) => {
this.products = updatedProducts;
}
)
}
ngOnDestroy() {
this.newProductsSubscription.unsubscribe();
}
}
<file_sep>import {Component, OnInit} from '@angular/core';
import {ProductModel} from '../../core/models/product.model';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {ProductsBackendHttpRequestsService} from "../products-backend-http-requests.service";
import {HttpErrorResponse} from "@angular/common/http";
import {ErrorModel} from "../../core/models/error.model";
@Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.scss']
})
export class ProductDetailsComponent implements OnInit {
product: ProductModel = new ProductModel();
errorModel: ErrorModel;
constructor(private route: ActivatedRoute,
private router: Router,
private productsBackendHttpRequestsService: ProductsBackendHttpRequestsService) {
}
ngOnInit(): void {
this.route.params.subscribe((params: Params) => {
const id: number = params.id;
this.productsBackendHttpRequestsService.getProduct(id).subscribe(
(product) => {
this.product = product;
console.log(this.product);
},
(error: HttpErrorResponse) => {
this.errorModel = error.error;
}
);
});
}
onEdit() {
this.router.navigate(['edit'], {relativeTo: this.route});
}
}
| 6541b1f0577b12b34a569f64b0dbcfa38d5015bd | [
"Markdown",
"TypeScript"
] | 9 | Markdown | PrettyParadise/pretty-paradise-admin-ui | 4881944d21ed5aa1e8c522e1f3e289988fd3c34f | c628f96865f48554ca272b059681ff0856a79f76 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using FortuneTellerMVC.Models;
namespace FortuneTellerMVC.Controllers
{
public class CustomersController : Controller
{
private FortuneTellerEntities db = new FortuneTellerEntities();
// GET: Customers
public ActionResult Index()
{
return View(db.Customers.ToList());
List<Customer> customerList = db.Customers.ToList();
}
// GET: Customers/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
//fortune variables
int retirementYears = 0;
string vacationHomeLocation = "";
string modeOfTransportation = "";
string ammountOfMoney = "";
//retirementYears
if (customer.Age % 2 != 0)
{
retirementYears = 30;
}
else
{
retirementYears = 110;
}
//Vacation Home
if (customer.NumberOfSiblings == 0)
{
vacationHomeLocation = "Hawaii";
}
else if (customer.NumberOfSiblings == 1)
{
vacationHomeLocation = "Boca Raton";
}
else if (customer.NumberOfSiblings == 2)
{
vacationHomeLocation = "Alaska";
}
else if (customer.NumberOfSiblings == 3)
{
vacationHomeLocation = "The Hamptons";
}
else if (customer.NumberOfSiblings > 3)
{
vacationHomeLocation = "Cozumel";
}
else
{
vacationHomeLocation = "The fires of Mordor";
}
//mode of transportation
switch (customer.FavoriteColor)
{
case "red":
modeOfTransportation = "sexy red motorcycle";
break;
case "orange":
modeOfTransportation = "magic carpet";
break;
case "yellow":
modeOfTransportation = "horse-drawn carriage";
break;
case "green":
modeOfTransportation = "Smart car";
break;
case "blue":
modeOfTransportation = "surf board";
break;
case "indigo":
modeOfTransportation = "tricycle";
break;
case "violet":
modeOfTransportation = "hover board";
break;
default:
modeOfTransportation = "you have to walk because you didn't follow directions!!";
break;
}
//money
if (customer.BirthMonth >= 1 && customer.BirthMonth <= 4)
{
ammountOfMoney = "10,000.00";
}
else if (customer.BirthMonth >= 5 && customer.BirthMonth <= 8)
{
ammountOfMoney = "2.00";
}
else if (customer.BirthMonth >= 9 && customer.BirthMonth <= 12)
{
ammountOfMoney = "1,000,000.00";
}
else
{
ammountOfMoney = "0.00";
}
//full fortune
string fortune = customer.FirstName + " " + customer.LastName + " will retire in " + retirementYears + " years with $" + ammountOfMoney + " in the bank, a vacation home in " + vacationHomeLocation + " and a " + modeOfTransportation + ".";
//fortune in view bag
ViewBag.Fortune = fortune;
return View(customer);
}
// GET: Customers/Create
public ActionResult Create()
{
return View();
}
// POST: Customers/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CustomersID,FirstName,LastName,Age,BirthMonth,FavoriteColor,NumberOfSiblings")] Customer customer)
{
if (ModelState.IsValid)
{
db.Customers.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
// GET: Customers/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// POST: Customers/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CustomersID,FirstName,LastName,Age,BirthMonth,FavoriteColor,NumberOfSiblings")] Customer customer)
{
if (ModelState.IsValid)
{
db.Entry(customer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
// GET: Customers/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// POST: Customers/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Customer customer = db.Customers.Find(id);
db.Customers.Remove(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
| 80c14b926d675d1139df8a48713703b0ce09727c | [
"C#"
] | 1 | C# | lwesley08/FortuneTellerMVC | 229912675b938186e34f9515b096c34acf9e2191 | 7ad402543efa77ebc3cf30201be85b95bc242c4c |
refs/heads/master | <file_sep>/* CyclicIterator from C++ snippets
* Cyclic iterator for STL containers.
* @author <NAME>
* @url http://kacperkolodziej.com/
* @github https://github.com/kolodziej/cppsnippets
*/
#ifndef CYCLIC_ITERATOR_HPP
#define CYCLIC_ITERATOR_HPP
#include <iostream>
#include <iterator>
template <typename Container>
using ContainerValueType = typename Container::value_type;
template <typename Container>
using ContainerIterator = typename Container::iterator;
template <typename Container, typename T = ContainerValueType<Container>, typename Iterator = ContainerIterator<Container>>
class CyclicIterator :
public std::iterator<std::bidirectional_iterator_tag, T, std::ptrdiff_t>
{
private:
Container& container_;
Iterator cursor_;
public:
CyclicIterator(Container& c) :
container_(c),
cursor_(c.begin())
{}
bool operator==(const CyclicIterator& it)
{
return cursor_ == it.cursor_;
}
bool operator!=(const CyclicIterator& it)
{
return !(cursor_ == it.cursor_);
}
T& operator*()
{
return *cursor_;
}
CyclicIterator& operator++()
{
++cursor_;
if (cursor_ == container_.end())
{
cursor_ = container_.begin();
}
return *this;
}
CyclicIterator operator++(int)
{
CyclicIterator it = *this;
++(*this);
return it;
}
CyclicIterator& operator--()
{
if (cursor_ == container_.begin())
{
cursor_ = container_.end();
}
--cursor_;
return *this;
}
CyclicIterator operator--(int)
{
CyclicIterator it = *this;
--(*this);
return it;
}
CyclicIterator& operator+(int n)
{
for (int i = 0; i < n; ++i, ++(*this));
return *this;
}
CyclicIterator& operator-(int n)
{
for (int i = 0; i < n; ++i, --(*this));
return *this;
}
};
#endif
<file_sep>C++ snippets
============
In this repository you will be able to find useful C++ code snippets written by me. I'll write about some of them on [my website](http://kacperkolodziej.com/articles/tag/cppsnippets "C++ snippets tag").
CyclicIterator
--------------
Cyclic iterator for STL containers.
Directory: **/cyclic_iterator/**
| 22cccdbda7fe0bab3c1c1973cc3da1b0777ebe0e | [
"Markdown",
"C++"
] | 2 | C++ | kolodziej/cppsnippets | 35356656c04ac673794518f95b93a7876e696064 | a58eb24ef6d25820dfb5bde7956832d772e788cb |
refs/heads/master | <file_sep># Game-of-life
My interpretation of Conway's game of life
Game-of-life is two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead.\
Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent.
At each step in time, the following transitions occur:
Any live cell with fewer than two live neighbors dies.\
Any live cell with two or three live neighbors lives.\
Any live cell with more than three live neighbors dies.\
Any dead cell with exactly three live neighbors becomes a live cell.
<file_sep>#include <iostream>
#include <Windows.h>
#define COLONS 55
#define ROWS 55
using namespace std;
/*
I use two arrays (map, newMap) for each frame.
At the beginning map has a figure in it and newMap is full with spaces.
Firstly, I check surrounding cells of each cell in map and then full newMap with live and dead cells (live cell ".", dead cell " ").
Secondly, map takes all values from newMap.
Finally, all steps are repeated for each frame.
*/
char map[COLONS][ROWS];
int countLiveCells = 0;//count live cells near the current one cell
bool isNewMapFull = false;
char newMap[COLONS][ROWS];
void FullingNewMap()
{
//Full newMap with spaces
for (int i = 0; i < COLONS; i++)
{
for (int j = 0; j < ROWS; j++)
{
newMap[i][j] = ' ';
}
}
}
void ClearScreen()
{
COORD cursorPosition;
cursorPosition.X = 0;
cursorPosition.Y = 0;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cursorPosition);
}
void StartFigure(int i, int j)
{
//Full map with the start figure
if (((i == 12 || i == 15) && j >= 22 && j <= 26) || ((i == 13 || i == 17) && (j == 22 || j == 26)) || ((i == 14 || i == 16) && (j == 22 || j == 24 || j == 26)) || (i == 18 && (j >= 23 && j <= 25)))
{
map[i][j] = '.';
}
else
{
map[i][j] = ' ';
}
}
void Rules(int i, int j)
{
/*
Decides if the current cell to be live or dead
And full newMap with them
*/
if (countLiveCells < 2 || countLiveCells > 3)
{
//Dead cell
newMap[i][j] = ' ';
}
else if (countLiveCells == 3)
{
//Live cell
newMap[i][j] = '.';
}
}
void CheckingForLiveCells(int i, int j)
{
/*
Check cells in the range of map
h and k are used to check the surrounding 8 cells
*/
if ((i > 0 && i < COLONS - 1) && (j > 0 && j < ROWS - 1))
{
for (int h = -1; h <= 1; h++)
{
for (int k = -1; k <= 1; k++)
{
if (map[i + h][j + k] == '.')
{
if (i + h != i || j + k != j)
{
//Count live cells around the current one cell
countLiveCells++;
if (h == 1)
{
//When the last cell around the current one is count
Rules(i, j);
}
}
}
else if (map[i + h][j + k] == ' ')
{
if (i + h != i || j + k != j)
{
//Count live cells around the current one cell
if (h == 1)
{
//When the last cell around the current one is count
Rules(i, j);
}
}
}
}
}
}
//Reset countLiveCells for the next cell
countLiveCells = 0;
}
void FullingMap()
{
//Full map with live and dead cellss
for (int i = 0; i < COLONS; i++)
{
for (int j = 0; j < ROWS; j++)
{
if (isNewMapFull == false)
{
StartFigure(i, j);
}
else if (isNewMapFull == true)
{
CheckingForLiveCells(i, j);
}
}
}
}
void OutputingMap()
{
for (int i = 0; i < COLONS; i++)
{
for (int j = 0; j < ROWS; j++)
{
if (isNewMapFull == true)
{
map[i][j] = newMap[i][j];
}
cout << map[i][j];
}
cout << endl;
}
}
int main()
{
while (true)
{
if (isNewMapFull == false)
{
FullingNewMap();
}
FullingMap();
OutputingMap();
isNewMapFull = true;
ClearScreen();
Sleep(700);
}
return 0;
}
| 38fbe79313d21d1dc93fc9730a4a64bcd215c21f | [
"Markdown",
"C++"
] | 2 | Markdown | borislavvv00/Game-of-life | dace7c682a0f706dd72ddca3c21fa0bdc01c74f1 | 05c131e11f4b5f6482ff633fe491716040b1bb75 |
refs/heads/master | <file_sep># SCSS Spectre.css
This is a fork of the current Spectre.css framework, modified to use **SCSS** rather than **LESS** precompilation. I have kept the original LESS `src/` folder to allow future updates and merges to be simpler, but the SCSS is located in the `scss/` sub-folder.
The `package.json` and `gulpfile.js` have been modified to compile the SCSS version rather than the LESS version.
The `docs/dist` folder is actually using the version of Spectre.css compiled with SCSS via Gulp and is used for testing and to ensure parity between LESS and SCSS versions.
### Overview
Spectre.css is a lightweight, responsive and modern CSS framework for faster and extensible development.
- Lightweight (~10KB gzipped) starting point for your projects
- Flexbox-based, responsive and mobile-friendly layout
- Elegantly designed and developed elements and components
Spectre is a side project based on years of CSS development work on a large web service project. Spectre only includes modern base styles, responsive layout system, CSS components and utilities, and it can be modified for your project with LESS compiler.
Spectre.css is completely free to use. If you enjoy it, please consider [donating via Paypal](https://www.paypal.me/picturepan2) for the further development. ♥
### Getting started
There are 5 ways to get started with Spectre CSS framework in your projects. You can either manually install or use NPM, Yarn and Bower.
#### Install manually
Download the compiled and minified [Spectre CSS file](https://github.com/trilbymedia/spectre-scss/tree/master/docs/dist). And include `spectre.css` located in `/docs/dist` in your website or Web app <head> part.
`<link rel="stylesheet" href="spectre.min.css" />`
#### Install from CDN
Alternatively, you can use the [unpkg](https://unpkg.com/) CDN to load compiled Spectre.css.
`<link rel="stylesheet" href="https://unpkg.com/spectre.css/dist/spectre.min.css" />`
#### Install with NPM
`$ npm install spectre.css --save`
#### Install with Yarn
`$ yarn add spectre.css`
#### Install with Bower
`$ bower install spectre.css --save`
### Compiling custom version
You can compile your custom version of Spectre.css. Read [the documentation](https://picturepan2.github.io/spectre/getting-started.html#compiling).
### Documentation and examples
#### Elements
- [Typography](https://picturepan2.github.io/spectre/elements.html#typography) - headings, paragraphs, semantic text, blockquote, lists and code elements, optimized for east asian fonts
- [Tables](https://picturepan2.github.io/spectre/elements.html#tables) - organize and display data
- [Buttons](https://picturepan2.github.io/spectre/elements.html#buttons) - button styles in different types and sizes, and even button groups
- [Forms](https://picturepan2.github.io/spectre/elements.html#forms) - input, radio, checkbox, switch and other form elements
- [Icons](https://picturepan2.github.io/spectre/elements.html#icons) - single-element, responsive and pure CSS icons
- [Labels](https://picturepan2.github.io/spectre/elements.html#labels) - formatted text tags for highlighted, informative information
- [Codes](https://picturepan2.github.io/spectre/elements.html#codes) - inline and multiline code snippets
- [Media](https://picturepan2.github.io/spectre/elements.html#media) - responsive images, figures and video classes
#### Layout
- [Flexbox grid](https://picturepan2.github.io/spectre/layout.html#grid) - flexbox based responsive grid system
- [Responsive](https://picturepan2.github.io/spectre/layout.html#responsive) - responsive grid and utilities
- [Navbar](https://picturepan2.github.io/spectre/layout.html#navbar) - layout container that appears in the header of apps and websites
#### Components
- [Accordions](https://picturepan2.github.io/spectre/components.html#accordions) - used to toggle sections of content
- [Autocomplete](https://picturepan2.github.io/spectre/components.html#autocomplete) - form component provides suggestions while you type
- [Avatars](https://picturepan2.github.io/spectre/components.html#avatars) - user profile pictures or name initials rendered avatar
- [Badges](https://picturepan2.github.io/spectre/components.html#badges) - unread number indicators
- [Breadcrumbs](https://picturepan2.github.io/spectre/components.html#breadcrumbs) - navigational hierarchy
- [Bars](https://picturepan2.github.io/spectre/components.html#bars) - progress of a task or the value within the known range
- [Cards](https://picturepan2.github.io/spectre/components.html#cards) - flexible content containers
- [Chips](https://picturepan2.github.io/spectre/components.html#chips) - complex entities in small blocks
- [Empty states](https://picturepan2.github.io/spectre/components.html#empty) - empty states/blank slates for first time use, empty data and error screens
- [Menus](https://picturepan2.github.io/spectre/components.html#menus) - list of links or buttons for actions and navigation
- [Navs](https://picturepan2.github.io/spectre/components.html#navs) - navigational list of links
- [Modals](https://picturepan2.github.io/spectre/components.html#modals) - flexible dialog prompts
- [Pagination](https://picturepan2.github.io/spectre/components.html#pagination) - navigational links for multiple pages
- [Panels](https://picturepan2.github.io/spectre/components.html#panels) - flexible view container with auto-expand content section
- [Popovers](https://picturepan2.github.io/spectre/components.html#popovers) - small overlay content containers
- [Steps](https://picturepan2.github.io/spectre/components.html#steps) - progress indicators of a sequence of task steps
- [Tabs](https://picturepan2.github.io/spectre/components.html#tabs) - toggle for different views
- [Tiles](https://picturepan2.github.io/spectre/components.html#tiles) - repeatable or embeddable information blocks
- [Toasts](https://picturepan2.github.io/spectre/components.html#toasts) - showing alerts or notifications
- [Tooltips](https://picturepan2.github.io/spectre/components.html#tooltips) - simple tooltip built entirely in CSS
#### Utilities
- [Utilities](https://picturepan2.github.io/spectre/utilities.html) - colors, display, divider, loading, position, shapes and text utilities
#### Experimentals
- [Calendars](https://picturepan2.github.io/spectre/experimentals.html#calendars) - date or date range picker and events display
- [Carousels](https://picturepan2.github.io/spectre/experimentals.html#carousels) - slideshows for cycling images
- [Comparison Sliders](https://picturepan2.github.io/spectre/experimentals.html#comparison) - sliders for comparing two images, built entirely in CSS
- [Filters](https://picturepan2.github.io/spectre/experimentals.html#carousels) - CSS only content filters
- [Meters](https://picturepan2.github.io/spectre/experimentals.html#meters) - representing the value within the known range
- [Parallax](https://picturepan2.github.io/spectre/experimentals.html#parallax) - acting like Apple TV/tvOS hover parallax effect, built entirely in CSS
- [Progress](https://picturepan2.github.io/spectre/experimentals.html#progress) - indicators for the progress completion of a task
- [Sliders](https://picturepan2.github.io/spectre/experimentals.html#sliders) - selecting values from ranges
- [Timelines](https://picturepan2.github.io/spectre/experimentals.html#timelines) - ordered sequences of activities
### Browser support
Spectre uses [Autoprefixer](https://github.com/postcss/autoprefixer) to make most styles compatible with earlier browsers and [Normalize.css](https://necolas.github.io/normalize.css/) for CSS resets. Spectre is designed for modern browsers. For best compatibility, these browsers are recommended:
- Chrome (last 4)
- Microsoft Edge (last 4)
- Firefox (last 4)
- Safari (last 4)
- Opera (last 4)
- Internet Explorer 10+
Designed and built with ♥ by [<NAME>](https://twitter.com/picturepan2). Feel free to submit a pull request. Help is always appreciated.
<file_sep>#!/bin/sh
for f in *.scss ; do mv "$f" "_$f" ; done
| 65397f9bbb9d9c0909248744f3a6f0d993caef55 | [
"Markdown",
"Shell"
] | 2 | Markdown | trilbymedia/spectre-scss | dc67f24b261ab6f3f9b0d13af387fccacfcfc1cd | a538f7fe9bdd206706ab0d17d972e6e181bafec3 |
refs/heads/master | <repo_name>mars-rover-society/gps<file_sep>/src/gps_node.cpp
/***************************************************************************************************
* NOVA ROVER TEAM - URC2018
* This code is a ROS package which periodically retrieves data from a Waveshare NEO-7M-C GPS module.
* The data is retrieved via UART, and is parsed through to obtain the latitude and longitude
* GPS coordinates.
*
* The GPS module being used:
* www.robotshop.com/ca/en/uart-neo-7m-c-gps-module.html
*
* Author: <NAME>
* Last Modified by: <NAME> (30/11/2017)
***************************************************************************************************/
/***************************************************************************************************
* INCLUDES, DECLARATIONS AND GLOBAL VARIABLES
***************************************************************************************************/
#include "ros/ros.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <wiringPi.h>
#include <wiringSerial.h>
#include <gps/Gps.h>
#include <sstream>
#define LOOP_HERTZ 1 // GPS sends data every ~1 second
//char GPS_data_array[40]; // Holds data from the GLL line to be parsed
double latitude, longitude;
bool use_fake; // Use fake coords?
double fake_lat, fake_long; // Fake GPS coords
/**************************************************************************************************
* DEGREES-MINUTES-SECONDS TO DECIMAL DEGREES CONVERSION FUNCTION
*
* Converts a number in decimal-minutes-seconds to decimal degrees and returns it.
*
* Inputs: int deg - the degree value of the coordinate
* int min - the minutes value of the coordinate
* float sec - the seconds value of the coordinate, should be a decimal
* int dir - the direction of the coordinate as a positive or negative multiplier (1/-1).
*
* Output: float DecDeg - the decimal degrees representation of the DMS number
**************************************************************************************************/
float ConvertDMSToDD(int deg, int min, float sec, int dir) {
float DecDeg = (float)dir * (((float)deg) + ((float)min/60) + (sec/3600));
return DecDeg;
}
/***************************************************************************************************
* DATA PARSING FUNCTIOM
* This function parses the GLL line sent by module for the GPS coordinates, if it is a valid reading.
* The output of this function is applied directly to the global variables "latitude" and "longitude".
*
* This function assumes that the GLL output format is fixed.
*
* Inputs: char *GPS_data_array - The character array containing all required data from the GLL line.
*
* todo: modify function to return obtained coordinates using a float array rather than modifying
* global variables directly.
***************************************************************************************************/
void ProcessGPSData(char *GPS_data_array) {
int lat_deg, lat_min, long_deg, long_min, lat_dir, long_dir;
float lat_sec, long_sec;
// Determine latitude in degrees-minutes-seconds (DMS) format.
// "GPS_data_array[X]-'0'" converts a number in character format to int, allowing for calculations
lat_deg = ((GPS_data_array[1]-'0')*10) + (GPS_data_array[2]-'0');
lat_min = ((GPS_data_array[3]-'0')*10) + (GPS_data_array[4]-'0');
lat_sec = (((float)(GPS_data_array[6]-'0')/10) + ((float)(GPS_data_array[7]-'0')/100) + ((float)(GPS_data_array[8]-'0')/1000) + ((float)(GPS_data_array[9]-'0')/10000) + ((float)(GPS_data_array[10]-'0')/100000))*60;
// Determine latitude direction by checking if character following DMS value is North (N) / South (S).
if(GPS_data_array[12]=='N') {
lat_dir = 1; // Let 1 represent North, -1 represent South
}
else {
lat_dir = -1;
}
// Determine longitude in DMS format
long_deg = ((GPS_data_array[14]-'0')*100) + ((GPS_data_array[15]-'0')*10) + (GPS_data_array[16]-'0');
long_min = ((GPS_data_array[17]-'0')*10) + (GPS_data_array[18]-'0');
long_sec = (((float)(GPS_data_array[20]-'0')/10) + ((float)(GPS_data_array[21]-'0')/100) + ((float)(GPS_data_array[22]-'0')/1000) + ((float)(GPS_data_array[23]-'0')/10000) + ((float)(GPS_data_array[24]-'0')/100000))*60;
// Determine longitude direction
if(GPS_data_array[26]=='E') {
long_dir = 1;
}
else {
long_dir = -1;
}
// Convert DMS to DD
latitude = ConvertDMSToDD(lat_deg, lat_min, lat_sec, lat_dir);
longitude = ConvertDMSToDD(long_deg, long_min, long_sec, long_dir);
}
/***************************************************************************************************
* MAIN FUNCTION
* Sets up UART connection and periodically reads data on connection for new GPS data.
* This parsed data is then published via ROS.
* Published messages:
* Valid Reading - Two message are sent: one containing the latitude coordinates (msg.latitude) and
* one which contains the longitude coordinates (msg.longitude). Both coordinates are in decimal
* degrees format.
* Invalid Reading - Nothing. A warning will be printed to the ROS info stream to inform the user.
***************************************************************************************************/
int main(int argc, char **argv)
{
setenv("WIRINGPI_GPIOMEM","1",1); // Set environmental var to allow non-root access to GPIO pins
ros::init(argc, argv, "gps"); // Initialise ROS package
ros::NodeHandle n("/");
//ros::NodeHandle np("~"); // Private nodehandle
ros::Publisher sensor_pub = n.advertise<gps::Gps>("/gps/gps_data", 1000);
ros::Rate loop_rate(LOOP_HERTZ); // Define loop rate
int fd;
char uartChar; // The character retrieved from the UART RX buffer
unsigned int enable_data_capture = 0; // Boolean which is set to 1 (TRUE) when GLL line has been located
unsigned int data_is_valid = 0;
unsigned int array_index;
char data_capture_array[40];
bool print_coords = 0;
// Grab params
//n.getParam("/gps/use_fake", use_fake);
//n.getParam("/gps/fake_lat", fake_lat);
//n.getParam("/gps/fake_long", fake_long);
use_fake=false;
fake_lat = -37.9089064;
fake_long = 145.1338591;
//ROS_INFO_STREAM("use_fake is " << use_fake);
// Attempt to open UART
if((fd=serialOpen("/dev/ttyS0",9600))<0) { // 9600 baudrate determined from module datasheet
printf("Unable to open serial device\n");
return 1;
}
// Attempt to setup WiringPi
if(wiringPiSetup() == -1) {
printf("Cannot start wiringPi\n");
}
while (ros::ok())
{
gps::Gps msg;
while(1)
{
//if(!use_fake) // Use real GPS data
//{
// If there is new UART data...
if(serialDataAvail(fd))
{
// ... retrieve the next character
uartChar = serialGetchar(fd);
// If the character is "L", it must be a GLL line
if(uartChar=='L')
{
enable_data_capture = 1; // So we save the data by enabling data capture
array_index = 0;
print_coords = 0;
data_is_valid = 1; // Assume that the reading is valid until otherwise
}
else
{
// If we are in the GLL line...
if(enable_data_capture)
{
// ... check for EOL char or validity character
switch(uartChar)
{
case '\r': // EOL found, GLL line over; end data capture
enable_data_capture = 0;
// If the data is valid...
if(data_is_valid)
{
ProcessGPSData(data_capture_array); // ...obtain coordinates from the data
print_coords = 1;
}
else
{
// Otherwise, inform user that coordinates could not be obtained
ROS_INFO("GPS module cannot locate position.");
}
break;
case 'V': // If the reading is invalid, the module sends a "V" char
data_is_valid = 0; // Set valid reading boolean to 0 (FALSE)
default:
data_capture_array[array_index] = uartChar; // Save all other data if data capture is enabled
array_index++;
}
}
}
fflush(stdout); // Flush buffer
}
else
{
// Do not publish message on startup before data has been received
if((latitude==0)&&(longitude==0))
{
data_is_valid = 0;
}
break; // No data available; end loop to free CPU
}
// Publish readings
if(data_is_valid && print_coords)
{
msg.latitude = latitude;
msg.longitude = longitude;
// ROS_INFO("Latitude: %f, Longitude: %f", latitude, longitude);
sensor_pub.publish(msg);
}
}
/*
else // Use fake gps coordinate
{
msg.latitude = fake_lat;
msg.longitude = fake_long;
ROS_INFO("Latitude: %f, Longitude: %f", fake_lat, fake_long);
sensor_pub.publish(msg);
}*/
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<file_sep>/README.md
# ROS GPS Package
This code is a ROS package which periodically retrieves data from a Waveshare NEO-7M-C GPS module.
The data is retrieved via UART, and is parsed through to obtain the latitude and longitude GPS coordinates.
The GPS module being used: www.robotshop.com/ca/en/uart-neo-7m-c-gps-module.html
## Dependencies:
- WiringPi (http://wiringpi.com/download-and-install/)
## Physical Connections:
The module should be connected to the Raspberry Pi as such:
GPS Module: Raspberry Pi:
* Vcc --> 3.3V
* GND --> Ground
* TX --> UART0 RX
* RX --> UART0 TX
For more information about pin assignments, see the package.xml
## Publications:
Topic: **/gps/gps_data**<br />
Msg type: gps/Gps (custom)<br />
Description: Provides latitude and longitude readings from the GPS module.
| 7ff4a712c9fbc84bbc11b33b4c640fc6548bc459 | [
"Markdown",
"C++"
] | 2 | C++ | mars-rover-society/gps | 5b824f4a6877c3c2f57450d89432b4e1fb8b0e42 | 8ad523a2a561f8263a456a4495179db4457f4f3b |
refs/heads/master | <file_sep>from django.contrib import admin
from .models import Target, Exercise, Workout
# Register your models here.
admin.site.register(Target)
admin.site.register(Exercise)
admin.site.register(Workout)
<file_sep># itc172_final
An app for logging workouts
<file_sep>from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Target(models.Model):
targetname = models.CharField(max_length=255)
def __str__(self):
return self.targetname
class Meta:
db_table = 'target'
class Exercise(models.Model):
exercisename = models.CharField(max_length=255)
exercisedescription = models.TextField(null=True, blank=True)
target = models.ForeignKey(Target, on_delete=models.DO_NOTHING)
def __str__(self):
return self.exercisename
class Meta:
db_table = 'exercise'
class Workout(models.Model):
userid = models.ForeignKey(User, on_delete=models.DO_NOTHING)
workoutname = models.CharField(max_length=255, null=True, blank=True)
workoutdate = models.DateField()
workouttime = models.TimeField()
workoutlocation = models.CharField(max_length=255, null=True, blank=True)
exercises = models.ManyToManyField(Exercise)
def __str__(self):
return self.workoutname
class Meta:
db_table = 'workout'<file_sep>from django import forms
from .models import Target, Exercise, Workout
class WorkoutForm(forms.ModelForm):
class Meta:
model=Workout
fields='__all__'<file_sep>from django.test import TestCase
from .models import Target, Exercise, Workout
from .forms import WorkoutForm
from datetime import datetime
from django.urls import reverse
# Create your tests here.
# model tests
class TargetTest(TestCase):
def test_stringOutput(self):
target=Target(targetname='Cardio')
self.assertEqual(str(target), target.targetname)
def test_tablename(self):
self.assertEqual(str(Target._meta.db_table), 'target')
class ExerciseTest(TestCase):
def test_stringOutput(self):
exercise=Exercise(exercisename='Cycling')
self.assertEqual(str(exercise), exercise.exercisename)
def test_tablename(self):
self.assertEqual(str(Exercise._meta.db_table), 'exercise')
class ReviewTest(TestCase):
def test_stringOutput(self):
workout=Workout(workoutname='Night Jog')
self.assertEqual(str(workout), workout.workoutname)
def test_tablename(self):
self.assertEqual(str(Workout._meta.db_table), 'workout')
class TestIndex(TestCase):
def test_view_url_accessible_by_name(self):
response = self.client.get(reverse('index'))
self.assertEqual(response.status_code, 200)
def test_view_uses_correct_template(self):
response = self.client.get(reverse('index'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'workout/index.html')
class TestExercises(TestCase):
def test_view_url_exists_at_desired_location(self):
response = self.client.get('/workout/exercises')
self.assertEqual(response.status_code, 200)
def test_view_url_accessible_by_name(self):
response = self.client.get(reverse('exercises'))
self.assertEqual(response.status_code, 200)
def test_view_uses_correct_template(self):
response = self.client.get(reverse('exercises'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'workout/exercises.html')
class New_Workout_Form_Test(TestCase):
# Valid Form Data
def test_productForm_is_valid(self):
form = WorkoutForm(data={'userid': "michael", 'workoutname': "Night Ride", 'workoutdate': "2018-12-17", 'workouttime': "06:34:30", 'workoutlocation':"Cal Anderson Park", 'exercises':"Cycling" })
self.assertTrue(form.is_valid())
# Invalid Form Data
def test_UserForm_invalid(self):
form = WorkoutForm(data={'userid': "michael", 'workoutname': "Night Ride", 'workoutdate': "2018-12-17", 'workouttime': "06:34:30", 'workoutlocation':"Cal Anderson Park", 'exercises':"Cycling" })
self.assertFalse(form.is_valid())
<file_sep># Generated by Django 2.1.5 on 2019-03-17 06:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Exercise',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('exercisename', models.CharField(max_length=255)),
('exercisedescription', models.TextField(blank=True, null=True)),
],
options={
'db_table': 'exercise',
},
),
migrations.CreateModel(
name='Target',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('targetname', models.CharField(max_length=255)),
],
options={
'db_table': 'target',
},
),
migrations.CreateModel(
name='Workout',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('workoutdate', models.DateField()),
('workouttime', models.TimeField()),
('workoutlocation', models.CharField(blank=True, max_length=255, null=True)),
('exercises', models.ManyToManyField(to='workout.Exercise')),
('userid', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'workout',
},
),
migrations.AddField(
model_name='exercise',
name='target',
field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='workout.Target'),
),
]
<file_sep>from django.shortcuts import render, get_object_or_404
from .models import Exercise, Workout
from .forms import WorkoutForm
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
return render(request, 'workout/index.html')
def exercises(request):
exercise_list=Exercise.objects.all()
return render (request, 'workout/exercises.html', {'exercise_list': exercise_list})
def getworkouts(request):
workout_list=Workout.objects.all()
return render (request, 'workout/workouts.html', {'workout_list': workout_list})
def workoutdetail(request, id):
detail=get_object_or_404(Workout, pk=id)
return render (request, 'workout/logentry.html', {'detail': detail})
#form view
@login_required
def newWorkout(request):
form=WorkoutForm
if request.method=='POST':
form=WorkoutForm(request.POST)
if form.is_valid():
post=form.save(commit=True)
post.save()
form=WorkoutForm()
else:
form=WorkoutForm()
return render (request, 'workout/newworkout.html', {'form': form})
def loginmessage(request):
return render (request, 'workout/loginmessage.html')
def logoutmessage(request):
return render (request, 'workout/logoutmessage.html')<file_sep># Generated by Django 2.1.5 on 2019-03-18 06:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workout', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='workout',
name='workoutname',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('exercises/', views.exercises, name='exercises'),
path('getworkouts/', views.getworkouts, name='getworkouts'),
path('workoutdetail/<int:id>', views.workoutdetail, name='workoutdetail'),
path('newWorkout', views.newWorkout, name='newWorkout'),
path('loginmessage', views.loginmessage, name='loginmessage'),
path('logoutmessage', views.logoutmessage, name='logoutmessage'),
] | 9de99cbf46fc613adb91586a69ca12d954a37dda | [
"Markdown",
"Python"
] | 9 | Python | michaelrodgers/itc172_final | b71f25a5cbffab00b06c60c8816f339d169d9dc1 | 8dbbdd77d79fd30791f75a1b4d958f429dfacda3 |
refs/heads/master | <repo_name>iris-rain/mycode<file_sep>/apisqlite/templates/OMDBSearch.html
<h bold=true> Welcome to the OMDB Movie Client and DB </h>
<h2>Returned data will be written into the local database </h2>
<ul>
<li><a href="/searchstring">Search for All Movies Containing String</a></li>
<li><a href="/searchstringtype">Search for Movies Containing String, and by Type</a></li>
<li> Exit</li>
</ul>
<file_sep>/flaskapi/consumelimitedapis.py
import requests
url = "http://0.0.0.0:2224/fast"
def main():
counter = 0
while True:
resp = requests.get(url)
#got_dj = resp.json()
print(resp.status_code)
counter += 1
if counter > 201:
break
if __name__ == "__main__":
main()
<file_sep>/iceAndFire05.py
#!/usr/bin/python3
"""Alta3 Research - Exploring OpenAPIs with requests"""
# documentation for this API is at
# https://anapioficeandfire.com/Documentation
import requests
import pprint
AOIF_CHAR = "https://www.anapioficeandfire.com/api/characters/"
def main():
while True:
#os.system("clear")
## Ask user for input
got_charToLookup = input("Pick a number between 1 and 1000 to return info on a GoT character! " )
## Send HTTPS GET to the API of ICE and Fire character resource
gotresp = requests.get(AOIF_CHAR + got_charToLookup)
## Decode the response
got_dj = gotresp.json()
pprint.pprint(got_dj)
house_apis = got_dj['allegiances']
print(f'{got_dj["name"]} belongs to the following houses:\n')
for house_api in house_apis:
got_house = requests.get(house_api).json()
pprint.pprint(got_house['name'])
print(f'\n\n{got_dj["name"]} appears in the following books:\n')
for book_api in got_dj['books']:
got_book = requests.get(book_api).json()
pprint.pprint(got_book['name'])
for book_api in got_dj['povBooks']:
got_book = requests.get(book_api).json()
pprint.pprint(got_book['name'])
cont= input('\n Do you want to continue? (Y/N)')
if cont.upper() != "Y":
break
if __name__ == "__main__":
main()
<file_sep>/trivia.py
#!/usr/bin/python3
import requests
import pprint
import html
def HandleMultiple(correct, incorrect):
def main():
# issue an HTTP PUT transaction to store our data within /keys/requests
# in this case, PUT created a 'file' called '/requests', with a 'value' of 'http for humans'
# r is the response code resulting from the PUT
r = requests.get("https://opentdb.com/api.php?amount=2&difficulty=hard&type=boolean")
# pretty print the json in the response
#pprint.pprint(r.json()['results'])
for q in r.json()['results']:
print(html.unescape(q['question']))
if q['type'] == 'boolean':
print("(True/False)")
a = input()
if a.lower() == q['correct_answer'].lower():
print("\n---You got it---\n")
else:
print("\n---Wrong---\n")
print('******')
if __name__ == "__main__":
main()
<file_sep>/flaskapi/jinja2challenge.py
#!/usr/bin/env python3
import json
from flask import Flask
from flask import session
from flask import render_template
from flask import redirect
from flask import url_for
from flask import request
app = Flask(__name__)
app.secret_key = "any random string"
#grab the value 'username'
@app.route("/login", methods=["GET", "POST"])
def login():
## if you sent us a POST because you clicked the login button
if request.method == "POST":
## request.form["xyzkey"]: use indexing if you know the key exists
## request.form.get("xyzkey"): use get if the key might not exist
session["username"] = request.form.get("username")
return redirect(url_for("showhosts"))
## return this HTML data if you send us a GET
return """
<form action = "" method = "post">
<p><input type = text name = username></p>
<p><input type = submit value = Login></p>
</form>
"""
@app.route("/logout")
def logout():
# remove the username from the session if it is there
session.pop("username", None)
return redirect(url_for("showhosts"))
@app.route("/")
@app.route("/showhosts")
def showhosts():
# render the jinja template "helloname.html"
# apply the value of username for the var name
with open("hostnames.json", "r") as hostinfos:
hoststring = hostinfos.read()
hosts = json.loads(hoststring)
return render_template("challenge.html", groups= hosts)
@app.route("/addhost", methods=["GET", "POST"])
def addhost():
if "username" not in session:
return "You are not logged in <br><a href = '/login'></b>" + \
"click here to log in</b></a>"
if request.method == "POST":
hostname = request.form.get("hostname")
ip = request.form.get("ip")
fqdn = request.form.get("fqdn")
y = {"hostname": hostname, "ip": ip, "fqdn": fqdn}
with open("hostnames.json", "r+") as file:
# First we load existing data into a dict.
file_data = json.load(file)
# Join new_dat3a with file_data
file_data.append(y)
# Sets file's current position at offset.
file.seek(0)
# convert back to json.
json.dump(file_data, file, indent = 4)
return redirect(url_for("showhosts"))
return render_template("addhost.html")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=2224)
| 4b84238289d249c8197f5cbfcbb0a556645f4701 | [
"Python",
"HTML"
] | 5 | HTML | iris-rain/mycode | efc4a35a076ab4f21e3549025759f7f02b44c6c0 | fa7d4e96c7927f3588b08c0fb61baca4fbeea673 |
refs/heads/master | <file_sep>/**
* @public
* Enum of all renderer form types available
* @properties={typeid:35,uuid:"E4F70004-F7BE-4806-AC3C-F727EC06AF8F",variableType:-4}
*/
var FILTER_TYPES = {
/**
* Date filter
* */
DATE: 'datePopupFilterTemplate',
/**
* Number filter
* */
NUMBER: 'numberPopupFilterTemplate',
/**
* Tokens filter
* */
TOKEN: 'tokenPopupFilterTemplate',
/**
* Select filter
* */
SELECT: 'selectFilterTemplate'
};
/**
* @type {String}
* @private
*
* @properties={typeid:35,uuid:"472FF5A6-F073-4910-9CB1-565F46327D67"}
*/
var TOOLBAR_FILTER_NAME = "svy-toolbar-filter";
/**
* cache locally the latest popup filter open, to be used in the callback method
* @type {AbstractToolbarFilterUX}
* @private
* @properties={typeid:35,uuid:"4E5DE070-8F3C-45A1-8804-15236FE03AAB",variableType:-4}
*/
var latestToolbarFilter = null;
/**
* This is a Singleton
* @type {PopupRendererForms}
* @private
* @properties={typeid:35,uuid:"85FB53C2-C19C-419B-9F03-642998E3B1F4",variableType:-4}
*/
var popupRendererForms;
/**
* This is a Singleton
* @type {FilterConfig}
* @private
* @properties={typeid:35,uuid:"9F30ABE1-06E5-4A81-BDAF-688EEE5A73F4",variableType:-4}
*/
var globalFilterConfig;
/**
* @private
* @properties={typeid:24,uuid:"51DB1DD3-1632-4667-82F9-C2EF07BF1A5B"}
*/
function FilterConfig() {
// TODO default auto-apply behavior
// this.autoApply = true;
this.useNonVisibleColumns = true;
this.globalDateDisplayFormat = "dd-MM-yyyy";
}
/**
* @since v1.1.0
* @return {Boolean} Default true.
* @private
* @properties={typeid:24,uuid:"CE62E19D-27B9-49C7-BD74-5B47D8F2F3B2"}
*/
function getConfigUseNonVisibleColumns() {
return globalFilterConfig.useNonVisibleColumns;
}
/**
* Use only visible columns of the grid when set to false
*
* @since v1.1.0
* @public
* @param {Boolean} useNonVisibleColumns Default true.
*
* @properties={typeid:24,uuid:"11013635-12DE-4CDF-9A28-57E9AC8784EB"}
*/
function setConfigUseNonVisibleColumns(useNonVisibleColumns) {
// TODO can i make it an UI property
globalFilterConfig.useNonVisibleColumns = useNonVisibleColumns;
}
/**
* Sets global display date format to be used
*
* @public
* @param {String} displayFormat
*
* @properties={typeid:24,uuid:"1637F3D9-CE2A-445C-B0C3-9150B13B75C7"}
*/
function setConfigDateDisplayFormat(displayFormat) {
if(displayFormat != null && displayFormat.trim() != "")
globalFilterConfig.globalDateDisplayFormat = displayFormat;
}
/**
* @constructor
* @private
* @properties={typeid:24,uuid:"EA19BC69-1CA7-4C3A-B6F3-BB972688F4BD"}
*/
function PopupRendererForms() {
/**
* @protected
* @type {RuntimeForm<AbstractPopupFilter>}
* */
this.datePopupFilterTemplate = {template: forms.svyDatePopupFilter};
/**
* @protected
* @type {RuntimeForm<AbstractPopupFilter>}
* */
this.numberPopupFilterTemplate = {template: forms.svyNumberPopupFilter};
/**
* @protected
* @type {RuntimeForm<AbstractPopupFilter>}
* */
this.tokenPopupFilterTemplate = {template: forms.svyTokenPopupFilter};
/**
* @protected
* @type {RuntimeForm<AbstractLookup>}
* */
this.selectFilterTemplate = {template: forms.svySelectPopupFilter};
}
/**
* @return {PopupRendererForms}
* @protected
* @deprecated
* @properties={typeid:24,uuid:"BBACCB75-672F-4067-BE33-A14A7150496C"}
*/
function getPopupUIFormRendered() {
return popupRendererForms;
}
/**
* @return {PopupRendererForms}
* @private
* @properties={typeid:24,uuid:"76C600A8-C6E6-4CDA-8CE1-7959A936BB36"}
*/
function getPopupRendererForms() {
return popupRendererForms;
}
/**
* @public
* Sets the renderer form for the given formType
* @param {String} formType any of the FILTER_TYPES
* @param {RuntimeForm<AbstractPopupFilter>|RuntimeForm<AbstractLookup>} form the form to set
*
* @properties={typeid:24,uuid:"D64D95B4-75A2-43D7-8D2E-1DFDEBBD64E1"}
*/
function setPopupRendererForm(formType, form) {
popupRendererForms.setRendererForm(formType, form);
}
/**
* @since v1.1.0
* @public
* Sets the default operator for the given formType
*
* Is possible to change the default operator used by the filters using the global setting _setPopupDefaultOperator_.
* Each filter type can make use of a different set of operators; user enum scopes.svyPopupFilter.OPERATOR for available options.
* Specifically
* <br/>
* <br/>
* - TOKEN: IS_IN(DEFAULT), LIKE, LIKE_CONTAINS<br/>
* - NUMBER: EQUALS(DEFAULT), BETWEEN, GREATER_EQUAL, GREATER_THEN, SMALLER_EQUAL, SMALLER_THEN<br/>
* - DATE: BETWEEN(DEFAULT), GREATER_EQUAL, SMALLER_EQUAL, EQUALS<br/>
* - SELECT: IS_IN(DEFAULT)<br/>
* <br/>
*
* The TOKEN filter type used to search on TEXT fields by default will search for an exact match using the IS_IN clause.
* Is possible to change such behavior into a LIKE for SEARCH_WORD% or %SEARCH_WORD% by changing the default operator to LIKE or LIKE_CONTAINS.
*
* @param {String} formType any of the FILTER_TYPES
* @param {String} operator the default operator to be used. Use enum value from scopes.svyToolbarFilter.OPERATOR
*
* @example <pre>
* // change default operator for TEXT token filters.
* scopes.svyToolbarFilter.setPopupDefaultOperator(scopes.svyToolbarFilter.FILTER_TYPES.TOKEN, scopes.svyPopupFilter.OPERATOR.LIKE);
* </pre>
*
* @properties={typeid:24,uuid:"C1D86EEE-BC55-473B-A6E7-D963E3B9866E"}
*/
function setPopupDefaultOperator(formType, operator) {
popupRendererForms.setDefaultOperator(formType, operator);
}
/**
* @constructor
* @private
* @properties={typeid:24,uuid:"37935D63-8170-4771-AB8E-B448458A08E5"}
* @AllowToRunInFind
*/
function initPopupRendererForms() {
PopupRendererForms.prototype = Object.create(PopupRendererForms.prototype);
PopupRendererForms.prototype.constructor = PopupRendererForms;
/**
* Returns the renderer form for the given formType
* @param {String} formType any of the FILTER_TYPES
* @return {RuntimeForm<AbstractPopupFilter>|RuntimeForm<AbstractLookup>}
* @public
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.getRendererForm = function(formType) {
/** @type {{template:RuntimeForm<AbstractPopupFilter>|RuntimeForm<AbstractLookup>}} */
var result = this[formType];
return result.template;
}
/**
* Sets the renderer form for the given formType
* @param {String} formType any of the FILTER_TYPES
* @param {RuntimeForm<AbstractPopupFilter>|RuntimeForm<AbstractLookup>} form the form to set
* @return {PopupRendererForms}
* @public
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.setRendererForm = function(formType, form) {
this[formType].template = form;
return this;
}
/**
* Returns the default operator for the given formType
* @param {String} formType any of the FILTER_TYPES
* @return {String}
* @public
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.getDefaultOperator = function(formType) {
/** @type {{template:RuntimeForm<AbstractPopupFilter>|RuntimeForm<AbstractLookup>, operator:String=}} */
var result = this[formType];
return result.operator;
}
/**
* Sets the default operator for the given formType
* @param {String} formType any of the FILTER_TYPES
* @param {String} operator the operator to set
* @return {PopupRendererForms}
* @public
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.setDefaultOperator = function(formType, operator) {
// check if operator is allowed
var allowedOperators = [];
var OPERATOR = scopes.svyPopupFilter.OPERATOR;
switch (formType) {
case FILTER_TYPES.TOKEN:
allowedOperators = [OPERATOR.IS_IN, OPERATOR.LIKE, OPERATOR.LIKE_CONTAINS];
break;
case FILTER_TYPES.SELECT:
allowedOperators = [OPERATOR.IS_IN];
break;
case FILTER_TYPES.NUMBER:
allowedOperators = [OPERATOR.BETWEEN, OPERATOR.GREATER_EQUAL, OPERATOR.GREATER_THEN, OPERATOR.SMALLER_EQUAL, OPERATOR.SMALLER_THEN, OPERATOR.EQUALS];
break;
case FILTER_TYPES.DATE:
allowedOperators = [OPERATOR.BETWEEN, OPERATOR.GREATER_EQUAL, OPERATOR.SMALLER_EQUAL, OPERATOR.EQUALS];
break;
default:
break;
}
if (allowedOperators.indexOf(operator) == -1) {
var allowed = [];
for (var op in OPERATOR) {
if (allowedOperators.indexOf(OPERATOR[op]) > -1) {
allowed.push(op);
}
}
throw "The given operator is not allowed for the given form type. Allowed operators for such formType are: " + allowed.join(", ");
}
this[formType].operator = operator;
return this;
}
/**
* @return {RuntimeForm<AbstractPopupFilter>}
* @protected
* @deprecated use getRendererForm(FILTER_TYPES.DATE) instead
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.getDateUIFormRendered = function() {
/** @type {RuntimeForm<AbstractPopupFilter>} */
var result = this.getRendererForm(FILTER_TYPES.DATE);
return result;
}
/**
* @param {RuntimeForm<AbstractPopupFilter>} form
* @protected
* @deprecated use setRendererForm(FILTER_TYPES.DATE, form) instead
* @return {PopupRendererForms}
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.setDateUIFormRendered = function(form) {
return this.setRendererForm(FILTER_TYPES.DATE, form);
}
/**
* @return {RuntimeForm<AbstractPopupFilter>}
* @protected
* @deprecated use getRendererForm(FILTER_TYPES.NUMBER) instead
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.getNumberUIFormRendered = function() {
/** @type {RuntimeForm<AbstractPopupFilter>} */
var result = this.getRendererForm(FILTER_TYPES.NUMBER);
return result;
}
/**
*
* @param {RuntimeForm<AbstractPopupFilter>} form
* @protected
* @deprecated use setRendererForm(FILTER_TYPES.DATE, form) instead
* @return {PopupRendererForms}
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.setNumberUIFormRendered = function(form) {
return this.setRendererForm(FILTER_TYPES.NUMBER, form);
}
/**
* @return {RuntimeForm<AbstractPopupFilter>}
* @protected
* @deprecated use getRendererForm(FILTER_TYPES.TOKEN) instead
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.getTokenUIFormRendered = function() {
/** @type {RuntimeForm<AbstractPopupFilter>} */
var result = this.getRendererForm(FILTER_TYPES.TOKEN);
return result;
}
/**
* @param {RuntimeForm<AbstractPopupFilter>} form
* @protected
* @deprecated use setRendererForm(FILTER_TYPES.TOKEN, form) instead
* @return {PopupRendererForms}
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.setTokenUIFormRendered = function(form) {
return this.setRendererForm(FILTER_TYPES.TOKEN, form);
}
/**
* @return {RuntimeForm<AbstractLookup>}
* @protected
* @deprecated use getRendererForm(FILTER_TYPES.SELECT) instead
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.getSelectUIFormRendered = function() {
/** @type {RuntimeForm<AbstractLookup>} */
var result = this.getRendererForm(FILTER_TYPES.SELECT);
return result;
}
/**
* @param {RuntimeForm<AbstractLookup>} form
* @protected
* @deprecated use setRendererForm(FILTER_TYPES.TOKEN, form) instead
* @return {PopupRendererForms}
* @this {PopupRendererForms}
* */
PopupRendererForms.prototype.setSelectUIFormRendered = function(form) {
return this.setRendererForm(FILTER_TYPES.SELECT, form);
}
}
/**
* @param {RuntimeComponent} uiComponent
* @param {RuntimeWebComponent<aggrid-groupingtable>} tableComponent
*
* @private
* @constructor
* @this {AbstractToolbarFilterUX}
* @properties={typeid:24,uuid:"D21B3F79-9C77-4006-8A82-95AA24DC56AA"}
* @AllowToRunInFind
*/
function AbstractToolbarFilterUX(uiComponent, tableComponent) {
/**
* @protected
* @type {RuntimeComponent}
*/
this.element = uiComponent;
/**
* @protected
* @type {String}
*/
this.elementName = uiComponent.getName();
/**
* @protected
* @type {String}
*/
this.formName = uiComponent.getFormName();
/**
* @protected
* @type {SvyGridFilters}
*/
this.svyGridFilters = new SvyGridFilters(tableComponent);
/**
* @protected
* @type {String}
*/
this.onFilterCreate = null;
/**
* @protected
* @type {String}
*/
this.onFilterApplyEvent = null;
/**
* @protected
* @type {String}
*/
this.onFilterAddedEvent = null;
/**
* @protected
* @type {String}
*/
this.onFilterRemovedEvent = null;
// TODO allow the form to implement such funcitonalities
// update grid filter
// get filter tag/entry/index..
// on click (show IT)
// create filter
}
/**
* Filter Toolbar implementation using the listcomponent from the custom-rendered-components package.
* This implementation requires a "List Component" element and an "Data-Grid" element.
* You should create a toolbar filter instance at the onLoad of your form and assign it to a form variable.
* The "List Component" must have it's 'foundset' property set to '-none-'.
* Make sure to re-direct the onClick event of the "List Component" to the toolbar.onClick(entry, index, dataTarget, event);
*
*
* @constructor
* @param {RuntimeWebComponent<customrenderedcomponents-listcomponent>} listComponent
* @param {RuntimeWebComponent<aggrid-groupingtable>} table
*
* @deprecated use ListComponentFilterRenderer instead
*
* @extends {AbstractToolbarFilterUX}
* @this {ListComponentFilterRender}
* @private
* @example <pre>
* //keep track of toolbarFilter object in a form variable
* var toolbarFilter;
*
* //init the toolbarFilter at the onLoad.
* function onLoad(event) {
* toolbarFilter = new scopes.svyToolbarFilter.ListComponentFilterRender(elements.filterToolbar, elements.table)
* }
*
* //propagate the onClick event of the "List Component" to the toolbar filter.
* function onClick(entry, index, dataTarget, event) {
* toolbarFilter.onClick(entry,index,dataTarget,event);
* }
*
* //optionally set a searchText for a cross-field search to further filter the result set
* function search() {
* toolbarFilter.setSearchText(searchText);
* toolbarFilter.search();
* }
* </pre>
*
* @properties={typeid:24,uuid:"3DA99E05-2496-479B-BAEC-761249725BA3"}
* @SuppressWarnings(wrongparameters)
*/
function ListComponentFilterRender(listComponent, table) {
return new ListComponentFilterRenderer(listComponent, table);
}
/**
* Filter Toolbar implementation using the custom list from the custom-rendered-components package.
* This implementation requires a "List Component" element and an "Data-Grid" element.
* You should create a toolbar filter instance at the onLoad of your form and assign it to a form variable.
* Make sure to re-direct the onClick event of the "List Component" to the toolbar.onClick(entry, index, dataTarget, event);
*
* @constructor
*
* @param {RuntimeWebComponent<customrenderedcomponents-customlist>|RuntimeWebComponent<customrenderedcomponents-customlist_abs>} listComponent
* @param {RuntimeWebComponent<aggrid-groupingtable>|RuntimeWebComponent<aggrid-groupingtable_abs>} table
*
* @extends {AbstractToolbarFilterUX}
* @this {ListComponentFilterRenderer}
* @protected
* @example <pre>
* //keep track of toolbarFilter object in a form variable
* var toolbarFilter;
*
* //init the toolbarFilter at the onLoad.
* function onLoad(event) {
* toolbarFilter = new scopes.svyToolbarFilter.ListComponentFilterRenderer(elements.filterToolbar, elements.table)
* }
*
* //propagate the onClick event of the "List Component" to the toolbar filter.
* function onClick(entry, index, dataTarget, event) {
* toolbarFilter.onClick(entry,index,dataTarget,event);
* }
*
* //optionally set a searchText for a cross-field search to further filter the result set
* function search() {
* toolbarFilter.setSearchText(searchText);
* toolbarFilter.search();
* }
* </pre>
*
* @properties={typeid:24,uuid:"8E1C5902-993A-4F97-98D1-676643FE105B"}
*/
function ListComponentFilterRenderer(listComponent, table) {
if (!listComponent) {
throw 'listComponent element is required';
}
if (!table) {
throw 'table element is required';
}
if (listComponent.getElementType() != "customrenderedcomponents-listcomponent" && listComponent.getElementType() != "customrenderedcomponents-customlist") {
throw "The given listComponent element should be an element of type customrenderedcomponents-customlist; check the 'Custom List' from the Custom Rendered Components package";
}
if (table.getElementType() != "aggrid-groupingtable") {
throw "The given table element should be an element of type aggrid-groupingtable; check the 'Data Grid' from the NG Grids package";
}
AbstractToolbarFilterUX.call(this, listComponent, table);
/**
* @protected
* @type {RuntimeWebComponent<customrenderedcomponents-customlist>|RuntimeWebComponent<customrenderedcomponents-customlist_abs>}
*/
this.element = listComponent;
/**
* @protected
* @type {String}
*/
this.elementName = listComponent.getName();
/**
* @protected
* @type {String}
*/
this.formName = listComponent.getFormName();
/**
* @protected
* @type {SvyGridFilters}
*/
this.svyGridFilters = new SvyGridFilters(table);
//TODO: remove when old list component has finally disappeared
if (listComponent.getElementType() == "customrenderedcomponents-listcomponent") {
listComponent['entryRendererFunc'] = this.getRenderTemplate();
} else {
listComponent.entryRendererFunction = this.getRenderTemplate();
}
listComponent.addStyleClass("svy-toolbar-filter")
listComponent.clear();
}
/**
* @private
* @param {RuntimeWebComponent<aggrid-groupingtable>|RuntimeWebComponent<aggrid-groupingtable_abs>} table
* @constructor
* @properties={typeid:24,uuid:"A6E91332-3686-48ED-9D89-5B07B0925132"}
* @AllowToRunInFind
*/
function SvyGridFilters(table) {
/** @type {SvyGridFilters} */
var thisInstance = this;
/**
* @public
* @return {RuntimeWebComponent<aggrid-groupingtable>|RuntimeWebComponent<aggrid-groupingtable_abs>}
*
* @this {SvyGridFilters}
*/
this.getTable = function() {
return table;
}
/**
* @type {Boolean}
*/
this.autoApply = true;
/**
* @protected
* @type {Object}
*/
this.toolbarFilters = new Object();
/**
* @protected
* @type {String}
*/
this.tableName = table.getName();
/**
* @protected
* @type {String}
*/
this.formName = table.getFormName();
/**
* @protected
* @type {String}
*/
this.searchText = null;
/**
* @protected
* @type {scopes.svySearch.SimpleSearch}
*/
this.simpleSearch = thisInstance.getDefaultSearch();
/**
* @protected
* @type {function}
*/
this.onSearchCommand = null;
}
/**
* @private
* @param {Array<scopes.svyPopupFilter.AbstractPopupFilter>} filters
* @param {JSFoundSet} foundset
*
* @return {QBSelect}
*
* @properties={typeid:24,uuid:"5B04853F-1A4F-4752-83E9-B332D697F935"}
*/
function getFilterQuery(filters, foundset) {
var isFilterSet = false;
var query = databaseManager.createSelect(foundset.getDataSource());
for (var i = 0; i < filters.length; i++) {
var filter = filters[i];
var dp = filter.getDataProvider();
if (!dp) {
throw "dataprovider unknown";
}
var op = filter.getOperator();
var values = filter.getValues();
var useNot = false;
var useIgnoreCase = true; // default to case -insensitive
// Clean up values from empty values
var qValues = values.filter(function(qv) {
if (qv === undefined || qv === null || qv === '') {
return false;
} else {
return true;
}
});
//Dont use lower on date
if(qValues.length && (qValues[0] instanceof Date || qValues[0] instanceof Number)) {
useIgnoreCase = false;
}
if (useIgnoreCase != false) {
// Clean up values from empty values
qValues = qValues.map(function(qv) {
if (qv instanceof String) {
return qv.toLowerCase();
} else {
return qv;
}
});
}
// skip filter if no values
if (!qValues || !qValues.length) {
continue;
}
var value;
var OPERATOR = scopes.svyPopupFilter.OPERATOR;
switch (op) {
case OPERATOR.EQUALS:
if (qValues[0] && qValues[0] instanceof Date) {
op = "between";
/** @type {String} */
var qDateValue = qValues[0];
value = [scopes.svyDateUtils.toStartOfDay(new Date(qDateValue)), scopes.svyDateUtils.toEndOfDay(new Date(qDateValue))];
} else {
op = "eq";
value = qValues[0];
}
break;
case OPERATOR.GREATER_EQUAL:
op = "ge";
value = qValues[0];
break;
case OPERATOR.GREATER_THEN:
op = "gt";
value = qValues[0];
break;
case OPERATOR.SMALLER_EQUAL:
op = "le";
value = qValues[0];
break;
case OPERATOR.SMALLER_THEN:
op = "lt";
value = qValues[0];
break;
case OPERATOR.BETWEEN:
// TODO should this be handled by the popup form instead !?
if (qValues.length == 2) {
op = "between";
value = qValues;
} else if (qValues.length == 1) {
if (values[0] === undefined || values[0] === null || values[0] === '') {
op = "lt";
} else {
op = "gt";
}
value = qValues[0];
} else {
throw "this should not happen";
}
break;
case OPERATOR.IS_IN:
op = "isin";
value = qValues;
break;
case OPERATOR.LIKE:
op = "like";
value = qValues;
// add wildcard
if (value instanceof Array) {
value = value.map(function(qv) {
if (qv instanceof String) {
return qv + "%";
} else {
return qv;
}
});
} else if (value instanceof String) {
value = value + "%"
}
break;
case OPERATOR.LIKE_CONTAINS:
op = "like";
value = qValues;
// add wildcard
if (value instanceof Array) {
value = value.map(function(qv) {
if (qv instanceof String) {
return "%" + qv + "%";
} else {
return qv;
}
});
} else if (value instanceof String) {
value = "%"+ value + "%"
}
break;
default:
break;
}
/** @type {QBSelect} */
var querySource = null;
var aDP = dp.split('.');
for (var j = 0; j < aDP.length - 1; j++) {
querySource = querySource == null ? query.joins[aDP[j]] : querySource.joins[aDP[j]];
}
/** @type {QBColumn} */
var whereClause = querySource == null ? query.columns[aDP[aDP.length - 1]] : querySource.columns[aDP[aDP.length - 1]];
// do not lower case Dates.
if (value instanceof Date) {
useIgnoreCase = false;
}
if (useIgnoreCase != false) {
whereClause = whereClause["lower"];
if (value instanceof String) {
/** @type {String} */
var valueString = value;
value = valueString.toLowerCase();
} else if (value instanceof Array) {
// Clean up values from empty values
/** @type {Array} */
var valueArray = value;
value = valueArray.map(function(qv) {
if (qv instanceof String) {
return qv.toLowerCase();
} else {
return qv;
}
});
}
}
if (useNot) {
whereClause = whereClause["not"];
}
switch (op) {
case "between":
whereClause = whereClause[op](value[0], value[1]);
break;
case "like":
if (value instanceof Array) {
var or = query.or;
for (var v = 0; v < value.length; v++) {
or.add(whereClause[op](value[v]));
}
whereClause = or;
break;
}
whereClause = whereClause[op](value);
break;
default:
whereClause = whereClause[op](value);
break;
}
//whereClause = op == "between" ? whereClause[op](value[0], value[1]) : whereClause[op](value);
if (!isFilterSet) isFilterSet = true;
/** @type {QBCondition} */
var where = whereClause;
query.where.add(where);
}
return query;
}
/**
* @public
* @param {Array<scopes.svyPopupFilter.AbstractPopupFilter>} filters
* @param {JSFoundSet} foundset
*
* @return {QBSelect}
*
* @deprecated use AbstractToolbarFilterUX.applyFilters() instead
*
* @properties={typeid:24,uuid:"DE3A02D8-BD4A-42B7-9870-6E5BC70D9D2A"}
*/
function applyFilters(filters, foundset) {
// remove previous filter
foundset.removeFoundSetFilterParam(TOOLBAR_FILTER_NAME);
// get the filter query
var filterQuery;
if (filters.length) {
filterQuery = getFilterQuery(filters,foundset);
// apply the query as filter
foundset.addFoundSetFilterParam(filterQuery, TOOLBAR_FILTER_NAME);
} else {
// refresh foundset since filters have been removed
foundset.loadRecords();
filterQuery = foundset.getQuery();
}
return filterQuery;
}
/**
* @public
* @param {JSFoundSet} foundset
*
* @deprecated
*
* @properties={typeid:24,uuid:"9078E2C7-E065-4E71-B4AB-D0D6F9F896E8"}
*/
function clearFilters(foundset) {
if (foundset.removeFoundSetFilterParam(TOOLBAR_FILTER_NAME)) {
return foundset.loadRecords();
}
return false;
}
/**
* Creates a filter toolbar implementation using the custom list from the custom-rendered-components package.<br><br>
*
* This implementation expects an NG "Data Grid" table component and a "Custom List" component.<br><br>
*
* The filters offered from this implementation are generated from the table provided as follows:
*
* <ul><li>any column with its <code>filterType</code> property set to TEXT will be offered as a token popup, allowing the user to enter any number of Strings to match</li>
* <li>any column with its <code>filterType</code> property set to TEXT and the <code>valuelist</code> will be offered as a lookup where the user can search for and select any number of values</li>
* <li>any column with its <code>filterType</code> property set to NUMBER will be offered as a number filter with a number of operators</li>
* <li>any column with its <code>filterType</code> property set to DATE will be offered as a date filter with a number of operators</li></ul>
*
* You should create a toolbar filter instance at the onLoad of your form and assign it to a form variable.
*
* Make sure to re-direct the onClick event of the "List Component" to the toolbar.onClick(entry, index, dataTarget, event);
*
* @param {RuntimeWebComponent<customrenderedcomponents-customlist>|RuntimeWebComponent<customrenderedcomponents-customlist_abs>} listComponent
* @param {RuntimeWebComponent<aggrid-groupingtable>|RuntimeWebComponent<aggrid-groupingtable_abs>} table
*
* @extends {AbstractToolbarFilterUX}
* @this {ListComponentFilterRenderer}
* @public
* @example <pre>
* //keep track of toolbarFilter object in a form variable
* var toolbarFilter;
*
* //init the toolbarFilter at the onLoad.
* function onLoad(event) {
* toolbarFilter = scopes.svyToolbarFilter.createFilterToolbar(elements.filterToolbar, elements.table)
* }
*
* //propagate the onClick event of the "Custom List" component to the toolbar filter.
* function onClick(entry, index, dataTarget, event) {
* toolbarFilter.onClick(entry, index, dataTarget, event);
* }
*
* //optionally set a searchText for a cross-field search to further filter the result set
* function search() {
* toolbarFilter.search(searchText);
* }
* </pre>
*
* @properties={typeid:24,uuid:"4BB94EC8-F877-445D-93E1-541F0A58D664"}
*/
function createFilterToolbar(listComponent, table) {
return new ListComponentFilterRenderer(listComponent, table);
}
/**
* @private
* @param headerTitle
* @return {String}
*
* @properties={typeid:24,uuid:"CACDDD32-E443-413B-8229-578929CD7F20"}
*/
function getI18nText(headerTitle) {
/** @type {String} */
var text = headerTitle;
if (text && text.indexOf("i18n:") == 0) {
text = i18n.getI18NMessage(text.replace("i18n:",""))
}
return text;
}
/**
* @constructor
* @private
* @properties={typeid:24,uuid:"924B1AFF-94F1-4808-ADDC-BB1F10516E5C"}
* @AllowToRunInFind
*/
function initSvyGridFilters() {
SvyGridFilters.prototype = Object.create(SvyGridFilters.prototype);
SvyGridFilters.prototype.constructor = SvyGridFilters;
/**
* @public
* @param {Boolean} forceApply
* @return {QBSelect}
*
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.applyFilters = function(forceApply) {
var foundset = this.getFoundSet();
var filters = this.getActiveFilters();
// remove previous filter
if ((this.autoApply === true || forceApply === true) && !this.onSearchCommand) {
foundset.removeFoundSetFilterParam(TOOLBAR_FILTER_NAME);
}
// get the filter query
var filterQuery;
if (filters.length) {
filterQuery = getFilterQuery(filters, foundset);
// apply the query as filter
// DO NOTHING if onSearchCommand is set
if ((this.autoApply === true || forceApply === true) && !this.onSearchCommand) {
foundset.addFoundSetFilterParam(filterQuery, TOOLBAR_FILTER_NAME);
}
} else {
// refresh foundset since filters have been removed
// if autoApply reload records and return the query
if ((forceApply === true || this.autoApply === true) && !this.searchText) {
foundset.loadRecords();
return foundset.getQuery();
}
filterQuery = foundset.getQuery();
}
// DO NOTHING if onSearchCommand is set
//if ((forceApply === true || this.autoApply === true) && !this.searchText) {
if ((forceApply === true || this.autoApply === true) && !this.onSearchCommand && !this.searchText) {
foundset.loadRecords();
}
return filterQuery;
}
/**
* @public
* @return {SvyGridFilters}
*
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.setSearchText = function(searchText) {
this.searchText = searchText;
return this;
}
/**
* @public
* @param {function(QBSelect, JSFoundSet)} callback
* @return {SvyGridFilters}
*
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.setOnSearchCommand = function(callback) {
this.onSearchCommand = callback;
return this;
}
/**
* @public
* @return {String}
*
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.getSearchText = function() {
return this.searchText;
}
/**
* @public
* @return {scopes.svySearch.SimpleSearch}
*
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.getSimpleSearch = function() {
return this.simpleSearch;
}
/**
* @param {CustomType<aggrid-groupingtable.column>} column
* @public
* @return {scopes.svySearch.SearchProvider}
*
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.getSearchProvider = function(column) {
return this.simpleSearch.getSearchProvider(column.dataprovider);
}
/**
* @public
* @return {JSFoundSet}
*
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.getFoundSet = function() {
return this.getTable().myFoundset.foundset;
}
/**
* @public
* @return {Array<{text:String,
* dataprovider:String,
* id:String=,
* columnIndex:Number
* }>}
*
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.getFilters = function() {
var column;
var filter;
var filters = [];
var table = this.getTable();
var columns = table.columns;
var useNonVisibleColumns = getConfigUseNonVisibleColumns();
if (useNonVisibleColumns) {
// scan all columns
for (var index = 0; index < columns.length; index++) {
column = columns[index];
if (column.filterType && column.filterType != 'NONE') {
filter = new Object();
filter.text = getI18nText(column.headerTitle);
filter.dataprovider = column.dataprovider;
filter.id = column.id;
filter.columnIndex = index;
filters.push(filter);
}
}
} else {
// scan only visible columns. Access the column state
var jsonState = table.getColumnState();
if (jsonState) {
/** @type {{columnState:Array}} */
var state = JSON.parse(jsonState);
/** @type {Array} */
var colsState = state.columnState ? state.columnState : [];
for (var j = 0; j < colsState.length; j++) {
if (!colsState[j].hide) { // skip column if hidden
// NEW API
var colIndex = table.getColumnIndex(colsState[j].colId);
column = columns[colIndex];
if (column && column.filterType && column.filterType != 'NONE') {
//visibleColumns.push(col.dataprovider);
filter = new Object();
filter.text = getI18nText(column.headerTitle);
filter.dataprovider = column.dataprovider;
filter.id = column.id;
filter.columnIndex = colIndex;
filters.push(filter);
}
}
}
} else {
for (var i = 0; i < columns.length; i++) {
column = columns[i];
if (column.filterType && column.filterType != 'NONE' && column.visible) {
filter = new Object();
filter.text = column.headerTitle;
filter.text = getI18nText(column.headerTitle);
filter.dataprovider = column.dataprovider;
filter.id = column.id;
filter.columnIndex = i;
filters.push(filter);
}
}
}
}
return filters;
}
/**
* @public
* @return {Array<scopes.svyPopupFilter.AbstractPopupFilter>}
*
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.getActiveFilters = function() {
/** @type {Array<scopes.svyPopupFilter.AbstractPopupFilter>} */
var activeFilters = [];
for (var dp in this.toolbarFilters) {
/** @type {scopes.svyPopupFilter.AbstractPopupFilter} */
var filter = this.toolbarFilters[dp];
if (filter.getValues() && filter.getValues().length) {
activeFilters.push(this.toolbarFilters[dp]);
}
}
return activeFilters;
}
/**
* @param {CustomType<aggrid-groupingtable.column>} column
* @public
* @return {Boolean}
*
* @this {SvyGridFilters}
* */
SvyGridFilters.prototype.hasActiveFilter = function(column) {
return this.toolbarFilters[column.dataprovider] ? true : false;
}
/**
* @public
* @param {CustomType<aggrid-groupingtable.column>} column
* @param {scopes.svyPopupFilter.AbstractPopupFilter} filter
*
* @properties={typeid:24,uuid:"7097146A-EDA1-4C7A-9A9F-58FAEC3D883B"}
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.addGridFilter = function(column, filter) {
if (column.dataprovider) {
this.toolbarFilters[column.dataprovider] = filter;
}
}
/**
* @public
* @param {CustomType<aggrid-groupingtable.column>} column
* @return {scopes.svyPopupFilter.AbstractPopupFilter}
*
* @properties={typeid:24,uuid:"7097146A-EDA1-4C7A-9A9F-58FAEC3D883B"}
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.getGridFilter = function(column) {
/** @type {scopes.svyPopupFilter.AbstractPopupFilter} */
var filter = this.toolbarFilters[column.dataprovider];
return filter;
}
/**
* @public
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @properties={typeid:24,uuid:"7097146A-EDA1-4C7A-9A9F-58FAEC3D883B"}
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.removeGridFilter = function(column) {
var toolbarFilter = this.toolbarFilters[column.dataprovider];
var hasValues = toolbarFilter && toolbarFilter.getValues().length > 0 ? true : false;
// remove the filter from cache
delete this.toolbarFilters[column.dataprovider];
if (hasValues) {
this.search()
}
}
/**
* @public
*
* @properties={typeid:24,uuid:"7097146A-EDA1-4C7A-9A9F-58FAEC3D883B"}
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.clearGridFilters = function() {
// remove the filter from cache
this.toolbarFilters = new Object();
this.search();
}
/**
* @public
* @return {Array<{
id: String,
dataprovider: String,
operator: String,
params: Object,
text: String,
values: Array}>}
*
* @properties={typeid:24,uuid:"7097146A-EDA1-4C7A-9A9F-58FAEC3D883B"}
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.getGridFiltersState = function() {
var jsonState = [];
for (var dp in this.toolbarFilters) {
var filter = this.toolbarFilters[dp];
var filterState = filter.getState();
delete filterState.params;
jsonState.push(filterState)
}
return jsonState;
}
/**
* @deprecated this function doesnt't work and is not used
* @protected
* @param {Array<{
id: String,
dataprovider: String,
operator: String,
params: Object,
text: String,
values: Array}>} jsonState
*
* @properties={typeid:24,uuid:"7097146A-EDA1-4C7A-9A9F-58FAEC3D883B"}
*
* @return {SvyGridFilters}
* @this {SvyGridFilters}
*/
SvyGridFilters.prototype.restoreGridFiltersState = function(jsonState) {
// clear previous filters
this.clearGridFilters();
// restore new filters
for (var i = 0; i < jsonState.length; i++) {
var obj = jsonState[i];
var column = this.getColumn(obj.dataprovider);
if (column) {
// FIXME check filter type
var filter = new scopes.svyPopupFilter.SvyTokenFilter();
filter.restoreState(obj);
this.addGridFilter(column,filter);
}
}
return this;
}
/**
* @public
* @param {String} dataprovider
* @return {CustomType<aggrid-groupingtable.column>}
*
* @this {SvyGridFilters}
* */
SvyGridFilters.prototype.getColumn = function(dataprovider) {
var columns = this.getTable().columns;
for (var i = 0; i < columns.length; i++) {
var column = columns[i];
// TODO can i rely on dataprovider only !?
if (dataprovider == column.dataprovider) {
return column;
}
}
return null;
}
/**
* @public
* @return {QBSelect}
*
*
* @this {SvyGridFilters}
* */
SvyGridFilters.prototype.getQuery = function() {
//apply foundset filters and force when the search text has been changed
var filterQuery = this.applyFilters(this.searchText !== this.simpleSearch.getSearchText() ? true : false);
var query;
//quick search?
if (this.searchText !== this.simpleSearch.getSearchText()) {
this.simpleSearch.setSearchText(this.searchText);
}
if (this.searchText) {
// filters need to be applied
if (this.onSearchCommand && this.getActiveFilters().length) {
// include filters in query
var foundset = databaseManager.getFoundSet(this.simpleSearch.getDataSource());
var searchQuery = this.simpleSearch.getQuery();
// add temp filters to make sure filterQuery is merged with searchQuery
var toolbarFilterName = TOOLBAR_FILTER_NAME + "-temp";
var searchFilterName = TOOLBAR_FILTER_NAME + "-temp-search";
foundset.addFoundSetFilterParam(filterQuery, toolbarFilterName);
foundset.addFoundSetFilterParam(searchQuery ,searchFilterName);
foundset.loadRecords();
query = foundset.getQuery();
// remove filters from query
foundset.removeFoundSetFilterParam(toolbarFilterName);
foundset.removeFoundSetFilterParam(searchFilterName);
foundset.loadRecords();
} else {
query = this.simpleSearch.getQuery();
}
} else {
query = filterQuery;
}
return query;
}
/**
* @public
* @return {scopes.svySearch.SimpleSearch}
*
* @this {SvyGridFilters}
* */
SvyGridFilters.prototype.getDefaultSearch = function() {
if (!this.getTable()) {
return null;
}
var columns = this.getTable().columns;
var tableFoundset = this.getTable().myFoundset.foundset;
var tableDataSource;
var jsForm = solutionModel.getForm(this.getTable().getFormName());
var jsTable = jsForm.findWebComponent(this.getTable().getName());
var foundsetSelector = jsTable.getJSONProperty("myFoundset").foundsetSelector;
try {
if (foundsetSelector) {
if (databaseManager.getTable(foundsetSelector)) {
tableDataSource = foundsetSelector;
} else if (foundsetSelector.split('.').length > 1) {
tableDataSource = scopes.svyDataUtils.getRelationForeignDataSource(foundsetSelector)
} else if (solutionModel.getRelation(foundsetSelector)) {
var jsRel = solutionModel.getRelation(foundsetSelector);
tableDataSource = jsRel.foreignDataSource;
}
}
} catch (e) {
application.output(e, LOGGINGLEVEL.ERROR);
}
if (tableDataSource) {
// do nothing
} else if (tableFoundset) {
tableDataSource = tableFoundset.getDataSource();
} else {
var form = forms[this.formName];
tableDataSource = form ? form.foundset.getDataSource() : null;
}
if (!tableDataSource) {
return null;
}
// create a simple search
var simpleSearch = scopes.svySearch.createSimpleSearch(tableDataSource);
simpleSearch.setSearchText(this.searchText);
simpleSearch.setDateFormat("dd-MM-yyyy");
for (var i = 0; tableDataSource && columns && i < columns.length; i++) {
var column = columns[i];
if (column.dataprovider) {
// default behavior search only on visible columns.
// TODO should use the column.visible property or the columnState visible ?
if (!column.visible) {
continue;
}
// TODO use state of columns to determine non visible columns
// check the state of non visible columns stored by the user
if (false && !getConfigUseNonVisibleColumns()) {
// TODO non visible columns should be updated at every search ?
// scan only visible columns. Access the column state
var jsonState = this.getTable().getColumnState();
if (jsonState) {
/** @type {{columnState:Array}} */
var state = JSON.parse(jsonState);
/** @type {Array} */
var colsState = state.columnState ? state.columnState : [];
for (var j = 0; j < colsState.length; j++) {
if (colsState[j].hide) { // skip column if hidden
continue;
}
}
}
}
// Check if column exists
var relationName = scopes.svyDataUtils.getDataProviderRelationName(column.dataprovider)
var dataSource = relationName ? scopes.svyDataUtils.getRelationForeignDataSource(relationName) : tableDataSource;
var table = databaseManager.getTable(dataSource);
var col = table.getColumn(scopes.svyDataUtils.getUnrelatedDataProviderID(column.dataprovider));
if (col) {
var vlItems = null;
// skip media fields
if (col.getType() === JSColumn.MEDIA) {
continue;
}
// check if valuelist substitions can be applied
if (column.valuelist) {
vlItems = application.getValueListItems(column.valuelist);
if (!vlItems.getMaxRowIndex()) {
application.output("skip search on column with valuelist " + column.valuelist);
continue;
}
}
// create the search provider
// TODO shall i remove all white spaces !?
var provider = simpleSearch.addSearchProvider(column.dataprovider);
// set the provider alias
var alias = column.headerTitle ? getI18nText(column.headerTitle) : column.dataprovider;
provider.setAlias(alias);
// if is a date use explicit search
if (col.getType() === JSColumn.DATETIME) {
provider.setImpliedSearch(false);
}
// add valuelist substitutions
for (var index = 1; vlItems && index <= vlItems.getMaxRowIndex(); index++) {
var vlItem = vlItems.getRowAsArray(index);
provider.addSubstitution(vlItem[0], vlItem[1])
}
}
}
}
return simpleSearch;
}
/**
* @public
*
* @this {SvyGridFilters}
* */
SvyGridFilters.prototype.search = function() {
var searchTextChanged = this.searchText !== this.simpleSearch.getSearchText() ? true : false;
var foundset = this.getFoundSet();
// quick search
var searchQuery = this.getQuery();
if (this.onSearchCommand) {
//fire onSearchCommand
this.onSearchCommand.call(this, searchQuery, foundset);
} else if (searchTextChanged || this.searchText) {
//apply search if relevant
foundset.loadRecords(searchQuery);
}
}
}
/**
* @constructor
* @private
* @properties={typeid:24,uuid:"E8CB92CC-FCCF-4A46-B180-9CF800899C2E"}
* @AllowToRunInFind
*/
function initAbstractToolbarFilterUX() {
AbstractToolbarFilterUX.prototype = Object.create(AbstractToolbarFilterUX.prototype);
AbstractToolbarFilterUX.prototype.constructor = AbstractToolbarFilterUX;
/**
* @protected
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.applyFilters = function() {
this.svyGridFilters.applyFilters(true);
this.svyGridFilters.getFoundSet().loadAllRecords();
}
/**
* @public
* Sets whether filters are automatically applied each time they were changed (defaults to true)
* When set to false, filters can be applied via applyFilters() of this ToolbarFilter
* @param {Boolean} autoApply
* @return {AbstractToolbarFilterUX}
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.setAutoApplyFilters = function(autoApply) {
this.svyGridFilters.autoApply = autoApply;
return this;
}
/**
* Returns the element used to display the filters
* @public
* @return {RuntimeComponent}
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.getElement = function() {
return this.element;
}
/**
* Allows to provide a method that will be called when the filter for a specific column is created<br>
* That method then can create and return any filter that will then be used for this column
*
* @public
* @param {function(CustomType<aggrid-groupingtable.column>): scopes.svyPopupFilter.AbstractPopupFilter} callback function that receives an aggrid-groupingtable Column as argument and must return a scopes.svyPopupFilter.AbstractPopupFilter
* @return {AbstractToolbarFilterUX}
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.setOnFilterCreate = function(callback) {
this.onFilterCreate = scopes.svySystem.convertServoyMethodToQualifiedName(callback);
return this;
}
/**
* @protected
* @param {function({values:Array, operator:String, filter:scopes.svyPopupFilter.AbstractPopupFilter})} callback
*
* @return {AbstractToolbarFilterUX}
*
* @deprecated use setOnFilterApplyCallback
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.setOnFilterApplyEvent = function(callback) {
this.onFilterApplyEvent = scopes.svySystem.convertServoyMethodToQualifiedName(callback);
return this;
}
/**
* Sets a callback method that is fired whenever the filter is applied<br>
* The callback method receives an array of values, the operator and the filter as arguments
*
* @param {function(Array, String, scopes.svyPopupFilter.AbstractPopupFilter)} callback
*
* @return {AbstractToolbarFilterUX}
*
* @public
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.setOnFilterApplyCallback = function(callback) {
this.onFilterApplyEvent = scopes.svySystem.convertServoyMethodToQualifiedName(callback);
return this;
}
/**
* Sets a callback method that is fired whenever a filter has been added
*
* @param {function()} callback
*
* @return {AbstractToolbarFilterUX}
*
* @public
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.setOnFilterAddedCallback = function(callback) {
this.onFilterAddedEvent = scopes.svySystem.convertServoyMethodToQualifiedName(callback);
return this;
}
/**
*
* @param {function()} callback
*
* @return {AbstractToolbarFilterUX}
*
* @deprecated use setOnFilterRemovedCallback
*
* @protected
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.setOnFilterRemovedEvent = function(callback) {
this.onFilterRemovedEvent = scopes.svySystem.convertServoyMethodToQualifiedName(callback);
return this;
}
/**
* Sets a callback method that is fired whenever a filter is removed
*
* @param {function()} callback
*
* @return {AbstractToolbarFilterUX}
*
* @public
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.setOnFilterRemovedCallback = function(callback) {
this.onFilterRemovedEvent = scopes.svySystem.convertServoyMethodToQualifiedName(callback);
return this;
}
/**
* Set the onSearchCommand function to override the search behavior.
* You can add custom conditions to the filter query object;
*
* @public
* @param {function(QBSelect, JSFoundSet)} callback
* @return {AbstractToolbarFilterUX}
*
* @this {AbstractToolbarFilterUX}
* @example <pre>function onSearch(query, fs) {
* // add custom conditions to the query
* query.where.add(query.columns.orderdate.not.isNull);
*
* // apply the query to the foundset
* fs.loadRecords(query);
* }
* </pre>
*
* */
AbstractToolbarFilterUX.prototype.setOnSearchCommand = function(callback) {
this.svyGridFilters.setOnSearchCommand(callback);
return this;
}
/**
* Adds a filter for the given column
*
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @return {Boolean}
*
* @public
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.addGridFilter = function(column) {
throw scopes.svyExceptions.AbstractMethodInvocationException("addGridFilter not implemented")
}
/**
* Removes the filter for the given column
*
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @return {Boolean}
*
* @public
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.removeGridFilter = function(column) {
throw scopes.svyExceptions.AbstractMethodInvocationException("removeGridFilter not implemented")
}
/**
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @return {Boolean}
*
* @protected
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.showGridFilter = function(column) {
throw scopes.svyExceptions.AbstractMethodInvocationException("showGridFilter not implemented")
}
/**
* Clears all grid filters
*
* @return {Boolean}
*
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.clearGridFilters = function() {
// this.svyGridFilters.clearGridFilters();
this._clearGridFilters()
// on filter removed event
if (this.onFilterRemovedEvent) {
scopes.svySystem.callMethod(this.onFilterRemovedEvent);
}
return true;
}
/**
* Clears all grid filters
* Internal implementation, will take care to clear the filters and update the UI
* Will not trigger the event onFilterRemovedEvent
*
* @return {Boolean}
*
* @protected
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype._clearGridFilters = function() {
throw scopes.svyExceptions.AbstractMethodInvocationException("_clearGridFilters not implemented")
}
/**
*
* Override this method in a subclass to adjust the UI to the updated values for the given dataprovider
*
* @param {String} dataprovider
* @param {Array} values
*
* @return {Boolean}
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.updateGridFilter = function(dataprovider, values) {
throw scopes.svyExceptions.AbstractMethodInvocationException("updateGridFilter not implemented")
}
/**
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @return {Boolean}
*
* @protected
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.hasActiveFilter = function(column) {
throw scopes.svyExceptions.AbstractMethodInvocationException("hasActiveFilter not implemented")
}
/**
* Returns true if the table has any column it can filter on
*
* @return {Boolean}
*
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.hasFilters = function() {
return this.svyGridFilters.getFilters().length > 0 ? true : false;
}
/**
* Returns the filters' state of the toolbar
*
* @return {Array<{
id: String,
dataprovider: String,
operator: String,
params: Object,
text: String,
values: Array}>} jsonState
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.getToolbarFiltersState = function() {
return this.svyGridFilters.getGridFiltersState();
}
/**
* Restores the filters' state
*
* @param {Array<{
id: String,
dataprovider: String,
operator: String,
params: Object,
text: String,
values: Array}>} jsonState
*
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.restoreToolbarFiltersState = function(jsonState) {
// clear previous filters
this._clearGridFilters();
// restore new filters
for (var i = 0; i < jsonState.length; i++) {
var obj = jsonState[i];
var column = this.getColumn(obj.dataprovider);
if (!column) continue; // TODO throw a warning ?
switch (column.filterType) {
case 'NUMBER':
obj.values = obj.values.map(function(value) {
return utils.stringToNumber(value);
});
break;
case 'DATE':
obj.values = obj.values.map(function(value) {
return new Date(value);
});
break;
case 'TEXT':
default:
break;
}
var values = obj.values;
// set the filter again
this.setFilterValue(column, values, obj.operator);
var filter = this.getOrCreateToolbarFilter(column);
filter.restoreState(obj);
}
// update filter UI
var element = this.getElement();
if (this.hasFilters()) {
element.addStyleClass('has-filter');
} else {
element.removeStyleClass('has-filter');
}
}
/**
* Applies all filters and returns the query for this toolbar
*
* @return {QBSelect}
*
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.getQuery = function() {
return this.svyGridFilters.getQuery();
}
/**
* Sets the search text for the simple search
*
* @return {AbstractToolbarFilterUX}
*
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.setSearchText = function(searchText) {
this.svyGridFilters.setSearchText(searchText);
return this;
}
/**
* Returns the search text for the simple search
*
* @return {String}
*
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.getSearchText = function() {
return this.svyGridFilters.getSearchText();
}
/**
* Returns the SimpleSearch
*
* @return {scopes.svySearch.SimpleSearch}
*
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.getSimpleSearch = function() {
return this.svyGridFilters.getSimpleSearch();
}
/**
* Returns the SearchProvider for the given column
*
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @return {scopes.svySearch.SearchProvider}
*
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.getSearchProvider = function(column) {
return this.svyGridFilters.getSearchProvider(column);
}
/**
* Returns the table column for the given dataprovider
*
* @param {String} dataprovider
*
* @return {CustomType<aggrid-groupingtable.column>}
*
* @protected
*
* @this {AbstractToolbarFilterUX}
* */
AbstractToolbarFilterUX.prototype.getColumn = function (dataprovider) {
return this.svyGridFilters.getColumn(dataprovider);
}
/**
* Applies all filters and executes the search
*
* @param {String} [searchText] optional searchText to search for; if not provided here, call setSearchText() to set the search criteria before performing the search
*
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.search = function(searchText) {
if (arguments.length === 1) {
this.svyGridFilters.setSearchText(searchText);
}
this.svyGridFilters.applyFilters(true);
return this.svyGridFilters.search();
}
/**
* @param {CustomType<aggrid-groupingtable.column>} column
* @param {JSEvent} event
*
* @this {AbstractToolbarFilterUX}
*
* @protected
*
* @properties={typeid:24,uuid:"06EB08B6-AA6C-4DC8-A0A7-B7CF3C140D77"}
*/
AbstractToolbarFilterUX.prototype.showPopupFilter = function (column, event) {
var filter = this.getOrCreateToolbarFilter(column);
// show the filter
var popup = filter.createPopUp(this.onFilterApply);
popup.x(event.getX());
popup.y(event.getY());
// popup.width(300);
popup.show();
}
/**
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @protected
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.getFilter = function(column) {
/** @type {scopes.svyPopupFilter.AbstractPopupFilter} */
var filter = this.svyGridFilters.getGridFilter(column);
return filter;
}
/**
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @protected
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.getOrCreateToolbarFilter = function(column) {
/** @type {scopes.svyPopupFilter.AbstractPopupFilter} */
var filter = this.getFilter(column);
if (!filter && this.onFilterCreate) {
filter = scopes.svySystem.callMethod(this.onFilterCreate, [column]);
if (filter) {
// include this as param
filter.addParam(this);
// set filter's dataprovider
filter.setDataProvider(column.dataprovider);
// persist the filter in memory
this.svyGridFilters.addGridFilter(column, filter);
}
}
if (!filter) {
var popupTemplates = getPopupRendererForms();
var filterType;
if (column.valuelist) {
filterType = FILTER_TYPES.SELECT;
// will be a lookup form
// number picker
// calendar picker
var lookup = scopes.svyLookup.createValueListLookup(column.valuelist);
/** @type {RuntimeForm<AbstractLookup>} */
var lookupForm = popupTemplates.getRendererForm(FILTER_TYPES.SELECT);
lookup.setLookupForm(lookupForm);
filter = scopes.svyPopupFilter.createSelectFilter(column.dataprovider, lookup);
} else {
// will be a free text entry
switch (column.filterType) {
case 'TEXT':
filterType = FILTER_TYPES.TOKEN;
filter = scopes.svyPopupFilter.createTokenFilter();
filter.setRendererForm(popupTemplates.getRendererForm(FILTER_TYPES.TOKEN));
break;
case 'NUMBER':
// number picker
filterType = FILTER_TYPES.NUMBER;
filter = scopes.svyPopupFilter.createNumberFilter();
filter.setRendererForm(popupTemplates.getRendererForm(FILTER_TYPES.NUMBER));
break;
case 'DATE':
// calendar picker
filterType = FILTER_TYPES.DATE;
filter = scopes.svyPopupFilter.createDateFilter();
filter.setRendererForm(popupTemplates.getRendererForm(FILTER_TYPES.DATE));
break;
default:
break;
}
}
if (filter) {
// set filter's dataprovider
filter.setDataProvider(column.dataprovider);
filter.setText(getI18nText(column.headerTitle));
// set default operator
var operator = popupTemplates.getDefaultOperator(filterType);
if (operator) {
filter.setOperator(operator);
}
// include this as param
filter.addParam(this);
// persist the filter in memory
this.svyGridFilters.addGridFilter(column, filter);
}
}
return filter;
}
/**
* Shows the filter picker popup
*
* @param {RuntimeComponent} target
*
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.showPopupFilterPicker = function(target) {
var filterPopupMenu = plugins.window.createPopupMenu();
var menuItem = filterPopupMenu.addMenuItem("title");
menuItem.enabled = false;
menuItem.text = "Add filter";
var columnFilters = this.svyGridFilters.getFilters();
for (var index = 0; index < columnFilters.length; index++) {
var columnFilter = columnFilters[index];
var check = filterPopupMenu.addCheckBox(columnFilter.dataprovider);
check.selected = this.hasActiveFilter(this.getColumn(columnFilter.dataprovider));
check.text = columnFilter.text;
check.methodArguments = [columnFilter.columnIndex, columnFilter.id, columnFilter.dataprovider]
check.setMethod(onFilterPopupMenuClicked);
}
filterPopupMenu.cssClass = "toolbar-filter-popup";
// cache the latest menu so it can be used in callback
latestToolbarFilter = this;
filterPopupMenu.show(target);
}
/**
* Sets a filter value for the given column
*
* @param {CustomType<aggrid-groupingtable.column>} column
* @param {Array} values
* @param {String} operator
*
* @public
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.setFilterValue = function(column, values, operator) {
if (!this.hasActiveFilter(column)) {
this.addGridFilter(column);
}
var filter = this.getOrCreateToolbarFilter(column);
filter.setValues(values);
filter.setOperator(operator);
this.onFilterApply(values, operator, filter, true);
}
/**
* @param {Array} values
* @param {String} operator
* @param {scopes.svyPopupFilter.AbstractPopupFilter} filter
* @param {Boolean} [forceApply] Default false.
*
* @protected
*
* @this {AbstractToolbarFilterUX}
*/
AbstractToolbarFilterUX.prototype.onFilterApply = function (values, operator, filter, forceApply) {
/** @type {AbstractToolbarFilterUX} */
var thisIntance = filter.getParams()[0];
/** @type {SvyGridFilters} */
var gridFilters = thisIntance['svyGridFilters'];
// check if values or operator have changed
var currentValues = filter.getValues();
var currentOperator = filter.getOperator();
if (!forceApply && scopes.svyJSUtils.areObjectsEqual(currentValues, values) && operator == currentOperator) {
// nothing has changed, do nothing
return;
}
// TODO to be moved somewhere else ~?
// persist the values & operator:
filter.setOperator(operator);
filter.setValues(values);
var displayValues = values ? values : [];
// resolve valuelist real values
var column = gridFilters.getColumn(filter.getDataProvider());
if (column.valuelist) {
displayValues = [];
for (var i = 0; i < values.length; i++) {
displayValues[i] = application.getValueListDisplayValue(column.valuelist, values[i]);
}
}
// format dates
displayValues = displayValues.map(function(v) {
if (v instanceof Date) {
return utils.dateFormat(v, globalFilterConfig.globalDateDisplayFormat);
} else {
return v;
}
});
// update the UI
thisIntance.updateGridFilter(filter.getDataProvider(), displayValues);
// apply the search
gridFilters.search();
// if has active filters
var element = thisIntance.getElement();
if (gridFilters.getActiveFilters().length) {
element.addStyleClass('has-active-filter');
} else {
element.removeStyleClass('has-active-filter');
}
if (thisIntance['onFilterApplyEvent']) {
/** @type {String} */
var onFilterApplyEvent = thisIntance['onFilterApplyEvent'];
scopes.svySystem.callMethod(onFilterApplyEvent, [values, operator, filter])
}
}
}
/**
* @private
* @param {Number} itemIndex
* @param {Number} parentIndex
* @param {Boolean} isSelected
* @param {String} parentText
* @param {String} menuText
* @param {Number} columnIndex the column index
* @param {String} [columnId] the id of the column
* @param {String} [columnDataprovider] dataprovider bound to the column
*
* @properties={typeid:24,uuid:"4288095A-3F08-48FD-AD10-C86B79972DA9"}
*/
function onFilterPopupMenuClicked(itemIndex, parentIndex, isSelected, parentText, menuText, columnIndex, columnId, columnDataprovider) {
var toolbarFilterUX = latestToolbarFilter;
latestToolbarFilter = null;
if (toolbarFilterUX) {
/** @type {SvyGridFilters} */
var gridFilters = toolbarFilterUX['svyGridFilters'];
var selectedColumn = gridFilters.getTable().getColumn(columnIndex);
if (isSelected) {
toolbarFilterUX.removeGridFilter(selectedColumn);
} else {
toolbarFilterUX.addGridFilter(selectedColumn);
}
}
}
/**
* @constructor
* @extends {AbstractToolbarFilterUX}
* @private
* @properties={typeid:24,uuid:"C7D04E91-D3C9-42D0-8837-7F1AFE0FF731"}
*/
function initListComponentFilterRenderer() {
ListComponentFilterRenderer.prototype = Object.create(AbstractToolbarFilterUX.prototype);
ListComponentFilterRenderer.prototype.constructor = ListComponentFilterRenderer;
/**
* Returns the Custom List element this renderer is using to display the filters
*
* @return {RuntimeWebComponent<customrenderedcomponents-customlist>|RuntimeWebComponent<customrenderedcomponents-customlist_abs>}
*
* @public
*
* @override
*
* @this {ListComponentFilterRenderer}
*/
ListComponentFilterRenderer.prototype.getElement = function() {
return this.element;
}
/**
* @return {String}
*
* @protected
*
* @this {ListComponentFilterRenderer}
*/
ListComponentFilterRenderer.prototype.getRenderTemplate = function() {
return "(function renderFilterEntry(entry) { \n\
var template = '';\n\
var strDivider = ' : ';\n\
template += '<div class=\"btn-group push-right margin-left-10 toolbar-filter-tag\">' + \n\
'<button class=\"btn btn-default btn-sm btn-round\" data-target=\"open\" svy-tooltip=\"entry.text + strDivider + entry.value\">' + \n\
'<span class=\"toolbar-filter-tag-text\">' + entry.text + '</span>' + \n\
'<span class=\"toolbar-filter-tag-value\"> ' + entry.value.split(',').join(', ') + ' </span>' + \n\
'<span class=\"toolbar-filter-tag-icon fas fa-angle-down\">' + '</span>' + \n\
'</button>' + \n\
'<button class=\"btn btn-default btn-sm btn-round\" data-target=\"close\">' + \n\
'<span class=\"fas fa-times text-danger\">' + '</span>' + '</button>' + '</div>'; \n\
return template; \n\
})";
}
/**
* Called when the mouse is clicked on a list entry.
*
* @param {object} entry
* @return {String}
* @protected
* @this {ListComponentFilterRenderer}
* */
ListComponentFilterRenderer.prototype.getDataProvider = function(entry) {
return entry['dataprovider'];
}
/**
* Called when the mouse is clicked on a list entry.
*
* @param {object} entry
* @param {Number} index
* @param {string} dataTarget
* @param {JSEvent} event
*
* @public
* @this {ListComponentFilterRenderer}
* */
ListComponentFilterRenderer.prototype.onClick = function(entry, index, dataTarget, event) {
var column = this.svyGridFilters.getColumn(this.getDataProvider(entry));
if (!dataTarget || dataTarget == "open") {
//open the filter
if (column) {
this.showPopupFilter(column, event);
}
} else if (dataTarget == "close") {
// remove the filter
if (column) {
this.removeGridFilter(column);
} else {
this.getElement().removeEntry(index)
}
}
}
/**
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @protected
*
* @this {ListComponentFilterRenderer}
*/
ListComponentFilterRenderer.prototype.addGridFilter = function(column) {
var newFilter = this.getElement().newEntry();
newFilter.text = getI18nText(column.headerTitle);
newFilter.dataprovider = column.dataprovider;
newFilter.value = "";
// if has active filters
var element = this.getElement();
element.addStyleClass('has-filter');
if (this.onFilterAddedEvent) {
scopes.svySystem.callMethod(this.onFilterAddedEvent)
}
}
/**
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @protected
*
* @this {ListComponentFilterRenderer}
*/
ListComponentFilterRenderer.prototype.removeGridFilter = function(column) {
var index = this.getFilterTagIndex(column);
if (index > -1) {
this.getElement().removeEntry(index);
}
this.svyGridFilters.removeGridFilter(column);
// on filter removed event
if (this.onFilterRemovedEvent) {
scopes.svySystem.callMethod(this.onFilterRemovedEvent);
}
}
/**
* @param {String} dataprovider
* @param {Array} displayValues
*
* @protected
*
* @this {ListComponentFilterRenderer}
*/
ListComponentFilterRenderer.prototype.updateGridFilter = function(dataprovider, displayValues) {
var index;
var element = this.getElement();
var count = element.getEntriesCount();
var entries = [];
for (var i = 0; i < count; i++) {
var filterTag = element.getEntry(i);
// TODO can i rely on dataprovider only !?
if (filterTag && filterTag.dataprovider == dataprovider) {
index = i;
}
entries.push(filterTag);
}
if (index || index == 0) {
// TODO can i make an API in listcomponent to update an entry value !?
// clear and re-draw all elements
element.clear();
for (i = 0; i < entries.length; i++) {
var entryCopy = entries[i];
var entry = element.newEntry();
// copy entry properties
for (var prop in entryCopy) {
entry[prop] = entryCopy[prop];
}
// update display value if necessary
if (i === index) {
entry.value = displayValues.join(",");
}
}
return true;
} else {
return false;
}
}
/**
* Clears all grid filters
*
* @protected
*
* @override
*
* @this {ListComponentFilterRenderer}
*/
ListComponentFilterRenderer.prototype._clearGridFilters = function() {
this.getElement().clear();
this.svyGridFilters.clearGridFilters();
// if has no filters
var element = this.getElement();
element.removeStyleClass('has-filter');
}
/**
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @return {Boolean}
*
* @protected
*
* @this {ListComponentFilterRenderer}
*/
ListComponentFilterRenderer.prototype.hasActiveFilter = function(column) {
return this.getFilterTagIndex(column) > -1 ? true : false;
}
/**
* @param {CustomType<aggrid-groupingtable.column>} column
*
* @return {Number}
*
* @protected
*
* @this {ListComponentFilterRenderer}
*/
ListComponentFilterRenderer.prototype.getFilterTagIndex = function(column) {
var count = this.getElement().getEntriesCount();
for (var i = 0; i < count; i++) {
var filterTag = this.getElement().getEntry(i);
// TODO can i rely on dataprovider only !?
if (filterTag && filterTag.dataprovider == column.dataprovider) {
return i;
}
}
return -1;
}
}
/**
* @private
* @SuppressWarnings(unused)
* @properties={typeid:35,uuid:"FE4768E2-C48C-4BBE-B6B1-30CCC1194975",variableType:-4}
*/
var init = (function() {
initPopupRendererForms();
globalFilterConfig = new FilterConfig();
popupRendererForms = new PopupRendererForms();
initSvyGridFilters();
initAbstractToolbarFilterUX();
initListComponentFilterRenderer();
}());
<file_sep>/**
* @type {String}
*
* @properties={typeid:35,uuid:"ADB453C4-D190-4BE0-93AE-D6C34FF82E4E"}
*/
var searchText = null;
/**
* @type {scopes.svyToolbaFilter.ListComponentFilterRender}
*
* @properties={typeid:35,uuid:"30AE6150-1BE1-41D9-A9C2-99E5E9DB97BA",variableType:-4}
*/
var toolbarFilter;
/**
* Callback method when form is (re)loaded.
*
* @param {JSEvent} event the event that triggered the action
*
* @protected
*
* @properties={typeid:24,uuid:"1EA9C25D-7811-49F6-858C-679CD8F411B5"}
*/
function onLoad(event) {
toolbarFilter = new scopes.svyToolbarFilter.ListComponentFilterRender(elements.filterToolbar, elements.table);
}
/**
* @param {JSEvent} event
*
* @protected
*
* @properties={typeid:24,uuid:"542C354A-019D-42BB-A7DC-6FA93C168E1D"}
*/
function onActionSearch(event) {
search();
}
/**
* @param oldValue
* @param newValue
* @param {JSEvent} event
*
* @return {boolean}
*
* @protected
*
* @properties={typeid:24,uuid:"5C2E5EBC-F85A-4681-816B-13900BC8043C"}
*/
function onDataChangeSearch(oldValue, newValue, event) {
search();
return true
}
/**
* @param {JSEvent} event
*
* @protected
*
* @properties={typeid:24,uuid:"44F64442-4B61-4599-B3F6-F68407B04CE2"}
*/
function onActionFilter(event) {
toolbarFilter.showPopupFilterPicker(elements[event.getElementName()])
}
/**
* Called when the mouse is clicked on a list entry.
*
* @param {object} entry
* @param {Number} index
* @param {string} dataTarget
* @param {JSEvent} event
*
* @protected
*
* @properties={typeid:24,uuid:"8AB6C6C0-B9C4-412F-8A2D-B4282166D61A"}
*/
function onClick(entry, index, dataTarget, event) {
toolbarFilter.onClick(entry,index,dataTarget,event);
}
/**
* @protected
* @properties={typeid:24,uuid:"9DF586CB-7A02-4F07-9D7E-F98AD7A6A41B"}
* @AllowToRunInFind
*/
function search() {
toolbarFilter.setSearchText(searchText);
toolbarFilter.search();
}
<file_sep>/**
* @type {Date}
* @protected
*
* @properties={typeid:35,uuid:"EE42E940-E5C5-4427-A12E-10DBD3F5B5B3",variableType:93}
*/
var dateFrom;
/**
* @type {Date}
* @protected
*
* @properties={typeid:35,uuid:"27156EB3-336E-4F82-BFCB-4FE772DBC5D6",variableType:93}
*/
var dateTo;
/**
* @param {JSEvent} event
*
* @properties={typeid:24,uuid:"0B8B503C-329D-4924-A924-0137E86BB291"}
* @override
*/
function onLoad(event) {
_super.onLoad(event);
// default operator to between
operator = scopes.svyPopupFilter.OPERATOR.BETWEEN;
updateUI();
}
/**
* @protected
* @param {Array} selectedValues
*
* @properties={typeid:24,uuid:"61DC1807-93A7-404C-8C3C-5418355F4597"}
* @override
*/
function setSelectedFilterValues(selectedValues) {
if (selectedValues && selectedValues.length) {
dateFrom = selectedValues[0];
dateTo = selectedValues[1];
} else {
dateFrom = null;
dateTo = null;
}
}
/**
* @protected
* @properties={typeid:24,uuid:"3663C0D4-B5FC-4A94-899D-41588025D5B4"}
* @override
*/
function getSelectedFilterValues() {
if (dateFrom && dateTo) {
operator = scopes.svyPopupFilter.OPERATOR.BETWEEN;
return [scopes.svyDateUtils.toStartOfDay(dateFrom), scopes.svyDateUtils.toEndOfDay(dateTo)];
} else if (dateFrom) {
operator = scopes.svyPopupFilter.OPERATOR.GREATER_EQUAL;
return [scopes.svyDateUtils.toStartOfDay(dateFrom)];
} else if (dateTo) {
operator = scopes.svyPopupFilter.OPERATOR.SMALLER_EQUAL;
return [scopes.svyDateUtils.toStartOfDay(dateTo)];
} else {
return [];
}
// return [dateFrom ? scopes.svyDateUtils.toStartOfDay(dateFrom) : null, dateTo ? scopes.svyDateUtils.toEndOfDay(dateTo) : null];
}
/**
* @protected
* @properties={typeid:24,uuid:"4CDDC978-247C-437E-8B5D-65CEFA7E9EF1"}
*/
function updateUI() {
}
/**
* @protected
* @properties={typeid:24,uuid:"28611948-0EA9-4818-8386-9FEB4BFE36AE"}
*/
function setSelectionToday() {
var today = new Date();
dateFrom = scopes.svyDateUtils.toStartOfDay(today);
dateTo = scopes.svyDateUtils.toEndOfDay(today);
operator = scopes.svyPopupFilter.OPERATOR.EQUALS;
updateUI();
}
/**
* @protected
* @properties={typeid:24,uuid:"C7DBF849-C71C-4404-898F-398F9B703E12"}
*/
function setSelectionTomorrow() {
var tomorrow = scopes.svyDateUtils.addDays(new Date(), 1);
dateFrom = scopes.svyDateUtils.toStartOfDay(tomorrow);
dateTo = scopes.svyDateUtils.toEndOfDay(tomorrow);
operator = scopes.svyPopupFilter.OPERATOR.EQUALS;
updateUI();
}
/**
* @protected
* @properties={typeid:24,uuid:"3BA53559-058F-404B-8661-F406A18E34B1"}
*/
function setSelectionThisWeek() {
var today = new Date();
dateFrom = scopes.svyDateUtils.toStartOfDay(scopes.svyDateUtils.getFirstDayOfWeek(today));
dateTo = scopes.svyDateUtils.toEndOfDay(scopes.svyDateUtils.getLastDayOfWeek(today));
operator = scopes.svyPopupFilter.OPERATOR.BETWEEN;
updateUI();
}
/**
* @protected
* @properties={typeid:24,uuid:"0383EF7C-9B17-46A5-AFFE-6B02F1D7FD8C"}
*/
function setSelectionThisMonth() {
var today = new Date();
dateFrom = scopes.svyDateUtils.toStartOfDay(scopes.svyDateUtils.getFirstDayOfMonth(today));
dateTo = scopes.svyDateUtils.toEndOfDay(scopes.svyDateUtils.getLastDayOfMonth(today));
operator = scopes.svyPopupFilter.OPERATOR.BETWEEN;
updateUI();
}
/**
* @protected
* @properties={typeid:24,uuid:"B7AAD534-BAA8-4F35-BDB1-4B71EB9EBB87"}
*/
function setSelectionThisYear() {
var today = new Date();
dateFrom = scopes.svyDateUtils.toStartOfDay(scopes.svyDateUtils.getFirstDayOfYear(today));
dateTo = scopes.svyDateUtils.toEndOfDay(scopes.svyDateUtils.getLastDayOfYear(today));
operator = scopes.svyPopupFilter.OPERATOR.BETWEEN;
updateUI();
}
/**
* @protected
* @properties={typeid:24,uuid:"D67CCAF0-67F8-4BF3-B942-8D680A60931F"}
*/
function setSelectionNextWeek() {
var date = scopes.svyDateUtils.addDays(new Date(), 7);
dateFrom = scopes.svyDateUtils.toStartOfDay(scopes.svyDateUtils.getFirstDayOfWeek(date));
dateTo = scopes.svyDateUtils.toEndOfDay(scopes.svyDateUtils.getLastDayOfWeek(date));
operator = scopes.svyPopupFilter.OPERATOR.BETWEEN;
updateUI();
}
/**
* @protected
* @properties={typeid:24,uuid:"C30C5704-306C-48BC-9B46-E7DF7ECBCF68"}
*/
function setSelectionNextMonth() {
var date = scopes.svyDateUtils.addMonths(new Date(), 1);
dateFrom = scopes.svyDateUtils.toStartOfDay(scopes.svyDateUtils.getFirstDayOfMonth(date));
dateTo = scopes.svyDateUtils.toEndOfDay(scopes.svyDateUtils.getLastDayOfMonth(date));
operator = scopes.svyPopupFilter.OPERATOR.BETWEEN;
updateUI();
}
/**
* @protected
* @properties={typeid:24,uuid:"D34FEE7C-1E68-40B5-A487-C6F715E9C9B6"}
*/
function setSelectionLastYear() {
var date = scopes.svyDateUtils.addYears(new Date(), -1);
dateFrom = scopes.svyDateUtils.toStartOfDay(scopes.svyDateUtils.getFirstDayOfYear(date));
dateTo = scopes.svyDateUtils.toEndOfDay(scopes.svyDateUtils.getLastDayOfYear(date));
operator = scopes.svyPopupFilter.OPERATOR.BETWEEN;
updateUI();
}<file_sep>/**
* @type {String}
*
* @properties={typeid:35,uuid:"F75353CC-9485-4B79-82A5-82A230716775"}
*/
var searchText = null;
/**
* @protected
* @param event
*
* @properties={typeid:24,uuid:"77598B3B-21D1-4B82-ACFD-84560EE97FA8"}
* @override
*/
function onLoad(event) {
var renderFunction = "(" + scopes.svySystem.printMethodCode(renderFilterEntry).join("") + ")";
elements.listTags.entryRendererFunction = renderFunction;
_super.onLoad(event);
}
/**
* @protected
* @param firstShow
* @param event
*
* @properties={typeid:24,uuid:"D9DA9D2A-F16E-469F-A19A-7625D3798EC5"}
* @override
*/
function onShow(firstShow,event) {
_super.onShow(firstShow,event);
if (firstShow) {
elements.listTags.clear();
for (var i = 0; i < values.length; i++) {
var tag = elements.listTags.newEntry();
tag.text = values[i];
}
}
}
/**
* @protected
* @param selectedValues
*
* @properties={typeid:24,uuid:"9F26FAEA-39F7-41B5-80D8-7C2117A36A2E"}
* @override
*/
function setSelectedFilterValues(selectedValues) {
_super.setSelectedFilterValues(selectedValues);
// clear tags
elements.listTags.clear();
// set all values
for (var i = 0; i < values.length; i++) {
addTag(values[i]);
}
}
/**
* @param entry.dataprovider name
* @param entry.text timeEntry
*
* @protected
* @properties={typeid:24,uuid:"41DCC810-7BC6-4D8F-BD4B-251DA79704E2"}
*/
function renderFilterEntry(entry) {
var template = '';
template += '<div class="row">' +
'<div class="col-md-12 svy-popup-filter-token">' +
'<span class="fa fa-trash text-danger svy-popup-filter-token-icon" data-target="close"></span>' +
'<span class="svy-popup-filter-token-text">' +
entry.text +
'</span>' +
'</div>' +
'</div>';
return template;
}
/**
* @param {JSEvent} event
*
* @protected
*
* @properties={typeid:24,uuid:"BE24F6EF-5DD7-4EB6-9AC9-305215A865DA"}
*/
function onActionSearchText(event) {
addTag(searchText);
}
/**
* @param oldValue
* @param newValue
* @param {JSEvent} event
*
* @return {boolean}
*
* @protected
*
* @properties={typeid:24,uuid:"8663257D-6939-43F4-A748-873F81D0D52B"}
*/
function onDataChange(oldValue, newValue, event) {
addTag(searchText);
return true
}
/**
* Called when the mouse is clicked on a list entry.
*
* @param {{text: String}} entry
* @param {Number} index
* @param {string} dataTarget
* @param {JSEvent} event
*
* @protected
*
* @properties={typeid:24,uuid:"A67A8863-8ACB-48BF-BDC1-0F65B9F0C566"}
*/
function onClick(entry, index, dataTarget, event) {
if (dataTarget == "close") {
removeTag(entry.text, index);
}
}
/**
* @param {JSEvent} event
* @param {string} dataTarget
*
* @protected
*
* @properties={typeid:24,uuid:"69A13409-C425-4D4D-ADF9-29148E922AF0"}
*/
function onActionRemoveAll(event, dataTarget) {
clear();
}
/**
* @protected
* @properties={typeid:24,uuid:"9FEBB97F-A251-4EA3-8C33-D9A5FBFD9E53"}
*/
function clear() {
values = [];
elements.listTags.clear();
}
/**
* @protected
* @param text
*
* @properties={typeid:24,uuid:"B8552CF6-0A2A-49D2-BCFF-C4B3EFCE6EF7"}
*/
function addTag(text) {
if (!text && text != "0") return;
if (values.indexOf(text) == -1) {
values.push(text);
var tag = elements.listTags.newEntry();
tag.text = text;
searchText = null;
} else {
// do nothing
}
}
/**
* @protected
* @param {String} text
* @param {Number} index
*
* @properties={typeid:24,uuid:"1E39D48A-7276-498F-B958-274E7CDCBDC5"}
*/
function removeTag(text, index) {
if (!text && text != "0") return;
var indexOfText = values.indexOf(text)
if (indexOfText > -1) {
values.splice(indexOfText,1);
elements.listTags.removeEntry(index);
} else {
// do nothing
}
}
<file_sep>/**
* @param {JSEvent} event
*
* @properties={typeid:24,uuid:"1FDAB7CD-2E1C-4A0E-B48A-5270A7675147"}
* @override
*/
function onLoad(event) {
_super.onLoad(event);
updateUI();
}
/**
* @protected
* @param firstShow
* @param event
*
* @properties={typeid:24,uuid:"E20DFB62-7543-43D9-B286-EAE20058A031"}
* @override
*/
function onShow(firstShow,event) {
if (filter && filter.getText()) {
elements.labelTitle.text = filter.getText();
}
_super.onShow(firstShow,event);
}
/**
* @param {String} newOperator
*
* @properties={typeid:24,uuid:"F928B519-7FE3-45DC-A5A4-3CE1F8D0945B"}
*/
function toggleOperator(newOperator) {
operator = newOperator;
updateUI();
}
/**
* @param {JSEvent} event
*
* @protected
*
* @properties={typeid:24,uuid:"826402C7-E82F-450F-AA53-065F3010F6FB"}
*/
function onActionToggleEqualTo(event) {
toggleOperator(scopes.svyPopupFilter.OPERATOR.EQUALS);
}
/**
* @param {JSEvent} event
*
* @protected
*
* @properties={typeid:24,uuid:"5742086A-6023-4D71-807C-5764C6984519"}
*/
function onActionToggleBiggerThen(event) {
toggleOperator(scopes.svyPopupFilter.OPERATOR.GREATER_EQUAL);
}
/**
* @param {JSEvent} event
*
* @protected
*
* @properties={typeid:24,uuid:"2B9B6314-E227-482B-BB1D-E47D89D93AF6"}
*/
function onActionToggleSmallerThen(event) {
toggleOperator(scopes.svyPopupFilter.OPERATOR.SMALLER_EQUAL);
}
/**
* @param {JSEvent} event
*
* @protected
*
* @properties={typeid:24,uuid:"660BF5E2-956E-4637-8522-8B9B020DBE7C"}
*/
function onActionToggleBetween(event) {
toggleOperator(scopes.svyPopupFilter.OPERATOR.BETWEEN);
}
/**
* @protected
* @properties={typeid:24,uuid:"0F223D2E-2293-4D7F-A3FE-3508E1761285"}
*/
function updateUI() {
elements.labelEqualTo.addStyleClass("text-tertiary");
elements.iconEqualTo.styleclass = "fa fa-circle-o text-tertiary clickable";
elements.textboxEqualTo.enabled = false;
elements.labelGreater.addStyleClass("text-tertiary");
elements.iconGreater.styleclass = "fa fa-circle-o text-tertiary clickable";
elements.textboxGreater.enabled = false;
elements.labelSmaller.addStyleClass("text-tertiary");
elements.iconSmaller.styleclass = "fa fa-circle-o text-tertiary clickable";
elements.textboxSmaller.enabled = false;
elements.labelBetween.addStyleClass("text-tertiary");
elements.iconBetween.styleclass = "fa fa-circle-o text-tertiary clickable";
elements.textboxBetweenMin.enabled = false;
elements.textboxBetweenMax.enabled = false;
switch (operator) {
case scopes.svyPopupFilter.OPERATOR.EQUALS:
elements.labelEqualTo.removeStyleClass("text-tertiary");
elements.iconEqualTo.styleclass = "fas fa-dot-circle text-primary clickable";
elements.textboxEqualTo.enabled = true;
break;
case scopes.svyPopupFilter.OPERATOR.BETWEEN:
elements.labelBetween.removeStyleClass("text-tertiary");
elements.iconBetween.styleclass = "fas fa-dot-circle text-primary clickable";
elements.textboxBetweenMin.enabled = true;
elements.textboxBetweenMax.enabled = true;
break;
case scopes.svyPopupFilter.OPERATOR.GREATER_EQUAL:
elements.labelGreater.removeStyleClass("text-tertiary");
elements.iconGreater.styleclass = "fas fa-dot-circle text-primary clickable";
elements.textboxGreater.enabled = true;
break;
case scopes.svyPopupFilter.OPERATOR.SMALLER_EQUAL:
elements.labelSmaller.removeStyleClass("text-tertiary");
elements.iconSmaller.styleclass = "fas fa-dot-circle text-primary clickable";
elements.textboxSmaller.enabled = true;
break;
default:
break;
}
}
| 4b8efc87ce818c75664b2f5c126dcea84783adac | [
"JavaScript"
] | 5 | JavaScript | nanjum30/svyPopupFilter | 7165320994ec590de5c315600ded2bfbc19f7b34 | 6b9352baeba59e41ee327c38d6278da4f350a20b |
refs/heads/master | <repo_name>Mimand3r/PurpleprintKit<file_sep>/Projects/UnrealEngine4/Purpleprint2Kit/Plugins/PurpleprintKitPlugin/Source/PPKLibrary/Core/PPKLibraryMath.cpp
/*
===========================================================================
This code is part of the "Source Code" content in
Purpleprint 2 - Kit by Hevedy <https://github.com/Hevedy>
<https://github.com/Hevedy/PurpleprintKit>
The MIT License (MIT)
Copyright (c) 2014-2016 Hevedy <https://github.com/Hevedy>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
===========================================================================
*/
/*
================================================
PPKLibraryMath.cpp
================================================
*/
#include "PPKLibraryPrivatePCH.h"
#include "PPKLibraryMath.h"
UPPKLibraryMath::UPPKLibraryMath( const class FObjectInitializer& ObjectInitializer ) {
}
int32 UPPKLibraryMath::FullRotSector( const float FloatValue, const int32 SectorsNumber ) {
int32 calcSectors = FMath::TruncToInt( 360 / SectorsNumber );
int32 calcValue = FMath::TruncToInt( FMath::TruncToInt( FloatValue + 360 ) % 360 );
return FMath::TruncToInt( calcValue / calcSectors );
}
uint8 UPPKLibraryMath::FullRotSectorByte( const float FloatValue, const int32 SectorsNumber ) {
return (uint8)FullRotSector( FloatValue, SectorsNumber );
}
int32 UPPKLibraryMath::FullRotSectorInt( const float FloatValue, const int32 SectorsNumber ) {
return FullRotSector( FloatValue, SectorsNumber );
}
FVector UPPKLibraryMath::FullRotSectorVector( const FVector VectorValue, const FVector SectorsNumber ) {
return FVector( FullRotSector( VectorValue.X, SectorsNumber.X ),
FullRotSector( VectorValue.Y, SectorsNumber.Y ),
FullRotSector( VectorValue.Z, SectorsNumber.Z ) );
}
FVector UPPKLibraryMath::FullRotSectorRotator( const FRotator RotValue, const FVector SectorsNumber ) {
return FVector( FullRotSector( RotValue.Roll, SectorsNumber.X ),
FullRotSector( RotValue.Pitch, SectorsNumber.Y ),
FullRotSector( RotValue.Yaw, SectorsNumber.Z ) );
}
int32 UPPKLibraryMath::IntCount( const int32 IntValue ) {
//return IntValue == 0 ? 1 : FMath::FloorToInt( log10( FMath::Abs( IntValue ) ) ) + 1;
FString numValue = FString::FromInt( IntValue );
return numValue.Len();
}
int32 UPPKLibraryMath::FloatCount( const float FloatValue ) {
//return IntValue == 0 ? 1 : FMath::FloorToInt( log10( FMath::Abs( IntValue ) ) ) + 1;
FString numValue = FString::SanitizeFloat( FloatValue );
return numValue.Len() - 1;
}
int32 UPPKLibraryMath::IMakeFullFromHalfRot( const int32 IntValue ) {
return IntValue < 0 ? IntValue + 360 : IntValue;
}
float UPPKLibraryMath::FMakeFullFromHalfRot( const float FloatValue ) {
return FloatValue < 0.0f ? FloatValue + 360.0f : FloatValue;
}
int32 UPPKLibraryMath::ICMakeHalfFromFullRot( const int32 IntValue ) {
return IntValue > 180 ? IntValue - 360 : IntValue;
}
float UPPKLibraryMath::FMakeHalfFromFullRot( const float FloatValue ) {
return FloatValue > 180.0f ? FloatValue - 360.0f : FloatValue;
}
FRotator UPPKLibraryMath::MakeFullFromHalfRot( const FRotator RotValue ) {
FRotator value;
value.Roll = RotValue.Roll < 0.0f ? RotValue.Roll + 360.0f : RotValue.Roll;
value.Pitch = RotValue.Pitch < 0.0f ? RotValue.Pitch + 360.0f : RotValue.Pitch;
value.Yaw = RotValue.Yaw < 0.0f ? RotValue.Yaw + 360.0f : RotValue.Yaw;
return value;
}
FRotator UPPKLibraryMath::MakeHalfFromFullRot( const FRotator RotValue ) {
FRotator value;
value.Roll = RotValue.Roll > 180.0f ? RotValue.Roll - 360.0f : RotValue.Roll;
value.Pitch = RotValue.Pitch > 180.0f ? RotValue.Pitch - 360.0f : RotValue.Pitch;
value.Yaw = RotValue.Yaw > 180.0f ? RotValue.Yaw - 360.0f : RotValue.Yaw;
return value;
}
FVector2D UPPKLibraryMath::V2DMakeFullFromHalfRot( const FVector2D Vec2Value ) {
FVector2D value;
value.X = Vec2Value.X < 0.0f ? Vec2Value.X + 360.0f : Vec2Value.X;
value.Y = Vec2Value.Y < 0.0f ? Vec2Value.Y + 360.0f : Vec2Value.Y;
return value;
}
FVector2D UPPKLibraryMath::V2DMakeHalfFromFullRot( const FVector2D Vec2Value ) {
FVector2D value;
value.X = Vec2Value.X > 180.0f ? Vec2Value.X - 360.0f : Vec2Value.X;
value.Y = Vec2Value.Y > 180.0f ? Vec2Value.Y - 360.0f : Vec2Value.Y;
return value;
}
FVector UPPKLibraryMath::VMakeFullFromHalfRot( const FVector VecValue ) {
FVector value;
value.X = VecValue.X < 0.0f ? VecValue.X + 360.0f : VecValue.X;
value.Y = VecValue.Y < 0.0f ? VecValue.Y + 360.0f : VecValue.Y;
value.Z = VecValue.Z < 0.0f ? VecValue.Z + 360.0f : VecValue.Z;
return value;
}
FVector UPPKLibraryMath::VMakeHalfFromFullRot( const FVector VecValue ) {
FVector value;
value.X = VecValue.X > 180.0f ? VecValue.X - 360.0f : VecValue.X;
value.Y = VecValue.Y > 180.0f ? VecValue.Y - 360.0f : VecValue.Y;
value.Z = VecValue.Z > 180.0f ? VecValue.Z - 360.0f : VecValue.Z;
return value;
}
FVector4 UPPKLibraryMath::V4MakeFullFromHalfRot( const FVector4 Vec4Value ) {
FVector4 value;
value.X = Vec4Value.X < 0.0f ? Vec4Value.X + 360.0f : Vec4Value.X;
value.Y = Vec4Value.Y < 0.0f ? Vec4Value.Y + 360.0f : Vec4Value.Y;
value.Z = Vec4Value.Z < 0.0f ? Vec4Value.Z + 360.0f : Vec4Value.Z;
value.W = Vec4Value.W < 0.0f ? Vec4Value.W + 360.0f : Vec4Value.W;
return value;
}
FVector4 UPPKLibraryMath::V4MakeHalfFromFullRot( const FVector4 Vec4Value ) {
FVector4 value;
value.X = Vec4Value.X > 180.0f ? Vec4Value.X - 360.0f : Vec4Value.X;
value.Y = Vec4Value.Y > 180.0f ? Vec4Value.Y - 360.0f : Vec4Value.Y;
value.Z = Vec4Value.Z > 180.0f ? Vec4Value.Z - 360.0f : Vec4Value.Z;
value.W = Vec4Value.W > 180.0f ? Vec4Value.W - 360.0f : Vec4Value.W;
return value;
}
uint8 UPPKLibraryMath::BMin( uint8 A, uint8 B ) {
return FMath::Min<uint8>( A, B );
}
uint8 UPPKLibraryMath::BMax( uint8 A, uint8 B ) {
return FMath::Max<uint8>( A, B );
}
uint8 UPPKLibraryMath::BGetCloser( uint8 Ref, uint8 A, uint8 B ) {
return Closer<uint8>( Ref, A, B );
}
uint8 UPPKLibraryMath::BGetFurther( uint8 Ref, uint8 A, uint8 B ) {
return Further<uint8>( Ref, A, B );
}
int32 UPPKLibraryMath::IGetCloser( int32 Ref, int32 A, int32 B ) {
return Closer<int32>( Ref, A, B );
}
int32 UPPKLibraryMath::IGetFurther( int32 Ref, int32 A, int32 B ) {
return Further<int32>( Ref, A, B );
}
float UPPKLibraryMath::FGetCloser( float Ref, float A, float B ) {
return Closer<float>( Ref, A, B );
}
float UPPKLibraryMath::FGetFurther( float Ref, float A, float B ) {
return Further<float>( Ref, A, B );
}
void UPPKLibraryMath::CloserByteArray( const uint8 ByteRefValue, const TArray<uint8>& ByteArray, const bool NotEqual,
int32& IndexOfCloserValue, uint8& CloserValue ) {
CloserValue = Closer<uint8>( ByteRefValue, ByteArray, NotEqual, &IndexOfCloserValue );
}
void UPPKLibraryMath::FurtherByteArray( const uint8 ByteRefValue, const TArray<uint8>& ByteArray, int32& IndexOfFurtherValue,
uint8& FurtherValue ) {
FurtherValue = Further<uint8>( ByteRefValue, ByteArray, &IndexOfFurtherValue );
}
void UPPKLibraryMath::CloserIntegerArray( const int32 IntRefValue, const TArray<int32>& IntArray, const bool NotEqual,
int32& IndexOfCloserValue, int32& CloserValue ) {
CloserValue = Closer<int32>( IntRefValue, IntArray, NotEqual, &IndexOfCloserValue );
}
void UPPKLibraryMath::FurtherIntegerArray( const int32 IntRefValue, const TArray<int32>& IntArray, int32& IndexOfFurtherValue,
int32& FurtherValue ) {
FurtherValue = Further<int32>( IntRefValue, IntArray, &IndexOfFurtherValue );
}
void UPPKLibraryMath::CloserFloatArray( const float FloatRefValue, const TArray<float>& FloatArray, const bool NotEqual,
int32& IndexOfCloserValue, float& CloserValue ) {
CloserValue = Closer<float>( FloatRefValue, FloatArray, NotEqual, &IndexOfCloserValue );
}
void UPPKLibraryMath::FurtherFloatArray( const float FloatRefValue, const TArray<float>& FloatArray, int32& IndexOfFurtherValue,
float& FurtherValue ) {
FurtherValue = Further<float>( FloatRefValue, FloatArray, &IndexOfFurtherValue );
}
void UPPKLibraryMath::MinByteArray( const TArray<uint8>& ByteArray, const int32 NumberOfIndexToDiscard, int32& IndexOfMinValue,
float& MinValue ) {
if ( NumberOfIndexToDiscard < 0 || NumberOfIndexToDiscard >= ByteArray.Num() ) {
IndexOfMinValue = -1; MinValue = -1; return;
}
TArray<uint8> localArray = ByteArray; TArray<uint8> localArrayRef;
int32 minIndex = -1; int32 lastMinIndex = -1; float minValue = -1; int32 numdiff = 0;
for ( int32 i = -1; i < NumberOfIndexToDiscard; i++ ) {
minValue = FMath::Min<uint8>( localArray, &minIndex );
localArrayRef.Add( minIndex );
localArray.RemoveAt( minIndex );
lastMinIndex = minIndex;
}
for ( int32 i = 0; i < localArrayRef.Num(); i++ ) {
minIndex = ( localArrayRef[i] < lastMinIndex ) ? minIndex + 1 : minIndex;
}
IndexOfMinValue = minIndex; MinValue = minValue;
}
void UPPKLibraryMath::MaxByteArray( const TArray<uint8>& ByteArray, const int32 NumberOfIndexToDiscard, int32& IndexOfMaxValue,
float& MaxValue ) {
if ( NumberOfIndexToDiscard < 0 || NumberOfIndexToDiscard >= ByteArray.Num() ) {
IndexOfMaxValue = -1; MaxValue = -1; return;
}
TArray<uint8> localArray = ByteArray; TArray<uint8> localArrayRef;
int32 maxIndex = -1; int32 lastMaxIndex = -1; float maxValue = -1; int32 numdiff = 0;
for ( int32 i = -1; i < NumberOfIndexToDiscard; i++ ) {
maxValue = FMath::Max<uint8>( localArray, &maxIndex );
localArrayRef.Add( maxIndex );
localArray.RemoveAt( maxIndex );
lastMaxIndex = maxIndex;
}
for ( int32 i = 0; i < localArrayRef.Num(); i++ ) {
maxIndex = ( localArrayRef[i] < lastMaxIndex ) ? maxIndex + 1 : maxIndex;
}
IndexOfMaxValue = maxIndex; MaxValue = maxValue;
}
void UPPKLibraryMath::MinIntegerArray( const TArray<int32>& IntArray, const int32 NumberOfIndexToDiscard, int32& IndexOfMinValue,
float& MinValue ) {
if ( NumberOfIndexToDiscard < 0 || NumberOfIndexToDiscard >= IntArray.Num() ) {
IndexOfMinValue = -1; MinValue = -1; return;
}
TArray<int32> localArray = IntArray; TArray<int32> localArrayRef;
int32 minIndex = -1; int32 lastMinIndex = -1; float minValue = -1; int32 numdiff = 0;
for ( int32 i = -1; i < NumberOfIndexToDiscard; i++ ) {
minValue = FMath::Min<int32>( localArray, &minIndex );
localArrayRef.Add( minIndex );
localArray.RemoveAt( minIndex );
lastMinIndex = minIndex;
}
for ( int32 i = 0; i < localArrayRef.Num(); i++ ) {
minIndex = ( localArrayRef[i] < lastMinIndex ) ? minIndex + 1 : minIndex;
}
IndexOfMinValue = minIndex; MinValue = minValue;
}
void UPPKLibraryMath::MaxIntegerArray( const TArray<int32>& IntArray, const int32 NumberOfIndexToDiscard, int32& IndexOfMaxValue,
float& MaxValue ) {
if ( NumberOfIndexToDiscard < 0 || NumberOfIndexToDiscard >= IntArray.Num() ) {
IndexOfMaxValue = -1; MaxValue = -1; return;
}
TArray<int32> localArray = IntArray; TArray<int32> localArrayRef;
int32 maxIndex = -1; int32 lastMaxIndex = -1; float maxValue = -1; int32 numdiff = 0;
for ( int32 i = -1; i < NumberOfIndexToDiscard; i++ ) {
maxValue = FMath::Max<int32>( localArray, &maxIndex );
localArrayRef.Add( maxIndex );
localArray.RemoveAt( maxIndex );
lastMaxIndex = maxIndex;
}
for ( int32 i = 0; i < localArrayRef.Num(); i++ ) {
maxIndex = ( localArrayRef[i] < lastMaxIndex ) ? maxIndex + 1 : maxIndex;
}
IndexOfMaxValue = maxIndex; MaxValue = maxValue;
}
void UPPKLibraryMath::MinFloatArray( const TArray<float>& FloatArray, const int32 NumberOfIndexToDiscard, int32& IndexOfMinValue,
float& MinValue ) {
if ( NumberOfIndexToDiscard < 0 || NumberOfIndexToDiscard >= FloatArray.Num() ) {
IndexOfMinValue = -1; MinValue = -1; return;
}
TArray<float> localArray = FloatArray; TArray<int32> localArrayRef;
int32 minIndex = -1; int32 lastMinIndex = -1; float minValue = -1; int32 numdiff = 0;
for ( int32 i = -1; i < NumberOfIndexToDiscard; i++ ) {
minValue = FMath::Min<float>( localArray, &minIndex );
localArrayRef.Add( minIndex );
localArray.RemoveAt( minIndex );
lastMinIndex = minIndex;
}
for ( int32 i = 0; i < localArrayRef.Num(); i++ ) {
minIndex = ( localArrayRef[i] < lastMinIndex ) ? minIndex + 1 : minIndex;
}
IndexOfMinValue = minIndex; MinValue = minValue;
}
void UPPKLibraryMath::MaxFloatArray( const TArray<float>& FloatArray, const int32 NumberOfIndexToDiscard, int32& IndexOfMaxValue,
float& MaxValue ) {
if ( NumberOfIndexToDiscard < 0 || NumberOfIndexToDiscard >= FloatArray.Num() ) {
IndexOfMaxValue = -1; MaxValue = -1; return;
}
TArray<float> localArray = FloatArray; TArray<int32> localArrayRef;
int32 maxIndex = -1; int32 lastMaxIndex = -1; float maxValue = -1; int32 numdiff = 0;
for ( int32 i = -1; i < NumberOfIndexToDiscard; i++ ) {
maxValue = FMath::Max<float>( localArray, &maxIndex );
localArrayRef.Add( maxIndex );
localArray.RemoveAt( maxIndex );
lastMaxIndex = maxIndex;
}
for ( int32 i = 0; i < localArrayRef.Num(); i++ ) {
maxIndex = ( localArrayRef[i] < lastMaxIndex ) ? maxIndex + 1 : maxIndex;
}
IndexOfMaxValue = maxIndex; MaxValue = maxValue;
}
| b76404b4c3961dd77ac9268c3e8c00acb80c6a71 | [
"C++"
] | 1 | C++ | Mimand3r/PurpleprintKit | b04482fb66ebba99a434493c6b99240398ced6dc | 5d12968370f76087c52a23f6c262c59f81e3b04c |
refs/heads/master | <repo_name>lee001001/movielist<file_sep>/favorite.js
const BASE_URL = 'https://movie-list.alphacamp.io'
const INDEX_URL = BASE_URL + '/api/v1/movies/'
const POSTER_URL = BASE_URL + '/posters/'
const datapanel = document.querySelector('#data-panel')
const searchForm = document.querySelector('#search-form')
const searchInput = document.querySelector('#search-input')
//製作movies的容器
const movies = JSON.parse(localStorage.getItem('favoriteMovies'))
//movieModal製作
function showMovieModal(id) {
const movieModdalTitle = document.querySelector('#movie-modal-title')
const movieModalData = document.querySelector('#movie-modal-data')
const movieModalDescription = document.querySelector('#movie-modal-description')
const movieModdalimage = document.querySelector('#movie-modal-image')
axios
.get(INDEX_URL + id)
.then((res) => {
const data = res.data.results
movieModdalTitle.innerText = data.title
movieModalData.innerText = 'release data: ' + data.release_date
movieModalDescription.innerText = data.description
movieModdalimage.innerHTML = `
<img
src="${POSTER_URL + data.image}"
class="card-img-top" alt="Movie Poster" class="img-fluid" />
`
})
}
function renderMovieCardList(data) {
let rawHTML = ''
data.forEach((item) => {
//title , image
rawHTML += `
<div class="col-sm-3">
<div class="mb-2">
<div class="card" style="width: 18rem;">
<img
src="${POSTER_URL + item.image}"
class="card-img-top" alt="Movie Poster" />
<div class="card-body">
<h5 class="card-title">${item.title}</h5>
</div>
<div class="card-footer">
<button class="btn btn-primary btn-show-movie" data-toggle="modal" data-target="#movie-modal" data-id="${item.id}">More
</button>
<button type="button" class="btn btn-danger btn-remove-favorite" data-id="${item.id}">X</button>
</div>
</div>
</div>
</div>
`
datapanel.innerHTML = rawHTML
});
}
function removieFormfavorite(id) {
if (!movies) return
const movieIndex = movies.findIndex((movie) => movie.id === id)
if (movieIndex === -1) return
movies.splice(movieIndex, 1)
localStorage.setItem('favoriteMovies', JSON.stringify(movies))
renderMovieCardList(movies)
}
//監聽器
datapanel.addEventListener('click', function onPanelClicked(event) {
if (event.target.matches('.btn-show-movie')) {
showMovieModal(Number(event.target.dataset.id))
} else if (event.target.matches('.btn-remove-favorite')) {
removieFormfavorite(Number(event.target.dataset.id))
}
})
renderMovieCardList(movies)
| 9466615765f2d26fa94d0c4694f5f8e1db53b7cc | [
"JavaScript"
] | 1 | JavaScript | lee001001/movielist | d547e1845936bc80e184d02bff7169419096677a | f5664cab3ac3b0ddeb8ab61a70acb5c03bbff6fa |
refs/heads/master | <file_sep>#!/usr/bin/bash
#
# Wonderdump is a workaround to download SRA files directly
# when fastq-dump's internet connection does not work.
# Which can happen surprisingly frequently.
#
# Usage:
# wonderdump -X 10000 SRR1553500
set -ue
# This is where we will store the file.
SRA_DIR=~/ncbi/public/sra
# Make the directory if it does not exist.
mkdir -p $SRA_DIR
# All other parameters up to last.
PARAMS=${@:1:$(($# - 1))}
# The last parameter must be the SRR number.
SRR=${@:$#}
if [ -z "$SRR" ]
then
echo "*** Please specify an SRR number"
exit;
fi
echo "*** Getting SRR run: $SRR"
# Create the full path to the file.
SRA_FILE="$SRA_DIR/$SRR.sra"
TMP_FILE="$SRA_DIR/$SRR.tmp"
# Download only if it does not exist.
if [ ! -f $SRA_FILE ];
then
PATH1=${SRR:0:6}
PATH2=${SRR:0:10}
URL="ftp://ftp-trace.ncbi.nih.gov/sra/sra-instant/reads/ByRun/sra/SRR/${PATH1}/${PATH2}/${SRR}.sra"
echo "*** Downloading: $URL"
echo "*** Saving to: $SRA_FILE"
curl $URL > $TMP_FILE
# Move to local file only if successful.
mv $TMP_FILE $SRA_FILE
else
echo "*** SRA file found: $SRA_FILE"
fi
# Run the fastq-dump.
fastq-dump $PARAMS ${SRA_FILE}<file_sep>/* >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
batchSEQ - a simple batch program for automated downloading and processing of raw sequencing reads
into sorted BAM files for downstream applications
Requires the NCBI SRA toolkit, HISAT2, and Samtools
(c) 2018 The Hope Cancer Lab, McMaster University
DISCLAIMER: This software is provided AS IS with no otherwise implied or guaranteed warranties. The
end user assumes all potential risks involved with the use of this software, and has read and
acknowledged the terms included in the original repository's 'licence.txt.'
Use of this code is free and permissible for personal, academic, and commercial purposes including
redistribution.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
BEFORE RUNNING:
- In bash, set the PATH environment variable as follows:
export PATH=$PATH:"/c/path/to/samtools/":"/c/path/to/SRA/bin/"
- Make sure a HISAT2 genome index is downloaded from the HISAT site
- Recommended grch38_snp_tran to capture all possible transcripts
- If this is not in the C:/hisat2/index/ directory, you must specify it in the command line
by adding -gen /c/path/to/hisat2/index/grch38_snp_tran/genome
PARAMS:
-dir [directory]: The program will read from the SraRunTable file in the directory
specified by -dir and download, process, cleanup, merge, and sort
BAM files for every detected sample.
-acc [file path]: If the SraRunTable is not in the same directory as the one you
want this BAM files to be saved and processed in, you will need to specify it in
this way
-gen [directory ending in filename base]: The indexes downloaded from the John Hopkins servers
contain a common filename such as genome.ht2.1, genome.ht2.2, etc. Specify the
location that this base filename is located so that batchSeq can perform the transcript
alignments
*/
#include <stdio.h>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <chrono>
#include <thread>
#if defined WIN32 || defined __WIN32
#include <windows.h>
#elif defined __APPLE__
#include <mach-o/dyld.h>
#endif
using namespace std;
int main(int argc, char** argv){
vector<thread> allThreads; // Thread registry
unsigned int mP = 1000; // Get the executable directory
char contextPath[mP];
#if defined WIN32 || defined __WIN32
cout << "OS: WINDOWS\n";
GetCurrentDirectory(mP, contextPath);
#elif defined __APPLE__
_NSGetExecutablePath(contextPath, &mP);
cout << "OS: APPLE\n";
#endif
string accFileName, // The filename for the accession IDs as an input to this program
genomeIndex, // The hisat2 genome index to align the reads to
directory, // The directory for output
homeDir = contextPath;
for(size_t i = 0; i < homeDir.size(); ++i){ // Forward slash is universally understood as a path branch delimiter
if(homeDir[i] == '\\') homeDir[i] = '/';
}
#ifdef __APPLE__
while(homeDir.back() != '/') homeDir.pop_back(); // OSX path will contain the executable name - remove this
#endif
directory = homeDir; // By default, the directory is the path of the executable
genomeIndex = "C:/hisat2/index/grch38/genome"; // Requires hisat2 to be installed in the base drive directory
unsigned int numThreads = 4; // Default thread count of 4
for(size_t i = 0; i < argc; ++i){ // Process the arguments
if(string(argv[i]) == "-acc"){ // We require an argument with the "-acc" prefix for the accession IDs
if(i+1 < argc){
if(strchr(argv[i+1], '-') == NULL){
accFileName = argv[i+1];
++i;
}
}
}
else if(string(argv[i]) == "-gen"){ // Obtain the genome index if given
if(i+1 < argc){
if(strchr(argv[i+1], '-') == NULL){
genomeIndex = argv[i+1];
++i;
}
}
}
else if(string(argv[i]) == "-dir"){ // Obtain the desired output directory
if(i+1 < argc){
if(strchr(argv[i+1], '-') == NULL){
directory = argv[i+1];
++i;
}
}
}
else if(string(argv[i]) == "-threads"){ // Obtain the desired output directory
if(i+1 < argc){
if(strchr(argv[i+1], '-') == NULL){
try{
numThreads = (uint32_t)strtod(argv[i+1], NULL);
}catch(...){ }
++i;
}
}
}
}
if(accFileName.empty()){
accFileName = directory + "/SraRunTable.txt"; /* By default, the accession filename
is the default downloaded from the NCBI trace database for a bioproject */
}
for(size_t i = 0; i < directory.size(); ++i){
if(directory[i] == '\\') directory[i] = '/';
}
while(directory.back() == '/') directory.pop_back(); // Format to fit algorithms
system(std::string("cd ").append(homeDir).c_str());
if(access(accFileName.c_str(), X_OK)){
cout << "Could not find accession file\n";
return -1;
}
else{
cout << "Loading accession IDs from " << accFileName << "...\n";
}
// Read the accession file
FILE* accFILE = fopen(accFileName.c_str(), "rb");
size_t fileSIZE;
fseek(accFILE, 0, SEEK_END);
fileSIZE = ftell(accFILE);
fseek(accFILE, 0, SEEK_SET);
char fileData[fileSIZE];
fread(fileData, fileSIZE, sizeof(char), accFILE);
vector<vector<string>> dataMatrix(1, vector<string>());
size_t lastIndex = 0;
for(size_t i = 0; i < fileSIZE; ++i){
if((fileData[i] == '\t') || (fileData[i] == ',')){
dataMatrix.back().emplace_back();
dataMatrix.back().back().assign(fileData + lastIndex, fileData + i);
lastIndex = i+1;
}
else if(fileData[i] == '\n'){
dataMatrix.back().emplace_back();
dataMatrix.back().back().assign(fileData + lastIndex, fileData + i);
dataMatrix.emplace_back();
lastIndex = i+1;
}
}
// Interpret the table
vector<string> accIDs,
sampleIDs;
cout << "Detected table with " << dataMatrix.size()-1 << " entries" << endl;
for(size_t i = 0; i < dataMatrix[0].size(); ++i){ // Check the header for the appropriate columns
if(dataMatrix[0][i] == "Run"){
for(size_t j = 1; j < dataMatrix.size(); ++j){
if(dataMatrix[j].size() > i){
accIDs.push_back(dataMatrix[j][i]);
}
}
}
else if(dataMatrix[0][i] == "Sample_Name"){
for(size_t j = 1; j < dataMatrix.size(); ++j){
if(dataMatrix[j].size() > i){
sampleIDs.push_back(dataMatrix[j][i]);
}
}
}
}
if(accIDs.size() < 1){
cout << "Could not find accession IDs in " << accFileName << endl;
return -1;
}
cout << "Found accession IDs:\n";
unsigned int maxPrint = 30, printIndex = 0;
for(auto& ID : accIDs){
cout << '\t' << ID;
if(printIndex < sampleIDs.size()) cout << " from sample " << sampleIDs[printIndex] << '\n';
++printIndex;
if(printIndex == maxPrint) break;
}
if(accIDs.size() > maxPrint){
cout << "\t... " << accIDs.size() - maxPrint << " others\n";
}
cout << endl;
stringstream strbuf;
string fastq_1_FN,
fastq_2_FN,
SRA_FN,
sam_FN,
bam_FN,
sample_bam_FN,
acc_ID,
sample_ID;
unsigned int accIndex = 0;
for(; accIndex < accIDs.size(); ++accIndex){ // Download and process the reads one accession at a time
sample_ID = sampleIDs[accIndex];
sample_bam_FN = directory + "/" + sample_ID + ".bam";
while(!access(sample_bam_FN.c_str(), X_OK)){
cout << "Detected assembled *.BAM file for " << sample_ID << ": skipping" << endl;
while(sample_ID == sampleIDs[accIndex]) ++accIndex;
sample_ID = sampleIDs[accIndex];
sample_bam_FN = directory + "/" + sample_ID + ".bam";
}
acc_ID = accIDs[accIndex];
fastq_1_FN = directory + "/" + acc_ID + "_1.fastq";
fastq_2_FN = directory + "/" + acc_ID + "_2.fastq";
SRA_FN = "~/ncbi/public/sra/" + acc_ID + ".sra";
sam_FN = directory + "/" + acc_ID + ".sam";
bam_FN = directory + "/" + acc_ID + ".bam";
if(!access(bam_FN.c_str() ,X_OK)){
if((accIndex == accIDs.size() - 1) || // Assume *.bam files not at the end of the list are complete
!access(std::string(directory).append("/").append(accIDs[accIndex+1]).append(".bam").c_str(), X_OK)){
cout << "Detected fragment *.BAM file for accession " << acc_ID << endl;
goto checkMerge;
}
else{
cout << "Found incomplete fragment " << acc_ID << " for sample " << sample_ID << ": resuming" << endl;
}
}
cout << "Obtaining read data for " << acc_ID << "... " << endl;
strbuf << "bash wonderdump.sh -I --split-files --outdir " << directory << " " << acc_ID;
system(strbuf.str().c_str());
strbuf.str("");
cout << endl;
if(!access(fastq_1_FN.c_str(), X_OK) &&
!access(fastq_2_FN.c_str(), X_OK)){
cout << "Aligning paired-end read data into " << acc_ID << ".sam ..." << endl;
/*
HISAT2 perl script with params:
-q [fastq input]
-p 4 [4 threads]
-x [genome index]
-1 [forward read file]
-2 [reverse read file]
-S [output file]
*/
strbuf << "perl C:/hisat2/hisat2 -q -p " << numThreads << " -x "
<< genomeIndex << " -1 " << fastq_1_FN << " -2 "
<< fastq_2_FN << " -S " << sam_FN;
system(strbuf.str().c_str());
strbuf.str("");
cout << endl;
}
if(!access(fastq_1_FN.c_str(), X_OK)){ // Clean up FASTA files
remove(fastq_1_FN.c_str());
}
if(!access(fastq_2_FN.c_str(), X_OK)){
remove(fastq_2_FN.c_str());
}
if(!access(SRA_FN.c_str(), X_OK)){ // Clean up SRA file
remove(SRA_FN.c_str());
}
cout << "Converting to *.BAM format ... " << endl;
strbuf << "samtools view -bS --threads " << numThreads << ' ' << sam_FN << " > " << bam_FN;
system(strbuf.str().c_str());
strbuf.str("");
cout << endl;
if(!access(sam_FN.c_str(), X_OK)){
remove(sam_FN.c_str());
}
if(access(bam_FN.c_str(), X_OK)){
cout << "Failed to produce *.BAM format for accession " << acc_ID << endl;
cout << "Exiting...";
break;
}
else{
cout << "Successfully produced *.BAM format for accession " << acc_ID << endl;
}
checkMerge:;
if((accIndex == sampleIDs.size() - 1) ||
(sample_ID != sampleIDs[accIndex+1])){ // Merge and sort if all BAM files for this sample have been accounted for
allThreads.emplace_back([&, directory, accIDs, accIndex, sampleIDs, sample_ID,
acc_ID, sample_bam_FN, numThreads](){ // Add a new thread to merge completed fragments
// While main thread continues on
std::stringstream strbuf;
std::string sample_sorted_FN = directory + "/" + sample_ID + "_sorted.bam";
vector<string> parts; // Collect part accession IDs for this sample
int i = accIndex;
cout << "Merging:\n";
while((i >= 0) && (sampleIDs[i] == sample_ID)){
parts.insert(parts.begin(), directory + "/" + accIDs[i] + ".bam");
if(access(parts.front().c_str(), X_OK)){
cout << "Missing part: " << parts.front() << "\n";
cout << "Unable to complete sample " << sample_ID << endl;
return -1;
}
--i;
}
strbuf << "samtools merge --threads " << numThreads << " " << sample_bam_FN;
for(auto& part : parts){
cout << '\t' << part << endl;
strbuf << " " << part;
}
cout << "Into: " << sample_bam_FN << endl;
system(strbuf.str().c_str()); // Perform merge using samtools
strbuf.str("");
if(!access(sample_bam_FN.c_str(), X_OK)){
cout << "Successfully created sample *.BAM file:\n" << sample_bam_FN << endl;
for(auto& part : parts){ // Clean up parts
if(!access(part.c_str(), X_OK)){
remove(part.c_str());
}
}
strbuf << "samtools sort " << sample_bam_FN << " -o " << sample_sorted_FN;
cout << "Sorting: " << sample_bam_FN << endl;
system(strbuf.str().c_str());
strbuf.str("");
cout << endl;
if(!access(sample_sorted_FN.c_str(), X_OK)){
remove(sample_bam_FN.c_str());
rename(sample_sorted_FN.c_str(), sample_bam_FN.c_str());
}
}
else{
cout << "Unable to create sample *.BAM file:\n" << sample_bam_FN << endl;
return -1;
}
});
}
}
for(auto& thread : allThreads){ // Wait for all merge threads to finish
thread.join();
}
cout << "Processing complete" << endl;
return 0;
}
<file_sep># batchSEQ
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
batchSEQ - a simple batch program for automated downloading and processing of raw sequencing reads
into sorted BAM files for downstream applications
Requires the NCBI SRA toolkit, HISAT2, and Samtools
(c) 2018 The Hope Cancer Lab, McMaster University
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
## REQUIREMENTS:
- Strawberry Perl >= 5.28.0
- Mingw64 and development toolchains (on Windows)
- HISAT2
- Samtools and Htslib
- NCBI SRA Toolkit (for your OS)
## BEFORE RUNNING:
- In bash, set the PATH environment variable as follows (no spaces after the one following "export"):
`export PATH=$PATH:/c/path/to/samtools/:/c/path/to/SRA/bin/`
ie. `export PATH=$PATH:/c/samtools-develop/:/c/SRA/bin`
( This has to be done once on each new bash terminal startup )
- Make sure a HISAT2 genome index is downloaded from the HISAT site
- Recommended grch38_snp_tran to capture all possible transcripts
- If this is not in the C:/hisat2/index/ directory, you must specify it
in the command line by adding `-gen /c/path/to/hisat2/index/grch38_snp_tran/genome`
- Download a RunInfo table from the BioProject of interest from:
ncbi.nlm.nih.gov/Traces/study/
-Leave the filename as is (SraRunTable.txt) and move it to the directory
where you want to download and process the reads
## PARAMS:
-dir [directory]: The program will read from the SraRunTable file in the directory
specified by -dir and download, process, cleanup, merge, and sort
BAM files for every detected sample.
-acc [file path]: If the SraRunTable is not in the same directory as the one you
want this BAM files to be saved and processed in, you will need to specify it in
this way. Otherwise don't use this argument.
-gen [directory ending in filename base]: The indexes downloaded from the John Hopkins servers
contain a common filename such as genome.ht2.1, genome.ht2.2, etc. Specify the
location that this base filename is located so that batchSeq can perform the transcript
alignments.
## EXECUTION:
2 ways:
1: Run by copying into the directory where you'd like to
create the database, and entering in the bash terminal:
export PATH=$PATH:/c/path/to/samtools/:/c/path/to/SRA/bin/
cd /c/the/directory/
./batchSeq -gen [genome index]
2: Run by entering in the bash terminal:
export PATH=$PATH:/c/path/to/samtools/:/c/path/to/SRA/bin/
cd /c/the/directory/with/batchSeq
./batchSeq -dir [directory] -gen [genome index]
| f23872c7d67a58f4422ae6d32c133eca2727bdc0 | [
"Markdown",
"C++",
"Shell"
] | 3 | Shell | DamianTran/batchSeq | 9b35748b798c1ebe52b02dab97eb1b473967ec4a | a054329f9f0d773f2913dcc5527b8f78f1ec6c5a |
refs/heads/main | <file_sep>const canvas = document.getElementById('canv');
const ctx = canvas.getContext('2d');
const color = document.getElementById("color");
const range = document.getElementById("range");
console.log(ctx);
let tool = null;
canvas.addEventListener('mousedown', (e) => {
if (tool) {
if (tool == 'pencil') {
drawPencil(e)
}
if (tool == 'clearCnv') {
clearCnv(e)
}
if (tool == 'square') {
square(e)
}
if (tool == 'circle') {
circle(e)
}
if (tool == 'line') {
lineTo(e)
}
}
})
document.querySelector('#tools').addEventListener('click', buttons)
function buttons(e) {
if (e.target.dataset.tool == 'pencil') {
tool = 'pencil';
}
if (e.target.dataset.tool == 'clearCnv') {
tool = 'clearCnv';
}
if (e.target.dataset.tool == 'square') {
tool = 'square';
}
if (e.target.dataset.tool == 'circle') {
tool = 'circle';
}
if (e.target.dataset.tool == 'line') {
tool = 'line';
}
}
function circle(e) {
ctx.strokeStyle = color.value;
let x = e.offsetX;
let y = e.offsetY;
ctx.beginPath();
ctx.arc(x, y, range.value, 0, 2 * Math.PI);
ctx.fill();
}
function lineTo(e) {
}
function square(e) {
ctx.strokeStyle = color.value;
let x = e.offsetX;
let y = e.offsetY;
ctx.strokeRect(x, y, range.value, range.value);
}
function clearCnv(e) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function drawPencil(e) {
ctx.fillStyle = color.value;
let x = e.offsetX;
let y = e.offsetY;
ctx.fillRect(x, y, range.value, range.value)
}
// ctx.fillRect(100, 50, 300, 150)
// ctx.beginPath()
// ctx.ellipse(100, 100, 50, 75, Math.PI / 4, 0, 2 * Math.PI)
// ctx.fill()
// ctx.beginPath()
// ctx.ellipse(250, 100, 50, 50, Math.PI / 4, 0, 2 * Math.PI)
// ctx.stroke() | 3cc6063fe017440942cc88c8906d64da1673bcf4 | [
"JavaScript"
] | 1 | JavaScript | DENDarkness/AdobePhotoZhab | f63dbfa3a70030a2f96fa4698c921878118e697f | fa7ba9fb3b0d5183ab766ea7c9cbd87cfbd2f32c |
refs/heads/master | <repo_name>johnnygreco/mrf<file_sep>/requirements.txt
numpy
scipy
astropy>=3.0
matplotlib>=2.0
pyraf
photutils
palettable
shapely<file_sep>/examples/mrf-script.py
import sys
import os
import math
import logging
import copy
import yaml
import argparse
import logging
import numpy as np
import matplotlib.pyplot as plt
from astropy import wcs
from astropy.io import fits
from astropy.coordinates import SkyCoord, match_coordinates_sky
from astropy.table import Table, Column, hstack
from mrf.utils import (save_to_fits, Flux_Model, mask_out_stars, extract_obj, \
bright_star_mask, Autokernel, psf_bkgsub)
from mrf.utils import seg_remove_obj, mask_out_certain_galaxy
from mrf.display import display_single, SEG_CMAP, display_multiple, draw_circles
from mrf.celestial import Celestial, Star
from mrf.utils import Config
from reproject import reproject_interp
def main(argv=sys.argv[1:]):
# In non-script code, use getLogger(__name__) at module scope instead.
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO,
handlers=[logging.StreamHandler(sys.stdout),
logging.FileHandler('DF_compsub.log', mode='w')])
logger = logging.getLogger("DF_compsub.log")
# Parse the input
parser = argparse.ArgumentParser(description='This script subtract compact objects from Dragonfly image.')
parser.add_argument('--config', '-c', required=True, help='configuration file')
args = parser.parse_args()
#############################################################
#############################################################
logger.info('Open configuration file {}'.format(args.config))
# Open configuration file
with open(args.config, 'r') as ymlfile:
cfg = yaml.safe_load(ymlfile)
config = Config(cfg)
# 1. subtract background of DF, if desired
df_image = config.file.df_image
hi_res_image_blue = config.file.hi_res_image_blue
hi_res_image_red = config.file.hi_res_image_red
hdu = fits.open(config.file.df_image)
df = Celestial(hdu[0].data, header=hdu[0].header)
if config.DF.sub_bkgval:
logger.info('Subtract BACKVAL=%.1f of Dragonfly image', float(df.header['BACKVAL']))
df.image -= float(df.header['BACKVAL'])
hdu.close()
# 2. Create magnified DF image, and register high-res images with subsampled DF ones
f_magnify = config.DF.magnify_factor
resize_method = config.DF.resize_method
logger.info('Magnify Dragonfly image with a factor of %.1f:', f_magnify)
df.resize_image(f_magnify, method=resize_method);
df.save_to_fits('_df_{}.fits'.format(int(f_magnify)));
logger.info('Register high resolution image "{0}" with "{1}"'.format(hi_res_image_blue, df_image))
hdu = fits.open(hi_res_image_blue)
if 'hsc' in hi_res_image_blue:
array, _ = reproject_interp(hdu[1], df.header)
else:
array, _ = reproject_interp(hdu[0], df.header)
hires_b = Celestial(array, header=df.header)
hdu.close()
logger.info('Register high resolution image "{0}" with "{1}"'.format(hi_res_image_red, df_image))
hdu = fits.open(hi_res_image_red)
if 'hsc' in hi_res_image_red:
array, _ = reproject_interp(hdu[1], df.header)
else:
array, _ = reproject_interp(hdu[0], df.header)
hires_r = Celestial(array, header=df.header)
hdu.close()
# 3. Extract sources on hires images using SEP
sigma = config.sex.sigma
minarea = config.sex.minarea
b = config.sex.b
f = config.sex.f
deblend_cont = config.sex.deblend_cont
deblend_nthresh = config.sex.deblend_nthresh
sky_subtract = config.sex.sky_subtract
flux_aper = config.sex.flux_aper
show_fig = config.sex.show_fig
logger.info('Build flux models on high-resolution images: Blue band')
logger.info(' - sigma = %.1f, minarea = %d', sigma, minarea)
logger.info(' - deblend_cont = %.5f, deblend_nthres = %.1f', deblend_cont, deblend_nthresh)
_, _, b_imflux = Flux_Model(hires_b.image, hires_b.header, sigma=sigma, minarea=minarea,
deblend_cont=deblend_cont, deblend_nthresh=deblend_nthresh, save=True)
logger.info('Build flux models on high-resolution images: Red band')
logger.info(' - sigma = %.1f, minarea = %d', sigma, minarea)
logger.info(' - deblend_cont = %.5f, deblend_nthres = %.1f', deblend_cont, deblend_nthresh)
_, _, r_imflux = Flux_Model(hires_r.image, hires_b.header, sigma=sigma, minarea=minarea,
deblend_cont=deblend_cont, deblend_nthresh=deblend_nthresh, save=True)
# 4. Make color correction, remove artifacts as well
logger.info('Make color correction to blue band, remove artifacts as well')
col_ratio = (b_imflux / r_imflux)
col_ratio[np.isnan(col_ratio) | np.isinf(col_ratio)] = 0 # remove artifacts
save_to_fits(col_ratio, '_colratio.fits', header=hires_b.header)
color_term = config.DF.color_term
logger.info('### color_term = {}'.format(color_term))
median_col = np.nanmedian(col_ratio[col_ratio != 0])
logger.info('### median_color (blue/red) = {:.5f}'.format(median_col))
fluxratio = col_ratio / median_col
fluxratio[(fluxratio < 0.1) | (fluxratio > 10)] = 1 # remove extreme values
col_correct = np.power(fluxratio, color_term) # how to improve this correction?
save_to_fits(col_correct, '_colcorrect.fits', header=hires_b.header)
if config.DF.band == 'r':
hires_3 = Celestial(hires_r.image * col_correct, header=hires_r.header)
elif config.DF.band == 'g':
hires_3 = Celestial(hires_b.image * col_correct, header=hires_b.header)
else:
raise ValueError('config.DF.band must be "g" or "r"!')
_ = hires_3.save_to_fits('_hires_{}.fits'.format(int(f_magnify)))
# 5. Extract sources on hires corrected image
logger.info('Extracting objects from color-corrected high resolution image with:')
logger.info(' - sigma = %.1f, minarea = %d', sigma, minarea)
logger.info(' - deblend_cont = %.5f, deblend_nthres = %.1f', deblend_cont, deblend_nthresh)
objects, segmap = extract_obj(hires_3.image, b=b, f=f, sigma=sigma, minarea=minarea,
show_fig=False, flux_aper=flux_aper,
deblend_nthresh=deblend_nthresh,
deblend_cont=deblend_cont)
objects.write('_hires_obj_cat.fits', format='fits', overwrite=True)
# 6. Remove bright stars (and certain galaxies)
logger.info('Remove bright stars from this segmentation map, using SEP results. ')
logger.info('Bright star limit = {}'.format(config.star.bright_lim))
seg = copy.deepcopy(segmap)
mag = config.file.hi_res_zp - 2.5 * np.log10(abs(objects['flux']))
flag = np.where(mag < config.star.bright_lim)
for obj in objects[flag]:
seg = seg_remove_obj(seg, obj['x'], obj['y'])
objects[flag].write('_bright_stars_3.fits', format='fits', overwrite=True)
# You can Mask out certain galaxy here.
logger.info('Remove objects from catalog {}'.format(config.file.certain_gal_cat))
gal_cat = Table.read(config.file.certain_gal_cat, format='ascii')
seg = mask_out_certain_galaxy(seg, hires_3.header, gal_cat=gal_cat)
save_to_fits(seg, '_seg_3.fits', header=hires_3.header)
# 7. Remove artifacts from `hires_3` by color ratio and then smooth it
# multiply by mask created from ratio of images - this removes all objects that are
# only in g or r but not in both (artifacts, transients, etc)
mask = seg * (col_ratio != 0)
mask[mask != 0] = 1
# Then blow mask up
from astropy.convolution import Gaussian2DKernel, Box2DKernel, convolve
smooth_radius = config.fluxmodel.gaussian_radius
mask_conv = copy.deepcopy(mask)
mask_conv[mask_conv > 0] = 1
mask_conv = convolve(mask_conv.astype(float), Gaussian2DKernel(smooth_radius))
seg_mask = (mask_conv >= config.fluxmodel.gaussian_threshold)
hires_fluxmod = Celestial(seg_mask * hires_3.image, header=hires_3.header)
_ = hires_fluxmod.save_to_fits('_hires_fluxmod.fits')
logger.info('Flux model from high resolution image has been built!')
# 8. Build kernel based on some stars
img_hires = Celestial(hires_3.image.byteswap().newbyteorder(),
header=hires_3.header, dataset='cfht_3')
img_lowres = Celestial(df.image.byteswap().newbyteorder(),
header=df.header, dataset='df_3')
cval = config.kernel.cval
if isinstance(cval, str) and 'nan' in cval.lower():
cval = np.nan
else:
cval = float(cval)
logger.info('Build convolving kernel to degrade high resolution image.')
kernel_med, good_cat = Autokernel(img_hires, img_lowres,
int(f_magnify * config.kernel.kernel_size),
int(f_magnify * (config.kernel.kernel_size - config.kernel.kernel_edge)),
frac_maxflux=config.kernel.frac_maxflux,
show_figure=config.kernel.show_fig, cval=cval,
nkernels=config.kernel.nkernel)
# You can also circularize the kernel
if config.kernel.circularize:
logger.info('Circularize the kernel.')
from compsub.utils import circularize
kernel_med = circularize(kernel_med, n=14)
save_to_fits(kernel_med, '_kernel_median.fits')
# 9. Convolve this kernel to high-res image
# Two options: if you have `galsim` installed, use galsim, it's much faster.
# Otherwise, use `fconvolve` from iraf.
# Galsim solution:
import galsim
psf = galsim.InterpolatedImage(galsim.Image(kernel_med),
scale=config.DF.pixel_scale / f_magnify)
gal = galsim.InterpolatedImage(galsim.Image(hires_fluxmod.image),
scale=config.DF.pixel_scale / f_magnify)
logger.info('Convolving image, this will be a bit slow @_@ ###')
final = galsim.Convolve([gal, psf])
image = final.drawImage(scale=config.DF.pixel_scale / f_magnify,
nx=hires_3.shape[1],
ny=hires_3.shape[0])
save_to_fits(image.array, '_df_model_{}.fits'.format(int(f_magnify)), header=hires_3.header)
# Optinally remove low surface brightness objects from model:
if config.fluxmodel.unmask_lowsb:
E = hires_fluxmod.image / image.array
E[np.isinf(E) | np.isnan(E)] = 0.0
kernel_flux = np.sum(kernel_med)
print("# Kernel flux = {}".format(kernel_flux))
E *= kernel_flux
print('# Maximum of E = {}'.format(np.nanmax(E)))
im_seg = copy.deepcopy(seg)
im_highres = copy.deepcopy(hires_fluxmod.image)
im_ratio = E
im_highres_new = np.zeros_like(hires_fluxmod.image)
objects = Table.read('_hires_obj_cat.fits', format='fits')
# calculate SB limit in counts per pixel
sb_lim_cpp = 10**((config.fluxmodel.sb_lim - config.file.hi_res_zp)/(-2.5)) * (config.file.hi_res_pixelsize / f_magnify)**2
print('# SB limit in counts / pixel = {}'.format(sb_lim_cpp))
im_seg_ind = np.where(im_seg>0)
im_seg_slice = im_seg[im_seg_ind]
im_highres_slice = im_highres[im_seg_ind]
im_highres_new_slice = im_highres_new[im_seg_ind]
im_ratio_slice = im_ratio[im_seg_ind]
# loop over objects
for obj in objects[:1000]:
ind = np.where(np.isin(im_seg_slice, obj['index']))
flux_hires = im_highres_slice[ind]
flux_ratio = im_ratio_slice[ind]
if ((np.mean(flux_hires) < sb_lim_cpp) and (np.mean(flux_ratio) < config.fluxmodel.unmask_ratio)) and (np.mean(flux_ratio) != 0):
im_highres_new_slice[ind] = 1
print('# removed object {}'.format(obj['index']))
im_highres_new[im_seg_ind] = im_highres_new_slice
save_to_fits(im_highres_new, '_hires_fluxmode_clean_mask.fits')
# BLow up the mask
smooth_radius = config.fluxmodel.gaussian_radius
mask_conv = copy.deepcopy(im_highres_new)
mask_conv[mask_conv > 0] = 1
mask_conv = convolve(mask_conv.astype(float), Gaussian2DKernel(smooth_radius))
seg_mask = (mask_conv >= config.fluxmodel.gaussian_threshold)
im_highres[seg_mask] = 0
psf = galsim.InterpolatedImage(galsim.Image(kernel_med),
scale=config.DF.pixel_scale / f_magnify)
gal = galsim.InterpolatedImage(galsim.Image(im_highres),
scale=config.DF.pixel_scale / f_magnify)
logger.info('Convolving image, this will be a bit slow @_@ ###')
final = galsim.Convolve([gal, psf])
image = final.drawImage(scale=config.DF.pixel_scale / f_magnify,
nx=hires_3.shape[1],
ny=hires_3.shape[0])
save_to_fits(image.array, '_df_model_clean_{}.fits'.format(f_magnify), header=hires_3.header)
df_model = Celestial(image.array, header=hires_3.header)
res = Celestial(df.image - df_model.image, header=df.header)
res.save_to_fits('_res_{}.fits'.format(f_magnify))
df_model.resize_image(1 / f_magnify, method=resize_method)
df_model.save_to_fits('_df_model.fits')
res.resize_image(1 / f_magnify, method=resize_method)
res.save_to_fits('res.fits')
logger.info('Compact objects has been subtracted from Dragonfly image! Saved as "res.fits".')
#10. Subtract bright star halos! Only work with those left out in flux model!
star_cat = Table.read('_bright_stars_3.fits', format='fits')
star_cat['x'] /= f_magnify
star_cat['y'] /= f_magnify
ra, dec = res.wcs.wcs_pix2world(star_cat['x'], star_cat['y'], 0)
star_cat.add_columns([Column(data=ra, name='ra'), Column(data=dec, name='dec')])
sigma = config.starhalo.sigma
minarea = config.starhalo.minarea
deblend_cont = config.starhalo.deblend_cont
deblend_nthresh = config.starhalo.deblend_nthresh
sky_subtract = config.starhalo.sky_subtract
flux_aper = config.starhalo.flux_aper
show_fig = config.starhalo.show_fig
logger.info('Extracting objects from compact-object-corrected Dragonfly image with:')
logger.info(' - sigma = %.1f, minarea = %d', sigma, minarea)
logger.info(' - deblend_cont = %.5f, deblend_nthres = %.1f', deblend_cont, deblend_nthresh)
objects, segmap = extract_obj(res.image.byteswap().newbyteorder(),
b=64, f=3, sigma=sigma, minarea=minarea,
deblend_nthresh=deblend_nthresh,
deblend_cont=deblend_cont,
sky_subtract=sky_subtract, show_fig=show_fig,
flux_aper=flux_aper)
ra, dec = res.wcs.wcs_pix2world(objects['x'], objects['y'], 0)
objects.add_columns([Column(data=ra, name='ra'), Column(data=dec, name='dec')])
# Match two catalogs
logger.info('Match detected objects with {} catalog to ensure they are stars.'.format(config.starhalo.method))
temp = match_coordinates_sky(SkyCoord(ra=star_cat['ra'], dec=star_cat['dec'], unit='deg'),
SkyCoord(ra=objects['ra'], dec=objects['dec'], unit='deg'))[0]
bright_star_cat = objects[np.unique(temp)]
mag = float(df.header['MEDIANZP']) - 2.5 * np.log10(bright_star_cat['flux'])
bright_star_cat.add_column(Column(data=mag, name='mag'))
bright_star_cat.write('_bright_star_cat.fits', format='fits', overwrite=True)
# Extract stars from image
psf_cat = bright_star_cat[bright_star_cat['fwhm_custom'] < config.starhalo.fwhm_lim] # FWHM selection
psf_cat = psf_cat[psf_cat['mag'] < config.starhalo.bright_lim]
psf_cat.sort('flux')
psf_cat.reverse()
psf_cat = psf_cat[:int(config.starhalo.n_stack)]
logger.info('You get {} stars to be stacked!'.format(len(psf_cat)))
# Construct and stack `Stars`!!!.
halosize = config.starhalo.halosize
padsize = config.starhalo.padsize
size = 2 * halosize + 1
stack_set = np.zeros((len(psf_cat), size, size))
bad_indices = []
logger.info('Stacking stars!')
for i, obj in enumerate(psf_cat):
try:
sstar = Star(res.image, header=res.header, starobj=obj,
halosize=halosize, padsize=padsize)
if config.starhalo.mask_contam:
sstar.mask_out_contam(show_fig=False, verbose=False)
sstar.centralize(method='iraf')
#sstar.sub_bkg(verbose=False)
cval = config.starhalo.cval
if isinstance(cval, str) and 'nan' in cval.lower():
cval = np.nan
else:
cval = float(cval)
if config.starhalo.norm == 'flux_ann':
stack_set[i, :, :] = sstar.get_masked_image(cval=cval) / sstar.fluxann
else:
stack_set[i, :, :] = sstar.get_masked_image(cval=cval) / sstar.flux
except Exception as e:
stack_set[i, :, :] = np.ones((size, size)) * 1e9
bad_indices.append(i)
logger.info(e)
stack_set = np.delete(stack_set, bad_indices, axis=0)
median_psf = np.nanmedian(stack_set, axis=0)
median_psf = psf_bkgsub(median_psf, int(config.starhalo.edgesize))
from astropy.convolution import convolve, Box2DKernel
median_psf = convolve(median_psf, Box2DKernel(3))
save_to_fits(median_psf, 'median_psf.fits');
logger.info('Stars are stacked in to a PSF and saved as "median_psf.fits"!')
save_to_fits(stack_set, '_stack_bright_stars.fits')
## Build starhalo models and then subtract
logger.info('Draw star halo models onto the image, and subtract them!')
zp = df.header['MEDIANZP']
# Make an extra edge, move stars right
ny, nx = res.image.shape
im_padded = np.zeros((ny + 2 * halosize, nx + 2 * halosize))
# Making the left edge empty
im_padded[halosize: ny + halosize, halosize: nx + halosize] = res.image
im_halos_padded = np.zeros_like(im_padded)
for i, obj in enumerate(bright_star_cat):
spsf = Celestial(median_psf, header=df_model.header)
x = obj['x']
y = obj['y']
x_int = x.astype(np.int)
y_int = y.astype(np.int)
dx = -1.0 * (x - x_int)
dy = -1.0 * (y - y_int)
spsf.shift_image(-dx, -dy, method='iraf')
x_int, y_int = x_int + halosize, y_int + halosize
if config.starhalo.norm == 'flux_ann':
im_halos_padded[y_int - halosize:y_int + halosize + 1,
x_int - halosize:x_int + halosize + 1] += spsf.image * obj['flux_ann']
else:
im_halos_padded[y_int - halosize:y_int + halosize + 1,
x_int - halosize:x_int + halosize + 1] += spsf.image * obj['flux']
im_halos = im_halos_padded[halosize: ny + halosize, halosize: nx + halosize]
img_sub = res.image - im_halos
df_model.image += im_halos
save_to_fits(im_halos, '_df_halos.fits', header=df_model.header)
save_to_fits(img_sub, '_df_halosub.fits', header=df_model.header)
save_to_fits(df_model.image, 'df_model_halos.fits', header=df_model.header)
logger.info('Bright star halos are subtracted! Saved as "df_halosub.fits".')
# Mask out dirty things!
if config.clean.clean_img:
logger.info('Clean the image! Replace relics with noise.')
model_mask = convolve(df_model.image, Gaussian2DKernel(config.clean.gaussian_radius))
model_mask[model_mask < config.clean.gaussian_threshold] = 0
model_mask[model_mask != 0] = 1
totmask = bright_star_mask(model_mask.astype(bool), bright_star_cat,
bright_lim=config.clean.bright_lim, r=config.clean.r)
# Total mask with noise
totmask = convolve(totmask.astype(float), Box2DKernel(2))
totmask[totmask > 0] = 1
if config.clean.replace_with_noise:
from compsub.utils import img_replace_with_noise
final_image = img_replace_with_noise(res.image.byteswap().newbyteorder(), totmask)
else:
final_image = res.image * (~totmask.astype(bool))
save_to_fits(final_image, 'final_image.fits', header=res.header)
logger.info('The final result is saved as "final_image.fits"!')
# Delete temp files
if config.clean.clean_file:
logger.info('Delete all temporary files!')
os.system('rm -rf _*.fits')
logger.info('Mission finished!')
if __name__ == "__main__":
main()<file_sep>/mrf/celestial.py
import os
import copy
import scipy
import numpy as np
import matplotlib.pyplot as plt
from astropy import wcs
from astropy.io import fits
from astropy.table import Table, Column
import astropy.units as u
from astropy.coordinates import SkyCoord
from .display import display_single, SEG_CMAP
from .utils import img_cutout
from .imtools import imshift, imdelete, magnify, blkavg
class Celestial(object):
'''
Class for `Celestial` object.
'''
def __init__(self, img, mask=None, header=None, dataset='Dragonfly'):
'''Initialize `Celestial` object'''
self.header = header
self.wcs = wcs.WCS(header)
try:
self.pixel_scale = abs(header['CD1_1'] * 3600)
except:
self.pixel_scale = abs(header['PC1_1'] * 3600)
self.shape = img.shape # in ndarray format
self.dataset = dataset
self._image = img
if mask is not None:
self._mask = mask
# Sky position
ny, nx = img.shape
self.ny = ny
self.nx = nx
self.ra_cen, self.dec_cen = list(map(float, self.wcs.wcs_pix2world(ny // 2, nx // 2, 0)))
# This follows lower-left, lower-right, upper-right, upper-left.
self.ra_bounds, self.dec_bounds = self.wcs.wcs_pix2world([0, img.shape[1], img.shape[1], 0],
[0, 0, img.shape[0], img.shape[0]], 0)
self.sky_bounds = np.append(self.ra_bounds[2:], self.dec_bounds[1:3])
self.scale_bar_length = 5 # initial length for scale bar when displaying
@property
def image(self):
return self._image
@image.setter
def image(self, img_array):
self._image = img_array
@property
def mask(self):
return self._mask
@mask.setter
def mask(self, mask_array):
self._mask = mask_array
@property
def hscmask(self):
return self._hscmask
@hscmask.setter
def hscmask(self, mask_array):
self._hscmask = mask_array
@property
def variance(self):
return self._variance
@variance.setter
def variance(self, variance_array):
self._variance = variance_array
# Save 2-D numpy array to `fits`
def save_to_fits(self, fits_file_name, data='image', overwrite=True):
"""Save numpy 2-D arrays to `fits` file. (from `kungpao`)
Parameters:
data (str): can be 'image' or 'mask'
fits_file_name (str): File name of `fits` file
overwrite (bool): Default is True
Returns:
None
"""
if data == 'image':
data_use = self.image
elif data == 'mask':
data_use = self.mask
else:
raise ValueError('Data can only be "image" or "mask".')
img_hdu = fits.PrimaryHDU(data_use)
if self.header is not None:
img_hdu.header = self.header
if self.wcs is not None:
wcs_header = self.wcs.to_header()
import fnmatch
for i in wcs_header:
if i in self.header:
self.header[i] = wcs_header[i]
if fnmatch.fnmatch(i, 'PC?_?'):
self.header['CD' + i.lstrip("PC")] = wcs_header[i]
img_hdu.header = self.header
elif self.wcs is not None:
wcs_header = self.wcs.to_header()
img_hdu.header = wcs_header
else:
img_hdu = fits.PrimaryHDU(data_use)
if os.path.islink(fits_file_name):
os.unlink(fits_file_name)
img_hdu.writeto(fits_file_name, overwrite=overwrite)
return img_hdu
# Shift image/mask
def shift_image(self, dx, dy, method='iraf', order=5, cval=0.0):
'''Shift the image of Celestial object. The WCS of image will also be changed.
Parameters:
dx, dy (float): shift distance (in pixel) along x (horizontal) and y (vertical).
Note that elements in one row has the same y but different x.
Example: dx = 2 is to shift the image "RIGHT", dy = 3 is to shift the image "UP".
method (str): interpolation method. Use 'lanczos' or 'iraf'.
If using 'iraf', default interpolation is 'poly3.
order (int): the order of Lanczos interpolation (>0).
cval (scalar): value to fill the edges. Default is NaN.
Returns:
shift_image: ndarray.
'''
ny, nx = self.image.shape
if abs(dx) > nx or abs(ny) > ny:
raise ValueError('# Shift distance is beyond the image size.')
if method == 'lanczos':
try: # try to import galsim
from galsim import degrees, Angle
from galsim.interpolant import Lanczos
from galsim import Image, InterpolatedImage
from galsim.fitswcs import AstropyWCS
except:
raise ImportError('# Import `galsim` failed! Please check if `galsim` is installed!')
# Begin shift
assert (order > 0) and isinstance(order, int), 'order of ' + method + ' must be positive interger.'
galimg = InterpolatedImage(Image(self.image, dtype=float),
scale=self.pixel_scale, x_interpolant=Lanczos(order))
galimg = galimg.shift(dx=dx * self.pixel_scale, dy=dy * self.pixel_scale)
result = galimg.drawImage(scale=self.pixel_scale, nx=nx, ny=ny)#, wcs=AstropyWCS(self.wcs))
self._image = result.array
# Change the WCS of image
hdr = copy.deepcopy(self.header)
hdr['CRPIX1'] += dx
hdr['CRPIX2'] += dy
self.header = hdr
self.wcs = wcs.WCS(hdr)
self._wcs_header_merge()
return result.array
elif method == 'iraf':
self.save_to_fits('./_temp.fits', 'image')
imshift('./_temp.fits', './_shift_temp.fits', dx, dy, interp_type='poly3', boundary_type='constant')
hdu = fits.open('./_shift_temp.fits')
self.image = hdu[0].data
self.shape = hdu[0].data.shape
self.header = hdu[0].header
self.wcs = wcs.WCS(self.header)
hdu.close()
imdelete('./*temp.fits')
else:
raise ValueError("# Not supported interpolation method. Use 'lanczos' or 'iraf'.")
def shift_mask(self, dx, dy, method='iraf', order=5, cval=0.0):
'''Shift the mask of Celestial object.
Parameters:
dx, dy (float): shift distance (in pixel) along x (horizontal) and y (vertical).
Note that elements in one row has the same y but different x.
Example: dx = 2 is to shift the image "RIGHT", dy = 3 is to shift the image "UP".
method (str): interpolation method. Use 'lanczos' or 'spline' or 'iraf'
order (int): the order of spline interpolation (within 0-5) or Lanczos interpolation (>0).
cval (scalar): value to fill the edges. Default is NaN.
Returns:
shift_mask: ndarray.
'''
ny, nx = self.mask.shape
if abs(dx) > nx or abs(ny) > ny:
raise ValueError('# Shift distance is beyond the image size.')
if method == 'lanczos':
try: # try to import galsim
from galsim import degrees, Angle
from galsim.interpolant import Lanczos
from galsim import Image, InterpolatedImage
from galsim.fitswcs import AstropyWCS
except:
raise ImportError('# Import `galsim` failed! Please check if `galsim` is installed!')
# Begin shift
assert (order > 0) and isinstance(order, int), 'order of ' + method + ' must be positive interger.'
galimg = InterpolatedImage(Image(self.mask, dtype=float),
scale=self.pixel_scale, x_interpolant=Lanczos(order))
galimg = galimg.shift(dx=dx * self.pixel_scale, dy=dy * self.pixel_scale)
result = galimg.drawImage(scale=self.pixel_scale, nx=nx, ny=ny)#, wcs=AstropyWCS(self.wcs))
self._mask = result.array
# Change the WCS of image
hdr = copy.deepcopy(self.header)
hdr['CRPIX1'] += dx
hdr['CRPIX2'] += dy
self.header = hdr
self.wcs = wcs.WCS(hdr)
self._wcs_header_merge()
return result.array
elif method == 'iraf':
self.save_to_fits('./_temp.fits', 'mask')
imshift('./_temp.fits', './_shift_temp.fits', dx, dy, interp_type='poly3', boundary_type='constant')
hdu = fits.open('./_shift_temp.fits')
self.mask = hdu[0].data
self.shape = hdu[0].data.shape
self.header = hdu[0].header
self.wcs = wcs.WCS(self.header)
hdu.close()
imdelete('./*temp.fits')
else:
raise ValueError("# Not supported interpolation method. Use 'lanczos' or 'iraf'.")
def shift_Celestial(self, dx, dy, method='iraf', order=5, cval=0.0):
'''Shift the Celestial object.
Parameters:
dx, dy (float): shift distance (in pixel) along x (horizontal) and y (vertical).
Note that elements in one row has the same y but different x.
Example: dx = 2 is to shift the image "RIGHT", dy = 3 is to shift the image "UP".
method (str): interpolation method. Use 'lanczos' or 'spline'.
order (int): the order of spline interpolation (within 0-5) or Lanczos interpolation (>0).
cval (scalar): value to fill the edges. Default is NaN.
Returns:
'''
self.shift_image(dx, dy, method=method, order=order, cval=cval)
if hasattr(self, 'mask'):
self.shift_mask(dx, dy, method=method, order=order, cval=cval)
def resize_image(self, f, method='iraf', order=5, cval=0.0):
'''Zoom/Resize the image of Celestial object.
f > 1 means the image will be resampled (finer)! f < 1 means the image will be degraded.
Parameters:
f (float): the positive factor of zoom. If 0 < f < 1, the image will be resized to smaller one.
method (str): interpolation method. Use 'lanczos' or 'spline' or 'iraf'.
order (int): the order Lanczos interpolation (>0).
cval (scalar): value to fill the edges. Default is NaN.
Returns:
shift_image: ndarray.
'''
if method == 'lanczos':
try: # try to import galsim
from galsim import degrees, Angle
from galsim.interpolant import Lanczos
from galsim import Image, InterpolatedImage
from galsim.fitswcs import AstropyWCS
except:
raise ImportError('# Import `galsim` failed! Please check if `galsim` is installed!')
assert (order > 0) and isinstance(order, int), 'order of ' + method + ' must be positive interger.'
galimg = InterpolatedImage(Image(self.image, dtype=float),
scale=self.pixel_scale, x_interpolant=Lanczos(order))
#galimg = galimg.magnify(f)
ny, nx = self.image.shape
result = galimg.drawImage(scale=self.pixel_scale / f, nx=round(nx * f), ny=round(ny * f))#, wcs=AstropyWCS(self.wcs))
self.wcs = self._resize_wcs(self.image, self.wcs, f)
self._image = result.array
self.shape = self.image.shape
self._wcs_header_merge()
self.pixel_scale /= f
return result.array
elif method == 'iraf':
self.save_to_fits('./_temp.fits', 'image')
if f > 1:
magnify('./_temp.fits', './_resize_temp.fits', f, f)
else:
blkavg('./_temp.fits', './_resize_temp.fits', 1/f, 1/f, option='sum')
hdu = fits.open('./_resize_temp.fits')
self.image = hdu[0].data
self.shape = hdu[0].data.shape
self.header = hdu[0].header
self.wcs = wcs.WCS(self.header)
self.pixel_scale /= f
hdu.close()
imdelete('./*temp.fits')
else:
raise ValueError("# Not supported interpolation method. Use 'lanczos' or 'iraf'.")
def resize_mask(self, f, method='iraf', order=5, cval=0.0):
'''Zoom/Resize the mask of Celestial object.
f > 1 means the mask will be resampled (finer)! f < 1 means the mask will be degraded.
Parameters:
f (float): the positive factor of zoom. If 0 < f < 1, the mask will be resized to smaller one.
method (str): interpolation method. Use 'lanczos' or 'spline' or 'iraf'.
order (int): the order Lanczos interpolation (>0).
cval (scalar): value to fill the edges. Default is NaN.
Returns:
shift_image: ndarray.
'''
if method == 'lanczos':
try: # try to import galsim
from galsim import degrees, Angle
from galsim.interpolant import Lanczos
from galsim import Image, InterpolatedImage
from galsim.fitswcs import AstropyWCS
except:
raise ImportError('# Import `galsim` failed! Please check if `galsim` is installed!')
assert (order > 0) and isinstance(order, int), 'order of ' + method + ' must be positive interger.'
galimg = InterpolatedImage(Image(self.mask, dtype=float),
scale=self.pixel_scale, x_interpolant=Lanczos(order))
ny, nx = self.mask.shape
result = galimg.drawImage(scale=self.pixel_scale / f, nx=round(nx * f), ny=round(ny * f))#, wcs=AstropyWCS(self.wcs))
self.wcs = self._resize_wcs(self.image, self.wcs, f)
self._image = result.array
self.shape = self.mask.shape
self._wcs_header_merge()
self.pixel_scale /= f
return result.array
elif method == 'iraf':
self.save_to_fits('./_temp.fits', 'mask')
if f > 1:
magnify('./_temp.fits', './_resize_temp.fits', f, f)
else:
blkavg('./_temp.fits', './_resize_temp.fits', 1/f, 1/f, option='sum')
hdu = fits.open('./_resize_temp.fits')
self.mask = hdu[0].data
self.shape = hdu[0].data.shape
self.header = hdu[0].header
self.wcs = wcs.WCS(self.header)
self.pixel_scale /= f
hdu.close()
imdelete('./*temp.fits')
else:
raise ValueError("# Not supported interpolation method. Use 'lanczos' or 'iraf'.")
def resize_Celestial(self, f, method='iraf', order=5, cval=0.0):
'''Resize the Celestial object. f > 1 means the image will be resampled! f < 1 means the image will be degraded.
Parameters:
angle (float): rotation angle in degress, counterclockwise.
order (int): the order of spline interpolation, can be in the range 0-5.
reshape (bool): if True, the output shape is adapted so that the rorated image
is contained completely in the output array.
cval (scalar): value to fill the edges. Default is NaN.
Returns:
'''
self.resize_image(f, method=method, order=order, cval=cval)
if hasattr(self, 'mask'):
self.resize_mask(f, method=method, order=order, cval=cval)
# Display image/mask
def display_image(self, **kwargs):
display_single(self.image, scale_bar_length=self.scale_bar_length, **kwargs)
def display_mask(self, **kwargs):
display_single(self.mask, scale='linear',
cmap=SEG_CMAP, scale_bar_length=self.scale_bar_length, **kwargs)
def display_Celestial(self, **kwargs):
if hasattr(self, 'mask'):
display_single(self.image * (~self.mask.astype(bool)),
scale_bar_length=self.scale_bar_length, **kwargs)
else:
self.display_image()
class Star(Celestial):
def __init__(self, img, header, starobj, halosize=40, padsize=40, mask=None, hscmask=None):
"""Halosize is the radius!!!
RA, DEC are not supported yet!
"""
Celestial.__init__(self, img, mask, header=header)
if hscmask is not None:
self.hscmask = hscmask
self.name = 'star'
self.scale_bar_length = 3
# Trim the image to star size
# starobj should at least contain x, y, (or ra, dec) and
# Position of a star, in numpy convention
x_int = int(starobj['x'])
y_int = int(starobj['y'])
dx = -1.0 * (starobj['x'] - x_int)
dy = -1.0 * (starobj['y'] - y_int)
halosize = int(halosize)
# Make padded image to deal with stars near the edges
padsize = int(padsize)
ny, nx = self.image.shape
im_padded = np.zeros((ny + 2 * padsize, nx + 2 * padsize))
im_padded[padsize: ny + padsize, padsize: nx + padsize] = self.image
# Star itself, but no shift here.
halo = im_padded[y_int + padsize - halosize: y_int + padsize + halosize + 1,
x_int + padsize - halosize: x_int + padsize + halosize + 1]
self._image = halo
self.shape = halo.shape
self.cen_xy = [x_int, y_int]
self.dx = dx
self.dy = dy
# FLux
self.flux = starobj['flux']
self.fluxann = starobj['flux_ann']
if hasattr(self, 'mask'):
im_padded = np.zeros((ny + 2 * padsize, nx + 2 * padsize))
im_padded[padsize: ny + padsize, padsize: nx + padsize] = self.mask
# Mask itself, but no shift here.
halo = (im_padded[y_int + padsize - halosize: y_int + padsize + halosize + 1,
x_int + padsize - halosize: x_int + padsize + halosize + 1])
self._mask = halo
if hasattr(self, 'hscmask'):
im_padded = np.zeros((ny + 2 * padsize, nx + 2 * padsize))
im_padded[padsize: ny + padsize, padsize: nx + padsize] = self.hscmask
# Mask itself, but no shift here.
halo = (im_padded[y_int + padsize - halosize: y_int + padsize + halosize + 1,
x_int + padsize - halosize: x_int + padsize + halosize + 1])
self.hscmask = halo
def centralize(self, method='iraf', order=5, cval=0.0):
self.shift_Celestial(self.dx, self.dy, method=method, order=order, cval=cval)
def sub_bkg(self, verbose=True):
# Here I subtract local sky background
# Evaluate local sky backgroud within `halo_i`
# Actually this should be estimated in larger cutuouts.
# So make another cutout (larger)!
from astropy.convolution import convolve, Box2DKernel
from .image import extract_obj, seg_remove_cen_obj
from sep import Background
img_blur = convolve(abs(self.image), Box2DKernel(2))
img_objects, img_segmap = extract_obj(abs(img_blur), b=5, f=4, sigma=4.5, minarea=2, pixel_scale=self.pixel_scale,
deblend_nthresh=32, deblend_cont=0.0001,
sky_subtract=False, show_fig=False, verbose=False)
bk = Background(self.image, img_segmap != 0)
glbbck = bk.globalback
self.globalback = glbbck
if verbose:
print('# Global background: ', glbbck)
self.image -= glbbck
def get_masked_image(self, cval=np.nan):
if not hasattr(self, 'mask'):
print("This `Star` object doesn't have a `mask`!")
return self.image
else:
imgcp = copy.copy(self.image)
imgcp[self.mask.astype(bool)] = cval
return imgcp
def mask_out_contam(self, blowup=True, show_fig=True, verbose=True):
from astropy.convolution import convolve, Box2DKernel
from .utils import extract_obj, seg_remove_cen_obj
img_blur = convolve(abs(self.image), Box2DKernel(2))
img_objects, img_segmap = extract_obj(abs(img_blur), b=5, f=4, sigma=4.5, minarea=2, pixel_scale=self.pixel_scale,
deblend_nthresh=32, deblend_cont=0.0005,
sky_subtract=False, show_fig=show_fig, verbose=verbose)
# remove central object from segmap
img_segmap = seg_remove_cen_obj(img_segmap)
detect_mask = (img_segmap != 0).astype(float)
if blowup is True:
from astropy.convolution import convolve, Gaussian2DKernel
cv = convolve(detect_mask, Gaussian2DKernel(1.5))
detect_mask = (cv > 0.1).astype(float)
self.mask = detect_mask
return <file_sep>/mrf/download.py
import os
import copy
import numpy as np
from astropy import wcs
from astropy.io import fits
from astropy.table import Table, Column
from tqdm import tqdm
class TqdmUpTo(tqdm):
"""Provides `update_to(n)` which uses `tqdm.update(delta_n)`."""
def update_to(self, b=1, bsize=1, tsize=None):
"""
b : int, optional
Number of blocks transferred so far [default: 1].
bsize : int, optional
Size of each block (in tqdm units) [default: 1].
tsize : int, optional
Total size (in tqdm units). If [default: None] remains unchanged.
"""
if tsize is not None:
self.total = tsize
self.update(b * bsize - self.n) # will also set self.n = b * bsize
def megapipe_query_sql(ra, dec, size):
''' Return SQL query sentence of CFHT megapipe
Parameters:
ra, dec: float, in degree
size: float, in degree.
Returns:
url: need to be opened by `wget` or `curl`
'''
return ("https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/sync?REQUEST=doQuery&LANG=ADQL&FORMAT=CSV&QUERY="
"SELECT * "
"FROM caom2.Observation AS o JOIN caom2.Plane AS p ON o.obsID=p.obsID "
"WHERE INTERSECTS(p.position_bounds, CIRCLE('ICRS', " + str(ra) + ', ' + str(dec) + ', ' + str(size) + ')) = 1 '
"AND p.calibrationLevel >= 1 AND o.collection='CFHTMEGAPIPE' ")
#"AND o.observationID LIKE 'MegaPipe%'")
def get_megapipe_catalog(ra, dec, size, output_filename='_megapipe_cat.csv', overwrite=True):
''' Download CFHT MegaPipe frame catalog of given (ra, dec) and image size.
Parameters:
ra, dec: float, in degree
size: use `astropy.units`. e.g. `size = 300 * u.arcsec`.
If not in `astropy.units` form, then default units are
'arcsec'.
output_filename: string. The file will be saved here.
overwrite: bool, it will overwrite the catalog if `overwrite=True`.
Returns:
None
'''
import astropy.units as u
if str(size).replace('.', '', 1).isdigit():
size = size * u.arcsec
size_deg = size.to(u.degree).value
print('# Retrieving CFHT MegaPipe catalog!')
sql = megapipe_query_sql(ra, dec, size_deg)
if os.path.isfile(output_filename):
if overwrite:
os.remove(output_filename)
os.system("wget -O " + output_filename + ' ' + '"' + sql + '"')
print('# CFHT MegaPipe catalog retrieved successfully! It is saved as ' + output_filename)
else:
raise FileExistsError('!!!The catalog "' + output_filename + '" already exists!!!')
else:
os.system("wget -O " + output_filename + ' ' + '"' + sql + '"')
print('# CFHT MegaPipe catalog retrieved successfully! It is saved as ' + output_filename)
def overlap_fraction(img, header, frame, is_print=True):
# Frame is one row of mega_cat.
from shapely.geometry import Polygon
w = wcs.WCS(header)
ra_bound = list(map(float, frame['position_bounds'].split(' ')))[0::2]
dec_bound = list(map(float, frame['position_bounds'].split(' ')))[1::2]
x_bound, y_bound = w.wcs_world2pix(ra_bound, dec_bound, 0)
img_bound = Polygon(list(zip([0, img.shape[1], img.shape[1], 0],
[0, 0, img.shape[0], img.shape[0]])))
frame_bound = Polygon(list(zip(x_bound, y_bound)))
if frame_bound.contains(img_bound):
if is_print:
print('# The intersection accounts for 100 %')
return 1
elif not frame_bound.overlaps(img_bound):
print('# No Intersection!')
return 0
else:
intersect = frame_bound.intersection(img_bound)
if is_print:
print('# The intersection accounts for {} %'.format(
round(intersect.area / img_bound.area * 100, 2)))
return intersect.area / img_bound.area
def wget_cfht(frame, band, output_dir, output_name, overwrite=True):
### Download frame ###
#from compsub.utils import TqdmUpTo
import urllib
print('# Downloading Frame ... Please Wait!!!')
URL = 'https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub/CFHTSG/' + frame[
'productID'] + '.fits'
filename = output_name + '_' + band + '.fits'
if not os.path.isfile(filename):
with TqdmUpTo(unit='B', unit_scale=True, miniters=1, desc=frame['productID']) as t: # all optional kwargs
urllib.request.urlretrieve(URL, filename=output_dir + filename,
reporthook=t.update_to, data=None)
print('# Downloading ' + filename + ' finished! ')
elif os.path.isfile(filename) and overwrite:
os.remove(filename)
with TqdmUpTo(unit='B', unit_scale=True, miniters=1, desc=frame['productID']) as t: # all optional kwargs
urllib.request.urlretrieve(URL, filename=output_dir + filename,
reporthook=t.update_to, data=None)
print('# Downloading ' + filename + ' finished! ')
elif os.path.isfile(filename) and not overwrite:
print('!!!The image "' + output_dir + filename + '" already exists!!!')
return
def download_cfht_megapipe(img, header, band='g', mega_cat_dir='_megapipe_cat.csv',
output_dir='./', output_name='CFHT_megapipe_img', overwrite=True):
''' Download CFHT MegaPipe frame catalog of given (ra, dec) and image size.
This could be really **TIME CONSUMING**!!!
Parameters:
img (numpy 2-D array): input image, usually low-resolution image (such as Dragonfly).
header (astropy.io.fits.header object): header of the input image.
band (string): such as 'g' ('G') and 'r' ('R').
mega_cat_dir (string): the directory of MegaPipe catalog,
which is downloaded by `get_megapipe_catalog`.
output_dir (string): the CFHT images will be downloaded here.
output_name (string): name of CFHT images, as you can change
overwrite: bool, it will overwrite the image if `overwrite=True`.
Returns:
None
'''
print('# Removing frames with small overlaps from the MegaPipe catalog ...')
if not os.path.isfile(mega_cat_dir):
raise ValueError('Cannot find MegaPipe catalog at: "' + mega_cat_dir + '"!')
else:
mega_cat = Table.read(mega_cat_dir, format='pandas.csv')
print('# Selecting frames with given filter ...')
mega_cat = mega_cat[[band.lower() in item for item in mega_cat['energy_bandpassName'].data]]
w = wcs.WCS(header)
# Listen, in w.wcs_pix2world(), it's (x, y) on the image (x along horizontal/RA, y along vertical/DEC)!!!!
ra_cen, dec_cen = w.wcs_pix2world(img.shape[1]//2, img.shape[0]//2, 0)
ra_corner, dec_corner = w.wcs_pix2world([0, img.shape[1], img.shape[1], 0],
[0, 0, img.shape[0], img.shape[0]], 0)
# Calculate the overlap between the given image and each CFHT frame
overlap = [overlap_fraction(img, header, frame, is_print=False) for frame in mega_cat]
mega_cat.add_column(Column(data = np.array(overlap), name='overlap'))
mega_cat.sort('overlap')
mega_cat.reverse()
overlap = mega_cat['overlap'].data
mega_cat.write(mega_cat_dir, format='pandas.csv')
if np.amax(overlap) >= 0.6:
mega_cat = mega_cat[overlap > 0.6]
status = 'good'
else:
mega_cat = mega_cat[(overlap >= 0.3)]
status = 'bad'
# Download multiple images
if any(['MegaPipe' in obj['productID'] for obj in mega_cat]):
flag = ['MegaPipe' in obj['productID'] for obj in mega_cat]
frame_list = mega_cat[flag]
# MegaPipe.xxx image doesn't have an exposure time
print('# The frame to be downloaded is ', frame_list['productID'].data)
for i, frame in enumerate(frame_list):
wget_cfht(frame, band=band, output_dir=output_dir,
output_name=output_name + '_' +str(i), overwrite=overwrite)
else: # Select those with longest exposure time
print('# Choosing the frame with longest exposure: ' + str(np.amax(mega_cat['time_exposure'])) + 's!')
frame = mega_cat[np.argmax(mega_cat['time_exposure'])]
print('# The frame to be downloaded is ' + frame['productID'])
wget_cfht(frame, band=band, output_dir=output_dir,
output_name=output_name, overwrite=overwrite)
def download_highres(lowres_dir, high_res='hsc', band='g', overwrite=False):
''' Download high resolution image which overlaps with the given low resolution image.
This could be **TIME CONSUMING**!
Parameters:
lowres_dir (string): the directory of input low-resolution image.
high_res (string): name of high-resolution survey, now support 'HSC' and 'CFHT'.
band (string): name of filter, typically 'g' or 'r'.
overwrite: bool, it will overwrite the image if `overwrite=True`.
Returns:
None
'''
from astropy.coordinates import SkyCoord
import astropy.units as u
from astropy import wcs
hdu = fits.open(lowres_dir)
img = hdu[0].data
header = hdu[0].header
w = wcs.WCS(header)
hdu.close()
# Calculate the (diagnal) size of image in degrees
c1 = SkyCoord(float(w.wcs_pix2world(0, 0, 0)[0]),
float(w.wcs_pix2world(0, 0, 0)[1]),
frame='icrs', unit='deg')
c2 = SkyCoord(float(w.wcs_pix2world(img.shape[1], img.shape[0], 0)[0]),
float(w.wcs_pix2world(img.shape[1], img.shape[0], 0)[1]),
frame='icrs', unit='deg')
c_cen = SkyCoord(float(w.wcs_pix2world(img.shape[1]//2, img.shape[0]//2, 0)[0]),
float(w.wcs_pix2world(img.shape[1]//2, img.shape[0]//2, 0)[1]),
frame='icrs', unit='deg')
print('# The center of input image is: ', c_cen.ra, c_cen.dec)
radius = c1.separation(c2).to(u.degree)
print('# The diagnal size of input low-resolution image is ' + str(radius))
if high_res.lower() == 'hsc':
if radius / 1.414 > 2116 * u.arcsec:
raise ValueError('# Input image size is too large for HSC! Try other methods!')
from unagi import hsc
from unagi.task import hsc_cutout, hsc_tricolor, hsc_check_coverage
# Setup HSC server
pdr2 = hsc.Hsc(dr='pdr2', rerun='pdr2_wide')
#pdr2 = hsc.Hsc(dr='dr2', rerun='s18a_wide')
# Check if it is within the footprint
cover = hsc_check_coverage(c_cen, archive=pdr2, verbose=False, return_filter=True)
if len(cover) == 0:
raise ValueError('# This region is NOT in the footprint of HSC PDR2!')
# Angular size (must with unit!)
else:
if os.path.isfile('hsc_cutout_' + band):
if not overwrite:
raise FileExistsError('# hsc_cutout_' + band + 'already exists!')
else:
cutout = hsc_cutout(c_cen,
cutout_size=radius / np.sqrt(2) / 2,
filters=band,
archive=pdr2,
use_saved=False,
mask=False,
variance=False,
output_dir='./',
prefix='hsc_cutout',
verbose=True,
save_output=True)
cutout.close()
elif high_res.lower() == 'cfht':
get_megapipe_catalog(c_cen.ra.value, c_cen.dec.value, radius / 2)
download_cfht_megapipe(img, header, band=band.upper(), output_dir='./', overwrite=overwrite)
else:
raise ValueError('# This survey is not supported yet. Please use "HSC" or "CFHT"!')
return
| adf60ace632d9958d2c555a4dadc6b9a4c872532 | [
"Python",
"Text"
] | 4 | Text | johnnygreco/mrf | e7d5d30c03b9b273fb3537da591acf9c19030eeb | 5d515dda630ab4ed2367bfec20434a0c07149169 |
refs/heads/master | <repo_name>jul-k/tic-tac-toe<file_sep>/app/scripts/controllers/screen.js
'use strict';
/**
* @ngdoc function
* @name ticTacToeApp.controller:ScreenCtrl
* @description
* # ScreenCtrl
* Controller of the ticTacToeApp
*/
var app = angular.module('ticTacToeApp');
app.controller('ScreenCtrl', ['$scope', '$location', function ($scope, $location) {
$scope.choice = 'X';
$scope.start = function () {
$location.path('/game/' + $scope.choice);
};
}]);
<file_sep>/app/scripts/controllers/main.js
'use strict';
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
/**
* @ngdoc function
* @name ticTacToeApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the ticTacToeApp
*/
var app = angular.module('ticTacToeApp');
app.controller('MainCtrl', ['$scope', '$routeParams', '$timeout', '$location', function ($scope, $routeParams, $timeout, $location) {
$scope.init = function() {
$scope.board = [
[null, null, null],
[null, null, null],
[null, null, null]
];
$scope.turnNumber = 1;
$scope.currentPlayer = 'X';
$scope.wait = false;
$scope.human = $routeParams.player;
if ($scope.human === 'X'){
$scope.robot = 'O';
} else {
$scope.robot = 'X';
$timeout(function() {
$scope.aiTurn($scope.robot);
$scope.turnNumber++;
$scope.currentPlayer = $scope.human;
}, 500);
}
}
$scope.init();
$scope.update = function (index, row) {
if (row[index] !== null || $scope.wait) {
return;
}
row[index] = $scope.human;
$scope.turnNumber++;
if ($scope.isWin()){
notie.alert(1, 'Player ' + $scope.human + ' won', 3);
$timeout($scope.init, 2000);
return;
}
$scope.currentPlayer = $scope.robot;
$scope.wait = true;
$timeout(function () {
$scope.aiTurn($scope.robot);
$scope.turnNumber++;
if ($scope.isWin()){
notie.alert(1, 'Player ' + $scope.robot + ' won', 3);
$timeout($scope.init, 2000);
return;
}
$scope.currentPlayer = $scope.human;
if ($scope.isFull()) {
$scope.tie();
}
$scope.wait = false;
}, 1000);
};
$scope.isFull = function() {
for (var i = 0; i < $scope.board.length; i++) {
for (var j = 0; j < $scope.board[i].length; j++) {
if($scope.board[i][j] === null) {
return false;
}
}
}
return true;
};
$scope.getAllPossibleLines = function(board) {
var lines = [];
_.each(board, function (el) {
lines.push(el);
});
_.each(_.unzip(board), function (el) {
lines.push(el);
});
var diagonal = [];
for (var i = 0; i < $scope.board.length; i++) {
for (var j = 0; j < $scope.board[i].length; j++) {
if (i == j) {
diagonal.push($scope.board[i][j]);
}
}
}
lines.push(diagonal);
// backward diagonal
var diagonal = [];
for (var i = 0; i < $scope.board.length; i++) {
for (var j = 0; j < $scope.board[i].length; j++) {
if ((i + j) === $scope.board[i].length - 1) {
diagonal.push($scope.board[i][j]);
}
}
}
lines.push(diagonal);
return lines;
};
$scope.isWin = function() {
function verifyArray(array) {
var vals = _.uniq(array);
if (vals.length != 1) {
return false;
}
return vals[0] != null;
}
var lines = $scope.getAllPossibleLines($scope.board);
var ok = _.map(lines, verifyArray); // -> [bool]
if (_.any(ok)){
return true;
}
return false;
};
$scope.aiTurn = function (whoAmI) {
whoAmI = whoAmI || 'O';
function hasPlaceToWin(array) {
var vals = _.uniq(array);
if (vals.length !== 2) {
return false;
}
if (vals.indexOf(null) === -1){
return false;
}
if ( _.filter(array, function (el) {
return el === null;
}).length != 1){
return false;
}
return array;
}
var lines = $scope.getAllPossibleLines($scope.board);
var spotes = _.map(lines, hasPlaceToWin); // [false, false, ['X', null, 'X'], ['O', 'O', null]]
var vals = _.filter(spotes, function (el) {
return el;
});
function resolveIndex(array) {
var nullIndex = array.indexOf(null);
var lineIndex = lines.indexOf(array);
var i, j;
if (lineIndex < 3) {
i = lineIndex;
j = nullIndex
}
else if (lineIndex < 6 && lineIndex >= 3) {
i = nullIndex;
j = lineIndex % 3;
}
else if (lineIndex == 6) {
i = nullIndex;
j = nullIndex;
}
else if (lineIndex == 7) {
i = nullIndex;
j = 2 - nullIndex;
}
return [i, j];
}
var prioritizedMovesToWin = _.map(vals, resolveIndex)
console.log(prioritizedMovesToWin);
if (prioritizedMovesToWin.length >= 1){
var k, m;
k = prioritizedMovesToWin[0][0];
m = prioritizedMovesToWin[0][1];
$scope.board[k][m] = whoAmI;
} else {
console.log('Random move');
var k, m;
var attempts = 100;
while (true) {
k = getRandomInt(0, 3);
m = getRandomInt(0, 3);
if ($scope.board[k][m] === null) {
$scope.board[k][m] = whoAmI;
break;
}
attempts--;
if (attempts < 0) {
$scope.tie();
break;
}
}
}
return $scope.board;
};
$scope.tie = function () {
notie.alert(1, 'It\'s a tie', 3);
$scope.init();
$scope.turnNumber = 0;
};
$scope.back = function () {
$location.path('/game/');
}
}]);
| e2297c36679ca98ba6c957e1780ada9ae3ed8dc0 | [
"JavaScript"
] | 2 | JavaScript | jul-k/tic-tac-toe | 9aec91613e6e528fb7115311fbad0a5ed8e15605 | b28322685077bd535dfee9f0d61d24d5f8ff2742 |
refs/heads/main | <file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-legs',
templateUrl: './legs.page.html',
styleUrls: ['./legs.page.scss'],
})
export class LegsPage implements OnInit {
constructor(private router : Router){}
gotoHome(){
this.router.navigate(['./home']);
}
ngOnInit() {
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { AbsPageRoutingModule } from './abs-routing.module';
import { AbsPage } from './abs.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
AbsPageRoutingModule
],
declarations: [AbsPage]
})
export class AbsPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: 'home',
loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'push',
loadChildren: () => import('./push/push.module').then( m => m.PushPageModule)
},
{
path: 'pull',
loadChildren: () => import('./pull/pull.module').then( m => m.PullPageModule)
},
{
path: 'legs',
loadChildren: () => import('./legs/legs.module').then( m => m.LegsPageModule)
},
{
path: 'abs',
loadChildren: () => import('./abs/abs.module').then( m => m.AbsPageModule)
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep># FitApp
A simple mobile application that details a push ,pull ,legs workout routine.
The application is made using the ionic framework in cordova.
It can be compiled to run on iOS ,Android or as a progressive web app.
The application was made using ionic 5.
# Requirements
Node.js(npm)
Cordova
Ionic 5
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-abs',
templateUrl: './abs.page.html',
styleUrls: ['./abs.page.scss'],
})
export class AbsPage implements OnInit {
constructor(private router : Router){}
gotoHome(){
this.router.navigate(['./home']);
}
ngOnInit() {
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { PullPageRoutingModule } from './pull-routing.module';
import { PullPage } from './pull.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
PullPageRoutingModule
],
declarations: [PullPage]
})
export class PullPageModule {}
| 879922d84010c3be4a8637a5088de6c43e5c91d5 | [
"Markdown",
"TypeScript"
] | 6 | TypeScript | jaggerjack61/FitApp | 4cd5a59eae8f5ea9f982588d68362e0078b16409 | 01dadc3b99f289f341ce83ee7f582d543b638ccc |
refs/heads/master | <repo_name>tmongero/salt-config-example<file_sep>/jenkins/phpmd.sh
#!/bin/bash
pear channel-discover pear.phpmd.org
pear channel-discover pear.pdepend.org
pear install --alldeps phpmd/PHP_PMD
if [ ! which phpmd ]; then
exit 1
fi
<file_sep>/php_fpm/apc.ini
; http://stackoverflow.com/a/7207587
extension=apc.so
apc.enabled=1
apc.shm_segments=1
; try 32M per WP install and go from there
apc.shm_size=300M
; Relative to approx cached PHP files
apc.num_files_hint=2048
; Relative to approx WP size W/ APC Object Cache Backend
apc.user_entries_hint=4096
apc.ttl=7200
apc.use_request_time=1
apc.user_ttl=7200
apc.gc_ttl=3600
apc.cache_by_default=1
apc.filters
apc.mmap_file_mask=/tmp/apc.XXXXXX
apc.file_update_protection=2
apc.enable_cli=0
apc.max_file_size=4M
;This should be used when you are finished with PHP file changes.
;As you must clear the APC cache to recompile already cached files.
;If you are still developing, set this to 1.
apc.stat=1
; Prevent slam warnings
; http://stackoverflow.com/a/6469096
apc.slam_defense=0
apc.stat_ctime=0
apc.canonicalize=1
apc.write_lock=1
apc.report_autofilter=0
apc.rfc1867=0
apc.rfc1867_prefix=upload_
apc.rfc1867_name=APC_UPLOAD_PROGRESS
apc.rfc1867_freq=0
apc.rfc1867_ttl=3600
;This MUST be 0, WP can have errors otherwise!
apc.include_once_override=0
apc.lazy_classes=0
apc.lazy_functions=0
apc.coredump_unmap=0
apc.file_md5=0
apc.preload_path
<file_sep>/jenkins/phpunit.sh
#!/bin/bash
pear upgrade pear
pear channel-discover pear.phpunit.de
pear channel-discover components.ez.no
pear channel-discover pear.symfony.com
pear install --alldeps phpunit/PHPUnit
if [ ! which phpunit ]; then
exit 1
fi
<file_sep>/readme.md
AppThemes SaltStack (Configuration Management Sources)
------------------------------------------------------
In August 2012 we started working on a new infrastructure for our [website](http://appthemes.com).
We chose SaltStack to be the tool that handles any operation
within this new infrastructure (from configuration management to deployments).
This repository is a snapshot of our salt `sls` files (with sensitive parts removed).
The idea is to help other interested parties in getting familiar
with SaltStack and share some of our experience/knowledge while working with it.
Our stack is basically LEMP - Ubuntu, Nginx, MySQL and PHP (WordPress). We use Git a lot.
Hints on what might be interesting while browsing this repository:
* `sls` files organization (it should deploy just by using `state.sls`)
* `vhosts` folder
* `apt` folder
* `monit` folder
* `jenkins` folder
* `firewall` folder
| 55414da69abfbeb1bbdbb7d23a918f9f90df2425 | [
"Markdown",
"INI",
"Shell"
] | 4 | Shell | tmongero/salt-config-example | 6414b5913abd66c2a32a21559d9af16ed1b706d2 | ec013858655b35d256cf79de4e93848c1833e878 |
refs/heads/master | <repo_name>msa190/divisaodeganhos<file_sep>/carteira.py
#encoding: utf-8
import os
entradao = open('entrada.txt', 'r')
entradai = open('entrada.txt','a')
divisao1 = open('divisao.txt', 'r')
divisao = []
razao = []
for i in divisao1:
divisao.append(i.split(';')[0])
razao.append((i.split(';')[1]))
def ganho():
nome = raw_input('Qual o nome para o ganho? ')
valor = raw_input('Quanto ganhou? ')
dia = input('Que dia?(dois digitos) ')
mes = input('Quem mes?(dois digitos) ')
ano = input('Em que ano?(quatro digitos) ')
string = str(nome) + ';' + str(valor) + ';' + str(dia)+';' +str(mes)+ ';' + str(ano)+';'+'\n'
entradai.write(string)
for i, j in enumerate(divisao[1:]):
carteira = open(j,'a')
carteira.write(str(nome) + ';' + str(float(valor)*float(razao[i+1])) + ';' + str(dia)+';' +str(mes)+ ';' + str(ano)+';'+'\n')
print string
def registro(ano,mes):
for i in entradao:
anox = i.split(';')[4]
mesx = i.split(';')[3]
string = i.split(';')[0] +' '+ i.split(';')[1] +' '+ i.split(';')[2] +' '+ i.split(';')[3]+' '+ i.split(';')[4]
if str(anox) == str(ano) and str(mesx) == str(mes):
print string
def verifica_razao(razao1):
soma = 0
for i in razao[1:]:
i = float(i)
soma = soma + i
if soma+razao1 < 1:
print 'Atenção, seu dinheiro não está todo dividido'
return 1
if soma + razao1 >1:
if soma > 1:
print 'Erro ao cadastrar divisao: Seu dinheiro está todo dividido, exclua alguma carteira'
return 0
else:
print 'Erro ao cadastrar divisao: Escolha outra razão, restam apenas ' + str(1-soma)
return 0
def cadastro_carteira(nome, razao):
divisaoin = open('divisao.txt','a')
if verifica_razao(razao) == 1:
divisaoin.write(nome+'.txt'+';'+str(razao)+';'+'\n')
else:
pass
class Usuario():
def __init__(self, nome='', idade=0):
self.nome = nome
self.idade = idade
def setNome(self,nome):
self.nome = nome
def setIdade(self,idade):
self.idade = idade
def takeRatio(self):
pass#assumir um conjunto de carteiras e razões
class Carteira():
def __init__(self, nome='a', razao = 0, saldo = 0):
self.nome = nome
self.razao = razao
self.saldo = saldo
entrada = open(self.nome+'.txt', 'a')
def gasto(self, valor=0, nome = '', dia = '', mes = '', ano = ''):
entrada.write(nome+';'+str(-valor)+str(dia)+str(mes)+str(ano))
def ganho(self, valor=0, nome = '', dia = '', mes = '', ano = ''):
entrada.write(nome+';'+str(valor)+str(dia)+str(mes)+str(ano))
entradas = []
for linha in entrada:
entradas.append(linha)
for linha in entradas[1:]:
self.saldo = self.saldo + float(linha.split(';')[1])
#viagem = Carteira('viagem',0.1,200)
<file_sep>/README.md
# divisaodeganhos
Modelo de economia e divisão de ganhos e despesas - ideal para autônomos
| deb264f1214db60664730cb1b7178e3d6e54330e | [
"Markdown",
"Python"
] | 2 | Python | msa190/divisaodeganhos | b3d46045f840cea7e8feb6183fc36e3e3e70c3b1 | eacaed8909d481ce1b7c61bdbc19ad5c3333649b |
refs/heads/master | <repo_name>scrbonilla/fighta<file_sep>/app/controllers/homepage_controller.rb
class HomepageController < ApplicationController
skip_before_action :require_signin, only: [:home]
def home
end
end
| 114f777e494799a8243d279350c495e1aa144093 | [
"Ruby"
] | 1 | Ruby | scrbonilla/fighta | ee4fb0fbc2bb8285d6ddc7ac8e0ffc5036068864 | e11f56b8b311003c27f5be0edbe1795ac636caa1 |
refs/heads/master | <file_sep>/** Authors & Student Number:
<NAME> 200286902
Date Modified: 08-18-2016
Short Version History: This is a Home Controller.
File Description: The home controller decides what to do wth the home view.
**/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace COMP2006_S2016_FinalExamV2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}<file_sep># COMP2006-S2016-FinalExamV2 | 89400e0e5205d313a58ada318b2b50e61e99b41e | [
"Markdown",
"C#"
] | 2 | C# | FlyingArs/COMP2006-S2016-FinalExamV2 | f18f048ef1a0457052a29565864584cc469ff616 | 533f0839e82101ab13a114699afa3a6fb72454e6 |
refs/heads/master | <file_sep>class CommandLineArg{
public static void main(String args[]){
//marks of 3 subjects with total and avg
System.out.println("Sub 1:"+args[0]);
System.out.println("Sub 2:"+args[1]);
System.out.println("Sub 3:"+args[2]);
System.out.println("Total:"+args[3]);
System.out.println("Avg:"+args[4]);
}
} | 9179854d9ffb7c82598fefc0e6cb42e4768dc11b | [
"Java"
] | 1 | Java | Sanduni93/Input-method-in-java | 66000faaf4913eb25999a5917648c51031102098 | 152401d4ac538a6a6ac81a0fd042ffb7488b0fe4 |
refs/heads/master | <repo_name>yuxiqian/electsys-utility<file_sep>/Electsys Utility/Electsys Utility/ExamKits/ExamConst.swift
//
// ExamConst.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
class ExamConst {
static let requestUrl = "http://i.sjtu.edu.cn/kwgl/kscx_cxXsksxxIndex.html?doType=query&gnmkdm=N358105"
static let termTable = ["", "3", "12", "16"]
}
<file_sep>/.github/ISSUE_TEMPLATE/---bug.md
---
name: 报告 Bug
about: 提交关于此程序的问题
---
**Bug 描述**
**您的操作系统版本**
- macOS 版本 [e.g. Sierra]
- Version [e.g. 10.12.6]
**复现问题的步骤**
1. 转到 '...'
2. 点击 '....'
3. 向下滚动到 '....'
4. 发生错误
**预期行为**
正常情况下预计应该发生的行为
**屏幕截图**
如果方便的话,能附上问题出现的屏幕截图就更棒了
**更多信息**
<file_sep>/Electsys Utility/Electsys Utility/UIKits/MainTabViewController.swift
//
// MainTabViewController.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/12/27.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Cocoa
class MainTabViewController: NSTabViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
override func viewWillAppear() {
(self.children[3] as! jAccountViewController).UIDelegate = (self.parent as! MainViewController)
// (self.children[3] as! jAccountViewController).htmlDelegate = (self.children[4] as! ResolveViewController)
//
// (self.children[5] as! ExamSyncViewController).accountDelegate = (self.children[3] as! jAccountViewController)
// (self.children[5] as! ExamSyncViewController).UIDelegate = (self.parent as! MainViewController)
}
@IBOutlet weak var featureTabView: NSTabView!
}
<file_sep>/Electsys Utility/Electsys Utility/ScoreKits/NGScore.swift
//
// NGScore.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
struct NGScore: Codable {
var classId: String?
var scorePoint: Float?
var holderSchool: String?
var teacher: String?
var courseCode: String?
var courseName: String?
var status: String?
/* It's likely that's not a number but an level */
var finalScore: Int?
var credit: Float?
}
<file_sep>/Electsys Utility/AdaptableTableView/Adapter/AdapterTableView.swift
//
// AdapterTableView.swift
// TableView
//
// Created by <NAME> on 07/10/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class AdapterTableView: NSObject {
fileprivate static let columns = ["nameColumn", "valueColumn"]
fileprivate static let heightOfRow: CGFloat = 18.0
fileprivate var items: [Property] = [Property]() {
didSet {
tableView.reloadData()
}
}
private var tableView: NSTableView
init(tableView: NSTableView) {
self.tableView = tableView
super.init()
self.tableView.dataSource = self
self.tableView.delegate = self
// self.tableView.usesAlternatingRowBackgroundColors = true
self.tableView.backgroundColor = .clear
}
func add(items: [Property]) {
self.items += items
}
}
extension AdapterTableView: NSTableViewDelegate, NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return items.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if tableColumn?.identifier.rawValue == "nameColumn" {
let name = items[row].name
let view = NSTextField(string: name)
view.isEditable = false
view.isBordered = false
view.backgroundColor = .clear
view.textColor = .secondaryLabelColor
view.alignment = .right
return view
} else if tableColumn?.identifier.rawValue == "valueColumn" {
let value = items[row].value
let view = NSTextField(string: value)
view.isEditable = false
view.isBordered = false
view.backgroundColor = .clear
view.lineBreakMode = .byTruncatingTail
return view
} else {
let error = "???"
let view = NSTextField(string: error)
view.isEditable = false
view.isBordered = false
view.backgroundColor = .clear
return view
}
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return AdapterTableView.heightOfRow
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
tableView.deselectAll(tableView)
return true
}
}
<file_sep>/Electsys Utility/Electsys Utility/LoginKits/LoginConst.swift
//
// LoginConst.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/12.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
class LoginConst {
static let masterDomain = ".sjtu.edu.cn"
static let initUrl = "https://i.sjtu.edu.cn/"
static let loginUrl = "https://i.sjtu.edu.cn/jaccountlogin"
static let logOutUrl = "https://i.sjtu.edu.cn/xtgl/login_slogin.html"
static let captchaUrl = "https://jaccount.sjtu.edu.cn/jaccount/captcha"
static let postUrl = "https://jaccount.sjtu.edu.cn/jaccount/ulogin"
static let mainPageUrl = "https://i.sjtu.edu.cn/xtgl/index_initMenu.html"
}
<file_sep>/Electsys Utility/Electsys Utility/LegacyExamSyncKits/Exam.swift
//
// Exam.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/9/6.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Foundation
class Exam {
var name: String?
var location: String?
var teacher: String?
var startDate: Date?
var endDate: Date?
func generatePrompt() -> String {
return "\(teacher ?? "某老师")「\(name ?? "某节课程")」@ \(location ?? "某地")"
}
}
<file_sep>/Electsys Utility/Electsys Utility/LoginKits/LoginKits.swift
//
// LoginKits.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/12.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Cocoa
import Kanna
import Alamofire
import SwiftyJSON
import Alamofire_SwiftyJSON
class LoginHelper {
static var sID: String?
static var client: String?
static var returnUrl: String?
static var se: String?
static var lastLoginUserName: String = "{null}"
static var lastLoginTimeStamp: String?
static func initRedirectUrl(handler: (() -> ())? = nil) {
Alamofire.request(LoginConst.loginUrl, method: .get).response { response in
if response.data != nil {
let doc = String(data: response.data!, encoding: .utf8)
if doc != nil {
let tokens = doc!.components(separatedBy: "'captcha?uuid=")
if tokens.count > 1 {
let latter_tokens = tokens.last!.components(separatedBy: "&t='")
if latter_tokens.count > 1 {
CaptchaHelper.uuid = latter_tokens.first!
CaptchaHelper.t = String(Date().timeIntervalSince1970)
ESLog.info("get captcha uuid %@", CaptchaHelper.uuid ?? "<< error >>")
ESLog.info("set captcha timestamp %@", CaptchaHelper.t ?? "<< error >>")
}
}
}
}
let redirectURL = response.response?.url?.absoluteString
if redirectURL == nil {
ESLog.error("failed to get 302 redirect url")
handler?()
return
}
ESLog.info("get 302 redirect url")
LoginHelper.sID = parseRequest(requestUrl: redirectURL!, parseType: "sid")
ESLog.info("got sID %@", LoginHelper.sID ?? "<nil>")
LoginHelper.client = parseRequest(requestUrl: redirectURL!, parseType: "client")
ESLog.info("got client %@", LoginHelper.client ?? "<nil>")
LoginHelper.returnUrl = parseRequest(requestUrl: redirectURL!, parseType: "returl")
ESLog.info("got returnUrl %@", LoginHelper.returnUrl ?? "<nil>")
LoginHelper.se = parseRequest(requestUrl: redirectURL!, parseType: "se")
ESLog.info("got se %@", LoginHelper.se ?? "<nil>")
handler?()
}
}
static func checkLoginAvailability(_ handler: @escaping (Bool) -> ()) {
Alamofire.request(LoginConst.loginUrl, method: .get).response { response in
// let responseStr = String(data: response.data!, encoding: .utf8)
let redirectURL = response.response?.url?.absoluteString
if redirectURL == nil {
handler(false)
} else if redirectURL?.contains(LoginConst.mainPageUrl) ?? false {
ESLog.info("good redirectURL: %@", redirectURL ?? "<< error >>")
LoginHelper.lastLoginTimeStamp = redirectURL?.replacingOccurrences(of: "https://i.sjtu.edu.cn/xtgl/index_initMenu.html?jsdm=xs&_t=", with: "")
ESLog.info("login timestamp: %@", LoginHelper.lastLoginTimeStamp ?? "<nil>")
handler(true)
} else {
ESLog.fault("bad redirectURL. might not login")
handler(false)
}
}
}
static func requestCaptcha(_ handler: @escaping (NSImage) -> ()) {
Alamofire.request(captchaUrl).responseData { response in
ESLog.info("get captcha response with %@", response.error?.localizedDescription ?? "no error")
let captchaImageObject = NSImage(data: response.data!)
if captchaImageObject != nil {
ESLog.info("retrieved captcha image")
handler(captchaImageObject!)
} else {
ESLog.error("failed to construct captcha image")
}
}
}
static func attemptLogin(username: String, password: String, captcha: String, handler: @escaping (_ success: Bool) -> ()) {
LoginHelper.initRedirectUrl(handler: {
self.performLogin(username, password, captcha, handler)
})
}
fileprivate static func performLogin(_ username: String, _ password: String, _ captcha: String, _ handler: @escaping (_ success: Bool) -> ()) {
if (sID == nil || LoginHelper.client == nil || returnUrl == nil || se == nil) {
ESLog.error("insufficient login certs")
handler(false)
return
}
let postParams: Parameters = [
"sid": LoginHelper.sID!,
"returl": LoginHelper.returnUrl!,
"se": LoginHelper.se!,
"v": "",
"uuid": "15cf4fb3-21a9-45a0-9dda-fbf1795065cb",
"client": LoginHelper.client!,
"user": username,
"pass": <PASSWORD>,
"captcha": captcha
]
Alamofire.request(LoginConst.postUrl, method: .post, parameters: postParams).response { response in
let redirectURL = response.response?.url?.absoluteString
// let realResponse = String(data: response.data!, encoding: .utf8)
ESLog.info("login redirect to: %@", redirectURL ?? "nil")
if redirectURL == nil || redirectURL!.contains("&err=1") {
ESLog.error("login post failure")
LoginHelper.lastLoginUserName = "{null}"
LoginHelper.logOut()
handler(false)
} else {
ESLog.info("login complete! check validation...")
LoginHelper.checkLoginAvailability({ result in
if result {
ESLog.info("good login session")
LoginHelper.lastLoginUserName = username
handler(true)
} else {
ESLog.fault("bad login session")
LoginHelper.lastLoginUserName = "{null}"
LoginHelper.logOut()
handler(false)
}
})
}
}
}
static func logOut(handler: (() -> ())? = nil) {
let getParams: Parameters = [
"t": LoginHelper.lastLoginTimeStamp ?? Date().milliStamp,
"login_type": ""
]
LoginHelper.lastLoginUserName = "{null}"
Alamofire.request(LoginConst.logOutUrl, method: .get, parameters: getParams).response { _ in
LoginHelper.removeCookie()
handler?()
}
}
static func removeCookie() {
let cstorage = HTTPCookieStorage.shared
if let cookies = cstorage.cookies(for: URL(string: "http://i.sjtu.edu.cn")!) {
for cookie in cookies {
ESLog.info("remove cookie %@", cookie.name)
cstorage.deleteCookie(cookie)
}
}
if let cookies = cstorage.cookies(for: URL(string: "https://jaccount.sjtu.edu.cn")!) {
for cookie in cookies {
ESLog.info("remove cookie %@", cookie.name)
cstorage.deleteCookie(cookie)
}
}
}
}
<file_sep>/Electsys Utility/Electsys Utility/InspectorKits/InspectedProperties.swift
//
// InspectedProperties.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/16.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
struct Property: Codable {
let name: String
var value: String
}
<file_sep>/Electsys Utility/Electsys Utility/ExamKits/ExamKits.swift
//
// ExamKits.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
import Alamofire
import Alamofire_SwiftyJSON
import SwiftyJSON
class ExamKits {
static func requestExamTable(year: Int, term: Int,
handler: @escaping ([NGExam]) -> Void,
failure: @escaping (Int) -> Void) {
// 1 - "3"
// 2 - "12"
// 3 - "16"
if term < 1 || term > 3 {
failure(-1)
return
}
let termString = CourseConst.termTable[term]
let getParams: Parameters = [
"xnm": year,
"xqm": termString,
]
Alamofire.request(ExamConst.requestUrl,
method: .get,
parameters: getParams).responseSwiftyJSON(completionHandler: { responseJSON in
if responseJSON.error == nil {
let jsonResp = responseJSON.value
if jsonResp != nil {
var examList: [NGExam] = []
for examObject in jsonResp?["items"].arrayValue ?? [] {
let timeString = examObject["kssj"].stringValue
let tokens = timeString.components(separatedBy: CharacterSet(charactersIn: "(-)")).filter({ $0 != ""})
if tokens.count != 5 {
ESLog.error("failed to parse time of `%@`. thrown.", timeString)
failure(-4)
return
}
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd HH:mm"
guard let startDate = dateStringFormatter.date(from: "\(tokens[0])-\(tokens[1])-\(tokens[2]) \(tokens[3])") else {
ESLog.error("failed to parse start date of `%@`. thrown.", timeString)
failure(-5)
return
}
guard let endDate = dateStringFormatter.date(from: "\(tokens[0])-\(tokens[1])-\(tokens[2]) \(tokens[4])") else {
ESLog.error("failed to parse end date of %@. thrown.", timeString)
failure(-5)
return
}
examList.append(NGExam(name: examObject["ksmc"].stringValue,
courseName: examObject["kcmc"].stringValue,
courseCode: examObject["kch"].stringValue,
location: examObject["cdmc"].stringValue,
teacher: examObject["jsxx"].stringValue,
startDate: startDate,
endDate: endDate,
campus: examObject["xqmc"].stringValue,
originalTime: examObject["kssj"].stringValue))
}
handler(examList)
} else {
failure(-3)
}
} else {
failure(-2)
}
})
}
}
<file_sep>/Electsys Utility/Electsys Utility/ScoreKits/GPAKits.swift
//
// GPAKits.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
class GPAKits {
static let GpaStrategies: [String] = ["标准 4.0 制",
"改进 4.0 制(第一类)",
"改进 4.0 制(第二类)",
"北京大学 4.0 制",
"加拿大 4.3 制",
"中国科学技术大学 4.3 制",
"上海交通大学 4.3 制"]
static func calculateGpa(scores: [NGScore]) -> Double? {
var totalGradePoints: Double = 0.0
var creditCount: Float = 0.0
switch PreferenceKits.gpaStrategy {
case .Canadian_4_3:
for score in scores {
if score.finalScore == nil || score.credit == nil {
continue
}
creditCount += score.credit!
switch score.finalScore! {
case 60 ..< 65:
totalGradePoints += 2.3 * Double(score.credit!)
case 65 ..< 70:
totalGradePoints += 2.7 * Double(score.credit!)
case 70 ..< 75:
totalGradePoints += 3.0 * Double(score.credit!)
case 75 ..< 80:
totalGradePoints += 3.3 * Double(score.credit!)
case 80 ..< 85:
totalGradePoints += 3.7 * Double(score.credit!)
case 85 ..< 90:
totalGradePoints += 4.0 * Double(score.credit!)
case 90 ... 100:
totalGradePoints += 4.3 * Double(score.credit!)
default: break
// do nothing
}
}
case .Normal_4_0:
for score in scores {
if score.finalScore == nil || score.credit == nil {
continue
}
creditCount += score.credit!
switch score.finalScore! {
case 60 ..< 70:
totalGradePoints += 1.0 * Double(score.credit!)
case 70 ..< 80:
totalGradePoints += 2.0 * Double(score.credit!)
case 80 ..< 90:
totalGradePoints += 3.0 * Double(score.credit!)
case 90 ... 100:
totalGradePoints += 4.0 * Double(score.credit!)
default: break
// do nothing
}
}
case .Improved_4_0_A:
for score in scores {
if score.finalScore == nil || score.credit == nil {
continue
}
creditCount += score.credit!
switch score.finalScore! {
case 60 ..< 70:
totalGradePoints += 2.0 * Double(score.credit!)
case 70 ..< 85:
totalGradePoints += 3.0 * Double(score.credit!)
case 85 ... 100:
totalGradePoints += 4.0 * Double(score.credit!)
default: break
}
}
case .Improved_4_0_B:
for score in scores {
if score.finalScore == nil || score.credit == nil {
continue
}
creditCount += score.credit!
switch score.finalScore! {
case 60 ..< 75:
totalGradePoints += 2.0 * Double(score.credit!)
case 75 ..< 85:
totalGradePoints += 3.0 * Double(score.credit!)
case 85 ... 100:
totalGradePoints += 4.0 * Double(score.credit!)
default: break
}
}
case .PKU_4_0:
for score in scores {
if score.finalScore == nil || score.credit == nil {
continue
}
creditCount += score.credit!
switch score.finalScore! {
case 60 ..< 64:
totalGradePoints += 1.0 * Double(score.credit!)
case 64 ..< 68:
totalGradePoints += 1.5 * Double(score.credit!)
case 68 ..< 72:
totalGradePoints += 2.0 * Double(score.credit!)
case 72 ..< 75:
totalGradePoints += 2.3 * Double(score.credit!)
case 75 ..< 78:
totalGradePoints += 2.7 * Double(score.credit!)
case 78 ..< 82:
totalGradePoints += 3.0 * Double(score.credit!)
case 82 ..< 85:
totalGradePoints += 3.3 * Double(score.credit!)
case 85 ..< 90:
totalGradePoints += 3.7 * Double(score.credit!)
case 90 ... 100:
totalGradePoints += 4.0 * Double(score.credit!)
default: break
}
}
case .USTC_4_3:
for score in scores {
if score.finalScore == nil || score.credit == nil {
continue
}
creditCount += score.credit!
switch score.finalScore! {
case 60 ..< 61:
totalGradePoints += 1.0 * Double(score.credit!)
case 61 ..< 64:
totalGradePoints += 1.3 * Double(score.credit!)
case 64 ..< 65:
totalGradePoints += 1.5 * Double(score.credit!)
case 65 ..< 68:
totalGradePoints += 1.7 * Double(score.credit!)
case 68 ..< 72:
totalGradePoints += 2.0 * Double(score.credit!)
case 72 ..< 75:
totalGradePoints += 2.3 * Double(score.credit!)
case 75 ..< 78:
totalGradePoints += 2.7 * Double(score.credit!)
case 78 ..< 82:
totalGradePoints += 3.0 * Double(score.credit!)
case 82 ..< 85:
totalGradePoints += 3.3 * Double(score.credit!)
case 85 ..< 90:
totalGradePoints += 3.7 * Double(score.credit!)
case 90 ..< 95:
totalGradePoints += 4.0 * Double(score.credit!)
case 95 ... 100:
totalGradePoints += 4.3 * Double(score.credit!)
default: break
}
}
case .SJTU_4_3:
for score in scores {
if score.finalScore == nil || score.credit == nil {
continue
}
creditCount += score.credit!
switch score.finalScore! {
case 60 ..< 62:
totalGradePoints += 1.0 * Double(score.credit!)
case 62 ..< 65:
totalGradePoints += 1.7 * Double(score.credit!)
case 65 ..< 67:
totalGradePoints += 2.0 * Double(score.credit!)
case 67 ..< 70:
totalGradePoints += 2.3 * Double(score.credit!)
case 70 ..< 75:
totalGradePoints += 2.7 * Double(score.credit!)
case 75 ..< 80:
totalGradePoints += 3.0 * Double(score.credit!)
case 80 ..< 85:
totalGradePoints += 3.3 * Double(score.credit!)
case 85 ..< 90:
totalGradePoints += 3.7 * Double(score.credit!)
case 90 ..< 95:
totalGradePoints += 4.0 * Double(score.credit!)
case 95 ... 100:
totalGradePoints += 4.3 * Double(score.credit!)
default: break
}
}
}
if creditCount == 0.0 {
return nil
}
return totalGradePoints / Double(creditCount)
}
}
<file_sep>/Electsys Utility/Electsys Utility/LegacyLoginKits/LegacyLoginHelper.swift
//
// LoginHelper.swift
// Sync Utility
//
// Created by yuxiqian on 2018/8/29.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Foundation
import Alamofire
let electSysUrl = "http://electsys.sjtu.edu.cn/"
let loginUrl = "http://electsys.sjtu.edu.cn/edu/login.aspx"
let targetUrl = "http://electsys.sjtu.edu.cn/edu/student/sdtMain.aspx"
let contentUrl = "http://electsys.sjtu.edu.cn/edu/newsboard/newsinside.aspx"
let captchaUrl = "https://jaccount.sjtu.edu.cn/jaccount/captcha"
let postUrl = "https://jaccount.sjtu.edu.cn/jaccount/ulogin"
let sdtLeftUrl = "http://electsys.sjtu.edu.cn/edu/student/sdtLeft.aspx"
let logOutUrl = "http://electsys.sjtu.edu.cn/edu/logOut.aspx"
class Login {
var delegate: loginHelperDelegate?
func attempt(userName: String, password: String, captchaWord: String, isLegacy: Bool = true) {
if isLegacy {
// Legacy stuff
var responseHtml: String = ""
Alamofire.request(loginUrl).response(completionHandler: { response in
if response.response == nil {
self.delegate?.validateLoginResult(htmlData: "")
return
}
let responseItem = response.response!
let jumpToUrl: String
if responseItem.url != nil {
jumpToUrl = responseItem.url!.absoluteString
} else {
self.delegate?.validateLoginResult(htmlData: "")
return
}
let sID = parseRequest(requestUrl: jumpToUrl, parseType: "sid")
ESLog.info("sID: %@", sID ?? "<nil>")
let returnUrl = parseRequest(requestUrl: jumpToUrl, parseType: "returl")
ESLog.info("returnUrl: %@", returnUrl ?? "<nil>")
let se = parseRequest(requestUrl: jumpToUrl, parseType: "se")
ESLog.info("se: %@", se ?? "<nil>")
let postParams: Parameters = [
"sid": sID ?? "",
"returl": returnUrl ?? "",
"se": se ?? "",
"v": "",
"user": userName,
"pass": <PASSWORD>,
"captcha": captchaWord
]
Alamofire.request(postUrl, method: .post, parameters: postParams, encoding: URLEncoding.httpBody).responseData(completionHandler: { response in
responseHtml = String(data: response.data!, encoding: .utf8)!
if (responseHtml.contains("上海交通大学教学信息服务网-学生服务平台")) {
// successfully goes in!
Alamofire.request(contentUrl).responseData(completionHandler: { response in
let realOutput = String(data: response.data!, encoding: .utf8)!
// print(realOutput)
self.delegate?.validateLoginResult(htmlData: realOutput)
})
} else {
self.delegate?.validateLoginResult(htmlData: responseHtml)
}
// NSLog("reponseHtml successfully obtained.")
})
})
} else {
// Brand new stuff
}
}
func updateCaptcha() {
Alamofire.request(captchaUrl).responseData { response in
let captchaImageObject = NSImage(data: response.data!)
if captchaImageObject != nil {
self.delegate?.setCaptchaImage(image: captchaImageObject!)
} else {
self.delegate?.setCaptchaImage(image: NSImage(imageLiteralResourceName: "NSStopProgressTemplate"))
self.delegate?.failedToLoadCaptcha()
}
}
}
func logOut() {
Alamofire.request(logOutUrl)
}
}
protocol loginHelperDelegate: NSObjectProtocol {
func validateLoginResult(htmlData: String) -> ()
// func syncExamInfo() -> ()
func setCaptchaImage(image: NSImage) -> ()
func failedToLoadCaptcha() -> ()
func forceResetAccount() -> ()
}
<file_sep>/build.sh
#!/bin/bash
TOP_DIR=$(pwd)
echo "----TOP_DIR----"
echo $TOP_DIR
CONFIGURATION=Release
BUILD_SCHEME=Package
cd Electsys\ Utility
xcodebuild clean
xcodebuild -workspace Electsys\ Utility.xcworkspace -scheme ${BUILD_SCHEME} -configuration ${CONFIGURATION}
echo "Build succeed"
#————————————————
#版权声明:本文为CSDN博主「huilibai」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
#原文链接:https://blog.csdn.net/huilibai/article/details/83659399
<file_sep>/Electsys Utility/Electsys Utility/InspectorKits/InspectorKits.swift
//
// InspectorKits.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/16.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
class InspectorKits {
static var window: NSWindow?
static func showProperties(properties: [Property]) {
let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
let windowController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("InspectorWindowController")) as! NSWindowController
InspectorKits.window = windowController.window
if InspectorKits.window != nil {
(window?.contentViewController as! TableViewController).configureTableView(properties: properties)
windowController.showWindow(self)
}
}
}
<file_sep>/Electsys Utility/Electsys Utility/GalleryKits/GalleryKits.swift
//
// GalleryKits.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/17.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Alamofire
import Alamofire_SwiftyJSON
import Foundation
import SwiftyJSON
class GalleryKits {
static var courseList: [NGCurriculum] = []
static let emptyCurriculum = NGCurriculum(identifier: "",
code: "",
holderSchool: "",
name: "",
year: 0,
term: 0,
targetGrade: 0,
teacher: [],
credit: 0.0,
arrangements: [],
studentNumber: 0,
notes: "")
fileprivate static let betaJsonHeader = "https://raw.githubusercontent.com/yuetsin/NG-Course/be-ta/release/"
fileprivate static let stableJsonHeader = "https://raw.githubusercontent.com/yuetsin/NG-Course/master/release/"
static var possibleUrl: String?
static func requestGalleryData(year: Int, term: Int, beta: Bool = false,
handler: @escaping (String) -> Void,
failure: @escaping (Int) -> Void) {
var requestUrl: String?
if beta {
requestUrl = "\(betaJsonHeader)\(year)_\(year + 1)_\(term).json"
} else {
requestUrl = "\(stableJsonHeader)\(year)_\(year + 1)_\(term).json"
}
GalleryKits.possibleUrl = requestUrl
Alamofire.request(requestUrl!,
method: .get).responseSwiftyJSON { responseJSON in
if responseJSON.error == nil {
let jsonResp = responseJSON.value
if jsonResp != nil {
let timeStamp = jsonResp?["generate_time"].stringValue
GalleryKits.courseList.removeAll()
for curObject in jsonResp?["data"].arrayValue ?? [] {
var arrangements: [NGArrangements] = []
for arrObject in curObject["arrangements"].arrayValue {
var weeksInt: [Int] = []
var sessionsInt: [Int] = []
for weekObj in arrObject["weeks"].arrayValue {
weeksInt.append(weekObj.intValue)
}
for sessionObj in arrObject["sessions"].arrayValue {
sessionsInt.append(sessionObj.intValue)
}
let arrangement = NGArrangements(weeks: weeksInt,
weekDay: arrObject["week_day"].intValue,
sessions: sessionsInt,
campus: arrObject["campus"].stringValue,
classroom: arrObject["classroom"].stringValue)
if !arrangements.contains(arrangement) {
arrangements.append(arrangement)
}
}
var teachersLiteral: [String] = []
for teacherObject in curObject["teacher"].arrayValue {
teachersLiteral.append(teacherObject.stringValue)
}
GalleryKits.courseList.append(NGCurriculum(identifier: curObject["identifier"].stringValue,
code: curObject["code"].stringValue,
holderSchool: curObject["holder_school"].stringValue,
name: curObject["name"].stringValue,
year: curObject["year"].intValue,
term: curObject["term"].intValue,
targetGrade: curObject["target_grade"].intValue,
teacher: teachersLiteral,
credit: curObject["credit"].doubleValue,
arrangements: arrangements,
studentNumber: curObject["student_number"].intValue,
notes: curObject["notes"].stringValue))
}
handler(timeStamp ?? "")
} else {
failure(-3)
}
} else {
failure(-2)
}
}
}
}
<file_sep>/Electsys Utility/Electsys Utility/LegacyScheduleKits/SchoolDay.swift
//
// SchoolDay.swift
// Sync Utility
//
// Created by yuxiqian on 2018/8/31.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Cocoa
class Day : NSObject {
init(_ dayNum: Int) {
self.dayNumber = dayNum
}
var dayNumber = 0
// var hasChildren = true
var children: [Course] = []
}
let dayOfWeekName = ["Unknown", "周一", "周二", "周三", "周四", "周五", "周六", "周日"]
func getCourseCountOfDay(dayIndex: Int, array: [Course]) -> Int {
var count: Int = 0
for course in array {
if course.courseDay == dayIndex {
count += 1
}
}
return count
}
func getAllCount(week: [Day]) -> Int {
var count = 0
for day in week {
count += day.children.count
}
return count
}
<file_sep>/Electsys Utility/Electsys Utility/Utilities/ArrayBeautify.swift
//
// ArrayBeautify.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/17.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
class Beautify {
static func beautifier(array: [Int]) -> [(Int, Int)] {
if array.count == 0 {
return []
} else if array.count == 1 {
return [(array.first!, array.first!)]
}
var begin = array.first!
var last = array.first!
var resultPair: [(Int, Int)] = []
var firstSkip = true
for integer in array {
if firstSkip {
firstSkip = false
continue
}
if integer - last == 1 {
last += 1
} else {
resultPair.append((begin, last))
begin = integer
last = integer
}
}
resultPair.append((begin, last))
return resultPair
}
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/CreditsViewController.swift
//
// ViewController.swift
// Sync Utility
//
// Created by yuxiqian on 2018/8/28.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Foundation
import Cocoa
class CreditsViewController : NSViewController {
override func viewWillDisappear() {
let application = NSApplication.shared
application.stopModal()
}
@IBAction func closeWindow(_ sender: NSButton) {
self.view.window?.close()
}
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/ExportFormatSelector+ExportFormatDecisionDelegate.swift
//
// ExportFormatSelector.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/27.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Cocoa
class ExportFormatSelector: NSViewController {
var delegate: ExportFormatDecisionDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
@IBAction func exportPlainText(_ sender: NSButton) {
delegate?.exportPlainText()
}
@IBAction func exportJSONFormat(_ sender: NSButton) {
delegate?.exportJSONFormat()
}
}
protocol ExportFormatDecisionDelegate {
func exportPlainText() -> ()
func exportJSONFormat() -> ()
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/MenuWithSeparator.swift
//
// MenuWithSeparator.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/10/26.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Cocoa
class MenuWithSeparator: NSMenu {
override func addItem(withTitle string: String, action selector: Selector?, keyEquivalent charCode: String) -> NSMenuItem {
if string == "MY_MENU_SEPARATOR" {
let separator = NSMenuItem.separator()
self.addItem(separator)
return separator
}
return super.addItem(withTitle: string, action: selector, keyEquivalent: charCode)
}
override func insertItem(withTitle string: String, action selector: Selector?, keyEquivalent charCode: String, at index: Int) -> NSMenuItem {
if string == "MY_MENU_SEPARATOR" {
let separator = NSMenuItem.separator()
self.insertItem(separator, at: index)
return separator
}
return super.insertItem(withTitle: string, action: selector, keyEquivalent: charCode, at: index)
}
}
<file_sep>/Homebrew/electsys-utility.rb
cask 'electsys-utility' do
version '0.9.9'
sha256 :no_check
url "https://github.com/yuetsin/electsys-utility/releases/download/v#{version}/Electsys.Utility.dmg"
appcast 'https://github.com/yuetsin/electsys-utility/releases.atom'
name 'Electsys Utility'
homepage 'https://github.com/yuetsin/electsys-utility/'
app 'Electsys Utility.app'
end<file_sep>/Electsys Utility/Electsys Utility/ViewController/CookieParserViewController.swift
//
// CookieParserViewController.swift
// Electsys Utility
//
// Created by 法好 on 2020/12/8.
// Copyright © 2020 yuxiqian. All rights reserved.
//
import Alamofire
import Cocoa
class CookieParserViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
var delegate: WebLoginDelegate?
@IBOutlet var textField: NSTextView!
@IBAction func giveUpLogin(_ sender: NSButton) {
done(success: false)
}
@IBAction func completeLogin(_ sender: NSButton) {
let dict = parseCookies(rawString: textField.string)
let targetUrl = URL(string: LoginConst.initUrl)!
for pair in dict {
ESLog.info("parsed cookie pair: `%@`: `%@`", pair.key, pair.value)
}
for cookie in HTTPCookie.cookies(withResponseHeaderFields: dict, for: targetUrl) {
Alamofire.HTTPCookieStorage.shared.setCookie(cookie)
}
done(success: true)
}
func done(success: Bool = true) {
delegate?.callbackCookie(success)
}
}
func parseCookies(rawString: String) -> [String: String] {
return rawString.split(separator: ";").map { chars -> Substring in
chars.drop(while: { (char: Character) in // Trim leading spaces
char == " "
})
}.reduce([String: String]()) { (dict, chars) -> [String: String] in
let pair = chars.split(separator: "=")
guard let name = pair.first, let value = pair.indices.contains(1) ? pair[1] : nil else {
return dict
}
var d = dict
d[String(name)] = String(value)
return d
}
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/TermSelectingViewController.swift
//
// TermSelectingViewController.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/11.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Cocoa
@available(OSX 10.12.2, *)
class TermSelectingViewController: NSViewController, NSScrubberDataSource, NSScrubberDelegate {
func numberOfItems(for scrubber: NSScrubber) -> Int {
return yearPopUpSelector.numberOfItems
}
func scrubber(_ scrubber: NSScrubber, viewForItemAt index: Int) -> NSScrubberItemView {
if index < yearPopUpSelector.numberOfItems {
let itemView = scrubber.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "TextScrubberItemIdentifier"),
owner: nil) as! NSScrubberTextItemView
itemView.textField.stringValue = yearPopUpSelector.item(at: index)?.title ?? "N/A"
return itemView
} else {
let itemView = scrubber.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "TextScrubberItemIdentifier"), owner: nil) as! NSScrubberTextItemView
itemView.textField.stringValue = "N/A"
return itemView
}
}
func scrubber(_ scrubber: NSScrubber, didSelectItemAt index: Int) {
// Log the index value for the item the user selected
if index < yearPopUpSelector.numberOfItems {
yearPopUpSelector.selectItem(at: index)
}
syncScrubber()
}
@IBOutlet var yearPopUpSelector: NSPopUpButton!
@IBOutlet var termPopUpSelector: NSPopUpButton!
@IBOutlet var yearPromptTextField: NSTextField!
@IBOutlet var OKButton: NSButton!
@IBOutlet var cancelButton: NSButton!
@IBOutlet weak var touchBarOkButton: NSButton!
@IBOutlet weak var touchBarCancelButton: NSButton!
@IBOutlet var yearScrubber: NSScrubber!
@IBOutlet var termSelector: NSSegmentedControl!
@IBOutlet weak var popOverTouchBar: NSPopoverTouchBarItem!
@IBAction func cancelTouchBarTapped(_ sender: NSButtonCell) {
cancelButtonTapped(cancelButton)
}
@IBAction func okTouchBarTapped(_ sender: NSButton) {
OKButtonTapped(OKButton)
}
@IBAction func touchBarTermTapped(_ sender: NSSegmentedControl) {
if sender.selectedSegment < termPopUpSelector.numberOfItems {
termPopUpSelector.selectItem(at: sender.selectedSegment)
}
}
func syncScrubber() {
if popOverTouchBar != nil {
popOverTouchBar.collapsedRepresentationLabel = yearPopUpSelector.selectedItem?.title ?? "N/A"
// popOverTouchBar.customizationLabel = yearPopUpSelector.selectedItem?.title ?? "N/A"
popOverTouchBar.dismissPopover(self)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
initPopUpLists()
if yearScrubber != nil {
yearScrubber.dataSource = self
yearScrubber.delegate = self
yearScrubber.mode = .free
syncScrubber()
yearScrubber.register(NSScrubberTextItemView.self, forItemIdentifier: NSUserInterfaceItemIdentifier(rawValue: "TextScrubberItemIdentifier"))
}
termPopUpButtonTapped(termPopUpSelector)
}
override func viewDidAppear() {
super.viewDidAppear()
view.window!.styleMask.remove(.resizable)
}
func disableUI() {
yearPopUpSelector.isEnabled = false
termPopUpSelector.isEnabled = false
OKButton.isEnabled = false
cancelButton.isEnabled = false
if touchBarOkButton != nil {
touchBarOkButton.isEnabled = false
}
if touchBarCancelButton != nil {
touchBarCancelButton.isEnabled = false
}
}
func enableUI() {
yearPopUpSelector.isEnabled = true
termPopUpSelector.isEnabled = true
OKButton.isEnabled = true
cancelButton.isEnabled = true
if touchBarOkButton != nil {
touchBarOkButton.isEnabled = true
}
if touchBarCancelButton != nil {
touchBarCancelButton.isEnabled = true
}
}
var requestType: RequestType?
func initPopUpLists() {
let date = Date()
let calendar = Calendar.current
var year = calendar.component(.year, from: date)
yearPopUpSelector.removeAllItems()
if year < 2019 {
year = 2019
// fallback as year 2019
}
for iteratedYear in (1996 ... year).reversed() {
yearPopUpSelector.addItem(withTitle: "\(iteratedYear) 至 \(iteratedYear + 1) 学年")
}
yearPopUpButtonTapped(yearPopUpSelector)
}
var successDelegate: YearAndTermSelectionDelegate?
var failureDelegate: PageNavigationDelegate?
@IBAction func cancelButtonTapped(_ sender: NSButton) {
successDelegate?.shutWindow()
}
@IBAction func OKButtonTapped(_ sender: NSButton) {
disableUI()
switch requestType {
case .course:
let actualYear = 1995 + yearPopUpSelector.numberOfItems - yearPopUpSelector.indexOfSelectedItem
let actualTerm = termPopUpSelector.indexOfSelectedItem + 1
CourseKits.requestCourseTable(year: actualYear, term: actualTerm,
handler: { courses in
self.successDelegate?.successCourseDataTransfer(data: courses)
// self.successDelegate?.shutWindow()
},
failure: { errCode in
self.showErrorMessage(errorMsg: "未能获取此学期的课表信息。\n错误代码:\(errCode)")
self.enableUI()
})
break
case .exam:
let actualYear = 1995 + yearPopUpSelector.numberOfItems - yearPopUpSelector.indexOfSelectedItem
let actualTerm = termPopUpSelector.indexOfSelectedItem + 1
ExamKits.requestExamTable(year: actualYear, term: actualTerm,
handler: { exams in
self.successDelegate?.successExamDataTransfer(data: exams)
// self.successDelegate?.shutWindow()
},
failure: { errCode in
self.showErrorMessage(errorMsg: "未能获取此学期的考试信息。\n错误代码:\(errCode)")
self.enableUI()
})
break
case .score:
let actualYear = 1995 + yearPopUpSelector.numberOfItems - yearPopUpSelector.indexOfSelectedItem
let actualTerm = termPopUpSelector.indexOfSelectedItem + 1
ScoreKits.requestScoreData(year: actualYear, term: actualTerm,
handler: { scores in
self.successDelegate?.successScoreDataTransfer(data: scores)
// self.successDelegate?.shutWindow()
},
failure: { errCode in
self.showErrorMessage(errorMsg: "未能获取此学期的成绩单。\n错误代码:\(errCode)")
self.enableUI()
})
break
default:
break
}
}
@IBAction func yearPopUpButtonTapped(_ sender: NSPopUpButton) {
let actualYear = 1996 + sender.numberOfItems - sender.indexOfSelectedItem
yearPromptTextField.stringValue = "指始于 \(actualYear - 1) 年秋季,终于 \(actualYear) 年夏季的学年。"
yearPopUpSelector.selectItem(at: sender.indexOfSelectedItem)
syncScrubber()
}
@IBAction func termPopUpButtonTapped(_ sender: NSPopUpButton) {
if termSelector != nil {
termSelector.selectSegment(withTag: sender.indexOfSelectedItem)
}
}
func showErrorMessage(errorMsg: String) {
let errorAlert: NSAlert = NSAlert()
errorAlert.messageText = "出错啦"
errorAlert.informativeText = errorMsg
errorAlert.addButton(withTitle: "嗯")
errorAlert.alertStyle = NSAlert.Style.critical
errorAlert.beginSheetModal(for: view.window!, completionHandler: nil)
ESLog.error("internal error occurred. message: ", errorMsg)
}
}
protocol YearAndTermSelectionDelegate {
func successCourseDataTransfer(data: [NGCourse]) -> Void
func successExamDataTransfer(data: [NGExam]) -> Void
func successScoreDataTransfer(data: [NGScore]) -> Void
func shutWindow() -> Void
}
protocol PageNavigationDelegate {
func failureBackToLoginPage() -> Void
}
enum RequestType {
case course
case exam
case score
}
<file_sep>/Electsys Utility/Electsys Utility/GalleryKits/[deprecated] JsonRequester.swift
//
// JsonRequester.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/9/16.
// Copyright © 2018/9/16 yuxiqian. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
let betaJsonHeader = "https://raw.githubusercontent.com/yuxiqian/finda-studyroom/be-ta/json_output/"
let stableJsonHeader = "https://raw.githubusercontent.com/yuxiqian/finda-studyroom/master/json_output/"
func generateCur(_ json: JSON) -> Curricula {
let cur = Curricula()
cur.identifier = json["identifier"].stringValue
cur.holderSchool = json["holder_school"].stringValue.sanitize()
let splitHolderSchool = cur.holderSchool.components(separatedBy: CharacterSet(charactersIn: "()"))
if splitHolderSchool.count > 2 {
if Int(splitHolderSchool[1]) != nil {
cur.holderSchool = splitHolderSchool[2]
// print("truncated \(cur.holderSchool)")
} else {
// print("misfire \(splitHolderSchool[1])")
}
}
cur.name = json["name"].stringValue.sanitize()
cur.year = Year(rawValue: json["year"].intValue) ?? .__BAD_YEAR
cur.targetGrade = json["target_grade"].intValue
cur.teacherName = json["teacher"].stringValue.sanitize()
cur.teacherTitle = json["teacher_title"].stringValue
cur.creditScore = json["credit"].floatValue
cur.startWeek = json["start_week"].intValue
cur.endWeek = json["end_week"].intValue
cur.studentNumber = json["student_number"].intValue
cur.notes = json["notes"].stringValue.deleteOccur(remove: " ").sanitize()
for i in 1...5 {
cur.notes = cur.notes.deleteOccur(remove: "(\(i))")
}
if let oddWeekArr = json["odd_week"].array {
for owa in oddWeekArr {
let a = Arrangement()
a.weekDay = owa["week_day"].intValue
a.startsAt = owa["start_from"].intValue
a.endsAt = owa["end_at"].intValue
a.classroom = owa["classroom"].stringValue.replacingOccurrences(of: "教一楼", with: "徐汇教一楼").replacingOccurrences(of: "教学一楼", with: "教一楼").replacingOccurrences(of: "新上院", with: "徐汇新上院").replacingOccurrences(of: "工程馆", with: "徐汇工程馆")
// .replacingOccurrences(of: "教一楼", with: "徐汇教一楼").replacingOccurrences(of: "新上院", with: "徐汇新上院").replacingOccurrences(of: "工程馆", with: "徐汇工程馆").replacingOccurrences(of: "西二楼", with: "卢湾西二楼").replacingOccurrences(of: "图书馆", with: "卢湾图书馆")
let splitedClassroom = a.classroom.components(separatedBy: CharacterSet(charactersIn: "(/)"))
if (splitedClassroom.count >= 3) {
if !splitedClassroom[2].starts(with: splitedClassroom[0].sanitize()) {
if splitedClassroom[0].sanitize() != "闵行" {
a.classroom = splitedClassroom[0].sanitize() + splitedClassroom[2]
} else {
a.classroom = splitedClassroom[2]
}
} else {
a.classroom = splitedClassroom[2]
}
}
if (sanitize(a.classroom) == "") {
a.classroom = splitedClassroom[0].sanitize() + "校区"
}
if (a.classroom == "不安排教室") {
a.classroom = ""
}
cur.oddWeekArr.append(a)
}
}
if let evenWeekArr = json["even_week"].array {
for ewa in evenWeekArr {
let a = Arrangement()
a.weekDay = ewa["week_day"].intValue
a.startsAt = ewa["start_from"].intValue
a.endsAt = ewa["end_at"].intValue
a.classroom = ewa["classroom"].stringValue.replacingOccurrences(of: "教一楼", with: "徐汇教一楼").replacingOccurrences(of: "教学一楼", with: "教一楼").replacingOccurrences(of: "新上院", with: "徐汇新上院").replacingOccurrences(of: "工程馆", with: "徐汇工程馆")
// .replacingOccurrences(of: "教一楼", with: "徐汇教一楼").replacingOccurrences(of: "新上院", with: "徐汇新上院").replacingOccurrences(of: "工程馆", with: "徐汇工程馆").replacingOccurrences(of: "西二楼", with: "卢湾西二楼").replacingOccurrences(of: "图书馆", with: "卢湾图书馆")
let splitedClassroom = a.classroom.components(separatedBy: CharacterSet(charactersIn: "(/)"))
if (splitedClassroom.count >= 3) {
if !splitedClassroom[2].starts(with: splitedClassroom[0].sanitize()) {
if splitedClassroom[0].sanitize() != "闵行" {
a.classroom = splitedClassroom[0].sanitize() + splitedClassroom[2]
} else {
a.classroom = splitedClassroom[2]
}
} else {
a.classroom = splitedClassroom[2]
}
}
if (sanitize(a.classroom) == "") {
a.classroom = splitedClassroom[0].sanitize() + "校区"
}
if (a.classroom == "不安排教室") {
a.classroom = ""
}
cur.evenWeekArr.append(a)
}
}
return cur
}
func hanToInt(_ str: String?) -> Int {
if str == nil { return -1 }
for i in 1...22 {
if str == "第 \(i) 周" {
return i
}
}
return 0
}
let dayToInt = ["", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日", ]
<file_sep>/Electsys Utility/Electsys Utility/UIKits/MainViewController.swift
//
// MainViewController.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/12/27.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Cocoa
class MainViewController: NSViewController, NSSplitViewDelegate, UIManagerDelegate {
override func viewDidLoad() {
if #available(OSX 10.12.2, *) {
ESLog.info("system version >= 10.12.2, ok")
} else {
ESLog.error("critical! bad system version")
let alert = NSAlert()
alert.messageText = "系统版本不合"
alert.informativeText = "Electsys Utility 至少需要 macOS 10.12.2 以正常运行。\nApp 即将退出。"
alert.addButton(withTitle: "行")
alert.alertStyle = .critical
alert.runModal()
NSApplication.shared.terminate(nil)
}
super.viewDidLoad()
// Do view setup here.
registerDelegate()
lockIcon()
setAccessibilityLabel()
// aboutButton.becomeFirstResponder()
aboutButton.image?.isTemplate = true
preferenceButton.image?.isTemplate = true
creditsButton.image?.isTemplate = true
loginJAccountButton.image?.isTemplate = true
syncCourseTableButton.image?.isTemplate = true
syncTestInfoButton.image?.isTemplate = true
getScoreButton.image?.isTemplate = true
insertHtmlButton.image?.isTemplate = true
queryLibraryButton.image?.isTemplate = true
reportIssueButton.image?.isTemplate = true
}
fileprivate func registerDelegate() {
splitView.delegate = self
}
func setAccessibilityLabel() {
tabViewController?.children[0].view.setAccessibilityParent(aboutButton)
tabViewController?.children[1].view.setAccessibilityParent(preferenceButton)
tabViewController?.children[2].view.setAccessibilityParent(creditsButton)
tabViewController?.children[3].view.setAccessibilityParent(loginJAccountButton)
tabViewController?.children[4].view.setAccessibilityParent(syncCourseTableButton)
tabViewController?.children[5].view.setAccessibilityParent(syncTestInfoButton)
tabViewController?.children[6].view.setAccessibilityParent(getScoreButton)
tabViewController?.children[7].view.setAccessibilityParent(insertHtmlButton)
tabViewController?.children[8].view.setAccessibilityParent(queryLibraryButton)
tabViewController?.children[9].view.setAccessibilityParent(reportIssueButton)
aboutButton.setAccessibilityLabel("切换到关于窗格")
preferenceButton.setAccessibilityLabel("切换到偏好设置窗格")
creditsButton.setAccessibilityLabel("切换到致谢窗格")
loginJAccountButton.setAccessibilityLabel("切换到系统登入窗格")
syncCourseTableButton.setAccessibilityLabel("切换到课程表同步窗格")
syncTestInfoButton.setAccessibilityLabel("切换到考试信息同步窗格")
getScoreButton.setAccessibilityLabel("切换到成绩查询窗格")
insertHtmlButton.setAccessibilityLabel("切换到离线同步窗格")
queryLibraryButton.setAccessibilityLabel("切换到查询课程库窗格")
reportIssueButton.setAccessibilityLabel("切换到问题报告窗格")
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
// Prepare for segue
tabViewController = segue.destinationController as? MainTabViewController
}
@IBOutlet var splitView: NSSplitView!
@IBOutlet weak var containerView: NSView!
@IBOutlet weak var aboutButton: NSButton!
@IBOutlet weak var preferenceButton: NSButton!
@IBOutlet weak var creditsButton: NSButton!
@IBOutlet weak var loginJAccountButton: NSButton!
@IBOutlet weak var syncCourseTableButton: NSButton!
@IBOutlet weak var syncTestInfoButton: NSButton!
@IBOutlet weak var getScoreButton: NSButton!
@IBOutlet weak var insertHtmlButton: NSButton!
@IBOutlet weak var queryLibraryButton: NSButton!
@IBOutlet weak var reportIssueButton: NSButton!
private var tabViewController: MainTabViewController?
@IBAction func switchFeature(_ sender: NSButton) {
aboutButton.state = .off
preferenceButton.state = .off
creditsButton.state = .off
loginJAccountButton.state = .off
syncCourseTableButton.state = .off
syncTestInfoButton.state = .off
getScoreButton.state = .off
insertHtmlButton.state = .off
queryLibraryButton.state = .off
reportIssueButton.state = .off
if tabViewController == nil {
return
}
tabViewController?.tabView.selectTabViewItem(at: sender.tag)
sender.state = .on
// sender.becomeFirstResponder()
// self.view.window?.makeFirstResponder(sender)
}
func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
return 200
}
func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
return 200
}
func splitView(_ splitView: NSSplitView, resizeSubviewsWithOldSize oldSize: NSSize) {
let oldWidth: CGFloat = (splitView.arrangedSubviews.first?.frame.size.width)!
splitView.adjustSubviews()
splitView.setPosition(oldWidth, ofDividerAt: 0)
}
func unlockIcon() {
loginJAccountButton.image = NSImage(imageLiteralResourceName: "NSLockUnlockedTemplate")
syncCourseTableButton.isEnabled = true
syncTestInfoButton.isEnabled = true
getScoreButton.isEnabled = true
}
func lockIcon() {
loginJAccountButton.image = NSImage(imageLiteralResourceName: "NSLockLockedTemplate")
syncCourseTableButton.isEnabled = false
syncTestInfoButton.isEnabled = false
getScoreButton.isEnabled = false
}
func visitAboutPage() {
switchFeature(aboutButton)
}
func visitPrefPage() {
switchFeature(preferenceButton)
}
func visitCreditsPage() {
switchFeature(creditsButton)
}
func switchToPage(index: Int) {
tabViewController?.tabView.selectTabViewItem(at: index)
}
}
protocol UIManagerDelegate: NSObjectProtocol {
func unlockIcon() -> ()
func lockIcon() -> ()
func switchToPage(index: Int) -> ()
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/ExamSyncViewController.swift
//
// ExamSyncViewController.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/9/6.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Cocoa
import Kanna
@available(OSX 10.12.2, *)
class ExamSyncViewController: NSViewController, writeCalendarDelegate, YearAndTermSelectionDelegate, NSTableViewDataSource, NSTableViewDelegate {
func successCourseDataTransfer(data: [NGCourse]) {
ESLog.error("bad type called")
dismiss(sheetViewController)
}
func successExamDataTransfer(data: [NGExam]) {
exams = data
updateTableViewContents()
dismiss(sheetViewController)
}
func successScoreDataTransfer(data: [NGScore]) {
ESLog.error("bad type called")
dismiss(sheetViewController)
}
func shutWindow() {
dismiss(sheetViewController)
}
var exams: [NGExam] = []
var helper: CalendarHelper?
var shouldRemind: Bool = true
@IBAction func TBSyncButtonTapped(_ sender: NSButton) {
restartAnalyse(sender)
}
@IBOutlet weak var TBSyncButton: NSButton!
lazy var sheetViewController: TermSelectingViewController = {
let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
return storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("YearAndTermViewController"))
as! TermSelectingViewController
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
tableView.delegate = self
tableView.dataSource = self
let sortByCourse = NSSortDescriptor(key: "sortByCourse", ascending: true)
// let sortByName = NSSortDescriptor(key: "sortByName", ascending: true)
let sortByTime = NSSortDescriptor(key: "sortByTime", ascending: true)
let sortByRoom = NSSortDescriptor(key: "sortByRoom", ascending: true)
let sortBySeat = NSSortDescriptor(key: "sortBySeat", ascending: true)
tableView.tableColumns[0].sortDescriptorPrototype = sortByCourse
// tableView.tableColumns[1].sortDescriptorPrototype = sortByName
tableView.tableColumns[1].sortDescriptorPrototype = sortByTime
tableView.tableColumns[2].sortDescriptorPrototype = sortByRoom
tableView.tableColumns[3].sortDescriptorPrototype = sortBySeat
tableView.target = self
tableView.doubleAction = #selector(tableViewDoubleClick(_:))
}
func sortArray(_ sortKey: String, _ isAscend: Bool) {
if exams.count <= 1 {
return
}
switch sortKey {
case "sortByCourse":
func titleSorter(p1: NGExam?, p2: NGExam?) -> Bool {
if p1?.courseName == nil {
return p2?.courseName == nil
}
if p2?.courseName == nil {
return p1?.courseName != nil
}
return (p1?.courseName!.compare(p2!.courseName!) == ComparisonResult.orderedAscending) == isAscend
}
exams.sort(by: titleSorter)
tableView.reloadData()
break
case "sortByName":
func codeSorter(p1: NGExam?, p2: NGExam?) -> Bool {
if p1?.name == nil {
return p2?.name == nil
}
if p2?.name == nil {
return p1?.name != nil
}
return (p1?.name!.compare(p2!.name!) == ComparisonResult.orderedDescending) == isAscend
}
exams.sort(by: codeSorter)
tableView.reloadData()
break
case "sortByTime":
func teacherSorter(p1: NGExam?, p2: NGExam?) -> Bool {
if p1?.teacher == nil {
return p2?.teacher == nil
}
if p2?.teacher == nil {
return p1?.teacher != nil
}
return (p1?.teacher!.compare(p2!.teacher!) == ComparisonResult.orderedAscending) == isAscend
}
exams.sort(by: teacherSorter)
tableView.reloadData()
break
case "sortByRoom":
func scoreSorter(p1: NGExam?, p2: NGExam?) -> Bool {
if p1?.location == nil {
return p2?.location == nil
}
if p2?.location == nil {
return p1?.location != nil
}
return (p1?.location!.compare(p2!.location!) == ComparisonResult.orderedAscending) == isAscend
}
exams.sort(by: scoreSorter)
tableView.reloadData()
break
case "sortBySeat":
func pointSorter(p1: NGExam?, p2: NGExam?) -> Bool {
if p1?.campus == nil {
return p2?.campus == nil
}
if p2?.campus == nil {
return p1?.campus != nil
}
return (p1?.campus!.compare(p2!.campus!) == ComparisonResult.orderedAscending) == isAscend
}
exams.sort(by: pointSorter)
tableView.reloadData()
break
case "badSortArgument":
showErrorMessageNormal(errorMsg: "排序参数出错。")
break
default:
break
}
}
@objc func tableViewDoubleClick(_ sender: AnyObject) {
if tableView.selectedRow < 0 || tableView.selectedRow >= exams.count {
return
}
let examObject = exams[tableView.selectedRow]
InspectorKits.showProperties(properties: [
Property(name: "考试名称", value: examObject.name ?? "N/A"),
Property(name: "课程代码", value: examObject.courseCode ?? "N/A"),
Property(name: "课程名称", value: examObject.courseName ?? "N/A"),
Property(name: "课程教师", value: examObject.teacher ?? "N/A"),
Property(name: "考试时间", value: examObject.getTime()),
Property(name: "考试地点", value: examObject.location ?? "N/A"),
Property(name: "校区", value: examObject.campus ?? "N/A"),
])
}
func showErrorMessageNormal(errorMsg: String) {
let errorAlert: NSAlert = NSAlert()
errorAlert.informativeText = errorMsg
errorAlert.messageText = "出错啦"
errorAlert.addButton(withTitle: "嗯")
errorAlert.alertStyle = NSAlert.Style.critical
errorAlert.beginSheetModal(for: view.window!)
}
func showInformativeMessage(infoMsg: String) {
let infoAlert: NSAlert = NSAlert()
infoAlert.informativeText = infoMsg
infoAlert.messageText = "提醒"
infoAlert.addButton(withTitle: "嗯")
infoAlert.alertStyle = NSAlert.Style.informational
infoAlert.beginSheetModal(for: view.window!)
}
override func viewDidAppear() {
if exams.count == 0 {
openYearTermSelectionPanel()
}
updateTableViewContents()
super.viewDidAppear()
}
func openYearTermSelectionPanel() {
sheetViewController.successDelegate = self
sheetViewController.requestType = .exam
presentAsSheet(sheetViewController)
sheetViewController.enableUI()
}
func updateTableViewContents() {
if exams.count == 0 {
promptTextField.stringValue = "目前没有任何考试安排。"
view.window?.makeFirstResponder(blurredView)
blurredView.blurRadius = 3.0
blurredView.isHidden = false
if (TBSyncButton != nil) {
TBSyncButton.isHidden = true
}
return
}
blurredView.isHidden = true
if (TBSyncButton != nil) {
TBSyncButton.isHidden = false
}
blurredView.blurRadius = 0.0
promptTextField.isEnabled = true
promptTextField.stringValue = "现有 \(exams.count) 项考试安排。"
tableView.reloadData()
}
@IBOutlet weak var tableView: NSTableView!
@IBOutlet weak var promptTextField: NSTextField!
@IBOutlet weak var blurredView: RMBlurredView!
@IBOutlet weak var syncTo: NSPopUpButton!
@IBOutlet weak var calendarName: NSTextField!
@IBOutlet weak var getRandomName: NSButton!
@IBOutlet weak var remindMe: NSButton!
@IBOutlet weak var startSync: NSButton!
@IBAction func generateName(_ sender: NSButton) {
self.calendarName.stringValue = getRandomNames()
}
@IBAction func startSync(_ sender: NSButton) {
if self.calendarName.stringValue == "" {
self.calendarName.stringValue = "jAccount 同步"
}
if syncTo.selectedItem!.title == "Mac 上的本地日历" {
helper = CalendarHelper(name: self.calendarName.stringValue , type: .local, delegate: self)
} else {
helper = CalendarHelper(name: self.calendarName.stringValue , type: .calDAV, delegate: self)
}
shouldRemind = (self.remindMe.state == .on)
helper?.delegate = self
disableUI()
}
func didWriteEvent(title: String) {
// promptTextField.stringValue = "正在写入:\(title)。此时请不要退出。"
}
func startWriteCalendar() {
DispatchQueue.global().async {
for exam in self.exams {
self.helper?.addToDate(exam: exam, remind: self.shouldRemind)
}
DispatchQueue.main.async {
self.resumeUI()
ESLog.info("exam sync success.")
self.showInfoMessage(infoMsg: "已完成同步。")
}
}
}
func showError(error: String) {
DispatchQueue.main.async {
let errorAlert: NSAlert = NSAlert()
errorAlert.informativeText = error
errorAlert.messageText = "出错啦"
errorAlert.addButton(withTitle: "嗯")
errorAlert.addButton(withTitle: "打开系统偏好设置")
errorAlert.alertStyle = NSAlert.Style.informational
if self.view.window == nil {
self.resumeUI()
return
}
errorAlert.beginSheetModal(for: self.view.window!) { (returnCode) in
if returnCode == NSApplication.ModalResponse.alertSecondButtonReturn {
openRequestPanel()
}
}
self.resumeUI()
}
ESLog.error("error occurred. message: ", error)
}
@IBAction func restartAnalyse(_ sender: NSButton) {
exams.removeAll()
tableView.reloadData()
updateTableViewContents()
openYearTermSelectionPanel()
}
func disableUI() {
// testInfo.isEnabled = false
tableView.isEnabled = false
syncTo.isEnabled = false
calendarName.isEnabled = false
getRandomName.isEnabled = false
remindMe.isEnabled = false
startSync.isEnabled = false
}
func resumeUI() {
// testInfo.isEnabled = true
tableView.isEnabled = true
syncTo.isEnabled = true
calendarName.isEnabled = true
getRandomName.isEnabled = true
remindMe.isEnabled = true
startSync.isEnabled = true
}
func showInfoMessage(infoMsg: String) {
if view.window == nil {
return
}
let errorAlert: NSAlert = NSAlert()
errorAlert.informativeText = infoMsg
errorAlert.messageText = "提示"
errorAlert.addButton(withTitle: "嗯")
errorAlert.alertStyle = NSAlert.Style.informational
errorAlert.beginSheetModal(for: self.view.window!, completionHandler: nil)
ESLog.info("informative message thrown. message: ", infoMsg)
}
// MARK: - NSTableViewDelegate and NSTableViewDataSource
func numberOfRows(in tableView: NSTableView) -> Int {
return exams.count
}
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
guard let sortDescriptor = tableView.sortDescriptors.first else {
return
}
// NSLog(sortDescriptor.key ?? "badSortArgument")
// NSLog("now ascending == \(sortDescriptor.ascending)")
sortArray(sortDescriptor.key ?? "badSortArgument", !sortDescriptor.ascending)
}
fileprivate enum CellIdentifiers {
static let CourseCell = "CourseIdCell"
static let ExamCell = "ExamNameCell"
static let TimeCell = "TimeCell"
static let RoomCell = "RoomIdCell"
static let SeatCell = "SeatCell"
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if row >= exams.count {
return nil
}
var text: String = ""
var cellIdentifier: String = ""
let item = exams[row]
if tableColumn == tableView.tableColumns[0] {
text = item.courseName ?? "考试科目"
cellIdentifier = CellIdentifiers.CourseCell
// } else if tableColumn == tableView.tableColumns[1] {
// text = item.name ?? "考试名称"
// cellIdentifier = CellIdentifiers.ExamCell
} else if tableColumn == tableView.tableColumns[1] {
text = item.originalTime ?? "未知"
cellIdentifier = CellIdentifiers.TimeCell
} else if tableColumn == tableView.tableColumns[2] {
text = item.location ?? "考试地点"
cellIdentifier = CellIdentifiers.RoomCell
} else if tableColumn == tableView.tableColumns[3] {
text = item.campus ?? "校区"
cellIdentifier = CellIdentifiers.SeatCell
}
if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView {
cell.textField?.stringValue = text
return cell
}
return nil
}
}
<file_sep>/Electsys Utility/AdaptableTableView/TableView.swift
//
// TableView.swift
// TableView
//
// Created by <NAME> on 07/10/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class TableView: BaseView {
var scrollViewTableView: NSScrollView = {
var scrollView = NSScrollView()
scrollView.drawsBackground = false
return scrollView
}()
var stackView: NSStackView = {
var textField = NSTextField()
var exportButton = NSButton()
textField.isEditable = false
textField.isSelectable = false
textField.isBordered = false
textField.backgroundColor = .clear
textField.stringValue = "共有 0 项属性可供检查。"
textField.textColor = .secondaryLabelColor
var font = NSFont(name: "System", size: 11.0)
textField.font = font
exportButton.bezelStyle = .roundRect
exportButton.controlSize = .mini
exportButton.title = "导出"
exportButton.font = font
let stackView = NSStackView(frame: .zero)
stackView.addView(textField, in: .center)
stackView.addView(exportButton, in: .center)
stackView.orientation = .horizontal
stackView.edgeInsets = NSEdgeInsets(top: 4.0, left: 8.0, bottom: 4.0, right: 8.0)
return stackView
}()
var tableView: NSTableView = {
let table = NSTableView(frame: .zero)
// table.rowSizeStyle = .large
table.backgroundColor = .clear
let nameColumn = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "nameColumn"))
table.headerView = nil
nameColumn.width = 70
table.addTableColumn(nameColumn)
let valueColumn = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "valueColumn"))
table.headerView = nil
valueColumn.width = 1
table.addTableColumn(valueColumn)
return table
}()
override func addSubviews() {
scrollViewTableView.documentView = tableView
[scrollViewTableView, stackView].forEach(addSubview)
}
override func addConstraints() {
scrollViewTableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([scrollViewTableView.topAnchor.constraint(equalTo: scrollViewTableView.superview!.topAnchor),
scrollViewTableView.leadingAnchor.constraint(equalTo: scrollViewTableView.superview!.leadingAnchor),
scrollViewTableView.trailingAnchor.constraint(equalTo: scrollViewTableView.superview!.trailingAnchor),
scrollViewTableView.bottomAnchor.constraint(equalTo: stackView.topAnchor),
])
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([stackView.topAnchor.constraint(equalTo: scrollViewTableView.bottomAnchor),
stackView.leadingAnchor.constraint(equalTo: stackView.superview!.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: stackView.superview!.trailingAnchor),
stackView.bottomAnchor.constraint(equalTo: stackView.superview!.bottomAnchor),
])
}
}
<file_sep>/Electsys Utility/VersionComparer.swift
//
// VersionComparer.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/19.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
import Version
@objc open class VersionComparer: NSObject {
@objc static func compare(_ version: NSString, isNewerThanVersion: NSString) -> Bool {
let versionString = String(version).replacingOccurrences(of: "v", with: "")
let anotherVersionString = String(isNewerThanVersion).replacingOccurrences(of: "v", with: "")
guard let versionA = Version(versionString) else {
return true
}
guard let versionB = Version(anotherVersionString) else {
return false
}
ESLog.debug("compare version code %@ and %@. Result is %@", versionString, anotherVersionString, (versionA > versionB).description)
return versionA > versionB
}
}
<file_sep>/Electsys Utility/Electsys Utility/Deprecated_DataGrabKits/CourseAnalyse.swift
//
// CourseAnalyse.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/9/6.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Foundation
import Kanna
func parseCourseDetail(_ htmlDoc: String) -> Curricula? {
let curricula = Curricula()
curricula.teacherName = getByXpath(htmlDoc,
"//*[@id=\"TeacherInfo1_dataListT\"]/tr/td/table/tr[2]/td[2]")
// curricula.codeName =
// getByXpath(htmlDoc, "//*[@id=\"LessonArrangeDetail1_dataListKc\"]/tr/td/table/tr[1]/td[1]").deleteOccur(remove: "课程代码:")
curricula.name =
getByXpath(htmlDoc, "//*[@id=\"LessonArrangeDetail1_dataListKc\"]/tr/td/table/tr[1]/td[2]").deleteOccur(remove: "课程名称:")
curricula.identifier =
getByXpath(htmlDoc, "//*[@id=\"LessonArrangeDetail1_dataListKc\"]/tr/td/table/tr[1]/td[3]").deleteOccur(remove: "课号:")
curricula.year = ConvertToYear(
getByXpath(htmlDoc, "//*[@id=\"LessonArrangeDetail1_dataListKc\"]/tr/td/table/tr[2]/td[2]").deleteOccur(remove: "学年:"))
curricula.term = ConvertToTerm(
getByXpath(htmlDoc, "//*[@id=\"LessonArrangeDetail1_dataListKc\"]/tr/td/table/tr[2]/td[3]").deleteOccur(remove: "学期:"))
// curricula.maximumNumber = Int(
// getByXpath(htmlDoc, "//*[@id=\"LessonArrangeDetail1_dataListKc\"]/tr/td/table/tr[5]/td[1]").deleteOccur(remove: "最大人数:"))!
curricula.studentNumber = Int(
getByXpath(htmlDoc, "//*[@id=\"LessonArrangeDetail1_dataListKc\"]/tr/td/table/tr[5]/td[2]").deleteOccur(remove: "已选课人数:"))!
// curricula.notes =
// getByXpath(htmlDoc, "//*[@id=\"LessonArrangeDetail1_dataListKc\"]/tr/td/table/tr[6]/td[1]").deleteOccur(remove: "备注:")
// if curricula.notes.contains("夏季") {
// curricula.term = .Summer
// 教务处不改学期字段,把信息写在备注里…… 绝了
// }
if curricula.identifier == "0" {
return nil
}
return curricula
}
func parseTeacherDetail(_ htmlDoc: String, _ teachers: inout [Teacher]) -> Bool {
let employeeId = getByXpath(htmlDoc, "//*[@id=\"TeacherInfo1_dataListT\"]/tr/td/table/tr[1]/td[2]")
if findTeacherById(employeeId, &teachers) == -1 {
// 此老师未入库,新建一条
let teacher = Teacher()
teacher.employeeID = employeeId
teacher.name = getByXpath(htmlDoc, "//*[@id=\"TeacherInfo1_dataListT\"]/tr/td/table/tr[2]/td[2]")
if getByXpath(htmlDoc, "//*[@id=\"TeacherInfo1_dataListT\"]/tr/td/table/tr[3]/td[2]") == "女" {
teacher.gender = .Female
} else {
teacher.gender = .Male
}
teachers.append(teacher)
return true
}
return false
}
func getByXpath(_ html: String, _ xpath: String) -> String {
if let html = try? HTML(html: html, encoding: .utf8) {
for i in html.xpath(xpath) {
return sanitize(i.text ?? "0")
}
}
return "0"
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/ScoreQueryViewController.swift
//
// ScoreQueryViewController.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Cocoa
import CSV
@available(OSX 10.12.2, *)
class ScoreQueryViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate, YearAndTermSelectionDelegate, ExportFormatDecisionDelegate {
var scoreList: [NGScore] = []
var openedWindow: NSWindow?
@IBAction func TBButtonTapped(_ sender: NSButton) {
restartAnalyse(sender)
}
@IBOutlet weak var TBButton: NSButton!
@IBOutlet var tableView: NSTableView!
@IBOutlet var promptTextField: NSTextField!
@IBOutlet var blurredView: RMBlurredView!
@IBAction func restartAnalyse(_ sender: NSButton) {
scoreList.removeAll()
tableView.reloadData()
updateTableViewContents()
openYearTermSelectionPanel()
}
@IBAction func calculateGpa(_ sender: NSButton) {
if scoreList.count == 0 {
return
}
let gpaResult = GPAKits.calculateGpa(scores: scoreList)
if gpaResult == nil {
showErrorMessageNormal(errorMsg: "未能成功计算您的平均绩点(GPA)。")
} else {
showGpaMessage(infoMsg: "根据「\(GPAKits.GpaStrategies[PreferenceKits.gpaStrategy.rawValue])」计算,\n您的平均绩点(GPA)为 \(String(format: "%.2f", gpaResult!))。")
}
}
override func viewDidLoad() {
updateTableViewContents()
let sortByName = NSSortDescriptor(key: "sortByName", ascending: true)
let sortByCode = NSSortDescriptor(key: "sortByCode", ascending: true)
let sortByTeacher = NSSortDescriptor(key: "sortByTeacher", ascending: true)
let sortByScore = NSSortDescriptor(key: "sortByScore", ascending: true)
let sortByPoint = NSSortDescriptor(key: "sortByPoint", ascending: true)
tableView.tableColumns[0].sortDescriptorPrototype = sortByName
tableView.tableColumns[1].sortDescriptorPrototype = sortByCode
tableView.tableColumns[2].sortDescriptorPrototype = sortByTeacher
tableView.tableColumns[3].sortDescriptorPrototype = sortByScore
tableView.tableColumns[4].sortDescriptorPrototype = sortByPoint
tableView.target = self
tableView.doubleAction = #selector(tableViewDoubleClick(_:))
super.viewDidLoad()
}
override func viewDidAppear() {
if scoreList.count == 0 {
openYearTermSelectionPanel()
}
updateTableViewContents()
super.viewDidAppear()
}
lazy var sheetViewController: TermSelectingViewController = {
let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
return storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("YearAndTermViewController"))
as! TermSelectingViewController
}()
func successCourseDataTransfer(data: [NGCourse]) {
ESLog.error("bad request type")
dismiss(sheetViewController)
}
func successExamDataTransfer(data: [NGExam]) {
ESLog.error("bad request type")
dismiss(sheetViewController)
}
func successScoreDataTransfer(data: [NGScore]) {
scoreList = data
updateTableViewContents()
dismiss(sheetViewController)
}
func shutWindow() {
dismiss(sheetViewController)
}
func updateTableViewContents() {
if scoreList.count == 0 {
promptTextField.stringValue = "目前没有任何科目的考试成绩。"
view.window?.makeFirstResponder(blurredView)
blurredView.blurRadius = 3.0
blurredView.isHidden = false
if TBButton != nil {
TBButton.isHidden = true
}
return
}
blurredView.isHidden = true
if TBButton != nil {
TBButton.isHidden = false
}
blurredView.blurRadius = 0.0
promptTextField.isEnabled = true
promptTextField.stringValue = "现有 \(scoreList.count) 门科目的考试成绩。"
tableView.reloadData()
}
func openYearTermSelectionPanel() {
sheetViewController.successDelegate = self
sheetViewController.requestType = .score
presentAsSheet(sheetViewController)
sheetViewController.enableUI()
}
func showErrorMessageNormal(errorMsg: String) {
let errorAlert: NSAlert = NSAlert()
errorAlert.informativeText = errorMsg
errorAlert.messageText = "出错啦"
errorAlert.addButton(withTitle: "嗯")
errorAlert.alertStyle = NSAlert.Style.critical
errorAlert.beginSheetModal(for: view.window!)
ESLog.error("error occurred. message: ", errorMsg)
}
func showInformativeMessage(infoMsg: String) {
let infoAlert: NSAlert = NSAlert()
infoAlert.informativeText = infoMsg
infoAlert.messageText = "提醒"
infoAlert.addButton(withTitle: "嗯")
infoAlert.alertStyle = NSAlert.Style.informational
infoAlert.beginSheetModal(for: view.window!)
ESLog.info("informative message: ", infoMsg)
}
func showGpaMessage(infoMsg: String) {
let gpaAlert: NSAlert = NSAlert()
gpaAlert.informativeText = infoMsg
gpaAlert.messageText = "平均绩点计算结果"
gpaAlert.addButton(withTitle: "嗯")
gpaAlert.addButton(withTitle: "了解更多…")
gpaAlert.alertStyle = NSAlert.Style.informational
gpaAlert.beginSheetModal(for: view.window!) { returnCode in
if returnCode == NSApplication.ModalResponse.alertSecondButtonReturn {
if let url = URL(string: "https://apps.chasedream.com/gpa/#"), NSWorkspace.shared.open(url) {
// successfully opened
}
}
}
}
fileprivate enum CellIdentifiers {
static let NameCell = "CourseNameCellID"
static let CodeCell = "CourseCodeCellID"
static let TeacherCell = "TeacherNameCellID"
static let ScoreCell = "FinalScoreCellID"
static let PointCell = "PointCellID"
}
//
// let sortByName = NSSortDescriptor(key: "sortByName", ascending: true)
// let sortByCode = NSSortDescriptor(key: "sortByCode", ascending: true)
// let sortByTeacher = NSSortDescriptor(key: "sortByTeacher", ascending: true)
// let sortByScore = NSSortDescriptor(key: "sortByScore", ascending: true)
// let sortByPoint = NSSortDescriptor(key: "sortByPoint", ascending: true)
func sortArray(_ sortKey: String, _ isAscend: Bool) {
if scoreList.count <= 1 {
return
}
switch sortKey {
case "sortByName":
func titleSorter(p1: NGScore?, p2: NGScore?) -> Bool {
if p1?.courseName == nil {
return p2?.courseName == nil
}
if p2?.courseName == nil {
return p1?.courseName != nil
}
return (p1?.courseName!.compare(p2!.courseName!) == ComparisonResult.orderedAscending) == isAscend
}
scoreList.sort(by: titleSorter)
tableView.reloadData()
break
case "sortByCode":
func codeSorter(p1: NGScore?, p2: NGScore?) -> Bool {
if p1?.courseCode == nil {
return p2?.courseCode == nil
}
if p2?.courseCode == nil {
return p1?.courseCode != nil
}
return (p1?.courseCode!.compare(p2!.courseCode!) == ComparisonResult.orderedDescending) == isAscend
}
scoreList.sort(by: codeSorter)
tableView.reloadData()
break
case "sortByTeacher":
func teacherSorter(p1: NGScore?, p2: NGScore?) -> Bool {
if p1?.teacher == nil {
return p2?.teacher == nil
}
if p2?.teacher == nil {
return p1?.teacher != nil
}
return (p1?.teacher!.compare(p2!.teacher!) == ComparisonResult.orderedAscending) == isAscend
}
scoreList.sort(by: teacherSorter)
tableView.reloadData()
break
case "sortByScore":
func scoreSorter(p1: NGScore?, p2: NGScore?) -> Bool {
if p1?.finalScore == nil {
return p2?.finalScore == nil
}
if p2?.finalScore == nil {
return p1?.finalScore != nil
}
return ((p1?.finalScore ?? 0) > (p2?.finalScore ?? 0)) == isAscend
}
scoreList.sort(by: scoreSorter)
tableView.reloadData()
break
case "sortByPoint":
func pointSorter(p1: NGScore?, p2: NGScore?) -> Bool {
if p1?.scorePoint == nil {
return p2?.scorePoint == nil
}
if p2?.scorePoint == nil {
return p1?.scorePoint != nil
}
return (p1?.scorePoint ?? 0.0 > p2?.scorePoint ?? 0.0) == isAscend
}
scoreList.sort(by: pointSorter)
tableView.reloadData()
break
case "badSortArgument":
showErrorMessageNormal(errorMsg: "排序参数出错。")
break
default:
break
}
}
@objc func tableViewDoubleClick(_ sender: AnyObject) {
if tableView.selectedRow < 0 || tableView.selectedRow >= scoreList.count {
return
}
let scoreObject = scoreList[tableView.selectedRow]
InspectorKits.showProperties(properties: [
Property(name: "课程代码", value: scoreObject.courseCode ?? "N/A"),
Property(name: "课程名称", value: scoreObject.courseName ?? "N/A"),
Property(name: "课程教师", value: scoreObject.teacher ?? "N/A"),
Property(name: "学分", value: String(format: "%.1f", scoreObject.credit ?? 0.0)),
Property(name: "最终成绩", value: "\(scoreObject.finalScore ?? 0)"),
Property(name: "绩点", value: String(format: "%.1f", scoreObject.scorePoint ?? 0.0)),
Property(name: "考试性质", value: scoreObject.status ?? "N/A"),
])
}
// MARK: - NSTableViewDelegate and NSTableViewDataSource
func numberOfRows(in tableView: NSTableView) -> Int {
return scoreList.count
}
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
guard let sortDescriptor = tableView.sortDescriptors.first else {
return
}
// NSLog(sortDescriptor.key ?? "badSortArgument")
// NSLog("now ascending == \(sortDescriptor.ascending)")
sortArray(sortDescriptor.key ?? "badSortArgument", !sortDescriptor.ascending)
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if row >= scoreList.count {
return nil
}
var text: String = ""
var cellIdentifier: String = ""
let item = scoreList[row]
if tableColumn == tableView.tableColumns[0] {
text = item.courseName ?? "课程名称"
cellIdentifier = CellIdentifiers.NameCell
} else if tableColumn == tableView.tableColumns[1] {
text = item.courseCode ?? "课号"
cellIdentifier = CellIdentifiers.CodeCell
} else if tableColumn == tableView.tableColumns[2] {
text = item.teacher ?? "教师"
cellIdentifier = CellIdentifiers.TeacherCell
} else if tableColumn == tableView.tableColumns[3] {
text = "\(item.finalScore ?? 0)"
cellIdentifier = CellIdentifiers.ScoreCell
} else if tableColumn == tableView.tableColumns[4] {
text = String(format: "%.1f", item.scorePoint ?? "0.0")
cellIdentifier = CellIdentifiers.PointCell
}
if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView {
cell.textField?.stringValue = text
return cell
}
return nil
}
let addMyPopover = NSPopover()
@IBAction func clickExportButton(_ sender: NSButton) {
if scoreList.count == 0 {
return
}
let popOverController = ExportFormatSelector()
popOverController.delegate = self
addMyPopover.behavior = .transient
addMyPopover.contentViewController = popOverController
addMyPopover.contentSize = CGSize(width: 250, height: 140)
addMyPopover.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
}
func exportPlainText() {
let csv = try! CSVWriter(stream: .toMemory())
try! csv.write(row: ["绩点", "教师", "课程代码", "课程名称", "考试状态", "最终成绩", "学分"])
for score in scoreList {
try! csv.write(row: [String(format: "%.1f", score.scorePoint ?? 0.0),
(score.teacher ?? "N/A").replacingOccurrences(of: "、", with: " "),
score.courseCode ?? "N/A",
score.courseName ?? "N/A",
score.status ?? "N/A",
"\(score.finalScore ?? 0)",
String(format: "%.1f", score.credit ?? 0.0)])
}
csv.stream.close()
let csvData = csv.stream.property(forKey: .dataWrittenToMemoryStreamKey) as! Data
let textString = String(data: csvData, encoding: .utf8)!
let panel = NSSavePanel()
panel.title = "保存 CSV 格式成绩单"
panel.message = "请选择 CSV 格式成绩单的保存路径。"
panel.nameFieldStringValue = "Transcript"
panel.allowsOtherFileTypes = false
panel.allowedFileTypes = ["csv", "txt"]
panel.isExtensionHidden = false
panel.canCreateDirectories = true
panel.beginSheetModal(for: view.window!, completionHandler: { result in
do {
if result == NSApplication.ModalResponse.OK {
if let path = panel.url?.path {
try textString.write(toFile: path, atomically: true, encoding: .utf8)
self.showInformativeMessage(infoMsg: "已经成功导出 CSV 格式成绩单。")
} else {
return
}
}
} catch {
self.showErrorMessageNormal(errorMsg: "无法导出 CSV 格式成绩单。")
}
})
}
func exportJSONFormat() {
addMyPopover.performClose(self)
do {
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(scoreList)
let jsonString = String(data: jsonData, encoding: String.Encoding.utf8)
let panel = NSSavePanel()
panel.title = "保存 JSON"
panel.message = "请选择 JSON 文稿的保存路径。"
panel.nameFieldStringValue = "Transcript"
panel.allowsOtherFileTypes = false
panel.allowedFileTypes = ["json"]
panel.isExtensionHidden = false
panel.canCreateDirectories = true
panel.beginSheetModal(for: view.window!, completionHandler: { result in
do {
if result == NSApplication.ModalResponse.OK {
if let path = panel.url?.path {
try jsonString?.write(toFile: path, atomically: true, encoding: .utf8)
self.showInformativeMessage(infoMsg: "已经成功导出 JSON 格式成绩单。")
} else {
return
}
}
} catch {
self.showErrorMessageNormal(errorMsg: "无法导出 JSON 表示的成绩单。")
}
})
} catch {
showErrorMessageNormal(errorMsg: "无法导出 JSON 表示的成绩单。")
}
}
}
<file_sep>/Electsys Utility/Electsys Utility/CourseKits/NGCourse.swift
//
// NGCourse.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
struct NGCourse {
var courseIdentifier: String = ""
var courseCode: String = ""
var courseName: String = ""
var courseTeacher: [String] = []
var courseTeacherTitle: [String] = []
var courseRoom: String = ""
var courseDay: Int = -1
var courseScore: Float = 0.0
var dayStartsAt: Int = 0
var dayEndsAt: Int = 0
var weekStartsAt: Int = 0
var weekEndsAt: Int = 0
var shiftWeek: ShiftWeekType = .Both
var notes: String = ""
func getExtraIdentifier() -> String {
var identifier = self.courseName + ","
switch self.shiftWeek {
case .EvenWeekOnly:
identifier += "双周"
break
case .OddWeekOnly:
identifier += "单周"
break
default:
break
}
identifier += dayOfWeekName[self.courseDay]
return identifier
}
func generateCourseName() -> String {
if PreferenceKits.courseDisplayStrategy == .nameOnly {
return "\(courseName)"
} else if PreferenceKits.courseDisplayStrategy == .nameAndTeacher {
return "\(courseName),\(courseTeacher.joined(separator: "、"))"
} else if PreferenceKits.courseDisplayStrategy == .codeNameAndTeacher {
return "\(courseCode) - \(courseName),\(courseTeacher.joined(separator: "、"))"
}
return ""
}
func getTime() -> String {
var timeString = ""
if self.weekStartsAt == self.weekEndsAt {
timeString += "\(self.weekStartsAt) 周"
} else if self.weekEndsAt - self.weekStartsAt == 1 {
timeString += "\(self.weekStartsAt)、\(self.weekEndsAt) 周"
} else {
timeString += "\(self.weekStartsAt) ~ \(self.weekEndsAt) 周"
}
switch self.shiftWeek {
case .EvenWeekOnly:
timeString += "双周"
break
case .OddWeekOnly:
timeString += "单周"
break
default:
break
}
timeString += dayOfWeekName[self.courseDay]
if (self.dayStartsAt == self.dayEndsAt) {
timeString += "第 \(self.dayStartsAt) 节,"
} else {
timeString += " \(self.dayStartsAt) ~ \(self.dayEndsAt) 节,"
}
timeString += getExactTime(startAt: self.dayStartsAt, duration: self.dayEndsAt - self.dayStartsAt + 1)
return timeString
}
}
<file_sep>/Acknowledgements.c
// macmade/GitHubUpdates/LICENSE
// The MIT License (MIT)
// Copyright (c) 2015 <NAME> - www.xs-labs.com / www.digidna.net
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// mxcl/Version/LICENSE
// Apache License
// Version 2.0, January 2004
// http://www.apache.org/licenses/
// TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
// 1. Definitions.
// "License" shall mean the terms and conditions for use, reproduction,
// and distribution as defined by Sections 1 through 9 of this document.
// "Licensor" shall mean the copyright owner or entity authorized by
// the copyright owner that is granting the License.
// "Legal Entity" shall mean the union of the acting entity and all
// other entities that control, are controlled by, or are under common
// control with that entity. For the purposes of this definition,
// "control" means (i) the power, direct or indirect, to cause the
// direction or management of such entity, whether by contract or
// otherwise, or (ii) ownership of fifty percent (50%) or more of the
// outstanding shares, or (iii) beneficial ownership of such entity.
// "You" (or "Your") shall mean an individual or Legal Entity
// exercising permissions granted by this License.
// "Source" form shall mean the preferred form for making modifications,
// including but not limited to software source code, documentation
// source, and configuration files.
// "Object" form shall mean any form resulting from mechanical
// transformation or translation of a Source form, including but
// not limited to compiled object code, generated documentation,
// and conversions to other media types.
// "Work" shall mean the work of authorship, whether in Source or
// Object form, made available under the License, as indicated by a
// copyright notice that is included in or attached to the work
// (an example is provided in the Appendix below).
// "Derivative Works" shall mean any work, whether in Source or Object
// form, that is based on (or derived from) the Work and for which the
// editorial revisions, annotations, elaborations, or other modifications
// represent, as a whole, an original work of authorship. For the purposes
// of this License, Derivative Works shall not include works that remain
// separable from, or merely link (or bind by name) to the interfaces of,
// the Work and Derivative Works thereof.
// "Contribution" shall mean any work of authorship, including
// the original version of the Work and any modifications or additions
// to that Work or Derivative Works thereof, that is intentionally
// submitted to Licensor for inclusion in the Work by the copyright owner
// or by an individual or Legal Entity authorized to submit on behalf of
// the copyright owner. For the purposes of this definition, "submitted"
// means any form of electronic, verbal, or written communication sent
// to the Licensor or its representatives, including but not limited to
// communication on electronic mailing lists, source code control systems,
// and issue tracking systems that are managed by, or on behalf of, the
// Licensor for the purpose of discussing and improving the Work, but
// excluding communication that is conspicuously marked or otherwise
// designated in writing by the copyright owner as "Not a Contribution."
// "Contributor" shall mean Licensor and any individual or Legal Entity
// on behalf of whom a Contribution has been received by Licensor and
// subsequently incorporated within the Work.
// 2. Grant of Copyright License. Subject to the terms and conditions of
// this License, each Contributor hereby grants to You a perpetual,
// worldwide, non-exclusive, no-charge, royalty-free, irrevocable
// copyright license to reproduce, prepare Derivative Works of,
// publicly display, publicly perform, sublicense, and distribute the
// Work and such Derivative Works in Source or Object form.
// 3. Grant of Patent License. Subject to the terms and conditions of
// this License, each Contributor hereby grants to You a perpetual,
// worldwide, non-exclusive, no-charge, royalty-free, irrevocable
// (except as stated in this section) patent license to make, have made,
// use, offer to sell, sell, import, and otherwise transfer the Work,
// where such license applies only to those patent claims licensable
// by such Contributor that are necessarily infringed by their
// Contribution(s) alone or by combination of their Contribution(s)
// with the Work to which such Contribution(s) was submitted. If You
// institute patent litigation against any entity (including a
// cross-claim or counterclaim in a lawsuit) alleging that the Work
// or a Contribution incorporated within the Work constitutes direct
// or contributory patent infringement, then any patent licenses
// granted to You under this License for that Work shall terminate
// as of the date such litigation is filed.
// 4. Redistribution. You may reproduce and distribute copies of the
// Work or Derivative Works thereof in any medium, with or without
// modifications, and in Source or Object form, provided that You
// meet the following conditions:
// (a) You must give any other recipients of the Work or
// Derivative Works a copy of this License; and
// (b) You must cause any modified files to carry prominent notices
// stating that You changed the files; and
// (c) You must retain, in the Source form of any Derivative Works
// that You distribute, all copyright, patent, trademark, and
// attribution notices from the Source form of the Work,
// excluding those notices that do not pertain to any part of
// the Derivative Works; and
// (d) If the Work includes a "NOTICE" text file as part of its
// distribution, then any Derivative Works that You distribute must
// include a readable copy of the attribution notices contained
// within such NOTICE file, excluding those notices that do not
// pertain to any part of the Derivative Works, in at least one
// of the following places: within a NOTICE text file distributed
// as part of the Derivative Works; within the Source form or
// documentation, if provided along with the Derivative Works; or,
// within a display generated by the Derivative Works, if and
// wherever such third-party notices normally appear. The contents
// of the NOTICE file are for informational purposes only and
// do not modify the License. You may add Your own attribution
// notices within Derivative Works that You distribute, alongside
// or as an addendum to the NOTICE text from the Work, provided
// that such additional attribution notices cannot be construed
// as modifying the License.
// You may add Your own copyright statement to Your modifications and
// may provide additional or different license terms and conditions
// for use, reproduction, or distribution of Your modifications, or
// for any such Derivative Works as a whole, provided Your use,
// reproduction, and distribution of the Work otherwise complies with
// the conditions stated in this License.
// 5. Submission of Contributions. Unless You explicitly state otherwise,
// any Contribution intentionally submitted for inclusion in the Work
// by You to the Licensor shall be under the terms and conditions of
// this License, without any additional terms or conditions.
// Notwithstanding the above, nothing herein shall supersede or modify
// the terms of any separate license agreement you may have executed
// with Licensor regarding such Contributions.
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor,
// except as required for reasonable and customary use in describing the
// origin of the Work and reproducing the content of the NOTICE file.
// 7. Disclaimer of Warranty. Unless required by applicable law or
// agreed to in writing, Licensor provides the Work (and each
// Contributor provides its Contributions) on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied, including, without limitation, any warranties or conditions
// of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
// PARTICULAR PURPOSE. You are solely responsible for determining the
// appropriateness of using or redistributing the Work and assume any
// risks associated with Your exercise of permissions under this License.
// 8. Limitation of Liability. In no event and under no legal theory,
// whether in tort (including negligence), contract, or otherwise,
// unless required by applicable law (such as deliberate and grossly
// negligent acts) or agreed to in writing, shall any Contributor be
// liable to You for damages, including any direct, indirect, special,
// incidental, or consequential damages of any character arising as a
// result of this License or out of the use or inability to use the
// Work (including but not limited to damages for loss of goodwill,
// work stoppage, computer failure or malfunction, or any and all
// other commercial damages or losses), even if such Contributor
// has been advised of the possibility of such damages.
// 9. Accepting Warranty or Additional Liability. While redistributing
// the Work or Derivative Works thereof, You may choose to offer,
// and charge a fee for, acceptance of support, warranty, indemnity,
// or other liability obligations and/or rights consistent with this
// License. However, in accepting such obligations, You may act only
// on Your own behalf and on Your sole responsibility, not on behalf
// of any other Contributor, and only if You agree to indemnify,
// defend, and hold each Contributor harmless for any liability
// incurred by, or claims asserted against, such Contributor by reason
// of your accepting any such warranty or additional liability.
// END OF TERMS AND CONDITIONS
// APPENDIX: How to apply the Apache License to your work.
// To apply the Apache License to your work, attach the following
// boilerplate notice, with the fields enclosed by brackets "[]"
// replaced with your own identifying information. (Don't include
// the brackets!) The text should be enclosed in the appropriate
// comment syntax for the file format. We also recommend that a
// file or class name and description of purpose be included on the
// same "printed page" as the copyright notice for easier
// identification within third-party archives.
// Copyright [yyyy] [name of copyright owner]
// 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.
// ## Runtime Library Exception to the Apache 2.0 License: ##
// As an exception, if you use this Software to compile your source code and
// portions of this Software are embedded into the binary product as a result,
// you may redistribute such product without providing attribution as would
// otherwise be required by Sections 4(a), 4(b) and 4(d) of the License.
// tid-kijyun/Kanna/LICENSE
// MIT License
// Copyright (c) 2014 - 2015 <NAME> (@_tid_)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// SwiftyJSON/Alamofire-SwiftyJSON/LICENSE
// The MIT License (MIT)
// Copyright (c) 2014 SwiftyJSON
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Alamofire/LICENSE
// Under the The MIT License (MIT)
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// SwiftyJSON/LICENSE
// The MIT License (MIT)
// Copyright (c) 2017 <NAME>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// raffael/RMBlurredView/LICENSE
// Copyright (c) 2013, <NAME> All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// - 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.
// 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.
// crossroadlabs/Regex/LICENSE
// Apache License
// Version 2.0, January 2004
// http://www.apache.org/licenses/
// TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
// 1. Definitions.
// "License" shall mean the terms and conditions for use, reproduction,
// and distribution as defined by Sections 1 through 9 of this document.
// "Licensor" shall mean the copyright owner or entity authorized by
// the copyright owner that is granting the License.
// "Legal Entity" shall mean the union of the acting entity and all
// other entities that control, are controlled by, or are under common
// control with that entity. For the purposes of this definition,
// "control" means (i) the power, direct or indirect, to cause the
// direction or management of such entity, whether by contract or
// otherwise, or (ii) ownership of fifty percent (50%) or more of the
// outstanding shares, or (iii) beneficial ownership of such entity.
// "You" (or "Your") shall mean an individual or Legal Entity
// exercising permissions granted by this License.
// "Source" form shall mean the preferred form for making modifications,
// including but not limited to software source code, documentation
// source, and configuration files.
// "Object" form shall mean any form resulting from mechanical
// transformation or translation of a Source form, including but
// not limited to compiled object code, generated documentation,
// and conversions to other media types.
// "Work" shall mean the work of authorship, whether in Source or
// Object form, made available under the License, as indicated by a
// copyright notice that is included in or attached to the work
// (an example is provided in the Appendix below).
// "Derivative Works" shall mean any work, whether in Source or Object
// form, that is based on (or derived from) the Work and for which the
// editorial revisions, annotations, elaborations, or other modifications
// represent, as a whole, an original work of authorship. For the purposes
// of this License, Derivative Works shall not include works that remain
// separable from, or merely link (or bind by name) to the interfaces of,
// the Work and Derivative Works thereof.
// "Contribution" shall mean any work of authorship, including
// the original version of the Work and any modifications or additions
// to that Work or Derivative Works thereof, that is intentionally
// submitted to Licensor for inclusion in the Work by the copyright owner
// or by an individual or Legal Entity authorized to submit on behalf of
// the copyright owner. For the purposes of this definition, "submitted"
// means any form of electronic, verbal, or written communication sent
// to the Licensor or its representatives, including but not limited to
// communication on electronic mailing lists, source code control systems,
// and issue tracking systems that are managed by, or on behalf of, the
// Licensor for the purpose of discussing and improving the Work, but
// excluding communication that is conspicuously marked or otherwise
// designated in writing by the copyright owner as "Not a Contribution."
// "Contributor" shall mean Licensor and any individual or Legal Entity
// on behalf of whom a Contribution has been received by Licensor and
// subsequently incorporated within the Work.
// 2. Grant of Copyright License. Subject to the terms and conditions of
// this License, each Contributor hereby grants to You a perpetual,
// worldwide, non-exclusive, no-charge, royalty-free, irrevocable
// copyright license to reproduce, prepare Derivative Works of,
// publicly display, publicly perform, sublicense, and distribute the
// Work and such Derivative Works in Source or Object form.
// 3. Grant of Patent License. Subject to the terms and conditions of
// this License, each Contributor hereby grants to You a perpetual,
// worldwide, non-exclusive, no-charge, royalty-free, irrevocable
// (except as stated in this section) patent license to make, have made,
// use, offer to sell, sell, import, and otherwise transfer the Work,
// where such license applies only to those patent claims licensable
// by such Contributor that are necessarily infringed by their
// Contribution(s) alone or by combination of their Contribution(s)
// with the Work to which such Contribution(s) was submitted. If You
// institute patent litigation against any entity (including a
// cross-claim or counterclaim in a lawsuit) alleging that the Work
// or a Contribution incorporated within the Work constitutes direct
// or contributory patent infringement, then any patent licenses
// granted to You under this License for that Work shall terminate
// as of the date such litigation is filed.
// 4. Redistribution. You may reproduce and distribute copies of the
// Work or Derivative Works thereof in any medium, with or without
// modifications, and in Source or Object form, provided that You
// meet the following conditions:
// (a) You must give any other recipients of the Work or
// Derivative Works a copy of this License; and
// (b) You must cause any modified files to carry prominent notices
// stating that You changed the files; and
// (c) You must retain, in the Source form of any Derivative Works
// that You distribute, all copyright, patent, trademark, and
// attribution notices from the Source form of the Work,
// excluding those notices that do not pertain to any part of
// the Derivative Works; and
// (d) If the Work includes a "NOTICE" text file as part of its
// distribution, then any Derivative Works that You distribute must
// include a readable copy of the attribution notices contained
// within such NOTICE file, excluding those notices that do not
// pertain to any part of the Derivative Works, in at least one
// of the following places: within a NOTICE text file distributed
// as part of the Derivative Works; within the Source form or
// documentation, if provided along with the Derivative Works; or,
// within a display generated by the Derivative Works, if and
// wherever such third-party notices normally appear. The contents
// of the NOTICE file are for informational purposes only and
// do not modify the License. You may add Your own attribution
// notices within Derivative Works that You distribute, alongside
// or as an addendum to the NOTICE text from the Work, provided
// that such additional attribution notices cannot be construed
// as modifying the License.
// You may add Your own copyright statement to Your modifications and
// may provide additional or different license terms and conditions
// for use, reproduction, or distribution of Your modifications, or
// for any such Derivative Works as a whole, provided Your use,
// reproduction, and distribution of the Work otherwise complies with
// the conditions stated in this License.
// 5. Submission of Contributions. Unless You explicitly state otherwise,
// any Contribution intentionally submitted for inclusion in the Work
// by You to the Licensor shall be under the terms and conditions of
// this License, without any additional terms or conditions.
// Notwithstanding the above, nothing herein shall supersede or modify
// the terms of any separate license agreement you may have executed
// with Licensor regarding such Contributions.
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor,
// except as required for reasonable and customary use in describing the
// origin of the Work and reproducing the content of the NOTICE file.
// 7. Disclaimer of Warranty. Unless required by applicable law or
// agreed to in writing, Licensor provides the Work (and each
// Contributor provides its Contributions) on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied, including, without limitation, any warranties or conditions
// of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
// PARTICULAR PURPOSE. You are solely responsible for determining the
// appropriateness of using or redistributing the Work and assume any
// risks associated with Your exercise of permissions under this License.
// 8. Limitation of Liability. In no event and under no legal theory,
// whether in tort (including negligence), contract, or otherwise,
// unless required by applicable law (such as deliberate and grossly
// negligent acts) or agreed to in writing, shall any Contributor be
// liable to You for damages, including any direct, indirect, special,
// incidental, or consequential damages of any character arising as a
// result of this License or out of the use or inability to use the
// Work (including but not limited to damages for loss of goodwill,
// work stoppage, computer failure or malfunction, or any and all
// other commercial damages or losses), even if such Contributor
// has been advised of the possibility of such damages.
// 9. Accepting Warranty or Additional Liability. While redistributing
// the Work or Derivative Works thereof, You may choose to offer,
// and charge a fee for, acceptance of support, warranty, indemnity,
// or other liability obligations and/or rights consistent with this
// License. However, in accepting such obligations, You may act only
// on Your own behalf and on Your sole responsibility, not on behalf
// of any other Contributor, and only if You agree to indemnify,
// defend, and hold each Contributor harmless for any liability
// incurred by, or claims asserted against, such Contributor by reason
// of your accepting any such warranty or additional liability.
// END OF TERMS AND CONDITIONS
// LinusU/node-appdmg/LICENSE
// The MIT License (MIT)
// Copyright (c) 2013 <NAME>
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Alexiuce/macOS-dev-basic/LICENSE
// MIT License
// Copyright (c) 2017 Alexiuce
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// MoralAlberto/NSTableView
// Copyright (c) 2017 <NAME>, www.albertomoral.com.
// All rights reserved.
// App Icon Gear
// 此 App 包含 「App Icon Gear」生成的图标数据。
// 版本 1.5.5 (66)
// Copyright © 2015年 樊航宇. All rights reserved.
// SJTU NIC
// 网络请求服务由 Network & Information Center, Shanghai Jiao Tong University 提供。
// Copyright © 2004-2019 上海交通大学网络信息中心。保留所有权利。
// SJTU “Weiwei”
// 「交大威威」形象图标来自上海交通大学学生军训网站。
// Copyright © 2018 东岳网络工作室。保留所有权利。<file_sep>/Electsys Utility/Electsys Utility/IdentityKits/IdentityKits.swift
//
// IdentityKits.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
class IdentityKits {
static var studentId: String?
static var studentName: String?
static var studentNameEn: String?
}
<file_sep>/README.md
<div align=center>
<img width="150" height="150" src="https://raw.githubusercontent.com/yuetsin/electsys-utility/master/Electsys%20Utility/Icons/Weiwei.png"/>
</div>
# Electsys Utility
上海交通大学教务处实用程序
[](https://github.com/yuetsin/electsys-utility/actions)




# 功能
- [x] 将课程表与考试安排同步到系统日历中
- [x] 查询考试成绩、计算均绩点
- [x] 利用 [NG-Course](https://github.com/yuetsin/NG-Course) 查询全部课程基本信息
- [ ] 导出为标准 ICS 格式
# 致谢
* [tid-kijyun/Kanna](https://github.com/tid-kijyun/Kanna)
* [SwiftyJSON](https://github.com/SwiftyJSON/SwiftyJSON)
* [Alamofire](https://github.com/Alamofire/Alamofire)
* [Alamofire-SwiftyJSON](https://github.com/SwiftyJSON/Alamofire-SwiftyJSON)
* [crossroadlabs/CrossroadRegex](https://github.com/crossroadlabs/Regex)
* [raffael/RMBlurredView](https://github.com/raffael/RMBlurredView)
* [MoralAlberto/NSTableView](https://github.com/MoralAlberto/NSTableView)
* [LinusU/node-appdmg](https://github.com/LinusU/node-appdmg)
* [mxcl/Version](https://github.com/mxcl/Version)
* [macmade/GitHubUpdates](https://github.com/macmade/GitHubUpdates)
* [yaslab/CSV.swift](https://github.com/yaslab/CSV.swift)
# 屏幕截图
## 使用 jAccount 登录
> 通过 jAccount 账号和密码来获取课程信息、考试安排

## 同步课程信息和考试安排


## 查看成绩单

## 偏好设定

## 免登录浏览课程库
### 按教室

### 按教师

### 按课程名称

## 同步课程到系统日历

## 属性检查器
<div align=center>
<img width="300" src="https://raw.githubusercontent.com/yuxiqian/electsys-utility/master/Electsys%20Utility/Screenshots/属性检查器.png"/>
</div>
<file_sep>/Electsys Utility/AdaptableTableView/TableViewController.swift
//
// TableViewViewController.swift
// TableView
//
// Created by <NAME> on 07/10/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
import CSV
class TableViewController: NSViewController, ExportFormatDecisionDelegate {
var mainView: TableView { return view as! TableView }
fileprivate var adapter: AdapterTableView?
@IBOutlet weak var contentView: NSView!
// MARK: View Controller
override func loadView() {
let rect = NSRect(x: 0, y: 0, width: 300, height: 400)
view = TableView(frame: rect)
}
var propertiesEntry: [Property] = []
let addMyPopover = NSPopover()
@IBAction func exportButtonClicked(_ sender: NSButton) {
if propertiesEntry.count == 0 {
return
}
let popOverController = ExportFormatSelector()
popOverController.delegate = self
addMyPopover.behavior = .transient
addMyPopover.contentViewController = popOverController
addMyPopover.contentSize = CGSize(width: 250, height: 140)
addMyPopover.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
}
override func viewDidLoad() {
super.viewDidLoad()
}
func showErrorMessageNormal(errorMsg: String) {
let errorAlert: NSAlert = NSAlert()
errorAlert.informativeText = errorMsg
errorAlert.messageText = "出错啦"
errorAlert.addButton(withTitle: "嗯")
errorAlert.alertStyle = NSAlert.Style.critical
errorAlert.beginSheetModal(for: view.window!)
ESLog.error("error occured. internal message: ", errorMsg)
}
func showInformativeMessage(infoMsg: String) {
let infoAlert: NSAlert = NSAlert()
infoAlert.informativeText = infoMsg
infoAlert.messageText = "提醒"
infoAlert.addButton(withTitle: "嗯")
infoAlert.alertStyle = NSAlert.Style.informational
infoAlert.beginSheetModal(for: view.window!)
ESLog.info("informative message thrown. message: ", infoMsg)
}
func configureTableView(properties: [Property]) {
adapter = AdapterTableView(tableView: mainView.tableView)
adapter?.add(items: properties)
(mainView.stackView.views[0] as! NSTextField).stringValue = "共有 \(properties.count) 项属性可供检查。"
(mainView.stackView.views[1] as! NSButton).action = #selector(exportButtonClicked(_:))
propertiesEntry = properties
}
func exportPlainText() {
let csv = try! CSVWriter(stream: .toMemory())
try! csv.write(row: ["属性名称", "属性值"])
for prop in propertiesEntry {
try! csv.write(row: [prop.name, prop.value])
}
csv.stream.close()
let csvData = csv.stream.property(forKey: .dataWrittenToMemoryStreamKey) as! Data
let textString = String(data: csvData, encoding: .utf8)!
let panel = NSSavePanel()
panel.title = "保存 CSV 格式属性列表"
panel.message = "请选择 CSV 格式属性列表的保存路径。"
panel.nameFieldStringValue = "PropertiesList"
panel.allowsOtherFileTypes = false
panel.allowedFileTypes = ["csv", "txt"]
panel.isExtensionHidden = false
panel.canCreateDirectories = true
panel.beginSheetModal(for: view.window!, completionHandler: { result in
do {
if result == NSApplication.ModalResponse.OK {
if let path = panel.url?.path {
try textString.write(toFile: path, atomically: true, encoding: .utf8)
self.showInformativeMessage(infoMsg: "已经成功导出 CSV 格式属性列表。")
} else {
return
}
}
} catch {
self.showErrorMessageNormal(errorMsg: "无法导出 CSV 格式属性列表。")
}
})
}
func exportJSONFormat() {
addMyPopover.performClose(self)
do {
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(propertiesEntry)
let jsonString = String(data: jsonData, encoding: String.Encoding.utf8)
let panel = NSSavePanel()
panel.title = "保存属性列表"
panel.message = "请选择 JSON 格式属性列表的保存路径。"
panel.nameFieldStringValue = "PropertiesList"
panel.allowsOtherFileTypes = false
panel.allowedFileTypes = ["json"]
panel.isExtensionHidden = false
panel.canCreateDirectories = true
panel.beginSheetModal(for: view.window!, completionHandler: { result in
do {
if result == NSApplication.ModalResponse.OK {
if let path = panel.url?.path {
try jsonString?.write(toFile: path, atomically: true, encoding: .utf8)
self.showInformativeMessage(infoMsg: "已经成功导出 JSON 格式的属性列表。")
} else {
return
}
}
} catch {
self.showErrorMessageNormal(errorMsg: "无法导出 JSON 表示的属性列表。")
}
})
} catch {
showErrorMessageNormal(errorMsg: "无法导出 JSON 表示的属性列表。")
}
}
}
<file_sep>/Electsys Utility/Electsys Utility/Deprecated_DataGrabKits/Teacher.swift
//
// Teacher.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/9/6.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Alamofire
import Kanna
class Teacher {
// She's my favorite teacher.
var employeeID: String = "1024800048"
// 某些老师的工号 ID 里会包含字母…所以不可以用整型存储。
var name: String = "何琼"
var gender: Gender = .Female
var graduateSchool: String = "上海外国语大学"
var rankScore: Float = 100.0
func requestRankScore() {
// let requestUrl = teacherEvaluate + "gh=\(self.employeeID)&xm=\(self.name)"
}
}
func findTeacherById(_ id: String, _ teachers: inout [Teacher]) -> Int {
var index = 0
for t in teachers {
if t.employeeID == id {
return index
}
index += 1
}
return -1
}
enum Gender {
case Male
case Female
}
<file_sep>/Electsys Utility/Electsys Utility/Deprecated_DataGrabKits/CourseQuery.swift
//
// CourseQuery.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/9/5.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Foundation
import Alamofire
let dataBaseUrl = "https://github.com/yuxiqian/sjtu-curricula-data/blob/master/data/"
// bsid 从 330001 开始往后递增遍历就能得到所有课程信息。(但是!没有教室信息 深坑)
let dataGrabUrlHead = "http://electsys.sjtu.edu.cn/edu/lesson/viewLessonArrangeDetail2.aspx?bsid="
// 这个网站很废…说是按教室查找但根本做不到单独获取教室信息。就不用他好了
let searchWithClassroom = "http://electsysq.sjtu.edu.cn/ReportServer/Pages/ReportViewer.aspx?%2fExamArrange%2fLessonArrangeForOthers&rs:Command=Render"
// 教室信息得来这里用课号得到真·详细信息。
let searchWithCourseCode = "http://electsys.sjtu.edu.cn/edu/lesson/LessonQuery.aspx"
// 获取老师评教信息。
let teacherEvaluate = "http://electsys.sjtu.edu.cn/edu/teacher/teacherEvaluateResult.aspx?"
// 后面用gh=(工号)&xm=(名字) 获取信息
// 最早的 bsid 从 330001 开始。
let firstBsid = 330001
class Query {
var delegate: queryDelegate?
func start(_ year: Int, _ term: Int) {
let requestUrl = "\(dataBaseUrl)\(year)/\(term)/"
print("Attempted to request \(requestUrl)")
Alamofire.request(requestUrl).responseData(completionHandler: { response in
let output = String(data: response.data!, encoding: .utf8)!
// print(realOutput)
self.delegate?.judgeResponse(htmlData: output)
})
}
}
<file_sep>/Electsys Utility/Electsys Utility/ExamKits/NGExam.swift
//
// NGExam.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
struct NGExam {
var name: String?
var courseName: String?
var courseCode: String?
var location: String?
var teacher: String?
var startDate: Date?
var endDate: Date?
var campus: String?
var originalTime: String?
func getTime() -> String {
if startDate == nil || endDate == nil {
ESLog.error("invalid NGExam date entry")
return "未知"
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm"
return "\(formatter.string(from: startDate!)) 至 \(formatter.string(from: endDate!))"
}
}
<file_sep>/Electsys Utility/Electsys Utility/LegacyLoginKits/CurriculaHelper.swift
//
// CurriculaHelper.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/12/27.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Cocoa
class CurriculaHelper: NSObject {
}
<file_sep>/Electsys Utility/Electsys Utility/CourseKits/CourseKits.swift
//
// CourseKits.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Alamofire
import Alamofire_SwiftyJSON
import Foundation
import SwiftyJSON
class CourseKits {
static func requestCourseTable(year: Int, term: Int,
handler: @escaping ([NGCourse]) -> Void,
failure: @escaping (Int) -> Void) {
// 1 - "3"
// 2 - "12"
// 3 - "16"
if term < 1 || term > 3 {
failure(-1)
return
}
let termString = CourseConst.termTable[term]
let getParams: Parameters = [
"xnm": year,
"xqm": termString,
]
Alamofire.request(CourseConst.requestUrl,
method: .get,
parameters: getParams).responseSwiftyJSON(completionHandler: { responseJSON in
if responseJSON.error == nil {
let jsonResp = responseJSON.value
if jsonResp != nil {
if !PreferenceKits.hidePersonalInfo {
IdentityKits.studentId = jsonResp?["xsxx"]["XH"].string
IdentityKits.studentName = jsonResp?["xsxx"]["XM"].string
IdentityKits.studentNameEn = jsonResp?["xsxx"]["YWXM"].string
}
var courseList: [NGCourse] = []
for courseObject in jsonResp?["kbList"].arrayValue ?? [] {
let teachers = courseObject["xm"].stringValue.components(separatedBy: ",")
let teacherTitles = courseObject["zcmc"].stringValue.components(separatedBy: ",")
let dayArrangeArray = courseObject["jcs"].stringValue.components(separatedBy: ",")
for dayArrStr in dayArrangeArray {
var dayArrangeList = dayArrStr.components(separatedBy: "-")
if dayArrangeList.count != 2 {
if dayArrangeList.count == 1 {
dayArrangeList.append(dayArrangeList[0])
} else {
ESLog.error("failed to parse dayArrangeList.")
continue
}
}
let weekArrDataList = courseObject["zcd"].stringValue.components(separatedBy: CharacterSet(charactersIn: ";,"))
for weekArrData in weekArrDataList {
var weekArrangeList = weekArrData.components(separatedBy: CharacterSet(charactersIn: "-周"))
if weekArrangeList.count == 1 {
weekArrangeList.append(weekArrangeList[0])
}
if weekArrangeList[1] == "" {
weekArrangeList[1] = weekArrangeList[0]
}
var dualType = ShiftWeekType.Both
if weekArrData.contains("(单)") {
dualType = .OddWeekOnly
} else if weekArrData.contains("(双)") {
dualType = .EvenWeekOnly
}
let dayStartsAtInt = Int(dayArrangeList[0])
let dayEndsAtInt = Int(dayArrangeList[1])
let weekStartsAtInt = Int(weekArrangeList[0])
let weekEndsAtInt = Int(weekArrangeList[1])
if dayStartsAtInt == nil {
ESLog.error("failed to convert dayStartsAt %@ to string of %@", dayArrangeList[0], courseObject["zcd"].string ?? "<json>")
continue
}
if dayEndsAtInt == nil {
ESLog.error("failed to convert dayEndsAt %@ to string of %@", dayArrangeList[1], courseObject["zcd"].string ?? "<json>")
continue
}
if weekStartsAtInt == nil {
ESLog.error("failed to convert weekStartsAt %@ to string of %@", weekArrangeList[0], courseObject["zcd"].string ?? "<json>")
continue
}
if weekEndsAtInt == nil {
ESLog.error("failed to convert weekEndsAt %@ to string of %@", weekArrangeList[1], courseObject["zcd"].string ?? "<json>")
continue
}
courseList.append(NGCourse(courseIdentifier: courseObject["jxbmc"].stringValue,
courseCode: courseObject["kch_id"].stringValue,
courseName: courseObject["kcmc"].stringValue,
courseTeacher: teachers,
courseTeacherTitle: teacherTitles,
courseRoom: courseObject["cdmc"].stringValue,
courseDay: courseObject["xqj"].intValue,
courseScore: courseObject["xf"].floatValue,
dayStartsAt: dayStartsAtInt!,
dayEndsAt: dayEndsAtInt!,
weekStartsAt: weekStartsAtInt!,
weekEndsAt: weekEndsAtInt!,
shiftWeek: dualType,
notes: courseObject["xkbz"].stringValue))
}
}
}
handler(courseList)
} else {
failure(-3)
}
} else {
failure(-2)
}
})
}
}
<file_sep>/Electsys Utility/package.sh
# Type a script or drag a script file from your workspace to insert its path.
echo ${SRCROOT}
# 创建 Result 目录
RESULT_DIR=${SRCROOT}/Result
if [ -e "${RESULT_DIR}" ] ;then
rm -r "${RESULT_DIR}"
fi
mkdir "${RESULT_DIR}"
echo "Copy app to result dir"
# 拷贝资源到result目录
RESOURCE_DIR=${SRCROOT}/Dist/
cp -R "${RESOURCE_DIR}" "${RESULT_DIR}"
# 拷贝 app 文件到result目录
PRODUCT_NAME=Electsys\ Utility
PRODUCT_APP="${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app"
cp -R "${PRODUCT_APP}" "${RESULT_DIR}/${PRODUCT_NAME}.app"
cd "${RESULT_DIR}"
# package dmg
echo "package dmg..."
appdmg appdmg.json "${PRODUCT_NAME}.dmg"
# remove no used files
rm -rf *.app
find . -type f -not -name '*.dmg' | xargs rm -rf
<file_sep>/Electsys Utility/Electsys Utility/ViewController/FullDataWindowController.swift
//
// FullDataWindowController.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/12/9.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Cocoa
class FullDataWindowController: NSWindowController {
@IBOutlet weak var toolBar: NSToolbar!
@IBOutlet weak var useBetaSwitcher: NSToolbarItem!
@IBOutlet weak var infoChecker: NSToolbarItem!
@IBAction func switchBeta(_ sender: NSToolbarItem) {
(self.contentViewController as! FullDataViewController).setLayoutType(.shrink)
if !(self.contentViewController as! FullDataViewController).shouldRequestBeta {
// sender.label = "使用 “Beta” 版数据"
toolBar.selectedItemIdentifier = sender.itemIdentifier
(self.contentViewController as! FullDataViewController).shouldRequestBeta = true
} else {
// sender.label = "使用稳定版数据"
toolBar.selectedItemIdentifier = nil
(self.contentViewController as! FullDataViewController).shouldRequestBeta = false
}
}
@IBAction func showInfo(_ sender: NSToolbarItem) {
(self.contentViewController as! FullDataViewController).showDataInfo()
}
override func windowDidLoad() {
super.windowDidLoad()
infoChecker.isEnabled = false
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/TransparentTitleWindowController.swift
//
// TransparentTitleWindowController.swift
// Electsys Utility
//
// Created by yuxiqian on 2018/10/14.
// Copyright © 2018年 yuxiqian. All rights reserved.
//
import Cocoa
class TransparentTitleWindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
window?.titlebarAppearsTransparent = true
window?.isMovableByWindowBackground = true
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
@available(OSX 10.12.2, *)
override func makeTouchBar() -> NSTouchBar? {
guard let viewController = contentViewController as? MainViewController else {
ESLog.error("invalid MainViewController instance")
return nil
}
return viewController.makeTouchBar()
}
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/AboutViewController.swift
//
// AboutViewController.swift
// cai-yun
//
// Created by yuxiqian on 2018/10/2.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Cocoa
class AboutViewController: NSViewController {
var windowController: NSWindowController?
static var updater: GitHubUpdater {
let updater = GitHubUpdater()
updater.user = "yuetsin"
updater.repository = "electsys-utility"
ESLog.info("updater initialized")
return updater
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")
let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")
let pI = ProcessInfo.init()
let systemVersion = pI.operatingSystemVersionString
ESLog.info("app version: %@", version as? String ?? "unknown")
ESLog.info("system version: %@", systemVersion)
self.versionLabel.stringValue = "App 版本 \(version ?? "未知") (\(build ?? "未知"))"
self.systemLabel.stringValue = "运行在 macOS \(systemVersion)"
}
@IBAction func turnCredits(_ sender: NSButton) {
// let storyboard = NSStoryboard(name: "Main", bundle: nil)
// windowController = storyboard.instantiateController(withIdentifier: "Credits Window Controller") as? NSWindowController
// windowController?.showWindow(sender)
(self.view.window?.contentViewController as! MainViewController).visitCreditsPage()
// (self.parent as! MainViewController).visitCreditsPage()
}
@IBAction func goToGithubPages(_ sender: NSButton) {
if let url = URL(string: "https://github.com/yuetsin/electsys-utility"), NSWorkspace.shared.open(url) {
ESLog.info("goes to github pages")
}
}
@IBAction func shutWindow(_ sender: NSButton) {
self.view.window?.close()
}
@IBAction func checkForUpdates(_ sender: NSButton) {
AboutViewController.updater.checkForUpdates(sender)
}
@IBOutlet weak var versionLabel: NSTextField!
@IBOutlet weak var systemLabel: NSTextField!
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/ResolveViewController.swift
//
// ResolveViewController.swift
// Sync Utility
//
// Created by yuxiqian on 2018/8/31.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Cocoa
import EventKit
@available(OSX 10.12.2, *)
class ResolveViewController: NSViewController, writeCalendarDelegate, YearAndTermSelectionDelegate {
@IBOutlet weak var resolveTBButton: NSButton!
@IBAction func resolveAnotherTerm(_ sender: NSButton) {
restartAnalyse(sender)
}
func successCourseDataTransfer(data: [NGCourse]) {
courseList = data
updatePopUpSelector()
self.dismiss(sheetViewController)
}
func successExamDataTransfer(data: [NGExam]) {
ESLog.error("bad request type")
self.dismiss(sheetViewController)
}
func successScoreDataTransfer(data: [NGScore]) {
ESLog.error("bad request type")
self.dismiss(sheetViewController)
}
func shutWindow() {
self.dismiss(sheetViewController)
}
override func viewDidLoad() {
updatePopUpSelector()
startWeekSelector.dateValue = Date()
onDatePicked(startWeekSelector)
loadingRing.startAnimation(self)
loadingTextField.stringValue = ""
// courseIdentifierField.isEnabled = false
// courseScoreField.isEnabled = false
// courseTimeField.isEnabled = false
}
override func viewDidAppear() {
super.viewDidAppear()
if courseList.count == 0 {
openYearTermSelectionPanel()
}
PreferenceKits.readPreferences()
if PreferenceKits.hidePersonalInfo {
showPersonalInfoButton.isHidden = true
} else {
showPersonalInfoButton.isHidden = false
}
}
func openYearTermSelectionPanel() {
sheetViewController.successDelegate = self
sheetViewController.requestType = .course
self.presentAsSheet(sheetViewController)
sheetViewController.enableUI()
}
lazy var sheetViewController: TermSelectingViewController = {
let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
return storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("YearAndTermViewController"))
as! TermSelectingViewController
}()
var htmlDoc: String = ""
var courseList: [NGCourse] = []
var startDate: Date?
var inputCounter: Int = 0
var expectedCounter: Int = 0
var calendarHelper: CalendarHelper?
var remindState: remindType = .fifteenMinutes
@IBOutlet var coursePopUpList: NSPopUpButton!
@IBOutlet var promptTextField: NSTextField!
@IBOutlet var willRemindBox: NSButton!
@IBOutlet var remindTypeSelector: NSPopUpButton!
@IBOutlet var startWeekSelector: NSDatePicker!
@IBOutlet var startWeekIndicator: NSTextField!
@IBOutlet var syncAccountType: NSPopUpButton!
@IBOutlet var calendarTextField: NSTextField!
@IBOutlet var loadingRing: NSProgressIndicator!
@IBOutlet var relsamaHouwyButton: NSButton!
@IBOutlet var startSyncButton: NSButton!
@IBOutlet var courseNameField: NSTextField!
@IBOutlet var courseRoomField: NSTextField!
@IBOutlet var courseIdentifierField: NSTextField!
@IBOutlet var courseScoreField: NSTextField!
@IBOutlet var courseTimeField: NSTextField!
@IBOutlet var loadingTextField: NSTextField!
@IBOutlet var diceButton: NSButton!
@IBOutlet weak var blurredView: RMBlurredView!
@IBOutlet weak var showPersonalInfoButton: NSButton!
@IBOutlet weak var showInspectorButton: NSButton!
@IBAction func showInspector(_ sender: NSButton) {
if coursePopUpList.indexOfSelectedItem < 0 || coursePopUpList.indexOfSelectedItem >= courseList.count {
return
}
let courseObject = courseList[coursePopUpList.indexOfSelectedItem]
var shiftWeekProperty = Property(name: "行课安排", value: "每周上课")
if courseObject.shiftWeek == .OddWeekOnly {
shiftWeekProperty.value = "仅单数周上课"
} else if courseObject.shiftWeek == .EvenWeekOnly {
shiftWeekProperty.value = "仅双数周上课"
}
InspectorKits.showProperties(properties: [
Property(name: "课号", value: courseObject.courseCode),
Property(name: "教学班 ID", value: courseObject.courseIdentifier),
Property(name: "课名", value: courseObject.courseName),
Property(name: "教室", value: courseObject.courseRoom),
Property(name: "学分", value: String.init(format: "%.1f", courseObject.courseScore)),
Property(name: "教师", value: courseObject.courseTeacher.joined(separator: "、")),
Property(name: "教师职称", value: courseObject.courseTeacherTitle.joined(separator: "、")),
Property(name: "上课时间", value: "\(defaultLessonTime[courseObject.dayStartsAt].getTimeString())"),
Property(name: "下课时间", value: "\(defaultLessonTime[courseObject.dayEndsAt].getTimeString(passed: durationMinutesOfLesson))"),
Property(name: "备注信息", value: courseObject.notes),
Property(name: "开始周数", value: "第 \(courseObject.weekStartsAt) 周"),
Property(name: "结束周数", value: "第 \(courseObject.weekEndsAt) 周"),
shiftWeekProperty
])
}
@IBAction func showPersonalInfo(_ sender: NSButton) {
if PreferenceKits.hidePersonalInfo {
showErrorMessageNormal(errorMsg: "当前的安全设置不允许显示个人信息。")
return
}
if IdentityKits.studentId == nil || IdentityKits.studentName == nil || IdentityKits.studentNameEn == nil {
showErrorMessageNormal(errorMsg: "未能获取个人信息。")
return
}
InspectorKits.showProperties(properties: [Property(name: "姓名", value: IdentityKits.studentName!),
Property(name: "英文名", value: IdentityKits.studentNameEn!),
Property(name: "学号", value: IdentityKits.studentId!)])
}
func disableUI() {
coursePopUpList.isEnabled = false
willRemindBox.isEnabled = false
remindTypeSelector.isEnabled = false
startWeekSelector.isEnabled = false
syncAccountType.isEnabled = false
courseNameField.isEnabled = false
courseRoomField.isEnabled = false
calendarTextField.isEnabled = false
relsamaHouwyButton.isEnabled = false
startSyncButton.isEnabled = false
diceButton.isEnabled = false
loadingRing.isHidden = false
if (resolveTBButton != nil) {
resolveTBButton.isHidden = true
}
}
func resumeUI() {
coursePopUpList.isEnabled = true
willRemindBox.isEnabled = true
remindTypeSelector.isEnabled = true
startWeekSelector.isEnabled = true
syncAccountType.isEnabled = true
courseNameField.isEnabled = true
courseRoomField.isEnabled = true
calendarTextField.isEnabled = true
relsamaHouwyButton.isEnabled = true
startSyncButton.isEnabled = true
diceButton.isEnabled = true
loadingRing.isHidden = true
if (resolveTBButton != nil) {
resolveTBButton.isHidden = false
}
remindTapped(willRemindBox)
updatePopUpSelector()
}
@IBAction func remindTapped(_ sender: NSButton) {
if willRemindBox.state == NSControl.StateValue.on {
remindTypeSelector.isEnabled = true
switch remindTypeSelector.selectedItem!.title {
case "上课前 15 分钟":
remindState = .fifteenMinutes
break
case "上课前 10 分钟":
remindState = .tenMinutes
break
case "上课时":
remindState = .atCourseStarts
break
default:
remindState = .noReminder
}
} else {
remindTypeSelector.isEnabled = false
remindState = .noReminder
}
}
@IBAction func updateRemindState(_ sender: NSPopUpButton) {
remindTapped(willRemindBox)
}
@IBAction func restartAnalyse(_ sender: NSButton) {
loadingTextField.stringValue = ""
courseList.removeAll()
updatePopUpSelector()
openYearTermSelectionPanel()
}
@IBAction func makeRandomName(_ sender: NSButton) {
calendarTextField.stringValue = getRandomNames()
}
@IBAction func popUpClicked(_ sender: NSPopUpButton) {
updateInfoField()
}
@IBAction func checkSummerBox(_ sender: NSButton) {
onDatePicked(startWeekSelector)
updatePopUpSelector()
}
@IBAction func removePiece(_ sender: NSButton) {
if coursePopUpList.itemArray.count == 0 {
return
}
let index = coursePopUpList.selectedItem?.indexIn((coursePopUpList?.itemArray)!)
if index == nil || index == -1 {
return
}
courseList.remove(at: index!)
updatePopUpSelector()
}
@IBAction func saveInfo(_ sender: NSButton) {
if coursePopUpList.itemArray.count == 0 {
return
}
let index = coursePopUpList.selectedItem?.indexIn((coursePopUpList?.itemArray)!)
if index == nil || index == -1 {
return
}
courseList[index!].courseName = courseNameField.stringValue
courseList[index!].courseRoom = courseRoomField.stringValue
updatePopUpSelector(at: index!)
}
@IBAction func onDatePicked(_ sender: NSDatePicker) {
var startDate = sender.dateValue
while startDate.getWeekDay() > 1 {
startDate = startDate.addingTimeInterval(-secondsInDay)
// print("Date: \(startDate.getStringExpression()), weekday: \(startDate.getWeekDay())")
}
startWeekIndicator.stringValue =
"以 \(startDate.getStringExpression()),星期一作为此学期第一周的开始。"
self.startDate = startDate
}
// @IBAction func addExampleEvent(_ sender: NSButton) {
// addToCalendar(date: self.startWeekSelector.dateValue,
// title: "Example Title",
// place: "Example Location",
// start: defaultLessonTime[2],
// end: defaultLessonTime[4],
// remindType: .tenMinutes)
// }
@IBAction func startSync(_ sender: NSButton) {
if courseList.count == 0 {
showErrorMessageNormal(errorMsg: "没有任何待同步的课表。")
return
}
inputCounter = 0
expectedCounter = 0
print("课表的名字:\(calendarTextField.stringValue)")
if calendarTextField.stringValue == "" {
calendarTextField.stringValue = "jAccount 同步"
}
switch syncAccountType.selectedItem!.title {
case "CalDAV 或 iCloud 日历":
calendarHelper = CalendarHelper(name: calendarTextField.stringValue,
type: .calDAV, delegate: self)
break
case "Mac 上的本地日历":
calendarHelper = CalendarHelper(name: calendarTextField.stringValue,
type: .local, delegate: self)
break
default:
return
}
disableUI()
// calendarHelper.commitChanges()
}
func updatePopUpSelector(at itemIndex: Int = 0) {
coursePopUpList.removeAllItems()
if courseList.count == 0 {
promptTextField.stringValue = "目前没有任何课程信息。"
view.window?.makeFirstResponder(blurredView)
blurredView.blurRadius = 3.0
blurredView.isHidden = false
promptTextField.isEnabled = false
showPersonalInfoButton.isEnabled = false
showInspectorButton.isEnabled = false
courseNameField.stringValue = ""
courseRoomField.stringValue = ""
courseIdentifierField.stringValue = ""
courseScoreField.stringValue = ""
courseTimeField.stringValue = ""
return
}
showInspectorButton.isEnabled = true
blurredView.isHidden = true
blurredView.blurRadius = 0.0
if IdentityKits.studentId == nil || IdentityKits.studentName == nil || IdentityKits.studentNameEn == nil {
showPersonalInfoButton.isEnabled = false
} else {
showPersonalInfoButton.isEnabled = true
}
promptTextField.isEnabled = true
promptTextField.stringValue = "现有 \(courseList.count) 条课程信息。"
var counter = 1
for course in courseList {
coursePopUpList.addItem(withTitle: "(\(counter)) " + course.getExtraIdentifier())
counter += 1
}
if itemIndex != 0 {
coursePopUpList.selectItem(at: itemIndex)
}
updateInfoField()
}
func startWriteCalendar() {
DispatchQueue.global().async {
for course in self.courseList {
for week in generateArray(start: course.weekStartsAt,
end: course.weekEndsAt,
shift: course.shiftWeek) {
self.expectedCounter += 1
self.calendarHelper!.addToCalendar(date: self.startDate!.convertWeekToDate(week: week, weekday: course.courseDay),
title: course.generateCourseName(),
place: course.courseRoom,
start: defaultLessonTime[course.dayStartsAt],
end: defaultLessonTime[course.dayEndsAt].getTime(passed: durationMinutesOfLesson),
remindType: self.remindState)
}
}
}
}
func updateInfoField() {
let index = coursePopUpList.selectedItem?.indexIn((coursePopUpList?.itemArray)!)
if index == nil || index == -1 {
return
}
let displayCourse = courseList[index!]
courseNameField.stringValue = displayCourse.courseName
courseRoomField.stringValue = displayCourse.courseRoom
courseIdentifierField.stringValue = displayCourse.courseCode
courseScoreField.stringValue = String(format: "%.1f", arguments: [displayCourse.courseScore])
courseTimeField.stringValue = displayCourse.getTime()
}
func didWriteEvent(title: String) {
DispatchQueue.main.async {
self.inputCounter += 1
self.loadingTextField.stringValue = "正在创建「\(title)」。不要现在退出。"
if self.inputCounter == self.expectedCounter {
self.loadingTextField.stringValue = "已经成功写入 \(self.inputCounter) / \(self.expectedCounter) 个日历事件。"
ESLog.info("written %@ items into calendar", self.expectedCounter)
self.resumeUI()
}
}
}
func showErrorMessage(errorMsg: String) {
let errorAlert: NSAlert = NSAlert()
errorAlert.informativeText = errorMsg
errorAlert.messageText = "出错啦"
errorAlert.addButton(withTitle: "嗯")
errorAlert.addButton(withTitle: "打开系统偏好设置")
errorAlert.alertStyle = NSAlert.Style.informational
errorAlert.beginSheetModal(for: view.window!) { returnCode in
if returnCode == NSApplication.ModalResponse.alertSecondButtonReturn {
openRequestPanel()
}
}
ESLog.error("error occured. message: ", errorMsg)
}
func showErrorMessageNormal(errorMsg: String) {
let errorAlert: NSAlert = NSAlert()
errorAlert.informativeText = errorMsg
errorAlert.messageText = "出错啦"
errorAlert.addButton(withTitle: "嗯")
errorAlert.alertStyle = NSAlert.Style.informational
errorAlert.beginSheetModal(for: view.window!)
ESLog.error("error occured. message: ", errorMsg)
}
func showError(error: String) {
DispatchQueue.main.async {
self.showErrorMessage(errorMsg: error)
self.resumeUI()
}
}
}
protocol writeCalendarDelegate: NSObjectProtocol {
func didWriteEvent(title: String) -> Void
func startWriteCalendar() -> Void
func showError(error: String) -> Void
}
protocol readInHTMLDelegate: NSObjectProtocol {
var htmlDoc: String { get set }
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/FeedBackViewController.swift
//
// FeedBackViewController.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/16.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Cocoa
class FeedBackViewController: NSViewController {
var issueType: String = "App 功能问题"
override func viewDidLoad() {
super.viewDidLoad()
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")
let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")
self.versionField.stringValue = "app version \(version ?? "N/A") (\(build ?? "N/A"))"
}
@IBAction func visitGitHubIssuePages(_ sender: NSButton) {
if let url = URL(string: "https://github.com/yuetsin/electsys-utility/issues"), NSWorkspace.shared.open(url) {
// successfully opened
ESLog.info("goes to GitHub issues")
}
}
@IBAction func switchIssueType(_ sender: NSButton) {
issueType = sender.title
}
@IBOutlet weak var versionField: NSTextField!
@IBOutlet weak var subjectField: NSTextField!
@IBOutlet var contentField: NSTextView!
@IBAction func sendEmail(_ sender: NSButton) {
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")
let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")
let pI = ProcessInfo.init()
let systemVersion = pI.operatingSystemVersionString
let mailService = NSSharingService(named: NSSharingService.Name.composeEmail)!
mailService.recipients = ["<EMAIL>"]
mailService.subject = "[es-util feedback] [\(issueType)] " + subjectField.stringValue
mailService.perform(withItems: [contentField.string + "\n\nSystem version: \(systemVersion)\nApp version: \(version ?? "unknown"), build \(build ?? "unknown")"])
}
}
<file_sep>/Electsys Utility/Electsys Utility/PreferenceKits/PreferenceKits.swift
//
// PreferenceKits.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
class PreferenceKits {
static func registerPreferenceKeys() {
UserDefaults.standard.register(defaults: [
"gpaStrategy" : GPACalculationStrategy.SJTU_4_3.rawValue,
"courseDisplayStrategy": CourseNameDisplayStrategy.nameAndTeacher.rawValue,
"hidePersonalInfo": true,
"autoFillTokens": false,
"autoFillUserName": "",
"autoFillPassWord": ""
])
}
static var courseDisplayStrategy: CourseNameDisplayStrategy = .nameAndTeacher
static var gpaStrategy: GPACalculationStrategy = .SJTU_4_3
static var hidePersonalInfo: Bool = true
static var autoFillTokens: Bool = false
static var autoFillUserName: String = ""
static var autoFillPassWord: String = ""
static func readPreferences() {
PreferenceKits.courseDisplayStrategy = CourseNameDisplayStrategy(rawValue: UserDefaults.standard.integer(forKey: "courseDisplayStrategy")) ?? .nameAndTeacher
PreferenceKits.gpaStrategy = GPACalculationStrategy(rawValue: UserDefaults.standard.integer(forKey: "gpaStrategy")) ?? .SJTU_4_3
PreferenceKits.hidePersonalInfo = UserDefaults.standard.bool(forKey: "hidePersonalInfo")
PreferenceKits.autoFillTokens = UserDefaults.standard.bool(forKey: "autoFillTokens")
if PreferenceKits.autoFillTokens {
PreferenceKits.autoFillUserName = UserDefaults.standard.string(forKey: "autoFillUserName") ?? ""
PreferenceKits.autoFillPassWord = UserDefaults.standard.string(forKey: "autoFillPassWord") ?? ""
}
}
static func savePreferences() {
UserDefaults.standard.set(PreferenceKits.courseDisplayStrategy.rawValue, forKey: "courseDisplayStrategy")
UserDefaults.standard.set(PreferenceKits.gpaStrategy.rawValue, forKey: "gpaStrategy")
UserDefaults.standard.set(PreferenceKits.hidePersonalInfo, forKey: "hidePersonalInfo")
UserDefaults.standard.set(PreferenceKits.autoFillTokens, forKey: "autoFillTokens")
if PreferenceKits.autoFillTokens {
UserDefaults.standard.set(PreferenceKits.autoFillUserName, forKey: "autoFillUserName")
UserDefaults.standard.set(PreferenceKits.autoFillPassWord, forKey: "<PASSWORD>Fill<PASSWORD>Word")
}
}
static func removeCertificates() {
UserDefaults.standard.set(false, forKey: "autoFillTokens")
UserDefaults.standard.set("", forKey: "autoFillUserName")
UserDefaults.standard.set("", forKey: "autoFillPassWord")
}
}
enum CourseNameDisplayStrategy: Int {
case nameAndTeacher = 0
case codeNameAndTeacher = 1
case nameOnly = 2
}
enum GPACalculationStrategy: Int {
case Normal_4_0 = 0
case Improved_4_0_A = 1
case Improved_4_0_B = 2
case PKU_4_0 = 3
case Canadian_4_3 = 4
case USTC_4_3 = 5
case SJTU_4_3 = 6
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/jAccountViewController.swift
//
// ViewController.swift
// Sync Utility
//
// Created by yuxiqian on 2018/8/29.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Alamofire
import Cocoa
import Foundation
import Kanna
class jAccountViewController: NSViewController, WebLoginDelegate {
func validateLoginResult(htmlData: String) {
// reset
}
func forceResetAccount() {
// reset
}
// var windowController: NSWindowController?
var htmlDelegate: readInHTMLDelegate?
var UIDelegate: UIManagerDelegate?
override func viewWillAppear() {
checkLoginStatus()
}
override func viewDidLoad() {
setAccessibilityLabel()
successImage.image = NSImage(named: "NSStatusNone")
loginStateText.stringValue = "您尚未登入。"
}
func setAccessibilityLabel() {
accessNewElectsys.setAccessibilityLabel("访问教学信息服务网")
// accessLegacyElectsys.setAccessibilityLabel("访问旧版教学信息服务网")
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
// var requestDelegate: requestHtmlDelegate?
// var inputDelegate: inputHtmlDelegate?
@IBOutlet var accessNewElectsys: NSButton!
// @IBOutlet var accessLegacyElectsys: NSButton!
// @IBOutlet var userNameField: NSTextField!
// @IBOutlet var passwordField: NSSecureTextField!
// @IBOutlet var captchaTextField: NSTextField!
// @IBOutlet var captchaImage: NSImageView!
// @IBOutlet var loginButton: NSButton!
// @IBOutlet var refreshCaptchaButton: NSButton!
// @IBOutlet var resetButton: NSButton!
//// @IBOutlet weak var manualOpenButton: NSButton!
// @IBOutlet var loadingIcon: NSProgressIndicator!
//// @IBOutlet weak var expandButton: NSButton!
//// @IBOutlet weak var operationSelector: NSPopUpButton!
//// @IBOutlet weak var checkHistoryButton: NSButton!
@IBOutlet var successImage: NSImageView!
@IBOutlet var loginStateText: NSTextField!
// @IBOutlet weak var switchAccountButton: NSButton!
@IBOutlet var exportCookieButton: NSButton!
lazy var embedWebVC: WebLoginViewController = {
let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
return storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("WebLoginViewController"))
as! WebLoginViewController
}()
lazy var cookieParserVC: CookieParserViewController = {
let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
return storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("CookieParserViewController"))
as! CookieParserViewController
}()
@IBAction func loginViaWebPage(_ sender: NSButton) {
if #available(OSX 10.13, *) {
embedWebVC.delegate = self
presentAsSheet(embedWebVC)
} else {
showErrorMessage(errorMsg: "当前运行的系统版本低于 macOS 10.13。\n囿于 WKWebView API 的限制,无法使用 Web 登录功能。")
}
}
@IBAction func exportCookieButton(_ sender: NSButton) {
guard let cookies = Alamofire.HTTPCookieStorage.shared.cookies else {
showErrorMessage(errorMsg: "没有可用于导出的 HTTP Cookie Storage。")
return
}
var cookieArray = [[HTTPCookiePropertyKey: Any]]()
for cookie in cookies {
cookieArray.append(cookie.properties!)
}
let data = NSKeyedArchiver.archivedData(withRootObject: cookieArray)
let panel = NSSavePanel()
panel.title = "导出 HTTP Cookies"
panel.message = "请选择 HTTP Cookies 的保存路径。"
panel.nameFieldStringValue = "cookie"
panel.allowsOtherFileTypes = false
panel.allowedFileTypes = ["plist"]
panel.isExtensionHidden = false
panel.canCreateDirectories = true
panel.beginSheetModal(for: view.window!, completionHandler: { result in
do {
if result == NSApplication.ModalResponse.OK {
if let path = panel.url?.path {
try data.write(to: URL(fileURLWithPath: path))
self.showInformativeMessage(infoMsg: "已经成功导出 HTTP Cookies。")
} else {
return
}
}
} catch {
self.showErrorMessage(errorMsg: "无法导出 HTTP Cookies。")
}
})
}
fileprivate func importCookie() {
let panel = NSOpenPanel()
panel.title = "读取 HTTP Cookies"
panel.message = "请选择要加载的 HTTP Cookies 的路径。"
panel.allowsOtherFileTypes = false
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
panel.allowedFileTypes = ["plist"]
panel.isExtensionHidden = false
panel.beginSheetModal(for: view.window!) { (result) in
do {
if result == NSApplication.ModalResponse.OK {
if let path = panel.url?.path {
let cookieArray = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? [[HTTPCookiePropertyKey: Any]]
if cookieArray == nil {
ESLog.error("invalid plist as [[HTTPCookiePropertyKey: Any]]")
throw NSError()
}
for cookieProp in cookieArray ?? [] {
if let cookie = HTTPCookie(properties: cookieProp) {
Alamofire.HTTPCookieStorage.shared.setCookie(cookie)
}
}
self.showInformativeMessage(infoMsg: "已经成功读取 HTTP Cookies。")
self.checkLoginStatus()
} else {
return
}
}
} catch {
self.showErrorMessage(errorMsg: "无法读取 HTTP Cookies。")
}
}
}
@IBAction func loginViaCookies(_ sender: NSButton) {
let infoAlert: NSAlert = NSAlert()
infoAlert.messageText = "确认格式"
infoAlert.informativeText = "要提供哪种类型的 HTTP Cookies?"
infoAlert.addButton(withTitle: "plist 持久化格式")
infoAlert.addButton(withTitle: "HTTP Plain 纯文本格式")
infoAlert.addButton(withTitle: "算了")
infoAlert.alertStyle = NSAlert.Style.informational
infoAlert.beginSheetModal(for: view.window!) { returnCode in
if returnCode == .alertSecondButtonReturn {
self.cookieParserVC.delegate = self
self.presentAsSheet(self.cookieParserVC)
} else if returnCode == .alertFirstButtonReturn {
self.importCookie()
}
}
}
func callbackWeb(_ success: Bool) {
dismiss(embedWebVC)
checkLoginStatus()
}
func callbackCookie(_ success: Bool) {
dismiss(cookieParserVC)
checkLoginStatus()
}
func checkLoginStatus() {
successImage.image = NSImage(named: "NSStatusPartiallyAvailable")
loginStateText.stringValue = "正在检查登入状态…"
LoginHelper.checkLoginAvailability({ status in
if status {
self.successImage.image = NSImage(named: "NSStatusAvailable")
self.loginStateText.stringValue = "您已经成功登入。"
self.UIDelegate?.unlockIcon()
self.exportCookieButton.isEnabled = true
} else {
self.exportCookieButton.isEnabled = false
self.UIDelegate?.lockIcon()
if LoginHelper.lastLoginUserName != "{null}" {
self.successImage.image = NSImage(named: "NSStatusUnavailable")
self.loginStateText.stringValue = "登入身份已过期。"
if self.view.window == nil {
LoginHelper.lastLoginUserName = "{null}"
}
LoginHelper.lastLoginUserName = "{null}"
} else {
self.successImage.image = NSImage(named: "NSStatusNone")
self.loginStateText.stringValue = "您尚未登入。"
}
}
})
}
func showErrorMessage(errorMsg: String) {
let errorAlert: NSAlert = NSAlert()
errorAlert.messageText = "出错啦"
errorAlert.informativeText = errorMsg
errorAlert.addButton(withTitle: "嗯")
errorAlert.alertStyle = NSAlert.Style.critical
errorAlert.beginSheetModal(for: view.window!, completionHandler: nil)
ESLog.error("internal error occured. message: ", errorMsg)
}
func failedToLoadCaptcha() {
showErrorMessage(errorMsg: "获取验证码时发生错误。\n请检查您的网络连接。")
}
// @IBAction func onExpand(_ sender: NSButton) {
// var frame: NSRect = (self.view.window?.frame)!
// if sender.state == .on {
// frame.size = NSSize(width: 260, height: 318)
// } else {
// frame.size = NSSize(width: 260, height: 230)
// }
// self.view.window?.setFrame(frame, display: true, animate: true)
// }
//
// @IBAction func operationSelectorPopped(_ sender: NSPopUpButton) {
// if sender.selectedItem!.title == "同步课程表到系统日历" {
// self.manualOpenButton.isEnabled = true
// } else {
// self.manualOpenButton.isEnabled = false
// }
// }
// @IBAction func checkHistoryData(_ sender: NSButton) {
// // do something crazy
// let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
// windowController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("FullDataWindowController")) as? FullDataWindowController
// windowController?.showWindow(self)
// }
@IBAction func goToElectsysNew(_ sender: NSButton) {
if let url = URL(string: "https://i.sjtu.edu.cn/"), NSWorkspace.shared.open(url) {
// successfully opened
ESLog.info("goes to electsys (modern version)")
}
}
@IBAction func goToElectsysLegacy(_ sender: NSButton) {
if let url = URL(string: "http://electsys.sjtu.edu.cn"), NSWorkspace.shared.open(url) {
// successfully opened
ESLog.info("goes to electsys (legacy version)")
}
}
func showInformativeMessage(infoMsg: String) {
let infoAlert: NSAlert = NSAlert()
infoAlert.informativeText = infoMsg
infoAlert.messageText = "提醒"
infoAlert.addButton(withTitle: "嗯")
infoAlert.alertStyle = NSAlert.Style.informational
infoAlert.beginSheetModal(for: view.window!)
ESLog.info("informative message thrown. message: ", infoMsg)
}
}
<file_sep>/Icons/resize.py
#!/usr/bin/env python3
import os
from PIL import Image
full_images = """arrow.backward.circle.png
arrow.clockwise.png
arrow.down.right.png
arrow.right.circle.fill.png
arrow.right.circle.png
bookmark.circle.png
bubble.left.and.bubble.right.png
calendar.png
checkmark.circle.png
delete.left.fill.png
doc.append.rtl.png
doc.zipper.png
gearshape.png
heart.fill.png
info.circle.png
magnifyingglass.png
mail.png
newspaper.png
printer.png
quote.bubble.png
rectangle.and.text.magnifyingglass.png
safari.png
tablecells.badge.ellipsis.png
tag.png
text.insert.png""".splitlines()
expected_size = 15 # points
for image_name in full_images:
folder_name = image_name.replace('.png', '.imageset')
# try:
# os.mkdir('./%s/' % folder_name)
# except:
# pass
for scale in [1, 2, 3]:
img = Image.open('./' + image_name).resize(
(expected_size * scale, expected_size * scale), Image.BICUBIC)
img.save("../Electsys Utility/Electsys Utility/Assets.xcassets/%s/@%dx.png" %
(folder_name, scale))
<file_sep>/Electsys Utility/Electsys Utility/ViewController/FullDataViewController.swift
//
// FullDataViewController.swift
// Sync Utility
//
// Created by yuxiqian on 2018/9/5.
// Copyright © 2018 yuxiqian. All rights reserved.
//
import Alamofire
import Cocoa
import Regex
import SwiftyJSON
class FullDataViewController: NSViewController {
static let toolBarHeight = 56
let specialSep = "$_$"
var shouldRequestBeta: Bool = false
// var courses: [NGCurriculum] = []
var queryCoursesOnTeacher: [NGCurriculum] = []
var queryCoursesOnName: [NGCurriculum] = []
var upperHall: [String] = []
var middleHall: [String] = []
var lowerHall: [String] = []
var eastUpperHall: [String] = []
var eastMiddleHall: [String] = []
var eastLowerHall: [String] = []
var MinHangCampus: [String] = []
var CRQBuilding: [String] = []
var YYMBuilding: [String] = []
var XuHuiCampus: [String] = []
var LuWanCampus: [String] = []
var FaHuaCampus: [String] = []
var QiBaoCampus: [String] = []
var OtherLand: [String] = []
var SMHC: [String] = []
var LinGangCampus: [String] = []
var possibleUrl: String = "未知"
var searchByNameButNotCode = true
@IBOutlet weak var nameAndCodePromptText: NSTextField!
@IBAction func alterNameAndCode(_ sender: NSButton) {
classNameCombo.stringValue = ""
if sender.tag == 0 {
// by name
searchByNameButNotCode = true
nameAndCodePromptText.stringValue = "课程名称关键字:"
} else {
// by code
searchByNameButNotCode = false
nameAndCodePromptText.stringValue = "课程编号:"
}
setComboSource()
updateNameQuery(self)
}
@objc dynamic var toggleUpperHall: Bool = true
@objc dynamic var toggleMiddleHall: Bool = true
@objc dynamic var toggleLowerHall: Bool = true
@objc dynamic var toggleEastUpperHall: Bool = true
@objc dynamic var toggleEastMiddleHall: Bool = true
@objc dynamic var toggleEastLowerHall: Bool = true
@objc dynamic var toggleMinHangCampus: Bool = true
@objc dynamic var toggleCRQBuilding: Bool = true
@objc dynamic var toggleYYMBuilding: Bool = true
@objc dynamic var toggleXuHuiCampus: Bool = true
@objc dynamic var toggleLuWanCampus: Bool = true
@objc dynamic var toggleFaHuaCampus: Bool = true
@objc dynamic var toggleQiBaoCampus: Bool = true
@objc dynamic var toggleOtherLand: Bool = true
@objc dynamic var toggleSMHC: Bool = true
@objc dynamic var toggleLinGangCampus: Bool = true
var localTimeStamp: String = ""
var arrangement: [NGCurriculum] = [NGCurriculum].init(repeating: GalleryKits.emptyCurriculum, count: 14)
var schools: [String] = []
var teachers: [String] = []
var classnames: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
progressIndicator.startAnimation(nil)
setWeekPop(start: 1, end: 18)
// Do view setup here.
let date = Date()
let calendar = Calendar.current
var year = calendar.component(.year, from: date)
tabTitleSeg.isEnabled = false
showMoreButton.isEnabled = false
tableView.selectTabViewItem(at: 3)
yearSelector.removeAllItems()
if year < 2019 {
year = 2019
// fallback as year 2019
}
if year < 2018 {
return
}
for iteratedYear in (2018 ... year).reversed() {
yearSelector.addItem(withTitle: "\(iteratedYear) 至 \(iteratedYear + 1) 学年")
}
}
func setEnableStats(_ stat: [Bool]) {
betaSelector.isEnabled = stat[0]
showMoreButton.isEnabled = stat[1]
}
func setWeekPop(start: Int, end: Int) {
weekSelector.removeAllItems()
for i in start ... end {
weekSelector.addItem(withTitle: "第 \(i) 周")
}
}
func clearLists() {
GalleryKits.courseList.removeAll()
schools.removeAll()
teachers.removeAll()
classnames.removeAll()
upperHall.removeAll()
middleHall.removeAll()
lowerHall.removeAll()
eastUpperHall.removeAll()
eastMiddleHall.removeAll()
eastLowerHall.removeAll()
XuHuiCampus.removeAll()
MinHangCampus.removeAll()
CRQBuilding.removeAll()
XuHuiCampus.removeAll()
LuWanCampus.removeAll()
FaHuaCampus.removeAll()
QiBaoCampus.removeAll()
OtherLand.removeAll()
SMHC.removeAll()
YYMBuilding.removeAll()
LinGangCampus.removeAll()
}
@IBAction func startQuery(_ sender: NSButton) {
setLayoutType(.shrink)
yearSelector.isEnabled = false
termSelector.isEnabled = false
searchButton.isEnabled = false
setEnableStats([false, false])
clearLists()
getJson()
}
@IBOutlet var yearSelector: NSPopUpButton!
@IBOutlet var termSelector: NSPopUpButton!
@IBOutlet var progressIndicator: NSProgressIndicator!
@IBOutlet var buildingSelector: NSPopUpButton!
@IBOutlet var roomSelector: NSPopUpButton!
@IBOutlet var weekDaySelector: NSPopUpButton!
@IBOutlet var weekSelector: NSPopUpButton!
@IBOutlet var oneButton: NSButton!
@IBOutlet var twoButton: NSButton!
@IBOutlet var threeButton: NSButton!
@IBOutlet var fourButton: NSButton!
@IBOutlet var fiveButton: NSButton!
@IBOutlet var sixButton: NSButton!
@IBOutlet var sevenButton: NSButton!
@IBOutlet var eightButton: NSButton!
@IBOutlet var nineButton: NSButton!
@IBOutlet var tenButton: NSButton!
@IBOutlet var elevenButton: NSButton!
@IBOutlet var twelveButton: NSButton!
@IBOutlet var tabTitleSeg: NSSegmentedControl!
@IBOutlet var sortBox: NSBox!
@IBOutlet var detailBox: NSBox!
@IBOutlet var holdingSchoolSelector: NSPopUpButton!
@IBOutlet var teacherNameCombo: NSComboBox!
@IBOutlet var teacherResultSelector: NSPopUpButton!
@IBOutlet var teacherDetail: NSButton!
@IBOutlet var teacherLabel: NSTextField!
@IBOutlet var classNameCombo: NSComboBox!
@IBOutlet var classNameLabel: NSTextField!
@IBOutlet var classNameResultSelector: NSPopUpButton!
@IBOutlet var classroomDetail: NSButton!
@IBOutlet var tableView: NSTabView!
@IBOutlet var betaSelector: NSButton!
@IBOutlet var showMoreButton: NSButton!
@IBOutlet var exactMatchChecker: NSButton!
@IBOutlet weak var searchButton: NSButton!
@IBAction func iconButtonTapped(_ sender: NSButton) {
let id = Int((sender.identifier?.rawValue)!)
let obj = arrangement[id! - 1]
if obj != GalleryKits.emptyCurriculum {
displayDetail(obj)
} else {
showCourseInfo(titleMsg: "空教室", infoMsg: "这里什么都没有…")
}
}
@IBAction func yearPopTapped(_ sender: NSPopUpButton) {
setLayoutType(.shrink)
}
@IBAction func betaTapped(_ sender: NSButton) {
setLayoutType(.shrink)
shouldRequestBeta = (sender.state == .on)
}
@IBAction func termPopTapped(_ sender: NSPopUpButton) {
setLayoutType(.shrink)
if sender.selectedItem?.title == "夏季小学期" {
setWeekPop(start: 1, end: 6)
} else {
setWeekPop(start: 1, end: 18)
}
}
func getJson() {
if yearSelector.titleOfSelectedItem == nil {
showErrorMessage(errorMsg: "请完整地填写所有信息。")
return
}
let yearInt = Int(yearSelector.titleOfSelectedItem!.components(separatedBy: " 至 ").first ?? "2019") ?? 2019
// print(jsonUrl)
let termInt = termSelector.indexOfSelectedItem + 1
sortBox.title = "\(yearSelector.selectedItem?.title ?? "未知学年")\(termSelector.selectedItem?.title ?? " 未知学期")"
progressIndicator.isHidden = false
let useBeta = betaSelector.state == .on
possibleUrl = GalleryKits.possibleUrl ?? "未知"
DispatchQueue.global().async {
GalleryKits.requestGalleryData(year: yearInt,
term: termInt,
beta: useBeta,
handler: { timeStamp in
self.aggregateData()
self.sortLists()
self.localTimeStamp = timeStamp
DispatchQueue.main.async {
self.progressIndicator.isHidden = true
self.pushPopListData(self.buildingSelector)
self.setComboSource()
self.startTeacherQuery()
self.updateNameQuery(self)
self.switchSeg(self.tabTitleSeg)
self.updateEnableStat()
// success!
self.setEnableStats([true, true])
self.yearSelector.isEnabled = true
self.termSelector.isEnabled = true
self.searchButton.isEnabled = true
}
},
failure: { code in
DispatchQueue.main.async {
self.progressIndicator.isHidden = true
self.yearSelector.isEnabled = true
self.termSelector.isEnabled = true
self.searchButton.isEnabled = true
self.setLayoutType(.shrink)
self.showErrorMessage(errorMsg: "未能读取此学期的数据。\n错误代码:\(code)")
}
})
}
}
func updateEnableStat() {
toggleUpperHall = upperHall != []
toggleMiddleHall = middleHall != []
toggleLowerHall = middleHall != []
toggleEastLowerHall = eastLowerHall != []
toggleEastMiddleHall = eastMiddleHall != []
toggleEastUpperHall = eastUpperHall != []
toggleCRQBuilding = CRQBuilding != []
toggleYYMBuilding = YYMBuilding != []
toggleMinHangCampus = MinHangCampus != []
toggleXuHuiCampus = XuHuiCampus != []
toggleLuWanCampus = LuWanCampus != []
toggleFaHuaCampus = FaHuaCampus != []
toggleQiBaoCampus = QiBaoCampus != []
toggleLinGangCampus = LinGangCampus != []
toggleSMHC = SMHC != []
}
@IBAction func pushPopListData(_ sender: NSPopUpButton) {
roomSelector.removeAllItems()
switch buildingSelector.selectedItem?.title {
case "闵行校区上院"?:
roomSelector.addRoomItems(withTitles: upperHall)
break
case "闵行校区中院"?:
roomSelector.addRoomItems(withTitles: middleHall)
break
case "闵行校区下院"?:
roomSelector.addRoomItems(withTitles: lowerHall)
break
case "闵行校区东上院"?:
roomSelector.addRoomItems(withTitles: eastUpperHall)
break
case "闵行校区东中院"?:
roomSelector.addRoomItems(withTitles: eastMiddleHall)
break
case "闵行校区东下院"?:
roomSelector.addRoomItems(withTitles: eastLowerHall)
break
case "闵行校区陈瑞球楼"?:
roomSelector.addRoomItems(withTitles: CRQBuilding)
break
case "闵行校区杨咏曼楼"?:
roomSelector.addRoomItems(withTitles: YYMBuilding)
break
case "其余闵行校区教学楼"?:
roomSelector.addRoomItems(withTitles: MinHangCampus)
break
case "徐汇校区"?:
roomSelector.addRoomItems(withTitles: XuHuiCampus)
break
case "卢湾校区"?:
roomSelector.addRoomItems(withTitles: LuWanCampus)
break
case "法华校区"?:
roomSelector.addRoomItems(withTitles: FaHuaCampus)
break
case "七宝校区"?:
roomSelector.addRoomItems(withTitles: QiBaoCampus)
break
case "外地"?:
roomSelector.addRoomItems(withTitles: OtherLand)
break
case "上海市精神卫生中心"?:
roomSelector.addRoomItems(withTitles: SMHC)
break
case "临港校区"?:
roomSelector.addRoomItems(withTitles: LinGangCampus)
break
default:
roomSelector.addItem(withTitle: "ˊ_>ˋ")
}
updateBoxes(sender)
}
@IBAction func updateQuery(_ sender: Any) {
startTeacherQuery()
}
@IBAction func updateNameQuery(_ sender: Any) {
if searchByNameButNotCode {
startNameQuery()
} else {
startCodeQuery()
}
}
func setComboSource() {
holdingSchoolSelector.removeAllItems()
holdingSchoolSelector.addItem(withTitle: "不限")
holdingSchoolSelector.addItem(withTitle: "MY_MENU_SEPARATOR")
holdingSchoolSelector.addItems(withTitles: schools)
teacherNameCombo.removeAllItems()
teacherNameCombo.addItems(withObjectValues: teachers.sorted().reversed())
teacherLabel.stringValue = "请确定筛选条件。"
classNameResultSelector.removeAllItems()
classNameLabel.stringValue = "请确定筛选条件。"
classNameCombo.removeAllItems()
if searchByNameButNotCode {
classNameCombo.addItems(withObjectValues: classnames)
}
}
func startTeacherQuery() {
PreferenceKits.readPreferences()
queryCoursesOnTeacher.removeAll()
teacherResultSelector.removeAllItems()
var limitSchool = holdingSchoolSelector.title
if limitSchool == "不限" {
limitSchool = ""
}
let teacherName = teacherNameCombo.stringValue
if teacherName == "" {
teacherLabel.stringValue = "请确定筛选条件。"
teacherResultSelector.isEnabled = false
teacherDetail.isEnabled = false
return
}
var counter = 1
for cur in GalleryKits.courseList {
if queryCoursesOnTeacher.contains(cur) {
continue
}
var contain = false
for teacherNameLiteral in cur.teacher {
if exactMatchChecker.state == .off {
if teacherNameLiteral.contains(teacherName) {
if limitSchool != "" {
if cur.holderSchool == limitSchool {
contain = true
break
}
} else {
contain = true
break
}
}
} else {
if teacherNameLiteral == teacherName {
if limitSchool != "" {
if cur.holderSchool == limitSchool {
contain = true
break
}
} else {
contain = true
break
}
}
}
}
if !contain {
continue
}
queryCoursesOnTeacher.append(cur)
if PreferenceKits.courseDisplayStrategy == .nameOnly {
teacherResultSelector.addItem(withTitle: "(\(counter)) \(cur.name)")
} else if PreferenceKits.courseDisplayStrategy == .nameAndTeacher {
teacherResultSelector.addItem(withTitle: "(\(counter)) \(cur.name),\(cur.teacher.joined(separator: "、"))")
} else if PreferenceKits.courseDisplayStrategy == .codeNameAndTeacher {
teacherResultSelector.addItem(withTitle: "(\(counter)) \(cur.code) - \(cur.name),\(cur.teacher.joined(separator: "、"))")
}
counter += 1
}
if queryCoursesOnTeacher.count == 0 {
teacherLabel.stringValue = "没有符合条件的结果。"
teacherResultSelector.isEnabled = false
teacherDetail.isEnabled = false
return
}
teacherResultSelector.isEnabled = true
teacherDetail.isEnabled = true
teacherLabel.stringValue = "匹配到 \(teacherResultSelector.numberOfItems) 条课程信息。"
}
func startNameQuery() {
queryCoursesOnName.removeAll()
classNameResultSelector.removeAllItems()
let courseName = classNameCombo.stringValue
if courseName == "" {
classNameLabel.stringValue = "请确定筛选条件。"
classNameResultSelector.isEnabled = false
classroomDetail.isEnabled = false
return
}
var counter = 1
for cur in GalleryKits.courseList {
if !cur.name.contains(courseName) {
continue
}
if queryCoursesOnName.contains(cur) {
continue
}
queryCoursesOnName.append(cur)
if PreferenceKits.courseDisplayStrategy == .nameOnly {
classNameResultSelector.addItem(withTitle: "(\(counter)) \(cur.name)")
} else if PreferenceKits.courseDisplayStrategy == .nameAndTeacher {
classNameResultSelector.addItem(withTitle: "(\(counter)) \(cur.name),\(cur.teacher.joined(separator: "、"))")
} else if PreferenceKits.courseDisplayStrategy == .codeNameAndTeacher {
classNameResultSelector.addItem(withTitle: "(\(counter)) \(cur.code) - \(cur.name),\(cur.teacher.joined(separator: "、"))")
}
counter += 1
}
if queryCoursesOnName.count == 0 {
classNameLabel.stringValue = "没有符合条件的结果。"
classNameResultSelector.isEnabled = false
classroomDetail.isEnabled = false
return
}
classNameResultSelector.isEnabled = true
classroomDetail.isEnabled = true
classNameLabel.stringValue = "匹配到 \(classNameResultSelector.numberOfItems) 条课程信息。"
}
func startCodeQuery() {
queryCoursesOnName.removeAll()
classNameResultSelector.removeAllItems()
let courseCode = classNameCombo.stringValue.uppercased()
if courseCode == "" {
classNameLabel.stringValue = "请确定筛选条件。"
classNameResultSelector.isEnabled = false
classroomDetail.isEnabled = false
return
}
var counter = 1
for cur in GalleryKits.courseList {
if !cur.code.contains(courseCode) {
continue
}
if queryCoursesOnName.contains(cur) {
continue
}
queryCoursesOnName.append(cur)
if PreferenceKits.courseDisplayStrategy == .nameOnly {
classNameResultSelector.addItem(withTitle: "(\(counter)) \(cur.name)")
} else if PreferenceKits.courseDisplayStrategy == .nameAndTeacher {
classNameResultSelector.addItem(withTitle: "(\(counter)) \(cur.name),\(cur.teacher.joined(separator: "、"))")
} else if PreferenceKits.courseDisplayStrategy == .codeNameAndTeacher {
classNameResultSelector.addItem(withTitle: "(\(counter)) \(cur.code) - \(cur.name),\(cur.teacher.joined(separator: "、"))")
}
counter += 1
}
if queryCoursesOnName.count == 0 {
classNameLabel.stringValue = "没有符合条件的结果。"
classNameResultSelector.isEnabled = false
classroomDetail.isEnabled = false
return
}
classNameResultSelector.isEnabled = true
classroomDetail.isEnabled = true
classNameLabel.stringValue = "匹配到 \(classNameResultSelector.numberOfItems) 条课程信息。"
}
func sortClassroom(building: String, campus: String) {
if building.contains("不排教室") || building.contains("未定") || building.contains("不安排") {
return
}
let numbersInStr = building.removeFloorCharacters(true)
let str = building.replacingOccurrences(of: numbersInStr, with: " " + numbersInStr)
if str.sanitize() == "" {
return
}
if str.sanitize().count <= 2 {
return
}
if campus == "闵行" {
if str.starts(with: "上院") {
if !upperHall.contains(str) {
upperHall.append(str)
}
} else if str.starts(with: "中院") {
if !middleHall.contains(str) {
middleHall.append(str)
}
} else if str.starts(with: "下院") {
if !lowerHall.contains(str) {
lowerHall.append(str)
}
} else if str.starts(with: "东上院") {
if !eastUpperHall.contains(str) {
eastUpperHall.append(str)
}
} else if str.starts(with: "东中院") {
if !eastMiddleHall.contains(str) {
eastMiddleHall.append(str)
}
} else if str.starts(with: "东下院") {
if !eastLowerHall.contains(str) {
eastLowerHall.append(str)
}
} else if str.contains("陈瑞球楼") {
if !CRQBuilding.contains(str) {
CRQBuilding.append(str)
}
} else if str.contains("杨咏曼楼") {
if !YYMBuilding.contains(str) {
YYMBuilding.append(str)
}
} else {
if !MinHangCampus.contains(str) {
MinHangCampus.append(str)
}
}
} else if campus == "徐汇" {
if !XuHuiCampus.contains(str) {
XuHuiCampus.append(str)
}
} else if campus == "卢湾" {
if !LuWanCampus.contains(str) {
LuWanCampus.append(str)
}
} else if campus == "法华" {
if !FaHuaCampus.contains(str) {
FaHuaCampus.append(str)
}
} else if campus == "七宝" {
if !QiBaoCampus.contains(str) {
QiBaoCampus.append(str)
}
} else if campus == "外地" {
if !OtherLand.contains(str) {
OtherLand.append(str)
}
} else if campus == "上海市精神卫生中心" {
if !SMHC.contains(str) {
SMHC.append(str)
}
} else if campus == "临港" {
if !LinGangCampus.contains(str) {
LinGangCampus.append(str)
}
} else {
ESLog.error("uncategorized: %@, %@", campus, building)
}
}
func showErrorMessage(errorMsg: String) {
if view.window == nil {
return
}
let errorAlert: NSAlert = NSAlert()
errorAlert.messageText = "出错啦"
errorAlert.informativeText = errorMsg
errorAlert.addButton(withTitle: "嗯")
errorAlert.alertStyle = NSAlert.Style.critical
errorAlert.beginSheetModal(for: view.window!, completionHandler: nil)
ESLog.error("error occured. message: ", errorMsg)
}
func sortLists() {
upperHall.sort()
middleHall.sort()
lowerHall.sort()
eastUpperHall.sort()
eastMiddleHall.sort()
eastLowerHall.sort()
CRQBuilding.sort()
XuHuiCampus.sort()
LuWanCampus.sort()
FaHuaCampus.sort()
QiBaoCampus.sort()
OtherLand.sort()
SMHC.sort()
LinGangCampus.sort()
YYMBuilding.sort()
MinHangCampus.sort()
}
@IBAction func updateBoxes(_ sender: NSPopUpButton) {
for i in 1 ... 12 {
drawBox(id: i)
}
arrangement = [NGCurriculum].init(repeating: GalleryKits.emptyCurriculum, count: 14)
let currentWeek = hanToInt(weekSelector.selectedItem?.title)
let weekDay = dayToInt.firstIndex(of: (weekDaySelector.selectedItem?.title)!)
detailBox.title = "\(roomSelector.selectedItem?.title ?? "某教室"),\(weekSelector.selectedItem?.title ?? "某周")\(weekDaySelector.selectedItem?.title ?? "某日")教室安排情况"
if let room = self.roomSelector.selectedItem?.title.sanitize() {
for cur in GalleryKits.courseList {
for arr in cur.arrangements {
if arr.weekDay != weekDay {
continue
}
if !arr.weeks.contains(currentWeek) {
continue
}
if !(arr.classroom.sanitize() == room.sanitize()) {
continue
}
for lessonIndex in arr.sessions {
drawBox(id: lessonIndex, population: cur.studentNumber)
arrangement[lessonIndex - 1] = cur
}
}
}
} else {
detailBox.title = "教室占用情况"
}
}
func drawBox(id: Int, population: Int = -1) {
var color: NSColor?
var description: String = ""
if population == -1 {
color = getColor(name: "empty")
description = "空教室"
} else if population < 25 {
color = getColor(name: "light")
description = "没什么人"
} else if population < 50 {
color = getColor(name: "medium")
description = "有点人"
} else if population < 100 {
color = getColor(name: "heavy")
description = "人很多"
} else {
color = getColor(name: "full")
description = "人满"
}
let colorBox = NSImage(color: color!, size: NSSize(width: 25, height: 25))
switch id {
case 1:
oneButton.image = colorBox
oneButton.setAccessibilityLabel("第一节课:" + description)
break
case 2:
twoButton.image = colorBox
twoButton.setAccessibilityLabel("第二节课:" + description)
break
case 3:
threeButton.image = colorBox
threeButton.setAccessibilityLabel("第三节课:" + description)
break
case 4:
fourButton.image = colorBox
fourButton.setAccessibilityLabel("第四节课:" + description)
break
case 5:
fiveButton.image = colorBox
fiveButton.setAccessibilityLabel("第五节课:" + description)
break
case 6:
sixButton.image = colorBox
sixButton.setAccessibilityLabel("第六节课:" + description)
break
case 7:
sevenButton.image = colorBox
sevenButton.setAccessibilityLabel("第七节课:" + description)
break
case 8:
eightButton.image = colorBox
eightButton.setAccessibilityLabel("第八节课:" + description)
break
case 9:
nineButton.image = colorBox
nineButton.setAccessibilityLabel("第九节课:" + description)
break
case 10:
tenButton.image = colorBox
tenButton.setAccessibilityLabel("第十节课:" + description)
break
case 11:
elevenButton.image = colorBox
elevenButton.setAccessibilityLabel("第十一节课:" + description)
break
case 12:
twelveButton.image = colorBox
twelveButton.setAccessibilityLabel("第十二节课:" + description)
break
default:
break
}
}
func showCourseInfo(titleMsg: String, infoMsg: String) {
if view.window == nil {
return
}
let infoAlert: NSAlert = NSAlert()
infoAlert.messageText = titleMsg
infoAlert.informativeText = infoMsg
infoAlert.addButton(withTitle: "嗯")
infoAlert.alertStyle = NSAlert.Style.informational
infoAlert.beginSheetModal(for: view.window!, completionHandler: nil)
}
static let layoutTable: [NSSize] = [
NSSize(width: 504, height: 79 + toolBarHeight),
NSSize(width: 536, height: 363 + 30 + toolBarHeight),
NSSize(width: 504, height: 290 + 30 + toolBarHeight),
NSSize(width: 556, height: 242 + 30 + toolBarHeight),
]
func setLayoutType(_ type: LayoutType) {
// self.tableView.alphaValue = 0.0
// let frame = self.view.window?.frame
// if frame != nil {
// let heightDelta = frame!.size.height - FullDataViewController.layoutTable[type.rawValue].height
// let origin = NSMakePoint(frame!.origin.x, frame!.origin.y + heightDelta)
// let size = FullDataViewController.layoutTable[type.rawValue]
// let newFrame = NSRect(origin: origin, size: size)
// self.view.window?.setFrame(newFrame, display: true, animate: true)
// NSAnimationContext.runAnimationGroup({ (context) in
// self.tableView.animator().alphaValue = 1.0
// }, completionHandler: nil)
//// }
if type == .shrink {
setEnableStats([true, false])
tableView.selectTabViewItem(at: 3)
tabTitleSeg.isEnabled = false
showMoreButton.isEnabled = false
} else {
tabTitleSeg.isEnabled = true
showMoreButton.isEnabled = true
tableView.selectTabViewItem(at: tabTitleSeg.selectedSegment)
}
}
func displayDetail(_ course: NGCurriculum) {
var targetGrade: String = "不针对特定年级"
if course.targetGrade > 2000 {
targetGrade = "\(course.targetGrade) 级"
}
var properties: [Property] = [
Property(name: "教学班 ID", value: course.identifier),
Property(name: "课号", value: course.code),
Property(name: "开课院系", value: course.holderSchool),
Property(name: "课名", value: course.name),
Property(name: "开课学年", value: "\(course.year) 至 \(course.year + 1) 学年"),
Property(name: "开课学期", value: "\(termLiteralNames[course.term % 4])"),
Property(name: "目标年级", value: targetGrade),
Property(name: "教师", value: course.teacher.joined(separator: "、")),
Property(name: "课程学分", value: String(format: "%.1f", course.credit)),
Property(name: "学生人数", value: String(course.studentNumber))
]
let footNotes = course.notes.replacingOccurrences(of: "\n", with: "").sanitize()
if footNotes != "" {
properties.append(Property(name: "备注", value: footNotes))
}
let sortedArrangements = course.arrangements.sorted(by: { arr1, arr2 in
return arr1.weeks.first ?? 0 < arr2.weeks.first ?? 1
})
var counter = 1
for arrange in sortedArrangements {
var weekDescInterp: [String] = []
for desc in Beautify.beautifier(array: arrange.weeks) {
if desc.0 == desc.1 {
weekDescInterp.append("第 \(desc.0) 周")
} else {
weekDescInterp.append("第 \(desc.0) 至第 \(desc.1) 周")
}
}
properties.append(Property(name: "排课 #\(counter)", value: weekDescInterp.joined(separator: "、")))
if arrange.weekDay > 7 || arrange.weekDay < 1 {
continue
}
var sessionDescInterp: [String] = []
for session in Beautify.beautifier(array: arrange.sessions) {
if session.0 == session.1 {
sessionDescInterp.append("第 \(session.0) 节")
} else {
sessionDescInterp.append("\(dayOfWeekName[arrange.weekDay])第 \(session.0) 至第 \(session.1) 节")
}
}
properties.append(Property(name: "", value: sessionDescInterp.joined(separator: "、")))
properties.append(Property(name: "", value: "\(arrange.campus)校区,\(arrange.classroom)"))
counter += 1
}
InspectorKits.showProperties(properties: properties)
// for i in classes {
// NSLog(i.identifier)
// }
// let className = classes[0].name
// let teacher = classes[0].teacher.joined(separator: "、")
// let holder = classes[0].holderSchool
//
// var declare = ""
//
// for cur in classes {
// var target = "课程 ID:\(cur.identifier)\n"
// if cur.targetGrade != 0 {
// target += "\t面向 \(cur.targetGrade) 级学生\n"
// }
// if cur.notes != "" {
// target += "附注:\(cur.notes)\n"
// }
// for arrange in cur.arrangements {
// target += "\(arrange.getWeeksInterpreter())\n\(dayOfWeekName[arrange.weekDay])\(arrange.getSessionsInterpreter())\n\(arrange.campus)校区 \(arrange.classroom)\n\n"
// }
// declare += target
// }
// declare.removeLast()
//
// let infoAlert: NSAlert = NSAlert()
// infoAlert.messageText = className
// infoAlert.informativeText = "教师:\(teacher)\n开课院系:\(holder)\n\n\(declare)"
// infoAlert.addButton(withTitle: "嗯")
// infoAlert.alertStyle = NSAlert.Style.informational
// if view.window == nil {
// return
// }
// infoAlert.beginSheetModal(for: view.window!, completionHandler: nil)
}
@IBAction func switchSeg(_ sender: NSSegmentedControl) {
tableView.selectTabViewItem(at: sender.selectedSegment)
if sender.selectedSegment == 0 {
setLayoutType(.classroom)
} else if sender.selectedSegment == 1 {
setLayoutType(.teacher)
} else if sender.selectedSegment == 2 {
setLayoutType(.name)
}
}
@IBAction func byNameDetail(_ sender: NSButton) {
let target = queryCoursesOnName[classNameResultSelector.indexOfSelectedItem]
displayDetail(target)
}
@IBAction func detailByTeacher(_ sender: NSButton) {
let target = queryCoursesOnTeacher[teacherResultSelector.indexOfSelectedItem]
displayDetail(target)
}
func showDataInfo() {
if localTimeStamp != "" {
let infoAlert: NSAlert = NSAlert()
infoAlert.messageText = "数据详情"
if shouldRequestBeta {
infoAlert.informativeText = "(Beta 数据)\n\n"
}
infoAlert.informativeText += "来源:\(GalleryKits.possibleUrl ?? "未知")\n\n生成时间:\(localTimeStamp) (GMT+08:00)\n数据量:\(GalleryKits.courseList.count)"
infoAlert.addButton(withTitle: "嗯")
infoAlert.alertStyle = NSAlert.Style.informational
if view.window == nil {
return
}
infoAlert.beginSheetModal(for: view.window!, completionHandler: nil)
} else {
let infoAlert: NSAlert = NSAlert()
infoAlert.messageText = "数据详情"
infoAlert.informativeText = "来源:\(possibleUrl)\n\n生成时间:未知\n数据量:\(GalleryKits.courseList.count)"
infoAlert.addButton(withTitle: "嗯")
infoAlert.alertStyle = NSAlert.Style.informational
if view.window == nil {
return
}
infoAlert.beginSheetModal(for: view.window!, completionHandler: nil)
}
}
func aggregateData() {
var cachedSchoolSets = Set<String>(schools)
var cachedTeacherSets = Set<String>(teachers)
var cachedClassnameSets = Set<String>(classnames)
for cur in GalleryKits.courseList {
for related in cur.getRelated() {
sortClassroom(building: related.strA, campus: related.strB)
}
if !cachedSchoolSets.contains(cur.holderSchool) {
cachedSchoolSets.insert(cur.holderSchool)
schools.append(cur.holderSchool)
}
for teacherName in cur.teacher {
if !cachedTeacherSets.contains(teacherName) {
if teacherName.sanitize() != "" {
teachers.append(teacherName)
cachedTeacherSets.insert(teacherName)
}
}
}
if !cachedClassnameSets.contains(cur.name) {
if cur.name.sanitize() != "" {
classnames.append(cur.name)
cachedClassnameSets.insert(cur.name)
}
}
}
}
@IBAction func getTimeStamp(_ sender: NSButton) {
showDataInfo()
}
}
extension NSImage {
convenience init(color: NSColor, size: NSSize) {
self.init(size: size)
lockFocus()
color.drawSwatch(in: NSRect(origin: .zero, size: size))
draw(in: NSRect(origin: .zero, size: size),
from: NSRect(origin: .zero, size: self.size),
operation: .color, fraction: 1)
unlockFocus()
}
}
@objc extension NSPopUpButton {
func addRoomItems(withTitles items: [String]) {
var lastIndex: Int?
var lastBuilding: String?
for item in items {
let analyseItem = item.sanitize()
if item.contains("校区") {
continue
}
let curIndex: Int? = Int(analyseItem.removeFloorCharacters().prefix(1))
let numericStr = analyseItem.removeFloorCharacters(true)
let curBuilding: String? = analyseItem.deleteOccur(remove: numericStr)
if curIndex != nil {
// print("cur: \(curIndex), last: \(lastIndex)")
if (lastIndex != nil) && (lastBuilding != nil) {
if (curIndex! != lastIndex) || (curBuilding != lastBuilding) {
lastIndex = curIndex!
lastBuilding = curBuilding!
// print("should add sep")
addItem(withTitle: "MY_MENU_SEPARATOR")
}
} else {
lastIndex = curIndex
lastBuilding = curBuilding
}
addItem(withTitle: item)
} else {
addItem(withTitle: item)
}
}
}
}
enum LayoutType: Int {
case shrink = 0
case classroom = 1
case teacher = 2
case name = 3
}
<file_sep>/.github/ISSUE_TEMPLATE/---.md
---
name: 新功能
about: 建议一项新功能
---
**这项新功能是否和使用过程中的某个小问题有关?**
**描述预期的功能**
**附加信息**
<file_sep>/Electsys Utility/Electsys Utility/ScoreKits/ScoreKits.swift
//
// ScoreKits.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
import Alamofire
import Alamofire_SwiftyJSON
import SwiftyJSON
class ScoreKits {
static func requestScoreData(year: Int, term: Int,
handler: @escaping ([NGScore]) -> Void,
failure: @escaping (Int) -> Void) {
// 1 - "3"
// 2 - "12"
// 3 - "16"
if term < 1 || term > 3 {
failure(-1)
return
}
let termString = ScoreConst.termTable[term]
let getParams: Parameters = [
"xnm": year,
"xqm": termString,
]
Alamofire.request(ScoreConst.requestUrl,
method: .get,
parameters: getParams).responseSwiftyJSON(completionHandler: { responseJSON in
if responseJSON.error == nil {
let jsonResp = responseJSON.value
if jsonResp != nil {
var scoreSheet: [NGScore] = []
for scoreObject in jsonResp?["items"].arrayValue ?? [] {
scoreSheet.append(NGScore(classId: scoreObject["bg"].stringValue,
scorePoint: scoreObject["jd"].floatValue,
holderSchool: scoreObject["jgmc"].stringValue,
teacher: scoreObject["jsxm"].stringValue.replacingOccurrences(of: ";", with: "、"),
courseCode: scoreObject["kch"].stringValue,
courseName: scoreObject["kcmc"].stringValue,
status: scoreObject["ksxz"].stringValue,
finalScore: scoreObject["bfzcj"].intValue,
credit: scoreObject["xf"].floatValue))
}
handler(scoreSheet)
} else {
failure(-3)
}
} else {
failure(-2)
}
})
}
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/PreferencesViewController.swift
//
// PreferencesViewController.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Cocoa
class PreferencesViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
readPreferences()
}
@IBOutlet weak var debugLevelMenuItem: NSMenuItem!
@IBOutlet weak var traceLevelMenuItem: NSMenuItem!
@IBOutlet var galleryDisplayStylePopUpSelector: NSPopUpButton!
@IBOutlet var gpaCalculatingStrategyPopUpSelector: NSPopUpButton!
@IBOutlet var hidePersonalInfoChecker: NSButton!
@IBOutlet var autoFillTokenChecker: NSButton!
@IBOutlet var userNameToken: NSTextField!
@IBOutlet var passWordToken: NSSecureTextField!
@IBOutlet var saveCredentialButton: NSButton!
@IBAction func generalStylePopUpButtonTapped(_ sender: NSPopUpButton) {
savePreferences()
}
@IBAction func gpaPopUpButtonTapped(_ sender: NSPopUpButton) {
savePreferences()
}
@IBAction func hideCheckBoxChecked(_ sender: NSButton) {
savePreferences()
}
@IBAction func autoFillBoxChecked(_ sender: NSButton) {
disableTextBox()
savePreferences()
}
@IBAction func saveCredentialButtonTapped(_ sender: NSButton) {
savePreferences()
}
func disableTextBox() {
// due to login strategy migration, auto-fill feature is disabled.
return
// if autoFillTokenChecker.state == .on {
// userNameToken.isEnabled = true
// passWordToken.isEnabled = true
// saveCredentialButton.isEnabled = true
// } else {
// userNameToken.isEnabled = false
// passWordToken.isEnabled = false
// saveCredentialButton.isEnabled = false
// }
}
@IBAction func removeCertificates(_ sender: NSButton) {
questionMe(questionMsg: "您确定要清除本地凭据缓存吗?", handler: {
self.autoFillTokenChecker.state = .off
self.userNameToken.stringValue = ""
self.passWordToken.stringValue = ""
self.disableTextBox()
PreferenceKits.autoFillTokens = false
PreferenceKits.autoFillUserName = ""
PreferenceKits.autoFillPassWord = ""
PreferenceKits.removeCertificates()
self.showNormalMessage(infoMsg: "已成功清除凭据缓存。")
})
}
@IBAction func removeLocalCookies(_ sender: NSButton) {
questionMe(questionMsg: "您确定要清除本地 HTTP Cookies 吗?", handler: {
LoginHelper.removeCookie()
self.showNormalMessage(infoMsg: "已成功清除 HTTP Cookies。")
})
}
@IBAction func showLoggings(_ sender: NSButton) {
let ws = NSWorkspace.shared
if let appUrl = ws.urlForApplication(withBundleIdentifier: "com.apple.Console") {
try! ws.launchApplication(at: appUrl,
options: NSWorkspace.LaunchOptions.default,
configuration: [:])
}
}
func showNormalMessage(infoMsg: String) {
let infoAlert: NSAlert = NSAlert()
infoAlert.informativeText = infoMsg
infoAlert.messageText = "提示"
infoAlert.addButton(withTitle: "嗯")
infoAlert.alertStyle = NSAlert.Style.informational
infoAlert.beginSheetModal(for: view.window!)
ESLog.info("informative message: ", infoMsg)
}
func readPreferences() {
PreferenceKits.readPreferences()
galleryDisplayStylePopUpSelector.selectItem(at: PreferenceKits.courseDisplayStrategy.rawValue)
gpaCalculatingStrategyPopUpSelector.selectItem(at: PreferenceKits.gpaStrategy.rawValue)
if PreferenceKits.hidePersonalInfo {
hidePersonalInfoChecker.state = .on
} else {
hidePersonalInfoChecker.state = .off
}
if PreferenceKits.autoFillTokens {
autoFillTokenChecker.state = .on
} else {
autoFillTokenChecker.state = .off
}
userNameToken.stringValue = PreferenceKits.autoFillUserName
passWordToken.stringValue = PreferenceKits.autoFillPassWord
disableTextBox()
}
func savePreferences() {
PreferenceKits.courseDisplayStrategy = CourseNameDisplayStrategy(rawValue: galleryDisplayStylePopUpSelector.indexOfSelectedItem) ?? .nameAndTeacher
PreferenceKits.gpaStrategy = GPACalculationStrategy(rawValue: gpaCalculatingStrategyPopUpSelector.indexOfSelectedItem) ?? .SJTU_4_3
PreferenceKits.hidePersonalInfo = hidePersonalInfoChecker.state == .on
PreferenceKits.autoFillTokens = autoFillTokenChecker.state == .on
if autoFillTokenChecker.state == .on {
PreferenceKits.autoFillUserName = userNameToken.stringValue
PreferenceKits.autoFillPassWord = <PASSWORD>WordToken.stringValue
}
PreferenceKits.savePreferences()
}
@IBAction func debugLevelTriggered(_ sender: NSPopUpButton) {
switch sender.selectedTag() {
case 0:
// fault
ESLog.minLevel = .fault
case 1:
// error
ESLog.minLevel = .error
case 2:
// info
ESLog.minLevel = .info
case 3:
// debug
ESLog.minLevel = .debug
case 5:
// disabled
ESLog.minLevel = .off
default:
// nothing to do
ESLog.error("gotta invalid debug level ", sender.selectedTag())
}
}
func questionMe(questionMsg: String, handler: @escaping () -> Void) {
let questionAlert: NSAlert = NSAlert()
questionAlert.informativeText = questionMsg
questionAlert.messageText = "操作确认"
questionAlert.addButton(withTitle: "确认")
questionAlert.addButton(withTitle: "手滑了")
questionAlert.alertStyle = NSAlert.Style.critical
questionAlert.beginSheetModal(for: view.window!) { returnCode in
if returnCode == NSApplication.ModalResponse.alertFirstButtonReturn {
ESLog.info("user gives positive response to the question ", questionMsg)
handler()
} else {
ESLog.info("user gives negative response to the question ", questionMsg)
}
}
}
}
<file_sep>/Electsys Utility/Electsys Utility/LoginKits/CaptchaHelper.swift
//
// CaptchaHelper.swift
// Electsys Utility
//
// Created by 法好 on 2020/12/8.
// Copyright © 2020 yuxiqian. All rights reserved.
//
import Cocoa
class CaptchaHelper {
static var uuid: String?
static var t: String?
}
<file_sep>/Electsys Utility/Electsys Utility/GalleryKits/NGCurriculum.swift
//
// NGCurricula.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/17.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
class NGArrangements: Equatable {
static func == (lhs: NGArrangements, rhs: NGArrangements) -> Bool {
return lhs.weeks == rhs.weeks && lhs.weekDay == rhs.weekDay
&& lhs.sessions == rhs.sessions && lhs.campus == rhs.campus
&& lhs.classroom == rhs.classroom
}
internal init(weeks: [Int], weekDay: Int, sessions: [Int], campus: String, classroom: String) {
self.weeks = weeks
self.weekDay = weekDay
self.sessions = sessions
self.campus = campus
self.classroom = classroom
}
var weeks: [Int]
var weekDay: Int
var sessions: [Int]
var campus: String
var classroom: String
func getWeeksInterpreter() -> String {
var weeksStr: [String] = []
for week in weeks {
weeksStr.append(String(week))
}
return "第 " + weeksStr.joined(separator: "、") + " 周"
}
func getSessionsInterpreter() -> String {
var sessionsStr: [String] = []
for session in sessions {
sessionsStr.append(String(session))
}
return "第 " + sessionsStr.joined(separator: "、") + " 节"
}
}
class NGCurriculum: Equatable {
static func == (lhs: NGCurriculum, rhs: NGCurriculum) -> Bool {
return lhs.identifier == rhs.identifier &&
lhs.code == rhs.code &&
lhs.teacher == rhs.teacher &&
lhs.name == rhs.name &&
lhs.arrangements == rhs.arrangements &&
lhs.notes == rhs.notes
}
internal init(identifier: String, code: String, holderSchool: String, name: String, year: Int, term: Int, targetGrade: Int, teacher: [String], credit: Double, arrangements: [NGArrangements], studentNumber: Int, notes: String) {
self.identifier = identifier
self.code = code
self.holderSchool = holderSchool
self.name = name
self.year = year
self.term = term
self.targetGrade = targetGrade
self.teacher = teacher
self.credit = credit
self.arrangements = arrangements
self.studentNumber = studentNumber
self.notes = notes
}
var identifier: String
var code: String
var holderSchool: String
var name: String
var year: Int
var term: Int
var targetGrade: Int
var teacher: [String]
var credit: Double
var arrangements: [NGArrangements]
var studentNumber: Int
var notes: String
func getRelated() -> [StringPair] {
var classRoomsLiteral: [StringPair] = []
for arr in arrangements {
if !classRoomsLiteral.contains(StringPair(strA: arr.classroom, strB: arr.campus)) {
classRoomsLiteral.append(StringPair(strA: arr.classroom, strB: arr.campus))
}
}
return classRoomsLiteral
}
}
struct StringPair: Equatable {
var strA: String
var strB: String
}
<file_sep>/Electsys Utility/Podfile
platform :macos, '10.12’
target 'Electsys Utility' do
use_frameworks!
pod 'SwiftyJSON'
pod 'CrossroadRegex'
pod 'Kanna', '~> 4.0.0'
pod 'Alamofire'
pod 'Alamofire-SwiftyJSON'
pod 'Version'
pod 'CSV.swift', '~> 2.4.2'
pod 'Log'
end
<file_sep>/Electsys Utility/Electsys Utility/LegacyScheduleKits/Course.swift
//
// Course.swift
// Sync Utility
//
// Created by yuxiqian on 2018/8/30.
// Copyright © 2018 yuxiqian. All rights reserved.
//
// ScheduleKits/Course.swift 用于处理「课程表内」相关的课程信息。
// Utility/Curricula.swift 用于处理不与课程表相关的其他信息。
import Foundation
class Course : NSObject {
let hasChildren = false
var courseIdentifier: String = ""
var isSummerVacation: Bool = false
var courseName: String = ""
var courseTeacher: String = ""
var courseRoom: String = ""
var courseDay: Int = -1
var courseScore: Float = 0.0
var dayStartsAt: Int = 0
var courseDuration: Int = 0
var weekStartsAt: Int = 0
var weekEndsAt: Int = 0
var shiftWeek: ShiftWeekType = .Both
var isFollower = false
init (_ CourseName: String, identifier: String, CourseScore: Float) {
self.courseName = sanitize(CourseName)
self.courseIdentifier = sanitize(identifier)
self.courseScore = CourseScore
}
func setClassroom(classroom: String) {
self.courseRoom = sanitize(classroom)
}
func setTeacherName(teacher: String) {
self.courseTeacher = sanitize(teacher)
}
func setTimetable(startsAt: Int, duration: Int) {
self.dayStartsAt = startsAt
self.courseDuration = duration
}
func setWeekDuration(start: Int, end: Int) {
self.weekStartsAt = start
self.weekEndsAt = end
}
func judgeIfConflicts(_ another: Course, summerMode: Bool = false) -> Bool {
// 判断冲突与否,需要看现在加入的是否是小学期的课程。
// 同一张课表里,就算不在同一周出现,也不会占有相同的时间(除非是在同一格中同时开始)
// (否则课表无法成形)
// 但是小学期和主课表完全分开不属于同一张课表
// 因此需要判断的内容更多。
// 故而需要参数 summerMode
if summerMode {
if (self.courseDay != another.courseDay) {
return false
}
if self.weekEndsAt < another.weekStartsAt {
return false
}
if self.weekStartsAt > another.weekEndsAt {
return false
}
if self.shiftWeek == .EvenWeekOnly && another.shiftWeek == .OddWeekOnly {
return false
}
if self.shiftWeek == .OddWeekOnly && another.shiftWeek == .EvenWeekOnly {
return false
}
}
let selfWeek = generateArray(start: self.weekStartsAt,
end: weekEndsAt,
shift: self.shiftWeek)
let anotherWeek = generateArray(start: another.weekStartsAt,
end: another.weekEndsAt,
shift: another.shiftWeek)
let shared = getSharedArray(selfWeek, anotherWeek)
if shared.isEmpty {
return false
}
if self.dayStartsAt + self.courseDuration - 1 < another.dayStartsAt {
return false
}
return true
}
func judgeIfDuplicates(in week: [Day]) -> Bool {
var count = 0
for day in week {
for item in day.children {
if self.courseName == item.courseName {
count += 1
}
}
}
if count > 1 {
return true
}
return false
}
func getExtraIdentifier() -> String {
var identifier = self.courseName + ","
switch self.shiftWeek {
case .EvenWeekOnly:
identifier += "双周"
break
case .OddWeekOnly:
identifier += "单周"
break
default:
break
}
identifier += dayOfWeekName[self.courseDay]
return identifier
}
func getTime() -> String {
var timeString = ""
if self.weekStartsAt == self.weekEndsAt {
timeString += "\(self.weekStartsAt) 周"
} else if self.weekEndsAt - self.weekStartsAt == 1 {
timeString += "\(self.weekStartsAt)、\(self.weekEndsAt) 周"
} else {
timeString += "\(self.weekStartsAt) ~ \(self.weekEndsAt) 周"
}
switch self.shiftWeek {
case .EvenWeekOnly:
timeString += "双周"
break
case .OddWeekOnly:
timeString += "单周"
break
default:
break
}
timeString += dayOfWeekName[self.courseDay]
timeString += " \(self.dayStartsAt) ~ \(self.dayStartsAt + self.courseDuration - 1) 节,"
timeString += getExactTime(startAt: self.dayStartsAt, duration: self.courseDuration)
return timeString
}
}
let errorCourse = Course("未知", identifier: "未知", CourseScore: 0.0)
enum ShiftWeekType {
case OddWeekOnly
case EvenWeekOnly
case Both
}
func getAllCourseInDay(_ index: Int, _ array: [Course]) -> [Course] {
var resultArray: [Course] = []
for course in array {
if course.courseDay == index {
resultArray.append(course)
}
}
return resultArray
}
<file_sep>/update_modules.sh
# This script will update `Version` and `AppUpdater` libraries from GitHub.
git submodule update
<file_sep>/Electsys Utility/Electsys Utility/TouchBarKits/TouchBarIdentifier.swift
//
// TouchBarIdentifier.swift
// Electsys Utility
//
// Created by 法好 on 2019/12/4.
// Copyright © 2019 yuxiqian. All rights reserved.
//
@available(OSX 10.12.2, *)
extension NSTouchBarItem.Identifier {
static let scrubberPopover = NSTouchBarItem.Identifier("TextScrubberItemIdentifier")
}
<file_sep>/Electsys Utility/Electsys Utility/WebLoginKits/WebLoginDelegate.swift
//
// WebLoginDelegate.swift
// Electsys Utility
//
// Created by 法好 on 2020/12/8.
// Copyright © 2020 yuxiqian. All rights reserved.
//
import Foundation
protocol WebLoginDelegate {
func callbackWeb(_: Bool) -> ()
func callbackCookie(_: Bool) -> ()
}
<file_sep>/Electsys Utility/Electsys Utility/ViewController/WebLoginViewController.swift
//
// WebLoginViewController.swift
// Electsys Utility
//
// Created by 法好 on 2020/12/8.
// Copyright © 2020 yuxiqian. All rights reserved.
//
import Alamofire
import Cocoa
import WebKit
class WebLoginViewController: NSViewController, WKUIDelegate, WKNavigationDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
embedWebView.uiDelegate = self
embedWebView.navigationDelegate = self
startLoading()
}
@IBOutlet var embedWebView: WKWebView!
@IBOutlet var backwardsButton: NSButton!
@IBOutlet var forwardButton: NSButton!
@IBOutlet var urlLabel: NSTextField!
var delegate: WebLoginDelegate?
@IBAction func onRefresh(_ sender: NSButton) {
startLoading()
}
@IBAction func goBack(_ sender: NSButton) {
embedWebView.goBack()
}
@IBAction func goForward(_ sender: NSButton) {
embedWebView.goForward()
}
@IBAction func giveUpLogin(_ sender: NSButton) {
done(success: false)
}
@IBAction func completeLogin(_ sender: NSButton) {
done(success: true)
}
func startLoading() {
let request = URLRequest(url: URL(string: LoginConst.initUrl)!)
embedWebView.load(request)
refreshUI()
}
func refreshUI() {
backwardsButton.isEnabled = embedWebView.canGoBack
forwardButton.isEnabled = embedWebView.canGoForward
urlLabel.stringValue = embedWebView.url?.absoluteString ?? "空"
ESLog.info("redirected to %@", embedWebView.url?.absoluteString ?? "<< error page >>")
if embedWebView.url?.absoluteString.starts(with: LoginConst.mainPageUrl) ?? false {
done()
}
}
func done(success: Bool = true) {
if success {
if #available(OSX 10.13, *) {
embedWebView.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in
for cookie in cookies {
ESLog.info("get cookie at domain `%@`, pair: %@: %@", cookie.domain, cookie.name, cookie.value)
Alamofire.HTTPCookieStorage.shared.setCookie(cookie)
}
self.delegate?.callbackWeb(success)
}
}
} else {
delegate?.callbackWeb(success)
}
}
// MARK: - WKWebView Delegate Stuff
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
refreshUI()
}
}
<file_sep>/Electsys Utility/Electsys Utility/ScoreKits/ScoreConst.swift
//
// ScoreConst.swift
// Electsys Utility
//
// Created by 法好 on 2019/9/15.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
class ScoreConst {
static let requestUrl = "http://i.sjtu.edu.cn/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005"
static let termTable = ["", "3", "12", "16"]
}
<file_sep>/Electsys Utility/Electsys Utility/LogKits/ESLog.swift
//
// ESLog.swift
// Electsys Utility
//
// Created by 法好 on 2019/12/23.
// Copyright © 2019 yuxiqian. All rights reserved.
//
import Foundation
import os.log
enum ESLogLevel: Int {
case off = -1
case debug = 0
case info = 10
case error = 20
case fault = 30
}
class ESLog {
private static let loggerEntities: [ESLogLevel: OSLog] = [
ESLogLevel.debug: OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "DEBUG"),
ESLogLevel.info: OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "INFO"),
ESLogLevel.error: OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "ERROR"),
ESLogLevel.fault: OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "FAULT")
]
static var minLevel: ESLogLevel = .error
static func debug(_ message: StaticString, _ args: CVarArg...) {
makeLog(level: .debug, message, args)
}
static func info(_ message: StaticString, _ args: CVarArg...) {
makeLog(level: .info, message, args)
}
static func error(_ message: StaticString, _ args: CVarArg...) {
makeLog(level: .error, message, args)
}
static func fault(_ message: StaticString, _ args: CVarArg...) {
makeLog(level: .fault, message, args)
}
fileprivate static func makeLog(level: ESLogLevel, _ message: StaticString, _ args: [CVarArg]) {
if minLevel.rawValue <= level.rawValue && loggerEntities[level] != nil {
let actualLogger = loggerEntities[level]!
// super ugly hack
switch args.count {
case 0:
os_log(message, log: actualLogger)
case 1:
os_log(message, log: actualLogger, args[0])
case 2:
os_log(message, log: actualLogger, args[0], args[1])
case 3:
os_log(message, log: actualLogger, args[0], args[1], args[2])
default:
os_log(message, log: actualLogger, args)
}
}
}
}
func initDebugger() {
ESLog.info("eslogger initialized")
}
| a4f40fd03ae768b3fd0571ca06fd69934044c680 | [
"Ruby",
"Swift",
"Markdown",
"Python",
"C",
"Shell"
] | 63 | Swift | yuxiqian/electsys-utility | 7b28ab4dfcf708a4b29f8bf62dd963596e84ccc9 | bfebd7406c08097d7dedfe167a051261cab6c289 |
refs/heads/main | <file_sep># Laravel Ecommerce Site
## Features:
- Registration and Login(User and Admin)
- Forgot Password Recovery System
- Show All Product
- Add to Cart Product
- Checkout Products
- Search Product
- Categorized Product
## Tools and Technology
- HTML
- CSS
- Bootstrap
- JavaScript
- jQuery
- AJAX
- Laravel
- MySQL
## Project View
## Frontend
### Laravel Ecommerce Site Home Page



### Product Page

### Product Search Page

### Cart Page

### Checkout Page


## Backend
### Admin Dashboard Page

### Product Table Page

### Brand Table Page

### Category Table Page

### Dvisions Table Page

### Districts Table Page

### Orders Table Page



### Slider Table Page

<file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 07, 2021 at 02:25 PM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.9
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `laravel_ecommerce`
--
-- --------------------------------------------------------
--
-- Table structure for table `admins`
--
CREATE TABLE `admins` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`phone_no` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`avatar` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`type` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'Super Admin' COMMENT 'Admin|Super Admin',
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `admins`
--
INSERT INTO `admins` (`id`, `name`, `email`, `password`, `phone_no`, `avatar`, `type`, `remember_token`, `created_at`, `updated_at`) VALUES
(1, '<NAME>', '<EMAIL>', <PASSWORD>', '01772308391', NULL, 'Super Admin', 'ZGfCPetIOlh53FS4PnqbnAL6zxu16nIgRXEeajIARgfyyq1y5qpDCIbgj31j', '2021-03-05 00:05:19', '2021-03-05 05:52:53');
-- --------------------------------------------------------
--
-- Table structure for table `brands`
--
CREATE TABLE `brands` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`image` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `brands`
--
INSERT INTO `brands` (`id`, `name`, `description`, `image`, `created_at`, `updated_at`) VALUES
(2, 'OPPO', 'OPPO', '1614615980.jpg', '2021-03-01 10:26:20', '2021-03-01 10:27:08'),
(3, 'Honor', 'Honor', '1614616016.jpg', '2021-03-01 10:26:56', '2021-03-01 10:26:56'),
(4, 'Others', 'others', '1614616159.jpg', '2021-03-01 10:29:19', '2021-03-01 10:29:19');
-- --------------------------------------------------------
--
-- Table structure for table `carts`
--
CREATE TABLE `carts` (
`id` int(10) UNSIGNED NOT NULL,
`product_id` int(10) UNSIGNED NOT NULL,
`user_id` int(10) UNSIGNED DEFAULT NULL,
`order_id` int(10) UNSIGNED DEFAULT NULL,
`ip_address` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`product_quantity` int(11) NOT NULL DEFAULT 1,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `carts`
--
INSERT INTO `carts` (`id`, `product_id`, `user_id`, `order_id`, `ip_address`, `product_quantity`, `created_at`, `updated_at`) VALUES
(23, 7, NULL, 7, '::1', 1, '2021-03-07 00:00:25', '2021-03-07 00:01:34'),
(24, 6, NULL, 7, '::1', 1, '2021-03-07 00:00:33', '2021-03-07 00:01:34'),
(25, 7, NULL, NULL, '::1', 1, '2021-03-07 00:33:44', '2021-03-07 00:33:44'),
(26, 6, NULL, NULL, '::1', 1, '2021-03-07 00:33:45', '2021-03-07 00:33:45'),
(27, 4, NULL, NULL, '::1', 1, '2021-03-07 00:33:48', '2021-03-07 00:33:48');
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE `categories` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`image` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`parent_id` int(11) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `name`, `description`, `image`, `parent_id`, `created_at`, `updated_at`) VALUES
(5, 'Mobile', 'Mobile category', '1614605056.jpg', NULL, '2021-03-01 07:24:16', '2021-03-01 07:24:16'),
(6, 'Fashion', 'fashion category', '1614605097.jpg', NULL, '2021-03-01 07:24:57', '2021-03-01 07:24:57'),
(7, 'house', 'house', '1614605592.jpg', 6, '2021-03-01 07:33:12', '2021-03-01 07:33:12');
-- --------------------------------------------------------
--
-- Table structure for table `districts`
--
CREATE TABLE `districts` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`division_id` int(10) UNSIGNED NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `districts`
--
INSERT INTO `districts` (`id`, `name`, `division_id`, `created_at`, `updated_at`) VALUES
(1, 'Jamalpur', 2, '2021-03-03 04:15:18', '2021-03-03 04:15:18'),
(2, 'Tangail', 1, '2021-03-03 04:15:38', '2021-03-03 04:16:17');
-- --------------------------------------------------------
--
-- Table structure for table `divisions`
--
CREATE TABLE `divisions` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`priority` tinyint(3) UNSIGNED NOT NULL DEFAULT 1,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `divisions`
--
INSERT INTO `divisions` (`id`, `name`, `priority`, `created_at`, `updated_at`) VALUES
(1, 'Dhaka', 1, '2021-03-03 03:58:14', '2021-03-03 03:58:14'),
(2, 'Mymensingh', 2, '2021-03-03 03:58:37', '2021-03-03 03:58:37'),
(3, 'khulna', 3, '2021-03-03 04:14:46', '2021-03-03 04:14:46');
-- --------------------------------------------------------
--
-- Table structure for table `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(2, '2014_10_12_100000_create_password_resets_table', 1),
(3, '2021_02_22_152751_create_categories_table', 1),
(4, '2021_02_22_152820_create_brands_table', 1),
(5, '2021_02_22_152919_create_products_table', 1),
(7, '2021_02_22_155023_create_product_images_table', 1),
(8, '2014_10_12_000000_create_users_table', 2),
(9, '2021_03_03_091022_create_divisions_table', 3),
(10, '2021_03_03_091313_create_districts_table', 3),
(12, '2021_03_04_053635_create_carts_table', 4),
(13, '2021_03_04_102417_create_settings_table', 5),
(14, '2021_03_04_111121_create_payments_table', 6),
(15, '2021_03_04_053432_create_orders_table', 7),
(16, '2021_02_22_153013_create_admins_table', 8),
(17, '2021_03_06_151708_create_sliders_table', 9);
-- --------------------------------------------------------
--
-- Table structure for table `orders`
--
CREATE TABLE `orders` (
`id` int(10) UNSIGNED NOT NULL,
`user_id` int(10) UNSIGNED DEFAULT NULL,
`payment_id` int(10) UNSIGNED DEFAULT NULL,
`ip_address` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`phone_no` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`shipping_address` text COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`message` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`is_paid` tinyint(1) NOT NULL DEFAULT 0,
`is_completed` tinyint(1) NOT NULL DEFAULT 0,
`is_seen_by_admin` tinyint(1) NOT NULL DEFAULT 0,
`transaction_id` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`shipping_charge` int(11) NOT NULL DEFAULT 60,
`custom_discount` int(11) NOT NULL DEFAULT 0,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `orders`
--
INSERT INTO `orders` (`id`, `user_id`, `payment_id`, `ip_address`, `name`, `phone_no`, `shipping_address`, `email`, `message`, `is_paid`, `is_completed`, `is_seen_by_admin`, `transaction_id`, `shipping_charge`, `custom_discount`, `created_at`, `updated_at`) VALUES
(3, 6, 2, '127.0.0.1', '<NAME>', '01772308391', 'New shipping address', '<EMAIL>', NULL, 1, 1, 1, '12345', 60, 0, '2021-03-04 21:46:12', '2021-03-05 11:15:50'),
(4, 6, 3, '127.0.0.1', '<NAME>', '01772308391', 'New shipping address 1', '<EMAIL>', NULL, 1, 1, 1, '123456', 60, 0, '2021-03-05 04:14:28', '2021-03-05 11:14:00'),
(5, 6, 1, '127.0.0.1', '<NAME>', '01772308391', 'New shipping address 1', '<EMAIL>', NULL, 1, 1, 1, NULL, 60, 0, '2021-03-05 11:24:44', '2021-03-05 11:27:22'),
(6, 6, 1, '127.0.0.1', '<NAME>', '01772308391', 'New shipping address 1', '<EMAIL>', NULL, 1, 0, 1, NULL, 70, 0, '2021-03-05 11:26:05', '2021-03-06 23:17:49'),
(7, 6, 1, '::1', '<NAME>', '01772308391', 'New shipping address 1', '<EMAIL>', NULL, 0, 0, 0, NULL, 60, 0, '2021-03-07 00:01:34', '2021-03-07 00:01:34');
-- --------------------------------------------------------
--
-- Table structure for table `password_resets`
--
CREATE TABLE `password_resets` (
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `password_resets`
--
INSERT INTO `password_resets` (`email`, `token`, `created_at`) VALUES
('<EMAIL>', '$2y$10$eivspAcL3tqV.zTb.SjsDeSpvYYAEosAYWr65n2mssIFotTw/xOy6', '2021-03-02 03:53:34');
-- --------------------------------------------------------
--
-- Table structure for table `payments`
--
CREATE TABLE `payments` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`image` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`priority` tinyint(4) NOT NULL DEFAULT 1,
`short_name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`no` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Payment No',
`type` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'agent|personal',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `payments`
--
INSERT INTO `payments` (`id`, `name`, `image`, `priority`, `short_name`, `no`, `type`, `created_at`, `updated_at`) VALUES
(1, 'cash_in', 'cash_in.jpg', 1, 'cash_in', NULL, NULL, '2021-03-04 11:18:04', '2021-03-04 11:18:04'),
(2, 'bkash', 'bkash.jpg', 2, 'bkash', '01772308391', 'personal', '2021-03-04 11:19:30', '2021-03-04 11:19:30'),
(3, 'rocket', 'rocket.jpg', 3, 'rocket', '01772308391', 'personal', '2021-03-04 11:21:17', '2021-03-04 11:21:17');
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`id` int(10) UNSIGNED NOT NULL,
`category_id` int(10) UNSIGNED NOT NULL,
`brand_id` int(10) UNSIGNED NOT NULL,
`title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` text COLLATE utf8mb4_unicode_ci NOT NULL,
`slug` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`quantity` int(11) NOT NULL DEFAULT 1,
`price` int(11) NOT NULL,
`status` tinyint(4) NOT NULL DEFAULT 0,
`offer_price` int(11) DEFAULT NULL,
`admin_id` int(10) UNSIGNED NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`id`, `category_id`, `brand_id`, `title`, `description`, `slug`, `quantity`, `price`, `status`, `offer_price`, `admin_id`, `created_at`, `updated_at`) VALUES
(1, 5, 2, 'OPPO A3', 'OPPO A3', 'opp0-a3', 1, 10000, 1, NULL, 1, '2021-02-22 16:16:34', '2021-02-22 16:16:34'),
(2, 6, 4, 'OPPO A9', 'OPPO A9', 'oppo-a9', 1, 15000, 1, NULL, 1, '2021-02-22 16:16:34', '2021-02-22 16:16:34'),
(4, 6, 3, 'New Circular 22', 'gdsfgadsfhgfghdcgh2', 'new-circular', 2, 1000, 0, NULL, 1, '2021-02-23 07:17:13', '2021-03-01 12:29:00'),
(6, 6, 2, 'Demo Product', 'Demo Product', 'demo-product', 2, 4000, 0, NULL, 1, '2021-02-24 09:19:44', '2021-02-24 09:19:44'),
(7, 5, 3, 'Honor 8x', 'Honor 8x', 'honor-8x', 12, 20000, 0, NULL, 1, '2021-03-01 10:53:19', '2021-03-01 10:53:19');
-- --------------------------------------------------------
--
-- Table structure for table `product_images`
--
CREATE TABLE `product_images` (
`id` int(10) UNSIGNED NOT NULL,
`product_id` int(10) UNSIGNED NOT NULL,
`image` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `product_images`
--
INSERT INTO `product_images` (`id`, `product_id`, `image`, `created_at`, `updated_at`) VALUES
(1, 1, '1.jpg', NULL, NULL),
(2, 2, '2.jpg', NULL, NULL),
(3, 4, '1614086233.jpg', '2021-02-23 07:17:14', '2021-02-23 07:17:14'),
(4, 5, '1614089584.jpg', '2021-02-23 08:13:04', '2021-02-23 08:13:04'),
(5, 5, '1614089584.jpg', '2021-02-23 08:13:04', '2021-02-23 08:13:04'),
(6, 6, '1614179984.jpg', '2021-02-24 09:19:44', '2021-02-24 09:19:44'),
(7, 6, '1614179984.jpg', '2021-02-24 09:19:44', '2021-02-24 09:19:44'),
(8, 7, '1614617599.jpg', '2021-03-01 10:53:19', '2021-03-01 10:53:19');
-- --------------------------------------------------------
--
-- Table structure for table `settings`
--
CREATE TABLE `settings` (
`id` int(10) UNSIGNED NOT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`phone` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`address` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`shipping_cost` int(10) UNSIGNED NOT NULL DEFAULT 100,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `settings`
--
INSERT INTO `settings` (`id`, `email`, `phone`, `address`, `shipping_cost`, `created_at`, `updated_at`) VALUES
(1, '<EMAIL>', '01772308391', 'Jamalpur', 100, '2021-03-04 10:30:08', '2021-03-04 10:30:08');
-- --------------------------------------------------------
--
-- Table structure for table `sliders`
--
CREATE TABLE `sliders` (
`id` int(10) UNSIGNED NOT NULL,
`title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`image` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`button_text` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`button_link` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`priority` tinyint(3) UNSIGNED NOT NULL DEFAULT 10,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `sliders`
--
INSERT INTO `sliders` (`id`, `title`, `image`, `button_text`, `button_link`, `priority`, `created_at`, `updated_at`) VALUES
(1, 'First Slider', '1615048129.jpg', NULL, NULL, 1, '2021-03-06 16:12:58', '2021-03-06 10:28:49'),
(2, 'Test slider', '1615047962.jpg', 'test', 'http://localhost/laravel_ecommerce/public/admin/sliders', 1, '2021-03-06 10:26:02', '2021-03-06 10:26:02'),
(3, 'New Product', '1615049388.jpg', NULL, NULL, 1, '2021-03-06 10:49:48', '2021-03-06 10:49:48');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(10) UNSIGNED NOT NULL,
`first_name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`last_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`username` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`phone_no` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`street_address` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`division_id` int(10) UNSIGNED NOT NULL COMMENT 'Division Table ID',
`district_id` int(10) UNSIGNED NOT NULL COMMENT 'District Table ID',
`status` tinyint(3) UNSIGNED NOT NULL DEFAULT 0 COMMENT '0=Inactive|1=Active|2=Ban',
`ip_address` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`avatar` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`shipping_address` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `first_name`, `last_name`, `username`, `phone_no`, `email`, `password`, `street_address`, `division_id`, `district_id`, `status`, `ip_address`, `avatar`, `shipping_address`, `remember_token`, `created_at`, `updated_at`) VALUES
(6, '<NAME>', 'Hossain', 'md-forhadhossain', '01772308391', '<EMAIL>', <PASSWORD>', 'Dewangonj, Jamalpur', 2, 1, 1, '127.0.0.1', NULL, 'New shipping address 1', 'pfxrxGvM1SIPl31ofOZ5YKwRKYRQbcs6o95dC3bSdjKX78gUmsavmgDqSnaZ', '2021-03-03 07:07:30', '2021-03-04 23:43:49');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admins`
--
ALTER TABLE `admins`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `admins_email_unique` (`email`);
--
-- Indexes for table `brands`
--
ALTER TABLE `brands`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `carts`
--
ALTER TABLE `carts`
ADD PRIMARY KEY (`id`),
ADD KEY `carts_user_id_foreign` (`user_id`),
ADD KEY `carts_product_id_foreign` (`product_id`),
ADD KEY `carts_order_id_foreign` (`order_id`);
--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `districts`
--
ALTER TABLE `districts`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `divisions`
--
ALTER TABLE `divisions`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
ADD PRIMARY KEY (`id`),
ADD KEY `orders_user_id_foreign` (`user_id`),
ADD KEY `orders_payment_id_foreign` (`payment_id`);
--
-- Indexes for table `password_resets`
--
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`);
--
-- Indexes for table `payments`
--
ALTER TABLE `payments`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `payments_short_name_unique` (`short_name`);
--
-- Indexes for table `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `product_images`
--
ALTER TABLE `product_images`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `settings`
--
ALTER TABLE `settings`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `sliders`
--
ALTER TABLE `sliders`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `users_username_unique` (`username`),
ADD UNIQUE KEY `users_phone_no_unique` (`phone_no`),
ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `admins`
--
ALTER TABLE `admins`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `brands`
--
ALTER TABLE `brands`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `carts`
--
ALTER TABLE `carts`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28;
--
-- AUTO_INCREMENT for table `categories`
--
ALTER TABLE `categories`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `districts`
--
ALTER TABLE `districts`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `divisions`
--
ALTER TABLE `divisions`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;
--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `payments`
--
ALTER TABLE `payments`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `product_images`
--
ALTER TABLE `product_images`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `settings`
--
ALTER TABLE `settings`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `sliders`
--
ALTER TABLE `sliders`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `carts`
--
ALTER TABLE `carts`
ADD CONSTRAINT `carts_order_id_foreign` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `carts_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `carts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
--
-- Constraints for table `orders`
--
ALTER TABLE `orders`
ADD CONSTRAINT `orders_payment_id_foreign` FOREIGN KEY (`payment_id`) REFERENCES `payments` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `orders_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 2386fb8318e5730c553f666cf13dedfc5ddde996 | [
"Markdown",
"SQL"
] | 2 | Markdown | forhadict/laravel_ecommerce | 8d9953dcf02346709ee39050010592aedfae2ac9 | 5c1de606bbc4ef66cf086cbca787fbeb90f69364 |
refs/heads/master | <file_sep>$(document).ready(function()
{
$('.chat-head').click(function()
{
$('.chat-body').slideToggle('slow');
});
$('.msg-head').click(function()
{
$('.msg-wrap').slideToggle('slow');
});
$('.close').click(function() {
$('.msg-box').hide();
});
$('.user').click(function()
{
$('.msg-wrap').show();
$('.msg-box').show();
});
$('.msg-input').keypress(
function(e){
if (e.keyCode == 13) {
var msg=$(this).val();
$(this).val("");
$("<div class='msg-b'>"+msg+"</div>").insertBefore(".msg-insert");
$('.msg-body').scrollTop($('.msg-body')[0].scrollHeight);
}
});
$(document).on('click','#button',function()
{
var feed=$('#feedbox').val();
if(!feed)
alert('enter');
else
{
$(' <div id="feed"><div class="row">\
<div class="col-md-2"><img src="DP from bestprofilepix.jpg" class="img-circle" width="100%"/></div>\
<div class="col-md-10"><div><b>RITI </b></div>\
<div class="pull-right text-muted" id="delete">delete</div>\
<div>'+feed+' </div>\
<div class="text-muted"><small> Posted 2 min ago <small></div>\
</div>\
</div><hr></div>').insertAfter('#insert').hide().slideDown();
}
$("#feedbox").val('');
});
$(document).on('click','#delete',function()
{
$(this).closest('#feed').slideUp();
});
});
| 0a3f42bf255507befced72a125e9437566200fa9 | [
"JavaScript"
] | 1 | JavaScript | riti12345/Fb-like_app | b7cc19de50b6dd0a65e317d3b1c7c9cfe854f05d | 6e904f79b6534062d216b76b6ce250ffc737ed0e |
refs/heads/master | <repo_name>pikeman1992/foodrium<file_sep>/src/providers/models/share.ts
export class Share {
userId: number;
postId: number;
shareTo: string;
createdAt: string;
updatedAt: string;
}<file_sep>/src/providers/services/post.service.ts
import { Observable } from 'rxjs/Observable'
import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { IPost } from '../models/post'
import { LoadingController } from 'ionic-angular'
import { DomSanitizer } from '@angular/platform-browser'
import { FileTransfer, FileTransferObject, FileUploadOptions } from '@ionic-native/file-transfer'
import { File } from '@ionic-native/file'
import { AuthService } from './auth.service'
import { env } from '../../environments/env'
@Injectable()
export class PostService {
constructor(private loadingCtrl: LoadingController,
private http: HttpClient,
private transfer: FileTransfer,
private file: File,
private authService: AuthService) {
}
findPosts(): Observable<any> {
return this.http.get(env.END_POINT + 'posts')
}
createPost(body: IPost): Promise<any> {
return this.authService.getToken().then(token => {
const fileTransfer: FileTransferObject = this.transfer.create()
const options: FileUploadOptions = {
fileKey: 'file',
fileName: body.file.fileName,
headers: {
'X-ACCESS-TOKEN': token
},
params: {
description: body.description,
location: body.location
}
}
return fileTransfer.upload(body.file.photoURL, `${env.END_POINT}posts`, options)
})
}
}<file_sep>/src/pages/camera/reducers/post.reducer.ts
import * as PostActions from '../actions/post.actions'
import { List, Map, Record } from 'immutable'
import { IPost } from '../../../providers/models/post'
export interface PostState extends Map<string, any> {
data: any
posts: List<IPost>
payload: any
error: any
pending: boolean
}
export const PostStateRecord = Record({
data: null,
posts: List([]),
payload: null,
error: null,
pending: false,
})
export const initialPostState: PostState = new PostStateRecord() as PostState
export function postReducer(state = initialPostState, action: PostActions.Actions): PostState {
switch (action.type) {
/**
* find post
*/
case PostActions.FIND_POSTS: {
return state.merge({data: action.payload, error: null, pending: true}) as PostState
}
case PostActions.FIND_POSTS_SUCCESS: {
return state.merge({
payload: action.payload,
posts: action.payload,
pending: false,
}) as PostState
}
case PostActions.FIND_POSTS_FAILURE: {
return state.merge({error: action.payload, pending: false}) as PostState
}
/**
* create post
*/
case PostActions.CREATE_POST: {
return state.merge({data: action.payload, error: null, pending: true}) as PostState
}
case PostActions.CREATE_POST_SUCCESS: {
return state.merge({
payload: action.payload,
posts: state.posts.unshift(action.payload),
pending: false,
}) as PostState
}
case PostActions.CREATE_POST_FAILURE: {
return state.merge({error: action.payload, pending: false}) as PostState
}
default: {
return state
}
}
}<file_sep>/src/pages/home/home.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { HomePage } from './home';
import { StoriesPage } from './components/stories/stories';
import { PostPage } from './components/post/post';
import { CommentDetailPage } from './components/comment-detail/comment-detail';
import { LatestPage } from './components/latest/latest';
import { ExplorePage } from './components/explore/explore';
import { AroundPage } from './components/around/around';
import { HomeTabsService } from './components/hometabs.service';
import { PostService } from '../../providers/services/post-mock.service';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@NgModule({
declarations: [
HomePage,
LatestPage,
ExplorePage,
AroundPage,
StoriesPage,
PostPage,
CommentDetailPage,
],
imports: [
CommonModule,
IonicModule,
],
bootstrap: [IonicApp],
entryComponents: [
HomePage,
LatestPage,
ExplorePage,
AroundPage,
StoriesPage,
PostPage,
CommentDetailPage,
],
providers: [
HomeTabsService,
PostService,
StatusBar,
SplashScreen,
{ provide: ErrorHandler, useClass: IonicErrorHandler }
]
})
export class HomeModule { }
<file_sep>/src/providers/models/post.ts
import { PostStatus } from './post-status';
import { PostType } from './post-type';
export interface IPost {
[key: string]: any
source?: string[]
description?: string
location?: string
coordinates?: [number, number]
user?: string
info?: string
status?: PostStatus
type?: PostType
}
<file_sep>/src/providers/models/follow.ts
export class Follow {
userId: number;
followerId: number;
createdAt: string;
unfollowedAt: string;
}<file_sep>/src/environments/_default.env.ts
export const DEFAULT_ENV = {
APP_ENV: 'development',
PROTOCOL: 'https://',
HOST: 'api.foodrium.com',
API_VERSION: '/v1/',
END_POINT: 'https://api.foodrium.com/v1/',
CDN_URL: 'https://s3-ap-southeast-1.amazonaws.com/foodrium.images/',
GOOGLE_MAP_API_KEY: '<KEY>'
}
<file_sep>/src/providers/models/bookmark-collection.ts
export class BookmarkCollection {
id: number;
name: string;
userId: number;
createdAt: string;
updatedAt: string;
}<file_sep>/src/pages/start/components/forgot-password/forgot-password.ts
import { Component, OnInit } from '@angular/core'
import { AlertController, App, Loading, LoadingController, NavController, ViewController } from 'ionic-angular'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { Store } from '@ngrx/store'
import * as AuthActions from '../../actions/auth.actions'
import { AppState } from '../../../../app/interface'
import * as fromAuth from '../../reducers/auth.state'
import { EmailValidator } from '../../../../providers/validators/email.validator'
@Component({
selector: 'page-forgot-password',
templateUrl: 'forgot-password.html',
})
export class ForgotPasswordPage implements OnInit {
loader: Loading
forgetPassForm: FormGroup
constructor(public navCtrl: NavController,
public viewCtrl: ViewController,
public alertCtrl: AlertController,
public loadingCtrl: LoadingController,
private fb: FormBuilder,
private store: Store<AppState>,) {
this.handleAlertSuccess()
}
ngOnInit() {
this.forgetPassForm = this.fb.group({
email: ['<EMAIL>', [Validators.required, EmailValidator]],
})
}
onSubmit() {
if (this.forgetPassForm.invalid)
return false
this.presentLoading()
const formModel = this.forgetPassForm.value
this.store.dispatch(new AuthActions.ForgotPassword(formModel))
}
handleAlertSuccess() {
this.store.select(fromAuth.getPayload).subscribe(
error => {
if (error) {
this.loader.dismiss()
this.presentAlert(`Send mail successfully. Please check you email. If you don't see mail in the inbox. Please check in your spam inbox.`)
}
},
)
}
presentAlert(message) {
const alert = this.alertCtrl.create({
title: 'Success',
subTitle: message,
buttons: ['Dismiss'],
})
alert.present()
}
presentLoading() {
this.loader = this.loadingCtrl.create({
content: 'Please wait...',
})
this.loader.present()
}
}<file_sep>/src/providers/models/like.ts
export class Like {
userId: number;
postId: number;
likeTypeId: number;
createAt: string;
updateAt: string;
}<file_sep>/src/providers/services/user-mock.service.ts
import { Injectable } from '@angular/core';
import users from './user-mock';
@Injectable()
export class UserService{
getAll() {
return Promise.resolve(users);
}
getById(id){
return Promise.resolve(users[id - 1]);
}
}<file_sep>/src/providers/validators/password.validator.ts
import { AbstractControl } from '@angular/forms'
export function MatchPassword(AC: AbstractControl) {
let password = AC.get('password').value
let confirmPassword = AC.get('confirmPassword').value
if (password != confirmPassword) {
AC.get('confirmPassword').setErrors({matchPassword: true})
} else {
return null
}
}<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core'
import { NavController, Platform, App } from 'ionic-angular'
import { StatusBar } from '@ionic-native/status-bar'
import { SplashScreen } from '@ionic-native/splash-screen'
import { LoginPage } from '../pages/start/components/login/login'
import { TabsPage } from '../pages/tabs/tabs'
import { LoadingPage } from '../pages/loading/loading'
import { AppState } from './interface'
import { Store } from '@ngrx/store'
import * as fromAuth from '../pages/start/reducers/auth.state'
import { Observable } from 'rxjs'
import { AuthService } from '../providers/services/auth.service'
import * as DeviceActions from '../pages/start/actions/device.actions'
// import { WritePostPage } from '../pages/camera/write-post/write-post';
@Component({
templateUrl: 'app.html',
})
export class MyApp {
rootPage: any = LoadingPage
constructor(platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
private authService: AuthService,
private store: Store<AppState>,
public app: App) {
this.store.dispatch(new DeviceActions.GetDeviceInfo())
console.log('testtt')
Promise.all([
this.authService.getToken(),
this.authService.getUser(),
platform.ready(),
]).then(vals => {
statusBar.styleDefault()
splashScreen.hide()
if (!vals[0]) {
this.rootPage = LoginPage
} else {
this.rootPage = TabsPage
}
})
}
ionViewDidLoad() {
console.log('/////')
this.store.dispatch(new DeviceActions.GetDeviceInfo())
}
}
<file_sep>/src/pages/notification/notify-following/notify-following.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-notify-following',
templateUrl: 'notify-following.html',
})
export class NotifyFollowingPage {
constructor(public navCtrl: NavController) {
}
}
<file_sep>/src/providers/services/user.service.ts
import 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Storage } from '@ionic/storage'
//import { Http, Headers, RequestOptions } from '@angular/http';
import { IUser } from '../models/user'
import { AuthService } from './auth.service'
import { env } from '../../environments/env'
@Injectable()
export class UserService {
constructor(private storage: Storage,
private http: HttpClient,
private authService: AuthService,
) {
}
//from server
getUser(userId: string): Observable<any> {
return this.http.get(env.END_POINT + `users/${userId}`)
}
updateUser(body: IUser, userId: string): Observable<any> {
return this.http.patch(env.END_POINT + `users/${userId}`, body)
}
}<file_sep>/src/pages/camera/components/gallery/gallery.ts
import { Component, Input } from '@angular/core'
import { ModalController, NavController } from 'ionic-angular'
/*Plugin take photo from device*/
//import { PhotoLibrary } from '@ionic-native/photo-library';
/*Write Post page*/
import { WritePostPage } from '../write-post/write-post'
import { PhotoLibrary } from '@ionic-native/photo-library'
@Component({
selector: 'page-gallery',
templateUrl: 'gallery.html',
})
export class GalleryPage {
@Input() photos: any[]
modal: any
constructor(public navCtrl: NavController,
public modalCtrl: ModalController,
private photoLib: PhotoLibrary,) {
}
writePost(selectedImage) {
console.log('%c selectedImage', 'background: red; color: white', selectedImage)
this.modal = this.modalCtrl.create(WritePostPage, {selectedImage})
this.modal.present()
}
}<file_sep>/src/providers/models/post-status.ts
export class PostStatus {
postId: number;
countLike: number;
countComment: number;
countShare: number;
postTypeId: number;
createdAt: Date;
updatedAt: Date;
}<file_sep>/src/pages/start/actions/auth.actions.ts
import { Action } from '@ngrx/store'
import { Authenticate, IUser } from '../../../providers/models/user'
export const LOGIN = '[Start] Login'
export const LOGIN_SUCCESS = '[Start] Login Success'
export const LOGIN_FAILURE = '[Start] Login Failure'
export const LOGOUT = '[Start] Logout'
export const LOGOUT_SUCCESS = '[Start] Logout Success'
export const LOGOUT_FAILURE = '[Start] Logout Failure'
export const SIGNUP = '[Start] Sign Up'
export const SIGNUP_SUCCESS = '[Start] Sign Up Success'
export const SIGNUP_FAILURE = '[Start] Sign Up Failure'
export const FORGOT_PASSWORD = <PASSWORD>'
export const FORGOT_PASSWORD_SUCCESS = '[Start] Forgot Password Success'
export const FORGOT_PASSWORD_FAILURE = '[Start] Forgot Password Failure'
/**
* Login
*/
export class Login implements Action {
readonly type = LOGIN
constructor(public payload: Authenticate) {
}
}
export class LoginSuccess implements Action {
readonly type = LOGIN_SUCCESS
constructor(public payload: { token: string, user: IUser }) {
}
}
export class LoginFailure implements Action {
readonly type = LOGIN_FAILURE
constructor(public payload: any) {
}
}
/**
* Logout
*/
export class Logout implements Action {
readonly type = LOGOUT
}
export class LogoutSuccess implements Action {
readonly type = LOGOUT_SUCCESS
}
export class LogoutFailure implements Action {
readonly type = LOGOUT_FAILURE
constructor(public payload: any) {
}
}
/**
* Sign up
*/
export class SignUp implements Action {
readonly type = SIGNUP
constructor(public payload: Authenticate) {
}
}
export class SignUpSuccess implements Action {
readonly type = SIGNUP_SUCCESS
constructor(public payload: { token: string, user: IUser }) {
}
}
export class SignUpFailure implements Action {
readonly type = SIGNUP_FAILURE
constructor(public payload: any) {
}
}
/**
* Forgot password
*/
export class ForgotPassword implements Action {
readonly type = FORGOT_PASSWORD
constructor(public payload: { email: string }) {
}
}
export class ForgotPasswordSuccess implements Action {
readonly type = FORGOT_PASSWORD_SUCCESS
constructor(public payload: any) {
}
}
export class ForgotPasswordFailure implements Action {
readonly type = FORGOT_PASSWORD_FAILURE
constructor(public payload: any) {
}
}
export type Actions =
| Login
| LoginSuccess
| LoginFailure
| Logout
| LogoutSuccess
| LogoutFailure
| SignUp
| SignUpSuccess
| SignUpFailure
| ForgotPassword
| ForgotPasswordSuccess
| ForgotPasswordFailure<file_sep>/src/providers/models/extend/gallery.ts
export class Gallery {
creationDate: Date;
thumbnailURL: string;
fileName: string;
}<file_sep>/src/providers/services/post-mock.service.ts
import { Injectable } from '@angular/core';
import posts from './post-mock';
import users from './user-mock';
@Injectable()
export class PostService {
getAll() {
return Promise.resolve(posts);
}
getById(id) {
return Promise.resolve(posts[id - 1]);
}
getUserByPostId(userId) {
return Promise.resolve(users[userId - 1]);
}
}<file_sep>/src/pages/camera/effects/post.effects.ts
import { Actions, Effect } from '@ngrx/effects'
import * as PostActions from '../actions/post.actions'
import { Observable } from 'rxjs/Observable'
import { Action } from '@ngrx/store'
import { of } from 'rxjs/observable/of'
import { Injectable } from '@angular/core'
import { App } from 'ionic-angular'
import { PostService } from '../../../providers/services/post.service'
import { LatestPage } from '../../home/components/latest/latest'
@Injectable()
export class PostEffects {
constructor(private actions$: Actions,
private postService: PostService,
public app: App,) {
}
@Effect()
FindPosts$: Observable<Action> = this.actions$
.ofType(PostActions.FIND_POSTS)
.map((action: PostActions.FindPosts) => action.payload)
.exhaustMap(() => this.postService.findPosts())
.map(res => new PostActions.FindPostsSuccess(res))
.catch(error => of(new PostActions.FindPostsFailure(error)))
@Effect()
CreatePost$: Observable<Action> = this.actions$
.ofType(PostActions.CREATE_POST)
.debounceTime(1000)
.map((action: PostActions.CreatePost) => action.payload)
.exhaustMap(post => this.postService.createPost(post))
.map(res => {
if (!res || !res.response) return Observable.throw(new Error('Something went wrong.'))
return JSON.parse(res.response)
})
.map(res => new PostActions.CreatePostSuccess(res))
.catch(error => of(new PostActions.CreatePostFailure(error)))
// @Effect({ dispatch: false })
// CreatePostSuccess$: Observable<Action> = this.actions$
// .ofType(PostActions.CREATE_POST_SUCCESS)
// .do(() => this.navCtrl.parent.select())
}<file_sep>/src/pages/home/components/post/post.ts
import { Component, Input, OnInit } from '@angular/core'
import { NavController } from 'ionic-angular'
import { CommentDetailPage } from '../comment-detail/comment-detail'
import { IPost } from '../../../../providers/models/post'
import { IUser } from '../../../../providers/models/user'
import { env } from '../../../../environments/env'
@Component({
selector: 'page-post',
templateUrl: 'post.html',
})
export class PostPage implements OnInit {
@Input() post: IPost
userInfo: IUser
commentPage = CommentDetailPage
isLoaded = true
cdnURL = env.CDN_URL
constructor(public navCtrl: NavController) {
}
// getUserId() {
// return this.postSer.getUserByPostId(this.post.userId)
// .then(data => {
// this.userInfo = data;
// });
// }
ngOnInit() {
// this.getUserId().then(() =>
// this.isLoaded = true);
}
}
<file_sep>/src/pages/chat/chat.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { ChatPage } from './chat';
import { MessagesPage } from './chat-messages/messages';
import { GroupChatPage } from './chat-groupchat/groupchat';
import { MessagesDetailPage } from './chat-messages/messages-detail/messages-detail';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@NgModule({
declarations: [
ChatPage,
MessagesPage,
GroupChatPage,
MessagesDetailPage,
],
imports: [
CommonModule,
IonicModule,
],
bootstrap: [IonicApp],
entryComponents: [
ChatPage,
MessagesPage,
GroupChatPage,
MessagesDetailPage,
],
providers: [
StatusBar,
SplashScreen,
{ provide: ErrorHandler, useClass: IonicErrorHandler }
]
})
export class ChatModule { }
<file_sep>/src/pages/user/components/editacount/editacount.ts
import { AfterViewInit, Component, OnInit } from '@angular/core';
import { AlertController, Loading, LoadingController, NavController, NavParams, ViewController } from 'ionic-angular';
import { env } from '../../../../environments/env'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { UserService } from '../../../../providers/services/user.service'
import * as fromUser from '../../reducers/user.state'
import * as UserActions from '../../actions/user.actions'
import { AppState } from '../../../../app/interface'
import { Store } from '@ngrx/store'
import { Alert } from 'ionic-angular/components/alert/alert';
@Component({
selector: 'page-editacount',
templateUrl: 'editacount.html'
})
export class EditAcountPage implements OnInit, AfterViewInit {
gender = "female";
userId: string;
userData: any = null;
cdnURL = env.CDN_URL;
userForm: FormGroup = null;
loader: Loading;
alertDialog: Alert;
constructor(public navCtrl: NavController,
private store: Store<AppState>,
public navParams: NavParams,
public viewCtrl: ViewController,
public loadingCtrl: LoadingController,
private fb: FormBuilder,
public userService: UserService,
public alertCtrl: AlertController) {
this.presentLoading()
this.userId = this.navParams.get('data');
console.log('edit', this.userId);
this.store.dispatch(new UserActions.GetUserInfo(this.userId));
this.getUserInfo();
}
onBack() {
this.viewCtrl.dismiss();
}
ngOnInit() {
}
ngAfterViewInit() {
}
getUserInfo() {
this.store.select(fromUser.getData).subscribe(
data => {
if (data) {
console.log('from server', (data as any).toJSON());
this.userData = (data as any).toJSON();
this.userForm = this.fb.group({
fullName: [this.userData.fullName],
userName: [this.userData.username, Validators.required],
website: [this.userData.website],
bio: [this.userData.bio],
phoneNumber: [this.userData.phoneNumber],
gender: [this.userData.gender],
})
}
this.loader.dismiss();
}
)
}
onSubmit() {
if (this.userForm.invalid)
return false
const formModel = this.userForm.value;
const userId = this.userId;
this.presentLoading();
this.store.dispatch(new UserActions.UpdateUser({
...formModel, userId
}))
}
showSuccessAlert() {
this.alertDialog = this.alertCtrl.create({
title: 'Edit Success!',
buttons: ['OK']
});
this.alertDialog.present();
}
getSuccessSave() {
this.store.select(fromUser.getPending).subscribe(
pending => {
if (!pending) {
this.store.select(fromUser.getError).subscribe(
error =>{
if(error == null){
this.loader.dismiss();
}
}
)
}
},
)
}
//Loading control
presentLoading() {
this.loader = this.loadingCtrl.create({
content: 'Please wait...',
})
this.loader.present()
}
}
<file_sep>/src/pages/user/user.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { UserPage } from './user';
import { EditAcountPage } from './components/editacount/editacount';
import { MyPicPage } from './components/store/mypic/mypic';
import { MyPostPage } from './components/store/mypost/mypost';
import { MyPicInPostPage } from './components/store/mypicinpost/mypicinpost';
import { MyBookMarksModule } from './components/store/mybookmarks/mybookmarks.module';
import { EffectsModule } from '@ngrx/effects'
import { UserEffects } from './effects/user.effects'
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@NgModule({
declarations: [
UserPage,
EditAcountPage,
MyPicPage,
MyPostPage,
MyPicInPostPage,
],
imports: [
CommonModule,
IonicModule,
MyBookMarksModule,
EffectsModule.forFeature([
UserEffects
]),
],
bootstrap: [IonicApp],
entryComponents: [
UserPage,
EditAcountPage,
MyPicPage,
MyPostPage,
MyPicInPostPage,
],
providers: [
StatusBar,
SplashScreen,
{ provide: ErrorHandler, useClass: IonicErrorHandler }
]
})
export class UserModule { }
<file_sep>/src/pages/start/reducers/device.reducer.ts
import * as DeviceActions from '../actions/device.actions'
import { Map, Record } from 'immutable'
export interface DeviceState extends Map<string, any> {
data: any
device: any
error: any
pending: boolean
}
export const DeviceStateRecord = Record({
data: null,
device: null,
error: null,
pending: false,
})
export const initialDeviceState: DeviceState = new DeviceStateRecord() as DeviceState
export function deviceReducer(state = initialDeviceState, action: DeviceActions.Actions): DeviceState {
switch (action.type) {
/**
* Get device info
*/
case DeviceActions.GET_DEVICE_INFO: {
return state.merge({error: null, pending: true}) as DeviceState
}
case DeviceActions.GET_DEVICE_INFO_SUCCESS: {
return state.merge({...action.payload, pending: false}) as DeviceState
}
case DeviceActions.GET_DEVICE_INFO_FAILURE: {
return state.merge({error: action.payload, pending: false}) as DeviceState
}
default: {
return state
}
}
}<file_sep>/src/pages/tabs/tabs.ts
import { Component, ViewChild } from '@angular/core'
import { SearchPage } from '../search/search';
import { CameraPage } from '../camera/camera';
import { HomePage } from '../home/home';
//import { ChatPage } from '../chat/chat';
import { UserPage } from '../user/user';
import { NotificationPage } from '../notification/notification';
import * as fromAuth from '../start/reducers/auth.state';
import { Store } from '@ngrx/store';
import { AppState } from '../../app/interface';
@Component({
templateUrl: 'tabs.html'
})
export class TabsPage {
@ViewChild('tabs') tabs
tab1Root = HomePage;
tab2Root = SearchPage;
tab3Root = CameraPage;
//tab4Root = ChatPage;
tab4Root = NotificationPage;
tab5Root = UserPage;
constructor(
private store: Store<AppState>,
) {
}
}
<file_sep>/src/providers/models/report.ts
export class Report {
id: number;
reporterId: number;
reportToId: number;
createdAt: string;
updatedAt: string;
}<file_sep>/src/providers/services/post-mock.ts
import { IPost } from '../models/post';
let posts: any[] = [
{
id: 1,
thumbnail: 'assets/img/content3.jpg',
description: 'Trà sữa Bobabop đặc biệt',
location: 'Bobabop ở đâu đó',
coordination: '',
userId: 1,
deleted: false,
},
{
id: 2,
thumbnail: 'assets/img/content4.jpg',
description: 'Pizza Double Chesse',
location: 'Cửa hàng Pizza trên đường ABC',
coordination: '',
userId: 2,
deleted: false,
},
{
id: 3,
thumbnail: 'assets/img/content1.jpg',
description: 'Mỳ ý bò bằm đặc biệt',
location: 'Nhà hàng Alfessco',
coordination: '',
userId: 2,
deleted: false,
},
{
id: 4,
thumbnail: 'assets/img/content2.jpg',
description: 'Cơm tấm cali',
location: 'Nhà hàng California',
coordination: '',
userId: 1,
deleted: false,
},
{
id: 5,
thumbnail: 'assets/img/content5.jpg',
description: 'Đùi gà chiên bơ',
location: 'Tiệm cơm nào đó',
coordination: '',
userId: 2,
deleted: false,
}
];
export default posts;<file_sep>/src/pages/user/components/store/mypost/mypost.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-mypost',
templateUrl: 'mypost.html'
})
export class MyPostPage {
constructor(public navCtrl: NavController) {
}
}
<file_sep>/src/pages/user/reducers/user.state.ts
import { createSelector } from '@ngrx/store'
import { UserState } from './user.reducers'
import { AppState } from '../../../app/interface'
export const selectUser = (state: AppState): UserState => state.user
export const getData = createSelector(
selectUser,
(state: UserState) => state.data,
)
export const getPayload = createSelector(
selectUser,
(state: UserState) => state.payload,
)
export const getPending = createSelector(
selectUser,
(state: UserState) => state.pending,
)
export const getError = createSelector(
selectUser,
(state: UserState) => state.error,
)<file_sep>/src/providers/models/user-info.ts
export class UserInfo{
userId:number;
followerCount:number;
followingCount:number;
statusId:number;
roleId:number;
isSentNotify:boolean;
createdAt:Date;
updatedAt:Date;
}<file_sep>/src/pages/user/user.ts
import { Component, OnInit } from '@angular/core'
import { ModalController, NavController, LoadingController, Loading } from 'ionic-angular'
import { Observable } from 'rxjs'
import { EditAcountPage } from './components/editacount/editacount'
import { MyBookMarksPage } from './components/store/mybookmarks/mybookmarks'
import { AppState } from '../../app/interface'
import { Store } from '@ngrx/store'
import * as Actions from '../start/actions/auth.actions'
import * as fromUser from './reducers/user.state'
import * as UserActions from './actions/user.actions'
import { AuthService } from '../../providers/services/auth.service'
import { env } from '../../environments/env'
@Component({
selector: 'page-user',
templateUrl: 'user.html',
})
export class UserPage implements OnInit {
profileId: any;
modal: any;
profile_child = 'pic'
bookmarkspage = MyBookMarksPage
cdnURL = env.CDN_URL
loader: Loading
constructor(
private store: Store<AppState>,
public navCtrl: NavController,
public modalCtrl: ModalController,
public authService: AuthService,
public loadingCtrl: LoadingController, ) {
this.presentLoading();
}
ngOnInit() {
}
ionViewDidLoad() {
this.store.dispatch(new UserActions.GetUserId());
this.getUserId();
}
getUserId() {
this.store.select(fromUser.getData).subscribe(
data => {
if (data) {
this.profileId = (data as any).toJSON()._id;
console.log('User ID', this.profileId);
this.loader.dismiss();
}
}
)
}
//Loading control
presentLoading() {
this.loader = this.loadingCtrl.create({
content: 'Please wait...',
})
this.loader.present()
}
// getUserInfo() {
// Observable.fromPromise(this.authService.getUser()).subscribe(
// data => {
// this.profileInfo = data;
// console.log('data', this.profileInfo);
// }
// )
// }
openEditUser() {
this.modal = this.modalCtrl.create(EditAcountPage, { data: this.profileId });
this.modal.present();
}
logout() {
this.store.dispatch(new Actions.Logout())
}
}
<file_sep>/src/providers/models/search-history.ts
export class SearchHistory {
id: number;
keyword: string;
userId: number;
deleted: boolean;
createdAt: string;
updatedAt: string;
}<file_sep>/src/pages/start/effects/device.effects.ts
import { Actions, Effect } from '@ngrx/effects'
import * as DeviceActions from '../actions/device.actions'
import { Observable } from 'rxjs'
import { Action } from '@ngrx/store'
import { of } from 'rxjs/observable/of'
import { Injectable } from '@angular/core'
import { App } from 'ionic-angular'
import { DeviceService } from '../../../providers/services/device.service'
import * as AuthActions from '../actions/auth.actions'
@Injectable()
export class DeviceEffects {
constructor(private actions$: Actions,
private deviceService: DeviceService,
public app: App) {
}
//Login effect
@Effect()
GetDeviceInfo$: Observable<Action> = this.actions$
.ofType(DeviceActions.GET_DEVICE_INFO)
.exhaustMap(() => this.deviceService.getInfo())
.map((res) => new DeviceActions.GetDeviceInfoSuccess(res))
.catch(error => of(new DeviceActions.GetDeviceInfoFailure(error)))
}<file_sep>/src/providers/providers.module.ts
import { NgModule } from '@angular/core'
import { ServicesModule } from './services/_services.module'
import { InterceptorsModule } from './interceptors/_interceptors.module'
@NgModule({
declarations: [],
exports: [],
imports: [
ServicesModule,
InterceptorsModule,
],
providers: [],
})
export class ProvidersModule {
}<file_sep>/src/pages/user/reducers/user.reducers.ts
import * as UserActions from '../actions/user.actions'
import { Map, Record } from 'immutable'
import { IUser } from '../../../providers/models/user'
export interface UserState extends Map<string, any> {
data: IUser | null
payload: any
error: any
pending: boolean
}
export const UserStateRecord = Record({
data: null,
payload: null,
error: null,
pending: false,
})
export const initialUserState: UserState = new UserStateRecord() as UserState
export function userReducer(state = initialUserState, action: UserActions.Actions): UserState {
switch (action.type) {
case UserActions.UPDATE_USER: {
return state.merge({ payload: action.payload, error: null, pending: true }) as UserState
}
case UserActions.UPDATE_USER_SUCCESS: {
return state.merge({ data: action.payload, pending: false }) as UserState
}
case UserActions.UPDATE_USER_FAILURE: {
return state.merge({ error: action.payload, pending: false }) as UserState
}
/**
* Get User Info
*/
case UserActions.GET_USER_INFO: {
return state.merge({ payload: action.payload, error: null, pending: true }) as UserState
}
case UserActions.GET_USER_INFO_SUCCESS: {
return state.merge({ data: action.payload, pending: false }) as UserState
}
case UserActions.GET_USER_INFO_FAILURE: {
return state.merge({ error: action.payload, pending: false }) as UserState
}
/**
* Get User Id
*/
case UserActions.GET_USER_ID: {
return state.merge({ error: null, pending: true }) as UserState
}
case UserActions.GET_USER_ID_SUCCESS: {
return state.merge({ data: action.payload, pending: false }) as UserState
}
case UserActions.GET_USER_ID_FAILURE: {
return state.merge({ error: action.payload, pending: false }) as UserState
}
default: {
return state
}
}
}<file_sep>/src/pages/camera/reducers/post.state.ts
import { createSelector } from '@ngrx/store';
import { PostState } from './post.reducer';
import { AppState } from '../../../app/interface';
export const selectPost = (state: AppState): PostState => state.post
export const getPosts = createSelector(
selectPost,
(state: PostState) => state.posts,
)
export const getPayload = createSelector(
selectPost,
(state: PostState) => state.payload,
)
export const getError = createSelector(
selectPost,
(state: PostState) => state.error,
)
export const getPending = createSelector(
selectPost,
(state: PostState) => state.pending,
)<file_sep>/src/providers/models/bookmark.ts
export class Bookmark {
postId: number;
collectionId: number;
createdAt: string;
updatedAt: string;
}<file_sep>/src/environments/_production.env.ts
export const PROD_ENV = {}<file_sep>/src/app/interface.ts
import { AuthState } from '../pages/start/reducers/auth.reducer'
import { DeviceState } from '../pages/start/reducers/device.reducer'
import { PostState } from '../pages/camera/reducers/post.reducer'
import { UserState } from '../pages/user/reducers/user.reducers'
export interface AppState {
auth: AuthState,
device: DeviceState,
post: PostState,
user: UserState
}<file_sep>/src/pages/start/components/login/login.ts
import { AfterViewInit, Component, OnInit } from '@angular/core'
import { AlertController, App, Loading, LoadingController, NavController } from 'ionic-angular'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { Store } from '@ngrx/store'
import * as AuthActions from '../../actions/auth.actions'
import { AppState } from '../../../../app/interface'
import * as fromAuth from '../../reducers/auth.state'
import { EmailValidator } from '../../../../providers/validators/email.validator'
import { SignupPage } from '../signup/signup'
import { ForgotPasswordPage } from '../forgot-password/forgot-password'
//model
import { IUser } from '../../../../providers/models/user'
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage implements OnInit, AfterViewInit {
loginForm: FormGroup
loader: Loading
user: IUser
signUpPage = SignupPage
forgotPasswordPage = ForgotPasswordPage
constructor(public navCtrl: NavController,
private fb: FormBuilder,
private store: Store<AppState>,
public loadingCtrl: LoadingController,
public alertCtrl: AlertController,
public app: App) {
this.presentLoading()
this.getErrorFromLogin()
}
ngOnInit() {
this.loginForm = this.fb.group({
email: ['<EMAIL>', [Validators.required, EmailValidator]],
password: ['123', Validators.required],
})
}
ngAfterViewInit() {
this.loader.dismiss()
}
ionViewCanLeave() {
this.loader.dismiss()
}
onSubmit() {
if (this.loginForm.invalid)
return false
const formModel = this.loginForm.value
this.presentLoading()
this.store.dispatch(new AuthActions.Login({
...formModel,
}))
}
getErrorFromLogin() {
this.store.select(fromAuth.getError).subscribe(
error => {
if (error) {
this.loader.dismiss()
this.presentAlert(error.get('message'))
}
},
)
}
presentAlert(message) {
const alert = this.alertCtrl.create({
title: 'Error',
subTitle: message,
buttons: ['Dismiss'],
})
alert.present()
}
//Loading control
presentLoading() {
this.loader = this.loadingCtrl.create({
content: 'Please wait...',
})
this.loader.present()
}
}
<file_sep>/src/providers/models/follower.ts
export class Follower {
id: number;
userId: number;
followerId: number;
createdAt: string;
updatedAt: string;
}<file_sep>/src/pages/home/components/latest/latest.ts
import { AfterViewInit, Component, OnInit } from '@angular/core'
import { AlertController, LoadingController, NavController } from 'ionic-angular'
import { PostService } from '../../../../providers/services/post-mock.service'
import { IPost } from '../../../../providers/models/post'
import { Observable } from 'rxjs/Observable'
import { AppState } from '../../../../app/interface'
import { Store } from '@ngrx/store'
import * as PostActions from '../../../camera/actions/post.actions'
import * as fromPosts from '../../../camera/reducers/post.state'
@Component({
selector: 'page-latest',
templateUrl: 'latest.html',
})
export class LatestPage implements OnInit {
latestPosts: Array<IPost>
loader: any
posts: IPost[]
constructor(public navCtrl: NavController,
public postService: PostService,
public alertCtrl: AlertController,
public loadingCtrl: LoadingController,
private store: Store<AppState>,) {
this.presentLoading()
this.getError()
this.getPosts()
}
ngOnInit() {
this.store.dispatch(new PostActions.FindPosts({}))
}
getPosts() {
this.store.select(fromPosts.getPosts).subscribe(
payload => {
if (payload) {
this.posts = (payload as any).toJSON()
console.log('%c payload', 'background: red; color: white', this.posts)
this.loader.dismiss()
}
},
)
}
getError() {
this.store.select(fromPosts.getError).subscribe(
error => {
if (error) {
this.loader.dismiss()
this.presentAlert(`Something went wrong. Please try again`)
}
},
)
}
presentAlert(message) {
const alert = this.alertCtrl.create({
title: 'Error',
subTitle: message,
buttons: ['Dismiss'],
})
alert.present()
}
presentLoading() {
this.loader = this.loadingCtrl.create({
content: 'Please wait...',
})
this.loader.present()
}
}
<file_sep>/src/providers/models/following.ts
export class Following{
id:number;
userId:number;
followingId:number;
createdAt:string;
updatedAt:string;
}<file_sep>/src/providers/models/story.ts
export class Story {
id: number;
thumbnail: string;
userId: number;
deleted: boolean;
createdAt: string;
updatedAt: string;
}<file_sep>/src/providers/interceptors/jwt.interceptor.ts
import {
HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest,
HttpResponse,
} from '@angular/common/http'
import { Observable } from 'rxjs'
import { AuthService } from '../services/auth.service'
import { Injectable, Injector } from '@angular/core'
import { Subject } from 'rxjs/Subject'
import { env } from '../../environments/env'
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
private authService: AuthService
private started: number
private _req: HttpRequest<any>
constructor(private injector: Injector) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.authService = this.injector.get(AuthService)
return this.transformRequest(req).flatMap((val: HttpRequest<any>) => {
return next.handle(val)
.do(this.doSuccess.bind(this), this.doError.bind(this))
.catch(event => Observable.throw(event.error))
})
}
private transformRequest(req: HttpRequest<any>) {
return new Observable((observer) => {
this.authService.getToken().then(token => {
this.started = Date.now()
this._req = req.clone({
url: env.END_POINT + req.url,
})
if (token) {
this._req = req.clone({
setHeaders: {
'X-ACCESS-TOKEN': token,
},
})
}
observer.next(this._req)
observer.complete()
})
})
}
private doSuccess(event: any) {
if (event instanceof HttpResponse) {
const elapsed = Date.now() - this.started
console.log(`%c ${this._req.method} for ${this._req.urlWithParams} took ${elapsed} ms.`, 'background: lime; color: white')
}
}
private doError(event: any) {
if (event instanceof HttpErrorResponse) {
const elapsed = Date.now() - this.started
console.log(`%c ${this._req.method} for ${this._req.urlWithParams} took ${elapsed} ms. with error`, 'background: tomato; color: white', event.error)
}
}
}<file_sep>/src/providers/interceptors/timeout.interceptor.ts
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'
import { Observable } from 'rxjs/Observable'
import { Inject, InjectionToken } from '@angular/core'
export const DEFAULT_TIMEOUT = new InjectionToken<number>('defaultTimeout')
export const defaultTimeout = 6000
export class TimeoutInterceptor implements HttpInterceptor {
constructor(@Inject(DEFAULT_TIMEOUT) protected defaultTimeout) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const timeout = Number(req.headers.get('timeout')) || this.defaultTimeout
return next.handle(req).timeoutWith(timeout, Observable.throw('Request timed out'))
}
}<file_sep>/src/pages/camera/camera.ts
import { Component, OnInit } from '@angular/core'
import { NavController } from 'ionic-angular'
import { PhotoLibrary } from '@ionic-native/photo-library'
@Component({
selector: 'page-camera',
templateUrl: 'camera.html',
})
export class CameraPage implements OnInit {
cam_child: string = 'camera'
photos: any[]
constructor(public navCtrl: NavController,
private photoLib: PhotoLibrary,) {
}
ngOnInit() {
this.getPhotosFromGallery()
}
getPhotosFromGallery() {
this.photoLib.requestAuthorization()
.then(() => {
this.photoLib.getLibrary()
.subscribe(
library => {
this.photos = library
console.log(this.photos)
},
err => {
console.log('could not get photos')
},
() => {
console.log('done getting photos')
},
)
})
.catch(err => console.log('permissions weren\'t granted'))
}
}
<file_sep>/src/providers/models/role.ts
export class Role {
id: number;
label: string;
createdAt: string;
updatedAt: string;
}<file_sep>/src/pages/home/components/around/around.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'
import { NavController, NavParams } from 'ionic-angular'
import {
GoogleMaps,
GoogleMap,
GoogleMapsEvent,
GoogleMapOptions,
CameraPosition,
MarkerOptions,
Marker,
} from '@ionic-native/google-maps'
@Component({
selector: 'page-around',
templateUrl: 'around.html',
})
export class AroundPage implements OnInit {
map: GoogleMap
constructor(public navCtrl: NavController,
public navParams: NavParams,
private googleMaps: GoogleMaps) {
}
ngOnInit() {
}
ngAfterViewInit() {
this.loadMap();
}
// displayMap() {
// const location = new google.maps.LatLng('17.3850044', '78.486671');
// const options = {
// center: location,
// zoom: 10,
// };
// const map = new google.maps.Map(this.mapRef.nativeElement, options);
// this.addMarker(location, map);
// }
// addMarker(position, map) {
// return new google.maps.Marker({
// position,
// map
// })
// }
loadMap() {
let mapOptions: GoogleMapOptions = {
camera: {
target: {
lat: 43.0741904,
lng: -89.3809802
},
zoom: 18,
tilt: 30
}
};
this.map = GoogleMaps.create('map', mapOptions);
// Wait the MAP_READY before using any methods.
this.map.one(GoogleMapsEvent.MAP_READY)
.then(() => {
console.log('Map is ready!');
// Now you can use all methods safely.
this.map.addMarker({
title: 'Ionic',
icon: 'blue',
animation: 'DROP',
position: {
lat: 43.0741904,
lng: -89.3809802
}
})
.then(marker => {
marker.on(GoogleMapsEvent.MARKER_CLICK)
.subscribe(() => {
alert('clicked');
});
});
});
}
}
<file_sep>/src/pages/start/start.module.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { IonicModule } from 'ionic-angular'
import { SignupPage } from './components/signup/signup'
import { LoginPage } from './components/login/login'
import { EffectsModule } from '@ngrx/effects'
import { AuthEffects } from './effects/auth.effects'
import { DeviceEffects } from './effects/device.effects'
import { ForgotPasswordPage } from './components/forgot-password/forgot-password'
@NgModule({
declarations: [
SignupPage,
LoginPage,
ForgotPasswordPage
],
imports: [
CommonModule,
IonicModule,
EffectsModule.forFeature([
AuthEffects,
DeviceEffects
]),
],
entryComponents: [
SignupPage,
LoginPage,
ForgotPasswordPage
],
})
export class StartPageModule {
}
<file_sep>/src/providers/models/like-type.ts
export class LikeType{
id:number;
label:string;
createdAt:string;
updatedAt:string;
}<file_sep>/src/environments/env.ts
import {merge, mergeAll} from 'ramda'
import { DEFAULT_ENV } from './_default.env'
import { DEV_ENV } from './_development.env'
import { PROD_ENV } from './_production.env'
const MER_DEFAULT_ENV = mergeAll([
DEFAULT_ENV
])
export const development = merge(MER_DEFAULT_ENV, DEV_ENV)
export const production = merge(MER_DEFAULT_ENV, PROD_ENV)
export const env = DEFAULT_ENV.APP_ENV === 'development' ? development : production as any<file_sep>/src/app/app.reducers.ts
import { authReducer } from '../pages/start/reducers/auth.reducer'
import { ActionReducer, ActionReducerMap, MetaReducer } from '@ngrx/store'
import { AppState } from './interface'
import { storeFreeze } from 'ngrx-store-freeze'
import { env } from '../environments/env'
import { storeLogger } from 'ngrx-store-logger'
import { deviceReducer } from '../pages/start/reducers/device.reducer'
import { postReducer } from '../pages/camera/reducers/post.reducer'
import { userReducer } from '../pages/user/reducers/user.reducers'
export const reducers: ActionReducerMap<AppState> = {
auth: authReducer,
post: postReducer,
device: deviceReducer,
user: userReducer,
}
export function logger(reducer: ActionReducer<AppState>): any {
// default, no options
return storeLogger()(reducer);
}
export const metaReducers: MetaReducer<AppState>[] = env.APP_ENV === 'development'
? [logger, storeFreeze]
: [];<file_sep>/src/pages/start/effects/auth.effects.ts
import { Actions, Effect } from '@ngrx/effects'
import { AuthService } from '../../../providers/services/auth.service'
import * as AuthActions from '../actions/auth.actions'
import { Observable } from 'rxjs/Observable'
import { Action } from '@ngrx/store'
import { of } from 'rxjs/observable/of'
import { Injectable } from '@angular/core'
import { App, NavController } from 'ionic-angular'
import { TabsPage } from '../../tabs/tabs'
import { LoginPage } from '../components/login/login'
@Injectable()
export class AuthEffects {
constructor(private actions$: Actions,
private authService: AuthService,
public app: App) {
}
//Login effect
@Effect()
Login$: Observable<Action> = this.actions$
.ofType(AuthActions.LOGIN)
.map((action: AuthActions.Login) => action.payload)
.exhaustMap(auth => this.authService.login(auth))
.flatMap((res: any) => Observable.forkJoin([
Promise.resolve(res),
this.authService.setToken(res.token),
this.authService.setUser(res.user),
]))
.map(res => new AuthActions.LoginSuccess(res[0]))
.catch(error => of(new AuthActions.LoginFailure(error)))
@Effect({ dispatch: false })
LoginSuccess$: Observable<Action> = this.actions$
.ofType(AuthActions.LOGIN_SUCCESS)
.do(() => this.app.getRootNav().setRoot(TabsPage))
//Logout effect
@Effect()
Logout$: Observable<Action> = this.actions$
.ofType(AuthActions.LOGOUT)
.exhaustMap(val => this.authService.logout())
.flatMap(val => this.authService.clearStorage())
.map((val) => new AuthActions.LogoutSuccess())
.catch(error => of(new AuthActions.LogoutFailure(error)))
@Effect({ dispatch: false })
LogoutSuccess$: Observable<Action> = this.actions$
.ofType(AuthActions.LOGOUT_SUCCESS)
.do(() => this.app.getRootNav().setRoot(LoginPage))
//Sign Up effect
@Effect()
signUp$: Observable<Action> = this.actions$
.ofType(AuthActions.SIGNUP)
.map((action: AuthActions.SignUp) => action.payload)
.exhaustMap(auth => this.authService.signup(auth))
.flatMap((res: any) => Observable.forkJoin([
Promise.resolve(res),
this.authService.setToken(res.token),
this.authService.setUser(res.user),
]))
.map(res => new AuthActions.SignUpSuccess(res[0]))
.catch(error => of(new AuthActions.SignUpFailure(error)))
@Effect({ dispatch: false })
SignUpSuccess$: Observable<Action> = this.actions$
.ofType(AuthActions.SIGNUP_SUCCESS)
.do(() => this.app.getActiveNav().setRoot(TabsPage))
//Forgot Password Effect
@Effect()
ForgotPassword$: Observable<Action> = this.actions$
.ofType(AuthActions.FORGOT_PASSWORD)
.map((action: AuthActions.ForgotPassword) => action.payload)
.exhaustMap((auth) => this.authService.forgotPassword(auth))
.map((res) => new AuthActions.ForgotPasswordSuccess(res))
.catch(error => of(new AuthActions.ForgotPasswordSuccess(error)))
}<file_sep>/src/pages/user/actions/user.actions.ts
import { Action } from '@ngrx/store'
import { IUser } from '../../../providers/models/user'
export const UPDATE_USER = '[Profile] Update User'
export const UPDATE_USER_SUCCESS = '[Profile] Update User Success'
export const UPDATE_USER_FAILURE = '[Profile] Update User Failure'
export const GET_USER_INFO = '[Profile] Get User Info'
export const GET_USER_INFO_SUCCESS = '[Profile] Get User Info Success'
export const GET_USER_INFO_FAILURE = '[Profile] Get User Info Failure'
export const GET_USER_ID = '[Profile] Get User Id'
export const GET_USER_ID_SUCCESS = '[Profile] Get User Id Success'
export const GET_USER_ID_FAILURE = '[Profile] Get User Id Failure'
/**
* Update User
*/
export class UpdateUser implements Action {
readonly type = UPDATE_USER
constructor(public payload: any) {
}
}
export class UpdateUserSuccess implements Action {
readonly type = UPDATE_USER_SUCCESS
constructor(public payload: IUser) {
}
}
export class UpdateUserFailure implements Action {
readonly type = UPDATE_USER_FAILURE
constructor(public payload: any) {
}
}
/**
* Get User Info
*/
export class GetUserInfo implements Action {
readonly type = GET_USER_INFO
constructor(public payload: string) {
}
}
export class GetUserInfoSuccess implements Action {
readonly type = GET_USER_INFO_SUCCESS
constructor(public payload: IUser) {
}
}
export class GetUserInfoFailure implements Action {
readonly type = GET_USER_INFO_FAILURE
constructor(public payload: any) {
}
}
/**
* Get User Id
*/
export class GetUserId implements Action {
readonly type = GET_USER_ID
}
export class GetUserIdSuccess implements Action {
readonly type = GET_USER_ID_SUCCESS
constructor(public payload: IUser) {
}
}
export class GetUserIdFailure implements Action {
readonly type = GET_USER_ID_FAILURE
constructor(public payload: any) {
}
}
export type Actions =
| UpdateUser
| UpdateUserSuccess
| UpdateUserFailure
| GetUserInfo
| GetUserInfoSuccess
| GetUserInfoFailure
| GetUserId
| GetUserIdSuccess
| GetUserIdFailure<file_sep>/src/environments/_development.env.ts
export const DEV_ENV = {}<file_sep>/src/pages/start/reducers/auth.state.ts
import { createSelector } from '@ngrx/store'
import { AuthState } from './auth.reducer'
import { AppState } from '../../../app/interface'
export const selectAuth = (state: AppState): AuthState => state.auth
export const getToken = createSelector(
selectAuth,
(state: AuthState) => state.token,
)
export const getUser = createSelector(
selectAuth,
(state: AuthState) => state.user,
)
export const getError = createSelector(
selectAuth,
(state: AuthState) => state.error,
)
export const getPayload = createSelector(
selectAuth,
(state: AuthState) => state.payload,
)
export const getPending = createSelector(
selectAuth,
(state: AuthState) => state.pending,
)
<file_sep>/src/pages/home/components/stories/stories.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { HomeTabsService } from '../hometabs.service';
@Component({
selector: 'page-stories',
templateUrl: 'stories.html'
})
export class StoriesPage {
latestList = [];
constructor(public navCtrl: NavController,
private homeTabSV: HomeTabsService, ) {
homeTabSV.getListItem();
this.latestList = homeTabSV.listitem;
}
}
<file_sep>/src/pages/camera/components/write-post/write-post.ts
import { Component, OnInit } from '@angular/core'
import { AlertController, Loading, LoadingController, NavController, NavParams, ViewController } from 'ionic-angular'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { Store } from '@ngrx/store'
import * as PostActions from '../../actions/post.actions'
import { AppState } from '../../../../app/interface'
import * as fromPost from '../../reducers/post.state'
@Component({
selector: 'page-write-post',
templateUrl: 'write-post.html',
})
export class WritePostPage implements OnInit {
selectedImage: any
postForm: FormGroup
loader: Loading
constructor(public navCtrl: NavController,
public navParams: NavParams,
public viewCtrl: ViewController,
private fb: FormBuilder,
private store: Store<AppState>,
private alertCtrl: AlertController,
private loadingCtrl: LoadingController) {
// this.getPayload()
this.selectedImage = this.navParams.get('selectedImage')
}
ngOnInit() {
this.postForm = this.fb.group({
description: ['<NAME>', Validators.required],
location: ['123 đương 50', Validators.required],
})
}
onSubmit() {
if (this.postForm.invalid)
return false
this.presentLoading()
const formModel = this.postForm.value
this.store.dispatch(new PostActions.CreatePost({
file: this.selectedImage,
...formModel
}))
}
onBack() {
this.viewCtrl.dismiss()
}
ionViewCanLeave() {
this.loader.dismiss()
}
dismissLoaderPost(){
this.store.select(fromPost.getPending).subscribe(
pending => {
if(!pending){
this.loader.dismiss();
}
}
)
}
getPayload() {
this.store.select(fromPost.getPayload).subscribe(
payload => {
console.log('%c payload.size', 'background: red; color: white', payload.size)
if (payload.length > 0) {
this.loader.dismiss()
this.presentAlert(`Create new post successfully.`)
}
},
)
}
presentAlert(message) {
const alert = this.alertCtrl.create({
title: 'Success',
subTitle: message,
buttons: ['Dismiss'],
})
alert.present()
}
presentLoading() {
this.loader = this.loadingCtrl.create({
content: 'Please wait...',
})
this.loader.present()
}
}
<file_sep>/src/app/app.module.ts
import { ErrorHandler, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'
//Components
import { MyApp } from './app.component'
/*Plugin*/
import { Camera } from '@ionic-native/camera'
import { PhotoLibrary } from '@ionic-native/photo-library'
import { Geolocation } from '@ionic-native/geolocation'
import { UniqueDeviceID } from '@ionic-native/unique-device-id'
import { Device } from '@ionic-native/device'
import { NativeGeocoder, } from '@ionic-native/native-geocoder'
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer'
import { File } from '@ionic-native/file'
import { TabsPage } from '../pages/tabs/tabs'
import { StartPageModule } from '../pages/start/start.module'
//All tab
import { HomeModule } from '../pages/home/home.module'
import { UserModule } from '../pages/user/user.module'
import { ChatModule } from '../pages/chat/chat.module'
import { SearchModule } from '../pages/search/search.module'
import { NotificationModule } from '../pages/notification/notification.module'
import { CameraModule } from '../pages/camera/camera.module'
import { StatusBar } from '@ionic-native/status-bar'
import { SplashScreen } from '@ionic-native/splash-screen'
//Modules
import { EffectsModule } from '@ngrx/effects'
import { StoreModule } from '@ngrx/store'
import { ProvidersModule } from '../providers/providers.module'
//Reducer
// adding rx operators
import 'rxjs'
import { StoreDevtoolsModule } from '@ngrx/store-devtools'
import { metaReducers, reducers } from './app.reducers'
import { LoadingPageModule } from '../pages/loading/loading.module'
import { HttpClientModule } from '@angular/common/http'
import { IonicStorageModule } from '@ionic/storage'
import { GoogleMaps } from '@ionic-native/google-maps'
@NgModule({
declarations: [
MyApp,
TabsPage,
],
imports: [
BrowserModule,
HttpClientModule,
ProvidersModule,
HomeModule,
UserModule,
ChatModule,
SearchModule,
NotificationModule,
StartPageModule,
CameraModule,
LoadingPageModule,
IonicStorageModule.forRoot(),
StoreModule.forRoot(reducers, {metaReducers}),
StoreDevtoolsModule.instrument({
maxAge: 25 // Retains last 25 states
}),
EffectsModule.forRoot([]),
IonicModule.forRoot(MyApp),
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
TabsPage,
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
Camera,
PhotoLibrary,
Geolocation,
UniqueDeviceID,
Device,
NativeGeocoder,
GoogleMaps,
FileTransfer,
FileTransferObject,
File,
],
})
export class AppModule {
}
<file_sep>/src/pages/start/reducers/auth.reducer.ts
import * as AuthActions from '../actions/auth.actions'
import { Authenticate, IUser } from '../../../providers/models/user'
import { Map, Record } from 'immutable'
export interface AuthState extends Map<string, any> {
token: string
data: Authenticate | any
user: IUser | null
payload: any
error: any
pending: boolean
}
export const AuthStateRecord = Record({
token: '',
data: null,
user: Map({}),
payload: null,
error: null,
pending: false,
})
export const initialAuthState: AuthState = new AuthStateRecord() as AuthState
export function authReducer(state = initialAuthState, action: AuthActions.Actions): AuthState {
switch (action.type) {
/**
* Login
*/
case AuthActions.LOGIN: {
return state.merge({ data: action.payload, error: null, pending: true }) as AuthState
}
case AuthActions.LOGIN_SUCCESS: {
return state.merge({ ...action.payload, pending: false }) as AuthState
}
case AuthActions.LOGIN_FAILURE: {
return state.merge({ error: action.payload, pending: false }) as AuthState
}
case AuthActions.LOGOUT: {
return initialAuthState
}
/**
* Sign Up
*/
case AuthActions.SIGNUP: {
return state.merge({ data: action.payload, error: null, pending: true }) as AuthState
}
case AuthActions.SIGNUP_SUCCESS: {
return state.merge({ ...action.payload, pending: false }) as AuthState
}
case AuthActions.SIGNUP_FAILURE: {
return state.merge({ error: action.payload, pending: false }) as AuthState
}
/**
* Get Password
*/
case AuthActions.FORGOT_PASSWORD: {
return state.merge({ data: action.payload, error: null, pending: true }) as AuthState
}
case AuthActions.FORGOT_PASSWORD_SUCCESS: {
return state.merge({ payload: action.payload, pending: false }) as AuthState
}
case AuthActions.FORGOT_PASSWORD_FAILURE: {
return state.merge({ payload: null, error: action.payload, pending: false }) as AuthState
}
default: {
return state
}
}
}<file_sep>/src/providers/interceptors/_interceptors.module.ts
import { NgModule } from '@angular/core'
import { HTTP_INTERCEPTORS } from '@angular/common/http'
import { JwtInterceptor } from './jwt.interceptor'
import { DEFAULT_TIMEOUT, defaultTimeout, TimeoutInterceptor } from './timeout.interceptor'
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
},
],
})
export class InterceptorsModule {
}<file_sep>/src/providers/models/session.ts
export class Session {
id: number;
token: string;
userId: number;
coordination: string;
deviceToken: string;
location: string;
createdAt: string;
updatedAt: string;
}<file_sep>/src/providers/services/user-mock.ts
import { IUser } from '../models/user';
let users: any[] = [
{
id: 1,
username: '<NAME>',
email: '<EMAIL>',
password: '<PASSWORD>',
avatar:'assets/img/avatar1.png',
gender:false,
},
{
id: 2,
username: '<NAME>',
email: '<EMAIL>',
password: '<PASSWORD>',
avatar:'assets/img/miule.png',
gender:false,
}
]
export default users;<file_sep>/src/pages/start/components/signup/signup.ts
import { Component, OnInit } from '@angular/core'
import { App, Loading, LoadingController, NavController, NavParams, ViewController } from 'ionic-angular'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { Store } from '@ngrx/store'
import { EmailValidator } from '../../../../providers/validators/email.validator'
import * as AuthActions from '../../actions/auth.actions'
import { AppState } from '../../../../app/interface'
import { MatchPassword } from '../../../../providers/validators/password.validator'
@Component({
selector: 'page-signup',
templateUrl: 'signup.html',
})
export class SignupPage implements OnInit {
signUpForm: FormGroup
loader: Loading
constructor(public navCtrl: NavController,
public viewCtrl: ViewController,
private fb: FormBuilder,
private store: Store<AppState>,
public loadingCtrl: LoadingController,
public app: App) {
}
ngOnInit() {
this.signUpForm = this.fb.group({
username: ['harry_nguyen', Validators.required],
email: ['<EMAIL>', [Validators.required, EmailValidator]],
password: ['123', Validators.required],
confirmPassword: ['123', Validators.required],
}, {
validator: MatchPassword,
})
}
onSubmit() {
if (this.signUpForm.invalid) return false
this.presentLoading()
const formModel = this.signUpForm.value
this.store.dispatch(new AuthActions.SignUp(formModel))
}
presentLoading() {
this.loader = this.loadingCtrl.create({
content: 'Please wait...',
})
this.loader.present()
}
}
<file_sep>/src/pages/home/components/hometabs.service.ts
export class HomeTabsService{
public listitem = [];
getListItem(){
this.listitem.length = 6;
}
}<file_sep>/src/pages/home/components/comment-detail/comment-detail.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-comment-detail',
templateUrl: 'comment-detail.html'
})
export class CommentDetailPage {
public list = [];
constructor(public navCtrl: NavController) {
this.list.length = 10;
}
}
<file_sep>/src/pages/camera/camera.module.ts
import { ErrorHandler, NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'
import { CameraPage } from './camera'
import { CDVPhotoLibraryPipe } from '../../providers/pipes/cdvphotolibrary.pipe'
import { WritePostPage } from './components/write-post/write-post'
import { GalleryPage } from './components/gallery/gallery'
import { TakePhotoPage } from './components/take-photo/take-photo'
import { StatusBar } from '@ionic-native/status-bar'
import { SplashScreen } from '@ionic-native/splash-screen'
import { PostEffects } from './effects/post.effects'
import { EffectsModule } from '@ngrx/effects'
@NgModule({
declarations: [
CameraPage,
WritePostPage,
GalleryPage,
TakePhotoPage,
CDVPhotoLibraryPipe,
],
imports: [
CommonModule,
IonicModule,
EffectsModule.forFeature([
PostEffects
]),
],
bootstrap: [IonicApp],
entryComponents: [
CameraPage,
WritePostPage,
GalleryPage,
TakePhotoPage,
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
],
})
export class CameraModule {
}
<file_sep>/src/providers/models/user.ts
export interface Authenticate {
email: string
password: string
remember?: boolean
username?: string
condinates?: {
latitude: number;
longitude: number;
}
}
export interface IUser {
id: number;
username: string;
email: string;
password: string;
birthday?: Date;
gender: boolean;
bio?: string;
phoneNumber?: number;
avatar: string;
fullName?: string;
status?: string;
token?: string;
website?:string;
createdAt?: Date;
updatedAt?: Date;
}
<file_sep>/src/pages/start/actions/device.actions.ts
import { Action } from '@ngrx/store'
export const GET_DEVICE_INFO = '[Start] Get Device Info'
export const GET_DEVICE_INFO_SUCCESS = '[Start] Get Device Info Success'
export const GET_DEVICE_INFO_FAILURE = '[Start] Get Device Info Failure'
/**
* get device info
*/
export class GetDeviceInfo implements Action {
readonly type = GET_DEVICE_INFO
}
export class GetDeviceInfoSuccess implements Action {
readonly type = GET_DEVICE_INFO_SUCCESS
constructor(public payload: any) {
}
}
export class GetDeviceInfoFailure implements Action {
readonly type = GET_DEVICE_INFO_FAILURE
constructor(public payload: any) {
}
}
export type Actions =
| GetDeviceInfo
| GetDeviceInfoSuccess
| GetDeviceInfoFailure;<file_sep>/src/providers/services/_services.module.ts
import { NgModule } from '@angular/core'
import { AuthService } from './auth.service'
import { DeviceService } from './device.service'
import { PostService } from './post.service'
import { UserService } from './user.service'
@NgModule({
providers: [
AuthService,
DeviceService,
PostService,
UserService,
],
})
export class ServicesModule { }<file_sep>/src/pages/search/search.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { SearchPage } from './search';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@NgModule({
declarations: [
SearchPage,
],
imports: [
CommonModule,
IonicModule,
],
bootstrap: [IonicApp],
entryComponents: [
SearchPage,
],
providers: [
StatusBar,
SplashScreen,
{ provide: ErrorHandler, useClass: IonicErrorHandler }
]
})
export class SearchModule { }
<file_sep>/src/pages/camera/components/take-photo/take-photo.ts
import { Component } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
/*Camera plugin*/
import { Camera, CameraOptions } from '@ionic-native/camera';
/*Write Post page*/
import { WritePostPage } from '../write-post/write-post';
@Component({
selector: 'page-take-photo',
templateUrl: 'take-photo.html'
})
export class TakePhotoPage {
public photos: any;
public base64Image: string;
public modal: any;
constructor(
public navCtrl: NavController,
private camera: Camera,
public modalCtrl: ModalController,
) {
}
ngOnInit() {
this.photos = [];
}
takePhoto() {
const options: CameraOptions = {
quality: 50,
destinationType: this.camera.DestinationType.DATA_URL,
sourceType: this.camera.PictureSourceType.CAMERA,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
console.log(imageData)
// If it's base64:
// this.base64Image = 'data:image/jpeg;base64,' + imageData;
// this.modal = this.modalCtrl.create(WritePostPage, { selectedImage: this.base64Image });
// this.modal.present();
}, (err) => {
console.log("something happen", err);
});
}
}
<file_sep>/src/providers/services/device.service.ts
import { UniqueDeviceID } from '@ionic-native/unique-device-id'
import { NativeGeocoder } from '@ionic-native/native-geocoder'
import { Observable } from 'rxjs'
import { Injectable } from '@angular/core'
import { Geolocation } from '@ionic-native/geolocation'
import { Device } from '@ionic-native/device'
import { Platform } from 'ionic-angular'
@Injectable()
export class DeviceService {
constructor(
private geolocation: Geolocation,
private uniqueDeviceID: UniqueDeviceID,
private device: Device,
private nativeGeocoder: NativeGeocoder,
private platform: Platform
) {}
getInfo() {
return Observable.fromPromise(this.geolocation.getCurrentPosition())
.flatMap(({coords}) => Observable.forkJoin([
Promise.resolve(coords),
this.nativeGeocoder.reverseGeocode(coords.latitude, coords.longitude),
this.uniqueDeviceID.get(),
this.toJSONDevice()
]))
}
private toJSONDevice() {
return Observable.create(observer => {
const keys = Object.keys(this.device.constructor.prototype)
const obj: any = keys.reduce((acc, cur) => {
acc[cur] = this.device[cur]
return acc
}, {})
obj.constructor = undefined
obj.isVirtual = undefined
observer.next(obj)
observer.complete()
})
}
}<file_sep>/src/pages/chat/chat-messages/messages.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { MessagesDetailPage } from './messages-detail/messages-detail';
@Component({
selector: 'page-messages',
templateUrl: 'messages.html'
})
export class MessagesPage {
detailMess = MessagesDetailPage;
constructor(public navCtrl: NavController) {
}
}
<file_sep>/src/providers/services/auth.service.ts
import { Authenticate } from '../models/user'
import { Observable } from 'rxjs/Observable'
import { Injectable } from '@angular/core'
import { HttpClient, HttpParams } from '@angular/common/http'
import { Storage } from '@ionic/storage'
import { IUser } from '../models/user'
@Injectable()
export class AuthService {
constructor(private storage: Storage,
private readonly http: HttpClient) {
}
getToken() {
return this.storage.get('token')
}
setToken(token: string) {
return this.storage.set('token', token)
}
//from local SQLife database
getUser(): Promise<IUser> {
return new Promise(resolve => {
this.storage.get('user').then(user => resolve(JSON.parse(user)))
})
}
setUser(user: any) {
return this.storage.set('user', JSON.stringify(user))
}
clearStorage() {
return this.storage.clear()
}
login(body: Authenticate): Observable<any> {
return this.http.post('login', body)
}
logout(): Observable<any> {
return Observable.create(observer => {
observer.next(true)
observer.complete()
})
}
signup(body: Authenticate): Observable<any> {
return this.http.post('signup', body)
}
forgotPassword(body: { email: string }): Observable<any> {
//TODO: fix forgot-password to forgot-password when fixed on API
return this.http.post('forgot-password', body)
}
}<file_sep>/src/pages/user/effects/user.effects.ts
import { Actions, Effect } from '@ngrx/effects'
import { Observable } from 'rxjs'
import { Action } from '@ngrx/store'
import { of } from 'rxjs/observable/of'
import { Injectable } from '@angular/core'
import { App } from 'ionic-angular'
import * as UserActions from '../actions/user.actions'
import { AuthService } from '../../../providers/services/auth.service'
import { UserService } from '../../../providers/services/user.service'
@Injectable()
export class UserEffects {
constructor(
private action$: Actions,
private authService: AuthService,
private userService: UserService
) {
}
//Get User Id
@Effect()
GetUserId$: Observable<Action> = this.action$
.ofType(UserActions.GET_USER_ID)
.exhaustMap(() => this.authService.getUser())
.map((res) => new UserActions.GetUserIdSuccess(res))
.catch(error => of(new UserActions.GetUserIdFailure(error)))
//Get User Info
@Effect()
GetUserInfo$: Observable<Action> = this.action$
.ofType(UserActions.GET_USER_INFO)
.map((action: UserActions.GetUserInfo) => action.payload)
.exhaustMap(userId => this.userService.getUser(userId))
.map((res) => new UserActions.GetUserInfoSuccess(res))
.catch(error => of(new UserActions.GetUserInfoFailure(error)))
//Update User
@Effect()
UpdateUser$: Observable<Action> = this.action$
.ofType(UserActions.UPDATE_USER)
.map((action: UserActions.UpdateUser) => action.payload)
.exhaustMap(data => this.userService.updateUser(data, data.userId))
.map((res) => new UserActions.UpdateUserSuccess(res))
.catch(error => of(new UserActions.UpdateUserFailure(error)))
}<file_sep>/src/pages/camera/actions/post.actions.ts
import { Action } from '@ngrx/store'
import { IPost } from '../../../providers/models/post'
export const CREATE_POST = '[Post] Create Post'
export const CREATE_POST_SUCCESS = '[Post] Create Post Success'
export const CREATE_POST_FAILURE = '[Post] Create Post Failure'
export const FIND_POSTS = '[Post] Find Posts'
export const FIND_POSTS_SUCCESS = '[Post] Find Posts Success'
export const FIND_POSTS_FAILURE = '[Post] Find Posts Failure'
/**
* find all posts
*/
export class FindPosts implements Action {
readonly type = FIND_POSTS
constructor(public payload: any) {
}
}
export class FindPostsSuccess implements Action {
readonly type = FIND_POSTS_SUCCESS
constructor(public payload: IPost[]) {
}
}
export class FindPostsFailure implements Action {
readonly type = FIND_POSTS_FAILURE
constructor(public payload: any) {
}
}
/**
* create post
*/
export class CreatePost implements Action {
readonly type = CREATE_POST
constructor(public payload: IPost ) {
}
}
export class CreatePostSuccess implements Action {
readonly type = CREATE_POST_SUCCESS
constructor(public payload: IPost) {
}
}
export class CreatePostFailure implements Action {
readonly type = CREATE_POST_FAILURE
constructor(public payload: any) {
}
}
export type Actions =
| FindPosts
| FindPostsSuccess
| FindPostsFailure
| CreatePost
| CreatePostSuccess
| CreatePostFailure<file_sep>/src/providers/models/user-notification.ts
export class UserNotification {
userId: number;
notificationId: number;
} | 67d39cbf0182a41065d60bc4c5f332140a96615e | [
"TypeScript"
] | 81 | TypeScript | pikeman1992/foodrium | 17de40072bf8a90113eca9645433e8523e01a82d | 946ff9f410c0b7056f279529592dfaece3a99128 |
refs/heads/master | <file_sep>package be.woubuc.conqueror.screens;
import be.woubuc.conqueror.Clock;
import be.woubuc.conqueror.factions.Faction;
import be.woubuc.conqueror.Game;
import be.woubuc.conqueror.map.Tile;
import be.woubuc.conqueror.util.ColourUtils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import java.util.HashMap;
import java.util.Map;
import static be.woubuc.conqueror.Globals.*;
public final class GameScreen implements Screen {
private static final String[] textureIds = {
"movement_explore",
"movement_fortify",
"movement_regroup",
"movement_retreat",
"strategy_avoid",
"strategy_charge",
"strategy_defend",
"strategy_provoke",
"training_bows",
"training_cannons",
"training_militia",
"training_swords"
};
private Game game;
private Batch batch;
private BitmapFont smallFont;
private BitmapFont largeFont;
private Map<String, Texture> icons = new HashMap<>();
private final Clock clock = new Clock();
@Override
public void show() {
System.out.println("Showing gameScreen");
game = Game.get();
batch = game.batch;
largeFont = game.assets.get("font-large.fnt");
smallFont = game.assets.get("font-small.fnt");
for (String id : textureIds) {
icons.put(id, game.assets.get(id + ".png"));
}
}
@Override
public void render(float delta) {
if (clock.tick(Gdx.graphics.getDeltaTime())) return;
if (game.player.getScore() == MAP_SIZE * MAP_SIZE) {
game.setScreen(game.victoryScreen);
return;
}
if (game.player.isEliminated()) {
game.setScreen(game.defeatScreen);
return;
}
Gdx.gl.glClearColor(COLOUR_BACKGROUND.r, COLOUR_BACKGROUND.g, COLOUR_BACKGROUND.b, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
// Draw the map tiles
for (Tile tile : game.map.tiles) {
if (tile.getOwner() == null) continue;
batch.draw(ColourUtils.getTexture(tile.getColour(0.15f)), tile.x * TILE_SIZE, tile.y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
if (tile.wasAttacked()) batch.draw(game.assets.get("icon_fight.png", Texture.class), tile.x * TILE_SIZE, tile.y * TILE_SIZE);
if (tile.isFrontline()) {
TextureRegion colour = ColourUtils.getTexture(tile.getColour(0.4f));
Tile left = tile.getRelative(-1, 0);
if (left != null && left.getOwner() != tile.getOwner()) batch.draw(colour, tile.x * TILE_SIZE, tile.y * TILE_SIZE, 1, TILE_SIZE);
Tile right = tile.getRelative(1, 0);
if (right != null && right.getOwner() != tile.getOwner()) batch.draw(colour, (tile.x + 1) * TILE_SIZE - 1, tile.y * TILE_SIZE, 1, TILE_SIZE);
Tile top = tile.getRelative(0, 1);
if (top != null && top.getOwner() != tile.getOwner()) batch.draw(colour, tile.x * TILE_SIZE, (tile.y + 1) * TILE_SIZE - 1, TILE_SIZE, 1);
Tile bottom = tile.getRelative(0, -1);
if (bottom != null && bottom.getOwner() != tile.getOwner()) batch.draw(colour, tile.x * TILE_SIZE, tile.y * TILE_SIZE, TILE_SIZE, 1);
}
//smallFont.draw(batch, tile.getAttacked() + "," + tile.getDefense() + "\n" + tile.getUnits(), tile.x * TILE_SIZE + 2, tile.y * TILE_SIZE + 18);
}
// Draw the info
int mapSizePx = MAP_SIZE * TILE_SIZE;
batch.draw(ColourUtils.getTexture(COLOUR_PANEL), mapSizePx, 0, 200, mapSizePx);
batch.draw(ColourUtils.getTexture(COLOUR_PANEL_ACTIVE), mapSizePx, 0, 200, 8);
batch.draw(ColourUtils.getTexture(Color.WHITE), mapSizePx, 0, 200 - (clock.getProgress() * 200), 8);
float maxScore = (float) (MAP_SIZE * MAP_SIZE);
float maxFactionAtk = 0;
float maxFactionDef = 0;
for (Faction faction : game.factions) {
float atk = faction.getAttack();
if (atk > maxFactionAtk) maxFactionAtk = atk;
float def = faction.getDefense();
if (def > maxFactionDef) maxFactionDef = def;
}
for (Faction faction : game.factions) {
largeFont.draw(batch, "Territory", mapSizePx + 20, mapSizePx - 15);
int i = game.factions.indexOf(faction) + 1;
float score = (float) faction.getScore() / maxScore * 160;
batch.draw(ColourUtils.getTexture(COLOUR_PANEL_ACTIVE), mapSizePx + 20, mapSizePx - 20 - (40 * i), 160, 20);
batch.draw(ColourUtils.getTexture(faction.colour), mapSizePx + 20, mapSizePx - 20 - (40 * i), score, 20);
smallFont.draw(batch, faction.name, mapSizePx + 20, mapSizePx - 20 - (40 * i) + 26);
smallFont.draw(batch, Integer.toString(faction.getScore()), mapSizePx + 25, mapSizePx - 20 - (40 * i) + 11);
largeFont.draw(batch, "Attack", mapSizePx + 20, mapSizePx - 175);
largeFont.draw(batch, "Defense", mapSizePx + 110, mapSizePx - 175);
float attack = faction.getAttack() / maxFactionAtk * 70;
float defense = faction.getDefense() / maxFactionDef * 70;
batch.draw(ColourUtils.getTexture(COLOUR_PANEL_ACTIVE), mapSizePx + 20, mapSizePx - 180 - (40 * i), 70, 20);
batch.draw(ColourUtils.getTexture(COLOUR_PANEL_ACTIVE), mapSizePx + 110, mapSizePx - 180 - (40 * i), 70, 20);
batch.draw(ColourUtils.getTexture(faction.colour), mapSizePx + 20, mapSizePx - 180 - (40 * i), attack, 20);
batch.draw(ColourUtils.getTexture(faction.colour), mapSizePx + 110, mapSizePx - 180 - (40 * i), defense, 20);
smallFont.draw(batch, faction.name, mapSizePx + 20, mapSizePx - 180 - (40 * i) + 26);
smallFont.draw(batch, Integer.toString(Math.round(faction.getAttack())), mapSizePx + 25, mapSizePx - 180 - (40 * i) + 11);
smallFont.draw(batch, Integer.toString(Math.round(faction.getDefense())), mapSizePx + 115, mapSizePx - 180 - (40 * i) + 11);
}
smallFont.draw(batch, "Movement", mapSizePx + 64, mapSizePx - 375);
switch (game.player.movement) {
case EXPLORE:
batch.draw(icons.get("movement_explore"), mapSizePx + 20, mapSizePx - 400);
largeFont.draw(batch, "Explore", mapSizePx + 64, mapSizePx - 385);
break;
case FORTIFY:
batch.draw(icons.get("movement_fortify"), mapSizePx + 20, mapSizePx - 400);
largeFont.draw(batch, "Fortify", mapSizePx + 64, mapSizePx - 385);
break;
case RETREAT:
batch.draw(icons.get("movement_retreat"), mapSizePx + 20, mapSizePx - 400);
largeFont.draw(batch, "Retreat", mapSizePx + 64, mapSizePx - 385);
break;
case REGROUP:
batch.draw(icons.get("movement_regroup"), mapSizePx + 20, mapSizePx - 400);
largeFont.draw(batch, "Regroup", mapSizePx + 64, mapSizePx - 385);
break;
}
smallFont.draw(batch, "Strategy", mapSizePx + 64, mapSizePx - 425);
switch (game.player.strategy) {
case CHARGE:
batch.draw(icons.get("strategy_charge"), mapSizePx + 20, mapSizePx - 450);
largeFont.draw(batch, "Charge", mapSizePx + 64, mapSizePx - 435);
break;
case DEFEND:
batch.draw(icons.get("strategy_defend"), mapSizePx + 20, mapSizePx - 450);
largeFont.draw(batch, "Defend", mapSizePx + 64, mapSizePx - 435);
break;
case AVOID:
batch.draw(icons.get("strategy_avoid"), mapSizePx + 20, mapSizePx - 450);
largeFont.draw(batch, "Avoid", mapSizePx + 64, mapSizePx - 435);
break;
case PROVOKE:
batch.draw(icons.get("strategy_provoke"), mapSizePx + 20, mapSizePx - 450);
largeFont.draw(batch, "Provoke", mapSizePx + 64, mapSizePx - 435);
break;
}
smallFont.draw(batch, "Recruitment", mapSizePx + 64, mapSizePx - 475);
switch (game.player.training) {
case SWORDS:
batch.draw(icons.get("training_swords"), mapSizePx + 20, mapSizePx - 500);
largeFont.draw(batch, "Swordsmen", mapSizePx + 64, mapSizePx - 485);
break;
case BOWS:
batch.draw(icons.get("training_bows"), mapSizePx + 20, mapSizePx - 500);
largeFont.draw(batch, "Bowmen", mapSizePx + 64, mapSizePx - 485);
break;
case CANNONS:
batch.draw(icons.get("training_cannons"), mapSizePx + 20, mapSizePx - 500);
largeFont.draw(batch, "Cannons", mapSizePx + 64, mapSizePx - 485);
break;
case MILITIA:
batch.draw(icons.get("training_militia"), mapSizePx + 20, mapSizePx - 500);
largeFont.draw(batch, "Militia", mapSizePx + 64, mapSizePx - 485);
break;
}
batch.end();
}
@Override public void hide() {
System.out.println("Hiding gameScreen");
game = null;
batch = null;
largeFont = null;
smallFont = null;
}
@Override public void pause() { }
@Override public void resume() { }
@Override public void resize(int width, int height) { }
@Override public void dispose() { }
}
<file_sep>package be.woubuc.conqueror.factions;
public enum UnitActions {
FREE,
DEFENDING,
COMBAT
}
<file_sep>package be.woubuc.conqueror.factions;
public enum UnitTypes {
SWORDSMEN,
BOWMEN,
CANNONS,
MILITIA
}
<file_sep>package be.woubuc.conqueror.focus;
public enum Movement {
EXPLORE,
FORTIFY,
RETREAT,
REGROUP
}
<file_sep>package be.woubuc.conqueror.factions;
import be.woubuc.conqueror.map.Tile;
import com.badlogic.gdx.utils.Pool;
import com.badlogic.gdx.utils.Pools;
import static be.woubuc.conqueror.Globals.*;
public final class Unit implements Pool.Poolable {
// Pool unit instances
private static Pool<Unit> pool = Pools.get(Unit.class);
/**
* Gets a new unit instance from the pool
* @param tile Tile where the unit starts
* @param type The unit type
* @param size The initial size of the unit
*/
public static Unit get(Tile tile, UnitTypes type, int size) {
Unit unit = pool.obtain();
unit.tile = tile;
unit.type = type;
unit.size = Math.max(UNIT_SIZE_MAX, size);
unit.action = UnitActions.FREE;
return unit;
}
private int size;
private Tile tile;
private UnitTypes type;
private UnitActions action;
/**
* Gets the attack value of this unit
* @return The ATK
*/
public float getAtk() {
switch (type) {
case MILITIA: return size * UNIT_ATK_MILITIA;
case SWORDSMEN: return size * UNIT_ATK_SWORDS;
case BOWMEN: return size * UNIT_ATK_BOWS;
case CANNONS: return size * UNIT_ATK_CANNONS;
default: throw new RuntimeException("Unknown unit type");
}
}
/**
* Gets the defense value of this unit
* @return The DEF
*/
public float getDef() {
switch (type) {
case MILITIA: return size * UNIT_DEF_MILITIA;
case SWORDSMEN: return size * UNIT_DEF_SWORDS;
case BOWMEN: return size * UNIT_DEF_BOWS;
case CANNONS: return size * UNIT_DEF_CANNONS;
default: throw new RuntimeException("Unknown unit type");
}
}
/**
* Moves the unit to a tile
* @param destination The tile to move to
*/
public void moveTo(Tile destination) {
tile.exit();
destination.enter(this);
}
/**
* Runs the step for this unit
*/
public void step() {
}
@Override
public void reset() {
size = 1;
tile = null;
type = null;
action = null;
}
}
<file_sep>package be.woubuc.conqueror.screens;
import be.woubuc.conqueror.Choices;
import be.woubuc.conqueror.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Stage;
import static be.woubuc.conqueror.Globals.COLOUR_PANEL;
public final class ChoiceScreen implements Screen {
private Game game;
private Stage stage;
public Choices choices;
@Override
public void show() {
System.out.println("Showing choiceScreen");
game = Game.get();
stage = game.stage;
choices = new Choices(game);
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(COLOUR_PANEL.r, COLOUR_PANEL.g, COLOUR_PANEL.b, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
@Override
public void hide() {
System.out.println("Hiding choiceScreen");
stage.clear();
game = null;
stage = null;
choices = null;
}
@Override public void pause() { }
@Override public void resume() { }
@Override public void resize(int width, int height) { }
@Override public void dispose() { }
}
<file_sep>package be.woubuc.conqueror.screens;
import be.woubuc.conqueror.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.utils.Align;
import static be.woubuc.conqueror.Globals.COLOUR_PANEL;
import static com.badlogic.gdx.Input.Keys.ANY_KEY;
public final class VictoryScreen implements Screen {
private BitmapFont font;
private BitmapFont smallFont;
private Batch batch;
@Override
public void show() {
System.out.println("Showing victoryScreen");
Game game = Game.get();
batch = game.batch;
font = game.assets.get("font-large.fnt");
smallFont = game.assets.get("font-small.fnt");
game.gameScreen = null;
game.choiceScreen = null;
}
@Override
public void render(float delta) {
if (Gdx.input.isKeyPressed(ANY_KEY)) {
Gdx.app.exit();
return;
}
Gdx.gl.glClearColor(COLOUR_PANEL.r, COLOUR_PANEL.g, COLOUR_PANEL.b, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
font.draw(batch, "Victory", 0, (Gdx.graphics.getHeight() / 2) + 20, Gdx.graphics.getWidth(), Align.center, false);
smallFont.draw(batch, "You live to rule over these lands another day. These heroic exploits will surely be remembered. By everyone you didn't just murder, that is.",
100, Gdx.graphics.getHeight() / 2, Gdx.graphics.getWidth() - 200, Align.center, false);
font.draw(batch, "Press any key to exit", 0, 50, Gdx.graphics.getWidth(), Align.center, false);
batch.end();
}
@Override
public void hide() {
System.out.println("Hiding victoryScreen");
font = null;
smallFont = null;
batch = null;
}
@Override public void pause() { }
@Override public void resume() { }
@Override public void resize(int width, int height) { }
@Override public void dispose() { }
}
<file_sep># Conqueror
A minimal, semi-interactive strategy game made for the LibGDX 48h game jam.
More info: https://woubuc.itch.io/conqueror
<file_sep>package be.woubuc.conqueror.screens;
import be.woubuc.conqueror.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.utils.Align;
/**
* Shows the loading progress while the game assets are loading
*/
public final class LoadingScreen implements Screen {
private Game game;
private BitmapFont font;
private Batch batch;
@Override
public void show() {
System.out.println("Showing loadingScreen");
game = Game.get();
font = game.assets.get("font-large.fnt");
batch = game.batch;
}
@Override
public void render(float delta) {
game.assets.update();
if (game.assets.getProgress() >= 1) {
game.setScreen(game.gameScreen);
return;
}
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
font.draw(batch, "Loading", 0, (Gdx.graphics.getHeight() / 2) + 20, Gdx.graphics.getWidth(), Align.center, false);
font.draw(batch, Math.round(game.assets.getProgress() * 100) + "%", 0, Gdx.graphics.getHeight() / 2, Gdx.graphics.getWidth(), Align.center, false);
batch.end();
}
@Override
public void hide() {
System.out.println("Hiding loadingScreen");
font = null;
batch = null;
game = null;
}
@Override public void pause() { }
@Override public void resume() { }
@Override public void resize(int width, int height) { }
@Override public void dispose() { }
}
<file_sep>package be.woubuc.conqueror;
import be.woubuc.conqueror.focus.Movement;
import be.woubuc.conqueror.focus.Strategy;
import be.woubuc.conqueror.focus.Training;
import be.woubuc.conqueror.screens.ChoiceScreen;
import be.woubuc.conqueror.util.ColourUtils;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Align;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
* Creates the choices UI, used in {@link ChoiceScreen}.
*
* Every choice category has 4 options, but only 3 are shown at a time. Players
* cannot choose the same value they chose on the previous choice window of
* the same category.
*/
public class Choices {
private final Game game;
/**
* Initialises the choices manager
* @param game The main game instance
*/
public Choices(Game game) {
this.game = game;
}
/**
* Creates the movement choice window
*/
void createMovementChoice() {
System.out.println("Creating movement choices");
List<Option<Movement>> options = new ArrayList<>();
if (game.player.movement != Movement.EXPLORE) {
options.add(new Option<>("Explore",
Game.getDrawable("movement_explore.png"),
Movement.EXPLORE,
"Send out explorers to chart the unknown areas, so the army can march on more efficiently."
));
}
if (game.player.movement != Movement.FORTIFY) {
options.add(new Option<>("Fortify",
Game.getDrawable("movement_fortify.png"),
Movement.FORTIFY,
"Make sure the frontline is protected before expanding our territory and conquering new lands."
));
}
if (game.player.movement != Movement.RETREAT) {
options.add(new Option<>("Retreat",
Game.getDrawable("movement_retreat.png"),
Movement.RETREAT,
"Abandon the frontline and retreat until a new, stronger line of defense has been established. (not implemented yet)"
));
}
if (game.player.movement != Movement.REGROUP) {
options.add(new Option<>("Regroup",
Game.getDrawable("movement_regroup.png"),
Movement.REGROUP,
"Attempt to bring the army together in strong groups, instead of spreading out. (not implemented yet)"
));
}
createChoice("Give movement orders", options, (choice) -> {
game.player.movement = choice.value;
game.setScreen(game.gameScreen);
});
}
/**
* Creates the strategy choice window
*/
void createStrategyChoice() {
System.out.println("Creating strategy choices");
List<Option<Strategy>> options = new ArrayList<>();
if (game.player.strategy != Strategy.AVOID) {
options.add(new Option<>("Avoid",
Game.getDrawable("strategy_avoid.png"),
Strategy.AVOID,
"Avoid conflict with the enemy. Will attempt to leave some space between our frontlines and the enemy. (not implemented yet)"
));
}
if (game.player.strategy != Strategy.CHARGE) {
options.add(new Option<>("Charge",
Game.getDrawable("strategy_charge.png"),
Strategy.CHARGE,
"Charge head-first into battle and try to overwhelm the enemy with surprise attacks and sheer power."
));
}
if (game.player.strategy != Strategy.DEFEND) {
options.add(new Option<>("Defend",
Game.getDrawable("strategy_defend.png"),
Strategy.DEFEND,
"Stand ground and try to defend the current territory, instead of expanding."
));
}
if (game.player.strategy != Strategy.PROVOKE) {
options.add(new Option<>("Provoke",
Game.getDrawable("strategy_provoke.png"),
Strategy.PROVOKE,
"Try to provoke the enemy to attack areas with more fighters, giving less defended areas a chance to recover. (not implemented yet)"
));
}
createChoice("Choose battleground strategy", options, (choice) -> {
game.player.strategy = choice.value;
game.setScreen(game.gameScreen);
});
}
/**
* Creates the training choice window
*/
void createTrainingChoice() {
System.out.println("Creating training choices");
List<Option<Training>> options = new ArrayList<>();
if (game.player.training != Training.SWORDS) {
options.add(new Option<>("Swordsman",
Game.getDrawable("training_swords.png"),
Training.SWORDS,
"Standard military units. Efficient at slaying enemies, but far from invulnerable."
));
}
if (game.player.training != Training.BOWS) {
options.add(new Option<>("Bowman",
Game.getDrawable("training_bows.png"),
Training.BOWS,
"Bowmen are very weak when defending, but in offense they can make it rain hell upon the enemy."
));
}
if (game.player.training != Training.CANNONS) {
options.add(new Option<>("Cannon",
Game.getDrawable("training_cannons.png"),
Training.CANNONS,
"Training is very slow, but these cannons are nearly invincible on the battlefield."
));
}
if (game.player.training != Training.MILITIA) {
options.add(new Option<>("Militia",
Game.getDrawable("training_militia.png"),
Training.MILITIA,
"Recruit anyone, as fast as possible. The army will quickly become low in skill but high in numbers."
));
}
createChoice("Select recruitment policy", options, (choice) -> {
game.player.training = choice.value;
game.setScreen(game.gameScreen);
});
}
/**
* Creates the actual dialog window, used by the other methods in this class.
* @param title The dialog title
* @param options The options
* @param onChosen Called when an option is chosen
*/
private <T> void createChoice(String title, List<Option<T>> options, Consumer<Option<T>> onChosen) {
Table root = new Table();
root.setFillParent(true);
game.stage.addActor(root);
Label.LabelStyle labelStyle = new Label.LabelStyle(game.assets.get("font-large.fnt"), Color.WHITE);
Label.LabelStyle smallLabelStyle = new Label.LabelStyle(game.assets.get("font-small.fnt"), Color.WHITE);
Table container = new Table();
Label label = new Label(title, labelStyle);
label.setAlignment(Align.center);
container.add(label).colspan(3).pad(10);
container.row();
for (Option<T> option : options) {
Table optionButton = new Table();
optionButton.setTouchable(Touchable.enabled);
Table image = new Table();
image.add(new Image(option.drawable)).center();
optionButton.add(image).height(34).pad(5).padTop(20);
optionButton.row();
optionButton.add(new Label(option.name, labelStyle)).pad(5).padBottom(10);
optionButton.row();
Label description = new Label(option.description, smallLabelStyle);
description.setWrap(true);
optionButton.add(description).width(150).height(30).pad(5);
optionButton.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
container.getChildren().forEach(Actor::clearListeners);
container.remove();
game.stage.clear();
onChosen.accept(option);
return true;
}
@Override
public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
optionButton.setBackground(new TextureRegionDrawable(ColourUtils.getTexture(Globals.COLOUR_PANEL_ACTIVE)));
}
@Override
public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) {
optionButton.setBackground((Drawable) null);
}
});
container.add(optionButton).width(160).pad(5).padBottom(50);
}
root.add(container);
}
/**
* Data container that holds information about the possible options
*/
private class Option<T> {
final Drawable drawable;
final T value;
final String name;
final String description;
Option(String name, Drawable drawable, T value, String description) {
this.drawable = drawable;
this.value = value;
this.name = name;
this.description = description;
}
}
}
| e068f1e7494e048edd727a9c01d1ec87df76592b | [
"Markdown",
"Java"
] | 10 | Java | woubuc/conqueror | d4583d9aed183a6394d1ba6145fc2e9c4f98ada6 | 1ca88f4c5e37cddbf04b6de6f55140d56900f13b |
refs/heads/master | <file_sep>package ln.broadcastreceiverexample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
BroadcastReceiver broadcastReceiver;
TextView textView, textContact;
Intent intent, intent1, intentFetch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
textContact = (TextView) findViewById(R.id.txt_contact);
findViewById(R.id.button_start).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intent = new Intent();
intent.setClass(MainActivity.this, MyService.class);
intent.setAction(MyService.ACTION_START);
startService(intent);
}
});
findViewById(R.id.button_stop).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intent1 = new Intent();
intent1.setClass(MainActivity.this, MyService.class);
intent1.setAction(MyService.ACTION_STOP);
startService(intent1);
}
});
findViewById(R.id.btn_contact).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intentFetch = new Intent();
intentFetch.setClass(MainActivity.this, MyService.class);
intentFetch.setAction(MyService.ACTION_FETCH);
startService(intentFetch);
}
});
}
@Override
protected void onStart() {
super.onStart();
registerReceivers();
}
private void registerReceivers() {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String value = intent.getStringExtra(MyService.EXTRA_VALUE);
textView.setText(value);
String contacts = intent.getStringExtra(MyService.EXTRA_FETCH);
textContact.setText(contacts);
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.ACTION_BROADCAST);
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, intentFilter);
IntentFilter intentFilterFetch = new IntentFilter();
intentFilterFetch.addAction(MyService.ACTION_FETCH);
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, intentFilter);
}
@Override
protected void onStop() {
super.onStop();
unRegisterReceivers();
stopService(intent);
stopService(intent1);
stopService(intentFetch);
}
private void unRegisterReceivers() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
}
}
| bc78c8be5fe17eccd858e8343f0464fc7f143cf9 | [
"Java"
] | 1 | Java | SaurabhPurohit/BroadCastTimer | 416fdee1f9925d8ad4cd6f0bd8058630e3d21059 | 41d32a9cb57c90883e4a7eb5e7f4b09b1132a2f4 |
refs/heads/master | <repo_name>lcs-mzhang/HappyOrSad<file_sep>/HappyOrSad/main.swift
//
// main.swift
// HappyOrSad
//
// Created by <NAME> on 2018-04-04.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
// Get the user input
var rawInput = readLine()
var happy = 0
var sad = 0
//Make sure input is not nil
guard let input = rawInput else
{
//error
exit(9)
}
// Print out the input provided
print("You said: \(input)")
//print(rawInput) //optional
//print(input) //non-optional
for individualCharacter in input
{
if individualCharacter == "😃" || individualCharacter == "😄" || individualCharacter == "😊" || individualCharacter == "🙂"
{
happy += 1
}
else if individualCharacter == "😔" || individualCharacter == "😕" || individualCharacter == "🙁" || individualCharacter == "☹️"
{
sad += 1
}
// print(individualCharacter)
}
if happy > sad
{
print("happy")
}
else if happy < sad
{
print("sad")
}
else if happy == 0 && sad == 0
{
print("none")
}
else if happy == sad
{
print("unsure")
}
| 4755547be561dbf67f43680d41ae84055e84afdb | [
"Swift"
] | 1 | Swift | lcs-mzhang/HappyOrSad | 86966187c568d1cd754fc6beefd9a01f45b7aaac | 4c5079a88231c1ea1132e887efac735558750a00 |
refs/heads/master | <repo_name>A1dricAP/react_spring<file_sep>/src/components/component1.js
import React from 'react'
import {Spring} from 'react-spring/renderprops'
export default function component1() {
return (
<Spring from={{opacity:0 , marginTop:-500}} to={{opacity:1, marginTop:0}}>
{props=>(
<div style={props}>
<div style={c1style}>
<h1>Component 1</h1>
<p>
publishing and graphic design, Lorem ipsum is a placeholder
text commonly used to demonstrate the visual form of a document
or a typeface without relying on meaningful content.
Lorem ipsum may be used before final copy is available, but
it may also be used to temporarily replace copy in a process called greeking,
which allows designers to consider form without the meaning of the text influencing
the design.
</p>
</div>
</div>
)
}
</Spring>
)
}
const c1style={
background:'steelblue',
color:'white',
padding:'0.01rem'
}
| d98ec76d503aaa36c3490ec1a232a6f7a89b3ab2 | [
"JavaScript"
] | 1 | JavaScript | A1dricAP/react_spring | 737f0be6828a81d96088503c818c8236dd399707 | fbffd8bc0c46a29af21dc7ffd159d71ea6a7fbc6 |
refs/heads/main | <file_sep>#!/usr/bin/env node
import name from '../src/cli.js';
console.log(`Hello, ${name}!`);
<file_sep>#!/usr/bin/env node
import runGame from '../src/games/gcd.js';
runGame();
<file_sep>import utilities from '../utilities.js';
import runEngine from '../index.js';
const gameRules = 'What is the result of the expression?';
const operators = ['+', '-', '*'];
const calcExpression = (num1, num2, operator) => {
let result;
if (operator === '+') {
result = num1 + num2;
} if (operator === '-') {
result = num1 - num2;
} if (operator === '*') {
result = num1 * num2;
}
return result;
};
const getGameQuestionAndAnswer = () => {
const num1 = utilities.getRandomInt(100);
const num2 = utilities.getRandomInt(100);
const operator = operators[utilities.getRandomInt(operators.length)];
const question = `${num1} ${operator} ${num2}`;
const correctAnswer = String(calcExpression(num1, num2, operator));
return { question, correctAnswer };
};
const gameData = { gameRules, getGameQuestionAndAnswer };
const runGame = () => {
runEngine(gameData);
};
export default runGame;
<file_sep>import readlineSync from 'readline-sync';
const numberOfRounds = 3;
const runEngine = (gameData) => {
console.log('Welcome to the Brain Games!');
const name = readlineSync.question('May i have your name? ');
console.log(`Hello, ${name}!`);
console.log(gameData.gameRules);
const playRound = (currentRound) => {
if (currentRound > numberOfRounds) {
return true;
}
const { question, correctAnswer } = gameData.getGameQuestionAndAnswer();
console.log(`Question: ${question}`);
const usrAnswer = readlineSync.question('Your answer: ');
if (usrAnswer === correctAnswer) {
console.log('Correct!');
return playRound(currentRound + 1);
}
console.log(`'${usrAnswer}' is wrong answer ;(. Correct answer was '${correctAnswer}'.`);
return false;
};
const isWinner = playRound(1);
if (isWinner) {
console.log(`Congratulations, ${name}!`);
} else {
console.log(`Let's try again, ${name}!`);
}
};
export default runEngine;
<file_sep>### Hexlet tests and linter status:
[](https://github.com/ALezhnin87/frontend-project-lvl1/actions)
[](https://codeclimate.com/github/codeclimate/codeclimate/maintainability)
[](https://github.com/ALezhnin87/frontend-project-lvl1/actions)
[](https://asciinema.org/a/LhM2Y1aBq3U1eXTgntxD3mrhl)
[](https://asciinema.org/a/j10Dp1Axmn8nAK7oIjLZjbBDB)
[](https://asciinema.org/a/UTwTkq9X4fLdjtnbjl0lOw9o6)
[](https://asciinema.org/a/3AdIsmWSc9SrtZsteigEP4izQ)
[](https://asciinema.org/a/OwwWMkZbqQ724NXLW2FXp80mg)
<file_sep>install: # установить зависимости
npm ci
brain-games: # запуск
node bin/brain-games.js
publish: # публикация игры
npm publish --dry-run
lint: # запуск eslint
npx eslint .
lint-fix: #исправление линтером
npx eslint . --fix
brain-even: #запуск игры "проверка на чётность"
node bin/brain-even.js
brain-calc: #Запуск игры "калькулятор"
node bin/brain-calc.js
brain-gcd: #Запуск игры "НОД"
node bin/brain-gcd.js
brain-progression: #запуск игры "Арифметическая прогрессия"
node bin/brain-progression.js
brain-prime: #запуск игры "простое ли число?
node bin/brain-prime.js
<file_sep>const getRandomInt = (max) => Math.floor(Math.random() * Math.floor(max));
const isEven = (num) => (num % 2 === 0);
const getGCD = (num1, num2) => {
if (num1 === num2 || num2 === 0) {
return num1;
}
return getGCD(num2, num1 % num2);
};
const getProgression = (firstElem, delta, amountOfElements) => {
const progression = [];
for (let i = 1; i <= amountOfElements; i += 1) {
progression.push(firstElem + delta * i - 1);
}
return progression;
};
const isPrime = (num) => {
if (num < 2) {
return false;
}
for (let i = 2; i <= num / 2; i += 1) {
if (num % i === 0) {
return false;
}
}
return true;
};
export default {
getRandomInt,
isEven,
getGCD,
getProgression,
isPrime,
};
<file_sep>import utilities from '../utilities.js';
import runEngine from '../index.js';
const gameRules = 'What number is missing in the progression?';
const getGameQuestionAndAnswer = () => {
const firstElem = utilities.getRandomInt(100);
const delta = utilities.getRandomInt(20);
const amountOfElements = 10;
const array = utilities.getProgression(firstElem, delta, amountOfElements);
const hiddenIndex = utilities.getRandomInt(amountOfElements);
let hiddenNum = '..';
[hiddenNum, array[hiddenIndex]] = [array[hiddenIndex], hiddenNum];
const question = array.join(' ');
const correctAnswer = String(hiddenNum);
return { question, correctAnswer };
};
const gameData = { gameRules, getGameQuestionAndAnswer };
const runGame = () => {
runEngine(gameData);
};
export default runGame;
| 3c063fb52f23ab7d6ec66daa51c49f140cfd4e7b | [
"JavaScript",
"Makefile",
"Markdown"
] | 8 | JavaScript | ALezhnin87/frontend-project-lvl1 | 19b51e08630da22feac142279cae30e98367963c | 91e43d055b4c06f2fcc269dab8600c3d5100c18b |
refs/heads/master | <repo_name>joker-beta/JZ_offer<file_sep>/Array/JZ_66.py
""" JZ_66 机器人的运动范围
题目描述:地上有一个 m行和 m 列的方格。一个机器人从坐标 (0,0) 的格子开始移动,
每一次只能向左,右,上,下四个方向移动一格,
但是不能进入行坐标和列坐标的数位之和大于 k 的格子。
例如,当 k 为 18 时,机器人能够进入方格 (35,37),因为 3+5+3+7 = 18。
但是,它不能进入方格 (35,38),因为 3+5+3+8 = 19。请问该机器人能够达到多少个格子 ?
"""
import sys
# 添加下面代码,重新定义最大递归深度
sys.setrecursionlimit(1000000) # 例如这里设置为一百万
# 否则出现报错:
# RecursionError: maximum recursion depth exceeded while getting the str of an object
class Solution:
def movingCount(self, k, rows, cols):
self.count = 0 # 统计能达到的格子数
arr = [[1 for j in range(cols)] for i in range(rows)]
# 从 (0,0) 开始遍历
self.findway(arr, 0, 0, k)
return self.count
def findway(self, arr, i, j, k):
# 越界直接返回
if (i < 0 or j < 0) or (i >= len(arr) or j >= len(arr[0])):
return
# 为了要计算各数码的累加和,所以将横纵坐标数码转为数组
tmpi = list(map(int, list(str(i))))
tmpj = list(map(int, list(str(j))))
# 1,若不满足累加和要求,或者当前点已经遍历过,直接返回
if (sum(tmpi) + sum(tmpj) > k) or (arr[i][j] != 1):
return
# 2,若满足累加和要求,进行遍历
# 首先,将当前点标记为0,表示已经遍历过
arr[i][j] = 0
self.count += 1 # 找到一个满足要求的点,将个数更新
# 然后,基于当前点分别往上下左右遍历
self.findway(arr, i+1, j, k) # 左
self.findway(arr, i-1, j, k) # 右
self.findway(arr, i, j+1, k) # 上
self.findway(arr, i, j-1, k) # 下
k = 25
rows = 60
cols = 50
print(Solution().movingCount(k, rows, cols))<file_sep>/Array/JZ_45.py
# -*- coding:utf-8 -*-
""" JZ—45 扑克牌顺子
题目描述
一副扑克牌,发现里面居然有 `2` 个大王, `2` 个小王,随机从中抽出了 `5` 张牌,
看看能不能抽到顺子,大\小 王可以看成任何数字,
并且 `A` 看作 `1`, `J` 为 `11` , `Q` 为 `12` , `K` 为 `13`,
使用这幅牌模拟上面的过程, 如果牌能组成顺子就输出 `true`,否则就输出 `false`。
为了方便起见,你可以认为大小王是 `0`。
"""
# 分情况讨论:假设都排完序
# 1,[1,2,3,4,5], (2-1)+(3-2)+(4-3)+(5-4) = 4 此时满足条件需要相邻元素差累加和 = 4
# [1,3,4,5,6], (3-1)+(4-3)+(5-4)+(6-5) != 4
# 2,[0,1,2,3,4],
# [0,0,1,2,3],
# [0,0,0,1,2] 若0的个数为1-3,那么非零元素相邻差累加和 = 4
# 3,[0,0,0,0,1] 若0的个数为4,必定满足
class Solution:
def IsContinuous(self, numbers):
if numbers == []:
return False
numbers.sort()
zero_count = 0
res = 0
# 1,若没有0元素
if 0 not in numbers:
# 统计相邻差累加和
for i in range(4):
res += numbers[i+1] - numbers[i]
return True if (res == 4) else False
# 2,若有 0 元素
else:
# 若0元素个数为4,或者相邻差累加和为4,返回 True
if (zero_count == 4) or (res == 4):
return True
else:
return False
<file_sep>/Array/JZ_67.py
# -*- coding:utf-8 -*-
""" JZ—67 剪绳子
题目描述
给你一根长度为 `n` 的绳子,请把绳子剪成整数长的 `m` 段(`m、n` 都是整数,`n>1` 并且`m>1,m<=n`),
每段绳子的长度记为 `k[1],...,k[m]`。请问 `k[1]x...xk[m]` 可能的最大乘积是多少?
例如,当绳子的长度是 `8` 时,我们把它剪成长度分别为 `2、3、3` 的三段,此时得到的最大乘积是 `18`。
"""
# [思路]:对不超过6的正整数number,最大乘积为
# number = 0, max = 0
# number = 1, max = 1
# number = 2, max = 1*1 = 1
# number = 3, max = 1*2 = 2
# number = 4, max = 2*2 = 4
# number = 5, max = 2*3 = 6
# number = 6, max = 3*3 = 9
#
# 对于超过6的正整数number,最大乘积为,尽量将数等分成3份,直接设辅助函数求导。。。
# number = 7, max = 4*3 = 2*2*3 = 12
# number = 8, max = 6*3 = 2*3*3 = 18
# number = 9, max = 9*3 = 3*3*3 = 27
# ...
# number = i, max = max[i-3]*3
class Solution:
def cutRope(self, number):
ans = [0, 0, 1, 2, 4, 6, 9]
if number <= 6:
return ans[number]
else:
for i in range(7, number + 1):
ans.append(ans[i-3] * 3)
return ans[-1]<file_sep>/Strings/JZ_34.py
# -*- coding:utf-8 -*-
""" JZ—34 第一层只出现一次的字符
题目描述:
在一个字符串(`0<=` 字符串长度 `<=10000`,全部由字母组成)中找到第一个只出现一次的字符,
并返回它的位置, 如果没有则返回 `-1`(需要区分大小写).(从 `0` 开始计数)
"""
class Solution:
def FirstNoteRepeatingChar(self, s):
# 统计每个字符出现的次数
ans = {}
for i in s:
if i not in ans:
ans[i] = 1
else:
ans[i] += 1
# 记录出现次数为1的字符位置
index = 0
for j in s:
if ans[j] == 1:
return index
index += 1 # 更新字符串的下标
return -1<file_sep>/Math/JZ_48.py
# -*- coding:utf-8 -*-
""" JZ—48 不用加减乘除做加法
题目描述
写一个函数,求两个整数之和,要求在函数体内不得使用 `+、-、*、/` 四则运算符号。
"""
class Solution:
def Add(self, num1, num2):
if (num1 is None) or (num2 is None):
return None
while num2 != 0:
s = (num1 ^ num2) # 相加,但不考虑进位
num2 = (num1 & num2) << 1 # 更新进位
num1 = s & 0xfffffff
return num1 if (num1 >> 31 == 0) else (num1 - pow(2, 32))
num1 = 1
num2 = 2
print(Solution().Add(num1, num2))<file_sep>/Stock_List/JZ_20.py
# -*- coding:utf-8 -*-
""" JZ—20 包含min函数的栈
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的 `min` 函数
(时间复杂度应为 `O(1)`)。
"""
# 思路:(待补。。。)
class Solution:
def __init__(self):
self.stack = [] # 将每次要比较的元素都压入栈,待定比较
self.min_stack = [] # 栈尾存放最小值,即该栈为单调递减的栈
self.length = 0 # 存放栈 stack 的长度
def isEmpty(self):
"""判断是否为空"""
return self.length == 0
def getLength(self):
"""得到栈的长度"""
return self.length
def min(self):
"""返回最小值"""
if self.isEmpty():
print("Stack is empty!")
return
if self.min_stack:
return self.min_stack[-1]
def push(self, data):
"""压栈"""
# 1,若当前待比较的元素不是整数,或者浮点数,说明不满足要求
if (not isinstance(data, int)) and (not isinstance(data, float)):
print("The element must be numberic!")
return
# 2,若满足要求,则先将待比较元素入栈stack,长度+1,
# 再通过比较栈stack当前元素和栈min_stack最后元素(当前记录最小元素),将较小者入栈 min_stack
else:
self.stack.append(data) # 压栈
self.length += 1 # 栈的长度+1
# 1,若栈为空,或者要压入栈的元素小于已入栈的最小元素,直接将当前元素压入栈
if (self.min_stack == []) or (data < self.min()):
self.min_stack.append(data)
# 2,否则,将当前对比后较小的元素,压入栈
else:
self.min_stack.append(self.min())
def pop(self):
"""出栈"""
# 1,若栈 stack 是空的,说明要么还没压入元素,或者栈stack中元素都已经对比处理完毕,直接返回
if self.isEmpty():
print("Stack is empty!")
return
data = self.stack.pop()
self.min_stack.pop()
self.length -= 1
return data
def clear(self):
"""清空栈"""
self.stack = []
self.min_stack = []
self.length = 0
<file_sep>/dp/JZ_64.py
# -*- coding:utf-8 -*-
""" JZ—64 滑动窗口的最大值
题目描述:
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
例如,如果输入数组 `{2,3,4,2,6,2,5,1}` 及滑动窗口的大小 `3`,那么一共存在 `6` 个滑动窗口,
他们的最大值分别为 `{4,4,6,6,6,5}`;
针对数组 `{2,3,4,2,6,2,5,1}` 的滑动窗口有以下 `6` 个:
`{[2,3,4],2,6,2,5,1}`,` {2,[3,4,2],6,2,5,1}`, `{2,3,[4,2,6],2,5,1}`,
`{2,3,4,[2,6,2],5,1}`, `{2,3,4,2,[6,2,5],1}`, `{2,3,4,2,6,[2,5,1]}`。
窗口大于数组长度的时候,返回空。
例子:
输入: [2,3,4,2,6,2,5,1],3
返回值: [4,4,6,6,6,5]
"""
# [思路一]:利用 python 切片策略,每次通过size大小进行窗口移动。
class Solution_1:
def maxInWindows(self, num, size):
if (num == []) or (size <= 0):
return []
res = []
for i in range(len(num) - size + 1):
res.append(max(num[i:i+size]))
return res
# [思路二]:模拟窗口移动的过程,
class Solution_2:
def maxInWindows(self, nums, k):
# write code here
if (nums == []) or (k < 0):
return 0
left = right = 0
ans = [] # 存放每个窗口的最大值
res = [] # 存放每个窗口最大值的下标
while right < len(nums):
# 记录当前窗口最大值下标
# 始终保证res[0]存放当前窗口最大值下标
while (len(res) > 0) and (nums[res[-1]] <= nums[right]):
res.pop()
res.append(right)
right += 1
# 若当前窗口长度=k,就将窗口最大值加入ans中,
while right - left == k:
ans.append(nums[res[0]])
# 在进行窗口收缩之前,先判断当前窗口最大值的下标是否是窗口左端点
# 若是,则将其从res中删除
if (res[0] == left) and (len(res) > 0):
res.pop(0)
# 然后将窗口收缩
left += 1
return ans<file_sep>/Stock_List/JZ_5.py
# -*- coding:utf-8 -*-
""" JZ—5 两个栈实现队列
题目描述:
用两个栈来实现一个队列,完成队列的 `Push` 和 `Pop` 操作。 队列中的元素为 `int` 类型。
"""
class Solution:
def __init__(self):
self.stockA = []
self.stockB = []
def push(self, node):
"""入栈"""
self.stockA.append(node)
def pop(self):
"""出栈"""
if self.stockB == []:
# 1,若两个栈都为空,直接返回None
if self.stockA == []:
return None
# 2,若此时 stockA 非空,那么对该栈进行出栈操作,即将 stockA中元素反向添加到stockB中
else:
for i in range(len(self.stockA)):
self.stockB.append(self.stockA.pop())
return self.stockB.pop()
<file_sep>/Math/JZ_33.py
# -*- coding:utf-8 -*-
""" JZ—33 丑数
题目描述
把只包含质因子 `2、3` 和 `5` 的数称作丑数(Ugly Number)。
例如: `6、8` 都是丑数,但 `14` 不是,因为它包含质因子 `7`。
习惯上我们把 `1` 当做是第一个丑数。求按从小到大的顺序的第 `N` 个丑数。
"""
class Solution:
def GetUglyNumber_Solution(self, index):
# 1,若序号为空,直接返回0
if index <= 0:
return 0
# 2,若序号不为空,则通过索引判断是否为丑数
res = [1]
# 设置质因子2,3,5的统计下标
index2 = index3 = index5 = 0
for i in range(1, index):
u2 = res[index2] * 2
u3 = res[index3] * 3
u5 = res[index5] * 5
res.append(min(u2, u3, u5)) # res 中的数按照顺序排序,所以每次添加当前比较的最小值
# 2.1,若当前遍历下标对应的数能被2整除,说明该数包含2因子,则将前一个index2更新
if res[i]//2 == res[index2]:
index2 += 1
# 2.2,若当前遍历下标对应的数能被3整除,说明该数包含3因子,则将前一个index3更新
if res[i]//3 == res[index3]:
index3 += 1
# 2.3,若当前遍历下标对应的数能被5整除,说明该数包含5因子,则将前一个index5更新
if res[i]//5 == res[index5]:
index5 += 1
return res[-1]
index = 100
print(Solution().GetUglyNumber_Solution(index))<file_sep>/Strings/JZ_53.py
# -*- coding:utf-8 -*-
""" JZ—53 表示数值的字符串
题目描述:
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
例如,字符串 `"+100","5e2","-123","3.1416"` 和 `"-1E-16"` 都表示数值。
但是 `"12e","1a3.14","1.2.3","+-5"` 和 `"12e+4.3"` 都不是。
"""
# [思路一]:分析不满足要求的情况
# 1,12e:说明 e 的后面必须有数字,不能有两个 e
# 2,+-5:说明符号位要么出现一次在首位,要么出现一次在 e 的后一位,其他地方都不能有
# 3,12e4.3:说明 e 的后面不能有小数
# 4,1.2.3:说明不能有两个小数点
# 5,1a3.14:说明不能有其他的非法字符,比如这里的 a
class Solution_1:
def isNumeric(self, s):
sign = 0 # 记录+-符号之前是否出现过
point = 0 # 记录小数点.之前是否出现过
letterE = 0 # 记录e或者E之前是否出现过
# 分析不满足条件的情况
for i in range(len(s)):
# 1,若当前字符为 +-
if s[i] in '+-':
# 1.1 若字符 +- 之前没有出现过,并且前一个位置不是 e或者E,那么不满足要求
if (sign == 0) and (i > 0) and (s[i-1] not in 'eE'):
return False
# 1.2 若字符之前出现过,但是前一个位置不是 e或者E,那么满足要求
elif (sign == 1) and (s[i-1] not in 'eE'):
return False
sign = 1 # 将符号标记为出现过
# 2,若当前字符为 数字
elif s[i].isdigit():
pass
# 3,若当前字符为 小数点
elif s[i] == '.':
# 若之前已经出现过字符e或者E,又或者出现过小数点,都不满足条件
if (point == 1) or (letterE == 1):
return False
point = 1 # 将小数点标记为出现过
# 4,若当前字符为 e或者E
elif s[i] in 'eE':
# 若之前已经出现过字符e或者E,又或者前一个字符不是数字,又或者当前已经遍历到最后一个字符
if (letterE == 1) or (not s[i-1].isdigit()) or (i == len(s)-1):
return False
letterE = 1 # 将e/E标记为出现过
# 5,若当前字符不是符号+-,数字,小数点,e/E,说明不满足要求
else:
return False
# 除去以上分析的情况,其余情况都满足要求
return True
#s = "1a3.14"
s = "1e2"
print(Solution_1().isNumeric(s))
# [思路二]:内置函数 float()
class Solution_2:
def isNumeric(self, s):
try:
ans = float(s) # 如果能直接转为浮点型,说明输入字符串满足条件
return True
except:
return False
ss = '123e31'
print(Solution_2().isNumeric(ss))
# [思路三]:正则表达式(待补。。。)
import re
class Solution_3:
def isNumeric(self, s):
return re.match(r"^[\+\-]?[0-9]*(\.[0-9]*)?([eE][\+\-]?[0-9]+)?$", s)
sss = '123e31'
print(Solution_3().isNumeric(sss))<file_sep>/dp/JZ_10.py
# -*- coding:utf-8 -*-
""" JZ—10 矩形覆盖
题目描述:
我们可以用 `2x1` 的小矩形横着或者竖着去覆盖更大的矩形。
请问用 `n` 个 `2x1` 的小矩形无重叠地覆盖一个 `2xn` 的大矩形,总共有多少种方法?
"""
# [思路]:dp[i] 表示覆盖 2xi 大矩形的方法数
# 1,若第一个小矩形竖着放,此时后面2x(i-1)大矩形有 dp[i-1] 种覆盖方法
# 2,若第一个小矩形横着放,那么必定前两个小矩形都是横着放,所以后面2x(i-2)大矩形有 dp[i-2] 种覆盖方法
# 所以合并起来的转移方程就是:dp[i] = dp[i-1] + dp[i-2]
class Solution_1:
def rectCover(self, n):
if n <= 0:
return 0
dp = [1 for _ in range(n + 1)]
for i in range(2, n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[-1]
# (做点优化)进一步可以将dp数组简化为三个变量
class Solution_2:
def rectCover(self, n):
if n <= 0:
return 0
fast = slow = 1
for i in range(2, n+1):
tmp = fast
fast += slow
slow = tmp
return fast
n = 6
print(Solution_2().rectCover(n))<file_sep>/dp/JZ_9.py
# -*- coding:utf-8 -*-
""" JZ—9 变态跳台阶
题目描述:
一只青蛙一次可以跳上 `1` 级台阶,也可以跳上 `2` 级……它也可以跳上 `n` 级。
求该青蛙跳上一个 `n` 级的台阶总共有多少种跳法。
"""
# [思路]:dp[i] 表示i个台阶的跳法数
# dp[i] = dp[i-1] + dp[i-2] + ... + dp[1]
# dp[i-1] = dp[i-2] + dp[i-3] + ... + dp[1]
# ==> dp[i] = 2 * dp[i-1], dp[1] = 1
# ==> dp[i] = 2^(i-1)
class Solution:
def JumpFloorII(self, number):
dp = [1 for i in range(number)]
for i in range(1, number):
dp[i] = 2 * dp[i-1]
return dp[-1]
""" 扩展(商汤2018年笔试)
题目描述:
有n级台阶,每次最多跳m级台阶,其中 0 < m <= n,计算总共的跳法数
"""
# [思路]:dp[i] 表示i个台阶的跳法数
# dp[i] = dp[i-1] + dp[i-2] + ... + dp[i-m]
class Solution_1:
def JumpFloorIII(self, n, m):
if (n <= 0) or (n < m):
return -1
if (n == 1) or (m == 1):
return 1
elif n == 2:
if m == 1:
return 1
elif m == 2:
return 2
else:
dp = [i for i in range(n)] # 由于从前往后累加,并且dp[0]=0, dp[1]=1, dp[2]=2
for i in range(n):
for j in range(i-1, i-1-m, -1):
if j >= 0:
dp[i] += dp[j]
return dp[-1]
n = 4
m = 3
print(Solution_1().JumpFloorIII(n, m))
<file_sep>/Array/JZ_13.py
# -*- coding:utf-8 -*-
"""
题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,
所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
"""
# [思路一]:冒泡排序的想法,若相邻两项偶数出现在奇数前面,则交换
class Solution_1:
def reOrderArray(self, array):
n = len(array)
for i in range(n):
for j in range(1, n-i):
# 若相邻两项,偶数出现在奇数前面,则交换
if (array[j-1]%2 == 0) and (array[j]%2 == 1):
array[j-1], array[j] = array[j], array[j-1]
return array
arr = [i for i in range(10)]
print(Solution_1().reOrderArray(arr))
# [思路二]:将奇数偶数分别存到两个列表中,最后再合并
class Solution_2:
def reOrderArray(self, array):
odd = [] # 存放奇数
even = [] # 存放偶数
for i in range(len(array)):
if array[i]%2 == 1:
odd.append(array[i])
else:
even.append(array[i])
return odd + even
arr2 = [3*i+2 for i in range(10)]
print(Solution_2().reOrderArray(arr2))<file_sep>/Math/JZ_31.py
# -*- coding:utf-8 -*-
""" JZ-31 整数中 1 出现的次数
题目描述:求出 `1~13` 的整数中 `1` 出现的次数,并算出 `100~1300` 的整数中 `1` 出现的次数?
为此他特别数了一下 `1~13` 中包含 `1` 的数字有 `1、10、11、12、13` 因此共出现 `6` 次,
但是对于后面问题他就没辙了。`ACMer` 希望你们帮帮他,并把问题更加普遍化,
可以很快的求出任意非负整数区间中 `1` 出现的次数(从 `1` 到 `n` 中 `1` 出现的次数)。
"""
# 方法一:调用内置函数 arr.count(str) 计算arr中字符(串)str 出现的次数
class Solution_1:
def NumberOf1Betetween1AndN_Solution(self, n):
if (n < 1):
return 0
count = 0
for i in range(1, n+1):
count += self.Count(i)
return count
def Count(self, m):
"""计算数字m中数码'1'的个数"""
arr = list(str(m)) # 将数字 m 转为字符列表
return arr.count('1') # 再返回列表中 '1' 的个数
# 方法二:(待补。。。)
class Solution_2:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
if (n < 1):
return 0
Len = self.getLen(n) # 获得整数长度
if (Len == 1):
return 1
tmp1 = pow(10, Len - 1)
first = n // tmp1 # 获得整数的首位数字
if first == 1: # 若首位数字为1
firstnum = n % tmp1 + 1
else: # 若首位数字不为1
firstnum = tmp1
othernum = first * (Len - 1) * (tmp1 // 10)
return firstnum + othernum + self.NumberOf1Between1AndN_Solution(n % tmp1)
def getLen(self, n):
"""计算整数的位数长度"""
Len = 0
while (n != 0):
Len += 1
n = n // 10
return Len
<file_sep>/dp/JZ_46.py
# -*- coding:utf-8 -*-
""" JZ—46 圆圈中最后剩下的元素
题目描述:
让小朋友们围成一个大圈。然后,他随机指定一个数 `m`,让编号为 `0` 的小朋友开始报数。
每次喊到 `m-1` 的那个小朋友要出列,并且不再回到圈中,从他的下一个小朋友开始,
继续 `0...m-1` 报数....这样下去....直到剩下最后一个小朋友,如果没有小朋友,请返回 `-1`。
例子:
输入: 5,3
返回值: 3
"""
"""
n:小孩个数,编号0,1,...,n-1
m:指定的数
小孩围成一圈,编号为0的小孩开始报数,喊到m-1的小孩出列,余下的小孩重新围成一圈
重该小孩的下一个小孩开始报数。。
[递归]:
1,假设f(n, m) 表示最终留下元素的序号。比如上例子中表示为:f(5,3) = 3
2,首先,长度为 n 的序列会先删除第 m % n 个元素,然后剩下一个长度为 n - 1 的序列。
3,当我们知道了 f(n - 1, m) 对应的答案 x 之后,我们也就可以知道,长度为 n 的序列最后一个删除的元素,
4,应当是从 m % n 开始数的第 x 个元素。因此有 f(n, m) = (m % n + x) % n = (m + x) % n。
当n等于1时,f(1,m) = 0
[简化]:
f[1] = 0
f[2] = (f[1] + m)%2
f[3] = (f[2] + m)%3
...
f[n] = (f[n-1] + m)%n
"""
class Solution:
def LastRemaining_Solution(self, n, m):
if n <= 0:
return -1
f = 0
for i in range(2, n+1):
f = (f + m) % i
return f
<file_sep>/Array/JZ_51.py
# -*- coding:utf-8 -*-
""" JZ—51 构建乘积数组
题目描述
给定一个数组 `A[0,1,...,n-1]`,请构建一个数组 `B[0,1,...,n-1]`,
其中 `B` 中的元素`B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]`。
不能使用除法。
(注意:规定 `B[0] = A[1] * A[2] * ... * A[n-1],B[n-1] = A[0] * A[1] * ... * A[n-2]`;)
对于 `A` 长度为 `1` 的情况,`B` 无意义,故而无法构建,因此该情况不会存在
"""
# [思路]:将B数组中每一个元素对应的乘积分成两部分c[i],d[i],分别计算
# B[i] = (A[0]*A[1]*...*A[i-1]) * (A[i+1]*...*A[n-1])
# = c[i] * d[i]
#
# 计算 c[i]: c[i] = c[i-1] * A[i-1], c[0] = 1
# 计算 d[j]: d[j] = d[j+1] * A[j+1], d[n-1] = 1
class Solution:
def multiply(self, A):
c = [1 for _ in range(len(A))]
d = [1 for _ in range(len(A))]
b = []
for i in range(len(A)-1):
c[i+1] = c[i] * A[i]
for j in range(len(A)-2, -1, -1):
d[j] = d[j+1] * A[j+1]
for k in range(len(A)):
b.append(c[k] * d[k])
return b<file_sep>/Math/JZ_11.py
# -*- coding:utf-8 -*-
""" JZ-11 二进制中 1 的个数
题目描述:
输入一个整数,输出该数 `32` 位二进制表示中 `1` 的个数。其中负数用补码表示。
"""
# 思路:(最优解)利用位运算 &: 两个数位都是1时,取1
class Solution:
def NumberOf1(self, n):
ans = 0
while (n&0xfffffff != 0):
ans += 1
n = n & (n-1) # 把最右边的一个数码1转化为0
return ans
n = 42
print(bin(n))
print(Solution().NumberOf1(n))<file_sep>/dp/JZ_47.py
# -*- coding:utf-8 -*-
""" JZ—47 礼物的最大价值
题目描述
在一个 `mxn` 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 `0`)。
你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。
给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物?
例子
输入: [[1,3,1],
[1,5,1],
[4,2,1]]
返回值: 12
解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物
"""
from typing import List
class Solution:
def maxValue(self, grid: List[List[int]]) -> int:
# dp[i][j] 表示走到 grid[i][j]位置时,获得的最大收益
dp = [[0 for j in range(len(grid[0]))] for i in range(len(grid))]
dp[0][0] = grid[0][0]
# 1,先计算dp矩阵第一列的元素
for i in range(1, len(grid)):
dp[i][0] = dp[i-1][0] + grid[i][0]
# 2,再计算dp矩阵第一行的元素
for j in range(1, len(grid[0])):
dp[0][j] =dp[0][j-1] + grid[0][j]
# 3,最后再计算dp矩阵内部元素
for i in range(1, len(grid)):
for j in range(1, len(grid[0])):
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + grid[i][j]
return dp[-1][-1]<file_sep>/Strings/JZ_52.py
# -*- coding:utf-8 -*-
""" JZ—52 正则表达式匹配
题目描述
请实现一个函数用来匹配包括 `'.'` 和 `'*'` 的正则表达式。模式中的字符 `'.'` 表示任意一个字符,
而 `'*'` 表示它前面的字符可以出现任意次(包含 `0` 次)。在本题中,匹配是指字符串的所有字符匹配整个模式。
例如,字符串 `"aaa"` 与模式 `"a.a"` 和 `"ab*ac*a"` 匹配,但是与 `"aa.a"` 和 `"ab*a"` 均不匹配。
"""
# [思路一]:递归迭代
class Solution_1:
"""
s, pattern: string
"""
def match(self, s, pattern):
# write code here
if s == pattern:
return True
# 1,若p[1]='*',那么对s[0]和p[0]比较
if (len(pattern) > 1) and (pattern[1] == '*'):
# 1,若s[0]和p[0]能够匹配,考虑到p[1]='*',那么递归对s[1:]和p[2:]匹配
if s and (s[0] == pattern[0] or pattern[0] == '.'):
return self.match(s, pattern[2:]) or self.match(s[1:], pattern)
# 2,若s[0]不能和p[0]匹配,同样考虑到p[1]='*',那么递归对s和p[2:]匹配
else:
return self.match(s, pattern[2:])
# 2,若字符s和p都非空,并且s[0]和p[0]能够匹配,那么递归对s[1:]和p[1:]进行匹配
elif s and pattern and (s[0] == pattern[0] or pattern[0] == '.'):
return self.match(s[1:], pattern[1:])
return False
# [思路二]:
# 假设主串为s,长度为sn,模式串为p,长度为pn,对于模式串p当前的第i位来说,有'正常字符'、'*'、'.'三种情况。
# 我们针对这三种情况进行讨论:
#
# 1,如果p[i]为正常字符, 那么我们看s[i]是否等于p[i], 如果相等,说明第i位匹配成功,接下来看s[i+1...sn-1] 和 p[i+1...pn-1]
# 2,如果p[i]为'.', 它能匹配任意字符,直接看s[i+1...sn-1] 和 p[i+1...pn-1]
# 3,如果p[i]为'*', 表明p[i-1]可以重复0次或者多次,需要把p[i-1] 和 p[i]看成一个整体.
# 3.1 如果p[i-1]重复0次,则直接看s[i...sn-1] 和 p[i+2...pn-1]
# 3.2 如果p[i-1]重复一次或者多次,则直接看s[i+1...sn-1] 和p[i...pn-1],但是有个前提:s[i]==p[i] 或者 p[i] == '.'
class Solution_2:
"""
s, pattern: string
"""
def match(self, s, p):
# write code here
sn = len(s)
pn = len(p)
# f[i][j]表示s的前i个和p的前j个能否匹配
f = [[0 for j in range(pn+1)] for i in range(sn+1)]
for i in range(sn+1):
for j in range(pn+1):
# 初始条件:
# 1,s为空且p为空,为真: f[0][0] = 1
# 2,s不为空且p为空,为假: f[1..sn][0] = 0
if j == 0:
f[i][j] = (i == 0)
else:
# 如果没有 '*'
if p[j-1] != '*':
# 对于方法一种的1,2两种情况可知:f[i][j] = f[i-1][j-1]
if (i >= 1) and (s[i-1] == p[j-1] or p[j-1] == '.'):
f[i][j] = f[i-1][j-1]
# 如果有 '*',第三种情况
else:
# 重复 0 次,如果重复0次,f[i][j] = f[i][j-2]
if j >= 2:
f[i][j] = f[i][j] | f[i][j-2] # 或运算
# 重复 1 次或者多次,如果重复1次或者多次,f[i][j] = f[i-1][j]
# 这里要用 | 连接, 不然重复 0 次的会直接覆盖
if (i >= 1) and (j >= 2) and (s[i-1] == p[j-2] or p[j-2] == '.'):
f[i][j] = f[i][j] | f[i-1][j]
return f[-1][-1]<file_sep>/Backtracking/JZ_23.py
""" JZ—23 字符串的排列
题目描述:输入一个字符串,按字典序打印出该字符串中字符的所有排列。
例如输入字符串 `abc`,则按字典序打印出由字符 `a, b, c`
所能排列出来的所有字符串 `abc, acb, bac, bca, cab` 和 `cba`。
例子:
输入:"ab"
输出:["ab", "ba"]
"""
class Solution:
def Permutation(self, Str):
if len(Str) == 0:
return []
if len(Str) == 1:
return [Str]
# 创建一个集合用于去除重复字符串
res = set()
# 遍历字符串,固定第一个元素,第一个元素可以取 a,b,c...全部渠道
# 然后递归求解
for i in range(len(Str)):
# 对Str中除去Str[i]元素外余下的字符串构成的所有排列进行遍历
# 此时,将Str[i] 作为新字符串的首字符进行拼接,构成新的字符排序
for j in self.Permutation(Str[:i] + Str[i+1:]):
res.add(Str[i] + j) # set() 集合添加元素的方法 add()
# 每次添加完之后进行字典排序,再返回
return sorted(res)
strs ='abc'
print(Solution().Permutation(strs))
<file_sep>/Array/JZ_19.py
# -*- coding:utf-8 -*-
""" JZ—19 顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,
例如,如果输入如下4 X 4矩阵: `1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16`
则依次打印出数字`1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.`
"""
# [思路]:从最外圈按顺时针打印,并在打印完一圈后往内收缩
class Solution:
def printMatrix(self, matrix):
rows, columns = len(matrix), len(matrix[0])
order = []
# 先固定两个对角顶点,即左上(left, top) 和右下(right, bottom)
left, right, top, bottom = 0, columns-1, 0, rows-1
while (left <= right) and (top <= bottom):
# 1,最上面一行,从左到右添加到 order
for j in range(left, right+1):
order.append(matrix[top][j])
# 2,最右边一列,从上到下添加到 order
for i in range(top+1, bottom+1):
order.append(matrix[i][right])
# 若没有越界,继续添加
if (left < right) and (top < bottom):
# 3,最下面一行,从右到左添加到 order
for j in range(right-1, left, -1):
order.append(matrix[bottom][j])
# 4,最左边一列,从下到上添加
for i in range(bottom, top, -1):
order.append(matrix[i][left])
# 上面的操作将二维矩阵的最外一层顺时针添加到 order 中
# 接下来,将定位的两个坐标的网内收缩
left += 1
right -= 1
top += 1
bottom -= 1
return order
n = 4
m = 5
mat = [[j + i*n for j in range(n)] for i in range(m)]
print(mat)
print(Solution().printMatrix(mat))<file_sep>/Strings/JZ_49.py
# -*- coding:utf-8 -*-
""" JZ—49 把字符串转换成整数
题目描述:
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。
数值为 `0` 或者字符串不是一个合法的数值则返回 `0`
"""
# [思路]:
# 1,建立 list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# 2,每个字符在 list 里面寻找他的索引,这个索引就是它对应的值
class Solution:
def StrToInt(self, s):
"""判断字符串是否为数字"""
if len(s) == 0:
return 0
List = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] # 或者 list(map(str, range(10))
flag = 1 # 记录正负号
ans = 0 # 存放拼接的数字
# 判断第一位是否为正负号,或者数字,或者其他
if s[0] == '+':
flag = 1
elif s[0] == '-':
flag = -1
elif (s[0] > '0') and (s[0] < '9'):
ans += List.index(s[0]) * pow(10, len(s)-1) # 最高位
else:
return 0 # 若字符首位不是'+/-',或者数字字符,说明字符串不合法
# 若字符串合法,进行每个数位的合并
for i in range(1, len(s)):
if (s[i] >= '0') and (s[i] <= '9'):
ans += List.index(s[i]) * pow(10, len(s)-1-i)
else:
return 0
return flag * ans
s = '+12456'
#s ='+12f3f'
print(Solution().StrToInt(s))<file_sep>/Array/JZ_1.py
# -*- coding:utf-8 -*-
""" JZ—1 二维数组中的查找
题目描述:
在一个二维数组中(每个一维数组的长度相同),
每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例1
输入 7, [[1, 2, 8, 9],
[2, 4, 9, 12],
[4, 7, 10, 13],
[6, 8, 11, 15]]
返回值 true
"""
# 思路:类似二分查找的策略,记当前遍历元素为cur,目标元素为tar,初始位置第一行最后一列的位置。
# 1,若cur < tar[行][列],则 列-1
# 2,若cur > tar[行][列],则 行+1
# 3,若cur = tar[行][列],则返回。
class Solution:
def Find(self, target, array):
rows = len(array)
cols = len(array[0])
if (rows > 0) and (cols > 0):
# 选取数组右上角元素为初始元素,开始对比
row = 0 # 第一行
col = cols - 1 # 最后一列
while (row < rows) and (col >= 0):
if target == array[row][col]:
return True
# 若目标值比当前遍历大,说明应该在下一行开始查找
elif target > array[row][col]:
row += 1
# 若目标值比当前遍历值小,说明应该在当前列的左边进行查找
elif target < array[row][col]:
col -= 1
# 若遍历完整个数组,还是没有找到,说明数组中不存在该值
return False
mat = [[1, 2, 8, 9],
[2, 4, 9, 12],
[4, 7, 10, 13],
[6, 8, 11, 15]]
target = 6
print(Solution().Find(target, mat))<file_sep>/Strings/JZ_44.py
# -*- coding:utf-8 -*-
""" JZ—44 翻转单词顺序列
题目描述:
牛客最近来了一个新员工 `Fish`,每天早晨总是会拿着一本英文杂志,写些句子在本子上。
同事`Cat` 对 `Fish` 写的内容颇感兴趣,有一天他向 `Fish` 借来翻看,但却读不懂它的意思。
例如,`“student. a am I”`。后来才意识到,这家伙原来把句子单词的顺序翻转了,
正确的句子应该是 `“ I am a student.”`。
"""
class Solution:
def ReaverseSentence(self, s):
if len(s) == 0:
return ""
a = list(s.split(' '))
# 以列表中轴线为基准,对称的元素进行互换
for i in range(len(a)//2):
a[i], a[len(a)-1-i] = a[len(a)-1-i], a[i]
return ' '.join(a)
s = 'student. a am I'
print(Solution().ReaverseSentence(s))<file_sep>/Array/JZ_50.py
# -*- coding:utf-8 -*-
""" JZ—50 数组中重复的数字
题目描述:
在一个长度为 `n` 的数组里的所有数字都在 `0` 到 `n-1` 的范围内。
数组中某些数字是重复的,但不知道有几个数字是重复的。
也不知道每个数字重复几次。请找出数组中第一个重复的数字。
例如,如果输入长度为7的数组 `{2,3,1,0,2,5,3}`,那么对应的输出是第一个重复的数字 `2`。
返回描述:
如果数组中有重复的数字,函数返回 `true`,否则返回 `false`。
如果数组中有重复的数字,把重复的数字放到参数 `duplication[0]` 中。
"""
# [思路]:先创建字典统计数组numbers中各数字出现的次数
# 再遍历字典输出第一个统计次数大于1的数字
class Solution:
def duplicate(self, numbers, duplication):
ans = {}
# 统计 numbers 中各数字出现的次数
for num in numbers:
if num in ans:
ans[num] += 1
else:
ans[num] = 1
# 数组中第一个出现的重复数字
for num in numbers:
if ans[num] > 1:
duplication[0] = num
return True
return False<file_sep>/dp/JZ_30.py
# -*- coding:utf-8 -*-
""" JZ—30 连续子数组的最大和(连续子序列)
题目描述:
给一个数组,返回它的最大连续子序列的和
例子:
输入: [1,-2,3,10,-4,7,2,-5]
返回值: 18
"""
class Solution:
def FindGreatstSumOfSubArray(self, array):
# dp[i] 表示以array[i]结尾的子序列构成的最大和
dp = [0 for i in range(len(array))]
dp[0] = array[0]
# 若前i-1个数累加和大于零,则继续往后添加,否则以当前元素array[i] 作为新的子序列的起始点
for i in range(1, len(array)):
dp[i] = max(dp[i-1], 0) + array[i]
return max(dp)<file_sep>/Array/JZ_32.py
# -*- coding:utf-8 -*-
""" JZ—32 把数组排成最小的数
题目描述:
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
例如输入数组 `{3,32,321}`,则打印出这三个数字能排成的最小数字为 `321323`。
"""
# 思路:将两个数字字符串x,y直接拼接对比,
# 1,若 x+y > y+x,则需要将x和y的位置互换
# 2,若 x+y < y+x,则不需要互换
# 3,若 x+y = y+x,则
from functools import cmp_to_key
class Solution_1:
def Compare_small(self, num1, num2):
"""对比两个字符串形成的整数大小,构成最小排序"""
if num1 + num2 > num2 + num1:
return 1
else:
return -1
def PrintMinNumber(self, numbers):
if numbers is None:
return ""
lens = len(numbers)
if lens == 0:
return ""
# 按照cmp_to_key引用排序函数规则进行排序
tmp_numbers = sorted(numbers, key=cmp_to_key(self.Compare_small)) # 注意这里是函数名
return int(''.join(tmp_numbers))
a = ['3', '32', '321']
print(Solution_1().PrintMinNumber(a))
class Solution_2:
def Compare_biger(self, num1, num2):
"""对比两个字符串形成的整数大小,构成最大排序"""
if num1 + num2 < num2 + num1:
return 1
else:
return -1
def PrintMaxNumber(self, numbers):
if numbers is None:
return ""
lens = len(numbers)
if lens == 0:
return ""
# 按照cmp_to_key引用排序函数规则进行排序
tmp_numbers = sorted(numbers, key=cmp_to_key(self.Compare_biger)) # 注意这里是函数名
return int(''.join(tmp_numbers))
b = ['3', '32', '321']
print(Solution_2().PrintMaxNumber(b))<file_sep>/Strings/JZ_54.py
# -*- coding:utf-8 -*-
""" JZ—54 字符流中第一个不重复的字符
题目描述:
请实现一个函数用来找出字符流中第一个只出现一次的字符。
例如,当从字符流中只读出前两个字符 `"go"` 时,第一个只出现一次的字符是 `"g"`。
当从该字符流中读出前六个字符 `“google"` 时,第一个只出现一次的字符是 `"l"`。
如果当前字符流没有存在出现一次的字符,返回 `#` 字符。
"""
class Solution:
def __init__(self):
self.s = ""
self.dict1 = {}
def Insert(self, char):
"""统计字符串中各字符出现的次数"""
self.s += char
if char in self.dict1:
self.dict1[char] += 1
else:
self.dict1[char] = 1
def FirstAppearingOnce(self):
"""返回第一个出现一次的字符"""
for i in self.s:
if self.dict1[i] == 1:
return i
return '#'<file_sep>/Strings/JZ_43.py
# -*- coding:utf-8 -*-
""" JZ—43 左旋字符串
题目描述
对于一个给定的字符序列 `S`,请你把其循环左移 `K` 位后的序列输出。
例如,字符序列`S=”abcXYZdef”`,要求输出循环左移 `3` 位后的结果,即 `“XYZdefabc”`。
"""
class Solution:
def LeftRotateString(self, s, n):
if len(s) <= 0:
return ""
n %= len(s) # n可能比字符串 S 长度长,移动出现循环
return s[n:] + s[:n]
s = 'abcXYZdef'
n = 4
print(Solution().LeftRotateString(s, n))<file_sep>/Array/JZ_29.py
# -*- coding:utf-8 -*-
""" JZ—29 最小的k个数
题目描述:
输入 `n` 个整数,找出其中最小的 `K` 个数。
例如输入 `4,5,1,6,2,7,3,8` 这 `8` 个数字,则最小的 `4` 个数字是 `1,2,3,4`。
"""
# [思路]:构建最大堆(每一层从上往下递减),默认是小顶堆,注意输出时需要逆序。
import heapq as hq
class Solution:
def GetLeastNumbers(self, arr, k):
"""最小的 k 个数"""
if (k <= 0) or (k > len(arr)):
return []
stack = [] # 记录数组中最小的k个数
for num in arr:
if len(stack) < k:
hq.heappush(stack, -num)
else:
if stack[0] < -num:
hq.heapreplace(stack, -num)
ans = []
while stack:
ans.append(-hq.heappop(stack))
return ans[::-1]
def GetGreastNumbers(self, arr, k):
"""最大的 k 个数"""
if (k <= 0) or (k > len(arr)):
return []
stack = []
for num in arr:
if len(stack) < k:
hq.heappush(stack, num)
else:
if stack[0] < num:
hq.heapreplace(stack, num)
ans = []
while stack:
ans.append(hq.heappop(stack))
return ans
a = [4, 5, 1, 6, 2, 7, 3, 8]
k = 5
print('最小%.f个:' %k, Solution().GetLeastNumbers(a, k))
print('最大%.f个:' %k, Solution().GetGreastNumbers(a, k))<file_sep>/Array/JZ_42.py
# -*- coding:utf-8 -*-
""" JZ—42 和为S的两个数
题目描述
输入一个递增排序的数组和一个数字 $S$,在数组中查找两个数,
使得他们的和正好是 $S$,如果有多对数字的和等于 $S$,输出两个数的乘积最小的。
"""
# [思路]:双指针想法,由于数组递增排序,设置两个指针在数组两头往内走,
# 若出现相加等于S的数字对,进行判断,并存下乘积小的一组
class Solution:
def FindNumberWithSum(self, array, tsum):
count = float('INF')
ans = []
left, right = 0, len(array)-1
while left < right:
s = array[left] + array[right]
# 若多组相加和等于S,选择乘积最小的一组
if s == tsum:
if count >= array[left] * array[right]:
count = array[left] * array[right]
ans = [array[left], array[right]]
# 若找到一组,接着让指针往里走,继续更新
left += 1
right -= 1
elif s > tsum:
right -= 1
else:
left += 1
return ans
| 37e271e42d670d5a53782df349170c0a3867fc50 | [
"Python"
] | 31 | Python | joker-beta/JZ_offer | 8a2b64cbbdd2ad6563273dccf7812c6192462fcf | be4f205f4fb1083c36b22bd15fb7ee08e1b48665 |
refs/heads/master | <file_sep># 仅仅是一个使用 redux-saga 的demo
使用了:
- redux
- redux-saga: 把副作用抽离成独立的 Generator 函数,执行完副作用的事件,再dispatch普通的action去修改state
- redux-action: action映射reducer, 简化action和reducer的编写
- redux-auto-local-storage: 自动持久化某些store.getState()的keys, 兼容immutable对象
- immutable: 不可变对象
## redux-thunk 和 redux-saga 的区别

<file_sep>import { handleActions } from 'redux-actions';
import { Map } from 'immutable';
import types from './types';
export const user = handleActions(
{
user_auto_local_storage: (state, { payload }) => payload,
[types.userAddCount]: (state, { payload }) => state.update('count', v => v + payload.count),
[types.userRemoveCount]: (state, { payload }) => state.update('count', v => v - payload.count),
[types.userUpdateAuth]: (state, { payload }) => state.update('data', v => ({ ...v, ...payload })),
},
Map({ count: 0, data: {} })
);
export const error = handleActions(
{
[types.errorFetchFainl]: (state, { payload }) => state.update('error', v => ({ ...v, ...payload })),
},
Map({})
);
<file_sep>export default {
userAddCount: 'userAddCount',
userRemoveCount: 'userRemoveCount',
userUpdateAuth: 'userUpdateAuth',
errorFetchFainl: 'errorFetchFainl',
// -- sage --
sagaFetchUser: 'sagaFetchUser',
sageUserUpdateAuth: 'sageUserUpdateAuth',
}; | b1220d34b341b1ee53c9c5143ae142dafd17a486 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | ymzuiku/react-redux-saga-demo | 0efd8f6fe226b60f733f6d711ede5427f2415750 | 37428c77559e72fcde9ba3353f5a098363212a19 |
refs/heads/master | <file_sep>class EtsyUploaderRecord < ActiveRecord::Base
self.abstract_class = true
establish_connection({
"adapter"=> "postgresql",
"encoding"=> "unicode",
"gssencmode" => "disable",
"url" => ENV["NINEID_DATABASE_URL"] || "postgres://postgres:<EMAIL>:5432/etsy-uploader"
})
end
<file_sep>class MailContent < ApplicationRecord
paginates_per 200
# max_paginates_per 200
end
<file_sep>class PubidRecord < ActiveRecord::Base
self.abstract_class = true
establish_connection({
"adapter"=> "postgresql",
"encoding"=> "unicode",
"url" => ENV["NINEID_DATABASE_URL"] || "postgres://fqtrkvegusnpxs:<EMAIL>@ec2-54-75-235-28.eu-west-1.<EMAIL>:5432/debi3b41f3otv1"
})
end
<file_sep>class CreateMailContents < ActiveRecord::Migration[6.0]
def change
create_table :mail_contents do |t|
t.integer :account_id
t.string :message_id
t.string :from
t.string :to
t.string :cc
t.string :subject
t.text :text_part
t.text :html_part
t.datetime :created_at
t.boolean :is_multipart
t.boolean :is_read
end
add_index :mail_contents, :account_id
add_index :mail_contents, :message_id
add_index :mail_contents, :created_at
end
end
<file_sep>class AccountsController < ApplicationController
before_action :authenticate_user!
before_action :set_account, only: [:show, :edit, :update, :destroy, :check_mail]
def index
@accounts = Account.where(error: nil).where.not(last_checked_at: nil).order(:error).order(:id)
end
def show
@mails = MailContent.where(account_id: @account.id).order(created_at: :desc).limit(100)
end
def new
@account = Account.new
end
def edit
end
def create
@account = Account.new(account_params)
@account.save
redirect_to @account, notice: 'Account was successfully created.'
end
def update
@account.update(account_params)
redirect_to @account, notice: 'Account was successfully updated.'
end
def destroy
@account.destroy
redirect_to accounts_url, notice: 'Account was successfully destroyed.'
end
def check_mail
end
private
def set_account
@account = Account.find(params[:id])
end
def account_params
params.require(:account).permit(:email, :password)
end
end
<file_sep>class MailContentsController < ApplicationController
before_action :authenticate_user!
def index
@mails = MailContent.order(created_at: :desc).page params[:page]
end
def show
@mail = MailContent.find(params[:id])
end
end
<file_sep>class CreateAccounts < ActiveRecord::Migration[6.0]
def change
create_table :accounts do |t|
t.string :email
t.string :password
t.datetime :last_checked_at
t.integer :unread_count
t.string :error
t.string :heroku_app_name
t.integer :priority
end
add_index :accounts, :last_checked_at
add_index :accounts, :priority
add_index :accounts, :email
end
end
<file_sep>class Account < ApplicationRecord
before_save :validate_data_before_save
after_create :check_mail
def self.reassign_heroku_app_name
accounts = Account.where(error: nil)
heroku_app_names = HerokuApp.where(shared_ip: nil).order(:id).limit(accounts.count).pluck(:name)
accounts.each_with_index {|acc,i| acc.update(heroku_app_name: heroku_app_names[i])}
end
def check_mail keys="UNSEEN"
url = "http://#{self.heroku_app_name}.herokuapp.com/imap?email=#{self.email}&password=#{self.password}&address=#{self.imap_address}&keys=#{keys}"
r = RestClient.get url
res = JSON.parse(r.body).with_indifferent_access
if res[:results]
res[:results].each do |r|
if MailContent.find_by(message_id: r[:message_id]).nil?
MailContent.create(r.merge(account_id: self.id))
end
end
self.update(last_checked_at: Time.now) if !res[:results].empty?
end
if res[:error]
self.update(last_checked_at: Time.now, error: res[:error])
end
end
def imap_address
return "outlook.office365.com" if !self.email.index("@hotmail.").nil? || !self.email.index("@outlook.").nil?
return "imap.gmx.com" if !self.email.index("@gmx.com").nil?
end
private
def validate_data_before_save
if self.heroku_app_name.nil?
heroku_app_names = Account.where.not(heroku_app_name: nil).pluck(:heroku_app_name)
if heroku_app = HerokuApp.where(shared_ip: nil).where.not(name: heroku_app_names).first
self.heroku_app_name = heroku_app.name
end
end
end
end
<file_sep>namespace :email do
task :check => :environment do
Account.where("last_checked_at is not null and heroku_app_name is not null").order(:last_checked_at).each {|a| a.check_mail}
end
end
<file_sep>class HerokuApp < EtsyUploaderRecord
end
| 0a51f263bf760eb26156d6e1961bd608dc80b478 | [
"Ruby"
] | 10 | Ruby | quangpham/imap-checker | 306771cbccbee7dcda4d46c9f209aafeaf130298 | 5b5040087e80ea0cccda4f9b1397d41d052de9c9 |
refs/heads/master | <file_sep>package com.inthebytes.deliveryservice.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.inthebytes.deliveryservice.dto.DeliveryDto;
import com.inthebytes.deliveryservice.dto.DriverDto;
import com.inthebytes.deliveryservice.entity.Driver;
import com.inthebytes.deliveryservice.service.DeliveryService;
@RestController
@RequestMapping("/delivery")
@CrossOrigin(origins = {"http://localhost:4200", "http://localhost:3000"})
public class DeliveryController {
@Autowired
DeliveryService service;
@RequestMapping(path = "/start", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<DeliveryDto> startDelivery(@RequestBody String driverId, String orderId) {
ResponseEntity<DeliveryDto> response;
try {
DeliveryDto responseDto = service.start(driverId, orderId);
if (responseDto == null) {
response = new ResponseEntity<>(responseDto, HttpStatus.NOT_FOUND);
} else {
response = new ResponseEntity<>(responseDto, HttpStatus.OK);
}
} catch (Exception e) {
e.printStackTrace(System.out);
response = new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
return response;
}
@RequestMapping(path = "/pickup", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<DeliveryDto> pickup(@RequestBody String deliveryId) {
ResponseEntity<DeliveryDto> response;
try {
DeliveryDto responseDto = service.pickup(deliveryId);
if (responseDto == null) {
response = new ResponseEntity<>(responseDto, HttpStatus.NOT_FOUND);
} else {
response = new ResponseEntity<>(responseDto, HttpStatus.OK);
}
} catch (Exception e) {
e.printStackTrace(System.out);
response = new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
return response;
}
@RequestMapping(path = "/delivered", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<DeliveryDto> delivered(@RequestBody String deliveryId) {
ResponseEntity<DeliveryDto> response;
try {
DeliveryDto responseDto = service.delivered(deliveryId);
if (responseDto == null) {
response = new ResponseEntity<>(responseDto, HttpStatus.NOT_FOUND);
} else {
response = new ResponseEntity<>(responseDto, HttpStatus.OK);
}
} catch (Exception e) {
e.printStackTrace(System.out);
response = new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
return response;
}
@RequestMapping(path = "/checkIn", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<DriverDto> checkIn(@RequestBody String driverId) {
ResponseEntity<DriverDto> response;
try {
DriverDto responseDto = service.checkIn(driverId);
if (responseDto == null) {
response = new ResponseEntity<>(responseDto, HttpStatus.NOT_FOUND);
} else {
response = new ResponseEntity<>(responseDto, HttpStatus.OK);
}
} catch (Exception e) {
e.printStackTrace(System.out);
response = new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
return response;
}
@RequestMapping(path = "/checkOut", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<DriverDto> checkOut(@RequestBody String driverId) {
ResponseEntity<DriverDto> response;
try {
DriverDto responseDto = service.checkOut(driverId);
if (responseDto == null) {
response = new ResponseEntity<>(responseDto, HttpStatus.NOT_FOUND);
} else {
response = new ResponseEntity<>(responseDto, HttpStatus.OK);
}
} catch (Exception e) {
e.printStackTrace(System.out);
response = new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
return response;
}
@RequestMapping(path = "/drivers/new", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<DriverDto> newDriver(@RequestBody Driver driver) {
ResponseEntity<DriverDto> response;
try {
DriverDto responseDto = service.newDriver(driver);
if (responseDto == null) {
response = new ResponseEntity<>(responseDto, HttpStatus.NOT_FOUND);
} else {
response = new ResponseEntity<>(responseDto, HttpStatus.CREATED);
}
} catch (Exception e) {
e.printStackTrace(System.out);
response = new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
return response;
}
@RequestMapping(path = "/drivers/update", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<DriverDto> editDriver(@RequestBody Driver driver) {
ResponseEntity<DriverDto> response;
try {
DriverDto responseDto = service.editDriver(driver);
if (responseDto == null) {
response = new ResponseEntity<>(responseDto, HttpStatus.NOT_FOUND);
} else {
response = new ResponseEntity<>(responseDto, HttpStatus.CREATED);
}
} catch (Exception e) {
e.printStackTrace(System.out);
response = new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
return response;
}
}
<file_sep>package com.inthebytes.deliveryservice.dao;
import org.springframework.stereotype.Repository;
import com.inthebytes.deliveryservice.entity.Delivery;
import org.springframework.data.jpa.repository.JpaRepository;
@Repository
public interface DeliveryDao extends JpaRepository<Delivery, String> {
}
<file_sep>-- MySQL Script generated by MySQL Workbench
-- Thu Apr 1 20:57:45 2021
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
-- SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
-- SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
-- SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
-- -----------------------------------------------------
-- Schema stacklunch
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema stacklunch
-- -----------------------------------------------------
-- CREATE SCHEMA IF NOT EXISTS `stacklunch` ;
-- DEFAULT CHARACTER SET utf8 ;
-- USE `stacklunch` ;
-- -----------------------------------------------------
-- Table `role`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `role` (
`role_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`role_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `user` (
`user_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_role` INT UNSIGNED NOT NULL,
`username` VARCHAR(45) NOT NULL,
`password` VARCHAR(120) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`phone` VARCHAR(45) NOT NULL,
`first_name` VARCHAR(45) NOT NULL,
`last_name` VARCHAR(45) NOT NULL,
`active` SMALLINT NOT NULL,
PRIMARY KEY (`user_id`),
CONSTRAINT `fk_user_role_id`
FOREIGN KEY (`user_role`)
REFERENCES `role` (`role_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `confirmation` (
`token_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT UNSIGNED NOT NULL,
`confirmation_token` varchar(256) NOT NULL,
`created_date` datetime NOT NULL,
`is_confirmed` tinyINT UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`token_id`),
CONSTRAINT `fk_confirmation_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
) ENGINE=InnoDB;
-- -----------------------------------------------------
-- Table `menu`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `menu` (
`menu_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`menu_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `hours`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `hours` (
`hours_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`monday_open` TIME NULL,
`monday_close` TIME NULL,
`tuesday_open` TIME NULL,
`tuesday_close` TIME NULL,
`wednesday_open` TIME NULL,
`wednesday_close` TIME NULL,
`thursday_open` TIME NULL,
`thursday_close` TIME NULL,
`friday_open` TIME NULL,
`friday_close` TIME NULL,
`saturday_open` TIME NULL,
`saturday_close` TIME NULL,
`sunday_open` TIME NULL,
`sunday_close` TIME NULL,
PRIMARY KEY (`hours_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `restaurant`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `restaurant` (
`restaurant_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`manager_id` INT UNSIGNED NOT NULL,
`name` VARCHAR(45) NOT NULL,
`menu_id` INT UNSIGNED NOT NULL,
`hours_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`restaurant_id`),
CONSTRAINT `fk_restaurant_manager_id`
FOREIGN KEY (`manager_id`)
REFERENCES `user` (`user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_restaurant_menu_id`
FOREIGN KEY (`menu_id`)
REFERENCES `menu` (`menu_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_restaurant_hours_id`
FOREIGN KEY (`hours_id`)
REFERENCES `hours` (`hours_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `genre`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `genre` (
`genre_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`genre_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `restaurant_genre`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `restaurant_genre` (
`restaurant_id` INT UNSIGNED NOT NULL,
`genre_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`genre_id`, `restaurant_id`),
CONSTRAINT `fk_restgenre_restaurant_id`
FOREIGN KEY (`restaurant_id`)
REFERENCES `restaurant` (`restaurant_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_restgenre_genre_id`
FOREIGN KEY (`genre_id`)
REFERENCES `genre` (`genre_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `location`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `location` (
`location_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`street` VARCHAR(45) NOT NULL,
`street_addition` VARCHAR(45) NOT NULL,
`unit` VARCHAR(45) NOT NULL,
`city` VARCHAR(45) NOT NULL,
`state` VARCHAR(45) NOT NULL,
`zip_code` INT NOT NULL,
PRIMARY KEY (`location_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `user_location`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `user_location` (
`user_id` INT UNSIGNED NOT NULL,
`location_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`user_id`, `location_id`),
CONSTRAINT `fk_userloc_user_id`
FOREIGN KEY (`user_id`)
REFERENCES `user` (`user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_userloc_location_id`
FOREIGN KEY (`location_id`)
REFERENCES `location` (`location_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `restaurant_location`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `restaurant_location` (
`restaurant_id` INT UNSIGNED NOT NULL,
`location_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`restaurant_id`, `location_id`),
CONSTRAINT `fk_restloc_restaurant_id`
FOREIGN KEY (`restaurant_id`)
REFERENCES `restaurant` (`restaurant_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_restloc_location_id`
FOREIGN KEY (`location_id`)
REFERENCES `location` (`location_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `section`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `section` (
`section_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`section_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `food`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `food` (
`food_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`price` FLOAT UNSIGNED NOT NULL,
`description` VARCHAR(100) NOT NULL,
PRIMARY KEY (`food_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `section_food`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `section_food` (
`section_id` INT UNSIGNED NOT NULL,
`food_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`section_id`, `food_id`),
CONSTRAINT `fk_secfood_menu_id`
FOREIGN KEY (`section_id`)
REFERENCES `section` (`section_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_secfood_food_id`
FOREIGN KEY (`food_id`)
REFERENCES `food` (`food_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `menu_section`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `menu_section` (
`menu_id` INT UNSIGNED NOT NULL,
`section_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`menu_id`, `section_id`),
CONSTRAINT `fk_menusec_menu_id`
FOREIGN KEY (`menu_id`)
REFERENCES `menu` (`menu_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_menusec_section_id`
FOREIGN KEY (`section_id`)
REFERENCES `section` (`section_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `transaction`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `transaction` (
`transaction_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`payment_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`transaction_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `order`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `order` (
`order_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`resturant_id` INT UNSIGNED NOT NULL,
`transaction_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`order_id`),
CONSTRAINT `fk_order_transaction_id`
FOREIGN KEY (`transaction_id`)
REFERENCES `transaction` (`transaction_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `user_order`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `user_order` (
`user_id` INT UNSIGNED NOT NULL,
`order_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`user_id`, `order_id`),
CONSTRAINT `fk_userorder_user_id`
FOREIGN KEY (`user_id`)
REFERENCES `user` (`user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_userorder_order_id`
FOREIGN KEY (`order_id`)
REFERENCES `order` (`order_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `order_food`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `order_food` (
`order_id` INT UNSIGNED NOT NULL,
`food_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`order_id`, `food_id`),
CONSTRAINT `fk_orderfood_order_id`
FOREIGN KEY (`order_id`)
REFERENCES `order` (`order_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_orderfood_food_id`
FOREIGN KEY (`food_id`)
REFERENCES `food` (`food_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `driver`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `driver` (
`driver_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT UNSIGNED NOT NULL,
`vehicle_id` INT UNSIGNED NOT NULL,
`financial_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`driver_id`),
CONSTRAINT `fk_driver_user_id`
FOREIGN KEY (`user_id`)
REFERENCES `user` (`user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- SET SQL_MODE=@OLD_SQL_MODE;
-- SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
-- SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep>FROM openjdk:17
ADD target/deliveryservice-0.0.1-SNAPSHOT.jar DeliveryService.jar
EXPOSE 8080
ENTRYPOINT ["java","-Dspring.datasource.hikari.maximum-pool-size=1","-jar","DeliveryService.jar"]
<file_sep><<<<<<< HEAD
# account-service
Manage users login, sign up, and authorizatoin
=======
# delivery-service
Spring Microservice for handling delivery assignment and tracking orders from a driver's perspective
>>>>>>> f81faaaebb90a120608081d9734c3049b12d9014
<file_sep>INSERT INTO role (name)
VALUES ('Admin');
INSERT INTO user (user_role, username, password, email, phone, first_name, last_name, active)
VALUES (1, 'mosaab', '$2a$10$YMGP6L6Pv553Fr/0eSgPK.fMsD2iH87x5L17vCcx4HQXkiDAQDIM6', '<EMAIL>', '0000000000', 'Mosaab', 'A', 0);
INSERT INTO user (user_role, username, password, email, phone, first_name, last_name, active)
VALUES (1, 'verified', '$2a$10$YMGP6L6Pv553Fr/0eSgPK.fMsD2iH87x5L17vCcx4HQXkiDAQDIM6', '<EMAIL>', '0000000000', 'Verified', 'U', 1);
INSERT INTO user (user_role, username, password, email, phone, first_name, last_name, active)
VALUES (1, 'waiting', '$2a$10$YMGP6L6Pv553Fr/0eSgPK.fMsD2iH87x5L17vCcx4HQXkiDAQDIM6', '<EMAIL>', '0000000000', 'Waiting', 'V', 0);
INSERT INTO confirmation (confirmation_token, user_id, created_date, is_confirmed)
VALUES ('123', 2, '2021-04-06 11:00:00', 1);
INSERT INTO confirmation (confirmation_token, user_id, created_date, is_confirmed)
VALUES ('validtoken', 3, NOW(), 0);
| e2c60de5764f528812dabe90706205df97de71bb | [
"Markdown",
"Java",
"Dockerfile",
"SQL"
] | 6 | Java | InTheBytes/delivery-service | 6b4378a17eecd18ef5cb20eea4040d2cd24df4f6 | b65c0dc31edd04bb03cee42beef681d61fe78a4b |
refs/heads/master | <file_sep># Green-AI
### Humans are really bad at recycling.
We are here to help!
Know if your trash is recyclable or not while also reducing cross-contamination.
This project was created for MakeSPP 2020
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="privacy.css" rel="stylesheet" type="text/css" />
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="icon" href="./logo.png" type="image/icon">
<title>Privacy Policy</title>
</head>
<body>
<nav class="navbar">
<img class ='logo' src="logo.png">
<ul class="elements">
<li class="nav-el"><a class="normal" href='/'>HOME</a></li>
<li class="nav-el"><a class="normal" href="start.html">START</a></li>
<li class="nav-el"><a class="normal" href="about.html">ABOUT</a></li>
<li class="nav-el current"><a class="normal" href="privacy.html">PRIVACY</a></li>
</ul>
<div class="burgerDiv">
<div class="rows">
<div class="span"></div>
<div class="span"></div>
<div class="span"></div>
</div>
</div>
</nav>
<div class="privacy-main">
<p class="privacy-title">Privacy Policy for Green AI</p>
<br>
<br>
<p>At Green AI, accessible from greenai.com, one of our main priorities is the privacy of our visitors. This Privacy Policy document contains types of information that is collected and recorded by Green AI and how we use it. If you have additional questions or require more information about our Privacy Policy, do not hesitate to contact us. This Privacy Policy applies only to our online activities and is valid for visitors to our website with regards to the information that they shared and/or collect in Green AI. This policy is not applicable to any information collected offline or via channels other than this</p>
<br>
<br>
<h2>Information we collect</h2>
<br>
<p>The personal information that you are asked to provide, and the reasons why you are asked to provide it, will be made clear to you at the point we ask you to provide your personal information. If you contact us directly, we may receive additional information about you such as your name, email address, phone number, the contents of the message and/or attachments you may send us, and any other information you may choose to provide. When you register for an Account, we may ask for your contact information, including items such as name, company name, address, email address, and telephone number.</p>
<br>
<br>
<h2>How we use your information</h2>
<br>
<p>We use the information we collect in various ways, including to:</p>
<br>
<ul>
<li>- Provide, operate, and maintain our webste</li>
<br>
<li>- Improve, personalize, and expand our webste</li>
<br>
<li>- Understand and analyze how you use our webste</li>
<br>
<li>- Develop new products, services, features, and functionality</li>
<br>
<li>- Communicate with you, either directly or through one of our partners, including for customer service, to provide you with updates and other information relating to the webste, and for marketing and promotional purposes</li>
<br>
<li>- Send you emails</li>
<br>
<li>- Find and prevent fraud</li>
</ul>
<br>
<br>
<h2>Log Files</h2>
<br>
<p>Green AI follows a standard procedure of using log files. These files log visitors when they visit websites. All hosting companies do this and a part of hosting services' analytics. The information collected by log files include internet protocol (IP) addresses, browser type, Internet Service Provider (ISP), date and time stamp, referring/exit pages, and possibly the number of clicks. These are not linked to any information that is personally identifiable. The purpose of the information is for analyzing trends, administering the site, tracking users' movement on the website, and gathering demographic information.</p>
<br>
<br>
<h2>Cookies and Web Beacons</h2>
<br>
<p>Like any other website, Green AI uses 'cookies'. These cookies are used to store information including visitors' preferences, and the pages on the website that the visitor accessed or visited. The information is used to optimize the users' experience by customizing our web page content based on visitors' browser type and/or other information.</p>
<br>
<p>For more general information on cookies, please read <a href="https://www.cookieconsent.com/what-are-cookies/">"What Are Cookies"</a>.</p><br>
<br>
<br>
<h2>Advertising Partners Privacy Policies</h2>
<br>
<p>You may consult this list to find the Privacy Policy for each of the advertising partners of Green AI. Third-party ad servers or ad networks uses technologies like cookies, JavaScript, or Web Beacons that are used in their respective advertisements and links that appear on Green AI, which are sent directly to users' browser. They automatically receive your IP address when this occurs. These technologies are used to measure the effectiveness of their advertising campaigns and/or to personalize the advertising content that you see on websites that you visit. Note that Green AI has no access to or control over these cookies that are used by third-party advertisers.</p>
<br>
<br>
<h2>Third Party Privacy Policies</h2>
<br>
<p>Green AI's Privacy Policy does not apply to other advertisers or websites. Thus, we are advising you to consult the respective Privacy Policies of these third-party ad servers for more detailed information. It may include their practices and instructions about how to opt-out of certain options. You can choose to disable cookies through your individual browser options. To know more detailed information about cookie management with specific web browsers, it can be found at the browsers' respective websites.</p>
<br>
<br>
<h2>CCPA Privacy Rights (Do Not Sell My Personal Information)</h2>
<br>
<p>Under the CCPA, among other rights, California consumers have the right to:</p>
<br>
<ul>
<li>- Request that a business that collects a consumer's personal data disclose the categories and specific pieces of personal data that a business has collected about consumers.</li>
<br>
<li>- Request that a business delete any personal data about the consumer that a business has collected.</li>
<br>
<li>- Request that a business that sells a consumer's personal data, not sell the consumer's personal data.</li>
<br>
<li>- If you make a request, we have one month to respond to you. If you would like to exercise any of these rights, please contact us.</li>
</ul>
<br>
<br>
<h2>GDPR Data Protection Rights</h2>
<br>
<p>We would like to make sure you are fully aware of all of your data protection rights. Every user is entitled to the following:</p>
<br>
<ul>
<li>- The right to access – You h<ave the right to request copies of your personal data. We may charge you a small fee for this service.</li>
<br>
<li>- The right to rectification – You have the right to request that we correct any information you believe is inaccurate. You also have the right to request that we complete the information you believe is incomplete.</li>
<br>
<li>- The right to erasure – You have the right to request that we erase your personal data, under certain conditions.</li>
<br>
<li>- The right to restrict processing – You have the right to request that we restrict the processing of your personal data, under certain conditions.</li>
<br>
<li>- The right to object to processing – You have the right to object to our processing of your personal data, under certain conditions.</li>
<br>
<li>- The right to data portability – You have the right to request that we transfer the data that we have collected to another organization, or directly to you, under certain conditions.</li>
<br>
<li>- If you make a request, we have one month to respond to you. If you would like to exercise any of these rights, please contact us.</li>
</ul>
<br>
<br>
<h2>Children's Information</h2>
<br>
<p>Another part of our priority is adding protection for children while using the internet. We encourage parents and guardians to observe, participate in, and/or monitor and guide their online activity. Green AI does not knowingly collect any Personal Identifiable Information from children under the age of 13. If you think that your child provided this kind of information on our website, we strongly encourage you to contact us immediately and we will do our best efforts to promptly remove such information from our records.</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html><file_sep>const URL = "https://teachablemachine.withgoogle.com/models/mLhDa6ugX/";
let model, webcam, labelContainer, maxPredictions;
const text = document.querySelector(".text-display");
async function init() {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
const flip = true;
webcam = new tmImage.Webcam(350, 350, flip);
await webcam.setup();
await webcam.play();
window.requestAnimationFrame(loop);
document.getElementById("webcam-container").appendChild(webcam.canvas);
labelContainer = document.getElementById("label-container");
for (let i = 0; i < maxPredictions; i++) {
labelContainer.appendChild(document.createElement("div"));
}
}
async function loop() {
webcam.update();
await predict();
window.requestAnimationFrame(loop);
}
async function predict() {
const prediction = await model.predict(webcam.canvas);
for (let i = 0; i < maxPredictions; i++) {
const classPrediction =
prediction[i].className + ": " + (prediction[i].probability.toFixed(2) * 100) + "%";
labelContainer.childNodes[i].innerHTML = classPrediction;
}
if (prediction[1].probability > 0.5) {
text.innerHTML = "This item is not recyclable.";
} else if (prediction[1].probability < 0.5) {
text.innerHTML = "This item is recyclable.";
}
}
| 2f8df40b54e1a4f1a3b259e55db2996c00f2376c | [
"Markdown",
"JavaScript",
"HTML"
] | 3 | Markdown | faisalsayed10/Green-AI | 510d8d7edd40b20043b5b273c6a971d4d180be02 | ed5e343f9282406d7a4b26801b5a679eddd1078d |
refs/heads/master | <repo_name>SakalOFF/lab4<file_sep>/lab4.py
import random
import scipy.stats
from prettytable import PrettyTable
from numpy.linalg import solve
x1min = -25
x1max = 75
x2min = 25
x2max = 65
x3min = 25
x3max = 40
xAvmax = (x1max + x2max + x3max) / 3
xAvmin = (x1min + x2min + x3min) / 3
ymax = int(200 + xAvmax)
ymin = int(200 + xAvmin)
m = 4
Xi = [[1, 1, 1, 1, 1, 1, 1, 1],
[-1, -1, -1, -1, 1, 1, 1, 1],
[-1, -1, 1, 1, -1, -1, 1, 1],
[-1, 1, -1, 1, -1, 1, -1, 1],
[1, 1, -1, -1, -1, -1, 1, 1],
[1, -1, 1, -1, -1, 1, -1, 1],
[1, -1, -1, 1, 1, -1, -1, 1],
[-1, 1, 1, -1, 1, -1, -1, 1]]
def sumkf2(x1, x2):
return [x1[i] * x2[i] for i in range(len(x1))]
def sumkf3(x1, x2, x3):
return [x1[i] * x2[i] * x3[i] for i in range(len(x1))]
X12 = sumkf2(Xi[1], Xi[2])
X13 = sumkf2(Xi[1], Xi[3])
X23 = sumkf2(Xi[2], Xi[3])
X123 = sumkf3(Xi[1], Xi[2], Xi[3])
X8 = list(map(lambda el: el * el, Xi[1]))
X9 = list(map(lambda el: el * el, Xi[2]))
X10 = list(map(lambda el: el * el, Xi[3]))
print("___________Таблиця кодованих значень_________")
table1 = PrettyTable()
table1.add_column("№", (1, 2, 3, 4, 5, 6, 7, 8))
table1.add_column("X1", Xi[1])
table1.add_column("X2", Xi[2])
table1.add_column("X3", Xi[3])
table1.add_column("X12", X12)
table1.add_column("X13", X13)
table1.add_column("X23", X23)
table1.add_column("X123", X123)
print(table1)
Y = [[random.randrange(ymin, ymax, 1) for _ in range(8)] for __ in range(m)]
X1 = [x1min, x1min, x1min, x1min, x1max, x1max, x1max, x1max]
X2 = [x2min, x2min, x2max, x2max, x2min, x2min, x2max, x2max]
X3 = [x3min, x3max, x3min, x3max, x3min, x3max, x3min, x3max]
X12 = sumkf2(X1, X2)
X13 = sumkf2(X1, X3)
X23 = sumkf2(X2, X3)
X123 = sumkf3(X1, X2, X3)
X0 = [1] * 8
s = [sum([Y[i][j] for i in range(m)]) for j in range(8)]
yav = [round(s[i] / m, 3) for i in range(8)]
sd = [sum([((Y[i][j]) - yav[j]) ** 2 for i in range(m)]) for j in range(8)]
d = [sd[i] / m for i in range(8)]
disper = [round(d[i], 3) for i in range(8)]
print("\n_________________________________Таблиця нормованих факторів___________________________________")
table2 = PrettyTable()
table2.add_column("№", (1, 2, 3, 4, 5, 6, 7, 8))
table2.add_column("X1", X1)
table2.add_column("X2", X2)
table2.add_column("X3", X3)
table2.add_column("X12", X12)
table2.add_column("X13", X13)
table2.add_column("X23", X23)
table2.add_column("X123", X123)
for i in range(m):
table2.add_column("Y" + str(i+1), Y[i])
table2.add_column("Y", yav)
table2.add_column("S^2", disper)
print(table2)
b = [round(i, 3) for i in solve(list(zip(X0, X1, X2, X3, X12, X13, X23, X123)), yav)]
m = 3
Gp = max(d) / sum(d)
q = 0.05
f1 = m - 1
f2 = N = 8
fisher = scipy.stats.f.isf(*[q / f2, f1, (f2 - 1) * f1])
Gt = fisher / (fisher + (f2 - 1))
if Gp < Gt:
print("Дисперсія однорідна")
print("\n______Критерій Стьюдента_______")
sb = sum(d) / N
ssbs = sb / N * m
sbs = ssbs ** 0.5
beta = [sum([yav[j] * Xi[i][j] for j in range(8)]) / 8 for i in range(8)]
t = [abs(beta[i]) / sbs for i in range(8)]
f3 = f1 * f2
ttabl = round(abs(scipy.stats.t.ppf(q / 2, f3)), 4)
d_ = 8
for i in range(8):
if t[i] < ttabl:
print(f"t{i} < ttabl, b{i} не значимий")
b[i] = 0
d_ -= 1
else:
print(f"t{i} > ttabl, b{i} значимий")
print("\nКількість значимих коефіцієнтів:", d_)
print("Кількість не значимих коефіцієнтів:", 8 - d_)
yy1 = b[0] + b[1] * x1min + b[2] * x2min + b[3] * x3min + b[4] * x1min * x2min + b[5] * x1min * x3min + b[6] * x2min * x3min + b[7] * x1min * x2min * x3min
yy2 = b[0] + b[1] * x1min + b[2] * x2min + b[3] * x3max + b[4] * x1min * x2min + b[5] * x1min * x3max + b[6] * x2min * x3max + b[7] * x1min * x2min * x3max
yy3 = b[0] + b[1] * x1min + b[2] * x2max + b[3] * x3min + b[4] * x1min * x2max + b[5] * x1min * x3min + b[6] * x2max * x3min + b[7] * x1min * x2max * x3min
yy4 = b[0] + b[1] * x1min + b[2] * x2max + b[3] * x3max + b[4] * x1min * x2max + b[5] * x1min * x3max + b[6] * x2max * x3max + b[7] * x1min * x2max * x3max
yy5 = b[0] + b[1] * x1max + b[2] * x2min + b[3] * x3min + b[4] * x1max * x2min + b[5] * x1max * x3min + b[6] * x2min * x3min + b[7] * x1max * x2min * x3min
yy6 = b[0] + b[1] * x1max + b[2] * x2min + b[3] * x3max + b[4] * x1max * x2min + b[5] * x1max * x3max + b[6] * x2min * x3max + b[7] * x1max * x2min * x3max
yy7 = b[0] + b[1] * x1max + b[2] * x2max + b[3] * x3min + b[4] * x1max * x2max + b[5] * x1max * x3min + b[6] * x2max * x3min + b[7] * x1max * x2min * x3max
yy8 = b[0] + b[1] * x1max + b[2] * x2max + b[3] * x3max + b[4] * x1max * x2max + b[5] * x1max * x3max + b[6] * x2max * x3max + b[7] * x1max * x2max * x3max
print("\n____________Критерій Фішера_______________________________________________")
f4 = N - d_
sad = ((yy1 - yav[0]) ** 2 + (yy2 - yav[1]) ** 2 + (yy3 - yav[2]) ** 2 + (yy4 - yav[3]) ** 2 + (yy5 - yav[4]) ** 2 + (
yy6 - yav[5]) ** 2 + (yy7 - yav[6]) ** 2 + (yy8 - yav[7]) ** 2) * (m / (N - d_))
Fp = sad / sb
Ft = abs(scipy.stats.f.isf(q, f4, f3))
if Fp > Ft:
print("Fp = {:.2f} > Ft = {:.2f} Рівняння неадекватно оригіналу,(збільшемо m)".format(Fp, Ft))
m += 1
else:
print("Fp = {:.2f} < Ft = {:.2f} Рівняння адекватно оригіналу".format(Fp, Ft))
else:
print("Дисперсія неоднорідна (збільшемо кількість дослідів)")
m += 1
print("\n__________Рівняння регресії з ефектом взаємодії__________")
print("y = {} + {}*x1 + {}*x2 + {}*x3 + {}*x1*x2 + {}*x1*x3 + {}*x2*x3 + {}*x1*x2*x3".format(*b))
| 346d0bf737d4176b8aa7935ddd028400413c275c | [
"Python"
] | 1 | Python | SakalOFF/lab4 | 46d6e780e7b434c296bdcb371a9e41bd20926f11 | 2a3c03eb931cde1961c752304f4783044adcd064 |
refs/heads/master | <repo_name>Abirvalgg/hns<file_sep>/src/router.js
import Vue from 'vue'
import Router from 'vue-router'
import Blank from './views/Blank.vue'
import Projects from './views/Projects.vue'
import Reports from './views/Reports.vue'
import Team from './views/Team.vue'
import Gtd from './views/Gtd.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'blank',
component: Blank
},
{
path: '/projects',
name: 'projects',
component: Projects
},
{
path: '/reports',
name: 'reports',
component: Reports
},
{
path: '/team',
name: 'team',
component: Team
},
{
path: '/gtd',
name: 'gtd',
component: Gtd
},
]
})
// { icon: 'dashboard', text: 'Расписание', route: '/' },
// { icon: 'book', text: 'Мои группы', route: '/projects' },
// { icon: 'person', text: 'Что-то', route: '/team' },
// { icon: 'assignment_turned_in', text: 'Отчеты', route: '/reports' }, | 78a562cf72a7c1059de0410acc2ea36b883a80c1 | [
"JavaScript"
] | 1 | JavaScript | Abirvalgg/hns | 1c82b04883dd0855adc3343834f334483f2acd2a | 415205413c3ca11fa86975cc99fd1e554a64e244 |
refs/heads/master | <file_sep>OPEN_WEATHER_API_KEY = "<KEY>"
<file_sep><h1>Sunshine</h1>
A simple weather GUI app with Tkinter that fetches weather data from openweather map API
How to use it?
1. Extract the zip and open python weather.py from terminal
Setup Instructions:
1. Make sure python 3.5.x is installed in your machine.
2. Feel free to clone this repo.
3. Install packages like Pillow(latest Version). In case of windows user install cx_Freeze(check the latest version) to make .exe using build
Steps to build .exe file:
1. Open terminal with the same directory of the project
2. Make sure you make a setup.py file for build. Check online for more details
3. After you have made setup.py. Type this - python setup.py build
### Few Screenshots:


| 3865260d90ac93b4f7821efb48eec5ddc34270f9 | [
"Markdown",
"Python"
] | 2 | Python | shadowdevcode/Weather-GUI-App | 9e14e90d9ab34f8b1a51ee83f5a79df7326be76b | cb6e8d0e8b5180f4f631e63a80784e21664690da |
refs/heads/master | <repo_name>green-fox-academy/tothlilla<file_sep>/opencv_practice/image_contrast.cpp
#include "practiceWeekHeader.h"
void changeImageContrastWithOperators(cv::Mat originImg)
{
cv::Mat contrastImg = originImg * 2;
cv::namedWindow("image5", cv::WINDOW_AUTOSIZE);
cv::moveWindow("image5", 500, 280);
cv::imshow("image5", contrastImg);
}
void changeImageContrastWithConvertTo(cv::Mat originImg)
{
cv::Mat contrastImg;
originImg.convertTo(contrastImg, -1, 0.5, 0);
cv::namedWindow("image6", cv::WINDOW_AUTOSIZE);
cv::moveWindow("image6", 500, 560);
cv::imshow("image6", contrastImg);
//--------HINT-----
//image.convertTo(new_image, -1, alpha, beta);
//double alpha contrast
//int beta brightness
}
void changeImageContrastPixelByPixel(cv::Mat originImg) {
//Initial pixel values equal to zero, same size and type as the original image
cv::Mat contrastImg = cv::Mat::zeros(originImg.size(), originImg.type());
double alpha = 200;
for (int y = 0; y < originImg.rows; y++) {
for (int x = 0; x < originImg.cols; x++) {
for (int c = 0; c < originImg.channels(); c++) {
contrastImg.at<cv::Vec3b>(y, x)[c] = cv::saturate_cast<uchar>(alpha * originImg.at<cv::Vec3b>(y, x)[c]);
}
}
}
cv::namedWindow("image7", cv::WINDOW_AUTOSIZE);
cv::moveWindow("image7", 1000, 0);
cv::imshow("image7", contrastImg);
}<file_sep>/week-08/function_templates_SKELETON/timer_init.c
#include "interruption_templates.h"
//task variables
//uint16_t tim_val = 0; /* variable to store the actual value of the timer's register (CNT) */
//uint16_t seconds = 0; /* variable to store the value of ellapsed seconds */
//tim_val = __HAL_TIM_GET_COUNTER(&tim);
//if (tim_val == 0) {}
//if (tim_val == 1000) {}
void timer_init(void)
{
__HAL_RCC_TIM2_CLK_ENABLE(); // we need to enable the TIM2
tim.Instance = TIM2;
tim.Init.Prescaler = 54000 - 1; /* 108000000/54000=2000 -> speed of 1 count-up: 1/2000 sec = 0.5 ms */
tim.Init.Period = 2000 - 1; /* 2000 x 0.5 ms = 1 second period */
tim.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
tim.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_Base_Init(&tim); // configure the timer
HAL_TIM_Base_Start(&tim); // starting the timer
}
void init_timer(void) {
__HAL_RCC_TIM2_CLK_ENABLE();
HAL_TIM_Base_DeInit(&tim_handle);
__HAL_TIM_SET_COUNTER(&tim_handle, 0);
tim_handle.Instance = TIM2;
tim_handle.Init.Prescaler = 54000 - 1; /* 108000000/54000=2000 -> speed of 1 count-up: 1/2000 sec = 0.5 ms */
tim_handle.Init.Period = 12000 - 1; /* 6000 x 0.5 ms = 6 second period */
tim_handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
tim_handle.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_Base_Init(&tim_handle); // configure the timer
HAL_NVIC_SetPriority(TIM2_IRQn, 1, 0); // assign the highest priority to our interrupt line
HAL_NVIC_EnableIRQ(TIM2_IRQn); // /* tell the interrupt handling unit to process our interrupts */
}
<file_sep>/week-04/day-3/LessonPractice_1/circle.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef LESSONPRACTICE_1_CIRCLE_H
#define LESSONPRACTICE_1_CIRCLE_H
#include "shape.h"
class Circle : public Shape {
int radius;
public:
Circle(int x, int y, int rad);
double circumference();
double area();
};
#endif //LESSONPRACTICE_1_CIRCLE_H
<file_sep>/week-01/day-3/Ex_34_ParametricAver/main.cpp
#include <iostream>
int main(int argc, char* args[])
{
// Write a program that asks for a number.
// It would ask this many times to enter an integer,
// if all the integers are entered, it should print the sum and average of these
// integers like:
//
// Sum: 22, Average: 4.4
float numb;
int sum = 0;
std::cout << "Number of numbers :" << std::endl;
std::cin >> numb;
for (int i = 0; i < numb ; ++i) {
std::cout << "Print your numb :" << std::endl;
int temp_sum;
std::cin >> temp_sum;
sum = sum + temp_sum;
}
std::cout << "Sum: " << sum << " " << "Average: " << sum / numb << std::endl;
return 0;
}<file_sep>/week-08/function_templates_SKELETON/uart_init.c
#include "interruption_templates.h"
//init printf() function
#include <string.h>
#define UART_PUTCHAR int __io_putchar(int ch)
UART_PUTCHAR
{
HAL_UART_Transmit(&uart, (uint8_t*)&ch, 1, 0xFFFF);
return ch;
}
void init_GPIO_BSP_uart()
{
//init uart for GPIO purpose with BSP
/* enable GPIO clock for A and B port*/
__HAL_RCC_USART1_CLK_ENABLE();
/* defining the UART configuration structure */
uart.Instance = USART1;
uart.Init.BaudRate = 115200;
uart.Init.WordLength = UART_WORDLENGTH_8B;
uart.Init.StopBits = UART_STOPBITS_1;
uart.Init.Parity = UART_PARITY_NONE;
uart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
uart.Init.Mode = UART_MODE_TX_RX;
BSP_COM_Init(COM1, &uart);
}
void init_GPIO_uart()
{
//init uart for GPIO purpose with HAL
//PA9 port 9 pin with AF7 alternate function means USART1_TX - no visible/connecting pin
//PB9 port 7 pint with AF7 alternate function means USART1_RX - no visible/connecting pin
/* enable GPIO clock for A and B port*/
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/* configure GPIO for UART transmit line */
GPIOTxConfig.Pin = GPIO_PIN_9; //chose PA port 9 pin
GPIOTxConfig.Mode = GPIO_MODE_AF_PP;
GPIOTxConfig.Pull = GPIO_NOPULL;
GPIOTxConfig.Speed = GPIO_SPEED_FAST;
GPIOTxConfig.Alternate = GPIO_AF7_USART1;
HAL_GPIO_Init(GPIOA, &GPIOTxConfig);
/* configure GPIO for UART receive line */
GPIORxConfig.Pin = GPIO_PIN_7;
GPIORxConfig.Mode = GPIO_MODE_AF_PP;
GPIOTxConfig.Pull = GPIO_NOPULL;
GPIORxConfig.Speed = GPIO_SPEED_FAST;
GPIORxConfig.Alternate = GPIO_AF7_USART1;
HAL_GPIO_Init(GPIOB, &GPIORxConfig);
/* enable the clock of the used peripherial instance */
__HAL_RCC_USART1_CLK_ENABLE();
/* defining the UART configuration structure */
uart.Instance = USART1;
uart.Init.BaudRate = 115200;
uart.Init.WordLength = UART_WORDLENGTH_8B;
uart.Init.StopBits = UART_STOPBITS_1;
uart.Init.Parity = UART_PARITY_NONE;
uart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
uart.Init.Mode = UART_MODE_TX_RX;
HAL_UART_Init(&uart);
}
//init uart for interrupt handle with BSP
void init_uart(void)
{
__HAL_RCC_USART1_CLK_ENABLE(); //giving clock
/* defining the UART configuration structure */
uart_handle.Instance = USART1;
uart_handle.Init.BaudRate = 115200;
uart_handle.Init.WordLength = UART_WORDLENGTH_8B;
uart_handle.Init.StopBits = UART_STOPBITS_1;
uart_handle.Init.Parity = UART_PARITY_NONE;
uart_handle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
uart_handle.Init.Mode = UART_MODE_TX_RX;
//uart_handle.Init.Mode = UART_MODE_TX;
//uart_handle.Init.Mode = UART_MODE_RX;
BSP_COM_Init(COM1, &uart_handle); //init USART
HAL_NVIC_SetPriority(USART1_IRQn, 3, 0); //set USART interrupt priority
HAL_NVIC_EnableIRQ(USART1_IRQn); //enable the interrupt to HAL
}
<file_sep>/week-06/day-1/Ex_26_position/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_26_position)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_26_position main.cpp)<file_sep>/week-01/day-3/Ex_28_DrawTriangle/main.cpp
#include <iostream>
int main(int argc, char* args[]) {
// Write a program that reads a number from the standard input, then draws a
// triangle like this:
//
// *
// **
// ***
// ****
//
// The triangle should have as many lines as the number was
int tringleRow;
std::string starBase= "*";
std::string star= "*";
std::cout << "Write how many rows should the tringle have: " << std::endl;
std::cin >> tringleRow;
for (int i = 0; i < tringleRow; ++i) {
std::cout << starBase << std::endl;
starBase = starBase + star;
}
return 0;
}<file_sep>/week-03/day-2/Ex_11_Sharpie_set/SharpieSet.h
//
// Created by Lilla on 2019. 02. 01..
//
#ifndef EX_11_SHARPIE_SET_SHARPIESET_H
#define EX_11_SHARPIE_SET_SHARPIESET_H
#include <vector>
#include <iostream>
#include "Sharpie.h"
class sharpieSet
{
public:
sharpieSet(std::vector<Sharpie> something);
int countUsable();
void removeTrash();
private:
std::vector<Sharpie> sharpies;
};
#endif //EX_11_SHARPIE_SET_SHARPIESET_H
<file_sep>/opencv_practice/image_blend.cpp
#include "practiceWeekHeader.h"
void blendImagesWithAddWeighted()
{
cv::Mat src1, src2, dst;
src1 = cv::imread("uranus.jpg");
src2 = cv::imread("lena.jpg");
cv::namedWindow("Linear Blend", cv::WINDOW_AUTOSIZE);
cv::resize(src1, src1, src2.size());
cv::moveWindow("Linear Blend", 1000, 280);
double alpha = 0.2;
double beta = (1.0 - alpha);
cv::addWeighted(src1, alpha, src2, beta, 0.0, dst);
cv::imshow("Linear Blend", dst);
}
<file_sep>/opencv_practice/image_brightness.cpp
#include "practiceWeekHeader.h"
void changeImageBrightnessWithScalar(cv::Mat originImg)
{
cv::Mat brightImg = originImg + cv::Scalar(75, 75, 75);
cv::namedWindow("image2", cv::WINDOW_AUTOSIZE);
cv::moveWindow("image2", 0, 280);
cv::imshow("image2", brightImg);
}
void changeImageBrightnessWithConvertTo(cv::Mat originImg)
{
cv::Mat brightImg;
originImg.convertTo(brightImg, -1, 1, -205);
cv::namedWindow("image3", cv::WINDOW_AUTOSIZE);
cv::moveWindow("image3", 0, 560);
cv::imshow("image3", brightImg);
//--------HINT-----
//image.convertTo(new_image, -1, alpha, beta);
//double alpha contrast
//int beta brightness
}
void changeImageBrightnessPixelByPixel(cv::Mat originImg) {
//Initial pixel values equal to zero, same size and type as the original image
cv::Mat brightImg = cv::Mat::zeros(originImg.size(), originImg.type());
int beta = 200;
for (int y = 0; y < originImg.rows; y++) {
for (int x = 0; x < originImg.cols; x++) {
for (int c = 0; c < originImg.channels(); c++) {
brightImg.at<cv::Vec3b>(y, x)[c] = cv::saturate_cast<uchar>(originImg.at<cv::Vec3b>(y, x)[c] + beta);
}
}
}
cv::namedWindow("image4", cv::WINDOW_AUTOSIZE);
cv::moveWindow("image4", 500, 0);
cv::imshow("image4", brightImg);
}
<file_sep>/week-02/day-1/Ex_14_hewillnever/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_14_hewillnever)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_14_hewillnever main.cpp)<file_sep>/week-01/day-4/Ex_07_Third/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_Third)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_07_Third main.cpp)<file_sep>/google_test_practice/test.cpp
#include "pch.h"
#include "../try_linking/doubleNum.cpp"
TEST(DoubleNumTest, PositiveValues)
{
ASSERT_EQ(12, doubleNum(6));
ASSERT_EQ(4, doubleNum(2));
ASSERT_EQ(40, doubleNum(20));
}
TEST(DoubleNumTest, NegativeValues)
{
ASSERT_EQ(-12, doubleNum(-6));
ASSERT_EQ(-4, doubleNum(-2));
ASSERT_EQ(-40, doubleNum(-20));
}
TEST(TestCaseName, TestName)
{
EXPECT_EQ(1, 1);
EXPECT_TRUE(true);
}<file_sep>/week-02/day-2/Ex_05_print_addresses/main.cpp
#include <iostream>
int main()
{
int a;
int mynumbers[5];
std::cout << "Write 5 numbers: " <<std::endl;
for (int i = 0; i < 5; i++) { // Create a program which accepts five integers from the console (given by the user)
std::cin >> a; // and store them in an array
mynumbers[i] = a;
}
int *mynumbersPtr = mynumbers;
for (int i = 0; i < 5; i++) {
std::cout << mynumbersPtr <<std::endl; // print out the memory addresses of the elements in the array
++mynumbersPtr;
}
return 0;
}
<file_sep>/week-04/day-1/ExBefInheritance/mentor.h
//
// Created by Lilla on 2019. 02. 03..
//
#ifndef EXBEFINHERITANCE_MENTOR_H
#define EXBEFINHERITANCE_MENTOR_H
#include <string>
#include "person.h"
//#include "gender.h"
class Mentor {
public:
Mentor(std::string name, int age, Gender gender, std::string level);
Mentor();
void introduce();
void getGoal();
std::string _name;
int _age;
Gender _gender;
std::string _level;
private:
};
#endif //EXBEFINHERITANCE_MENTOR_H
<file_sep>/week-02/day-2/Ex_08_look_for_maximum/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_08_look_for_maximum)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_08_look_for_maximum main.cpp)<file_sep>/week-06/day-1/Ex_20_isInSentence/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int is_in_sentence(int *word, int *sentence);
int main()
{
// Create a function which takes two strings as parameters
// One string is actually a sentence and the other one is a word
// It should return 1 if the given sentence contains the given word
// and 0 otherwise
// Try to erase small and uppercase sensitivity.
char *word = "apple";
char *sentence = "An Apple a day keeps the doctor away.";
// the output should be: 1
printf("The result is %d", is_in_sentence(&word, &sentence));
return 0;
}
int is_in_sentence(int *word, int *sentence)
{
int sizestr1 = strlen(*sentence) + 1;
int sizestr2 = strlen(*word) + 1;
char word_copy[sizestr2];
char sentence_copy[sizestr1];
//copy origingal string into a new array
strcpy(word_copy, *word);
strcpy(sentence_copy, *sentence);
//checking the result of copy
//printf("%s\n", word_copy); //checking the result of strcpy()
//printf("%s\n", sentence_copy); //checking the result of strcpy()
//modifying the copy strings by toupper()
for (int i = 0; i <sizestr1 ; ++i) {
sentence_copy[i] = toupper(sentence_copy[i]);
}
for (int i = 0; i <sizestr2 ; ++i) {
word_copy[i] = toupper(word_copy[i]);
}
//checking the result of toupper()
//printf("%s\n", word_copy); //checking the result of toupper()
//printf("%s\n", sentence_copy); //checking the result of toupper()
//making the comparision
char *ret = strstr(sentence_copy, word_copy);
if (sizestr1 == sizestr2){
return - 1;
} else if (ret != NULL){
return 1;
} else {
return 0;
}
}<file_sep>/week-02/day-3/Ex_07_Logs/main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
std::vector<std::string> ipAddress(std::string fileName){
std::ifstream myFile;
myFile.open(fileName);
std::string line;
std::vector<std::string> myVector;
while(std::getline(myFile, line)){
std::istringstream ss(line);
std::string expressions;
int counter = 0;
while (std::getline(ss, expressions, ' ')){
if (counter == 8){
if (std::find (myVector.begin(), myVector.end(), expressions) == myVector.end()){ // find végignézi elejétől a végéig
//ha elmegy a végéig kilépés nélkül, akkor nem találta meg a kifejezést, ezért ozzá lehet fűzni a vector-hoz
myVector.push_back(expressions);
}
}
counter ++;
}
}
myFile.close();
return myVector;
}
std::string ratio(std::string fileName){
std::ifstream myFile;
myFile.open(fileName);
std::string line;
int counterGET = 0;
int counterPOST = 0;
while (std::getline(myFile, line)) {
std::istringstream ss(line);
std::string expressions;
int counter = 0;
while (std::getline(ss, expressions, ' ')) {
if (counter == 11) {
if (expressions == "GET") {
counterGET++;
} else if (expressions == "POST") {
counterPOST++;
}
}
counter++;
}
}
myFile.close();
return (std::to_string(counterGET) + "/" + std::to_string(counterPOST));
}
int main() {
std::vector<std::string> printVector = ipAddress("log.txt");
for (int i = 0; i < printVector.size(); ++i) {
std::cout << i+1 << ": " << printVector[i] << std::endl;
}
std::cout << ratio("log.txt");
return 0;
}<file_sep>/week-03/day-2/Ex_06_Pokemon/pokemon.cpp
//
// Created by Lilla on 2019. 01. 30..
//
//Every pokemon has a name and a type. Certain types are effective against others, e.g. water is effective against fire.
//You have a Pokemon class with a method called isEffectiveAgainst().
//Ash has a few pokemon. Help Ash decide which Pokemon to use against the wild one.
//You can use the already created pokemon files.
#include "pokemon.h"
#include <iostream>
Pokemon::Pokemon(const std::string& name, const std::string& type, const std::string& effectiveAgainst)
{
_name = name;
_type = type;
_effectiveAgainst = effectiveAgainst;
}
bool Pokemon::isEffectiveAgainst(Pokemon anotherPokemon)
{
return _effectiveAgainst == anotherPokemon._type;
}
<file_sep>/week-04/day-2/Ex_01_GFOrganization/cohort.cpp
//
// Created by Lilla on 2019. 02. 05..
//
#include "cohort.h"
Cohort::Cohort(std::string name)
{
_name = name;
}
void Cohort::addStudent(Student* s) //Studentre mutató pointer
{
_students.push_back(*s);
}
void Cohort::addMentor(Mentor *m) //Studentre mutató pointer
{
_mentors.push_back(*m);
}
void Cohort::info()
{
std::cout << "The " << _name << " cohort has " << _students.size() << " students and " << _mentors.size() << " mentors." << std::endl;
}
<file_sep>/week-02/day-2/Ex_04_adding/main.cpp
#include <iostream>
int main()
{
// Add two numbers using pointers
//First solution
int a = 20;
int b = 17;
int c = a + b;
int *p_c = &c;
std::cout << *p_c << "\n" << c << "\n" << &c << std::endl;
//Second solution
int d = 20;
int e = 17;
int *p_d = &d;
int *p_e = &e;
int sum = *p_e + *p_d;
std::cout << *p_d << "\n" << *p_e << "\n" << sum << std::endl;
return 0;
}<file_sep>/week-06/day-3/Ex_04_merge/main.c
#include <stdio.h>
#include <stdlib.h>
// please allocate a 10 long array and fill it with even numbers
// please allocate a 10 long array and fill it with odd numbers
// select an array, and push the elements into the another array
// print the array in descending order
// delete the arrays after you don't use them
int main()
{
int* pointer_one = NULL;
int* pointer_two = NULL;
pointer_one = (int*)malloc(10 * sizeof(int));
pointer_two = (int*)malloc(10 * sizeof(int));
for (int i = 0; i < 10; ++i) {
pointer_one[i] = i * 2 + 2;
pointer_two[i] = i * 2 + 1;
}
for (int j = 0; j < 10; ++j) {
printf("%d ", pointer_one[j]);
}
puts("\n------------");
for (int k = 0; k < 10; ++k) {
printf("%d ", pointer_two[k]);
}
pointer_two = (int*)realloc(pointer_two, 20 * sizeof(int));
for (int l = 10; l < 20; ++l) {
pointer_two[l] = pointer_one[l - 10];
}
puts("\n------------");
for (int m = 19; m >= 0; --m) {
printf("%d ", pointer_two[m]);
}
free(pointer_one);
free(pointer_two);
return 0;
}<file_sep>/week-02/day-1/Ex_09_elementfinder/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_09_elementfinder)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_09_elementfinder main.cpp)<file_sep>/week-02/day-1/Ex_07_matchmaking_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_matchmaking_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_07_matchmaking_2 main.cpp)<file_sep>/week-06/day-1/Ex_08_organizing/main.c
//Continue working on the pi.c project
//Organise the function from the previous excercise to separate .c and .h files
//Create another function which calculates the circumference of a circle
//the radius of the circle should be passed as a parameter
//the function should return the calculated circumference
//circumference = 2 * radius * PI
//this function should be in the same .c and .h files as the one which calculates the area
#include <stdio.h>
#include "pi.h"
int main()
{
float radius;
printf("Give me the radius: \n");
scanf("%f", &radius);
printf("area = %.2f\n", areaMeasure(radius));
printf("circumference = %.2f", circumferenceMeasure(radius));
return 0;
}
<file_sep>/week-02/day-1/Ex_10_isinlist_2/main.cpp
#include <iostream>
#include <vector>
#include <algorithm>
bool checkNums(const std::vector<int> &numbVector, const std::vector<int> &checkerVector)
{
std::vector<int> temp;
std::vector<int> tempChecker;
for (unsigned int i = 0; i < numbVector.size(); ++i) {
temp.push_back(numbVector[i]);
}
for (unsigned int i = 0; i < checkerVector.size(); ++i) {
tempChecker.push_back(checkerVector[i]);
}
int checkerCounter = 0;
for (int i = 0; i < tempChecker.size(); ++i) {
if (std::find(temp.begin(), temp.end(), tempChecker[i]) != temp.end()){
checkerCounter++;
}
}
return (checkerCounter == tempChecker.size()) ? true : false;
}
int main(int argc, char* args[])
{
const std::vector<int> numbers = {2, 4, 6, 8, 10, 12, 14};
const std::vector<int> numbers2 = {2, 4, 6, 8, 10, 12, 14, 16};
const std::vector<int> checker = {4, 8, 12, 16};
// Check if vector contains all of the following elements: 4,8,12,16
// Create a method that accepts vector as an input
// it should return "true" if it contains all, otherwise "false"
// Expected output: "The first vector does not contain all the numbers"
if (checkNums(numbers, checker)) {
std::cout << "The first vector contains all the numbers" << std::endl;
} else {
std::cout << "The first vector does not contain all the numbers" << std::endl;
}
// Expected output: "The second vector contains all the numbers"
if (checkNums(numbers2, checker)) {
std::cout << "The second vector contains all the numbers" << std::endl;
} else {
std::cout << "The second vector does not contain all the numbers" << std::endl;
}
return 0;
}<file_sep>/week-04/day-2/Ex_03_Aircraft/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_Aircraft)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_03_Aircraft main.cpp aircraft.cpp aircraft.h)<file_sep>/week-03/day-2/Ex_10_Petrol_station/station.cpp
//
// Created by Lilla on 2019. 01. 30..
//
#include <iostream>
#include "station.h"
Station::Station(int gasAmount)
{
gasAmount_ = gasAmount;
}
void Station::fill(Car car) {
while (!car.isFull() && gasAmount_ > 0) {
car.fill();
gasAmount_--;
std::cout << "Filling the car!" << std::endl;
}
std::cout << "Remaining gas amount of the station: " << gasAmount_ << std::endl;
std::cout << "The gas amount in this car: " << car.gasAmount_ << std::endl;
}
/* while(car.capacity_ != car.gasAmount_) {
car.fill();
gasAmount_--;
std::cout << "Filling the car!" << std::endl;
}
std::cout << "Remaining gas amount of the station: " << gasAmount_ << std::endl;
}*/<file_sep>/week-02/day-2/Ex_06_five_numbers/main.cpp
#include <iostream>
int main()
{
int a;
int mynumbers[5];
std::cout << "Write 5 numbers: " <<std::endl;
for (int i = 0; i < 5; i++) { // Create a program which accepts five integers from the console (given by the user)
std::cin >> a; // and store them in an array
mynumbers[i] = a;
}
int *mynumbersPtr = mynumbers;
for (int i = 0; i < 5; i++) {
std::cout << *mynumbersPtr <<std::endl; // print out the values of that array using pointers again
++mynumbersPtr; //léptetni kell a deference-t is, mert enélkül csak az első elemet nyomtatjuk ki 5-ször
}
//Second solution
//for (int i = 0; i < 5; i++) {
// std::cout << *(mynumbersPtr + i) <<std::endl; // print out the values of that array using pointers again
//}
return 0;
}<file_sep>/week-03/day-2/Ex_05_Counter/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_05_Counter)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_05_Counter main.cpp Counter.cpp Counter.h)<file_sep>/week-06/day-1/Ex_08_organizing/pi.h
//
// Created by Lilla on 2019. 02. 18..
//
#ifndef EX_08_ORGANIZING_PI_H
#define EX_08_ORGANIZING_PI_H
float areaMeasure(float radius);
float circumferenceMeasure(float radius);
#endif //EX_08_ORGANIZING_PI_H
<file_sep>/week-02/day-1/Ex_06_solarsystem/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(EX_06_solarsystem)
set(CMAKE_CXX_STANDARD 14)
add_executable(EX_06_solarsystem main.cpp)<file_sep>/week-06/day-1/Ex_19_subString/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sub_string(char * str1, char * str2);
int main()
{
// Create a program which asks for two strings and stores them
// Create a function which takes two strings as parameters and
// returns 1 if the shorter string is a substring of the longer one and
// returns 0 otherwise
// If the two strings has the same lenght than the function should return -1
char * str1 = "abcde2fghi3jk4l";
char * str2 = "2fga";
printf("The result is %d", sub_string(str1, str2));
return 0;
}
int sub_string(char * str1, char * str2)
{
char *ret = strstr(str1, str2);
int sizestr1 = strlen(str1) + 1;
int sizestr2 = strlen(str2) + 1;
if (sizestr1 == sizestr2){
return - 1;
} else if (&ret != NULL){
return 1;
} else {
return 0;
}
}
<file_sep>/week-01/day-4/Ex_03_Append/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_Append)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_03_Append main.cpp)<file_sep>/week-02/day-3/Ex_06_Copy_file/main.cpp
#include <iostream>
#include <fstream>
#include <string>
// Write a function that reads all lines of a file and writes the read lines to an other file (a.k.a copies the file)
// It should take the filenames as parameters
// It should return a boolean that shows if the copy was successful
bool copy(std::string firstFile, std::string secondFile);
int main()
{
std::string firstFile;
std::string secondFile;
std::cout << "Write two filename :" << std::endl;
std::cin >> firstFile >> secondFile;
if (copy(firstFile, secondFile)){
std::cout << "It was succesful";
} else {
std::cout << "It was not succesful";
}
return 0;
}
bool copy(std::string firstFile, std::string secondFile)
{
std::string line;
std::ifstream whatUWant(firstFile);
std::ofstream whereUWant(secondFile);
try {
if (!whatUWant.is_open()){
throw 99;
}
if (!whereUWant.is_open()){
throw 99;
}
} catch (int x) {
return false;
}
while (std::getline(whatUWant, line)){
whereUWant << line << std::endl;
}
//return linecounterOne == linecounterTwo;
return true;
whatUWant.close();
whereUWant.close();
}<file_sep>/week-01/day-4/Ex_21_Anagram/main.cpp
#include <iostream>
#include <algorithm>
bool anagram(std::string input1, std::string input2) //two value to parameters - making copies
{
std::sort(input1.begin(), input1.end()); //std::sort function belongs to <algorithm>, sort the first copy
std::sort(input2.begin(), input2.end()); //std::sort function belongs to <algorithm>, sort the second copy
if (input1.size() != input2.size()){ //first statement - they not be equal size
return false;
} else {
for (int i = 0; i < input1.size(); ++i) { //counting the elements of both char[] until the end of them
if (input1[i] != input2[i]){ //second statement - after sorting, the i-elements of both char[i] have not equal value
return false;
}
}
}
return true; //any other case is true
}
int main() {
std::string input1 = "dog";
std::string input2 = "god";
std::string input3 = "fox";
std::string input4 = "green";
std::cout << anagram(input1, input2) << std::endl;
std::cout << anagram(input3, input4) << std::endl;
return 0;
}<file_sep>/week-01/day-3/Ex_21_PartyIndicator/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_21_PartyIndicator)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_21_PartyIndicator main.cpp)<file_sep>/week-9/practice/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
#define UART_PUTCHAR int __io_putchar(int ch)
GPIO_InitTypeDef PA15_LED_config; //PA 15 pin able to compare channel 1 with alternate function AF
GPIO_InitTypeDef user_button_handle; //PI 11 pin
TIM_HandleTypeDef pwm_led_init;
TIM_OC_InitTypeDef sConfig;
UART_HandleTypeDef uart; //the uart config for general purpose
void external_led_PA15_init(){
__HAL_RCC_GPIOA_CLK_ENABLE(); //A port clock
PA15_LED_config.Pin = GPIO_PIN_15; //PA 15 pin able to compare channel 1 with alternate function AF
PA15_LED_config.Mode = GPIO_MODE_AF_PP; /* configure as output, in push-pull mode */
PA15_LED_config.Pull = GPIO_NOPULL;
PA15_LED_config.Speed = GPIO_SPEED_HIGH;
PA15_LED_config.Alternate = GPIO_AF1_TIM2; /* this alternate function we need to use TIM2 in output compare mode */
HAL_GPIO_Init(GPIOA, &PA15_LED_config);
}
void pwm_init(){
//timer rész
pwm_led_init.Instance = TIM2;
pwm_led_init.Init.Prescaler = 108 - 1; /* 108000000/108=1000000 -> speed of 1 count-up: 1/1000000 s = 0.001 ms */
pwm_led_init.Init.Period = 100 - 1; /* 100 x 0.001 ms = 10 ms = 0.01 s period */
pwm_led_init.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
pwm_led_init.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_PWM_Init(&pwm_led_init);
//pwm output channel rész
sConfig.Pulse = 0; //ezt lehet változik
/* 50% * 0.01 s = 0.005 s: 0.005 low, then 0.005 s high; our eyes are not able to notice, that it is a vibrating light */
sConfig.OCMode = TIM_OCMODE_PWM1;
sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfig.OCFastMode = TIM_OCFAST_ENABLE;
HAL_TIM_PWM_ConfigChannel(&pwm_led_init, &sConfig, TIM_CHANNEL_1);
/* starting PWM */
HAL_TIM_PWM_Start(&pwm_led_init, TIM_CHANNEL_1); //talán itt marad
}
void init_user_button(void)
{
__HAL_RCC_GPIOI_CLK_ENABLE(); // enable the GPIOI clock
user_button_handle.Pin = GPIO_PIN_11; // the pin is the PI11
user_button_handle.Pull = GPIO_NOPULL;
user_button_handle.Speed = GPIO_SPEED_FAST; // port speed to fast
user_button_handle.Mode = GPIO_MODE_IT_RISING_FALLING; // our mode is interrupt on rising edge
HAL_GPIO_Init(GPIOI, &user_button_handle); // init PI11 user button
HAL_NVIC_SetPriority(EXTI15_10_IRQn, 1, 0); //set blue PI11 user button interrupt priority //a 11 a 10 és a 15 között van
HAL_NVIC_EnableIRQ(EXTI15_10_IRQn); //enable the interrupt to HAL
}
void init_GPIO_BSP_uart()
{
//init uart for GPIO purpose with BSP
__HAL_RCC_USART1_CLK_ENABLE();
uart.Instance = USART1;
uart.Init.BaudRate = 115200;
uart.Init.WordLength = UART_WORDLENGTH_8B;
uart.Init.StopBits = UART_STOPBITS_1;
uart.Init.Parity = UART_PARITY_NONE;
uart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
uart.Init.Mode = UART_MODE_TX_RX;
BSP_COM_Init(COM1, &uart);
}
int main(void)
{
HAL_Init();
BSP_LED_Init(LED1);
init_user_button();
init_GPIO_BSP_uart();
printf("yes main\r\n");
while(1){
}
}
void EXTI15_10_IRQHandler(void)
{
//HAL_GPIO_EXTI_IRQHandler(user_button_handle.Pin);
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_11);
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
if(GPIO_Pin == user_button_handle.Pin){
BSP_LED_Toggle(LED1);//tesztelés miatt!!
printf("yes\r\n"); //tesztelés miatt
}
}
UART_PUTCHAR
{
HAL_UART_Transmit(&uart, (uint8_t*)&ch, 1, 0xFFFF);
return ch;
}
<file_sep>/week-01/day-3/Ex_04_Introduce/main.cpp
#include <iostream>
int main(int argc, char const *argv[]) {
std::cout << "<NAME>" << std::endl;
std::cout << 30 << std::endl;
std::cout << 60.5 << std::endl;
return 0;
}
<file_sep>/week-01/day-4/Ex_21_Anagram/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_21_Anagram)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_21_Anagram main.cpp)<file_sep>/week-02/day-3/Ex_03_Count_lines/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_Count_lines)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_03_Count_lines main.cpp)<file_sep>/week-04/day-3/Ex_04_Devices/scanner.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_04_DEVICES_SCANNER_H
#define EX_04_DEVICES_SCANNER_H
class Scanner {
public:
Scanner(int speed);
void scan();
protected:
int _speed;
};
#endif //EX_04_DEVICES_SCANNER_H
<file_sep>/week-01/day-4/Ex_20_Unique/main.cpp
#include <iostream>
#include <string>
void unique(int numbers[], int size){
int tempNumbers;
int newSize = 0;
int tempArray[newSize];
for (int i = 0; i < size; ++i) {
tempNumbers = numbers [i];
for (int j = i; j < size; ++j) {
if (tempNumbers != numbers[j]){
newSize ++;
tempArray[i] = numbers[i];
}
}
}
for (int j = 0; j < newSize; ++j) {
std::cout << tempArray[j] << " ";
}
}
int main(int argc, char* args[]) {
// Create a function that takes a list of numbers as a parameter
// Don't forget you have pass the size of the list as a parameter as well
// Returns a list of numbers where every number in the list occurs only once
// Example
int numbers[] = {1, 11, 34, 11, 52, 61, 1, 34};
int size = sizeof(numbers) / sizeof(numbers[0]);
(unique(numbers, size));
// should print: `[1, 11, 34, 52, 61]`
return 0;
}
<file_sep>/week-01/day-3/Ex_04_Introduce/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_4_Introduce)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_4_Introduce main.cpp)<file_sep>/week-07/day-3/Ex_05_knight_rider/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
GPIO_InitTypeDef LEDS;
void init_external_led()
{
//initialize external LED on F port pin 7
__HAL_RCC_GPIOF_CLK_ENABLE(); //giving clock
LEDS.Pin = GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10;
LEDS.Mode = GPIO_MODE_OUTPUT_PP;
LEDS.Pull = GPIO_NOPULL;
LEDS.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOF, &LEDS); //first param: name of port, second param: name of structure
}
int main(void) {
HAL_Init();
init_external_led();
int counter = 0;
while (1) {
for (int i = 0; i < 6; ++i){
if (counter % 6 == 0) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_SET);
}
if (counter % 6 == 1) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_SET);
}
if (counter % 6 == 2) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_SET);
}
if (counter % 6 == 3) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_SET);
}
if (counter % 6 == 4) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_SET);
}
if (counter % 6 == 5) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_SET);
}
counter++;
HAL_Delay(200);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_RESET);
}
counter = 0;
}
}
<file_sep>/week-06/day-1/Ex_05_cuboid/main.c
// Write a program that stores 3 sides of a cuboid as variables (doubles)
// You should get these variables via console input
// The program should write the surface area and volume of the cuboid like:
//
// Surface Area: 600
// Volume: 1000
#include <stdio.h>
#include <stdlib.h>
int main()
{
double cuboidHeight, cuboidWidht, cuboidDeep;
double surface, volume;
printf("Enter the height: \n");
scanf("%lf", &cuboidHeight);
printf("Enter the widht: \n");
scanf("%lf", &cuboidWidht);
printf("Enter the deep: \n");
scanf("%lf", &cuboidDeep);
surface = 2 * (cuboidHeight * cuboidWidht + cuboidHeight * cuboidDeep + cuboidDeep * cuboidWidht);
volume = cuboidHeight * cuboidWidht * cuboidDeep;
printf("Surface Area: %.2lf\nVolume: %.2lf", surface, volume);
return 0;
}<file_sep>/week-05/day-4/trialTrialEx3Restaurant/restaurant.cpp
//
// Created by Lilla on 2019. 02. 14..
//
#include "restaurant.h"
Restaurant::Restaurant(std::string name, int foundYear)
{
_name= name;
_foundationYear = foundYear;
}
void Restaurant::guestsArrived()
{
for (int i = 0; i < _employees.size(); ++i) {
_employees[i]->work();
}
}
void Restaurant::hire(Employee &employee) {
_employees.push_back(&employee);
}
std::string Restaurant::toStringRestaurant()
{
std::string temp;
for (int i = 0; i < _employees.size(); ++i) {
temp += (_employees[i]->toString() +"\n");
}
return _name + " founded " + std::to_string(_foundationYear) + " years ago\n" + temp;
}
<file_sep>/week-06/day-1/Ex_25_sentence/main.cpp
#include <stdio.h>
#include <string.h>
// create a function which takes a char array as a parameter,
// and splits a string to words by space
// solve the problem with the proper string.h function
void sentenceSolutionOne(char string[]);
void sentenceSolutionTwo(char string[]);
int main()
{
printf("Type a sentence:\n");
char string[256];
gets(string);
printf("Type a sentence again:\n");
char string2[256];
gets(string2);
printf("First solution: \n");
sentenceSolutionOne(string);
printf("Second solution: \n");
sentenceSolutionTwo(string2); //nem működik
return(0);
}
void sentenceSolutionOne(char string[])
{
for (char *p = strtok(string, " "); p != NULL; p = strtok(NULL, " ")) {
puts(p);
}
}
void sentenceSolutionTwo(char string[])
{
char *word = strtok(string, " ");
while (word != NULL) {
puts(word);
word = strtok(NULL, " ");
}
}
<file_sep>/week-06/day-1/Ex_11_oddOrEven/oddOrEven.h
//
// Created by Lilla on 2019. 02. 18..
//
#ifndef EX_11_ODDOREVEN_ODDOREVEN_H
#define EX_11_ODDOREVEN_ODDOREVEN_H
#define ODDOREVEN(number) ((number % 2 == 0) ? 1 : 0)
#endif //EX_11_ODDOREVEN_ODDOREVEN_H
<file_sep>/week-01/day-3/Ex_33_GuessTheNumber/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_33_GuessTheNumber)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_33_GuessTheNumber main.cpp)<file_sep>/week-01/day-4/Ex_08_Compare_length/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_08_Compare_length)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_08_Compare_length main.cpp)<file_sep>/week-03/day-3/Ex_05_Bunnies/main.cpp
#include <iostream>
// We have a number of bunnies and each bunny has two big floppy ears.
// We want to compute the total number of ears across all the bunnies recursively (without loops or multiplication).
int bunnyEars(int bunnyNumber, int oneBunnyEars);
int main() {
int bunnyNumb;
int BunnyEars = 2;
std::cout << "Write the numbers of bunnies: ";
std::cin >> bunnyNumb;
std::cout << bunnyEars(bunnyNumb, BunnyEars);
return 0;
}
int bunnyEars(int bunnyNumber, int oneBunnyEars)
{
if (bunnyNumber <= 1){
return oneBunnyEars;
} else {
return (oneBunnyEars + bunnyEars(bunnyNumber-1, oneBunnyEars));
}
}<file_sep>/week-01/day-3/Ex_10_Basicinf/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_10_Basicinf)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_10_Basicinf main.cpp)<file_sep>/week-06/day-2/Ex_05_house/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_05_house C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_05_house main.c)<file_sep>/week-06/day-2/Ex_05_house/main.c
#include <stdio.h>
#include <string.h>
/*
Create a struct that represents a House
It should store:
- The address of the house
- The price in EUR
- The number of rooms
- The area of the house in square meters
The market price of the houses is 400 EUR / square meters
Create a function that takes a pointer to a house and decides if it's worth to buy
(if the price is lower than the calculated price from it's area)
Create a function that takes an array of houses (and it's length), and counts the
houses that are worth to buy.
*/
struct house{
char address[200];
double price_EUR;
int number_of_rooms;
double area_of_house;
};
void it_is_worth(struct house *one_house);
int count_houses_to_worth(struct house array[], int size);
int main()
{
struct house big_house;
strcpy(big_house.address, "Heaven Street 7.");
big_house.price_EUR = 55600;
big_house.number_of_rooms = 2;
big_house.area_of_house = 70;
it_is_worth(&big_house);
struct house small_house;
strcpy(small_house.address, "Devil Street 6.");
small_house.price_EUR = 10333;
small_house.number_of_rooms = 1;
small_house.area_of_house = 40;
it_is_worth(&small_house);
struct house very_big_house;
strcpy(very_big_house.address, "Devil Street 6.");
very_big_house.price_EUR = 61035;
very_big_house.number_of_rooms = 4;
very_big_house.area_of_house = 156.5;
it_is_worth(&very_big_house);
struct house array[] = {big_house, small_house, very_big_house};
int sizeOfArray = sizeof(array) / sizeof(array[0]);
printf("%d\n", sizeOfArray);
printf("The number of houses are worth to buy is %d.", count_houses_to_worth(array,sizeOfArray));
return 0;
}
void it_is_worth(struct house *one_house)
{
if (one_house->price_EUR/one_house->area_of_house < 400){
printf("The house with %d rooms and %.2lf EUR price is worth to buy.\n", one_house->number_of_rooms, one_house->price_EUR);
} else {
printf("This house with %d rooms and %.2lf EUR price is not worth to buy.\n", one_house->number_of_rooms, one_house->price_EUR);
}
}
int count_houses_to_worth(struct house array[], int size)
{
int counter = 0;
for (int i = 0; i < size ; ++i) {
if (array[i].price_EUR/array[i].area_of_house < 400){
counter++;
}
}
return counter;
}<file_sep>/week-01/day-3/Ex_24_PrintEven/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_24_PrintEven)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_24_PrintEven main.cpp)<file_sep>/week-03/day-2/Ex_01_Post_it/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_Post_it)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_01_Post_it main.cpp)<file_sep>/week-04/day-3/LessonPractice_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(LessonPractice_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(LessonPractice_2 main.cpp)<file_sep>/week-01/day-3/Ex_03_HelloOthers/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_3_HelloOthers)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_3_HelloOthers main.cpp)<file_sep>/week-01/day-4/Ex_18_SumAllElements/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_18_SumAllElements)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_18_SumAllElements main.cpp)<file_sep>/week-06/day-2/Ex_10_writeSingleLine/main.c
#include <stdio.h>
#include <string.h>
// Open a file called "my-file.txt"
// Write your name in it as a single line
int main ()
{
FILE * f_pointer;
f_pointer = fopen("my-file.txt", "w");
fprintf(f_pointer, "<NAME>\n"); //with fprintf
fputs("<NAME>\n", f_pointer); //with fputs
char third_name[] = "<NAME>";
for (int i = 0; i < sizeof(third_name); i++) {
fputc(third_name[i], f_pointer);
}
fclose(f_pointer);
return 0;
}<file_sep>/week-01/day-4/Ex_13_Matrix/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_13_Matrix)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_13_Matrix main.cpp)<file_sep>/week-04/day-1/VideoPractice_01/mother.cpp
//
// Created by Lilla on 2019. 02. 05..
//
#include <iostream>
#include "mother.h"
#include "daughter.h"
Mother::Mother ()
{
}
void Mother::sayName()
{
std::cout << "My name is mom." << std::endl;
}<file_sep>/week-02/day-1/Ex_03_takeslonger/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_takeslonger)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_03_takeslonger main.cpp)<file_sep>/week-02/day-3/Ex_07_Logs/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_Logs)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_07_Logs main.cpp)<file_sep>/week-02/day-3/Ex_05_Write_multiple_lines/main.cpp
#include <iostream>
#include <fstream>
#include <string>
// Create a function that takes 3 parameters: a path, a word and a number,
// than it should write to a file.
// The path parameter should describes the location of the file.
// The word parameter should be a string, that will be written to the file as lines
// The number paramter should describe how many lines the file should have.
// So if the word is "apple" and the number is 5, than it should write 5 lines
// to the file and each line should be "apple"
void funkyFunc (std::string path, std::string wordToRepeat, int numRepeat)
{
std::ofstream lillaFile(path);
for (int i = 0; i < numRepeat; ++i) {
lillaFile << wordToRepeat <<"\n";
}
}
int main()
{
std::string path;
std::string word;
int number;
std::cout << "Enter the path of the file, a word and a number: ";
std::cin >> path >> word >> number;
funkyFunc(path, word, number);
return 0;
}<file_sep>/week-02/day-3/Ex_05_Write_multiple_lines_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_05_Write_multiple_lines_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_05_Write_multiple_lines_2 main.cpp)<file_sep>/week-07/day-5/UART_game/main.c
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
#include <string.h>
//I made it based on Bola00's solution
#define UART_PUTCHAR int __io_putchar(int ch)
GPIO_InitTypeDef GPIOTxConfig;
GPIO_InitTypeDef GPIORxConfig;
RNG_HandleTypeDef rng_handle;
UART_HandleTypeDef uart;
GPIO_InitTypeDef leds;
GPIO_InitTypeDef external_button;
void init();
int active_waiting(int waiting);
int main(void)
{
//Part1: initialize things
HAL_Init();
init(); //init everything in one round
//Part2: starting stage of the game, which is destroyed by a button push
printf("Let's play a game! Are you ready?\n");
//mechanism: toggle LED until someone won't push the button
while (1) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_SET);
if (active_waiting(500)) //break, if active_waiting(500) function return true
break;
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_RESET);
if (active_waiting(500)) //break, if active_waiting(500) function return true
break;
}
printf("Start!\nReady!\n");
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_RESET);
//Part3: the game
int random_flash;
while (1) {
uint32_t random_number = HAL_RNG_GetRandomNumber(&rng_handle); //it gets a rng, not generate a rng
random_flash = random_number % 10 + 1; //this is a number between 1 and 10
HAL_Delay(random_flash * 1000); //this is a number between 1000 msec and 10000 msec
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_SET); //light up a led as a sign of the starting
int starting_time = HAL_GetTick(); //get a starting time
//nothing will happen until someone won't push the button
while(!HAL_GPIO_ReadPin(GPIOB, external_button.Pin)) {
}
int ending_time = HAL_GetTick(); //get an ending time after someone pushed the button
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_RESET); //light down means, someone pushed the button
//Part 4: printf() the result of the game
printf("your time: %d\n", ending_time - starting_time);
break;
}
}
void init()
{
/* enable GPIO clocks */
__HAL_RCC_GPIOA_CLK_ENABLE(); //A9 TX
__HAL_RCC_GPIOB_CLK_ENABLE(); //B7 RT, B4 button
__HAL_RCC_GPIOF_CLK_ENABLE(); //F7 Led,
/* configure GPIO for UART transmit line */
GPIOTxConfig.Pin = GPIO_PIN_9;
GPIOTxConfig.Mode = GPIO_MODE_AF_PP;
GPIOTxConfig.Pull = GPIO_NOPULL;
GPIOTxConfig.Speed = GPIO_SPEED_FAST;
GPIOTxConfig.Alternate = GPIO_AF7_USART1;
HAL_GPIO_Init(GPIOA, &GPIOTxConfig);
/* configure GPIO for UART receive line */
GPIORxConfig.Pin = GPIO_PIN_7;
GPIORxConfig.Mode = GPIO_MODE_AF_PP;
GPIOTxConfig.Pull = GPIO_NOPULL;
GPIORxConfig.Speed = GPIO_SPEED_FAST;
GPIORxConfig.Alternate = GPIO_AF7_USART1;
HAL_GPIO_Init(GPIOB, &GPIORxConfig);
/* enable the clock of the used peripherial instance */
__HAL_RCC_USART1_CLK_ENABLE();
/* defining the UART configuration structure */
uart.Instance = USART1;
uart.Init.BaudRate = 115200;
uart.Init.WordLength = UART_WORDLENGTH_8B;
uart.Init.StopBits = UART_STOPBITS_1;
uart.Init.Parity = UART_PARITY_NONE;
uart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
uart.Init.Mode = UART_MODE_TX_RX;
HAL_UART_Init(&uart);
/* defining a LED configuration structure */
leds.Pin = GPIO_PIN_7; /* setting up 1 pins */
leds.Mode = GPIO_MODE_OUTPUT_PP; /* configure as output, in push-pull mode */
leds.Pull = GPIO_NOPULL; /* we don't need internal pull-up or -down resistor */
leds.Speed = GPIO_SPEED_FAST; /* we need a high-speed output */
HAL_GPIO_Init(GPIOF, &leds); /* initialize the pin on GPIOF port */
/* defining the button configuration structure */
external_button.Pin = GPIO_PIN_4;
external_button.Mode = GPIO_MODE_INPUT;
external_button.Pull = GPIO_NOPULL;
external_button.Speed = GPIO_SPEED_FAST;
HAL_GPIO_Init(GPIOB, &external_button);
/* defining the RNG (random number generator) configuration structure */
__HAL_RCC_RNG_CLK_ENABLE();
rng_handle.Instance = RNG;
HAL_RNG_Init(&rng_handle);
}
int active_waiting(int waiting){
int tickstart = HAL_GetTick(); //take an instant time
//printf("%d\n",tickstart); //checking the mechanism
while (HAL_GetTick() - tickstart < waiting) { //function must wait 500 msec, wether someone touch the button, exp: (15365 - 15039) < 500
if (HAL_GPIO_ReadPin(GPIOB, external_button.Pin))
return 1; //if someone push the button, it returns true
}
return 0;
}
UART_PUTCHAR
{
HAL_UART_Transmit(&uart, (uint8_t*)&ch, 1, 0xFFFF);
return ch;
}
<file_sep>/week-01/day-3/Ex_25_MultiTable/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_25_MultiTable)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_25_MultiTable main.cpp)<file_sep>/week-03/day-2/Ex_06_Pokemon/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_06_Pokemon)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_06_Pokemon main.cpp pokemon.cpp pokemon.h)<file_sep>/week-03/day-2/Ex_05_Counter/Counter.cpp
//
// Created by Lilla on 2019. 01. 29..
//
//Create Counter class
// which has an integer field value
// when creating it should have a default value 0 or we can specify it when creating
// we can add(number) to this counter another whole number
// or we can add() without parameters just increasing the counter's value by one
// and we can get() the current value
// also we can reset() the value to the initial value
//Check if everything is working fine with the proper test
// Download main.cpp and use that instead of the default
// Without modifying anything in it, compile and run.
// Check the console output whether any of the tests failed.
#include "Counter.h"
#include <iostream>
Counter::Counter(int number) { //Constructor is used for giving back "values" of itself without any operations
number_ = number;
number_start_ = number;
}
void Counter::add(int x) {
number_ = number_ + x;
}
void Counter::add() {
number_++;
}
int Counter::get() {
return number_;
}
void Counter::reset(){
number_ = number_start_;
}<file_sep>/week-02/day-2/Ex_07_look_for_value/main.cpp
#include <iostream>
int lookforvalue (int myarray[], int size, int paranumb)
{
int a;
for (int i = 0; i < size ; ++i) {
if (paranumb == myarray[i]){
return i;
} else {
a = 0;
}
}
return a;
}
int main()
{
int parameter;
int examplearray[6] = {1, 5, 9, 7, 8, 6};// Create a function which takes an array (and it's lenght) and a number as a parameter
int size = sizeof(examplearray)/ sizeof(examplearray[0]);
std::cout <<"Write a number from the array :" <<std::endl;
std::cin >> parameter;
int abcd =lookforvalue(examplearray, size, parameter);
// the function should return index where it found the given value
// if it can't find the number return 0
std::cout << abcd <<std::endl;
return 0;
}<file_sep>/week-02/day-2/Ex_09_find_minimum/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_09_find_minimum)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_09_find_minimum main.cpp)<file_sep>/week-02/day-1/Ex_08_appendaletter/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_08_appendaletter)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_08_appendaletter main.cpp)<file_sep>/week-04/day-3/Ex_04_Devices/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_04_Devices)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_04_Devices main.cpp printer.cpp printer.h printer2d.cpp printer2d.h printer3d.cpp printer3d.h scanner.cpp scanner.h copier.cpp copier.h)<file_sep>/week-02/day-3/Ex_08_TicTakToe/main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
std::string ticTacResult(std::string path);
int main() {
// Write a function that takes a filename as string,
// open and read it. The file data represents a tic-tac-toe
// game result. Return 'X'/'O'/'draw' based on which player
// has winning situation.
std::cout << ticTacResult("win-o.txt");
// should print O
std::cout << std::endl;
std::cout << ticTacResult("win-x.txt");
// should print X
std::cout << std::endl;
std::cout << ticTacResult("draw.txt");
// should print draw
std::cout << std::endl;
return 0;
}
std::string ticTacResult(std::string path) {
std::ifstream myfile(path);
try {
if (!myfile.is_open()) {
throw std::string("Opening error");
}
} catch (std::string &e) {
std::cout << e << std::endl;
}
std::string line;
/*std::string temp;
while(std::getline(myfile, line)){
temp += line;
}
std::string result;
if (temp[0] == temp[3] && temp[0] == temp[6]){
result = temp[0];
return result;
} else if (temp[1] == temp[4] && temp[1] == temp[7]){
result = temp[1];
return result;
} else if (temp[2] == temp[5] && temp[2] == temp[8]){
result = temp[2];
return result;
} else if (temp[0] == temp[1] && temp[0] == temp[2]){
result = temp[0];
return result;
} else if (temp[3] == temp[4] && temp[3] == temp[5]){
result = temp[3];
return result;
} else if (temp[6] == temp[7] && temp[6] == temp[8]){
result = temp[6];
return result;
} else if (temp[0] == temp[4] && temp[0] == temp[8]){
result = temp[0];
return result;
} else if (temp[2] == temp[4] && temp[2] == temp[6]){
result = temp[2];
return result;
} else {
return "draw";
}
*/
std::vector<std::vector<char>> resultVector;
std::string result;
while (std::getline(myfile, line)) {
std::vector<char> temp;
temp.push_back(line[0]);
temp.push_back(line[1]);
temp.push_back(line[2]);
resultVector.push_back(temp);
}
for (int i = 0; i < resultVector.size(); i++) {
if (resultVector[i].at(0) == resultVector[i].at(1) && resultVector[i].at(0) == resultVector[i].at(2)) {
result = resultVector[i].at(0);
return result;
} else if (resultVector[0].at(i) == resultVector[1].at(i) && resultVector[0].at(i) == resultVector[0].at(i)) {
result = resultVector[0].at(i);
return result;
}
}
if (resultVector[0][0] == resultVector[1][1] && resultVector[0][0] == resultVector[2][2]) {
result = resultVector[0][0];
return result;
} else if (resultVector[0][1] == resultVector[1][1] && resultVector[0][1] == resultVector[2][1]) {
result = resultVector[0][1];
return result;
} else {
return "draw";
}
}<file_sep>/week-01/weekend/nested_loops/main.cpp
#include <iostream>
int main() {
for (int i = 2; i < 100; i++){
for (int j = 2; j <= (i / j); ++j) {
if (!(i % j)) {
break;
}
if (j > (i / j)) {
std::cout << i << " is prime" << std::endl;
}
}
}
return 0;
}<file_sep>/week-02/day-1/Ex_06_solarsystem/main.cpp
/*
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8};
// Output: 1 2 3 4 5 6 7 8
for(int i = 0; i < numbers.size(); ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
// You can do it in reverse as well (note the differences between the loop headers!)
// Output: 8 7 6 5 4 3 2 1
for(int i = numbers.size() - 1; i >= 0; --i) {
std::cout << numbers[i] << " ";
}
return 0;
}
*/
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> putSaturn(const std::vector<std::string> &planets)
{
std::vector<std::string> listNewplanets; //We created a new vector variable typed string to be independent from original vector
for (unsigned int i = 0; i < planets.size(); ++i) {
listNewplanets.push_back(planets[i]); //We copied the original elements of the vector in the new vector
}
std::string sat = "Saturn";
listNewplanets.insert(listNewplanets.begin() + 5, sat);
// listNewplanets.insert(listNewplanets.begin() + 5, "Saturn", 0); //We inserted an element in the copied vector
//First the index of element where we want to insert, in this case 0+5 = 5 means 5th index
//Second the new element
return listNewplanets;
}
int main(int argc, char *args[]) {
std::vector<std::string> planets = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Uranus", "Neptune"};
// Saturn is missing from the planetList
// Insert it into the correct position
// Create a method called putSaturn() which has list parameter and returns the correct list.
// Expected output: Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune
std::vector<std::string> correctPlanets = putSaturn(planets);
for (int i = 0; i < correctPlanets.size(); ++i) {
std::cout << correctPlanets[i] << " ";
}
return 0;
}<file_sep>/week-02/day-3/Ex_01_Divide_by_zero/main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <exception>
int divide(int thenumber)
{
int b;
if (thenumber == 0) {
throw std::string("fail");
}
b= 10/thenumber;
return b;
}
int main() {
int a;// Create a function that takes a number
std::cout << "Write a number :" << std::endl; // divides ten with it,
std::cin >> a;// and prints the result.
try {
std::cout << divide(a) << std::endl;;// It should print "fail" if the parameter is 0
} catch (std::string e) {
std::cout << e << std::endl;
}
return 0;
}
<file_sep>/week-04/day-3/Ex_01_InstruStringedInstru/violin.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include <iostream>
#include "violin.h"
Violin::Violin(int numberOfStrings) : StringedInstrument(numberOfStrings)
{
_name = "Violin";
}
/* PLAY
* Violin::Violin(int numberOfStrings, int size) : StringedInstrument (numberOfStrings)
{
_name = "Violin";
_size = size;
}*/
Violin::Violin() : StringedInstrument()
{
_numberOfStrings = 4;
_name = "Violin";
}
std::string Violin::sound()
{
return "Screech";
}<file_sep>/week-06/day-1/Ex_15_areTheSame/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_15_areTheSame)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_15_areTheSame main.c)<file_sep>/week-01/day-4/Ex_13_Matrix2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_13_Matrix2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_13_Matrix2 main.cpp)<file_sep>/week-04/day-3/Ex_02_Zoo/animal.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_02_ZOO_ANIMAL_H
#define EX_02_ZOO_ANIMAL_H
#include <iostream>
#include <string>
enum Gender
{
MALE,
FEMALE
};
std::string genderToString(Gender gender);
class Animal {
public:
virtual std::string getName() = 0;
virtual std::string breed() = 0;
protected:
std::string _name;
std::string color;
int health;
int _age;
Gender _gender;
};
#endif //EX_02_ZOO_ANIMAL_H
<file_sep>/week-03/day-3/Ex_10_Fibonacc/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_10_Fibonacc)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_10_Fibonacc main.cpp)<file_sep>/week-04/day-3/Ex_02_Zoo/reptile.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_02_ZOO_REPTILE_H
#define EX_02_ZOO_REPTILE_H
#include "byegg.h"
#include <iostream>
class Reptile : public Byegg {
public:
Reptile(std::string name);
std::string getName()override;
};
#endif //EX_02_ZOO_REPTILE_H
<file_sep>/week-05/day-1/ExampleExam_Shelter/cat.h
//
// Created by Lilla on 2019. 02. 11..
//
#ifndef EXAMPLEEXAM_SHELTER_CAT_H
#define EXAMPLEEXAM_SHELTER_CAT_H
#include "animal.h"
class Cat : public Animal {
public:
Cat(std::string name = "Cat");
};
#endif //EXAMPLEEXAM_SHELTER_CAT_H
<file_sep>/week-05/day-1/TrialExam_Pirates/ship.h
//
// Created by Lilla on 2019. 02. 11..
//
#ifndef TRIALEXAM_PIRATES_SHIP_H
#define TRIALEXAM_PIRATES_SHIP_H
#include <vector>
#include "pirate.h"
class Ship {
public:
Ship();
std::vector<std::string> getPoorPirates();
int getGolds();
void lastDayOnTheShip();
void prepareForBattle();
void addPirate(Pirate onepirate);
private:
//std::vector<Pirate> _pirates;
std::vector<Pirate> _pirates;
};
#endif //TRIALEXAM_PIRATES_SHIP_H
<file_sep>/week-08/function_templates_SKELETON/interruption_templates.c
/*
* interruption_templates.c
*
* Created on: 2019. márc. 12.
* Author: Lilla
*/
#include "interruption_templates.h"
/* we don't need to explicitly call the HAL_NVIC_SetPriorityGrouping function,
* because the grouping defaults to NVIC_PRIORITYGROUP_2:
* HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_2);
*/
void init_timer(void)
{
//initialize TIM2
__HAL_RCC_TIM2_CLK_ENABLE(); //giving clock
HAL_TIM_Base_DeInit(&tim_handle); // de-initialize the TIM_Base, because of safety reasons
// configuriation of the basic mode of the timer (which direction should it count, what is the maximum value, etc.)
tim_handle.Instance = TIM2; //register base address
tim_handle.Init.Prescaler = 10800 - 1; // 108000000 / 10800 = 10000 -> speed of 1 count-up: 1 /10000 s = 0.1 ms
tim_handle.Init.Period = 5000 - 1; // 5000 x 0.1 ms = 500 ms = 0.5 s period */
tim_handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
tim_handle.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_Base_Init(&tim_handle); //configure the timer
HAL_NVIC_SetPriority(TIM2_IRQn, 2, 0); //set TIM2 interrupt priority
HAL_NVIC_EnableIRQ(TIM2_IRQn); //enable the interrupt to HAL
}
void init_PWM(void)
{
//initialize TIM3 for PWM
__HAL_RCC_TIM3_CLK_ENABLE(); //giving clock
HAL_TIM_Base_DeInit(&pwm_tim_handle);// de-initialize the TIM_Base, because of safety reasons
// configuriation of the basic mode of the timer (which direction should it count, what is the maximum value, etc.)
pwm_tim_handle.Instance = TIM3; //register base address
pwm_tim_handle.Init.Prescaler = 10800 - 1; // 108000000 / 10800 = 10000 -> speed of 1 count-up: 1 /10000 s = 0.1 ms
pwm_tim_handle.Init.Period = 5000 - 1; // 5000 x 0.1 ms = 500 ms = 0.5 s period */
pwm_tim_handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
pwm_tim_handle.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_PWM_Init(&pwm_tim_handle); //configure the PWM timer
sConfig.Pulse = 50;
sConfig.OCMode = TIM_OCMODE_PWM1;
sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfig.OCFastMode = TIM_OCFAST_ENABLE;
HAL_TIM_PWM_ConfigChannel(&pwm_tim_handle, &sConfig, TIM_CHANNEL_1);
HAL_NVIC_SetPriority(TIM3_IRQn, 2, 0); //set TIM2 interrupt priority
HAL_NVIC_EnableIRQ(TIM3_IRQn); //enable the interrupt to HAL
}
<file_sep>/week-06/day-1/Ex_09_oldEnough_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_09_oldEnough_2 C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_09_oldEnough_2 main.c)<file_sep>/week-08/day-2/Ex_03_interrupt_with_TIM2/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
#include <string.h>
#define UART_PUTCHAR int __io_putchar(int ch) //to use printf() function
//global variables
GPIO_InitTypeDef LEDS; //the external Led config structure
TIM_HandleTypeDef tim_handle; //the timer's config structure
static void Error_Handler(void); //predefining of error handling function
static void SystemClock_Config(void); //predefining of system clock initializing function
void init_external_led()
{
//initialize LED
__HAL_RCC_GPIOF_CLK_ENABLE(); //giving clock
LEDS.Pin = GPIO_PIN_7; // setting up a pin
LEDS.Mode = GPIO_MODE_OUTPUT_PP;
LEDS.Pull = GPIO_NOPULL;
LEDS.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOF, &LEDS);
}
void init_timer(void)
{
//initialize TIM2
__HAL_RCC_TIM2_CLK_ENABLE(); //giving clock
// configuriation of the basic mode of the timer (which direction should it count, what is the maximum value, etc.)
HAL_TIM_Base_DeInit(&tim_handle);
tim_handle.Instance = TIM2; //register base address
tim_handle.Init.Prescaler = 10800 - 1; // 108000000 / 10800 = 10000 -> speed of 1 count-up: 1 /10000 s = 0.1 ms
tim_handle.Init.Period = 5000 - 1; // 5000 x 0.1 ms = 500 ms = 0.5 s period */
tim_handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
tim_handle.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_Base_Init(&tim_handle); //configure the timer
HAL_NVIC_SetPriority(TIM2_IRQn, 2, 0); //set TIM2 interrupt priority
HAL_NVIC_EnableIRQ(TIM2_IRQn); //enable the interrupt to HAL
}
int main(void)
{
HAL_Init(); //making HAL configuration
SystemClock_Config(); //this function call sets the timers input clock to 108 Mhz (=108000000 Hz) */
init_external_led(); //initialize LED
init_timer(); //initialize TIM2
//Starts the TIM Base generation in interrupt mode.
HAL_TIM_Base_Start_IT(&tim_handle);
while (1) {
}
}
/*TIMER handler and callback*/
void TIM2_IRQHandler()
// the name of the function must come from the startup/startup_stm32f746xx.s file
{
HAL_TIM_IRQHandler(&tim_handle);
// set timer_handle structure for the TIM2 handler
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if (htim->Instance == tim_handle.Instance) {
HAL_GPIO_TogglePin(GPIOF, GPIO_PIN_7);
}
}
static void Error_Handler(void)
{}
static void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
//Configure the main internal regulator output voltage
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 216;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/**Activate the Over-Drive mode */
if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) {
Error_Handler();
}
}
<file_sep>/week-06/day-1/Ex_18_countBetweenCharacters/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_18_countBetweenCharacters)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_18_countBetweenCharacters main.c)<file_sep>/week-08/day-2/Ex_02_on_off/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
// Declare two global variables
uint32_t last_debounce_time = 0; // the last time the output pin was toggled
const uint32_t debounce_delay = 150; // the debounce time in ms (increase if the output flickers)
GPIO_InitTypeDef external_button;
volatile int push_counter = 0;
void init_outside_button()
{
//init GPIO external button
__HAL_RCC_GPIOB_CLK_ENABLE();
external_button.Pin = GPIO_PIN_4;
external_button.Mode = GPIO_MODE_IT_RISING;
external_button.Pull = GPIO_NOPULL;
external_button.Speed = GPIO_SPEED_FAST;
HAL_GPIO_Init(GPIOB, &external_button);
//set external button interrupt priority
HAL_NVIC_SetPriority(EXTI4_IRQn, 4, 0);
//enable the interrupt to HAL
HAL_NVIC_EnableIRQ(EXTI4_IRQn);
}
int main(void)
{
HAL_Init();
BSP_LED_Init(LED_GREEN);
init_outside_button();
for(;;);
}
//interrupt handler
void EXTI4_IRQHandler()
{
HAL_GPIO_EXTI_IRQHandler(external_button.Pin);
}
//declare callback function
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
if(GPIO_Pin == external_button.Pin){
uint32_t current_time = HAL_GetTick();
if (current_time < last_debounce_time + debounce_delay) {
// Do nothing (this is not a real button press)
return;
}
push_counter++;
if(push_counter % 10 == 5){
BSP_LED_On(LED_GREEN);
}
if(push_counter % 10 == 0){
BSP_LED_Off(LED_GREEN);
}
last_debounce_time = current_time;
}
}
<file_sep>/week-06/day-2/Ex_09_countLines/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_09_countLines C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_09_countLines main.c)<file_sep>/week-06/day-3/Ex_05_realloc/main.c
#include <stdio.h>
#include <stdlib.h>
// Prompt the user to enter a number. -> This number will be X.
// Allocate memory for X numbers.
// Prompt the user to enter X numbers.
// Allocate memory for Y numbers, which is the sum of the X numbers.
// Fill that array with from 1 to Y, then print them.
int main()
{
int* pointer = NULL;
int number_x;
printf("Give a number: \n");
scanf("%d", &number_x);
pointer = (int*)malloc(number_x * sizeof(int));
printf("Give %d numbers\n", number_x);
int index_for_y = 0;
for (int i = 0; i < number_x; ++i) {
printf("The %d. number: \n", i + 1);
scanf("%d", &pointer[i]);
index_for_y += pointer[i];
}
int *pointer_y = NULL;
pointer_y = (int*)malloc(index_for_y * sizeof(int));
for (int j = 0; j < index_for_y; ++j) {
pointer_y[j] = j + 1;
}
for (int k = 0; k < index_for_y; ++k) {
printf("%d ", pointer_y[k]);
}
puts("\n---------");
//checking the X pointer array
for (int i = 0; i < number_x; ++i) {
printf("%d ", pointer[i]);
}
//checking the value of sum
printf("\n%d\n", index_for_y);
//dealloc pointers
free(pointer);
free(pointer_y);
return 0;
}<file_sep>/week-03/day-2/Ex_02_Blog_post/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_02_Blog_post)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_02_Blog_post main.cpp)<file_sep>/week-01/day-4/Ex_17_SwapElements/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_17_SwapElements)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_17_SwapElements main.cpp)<file_sep>/week-02/day-2/Ex_10_swap/main.cpp
#include <iostream>
void swap(int* aPrt, int* bPrt);
int main ()
{
// Create a function which swaps the values of 'a' and 'b'
// This time use a void funtion and pointers
int a = 10;
int b = 316;
std::cout << a << " " << b << std::endl;
int* aPrt = &a;
int* bPrt = &b;
swap(aPrt, bPrt);
std::cout << a << " " << b << std::endl;
return 0;
}
void swap(int* aPrt, int* bPrt)
{
int temp;
temp = *aPrt;
*aPrt = *bPrt;
*bPrt = temp;
}<file_sep>/week-06/day-2/Ex_03_car/main.c
#include <stdio.h>
// Write a function that takes a car as an argument and prints all it's stats
// If the car is a Tesla it should not print it's gas level
enum car_type {
VOLVO,
TOYOTA,
LAND_ROVER,
TESLA
};
struct car {
enum car_type car_name;
double km;
double gas;
};
const char* get_car_name(enum car_type car_name)
{
switch (car_name)
{
case VOLVO: return "Volvo";
case TOYOTA: return "Toyota";
case LAND_ROVER: return "Land Rover";
case TESLA: return "TESLA";
}
}
void stats_of_cars(struct car one_car);
int main()
{
struct car volvo_car;
volvo_car.car_name = VOLVO;
volvo_car.km = 500000.00;
volvo_car.gas = 6.7;
stats_of_cars(volvo_car);
struct car toyota_car;
toyota_car.car_name = TOYOTA;
toyota_car.km = 250000.00;
toyota_car.gas = 5.7;
stats_of_cars(toyota_car);
struct car landrover_car;
landrover_car.car_name = LAND_ROVER;
landrover_car.km = 400000.00;
landrover_car.gas = 9.8;
stats_of_cars(landrover_car);
struct car tesla_car;
tesla_car.car_name = TESLA;
tesla_car.km = 200000.00;
stats_of_cars(tesla_car);
return 0;
}
void stats_of_cars(struct car one_car)
{
printf("%s drives %.2lf and its gas consuption is: ", get_car_name(one_car.car_name), one_car.km);
if (one_car.car_name != TESLA) {
printf("%.2lf.\n", one_car.gas);
} else {
printf("zero.\n");
}
}<file_sep>/week-06/day-1/Ex_24_ascii/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_24_ascii)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_24_ascii main.cpp)<file_sep>/week-01/day-4/Ex_19_ReverseList/main.cpp
#include <iostream>
#include <string>
int main(int argc, char* args[]) {
// - Create an array variable named `aj`
// with the following content: `[3, 4, 5, 6, 7]`
// - Reverse the order of the elements in `aj`
// - Print the elements of the reversed `aj`
/* funnnnnny!!! int aj[] = {3, 4, 5, 6, 7};
int size = sizeof(aj)/ sizeof(aj[0]);
int d[size];
int size2=size-1;
for (int i = 0; i < size; ++i) {
d[i] = aj [size2];
aj [size2] = aj [i];
aj [i] = d [i];
size2= size2-1;
std::cout << aj[i] << " ";
}
*/
int aj[] = {3, 4, 5, 6, 7};
int size = sizeof(aj)/ sizeof(aj[0]);
int d[size];
int size2=size-1;
for (int i = 0; i < size/2; ++i) {
d[i] = aj[size2];
aj[size2] = aj[i];
aj[i] = d[i];
size2 = size2 - 1;
}
for (int j = 0; j < size; ++j) {
std::cout << aj[j] << " ";
}
return 0;
}<file_sep>/week-06/day-1/Ex_11_oddOrEven/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_11_oddOrEven)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_11_oddOrEven main.c oddOrEven.h)<file_sep>/week-01/day-3/Ex_18_OddEven/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_18_OddEven)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_18_OddEven main.cpp)<file_sep>/week-01/day-3/Ex_21_PartyIndicator/main.cpp
#include <iostream>
int main(int argc, char* args[]) {
// Write a program that asks for two numbers
// The first number represents the number of girls that comes to a party, the
// second the boys
int numbGirl, numbBoy;
std::cout << "How many girls are there? " << std::endl;
std:: cin >> numbGirl;
std::cout << "How many boys are there? " << std::endl;
std:: cin >> numbBoy;
// It should print: The party is excellent!
// If the the number of girls and boys are equal and 20 or more people are coming to the party
//
// It should print: Quite cool party!
// If there are 20 or more people coming to the party but the girl - boy ratio is not 1-1
//
// It should print: Average party...
// If there are less people coming than 20
//
// It should print: Sausage party
// If no girls are coming, regardless the count of the people
bool a = ((numbBoy + numbGirl) >= 20);
bool b = (numbBoy == numbGirl);
bool c = (numbGirl != 0);
if (a && b) {
std::cout << "The party is excellent!" << std::endl;
} else if (a && !b && c) {
std::cout << "Quite cool party!" << std::endl;
} else if (!a && c) {
std::cout << "Average party..." << std::endl;
} else if (c != 1) {
std::cout << "Sausage party" << std::endl;
}
return 0;
}<file_sep>/week-06/day-1/Ex_01_helloMe/main.c
#include<stdio.h>
int main()
{
// Modify this program to greet you instead of the World!
//char name[50] = "<NAME>"; //csak az első 11 karakter helyére ír, amiből a 11. egy zárókarakter
//char name[11] = "<NAME>"; //11-nek kell lennie a tömbnek a zárókarakter miatt
char name[] = "<NAME>"; //másik megadási mód, ilyenkor automatikus a méretezés
printf("Hello, %s!", name);
return 0;
}<file_sep>/week-04/day-3/Ex_02_Zoo/byegg.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include "byegg.h"
std::string Byegg::breed()
{
return "laying eggs";
}<file_sep>/week-03/day-2/Ex_11_Sharpie_set/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_11_Sharpie_set)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_11_Sharpie_set main.cpp Sharpie.cpp Sharpie.h SharpieSet.cpp SharpieSet.h)<file_sep>/week-01/day-3/Ex_14_HelloUser/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_14_HelloUser)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_14_HelloUser main.cpp)<file_sep>/week-06/day-3/Ex_04_merge/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_04_merge C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_04_merge main.c)<file_sep>/week-04/day-4/Ex_01_Apples/Ex_01_Apples_Tests/applesTest.cpp
//
// Created by Lilla on 2019. 02. 07..
//
#include "gtest/gtest.h"
#include "apples.h"
TEST(apple_check, test_apple){
EXPECT_EQ(getApple(), "lapple");
}
<file_sep>/week-05/day-4/trialTrialEx3Restaurant/restaurant.h
//
// Created by Lilla on 2019. 02. 14..
//
#ifndef TRIALTRIALEX3RESTAURANT_RESTAURANT_H
#define TRIALTRIALEX3RESTAURANT_RESTAURANT_H
#include <string>
#include <vector>
#include "employee.h"
class Restaurant {
public:
Restaurant(std::string name, int foundYear);
void guestsArrived();
void hire(Employee &employee);
std::string toStringRestaurant();
private:
std::string _name;
int _foundationYear;
std::vector<Employee*> _employees;
};
#endif //TRIALTRIALEX3RESTAURANT_RESTAURANT_H
<file_sep>/week-02/day-3/Ex_03_Count_lines_2/main.cpp
#include <iostream>
#include <fstream>
#include <string>
int lineCounter(std::string fileName);
int main () {
// Write a function that takes a filename as string,
// then returns the number of lines the file contains.
// It should return zero if it can't open the file
std::string filename = "tuna.txt";
std::cout <<lineCounter(filename);
return 0;
}
int lineCounter(std::string fileName)
{
std::string line;
int counter = 0;
std::ifstream myfile(fileName);
try {
if (!myfile.is_open()){
throw 0;
}
} catch (int x) {
return x;
}
while (std::getline(myfile, line)){
counter++;
}
myfile.close();
return counter;
}<file_sep>/week-06/day-2/Ex_07_Digimon/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_Digimon C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_07_Digimon main.c digimon.h digimon.c)<file_sep>/week-06/day-1/Ex_05_cuboid/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_05_cuboid)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_05_cuboid main.c)<file_sep>/week-04/day-4/LessonPractice_1/LessonPractice1_Tests/myClassTest.cpp
//
// Created by Lilla on 2019. 02. 07..
//
<file_sep>/week-04/day-3/Ex_03_Flyable/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_Flyable)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_03_Flyable main.cpp)<file_sep>/week-05/day-1/TrialExam_Pirates/pirate.h
//
// Created by Lilla on 2019. 02. 11..
//
#ifndef TRIALEXAM_PIRATES_PIRATE_H
#define TRIALEXAM_PIRATES_PIRATE_H
#include <iostream>
class Pirate {
public:
Pirate(std::string name, bool isCaptain, bool isWoodLeg);
void work();
void party();
bool captain();
bool woodLeg();
std::string toString();
int getGold();
int _gold;
std::string _name;
std::string getName();
private:
bool _isCaptain;
bool _isWoodLeg;
int _healthPoint;
};
#endif //TRIALEXAM_PIRATES_PIRATE_H
<file_sep>/week-08/day-1/Ex_02_traffic_light_with_one_timer/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
TIM_HandleTypeDef tim;
GPIO_InitTypeDef LEDS;
uint16_t tim_val = 0;
static void Error_Handler(void);
static void SystemClock_Config(void);
void timer_init(void);
void init_external_led();
int main(void)
{
HAL_Init();
SystemClock_Config();
timer_init();
init_external_led();
HAL_TIM_Base_Start(&tim);
while (1) {
tim_val = __HAL_TIM_GET_COUNTER(&tim);
//if(tim_val >= 0 && tim_val <= 4999) {
if(tim_val == 0) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_RESET);
}
//if(tim_val >= 5000 && tim_val <= 9999) {
if(tim_val == 5000) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_RESET);
}
//if(tim_val >= 10000 && tim_val <= 14999) {
if(tim_val == 10000) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_SET);
}
//if(tim_val >= 15000 && tim_val <= 19999) {
if(tim_val == 15000) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_SET);
}
}
}
void timer_init(void) //init TIM2
{
__HAL_RCC_TIM2_CLK_ENABLE(); // we need to enable the TIM2
tim.Instance = TIM2;
tim.Init.Prescaler = 108000 - 1; /* 108000000/108000=1000 -> speed of 1 count-up: 1/1000 sec = 1 ms */
tim.Init.Period = 20000 - 1; /* 20000 x 1 ms = 20 second period */
tim.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
tim.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_Base_Init(&tim); // configure the timer
//HAL_TIM_Base_Start(&tim); // starting the timer
}
void init_external_led()
{
//initialize external LEDs on F port
__HAL_RCC_GPIOF_CLK_ENABLE(); //giving clock
LEDS.Pin = GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10;
LEDS.Mode = GPIO_MODE_OUTPUT_PP;
LEDS.Pull = GPIO_NOPULL;
LEDS.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOF, &LEDS); //first param: name of port, second param: name of structure
}
//error handler
static void Error_Handler(void)
{}
//system clock config to TIMERs
static void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/**Configure the main internal regulator output voltage */
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 216;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/**Activate the Over-Drive mode */
if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) {
Error_Handler();
}
}
<file_sep>/week-06/day-1/Ex_07_pi_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_pi_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_07_pi_2 main.c)<file_sep>/week-02/day-3/Ex_07_Logs_2/main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <algorithm>
// Read all data from 'log.txt'.
// Each line represents a log message from a web server
// Write a function that returns an array with the unique IP adresses.
// Write a function that returns the GET / POST request ratio.
std::vector<std::string> IPadress(std::string path);
std::string ratio(std::string path);
int main() {
std::string path = "log.txt";
std::vector<std::string> uniqueAddress = IPadress(path);
for (int i = 0; i < uniqueAddress.size(); ++i) {
std::cout << uniqueAddress[i] << std::endl;
}
std::cout << ratio(path);
return 0;
}
std::vector<std::string> IPadress(std::string path)
{
std::ifstream myFile(path);
try {
if (!myFile.is_open()) {
throw std::string("Openning error");
}
} catch (std::string &e) {
std::cout << e;
}
std::vector<std::string> IPadressVector;
std::string line;
while (std::getline(myFile, line)){
std::istringstream ss(line);
std::string words;
int counter = 0;
while(std::getline(ss, words, ' ')){
if (counter == 8){
if (std::find(IPadressVector.begin(), IPadressVector.end(), words) == IPadressVector.end()){
IPadressVector.push_back(words);
}
}
counter++;
}
}
return IPadressVector;
}
std::string ratio(std::string path)
{
std::ifstream myFile(path);
try {
if (!myFile.is_open()) {
throw std::string("Openning error");
}
} catch (std::string &e) {
std::cout << e;
}
std::string line;
int counterPost = 0;
int counterGet = 0;
while (std::getline(myFile, line)) {
std::istringstream ss(line);
std::string words;
int counter = 0;
while (std::getline(ss, words, ' ')) {
if (counter == 11) {
if (words == "POST") {
counterPost++;
} else {
counterGet++;
}
}
counter++;
}
}
return std::to_string(counterGet) + " / " + std::to_string(counterPost);
}
<file_sep>/week-01/day-3/Ex_31_DrawSquare/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_31_DrawSquare)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_31_DrawSquare main.cpp)<file_sep>/week-01/day-3/Ex_20_Printbigger/main.cpp
#include <iostream>
#include <iostream>
int main(int argc, char* args[]) {
int firstNum, secondNum;
// Write a program that asks for two numbers and prints the bigger one
std::cout << "Write the first number: " << std::endl;
std::cin >> firstNum;
std::cout << "Write the second number: " << std::endl;
std::cin >> secondNum;
if (firstNum > secondNum) {
std::cout << firstNum << std::endl;
} else {
std::cout << secondNum << std::endl;
}
return 0;
}<file_sep>/week-06/day-3/Ex_03_deallocate_memory/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_deallocate_memory C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_03_deallocate_memory main.c)<file_sep>/week-07/day-5/LCD_game/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
/* necessary include files */
#include "stm32746g_discovery_ts.h"
#include "stm32746g_discovery_lcd.h"
static void Error_Handler(void);
static void SystemClock_Config(void);
TS_StateTypeDef current_ts_status;
int main(void)
{
HAL_Init();
SystemClock_Config();
/* initializing LCD */
BSP_LCD_Init();
BSP_LCD_LayerDefaultInit(1, LCD_FB_START_ADDRESS);
BSP_LCD_SelectLayer(1);
BSP_LCD_SetFont(&LCD_DEFAULT_FONT);
BSP_LCD_SetBackColor(LCD_COLOR_WHITE);
BSP_LCD_Clear(LCD_COLOR_WHITE);
/* drawing a red circle */
BSP_LCD_SetTextColor(LCD_COLOR_RED);
BSP_LCD_FillCircle(50, 50, 30);
/* initializing TS (Touch Screen) */
BSP_TS_Init(480, 272);
uint8_t text1_on_LCD[] = "Let's play a game! Are you ready?"; //Beginning text
uint8_t text2_on_LCD[] = "Something else";
//Beginning text parameters on LCD
sFONT start_text_fonts_size = Font16; //Changing default font size
BSP_LCD_SetFont(&start_text_fonts_size); //Using font size function
BSP_LCD_Clear(LCD_COLOR_GREEN); //Green color LCD background
BSP_LCD_SetBackColor(LCD_COLOR_GREEN); //Green color text background
BSP_LCD_DisplayStringAt(0, 0, text1_on_LCD, CENTER_MODE);
HAL_Delay(500);
/* BSP_LCD_SetBackColor(LCD_COLOR_WHITE); //White color LCD background
BSP_LCD_Clear(LCD_COLOR_WHITE); //White color text background
BSP_LCD_DisplayStringAt(0, 0, text1_on_LCD, CENTER_MODE);
HAL_Delay(500);
*/
while (1) {
//Beginning status of TS
BSP_TS_GetState(¤t_ts_status);
if (current_ts_status.touchX[0] != 0 && current_ts_status.touchY[0] != 0) {
BSP_LCD_Clear(LCD_COLOR_WHITE);
BSP_LCD_DisplayStringAt(0, 0, text2_on_LCD, CENTER_MODE);
current_ts_status.touchX[0];
current_ts_status.touchY[0];
HAL_Delay(500);
}
}
}
static void Error_Handler(void)
{}
static void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/**Configure the main internal regulator output voltage */
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 216;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/**Activate the Over-Drive mode */
if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) {
Error_Handler();
}
}
#ifdef USE_FULL_ASSERT
void assert_failed(uint8_t *file, uint32_t line){}
#endif
<file_sep>/opencv_practice/image_to_gray.cpp
#include "practiceWeekHeader.h"
void changeImageGrayWithImread(cv::Mat originImg)
{
originImg = cv::imread("lena.jpg", cv::IMREAD_GRAYSCALE);
cv::namedWindow("gray image 1", cv::WINDOW_AUTOSIZE);
cv::moveWindow("gray image 1", 1000, 280);
cv::imshow("gray image 1", originImg);
}
void changeImageGrayWithCvtColor1(cv::Mat originImg)
{
originImg = cv::imread("lena.jpg");
cv::Mat grayImage;
cv::cvtColor(originImg, grayImage, cv::COLOR_RGB2GRAY);
cv::namedWindow("gray image 2", cv::WINDOW_AUTOSIZE);
cv::moveWindow("gray image 2", 1000, 560);
cv::imshow("gray image 2", grayImage);
}
void changeImageGrayWithCvtColor2(cv::Mat originImg)
{
originImg = cv::imread("lena.jpg");
cv::Mat grayImage;
cv::cvtColor(originImg, grayImage, cv::COLOR_BGR2GRAY);
cv::namedWindow("gray image 3", cv::WINDOW_AUTOSIZE);
cv::moveWindow("gray image 3", 250, 140);
cv::imshow("gray image 3", grayImage);
}<file_sep>/week-06/day-3/Ex_06_concat_strings/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_06_concat_strings C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_06_concat_strings main.c)<file_sep>/week-08/embedded_trial/second_task/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum{
MANUAL,
AUTOMATIC,
CVT,
SEMI_AUTOMATIC,
DUAL_DUTCH
} transmission_t;
typedef struct
{
char manufacturer_name[255]; //shorter than 256 characters
float price_of_car; // in euros, stored as a floating point number
int year_of_manufacture;
transmission_t type_of_transmission; // as a custom type
} car_t;
int get_cars_older_than(car_t* cars, int array_length, int be_older_than);
int get_transmission_count(car_t* cars, int array_length, transmission_t transmission);
int main() {
car_t list_of_cars[9];
list_of_cars[0].year_of_manufacture = 5;
list_of_cars[0].type_of_transmission = MANUAL;
list_of_cars[1].year_of_manufacture = 7;
list_of_cars[1].type_of_transmission = MANUAL;
list_of_cars[2].year_of_manufacture = 7;
list_of_cars[2].type_of_transmission = DUAL_DUTCH;
list_of_cars[3].year_of_manufacture = 4;
list_of_cars[3].type_of_transmission = SEMI_AUTOMATIC;
list_of_cars[4].year_of_manufacture = 4;
list_of_cars[4].type_of_transmission = CVT;
list_of_cars[5].year_of_manufacture = 6;
list_of_cars[5].type_of_transmission = SEMI_AUTOMATIC;
list_of_cars[6].year_of_manufacture = 2;
list_of_cars[6].type_of_transmission = MANUAL;
list_of_cars[7].year_of_manufacture = 2;
list_of_cars[7].type_of_transmission = CVT;
list_of_cars[8].year_of_manufacture = 9;
list_of_cars[8].type_of_transmission = AUTOMATIC;
int be_older_than = 6;
int array_length = 9;
int number_of_older_than_cars = get_cars_older_than(list_of_cars, array_length, be_older_than);
printf("%d\n", number_of_older_than_cars);
transmission_t transmission = CVT;
int number_of_cars_specic_transm = get_transmission_count(list_of_cars, array_length, transmission);
printf("%d\n", number_of_cars_specic_transm);
return 0;
}
int get_cars_older_than(car_t* cars, int array_length, int be_older_than)
{
int number_of_older_cars = 0;
for (int i = 0; i < array_length; ++i){
if (cars[i].year_of_manufacture > be_older_than)
{
number_of_older_cars++;
}
}
return number_of_older_cars;
}
int get_transmission_count(car_t* cars, int array_length, transmission_t transmission)
{
int number_cars_with_transmission = 0;
for (int i = 0; i < array_length; ++i){
if (cars[i].type_of_transmission == number_cars_with_transmission)
{
number_cars_with_transmission++;
}
}
return number_cars_with_transmission;
}<file_sep>/week-03/day-2/Ex_10_Petrol_station_2/station.cpp
//
// Created by Lilla on 2019. 02. 13..
//
#include <iostream>
#include "station.h"
Station::Station(int gasAmount)
{
_gasAmount = gasAmount;
}
void Station::fill(Car &onecar)
{
while (!onecar.isFull() && _gasAmount > 0) {
onecar.fill();
std::cout << "Filling car!" << std::endl;
_gasAmount--;
if (onecar.isFull()){
std::cout << "The remaining gas amount of the station :" << _gasAmount;
}
}
if (_gasAmount == 0){
std::cout << "No more petrol" << std::endl;
}
}
<file_sep>/week-01/day-3/Ex_07_FavNumb/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_7_FavNumb)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_7_FavNumb main.cpp)<file_sep>/week-02/day-1/Ex_10_isinlist_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_10_isinlist_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_10_isinlist_2 main.cpp)<file_sep>/week-01/day-3/Ex_13_Seconds/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_13_Seconds)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_13_Seconds main.cpp)<file_sep>/week-02/day-3/Ex_02_Print_each_line/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_02_Print_each_line)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_02_Print_each_line main.cpp)<file_sep>/week-06/day-1/Ex_20_isInSentence/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_20_isInSentence C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_20_isInSentence main.c)<file_sep>/week-08/function_templates_SKELETON/pwm_init.c
#include "interruption_templates.h"
GPIO_InitTypeDef PA15_LED_config; //PA 15 pin able to compare channel 1 with alternate function AF
TIM_HandleTypeDef pwm_tim;
TIM_OC_InitTypeDef sConfig;
void pwm_init(){
// GPIO led config //TIM3_CH1 PB4 pinnel és AF2 alternate functionnel is működik
__HAL_RCC_GPIOA_CLK_ENABLE(); //A port clock
PA15_LED_config.Pin = GPIO_PIN_15; //PA 15 pin able to compare channel 1 with alternate function AF
PA15_LED_config.Mode = GPIO_MODE_AF_PP; /* configure as output, in push-pull mode */
PA15_LED_config.Pull = GPIO_NOPULL;
PA15_LED_config.Speed = GPIO_SPEED_HIGH;
PA15_LED_config.Alternate = GPIO_AF1_TIM2; /* this alternate function we need to use TIM2 in output compare mode */
HAL_GPIO_Init(GPIOA, &PA15_LED_config);
//__HAL_RCC_GPIOB_CLK_ENABLE(); //B port clock
//LEDS.Pin = GPIO_PIN_4; // PB port 4 pin
//LEDS.Mode = GPIO_MODE_AF_PP; //same as PA port 15 pin
//LEDS.Pull = GPIO_NOPULL; //same as PA port 15 pin
//LEDS.Speed = GPIO_SPEED_HIGH; //same as PA port 15 pin
//LEDS.Alternate = GPIO_AF2_TIM3; //alternate function to TIM3 channel 1 with PB4 led pin
//HAL_GPIO_Init(GPIOB, &LEDS); //init B port's led in pwm mode
/* base timer config ***************************************************************************************************/
/* we need to enable the TIM2 */
__HAL_RCC_TIM2_CLK_ENABLE();
/* configuring the basic mode of your timer (which direction should it count, what is the maximum value, etc.) */
pwm_tim.Instance = TIM2;
pwm_tim.Init.Prescaler = 108 - 1; /* 108000000/108=1000000 -> speed of 1 count-up: 1/1000000 s = 0.001 ms */
pwm_tim.Init.Period = 100 - 1; /* 100 x 0.001 ms = 10 ms = 0.01 s period */
pwm_tim.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
pwm_tim.Init.CounterMode = TIM_COUNTERMODE_UP;
/* configuring the timer in PWM mode instead of calling HAL_TIM_Base_Init(&TimHandle) */
HAL_TIM_PWM_Init(&pwm_tim);
/* output compare config ***********************************************************************************************/
sConfig.Pulse = 50;
/* 50% * 0.01 s = 0.005 s: 0.005 low, then 0.005 s high; our eyes are not able to notice, that it is a vibrating light */
sConfig.OCMode = TIM_OCMODE_PWM1;
sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfig.OCFastMode = TIM_OCFAST_ENABLE;
HAL_TIM_PWM_ConfigChannel(&pwm_tim, &sConfig, TIM_CHANNEL_1);
/* starting PWM */
HAL_TIM_PWM_Start(&pwm_tim, TIM_CHANNEL_1);
}
<file_sep>/week-06/day-2/Ex_03_car/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_car C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_03_car main.c)<file_sep>/week-04/day-1/VideoPractice_02/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(VideoPractice_02)
set(CMAKE_CXX_STANDARD 14)
add_executable(VideoPractice_02 main.cpp mother.cpp mother.h daughter.cpp daughter.h)<file_sep>/week-01/day-3/Ex_23_WontCheat/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_23_WontCheat)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_23_WontCheat main.cpp)<file_sep>/week-06/day-2/Ex_02_sandwich/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_02_sandwich C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_02_sandwich main.c)<file_sep>/week-02/day-2/Ex_01_pointer_type/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_pointer_type)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_01_pointer_type main.cpp)<file_sep>/week-04/day-3/Ex_01_InstruStringedInstru/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_InstruStringedInstru)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_01_InstruStringedInstru main.cpp instrument.cpp instrument.h stringedinstrument.cpp stringedinstrument.h electricguitar.cpp electricguitar.h bassguitar.cpp bassguitar.h violin.cpp violin.h)<file_sep>/week-02/day-1/Ex_09_elementfinder_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_09_elementfinder_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_09_elementfinder_2 main.cpp)<file_sep>/week-04/day-3/Ex_04_Devices/printer2d.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_04_DEVICES_PRINTER2D_H
#define EX_04_DEVICES_PRINTER2D_H
#include "printer.h"
class Printer2D : public Printer {
public:
Printer2D (int sizeX, int sizeY);
std::string getSize() override;
protected:
int _sizeX;
int _sizeY;
};
#endif //EX_04_DEVICES_PRINTER2D_H
<file_sep>/week-07/day-3/inner_push_button_PI11_config/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
int main(void)
{
HAL_Init();
/* setting PI1 as output */
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOIEN;
GPIOI->MODER |= (GPIO_MODER_MODER1_0);
GPIOI->OTYPER &= ~(GPIO_OTYPER_OT_1);
GPIOI->OSPEEDR |= (GPIO_OSPEEDER_OSPEEDR1);
GPIOI->PUPDR &= ~(GPIO_PUPDR_PUPDR1);
/* setting PI11 as input */
GPIOI->MODER |= 0b0000100000000000;
uint32_t green_led = (1 << 1);
while (1) {
/* when button is pushed LED turns on, when released, then LED turns off */
if (GPIOI->IDR & (1 << 11)) {
GPIOI->BSRR = green_led;
} else {
GPIOI->BSRR = green_led << 16;
}
}
}
<file_sep>/week-02/day-1/Ex_16_findpart/main.cpp
#include <iostream>
#include <vector>
#include <algorithm>
std::vector<int> subInt (int paraNumb, std::vector<int> ¶Vector)
{
std::vector<int >::iterator findResult;
std::vector<int >zerovector;
for (findResult = paraVector.begin(); findResult < paraVector.end(); ++findResult) {
if (findResult == paraVector.end()) {
return zerovector;
} else {
zerovector.push_back(paraVector.at(paraNumb));
}
}
return zerovector;
}
int main(int argc, char* args[])
{
// Create a function that takes a number and a vector of numbers as a parameter
// Returns the indeces of the numbers in the vector where the first number is part of
// Returns an empty list if the number is not part any of the numbers in the vector
// Example:
std::vector<int> numbers = {1, 11, 34, 52, 61};
std::vector<int>newArray;
subInt(1, numbers);
// should print: `[0, 1, 4]`
subInt(0, numbers);
// should print: '[]'
for (int i = 0; i < newArray.size() ; ++i) {
newArray[i] = subInt(1, numbers);
std::cout<< newArray[i];
}
return 0;
}<file_sep>/week-04/day-3/Ex_01_InstruStringedInstru/electricguitar.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include "electricguitar.h"
ElectricGuitar::ElectricGuitar(int numberOfStrings) : StringedInstrument(numberOfStrings){
_name = "Electric Guitar";
}
ElectricGuitar::ElectricGuitar() : StringedInstrument()
{
_numberOfStrings = 6;
_name = "Electric Guitar";
}
std::string ElectricGuitar:: sound()
{
return "Twang";
}<file_sep>/mysql_practice/todo_database.sql
/*DROP DATABASE ToDo;*/
CREATE DATABASE IF NOT EXISTS todo;
USE todo;
CREATE TABLE IF NOT EXISTS ToDo
(
storyID INTEGER UNSIGNED NULL
);
CREATE TABLE IF NOT EXISTS Doing
(
storyID INTEGER UNSIGNED NULL
);
CREATE TABLE IF NOT EXISTS Review
(
storyID INTEGER UNSIGNED NULL
);
CREATE TABLE IF NOT EXISTS Done
(
storyID INTEGER UNSIGNED NULL
);
CREATE TABLE IF NOT EXISTS Story
(
storyID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
storyText TEXT
);
INSERT INTO Story (storyText)
VALUES ("shopping"),("cleaning"),("cooking"), ("study");
INSERT ToDO (storyID)
SELECT storyID FROM Story
WHERE storyTEXT = "shopping";
INSERT ToDO (storyID)
SELECT storyID FROM Story
WHERE storyTEXT = "study";
INSERT Done (storyID)
SELECT storyID FROM Story
WHERE storyTEXT = "cleaning";
SELECT storyTEXT AS TODO FROM ToDo
INNER JOIN Story
ON story.storyID = ToDo.storyID;
SELECT storyTEXT AS DOING FROM Doing
INNER JOIN Story
ON story.storyID = Doing.storyID;
SELECT storyTEXT AS REVIEW FROM Review
INNER JOIN Story
ON story.storyID = Review.storyID;
SELECT storyTEXT AS DONE FROM Done
INNER JOIN Story
ON story.storyID = Done.storyID;
/*DROP DATABASE ToDo;*/
<file_sep>/week-06/day-1/Ex_07_pi/main.c
#include <stdio.h>
#include <stdlib.h>
#define PI 3.14
// define a variable called PI with the value of 3.14
// create a function which takes the radius of a circle as a parameter
// and return the area of that cirle
// area = radius * radius * PI
float areaMeasure(float radius);
int main()
{
float radius;
printf("Give me the radius: \n");
scanf("%f", &radius);
printf("%.2f", areaMeasure(radius));
return 0;
}
float areaMeasure(float radius)
{
float area;
area = radius * radius * PI;
return area;
}<file_sep>/week-04/day-2/Ex_01_GFOrganization/sponsor.h
//
// Created by Lilla on 2019. 02. 05..
//
#ifndef EX_01_GFORGANIZATION_SPONSOR_H
#define EX_01_GFORGANIZATION_SPONSOR_H
#include "person.h"
class Sponsor : public Person{
public:
Sponsor();
Sponsor(std::string name, int age, Gender gender, std::string company);
void introduce() override;
void getGoal() override;
void hire();
protected:
private:
std::string _company;
int _hiredStudents;
};
#endif //EX_01_GFORGANIZATION_SPONSOR_H
<file_sep>/week-06/day-1/Ex_06_guessTheNumber/main.c
// Write a program that stores a number, and the user has to figure it out.
// The user can input guesses, after each guess the program would tell one
// of the following:
//
// The stored number is higher
// The stried number is lower
// You found the number: 8
#include<stdio.h>
int main()
{
int guessnumb, tempNumb;
printf("Enter your guessed number: \n");
scanf("%d/n", &guessnumb); //don't use space after %d, because scanf() reads only the firs close character
do{
printf("Write a number :");
scanf("%d/n", &tempNumb); //don't use space after %d, because scanf() reads only the firs close character
if (tempNumb > guessnumb){
printf("The stored number is lower.\n");
} else if (tempNumb < guessnumb) {
printf("The stored number is higher.\n");
}
} while (guessnumb != tempNumb);
printf("You found the number: %d\n", tempNumb);
return 0;
}
<file_sep>/week-01/day-3/Ex_07_FavNumb/main.cpp
#include <iostream>
int main(int argc, char* args[]) {
/* int a = 12;
a += 4;
std::cout << a << std::endl;
int b = 12;
b -= 4;
std::cout << b << std::endl;
int c = 12;
std::cout << c++ << " \n" << std::endl;
std::cout << c << " \n" << std::endl;
int d = 12;
std::cout << ++d << std::endl;
std::cout << d << std::endl;
int e = 12;
std::cout << e-- << " \n"<< std::endl;
std::cout << e << " \n"<< std::endl;
int f = 12;
std::cout << --f << std::endl;
std::cout << f << std::endl;
int g = 12;
g *= 3;
std::cout << g << std::endl;
int h = 12;
h /= 3;
std::cout << h << std::endl;
int i = 12;
i %= 7;
std::cout << i << std::endl; */
// Store your favorite number in a variable (as an integer)
int favNum = 30;
// And print it like this: "My favorite number is: 8"
std::cout << "My favorite number is: " << favNum << std::endl;
return 0;
}<file_sep>/week-05/day-4/trialTrialEx3Restaurant/main.cpp
#include <iostream>
#include "employee.h"
#include "restaurant.h"
#include "waitor.h"
#include "chef.h"
#include "manager.h"
int main()
{
Waitor waiter ("Balazs", 5);
Chef c ("Top", 6);
Chef c2 ("Vice",4);
Manager m("Fread", 7);
Restaurant r("Riso", 50);
r.hire(c);
r.hire(waiter);
r.hire(m);
r.hire(c2);
c.cook("Soup");
c.cook("Pasta");
c.cook("Pizza");
c2.cook("Soup");
r.guestsArrived();
m.haveAmeeting();
m.haveAmeeting();
m.haveAmeeting();
std::cout << c2.toString() << std::endl;
std::cout << c.toString() << std::endl << std::endl;
std::cout << r.toStringRestaurant();
return 0;
}<file_sep>/week-01/day-3/Ex_27_FizzBuzz/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_27_FizzBuzz)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_27_FizzBuzz main.cpp)<file_sep>/week-06/day-1/Ex_21_indexOfIt/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_21_indexOfIt C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_21_indexOfIt main.c)<file_sep>/week-05/day-1/ExampleExam_Shelter/animal.cpp
//
// Created by Lilla on 2019. 02. 11..
//
#include "animal.h"
#include <iostream>
Animal::Animal()
{
}
Animal::Animal(std::string name, int healthCost)
{
_name = name;
_healthCost = healthCost;
}
std::string Animal::toString() {
if (_isHealty) {
return _name + " is healty and adoptable";
} else {
return _name + " is not healty (" + std::to_string(_healthCost) + "eur) and not adoptaple";
}
}
<file_sep>/week-03/day-2/Ex_10_Petrol_station_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_10_Petrol_station_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_10_Petrol_station_2 main.cpp station.cpp station.h car.cpp car.h)<file_sep>/week-04/day-1/ExBefInheritance_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(ExBefInheritance_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(ExBefInheritance_2 main.cpp person.cpp person.h mentor.cpp mentor.h)<file_sep>/week-06/day-3/Lession_practice/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Lession_practice C)
set(CMAKE_C_STANDARD 99)
add_executable(Lession_practice main.c)<file_sep>/week-03/day-2/Ex_03_Animal/main.cpp
#include <iostream>
#include <string>
//Create an Animal class
// Every animal has a hunger value, which is a whole number
// Every animal has a thirst value, which is a whole number
// when creating a new animal object these values are created with the default 50 value
//Every animal can eat() which decreases their hunger by one
// Every animal can drink() which decreases their thirst by one
// Every animal can play() which increases both by one
class Animal
{
public:
void eat()
{
_hunger--;
std::cout << "The hungry: " <<_hunger << std::endl;
}
void drink()
{
_thirst--;
std::cout << "The thirst: " << _thirst << std::endl;
}
void play()
{
//_thirst++;
//_hunger++;
//std::cout << "The hungry and the thirst: " << _hunger << " and " << _thirst << std::endl;
eat();
drink();
}
private:
int _hunger = 50;
int _thirst = 50;
};
int main(int argc, char* args[])
{
Animal tiger;
tiger.eat();
std::cout << "\n";
Animal lion;
lion.play();
lion.drink();
return 0;
}<file_sep>/week-01/day-3/Ex_35_DrawChessTable/main.cpp
#include <iostream>
int main(int argc, char* args[])
{
// Crate a program that draws a chess table like this
//
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
int chessRow = 8;
for (int i = 0; i < chessRow; ++i) {
for (int j = 0; j < chessRow; ++j) {
if (i % 2 == 1) { //the case of odd rows
while (j < chessRow / 2) {
std::cout << " %";
++j;
}
} else {
while (j < chessRow / 2) { // //the case of even rows
std::cout << "% ";
++j;
}
}
}
std::cout << std::endl;
}
return 0;
}
<file_sep>/week-05/day-4/trialTrialEx1Matrix/main.cpp
#include <iostream>
#include <vector>
std::vector<std::vector<int>> calculateMaxMatrix(std::vector<std::vector<int>> &input1, std::vector<std::vector<int>> &input2);
bool doesFirstTestPass()
{
//arrange
std::vector<std::vector<int>> firstInput = {{2, 1},{0, 1}};
std::vector<std::vector<int>> secondInput = {{0, 3},{-1, 1}};
//act
std::vector<std::vector<int>> result = calculateMaxMatrix(firstInput, secondInput);
//assert
std::vector<std::vector<int>> expected = {{2, 3},{0, 1}};
return (result == expected);
}
bool doesSecondTestPass()
{
//arrange
std::vector<std::vector<int>> firstInput = {{2, 1, 3},{0, 1, 3},{5, 6, -5}};
std::vector<std::vector<int>> secondInput = {{5, 0, 3},{-8,-1, 1},{6,7,8}};
//act
std::vector<std::vector<int>> result = calculateMaxMatrix(firstInput, secondInput);
//assert
std::vector<std::vector<int>> expected = {{5, 1, 3},{0, 1, 3}, {6, 7, 8}};
return (result == expected);
}
int main()
{
std::cout << "First test result is: " << doesFirstTestPass()<< std::endl;
std::cout << "Second test result is: " << doesSecondTestPass()<< std::endl;
return 0;
}
std::vector<std::vector<int>> calculateMaxMatrix(std::vector<std::vector<int>> &input1, std::vector<std::vector<int>> &input2)
{
std::vector<std::vector<int>> result;
result.resize(input1.size()); //átméretezem, hogy akkora legyen, mint a paraméter mátrix
for (int i = 0; i < input1.size(); ++i) {
result[i].resize(input1[i].size()); //
for (int j = 0; j < input2.size(); ++j) {
if (input1[i][j] > input2[i][j]){
result[i][j] = input1[i][j];
} else{
result[i][j] = input2[i][j];
}
}
}
//std::vector<std::vector<int>> result = input1; //így is el lehet kezdeni
return result;
}<file_sep>/week-04/day-1/VideoPractice_02/mother.cpp
//
// Created by Lilla on 2019. 02. 05..
//
#include <iostream>
#include "mother.h"
#include "daughter.h"
Mother::Mother()
{
std::cout << "I'm the mother constructor" << std::endl;
}
Mother::~Mother()
{
std::cout << "I'm the mother deconstructor" << std::endl;
}
<file_sep>/week-05/day-4/trialTrialEx3Restaurant/employee.h
//
// Created by Lilla on 2019. 02. 14..
//
#ifndef TRIALTRIALEX3RESTAURANT_EMPLOYEE_H
#define TRIALTRIALEX3RESTAURANT_EMPLOYEE_H
#include <string>
class Employee {
public:
Employee(std::string name, int experience = 0); //a default van utoljára
virtual void work() = 0;
virtual std::string toString();
private:
std::string _name;
protected:
int _experience;
};
#endif //TRIALTRIALEX3RESTAURANT_EMPLOYEE_H
<file_sep>/week-03/day-2/Ex_04_Sharpie/Sharpie.h
//
// Created by Lilla on 2019. 01. 29..
//
//Create Sharpie class
// We should know about each sharpie their
// color(which should be a string), width (which will be a floating point number), inkAmount (another floating point number)
// When creating one, we need to specify the color and the width
// Every sharpie is created with a default 100 as inkAmount
// We can use() the sharpie objects
// which decreases inkAmount
#ifndef EX_04_SHARPIE_SHARPIE_H
#define EX_04_SHARPIE_SHARPIE_H
#include <string>
class Sharpie
{
public:
Sharpie(std::string color, float width);
int use();
private:
std::string _color;
float _width;
float _inkAmount = 100;
};
#endif //EX_04_SHARPIE_SHARPIE_H
<file_sep>/week-03/day-2/Ex_11_Sharpie_set/SharpieSet.cpp
//
// Created by Lilla on 2019. 02. 01..
//
#include <iostream>
#include <vector>
#include "SharpieSet.h"
#include "Sharpie.h"
sharpieSet::sharpieSet(std::vector<Sharpie> something)
{
sharpies = something;
}
int sharpieSet::countUsable()
{
int tempSharpies = 0;
for (int i = 0; i < sharpies.size(); i++) {
if (sharpies[i].getInkAmount() > 0) {
}
tempSharpies++;
}
return tempSharpies;
}
void sharpieSet::removeTrash()
{
for (int i = 0; i < sharpies.size(); i++) {
if (sharpies[i].getInkAmount() == 0) {
sharpies.erase(sharpies.begin() + i);
i--;
}
}
}
<file_sep>/week-06/day-4/Ex_01_create_linked_list/linked_list.h
//
// Created by Lilla on 2019. 02. 28..
//
#ifndef EX_01_CREATE_LINKED_LIST_LINKED_LIST_H
#define EX_01_CREATE_LINKED_LIST_LINKED_LIST_H
typedef struct node
{
int value;
struct node * next;
} node_t;
//Function for creating a simple linked list
node_t *linked_list_creator(int node_value);
//Function for deallocating a linkedlist
void linked_list_dealloc(node_t * linked_list);
//Function for printing node memory addresses and the stored values
void linked_list_print(node_t * linked_list);
//Function for inserting a value in a new node at the end of a list
void linked_list_push_back(node_t * linked_list, int new_node_value);
//Function for inserting a value in a new node at the beginning of a list
void linked_list_push_front(node_t ** linked_list, int new_node_value);
//Function for inserting a value in after a given node
void linked_list_insert(node_t * linked_list_insert_after, int new_node_value);
//Function for returning the number of nodes in a given linked list
int linked_list_size(node_t * linked_list);
//Function for deciding if a linked list is empty or not
int linked_list_empty(node_t * linked_list);
//Function for deleting the first element of a linked list
void linked_list_pop_front(node_t ** linked_list);
//Function for removing an element of a linked list by the value
int linked_list_remove(node_t ** linked_list, int searched_node_value);
//Function for searching a node of a linked list by a value
node_t * linked_list_search(node_t * linked_list, int searched_node_value);
#endif //EX_01_CREATE_LINKED_LIST_LINKED_LIST_H
<file_sep>/week-05/day-1/TrialExam_Pirates/main.cpp
/*Write a program which can store pirates in a ship.
Pirate:
- A pirate has a name, an amount of gold and health points, the default value of which is 10.
- A pirate might be a captain and may have a wooden leg.
- You must create the following methods:
- if a pirate is a captain:
- `work()` which increases the amount of gold possessed by that pirate by 10 and decrease the HP by 5.
- `party()` which increases the HP by 10.
- if the pirate is not a captain:
- `work()` which increases the amount of gold by 1 and decreases the HP by 1.
- `party()` which increases the HP by 1.
- if the pirate has a wooden leg, then the string that is returned by the function must look like this:
- Hello, I'm Jack. I have a wooden leg and 20 golds.
- If not:
- Hello, I'm Jack. I still have my real legs and 20 golds.
Ship:
- It should have a list of pirates.
- You must be able to add new pirates to the ship. It must have only one captain!
- You must create the following methods:
- `getPoorPirates()` which returns a list of names containing the pirates that
- have a wooden leg and have less than 15 golds
- `getGolds()` which returns the sum of gold owned by the pirates of that particular ship
- `lastDayOnTheShip()` which calls the pirates' `party()` method.
- `prepareForBattle()` which calls
- the pirates' `work()` method 5 times
- then the ship's `lastDayOnTheShip()` method.
*/
#include <iostream>
#include "pirate.h"
#include "ship.h"
int main()
{
Pirate pirate1("<NAME>", true, false);
Pirate pirate2("Captain Hook", true, true);
Pirate pirate3("Blackburn 'Weasel' Lore", false, true);
std::cout << pirate1.toString() << std::endl;
std::cout << pirate2.toString() << std::endl;
std::cout << pirate3.toString() << std::endl;
Ship ship;
ship.addPirate(pirate1);
ship.addPirate(pirate2);
ship.addPirate(pirate3);
ship.prepareForBattle();
ship.lastDayOnTheShip();
std::cout << "The names of the poor pirates are: " << std::endl;
std::vector<std::string> poorPirateNames = ship.getPoorPirates();
for (int i = 0; i < poorPirateNames.size(); ++i) {
std::cout << "\t" << poorPirateNames[i] << std::endl;
}
std::cout << "The total amount of gold on the ship is " <<ship.getGolds() << std::endl;
return 0;
}<file_sep>/week-01/day-4/Ex_02_Greet/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_02_Greet)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_02_Greet main.cpp)<file_sep>/week-04/day-3/VideoPractice_1/main.cpp
#include <iostream>
class fridge
{
protected:
bool HasFreon;
public:
int Temp;
};
class truck
{
private:
int Gas; //alapesetben ez private és nem látja a derived class
public:
int Speed;
void setGas(int mGas){
Gas = mGas;
}
int getGas(){ //ezzel tudok visszahatni a private member Gas-re
return Gas + 30;
}
};
class freezetruck : public truck, public fridge
{
public:
void setFreon(){
this-> HasFreon = true;
}
};
int main() {
freezetruck mTruck;
mTruck.Speed = 100;
mTruck.Temp = 20;
std::cout << mTruck.Speed << std::endl;
std::cout << mTruck.Temp << std::endl;
std::cout << "\n" << std::endl;
//ez az eset nem működik, mert a Gas private member
//mTruck.setGas(500);
//std::cout << mTruck.Gas << std::endl;
mTruck.setGas(500); //a Gas helyére 500 kerül
std::cout << mTruck.getGas() << std::endl;
std::cout << "\n" << std::endl;
//mTruck.HasFreon = true; //alapesetben nem működik, mert private function
mTruck.setFreon();
//std::cout << mTruck.setFreon() << std::endl; nem lehet kiprintelni!
return 0;
}<file_sep>/week-04/weekend/ex_01/main.cpp
// Create a function named `rotateMatrix` that takes an n×n integer matrix (vector of vectors) as parameter
// and returns a matrix which elements are rotated 90 degrees clockwise.
#include <iostream>
#include <vector>
/*std::vector<std::vector<int>> rotateMatrix(std::vector<std::vector<int>> zero)
{
int tempnumb;
std::vector<std::vector<int>> tempMatrix;
for (int i = 0; i < zero.size(); ++i) {
for (int j = 0; j < zero.size(); ++j) {
tempMatrix[i][j] = zero[i][j];
}
}
for (int i = 0; i < tempMatrix.size(); ++i) {
for (int j = 0; j < tempMatrix.size(); ++j) {
tempnumb = tempMatrix[i][j];
tempMatrix [i][j] = tempMatrix[j][i];
tempMatrix[j][i] = tempnumb;
}
}
for (int k = 0; k < tempMatrix.size(); ++k) {
for (int i = 0; i < tempMatrix.size()/2; ++i) {
tempnumb = tempMatrix [k][i];
tempMatrix [k][i] = tempMatrix[i][k];
tempMatrix[i][k] = tempnumb;
}
}
return tempMatrix;
}
void printMatrix(const std::vector<std::vector<int>>& matrix)
{
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
*/
int main() {
std::vector<std::vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
/*std::vector<std::vector<int>> tempMainMatrix = rotatematrix(matrix);
for (int i = 0; i < tempMainMatrix.size(); ++i) {
for (int j = 0; j < tempMainMatrix.size(); ++j) {
std::cout << tempMainMatrix[i][j];
}
}*/
int tempnumb = 0;
/*for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix.size(); ++j) {
tempnumb = matrix[i][j];
matrix [i][j] = matrix[j][i];
matrix[j][i] = tempnumb;
}
}*/
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix.size()/2; ++j) {
tempnumb = matrix[i][j];
matrix [i][j] = matrix[i][matrix.size()-1-j];
matrix[i][matrix.size()-1-j] = tempnumb;
}
}
for (int i = 0; i < matrix.size()/2; ++i) {
for (int j = 0; j < matrix.size(); ++j) {
tempnumb = matrix[i][j];
matrix [i][j] = matrix[i][matrix.size()-1-j];
matrix[i][matrix.size()-1-j] = tempnumb;
}
}
for (int k = 0; k < matrix.size(); ++k) {
for (int i = 0; i < matrix.size(); ++i) {
std::cout << matrix[k][i] << " ";
}
std::cout << "\n";
}
//std::vector<std::vector<int>> rotatedMatrix = rotateMatrix(matrix);
//printMatrix(rotatedMatrix);
return 0;
}
<file_sep>/week-03/day-3/EX_02_numberadder/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(EX_02_numberadder)
set(CMAKE_CXX_STANDARD 14)
add_executable(EX_02_numberadder main.cpp)<file_sep>/week-06/day-2/Ex_12_smartPhones/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_12_smartPhones C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_12_smartPhones main.c)<file_sep>/week-01/day-4/Ex_10_ChangeElement/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_10_ChangeElement)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_10_ChangeElement main.cpp)<file_sep>/week-08/function_templates_SKELETON/user_button_init.c
#include "interruption_templates.h"
//init user_button for interrupt handle
void init_user_button(void)
{
__HAL_RCC_GPIOI_CLK_ENABLE(); // enable the GPIOI clock
user_button_handle.Pin = GPIO_PIN_11; // the pin is the PI11
user_button_handle.Pull = GPIO_NOPULL;
user_button_handle.Speed = GPIO_SPEED_FAST; // port speed to fast
user_button_handle.Mode = GPIO_MODE_IT_RISING; // our mode is interrupt on rising edge
//user_button_handle.Mode = GPIO_MODE_IT_FALLING; // our mode is interrupt on falling edge
//user_button_handle.Mode = GPIO_MODE_IT_RISING_FALLING;
HAL_GPIO_Init(GPIOI, &user_button_handle); // init PI11 user button
HAL_NVIC_SetPriority(EXTI15_10_IRQn, 4, 0); //set blue PI11 user button interrupt priority //a 11 a 10 és a 15 között van
HAL_NVIC_EnableIRQ(EXTI15_10_IRQn); //enable the interrupt to HAL
}
<file_sep>/week-01/day-3/Ex_15_Mile_to_km/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_15_Mile_to_km)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_15_Mile_to_km main.cpp)<file_sep>/week-03/day-2/Ex_10_Petrol_station/car.h
//
// Created by Lilla on 2019. 01. 30..
//
#ifndef EX_10_PETROL_STATION_CAR_H
#define EX_10_PETROL_STATION_CAR_H
class Car {
public:
Car(int capacity, int gasAmount);
void fill();
bool isFull();
int gasAmount_;
int capacity_;
private:
};
#endif //EX_10_PETROL_STATION_CAR_H
<file_sep>/opencv_practice/practiceWeekHeader.h
#pragma once
#include <iostream>
#include <opencv2/opencv.hpp>
//using namespace std;
//using namespace cv;
//----------START-------------
void finishedFunctions(cv::Mat originImg, cv::Mat originImgToEllipse);
//----------TOPICS------------
void display_basic_image_with_error_handler(cv::Mat originImg);
void brightFunctions(cv::Mat originImg);
void contrastFunctions(cv::Mat originImg);
void grayFunctions(cv::Mat originImg);
void blendFunctions();
void drawFunctions(cv::Mat originImg, cv::Mat originImgToEllipse);
void changeImageBrightnessWithScalar(cv::Mat originImg);
void changeImageBrightnessWithConvertTo(cv::Mat originImg);
void changeImageBrightnessPixelByPixel(cv::Mat originImg);
void changeImageContrastWithOperators(cv::Mat originImg);
void changeImageContrastWithConvertTo(cv::Mat originImg);
void changeImageContrastPixelByPixel(cv::Mat originImg);
void blendImagesWithAddWeighted();
void changeImageGrayWithImread(cv::Mat originImg);
void changeImageGrayWithCvtColor1(cv::Mat originImg);
void changeImageGrayWithCvtColor2(cv::Mat originImg);
void drawLine();
void drawEllipse(cv::Mat originImgToEllipse);
void drawCircle(cv::Mat origin);<file_sep>/week-04/day-1/VideoPractice_01/mother.h
//
// Created by Lilla on 2019. 02. 05..
//
#ifndef VIDEOPRACTICE_MOTHER_H
#define VIDEOPRACTICE_MOTHER_H
class Mother {
public:
Mother();
void sayName();
int publicv;
protected:
int protectedv;
private:
int privatev;
};
#endif //VIDEOPRACTICE_MOTHER_H
<file_sep>/week-02/day-1/Ex_14_hewillnever_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_14_hewillnever_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_14_hewillnever_2 main.cpp)<file_sep>/week-06/day-1/Ex_18_countBetweenCharacters/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int count_between_chars(int * word);
int main()
{
// Create a function which takes a string as a parameter and
// returns the number of characters between two repeating characters
// the repeating char can be a local variable in the function itself or
// it can be passed to the function as parameter
char *word = "Programming";
// the output should be: 6 (in this case the repeating char was 'g')
printf("%d\n", &word);// memóriacímet ad vissza (int)
printf("%s\n", word);//stringet ad vissza
printf("%d", count_between_chars(&word));
return 0;
}
int count_between_chars(int * word)
{
int indexFirst = 0;
char doubledChar = 'g';
char newArray[20];
strcpy(newArray, *word);
while(newArray[indexFirst] != doubledChar){
indexFirst++;
}
int indexSecond = indexFirst + 1;
while((newArray[indexSecond]) != doubledChar){
indexSecond++;
}
return (indexSecond - indexFirst - 1);
}<file_sep>/week-02/day-1/Ex_15_student_counter/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_15_student_counter)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_15_student_counter main.cpp)<file_sep>/week-04/day-3/Ex_04_Devices/printer2d.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include <iostream>
#include "printer2d.h"
Printer2D::Printer2D(int sizeX, int sizeY)
{
_sizeX = sizeX;
_sizeY = sizeY;
}
std::string Printer2D::getSize()
{
return (std::to_string(_sizeX) + " X " + std::to_string(_sizeY));
}<file_sep>/week-08/function_templates_SKELETON/important_BSP_functions.c
#include "interruption_templates.h"
//-------------------------------------
//init PI11 button wit BSP
//BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_GPIO);
//-------------------------------------
//Returns the selected button state.
//The Button GPIO pin value
//BSP_PB_GetState(BUTTON_KEY);
//-------------------------------------
//init PI1 led - LED1 or LED_GREEN
//BSP_LED_Init(LED1);
//-------------------------------------
//turning on and off led
//BSP_LED_On(LED1);
//BSP_LED_Off(LED1);
//BSP_LED_Toggle(LED1);
<file_sep>/week-08/day-1/Ex_03_time_keeper/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
#include <string.h>
#define UART_PUTCHAR int __io_putchar(int ch)
UART_HandleTypeDef uart;
GPIO_InitTypeDef GPIOTxConfig; //the uart config for general purpose without BSP
GPIO_InitTypeDef GPIORxConfig; //the uart config for general purpose without BSP
TIM_HandleTypeDef tim;
uint16_t tim_val1; //variable to store the actual value of the timer's register (CNT)
uint32_t user_number = 0;
uint8_t time_as_string[5];
static void Error_Handler(void);
static void SystemClock_Config(void);
void init_GPIO_uart();
void timer_init(void);
time_as_string_2[6];
int main(void) {
HAL_Init();
SystemClock_Config();
init_GPIO_uart();
//Ask for value
//memset(time_as_string, '\0', 5);
printf("Set the timer in this format: wx.yz\r\n");
HAL_UART_Receive(&uart, (uint8_t*) time_as_string, 5, 0xFFFF);
strcpy(time_as_string_2, time_as_string);
printf("\r\n%s\r\n", time_as_string_2);
//(uint32_t)???
uint8_t * prt;
user_number = strtol(time_as_string_2, &prt, 10) * 10000;
uint8_t * temp = strtok(prt, ".");
user_number += (strtol(temp, &prt, 10) *100);
printf("user number %u divide by 5 means prescaler counts until %u\r\n", user_number, user_number/5);
timer_init();
HAL_TIM_Base_Start(&tim); // starting the timer
tim_val1 = __HAL_TIM_GET_COUNTER(&tim);
printf("%d first get tim counter \r\n", tim_val1);
while (1) {
tim_val1 = __HAL_TIM_GET_COUNTER(&tim);
//check tim_val_1
if(tim_val1 == 5000){
printf("tim val 5000\r\n");
}
if(tim_val1 == 2000){
printf("tim val 2000\r\n");
}
if(tim_val1 == 5000){
printf("tim val 5000\r\n");
}
/*if (tim_val1 == 0) {
printf("%d counting from up to down \r\n", tim_val1);
}*/
if (tim_val1 == (user_number/5 - 1)) {
printf("%s seconds elapsed \r\n", time_as_string_2);
printf("%d mseconds elapsed \r\n", tim_val1);
HAL_NVIC_SystemReset();
}
if(tim_val1 == 2000){
printf("tim val 2000\r\n");
}
}
}
void timer_init(void) {
__HAL_RCC_TIM2_CLK_ENABLE()
; // we need to enable the TIM2
tim.Instance = TIM2;
tim.Init.Prescaler = 54000 - 1; /* 108000000/54000=10000 -> speed of 1 count-up: 1/2000 sec = 0.5 ms */
//tim.Init.Period = 10000- 1; /* 10000 XYza x 0.5 ms = XY.za 5 second period */
tim.Init.Period = user_number/5 - 1; /* 10000 * XYza x 0.5 ms = XY.za 5 second period */
tim.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
tim.Init.CounterMode = TIM_COUNTERMODE_DOWN;
HAL_TIM_Base_Init(&tim); // configure the timer
}
void init_GPIO_uart() {
//init uart for GPIO purpose with HAL
//PA9 port 9 pin with AF7 alternate function means USART1_TX - no visible/connecting pin
//PB9 port 7 pint with AF7 alternate function means USART1_RX - no visible/connecting pin
/* enable GPIO clock for A and B port*/
__HAL_RCC_GPIOA_CLK_ENABLE()
;
__HAL_RCC_GPIOB_CLK_ENABLE()
;
/* configure GPIO for UART transmit line */
GPIOTxConfig.Pin = GPIO_PIN_9; //chose PA port 9 pin
GPIOTxConfig.Mode = GPIO_MODE_AF_PP;
GPIOTxConfig.Pull = GPIO_NOPULL;
GPIOTxConfig.Speed = GPIO_SPEED_FAST;
GPIOTxConfig.Alternate = GPIO_AF7_USART1;
HAL_GPIO_Init(GPIOA, &GPIOTxConfig);
/* configure GPIO for UART receive line */
GPIORxConfig.Pin = GPIO_PIN_7;
GPIORxConfig.Mode = GPIO_MODE_AF_PP;
GPIOTxConfig.Pull = GPIO_NOPULL;
GPIORxConfig.Speed = GPIO_SPEED_FAST;
GPIORxConfig.Alternate = GPIO_AF7_USART1;
HAL_GPIO_Init(GPIOB, &GPIORxConfig);
/* enable the clock of the used peripherial instance */
__HAL_RCC_USART1_CLK_ENABLE()
;
/* defining the UART configuration structure */
uart.Instance = USART1;
uart.Init.BaudRate = 115200;
uart.Init.WordLength = UART_WORDLENGTH_8B;
uart.Init.StopBits = UART_STOPBITS_1;
uart.Init.Parity = UART_PARITY_NONE;
uart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
uart.Init.Mode = UART_MODE_TX_RX;
HAL_UART_Init(&uart);
}
static void Error_Handler(void)
{
}
static void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = { 0 };
RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 };
/**Configure the main internal regulator output voltage */
__HAL_RCC_PWR_CLK_ENABLE()
;
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 216;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/**Activate the Over-Drive mode */
if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) {
Error_Handler();
}
}
UART_PUTCHAR {
HAL_UART_Transmit(&uart, (uint8_t*) &ch, 1, 0xFFFF);
return ch;
}
<file_sep>/week-04/day-3/Ex_04_Devices/copier.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_04_DEVICES_COPIER_H
#define EX_04_DEVICES_COPIER_H
#include "scanner.h"
#include "printer2d.h"
class Copier : public Scanner, public Printer2D
{
public:
Copier(int sizeX, int sizeY, int speed);
void copy();
};
#endif //EX_04_DEVICES_COPIER_H
<file_sep>/week-03/day-3/Ex_06_BunniesAgain/main.cpp
#include <iostream>
// We have bunnies standing in a line, numbered 1, 2, ... The odd bunnies
// (1, 3, ..) have the normal 2 ears. The even bunnies (2, 4, ..) we'll say
// have 3 ears, because they each have a raised foot. Recursively return the
// number of "ears" in the bunny line 1, 2, ... n (without loops or multiplication).
int bunnyEars(int bunnyNumber, int oneBunnyEars);
int main() {
int bunnyNumb;
int BunnyEars = 2;
std::cout << "Write the numbers of bunnies: ";
std::cin >> bunnyNumb;
std::cout << bunnyEars(bunnyNumb, BunnyEars);
return 0;
}
int bunnyEars(int bunnyNumber, int oneBunnyEars)
{
if (bunnyNumber <= 1){
return oneBunnyEars;
} else {
if (bunnyNumber % 2 == 0){
return oneBunnyEars + 1 +bunnyEars(bunnyNumber-1, oneBunnyEars);
}else{
return oneBunnyEars +bunnyEars(bunnyNumber-1, oneBunnyEars);
}
}
}<file_sep>/week-04/day-4/LessonPractice_1/LessonPractice1_Lib/CMakeLists.txt
# Add all your .cpp files here (separated by spaces)
add_library(${PROJECT_LIB_NAME} myClass.cpp) #azt a nevet írom ide, ami a Lib mappa cpp file-ja, ha több van, akkor mindet<file_sep>/week-02/day-2/Ex_10_swap/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_10_swap)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_10_swap main.cpp)<file_sep>/week-06/day-1/Ex_22_printChar/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_22_printChar)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_22_printChar main.cpp)<file_sep>/week-01/day-3/Ex_19_OneTwo/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_19_OneTwo)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_19_OneTwo main.cpp)<file_sep>/week-02/day-3/Ex_06_Copy_file_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_06_Copy_file_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_06_Copy_file_2 main.cpp)<file_sep>/week-04/day-1/ExBefInheritance_2/person.h
//
// Created by Lilla on 2019. 02. 03..
//
#ifndef EXBEFINHERITANCE_2_PERSON_H
#define EXBEFINHERITANCE_2_PERSON_H
#include <string>
enum Gender
{
MALE,
FEMALE
};
std::string getGenderString(Gender gender);
class Person
{
public:
Person(std::string name, int age, Gender gender);
Person();
virtual void introduce(); //ezzel engedélyezem a leszármazottaknak, hogy másként is viselkedjenek
virtual void getGoal();
protected: //ezt kell használnom a private helyett, hogy a leszármazottak is lássák, viszont a main nem látja!!!
std::string _name;
int _age;
Gender _gender;
};
#endif //EXBEFINHERITANCE_2_PERSON_H
<file_sep>/week-01/day-4/Ex_15_Colors/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_15_Colors)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_15_Colors main.cpp)<file_sep>/week-02/day-1/Ex_08_appendaletter_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_08_appendaletter_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_08_appendaletter_2 main.cpp)<file_sep>/week-06/day-1/Ex_24_ascii/main.cpp
#include <stdio.h>
#include "string.h"
// print out the characters that corresponds to these ascii values
int main()
{
int array[] = {103, 114, 101, 101, 110, 32, 102, 111, 120};
int size = sizeof(array)/ sizeof(array[0]);
for (int i = 0; i < size; ++i) {
printf("%c", array[i]);
}
return 0;
}<file_sep>/week-02/day-1/Ex_15_student_counter_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_15_student_counter_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_15_student_counter_2 main.cpp)<file_sep>/week-06/day-1/Ex_07_pi_3/pi.c
//
// Created by Lilla on 2019. 02. 25..
//
#include "pi.h"
#define PI 3.14
float areaMeasure(float radius) {
float area;
area = radius * radius * PI;
return area;
}
<file_sep>/week-04/day-3/LessonPractice_1/circle.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include "circle.h"
Circle::Circle(int x, int y, int rad) : Shape(x, y)
{
radius = rad;
}
double Circle::circumference()
{
return 2 * radius * 3.14;
}
double Circle::area()
{
return radius * radius * 3.14;
}<file_sep>/google_test_practice/doubleNum.cpp
#include "doubleNum.h"
#include "pch.h"
int doubleNum(int num)
{
return num * 2;
}<file_sep>/week-01/day-4/Ex_13_Matrix/main.cpp
#include <iostream>
#include <string>
int main(int argc, char* args[]) {
int sizeOfMatrix;
std::cout << "Please give me the size of the identity matrix" << std::endl;
std::cin >> sizeOfMatrix;
int identityMatrix[sizeOfMatrix][sizeOfMatrix];
for (int i = 0; i < sizeOfMatrix; ++i) {
for (int j = 0; j < sizeOfMatrix; ++j) {
if (i == j) {
identityMatrix[i][j] = 1;
}else{
identityMatrix[i][j] = 0;
}
}
}
for (int k = 0; k < sizeOfMatrix; ++k) {
for (int l = 0; l < sizeOfMatrix; ++l) {
std::cout << identityMatrix[k][l] << " ";
}
std::cout << std::endl;
}
return 0;
}
/* #include <iostream>
#include <string>
int main(int argc, char* args[]) {
// - Create (dynamically) a two dimensional array
// with the following matrix. Use a loop!
// by dynamically, we mean here that you can change the size of the matrix
// by changing an input value or a parameter or this combined
//
// 1 0 0 0
// 0 1 0 0
// 0 0 1 0
// 0 0 0 1
//
// - Print this two dimensional array to the output
int i, j;
int howBig;
std::cout << "How big the matrix is?" << std::endl;
std::cin >> howBig;
int** dimarray = new int*[howBig];
for(int i = 0; i < howBig; ++i) {
dimarray[i] = new int[howBig];
}
std::cout << "Write the row elements: " << std::endl;
for (int i = 0; i < howBig; i++){
for (int j = 0; j < howBig; j++) {
std::cin >> dimarray[i][j];
}
std::cout << std::endl;
}
for(int i = 0; i < howBig; ++i) {
for (int j = 0; j < howBig; ++j) {
std::cout << dimarray[i][j];
}
std::cout << std::endl;
}
return 0;
}
*/<file_sep>/week-05/day-1/TrialExam_Pirates/pirate.cpp
//
// Created by Lilla on 2019. 02. 11..
//
#include "pirate.h"
Pirate::Pirate(std::string name, bool isCaptain, bool isWoodLeg)
{
_healthPoint = 10;
_name = name;
_isCaptain = isCaptain;
_isWoodLeg = isWoodLeg;
_gold = 0;
}
void Pirate::work()
{
if (_isCaptain){
_gold += 10;
_healthPoint -=5;
} else {
_gold += 1;
_healthPoint -=1;
}
}
void Pirate::party()
{
if (_isCaptain){
_healthPoint +=5;
} else {
_healthPoint +=1;
}
}
bool Pirate::captain() {
return _isCaptain;
}
bool Pirate::woodLeg() {
return _isWoodLeg;
}
std::string Pirate::toString() {
if (_isWoodLeg){
return ("Hello, I'm " + _name + ". I have a wooden leg and " + std::to_string(_gold) + " golds.");
} else {
return ("Hello, I'm " + _name + ". I still have my real legs and " + std::to_string(_gold) + " golds.");
}
}
int Pirate::getGold() {
return _gold;
}
std::string Pirate::getName() {
return _name;
}
<file_sep>/week-06/day-1/Ex_12_sumOfDigits/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_12_sumOfDigits)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_12_sumOfDigits main.c )<file_sep>/week-01/day-4/Ex_20_Unique/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_20_Unique)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_20_Unique main.cpp)<file_sep>/week-06/day-1/Ex_27_distance/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_27_distance)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_27_distance main.cpp)<file_sep>/week-06/day-1/Ex_26_position/main.cpp
#include <stdio.h>
#include <string.h>
// create a function which takes a char array as a parameter and
// lists all position where character 'i' is found
void listPosition(char string[]);
int main ()
{
char string[55] = "This is a string for testing";
char *p;
listPosition(string);
return 0;
}
void listPosition(char string[])
{
int positions = 0;
//int positions = 1; //melyik a jó megoldás?
for(char *p = strtok(string, "i"); p != NULL; p = strtok(NULL, "i")){
//printf("%d ",strlen(p)); //result: 2 2 7 11 2
positions += strlen(p);
printf("%d ", positions);
}
}<file_sep>/week-06/day-2/Ex_07_Digimon/digimon.h
//
// Created by Lilla on 2019. 03. 03..
//
#ifndef EX_07_DIGIMON_DIGIMON_H
#define EX_07_DIGIMON_DIGIMON_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum digivolution
{
BABY,
IN_TRAINING,
ROOKIE,
CHAMPION,
ULTIMATE,
MEGA
};
typedef struct
{
short age;
short health;
char name_digimon[127];
char name_tamer[255];
enum digivolution digi_level;
} digimon_t;
char * getlevel(enum digivolution digi_level);
int get_minimum_health_index(digimon_t * digimon_array, int size);
int count_digivolution_level(digimon_t * digimon_array, int size, enum digivolution digi_level);
int numb_same_tamer(digimon_t * digimon_array, int size, char name_tamer[]);
#endif //EX_07_DIGIMON_DIGIMON_H
<file_sep>/week-03/day-2/Ex_11_Sharpie_set_2/sharpieSet.h
//
// Created by Lilla on 2019. 02. 13..
//
#ifndef EX_11_SHARPIE_SET_2_SHARPIESET_H
#define EX_11_SHARPIE_SET_2_SHARPIESET_H
class sharpieSet {
};
#endif //EX_11_SHARPIE_SET_2_SHARPIESET_H
<file_sep>/week-02/day-3/Ex_01_Divide_by_zero_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_Divide_by_zero_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_01_Divide_by_zero_2 main.cpp)<file_sep>/week-01/day-4/Ex_06_Swap/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_06_Swap)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_06_Swap main.cpp)<file_sep>/week-04/day-2/Ex_01_GFOrganization/cohort.h
//
// Created by Lilla on 2019. 02. 05..
//
#ifndef EX_01_GFORGANIZATION_COHORT_H
#define EX_01_GFORGANIZATION_COHORT_H
#include <iostream>
#include <vector>
#include "student.h"
#include "mentor.h"
class Cohort {
public:
Cohort(std::string name);
void addStudent(Student*);
void addMentor(Mentor*);
void info();
protected:
private:
std::string _name;
std::vector<Student> _students; //a vector elkészül
std::vector<Mentor> _mentors;
};
#endif //EX_01_GFORGANIZATION_COHORT_H
<file_sep>/week-03/day-2/Ex_10_Petrol_station/station.h
//
// Created by Lilla on 2019. 01. 30..
//
#ifndef EX_10_PETROL_STATION_STATION_H
#define EX_10_PETROL_STATION_STATION_H
#include "car.h"
class Station {
public:
Station (int gasAmount);
void fill(Car car);
private:
int gasAmount_;
};
#endif //EX_10_PETROL_STATION_STATION_H
<file_sep>/week-01/day-3/Ex_32_DrawDiagonal/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_32_DrawDiagonal)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_32_DrawDiagonal main.cpp)<file_sep>/week-04/day-1/VideoPractice_03/farmer.cpp
//
// Created by Lilla on 2019. 02. 05..
//
#include <iostream>
#include "farmer.h"
//void Farmer::introduce()
//{
// std::cout << "hey from farmer" << std::endl;
//}<file_sep>/week-05/day-1/ExampleExam_Shelter/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(ExampleExam_Shelter)
set(CMAKE_CXX_STANDARD 14)
add_executable(ExampleExam_Shelter main.cpp animalshelter.cpp animalshelter.h animal.cpp animal.h dog.cpp dog.h cat.cpp cat.h parrot.cpp parrot.h)<file_sep>/week-04/day-1/VideoPractice_01/daughter.cpp
//
// Created by Lilla on 2019. 02. 05..
//
#include <iostream>
#include "mother.h"
#include "daughter.h"
Daughter::Daughter()
{
}
void Daughter::doSomething()
{
publicv = 1;
protectedv = 2;
//privatev = 3; this case is not allowed, because this is only of base class!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}<file_sep>/week-02/day-2/Ex_06_five_numbers/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_06_five_numbers)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_06_five_numbers main.cpp)<file_sep>/week-05/day-4/trialTrialEx3Restaurant/manager.h
//
// Created by Lilla on 2019. 02. 14..
//
#ifndef TRIALTRIALEX3RESTAURANT_MANAGER_H
#define TRIALTRIALEX3RESTAURANT_MANAGER_H
#include "employee.h"
class Manager :public Employee{
public:
Manager(std::string name, int experience = 0);
void work() override;
void haveAmeeting();
std::string toString() override;
private:
int _moodLevel =400;
};
#endif //TRIALTRIALEX3RESTAURANT_MANAGER_H
<file_sep>/week-04/day-1/ExBefInheritance/sponsor.h
//
// Created by Lilla on 2019. 02. 03..
//
#ifndef EXBEFINHERITANCE_SPONSOR_H
#define EXBEFINHERITANCE_SPONSOR_H
#include <string>
//#include "gender.h"
#include "person.h"
class Sponsor {
public:
Sponsor(std::string name, int age, Gender gender, std::string company);
Sponsor();
void hire();
void introduce();
void getGoal();
std::string _name = "<NAME>";
int _age ;
Gender _gender;
std::string _company;
int _hiredStudents;
private:
};
#endif //EXBEFINHERITANCE_SPONSOR_H
<file_sep>/week-06/day-2/Ex_08_printLines/main.c
#include <stdio.h>
#include <string.h>
// Write a program that opens a file called "my-file.txt", then prints
// each line from the file.
// You will have to create the file, for that you may use C-programming, although it is not mandatory
int main ()
{
FILE * input_file;
input_file = fopen("my-file.txt", "r");
char file_line[200];
while (!feof(input_file)){
fgets(file_line, 200, input_file);
printf("%s", file_line);
//puts(fileLine);
}
return 0;
}<file_sep>/week-04/day-3/LessonPractice_1/main.cpp
#include <iostream>
#include "shape.h"
#include "rect.h"
#include "circle.h"
#include <vector>
/*ez csak a kiinduló minta, ezt átraktuk külön file-okba
* class Shape{
int x; //x koordináta pont 0
int y; //y koordináta pont 0
public:
void move(int dx, int dy) //a mozgatási függvényem
{
x += dx;
y += dy;
}
virtual double circumference () = 0; //azért használok double-t, mert törtet várok vissza kerület
virtual double area() = 0; //terület
};
class Rect : public Shape {
int width;
int height;
double circumference()
{
return 2 * width + 2 * height;
}
double area()
{
return width * height;
}
};*/
int main() {
//Shape sh; //nem tudja meghívni, mert nem létező objectum, abstract
std::vector<Shape*> shapes;//azért kell pointer, mert enélkül nem is tudom létrehozni (=0), iletve azért, mert így rámutat az alosztályokra és nem vágja le az egyéb tagokat
Circle c(0, 0, 5);
Rect r(0, 0 , 10, 10);
shapes.push_back(&c);
shapes.push_back(&r);
shapes[0]->circumference();//futási időben rendeződik, hogy melyik circumstance-t használja, és felismeri, hogy az a köré, mert a 0. index a kör
//(*shapes[0]).circumference(); ez a kettő ugyanaz, a -> kiváltja a deference-et
shapes[1]->circumference();//ez a négyzet
std::cout << shapes[0]->circumference() << std::endl; //2*5*3.14
std::cout << shapes[1]->circumference() << std::endl; //2*10+2*10
return 0;
}<file_sep>/week-02/day-3/Ex_07_Logs_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_Logs_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_07_Logs_2 main.cpp)<file_sep>/week-04/day-3/Ex_02_Zoo/animal.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include "animal.h"
std::string genderToString(Gender gender)
{
if (gender == Gender::MALE) {
return "male";
} else if (gender == Gender::FEMALE) {
return "female";
}
}<file_sep>/week-06/day-3/Ex_01_malloc/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_malloc C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_01_malloc main.c)<file_sep>/week-02/day-2/Ex_03_change_value/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_change_value)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_03_change_value main.cpp)<file_sep>/week-03/day-2/Ex_10_Petrol_station_2/car.cpp
//
// Created by Lilla on 2019. 02. 13..
//
#include "car.h"
Car::Car(int gasAmount, int capacity)
{
_gasAmount = gasAmount;
_capacity = capacity;
}
bool Car::isFull() {
if (_gasAmount != _capacity){
return false;
}
return true;
}
void Car::fill()
{
_gasAmount++;
}
<file_sep>/week-04/day-3/Ex_02_Zoo/byegg.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_02_ZOO_BYEGG_H
#define EX_02_ZOO_BYEGG_H
#include "animal.h"
class Byegg : public Animal
{
public:
std::string breed() override;
};
#endif //EX_02_ZOO_BYEGG_H
<file_sep>/week-04/day-2/Ex_01_GFOrganization/student.h
//
// Created by Lilla on 2019. 02. 05..
//
#ifndef EX_01_GFORGANIZATION_STUDENT_H
#define EX_01_GFORGANIZATION_STUDENT_H
#include "person.h"
class Student : public Person
{
public:
Student();
Student(std::string name, int age, Gender gender, std::string previousOrganization);
void getGoal() override;
void introduce() override;
void skipDays(int numberOfDays);
private:
int _skippedDays;
std::string _previousOrganization;
};
#endif //EX_01_GFORGANIZATION_STUDENT_H
<file_sep>/week-04/day-1/VideoPractice_03/student.cpp
//
// Created by Lilla on 2019. 02. 05..
//
#include <iostream>
#include "student.h"
void Student::introduce()
{
std::cout << "hey from student" << std::endl;
}
<file_sep>/week-04/day-2/Ex_01_GFOrganization/person.h
//
// Created by Lilla on 2019. 02. 05..
//
#include <iostream>
#ifndef EX_01_GFORGANIZATION_PERSON_H
#define EX_01_GFORGANIZATION_PERSON_H
enum Gender
{
MALE,
FEMALE
};
std::string getGenderString(Gender gender);
class Person
{
public:
Person();
Person(std::string name, int age, Gender gender);
virtual void introduce();
virtual void getGoal();
protected:
std::string _name;
int _age;
Gender _gender;
private:
};
#endif //EX_01_GFORGANIZATION_PERSON_H
<file_sep>/week-04/day-1/ExBefInheritance/sponsor.cpp
//
// Created by Lilla on 2019. 02. 03..
//
#include <iostream>
#include "sponsor.h"
Sponsor::Sponsor(std::string name, int age, Gender gender, std::string company)
{
_name = name;
_age = age;
_gender = gender;
_company = company;
_hiredStudents = 0;
}
Sponsor::Sponsor() {
std::string _name = "<NAME>";
int _age = 30;
Gender _gender = Gender::FEMALE;
std::string _company = "Google";
int _hiredStudents = 0;
}
void Sponsor::hire()
{
_hiredStudents++;
}
void Sponsor::introduce()
{
std::cout << "Hi, I'm " << _name << ", a " << _age << "year old " << getGenderString(_gender) << "who represents "<< _company << "and hired " <<
_hiredStudents << "students so far." << std::endl;
}
void Sponsor::getGoal()
{
std::cout << "My goal is: Hire brilliant junior software developers." << std::endl;
}<file_sep>/week-06/day-1/Ex_07_pi_3/main.c
#include <stdio.h>
#include "pi.h"
int main() {
float radius;
printf("Give me the radius: \n");
scanf("%f", &radius);
printf("area = %.2f\n", areaMeasure(radius));
return 0;
}<file_sep>/week-03/day-3/Ex_04_Power/main.cpp
#include <iostream>
// Given base and n that are both 1 or more, compute recursively (no loops)
// the value of base to the n power, so powerN(3, 2) is 9 (3 squared).
int powerN(int baseNumber, int powerNumber);
int main() {
int base, power;
std::cout << "Write a number and the number to power the base number: ";
std::cin >> base >> power;
std::cout << powerN(base, power);
return 0;
}
int powerN(int baseNumber, int powerNumber)
{
if (powerNumber == 1){
return baseNumber;
} else {
return (baseNumber * powerN(baseNumber, powerNumber-1));
}
}<file_sep>/week-08/function_templates_SKELETON/important_GPIO_functions.c
#include "interruption_templates.h"
//turn on a led at F port 9 pin
//HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_SET);
//turn off a led at F port 9 pin
//HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_RESET);
//Reads the specified input port pin, returns the input port pin value.
//HAL_GPIO_ReadPin(GPIOB, external_button.Pin); //B port 4 pin - retval : 0 or 1
//Toggle a led
//HAL_GPIO_TogglePin(GPIOF, GPIO_PIN_9);
<file_sep>/week-02/day-1/Ex_02_urlfixer/main.cpp
#include <iostream>
#include <string>
int main(int argc, char *args[]) {
// Accidentally I got the wrong URL for a funny subreddit. It's probably "odds" and not "bots"
// Also, the URL is missing a crucial component, find out what it is and insert it too!
std::string url("https//www.reddit.com/r/nevertellmethebots"); //The original string
std::string need_expression = "bots"; //The part of the the string we want to change
std::string new_expression = "odds";
int start_replace = url.find(need_expression);
//Determinding the beginning index of the changing word with x.find function
url.replace(start_replace, need_expression.length(), "odds"); //Replacing original part with expression "odds"
//First is the index number, next is the length of changing part, finished by new expression
std::string need_expression2 = "//";
std::string new_expression2 = ":"; //The string of new part
//url.insert(5, new_expression2, 0, 1); //The method of inserting new parts in a string.
//First the beginning index, second the new part (as a string),
// third is the beginning index of new part you need to insert, the last is the closing index of new part you need to insert
int start_insert = url.find(need_expression2);
url.insert(start_insert, new_expression2, 0, new_expression2.length());
std::cout << url << std::endl; //Printing of the new string
return 0;
}<file_sep>/week-06/day-2/Ex_09_countLines/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Write a function that takes a filename as string,
// then returns the number of lines the file contains.
// It should return zero if it can't open the file
int count_lines(char file_name[]);
int main ()
{
char file_name[] = "../my-file.txt";
printf("%d",(count_lines(file_name)));
return 0;
}
int count_lines(char file_name[])
{
FILE * file_pointer;
file_pointer = fopen(file_name, "r");
if(file_pointer == NULL){
return -1;
}
int counter = 0;
char file_line[200];
while(!feof(file_pointer)){
fgets(file_line, 200, file_pointer);
counter++;
}
fclose(file_pointer);
return counter;
}<file_sep>/week-06/day-1/Ex_08_organizing_2/main.cpp
//Continue working on the pi.c project
//Organise the function from the previous excercise to separate .c and .h files
//Create another function which calculates the circumference of a circle
//the radius of the circle should be passed as a parameter
//the function should return the calculated circumference
//circumference = 2 * radius * PI
//this function should be in the same .c and .h files as the one which calculates the area
#include <stdio.h>
#include "pi.h"
int main()
{
float radius;
printf("Give me the radius: \n");
scanf("%f", &radius);
printf("area = %.2f\n", AREA(radius));
printf("circumference = %.2f", CIRCUMFERENCD(radius));
return 0;
}
<file_sep>/week-06/day-1/Ex_16_whereIsIt/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int embedded(char str[], char findChar);
int main()
{
// Create a program which asks for a string and a character and stores them
// Create a function which takes a string and a character as a parameter and
// if the given character is in the string, it should return the index of the
// first appearance (in the given string) otherwise the function should return -1
//
// Example:
//
// Case 1:
//
// given_string = "embedded"
// given_char = 'd'
//
// the function should return: 4, because this is the index of the first appearance of char 'd'
//
//
// Case 2:
//
// given_string = "embedded"
// given_char = 'a'
//
// the function should return: -1, because there is no 'a' in the word "embedded"
//
printf("Type your string: ");
char str[50];
char findChar;
gets(str);
printf("Type the character you want find: ");
scanf("%c", &findChar);
int result = embedded(str,findChar);
printf("%d", result);
return 0;
}
int embedded(char str[], char findChar)
{
int len;
len = strlen(str);
for (int i = 0; i < len; ++i) {
if (findChar == str[i]){
return i;
}
}
return -1;
}<file_sep>/week-02/day-3/Ex_01_Divide_by_zero/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_Divide_by_zero)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_01_Divide_by_zero main.cpp)<file_sep>/week-03/day-3/Ex_08_StringAgain/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_08_StringAgain)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_08_StringAgain main.cpp)<file_sep>/week-08/function_templates_SKELETON/interruption_templates.h
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
//create global variable configuration structs
//---------- interrupt handle variables ------------------
GPIO_InitTypeDef user_button_handle; // the PI11 user button handle structure
GPIO_InitTypeDef external_button_handle; // the B4 external digital(?) button handle structure
UART_HandleTypeDef uart_handle; // UART config handle structure
TIM_HandleTypeDef tim_handle; // timer (TIM2) config handle structure
TIM_HandleTypeDef pwm_tim_handle; // PWM timer (TIM) config handle structure
//----------- no interrupt handle variables -------------
GPIO_InitTypeDef LEDS; //the external Led config structure
GPIO_InitTypeDef external_button; // the B4 external button structure for general purpose
TIM_OC_InitTypeDef sConfig; // the output compare channel's config structure for PWM
UART_HandleTypeDef uart; //the uart config for general purpose
GPIO_InitTypeDef GPIOTxConfig; //the uart config for general purpose without BSP
GPIO_InitTypeDef GPIORxConfig; //the uart config for general purpose without BSP
TIM_HandleTypeDef tim; // timer (TIM2) config structure for general purpose
//---------- task variables -------------------------------
//---------- 2 EXTERNAL BUTTON HANDLER -------------------
uint32_t last_debounce_time = 0; // the last time the output pin was toggled
const uint32_t debounce_delay = 150; // the debounce time in ms (increase if the output flickers)
volatile int push_counter = 0;
//---------- 3 USART HANDLER -----------------------------
volatile char buffer; //to USART (Receiver) interrupt handler
//interrupt handler functions
void init_user_button(void); //init board user push button PI11 with external interrupt
void init_external_button(void); //init external push button B port 4 pin with external interrupt
void init_uart(void); //init USART with external interrupt
void init_timer(void); // init simple timer interrupt
//general functions
void init_external_led(); //external led on F port 7 pin (8, 9 , 10) for general purpose
void init_GPIO_extern_button(); //external button on B post 4 pin for general purpose
void init_GPIO_BSP_uart(); //uart for general purpose with BSP
void init_GPIO_uart(); //uart for general purpose without BSP
void timer_init(); //timer for general purpose (TIM2)
<file_sep>/week-05/day-4/trialTrialEx3Restaurant/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(trialTrialEx3Restaurant)
set(CMAKE_CXX_STANDARD 14)
add_executable(trialTrialEx3Restaurant main.cpp restaurant.cpp restaurant.h employee.cpp employee.h waitor.cpp waitor.h chef.cpp chef.h manager.cpp manager.h)<file_sep>/week-05/day-1/ExampleExam_Shelter/parrot.cpp
//
// Created by Lilla on 2019. 02. 11..
//
#include "parrot.h"
Parrot::Parrot(std::string name) : Animal(name, 50)
{
}
<file_sep>/week-04/day-3/Ex_01_InstruStringedInstru/instrument.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_01_INSTRUSTRINGEDINSTRU_INSTRUMENT_H
#define EX_01_INSTRUSTRINGEDINSTRU_INSTRUMENT_H
#include <string>
#include <iostream>
class Instrument {
public:
virtual void play() = 0;
protected:
std::string _name;
};
#endif //EX_01_INSTRUSTRINGEDINSTRU_INSTRUMENT_H
<file_sep>/week-01/day-3/Ex_05_TWoNumb/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_5_TWoNumb)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_5_TWoNumb main.cpp)<file_sep>/week-01/day-4/Ex_19_ReverseList/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_19_ReverseList)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_19_ReverseList main.cpp)<file_sep>/week-06/day-4/Ex_01_create_linked_list/main.c
#include <stdio.h>
#include <stdlib.h>
#include "linked_list.h"
int main() {
//Creating a new list
int node_value = 6;
node_t * my_first_linked_list = linked_list_creator(node_value);
linked_list_print(my_first_linked_list);
puts("");
//Insertation at the end
linked_list_push_back(my_first_linked_list, 15);
linked_list_push_back(my_first_linked_list, 74);
linked_list_print(my_first_linked_list);
puts("");
//Insertation at the beginning
linked_list_push_front(&my_first_linked_list, 30);
linked_list_push_front(&my_first_linked_list, 14);
linked_list_print(my_first_linked_list);
puts("");
//Insertation after the second element
linked_list_insert(my_first_linked_list->next, 15);
linked_list_print(my_first_linked_list);
puts("");
//The number of nodes in my current list
printf("%d\n", linked_list_size(my_first_linked_list));
puts("");
//Deciding whether a linked link empty or not
if(!linked_list_empty(my_first_linked_list)){ //Output: This linked link is not empty.
printf("This linked link is not empty.\n");
} else {
printf("This linked link is empty.\n");
}
node_t * test_is_empty = NULL; //This is the case of empty list
if(!linked_list_empty(test_is_empty)){ //Output: This linked link is empty.
printf("This linked link is not empty.\n");
} else {
printf("This linked link is empty.\n");
}
puts("");
//Deleting the first node of a linked list
linked_list_pop_front(&my_first_linked_list);
linked_list_print(my_first_linked_list);
puts("");
//Removing an element of a linked list by the value
printf("The number of a deleted nodes: %d\n", linked_list_remove(&my_first_linked_list, 15));
linked_list_print(my_first_linked_list);
puts("");
//Searching a node memory address of a linked list by a value
printf("The memory address of the searched nodes: %p\n",linked_list_search(my_first_linked_list, 6));
puts("");
//Deallocation the whole linked list
linked_list_dealloc(my_first_linked_list);
printf("Hello, World!\n");
return 0;
}<file_sep>/week-05/day-4/trialTrialEx3Restaurant/employee.cpp
//
// Created by Lilla on 2019. 02. 14..
//
#include "employee.h"
Employee::Employee(std::string name, int experience)
{
_experience = experience;
_name = name;
}
std::string Employee::toString() {
return (_name + " has " + std::to_string(_experience)) + " experience";
}
<file_sep>/week-03/day-2/Ex_04_Sharpie/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_04_Sharpie)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_04_Sharpie main.cpp Sharpie.cpp Sharpie.h)<file_sep>/week-01/day-3/Ex_12_cuboid/main.cpp
#include <iostream>
int main(int argc, char* args[]) {
// Write a program that stores 3 sides of a cuboid as variables (doubles)
// The program should write the surface area and volume of the cuboid like:
//
// Surface Area: 600
// Volume: 1000
double a = 20;
double b = 24.56;
double c = 1.5;
std::cout << "Surface Area: " << 2*(a*b+a*c+ b*c) << "\n" << "Volume: " << a*b*c << std::endl;
return 0;
}<file_sep>/week-08/day-2/Ex_04_dynamo_with_PWM/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
GPIO_InitTypeDef user_button_handle; // the PI11 user button handle structure
GPIO_InitTypeDef LEDS; //the external Led config structure
TIM_HandleTypeDef pwm_tim; // PWM timer (TIM) config structure
TIM_OC_InitTypeDef sConfig; // the output compare channel's config structure for PWM
volatile uint32_t pushing_speed = 0;
static void Error_Handler(void);
static void SystemClock_Config(void);
void init_user_button(void)
{
__HAL_RCC_GPIOI_CLK_ENABLE(); // enable the GPIOI clock
user_button_handle.Pin = GPIO_PIN_11; // the pin is the PI11
user_button_handle.Pull = GPIO_NOPULL;
user_button_handle.Speed = GPIO_SPEED_FAST; // port speed to fast
user_button_handle.Mode = GPIO_MODE_IT_RISING; // our mode is interrupt on rising edge
HAL_GPIO_Init(GPIOI, &user_button_handle); // init PI11 user button
HAL_NVIC_SetPriority(EXTI15_10_IRQn, 4, 0); //set blue PI11 user button interrupt priority
HAL_NVIC_EnableIRQ(EXTI15_10_IRQn); //enable the interrupt to HAL
}
void init_external_led()
{
//initialize external LED on B port pin 4 (PWM compatibility)
__HAL_RCC_GPIOB_CLK_ENABLE(); //giving clock
LEDS.Pin = GPIO_PIN_4; // setting up a pin
LEDS.Mode = GPIO_MODE_AF_PP;
LEDS.Pull = GPIO_NOPULL;
LEDS.Speed = GPIO_SPEED_HIGH;
LEDS.Alternate = GPIO_AF2_TIM3;
HAL_GPIO_Init(GPIOB, &LEDS);
}
void init_PWM(void)
{
//initialize TIM3 for PWM
__HAL_RCC_TIM3_CLK_ENABLE(); //giving clock
// configuriation of the basic mode of the timer (which direction should it count, what is the maximum value, etc.)
pwm_tim.Instance = TIM3; //register base address
pwm_tim.Init.Prescaler = 108 - 1; /* 108000000/10800=10000 -> speed of 1 count-up: 1/10000 sec = 0.1 ms */
pwm_tim.Init.Period = 100 - 1; /* 10000 x 0.1 ms = 1 second period */
pwm_tim.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
pwm_tim.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_PWM_Init(&pwm_tim); //configure the PWM timer
sConfig.Pulse = 0;
sConfig.OCMode = TIM_OCMODE_PWM1;
sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfig.OCFastMode = TIM_OCFAST_ENABLE;
HAL_TIM_PWM_ConfigChannel(&pwm_tim, &sConfig, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&pwm_tim, TIM_CHANNEL_1);
}
int main(void)
{
HAL_Init(); //making HAL configuration
SystemClock_Config(); //for TIMERS - this function call sets the timers input clock to 108 Mhz (=108000000 Hz) */
init_external_led(); //init external Led on F port pin 7
init_user_button();
init_PWM();
while (1) {
__HAL_TIM_SET_COMPARE(&pwm_tim, TIM_CHANNEL_1, pushing_speed);
if (pushing_speed >= 3) {
pushing_speed -= 3;
} else {
pushing_speed = 0;
}
HAL_Delay(500);
}
}
//user push button PI11 external interrupt handler
void EXTI15_10_IRQHandler(void)
{
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_11);
}
//user push button PI11 external interrupt week callback
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
//if(GPIO_Pin == GPIO_PIN_11){
if (GPIO_Pin == user_button_handle.Pin) {
if (pushing_speed <= 50) {
if (pushing_speed + 5 <= 50) {
pushing_speed += 5;
} else {
pushing_speed = 50;
}
}
}
}
//error handler
static void Error_Handler(void)
{
}
//system clock config to TIMERs
static void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = { 0 };
RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 };
/**Configure the main internal regulator output voltage */
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 216;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/**Activate the Over-Drive mode */
if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) {
Error_Handler();
}
}
<file_sep>/week-06/day-1/Ex_21_indexOfIt/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int index_in_sentence(int *word, int *sentence);
int main()
{
// Create a function which takes two strings as parameters
// One string is actually a sentence and the other one is a word
// It should return the index of the word in the sentence and 0 otherwise
// Try to erase small and uppercase sensitivity.
char *word = "doctor";
char *sentence = "An apple a day keeps the doctor away jncq.";
// the output should be: 6
printf("The index of the word is %d", index_in_sentence(&word, &sentence));
return 0;
}
int index_in_sentence(int *word, int *sentence)
{
int sizestr1 = strlen(*sentence) + 1;
int sizestr2 = strlen(*word) + 1;
char word_copy[sizestr2];
char sentence_copy[sizestr1];
int return_index = 0;
int bool = 0;
//copy origingal string into a new array
strcpy(word_copy, *word);
strcpy(sentence_copy, *sentence);
//modifying the copy strings by toupper()
for (int i = 0; i <sizestr1 ; ++i) {
sentence_copy[i] = toupper(sentence_copy[i]);
}
for (int i = 0; i <sizestr2 ; ++i) {
word_copy[i] = toupper(word_copy[i]);
}
//finding the word
for (int j = 0; j < sizestr1; ++j) {
if (sentence_copy[j] == ' '){
return_index++;
} else if (sentence_copy[j] == word_copy[0]){
bool = 1;
int inner_counter = j;
for (int i = 0; i < strlen(word_copy); ++i) {
if (word_copy[i] != sentence_copy[inner_counter]){
bool = 0;
}
inner_counter++;
}
if (bool){
return return_index;
}
}
}
return 0;
}<file_sep>/week-02/day-1/Ex_02_urlfixer/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_02_urlfixer)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_02_urlfixer main.cpp)<file_sep>/week-08/function_templates_SKELETON/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "interruption_templates.h"
static void Error_Handler(void);
static void SystemClock_Config(void);
int main(void)
{
HAL_Init(); //making HAL configuration
SystemClock_Config(); //for TIMERS - this function call sets the timers input clock to 108 Mhz (=108000000 Hz) */
//your possibilities:
BSP_LED_Init(LED_GREEN); //init LED1/LED_GREEN by BSP
init_external_led(LEDS); //init external Led on F port pin 7
BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_GPIO); //init blue user button for general purpose
init_user_button(); //init blue user button for interrupt handler mode
init_external_button(); //init external button B port pin 4 for interrupt handler mode
init_uart(); //init USART for interrupt handler mode
init_timer(); //init TIM2 for interrupt handler mode
//others
HAL_UART_Receive_IT(&uart_handle, &buffer, 1); //in the case of USART we must do it once in the main before the callback - without this the first callback won't get signal
HAL_TIM_Base_Start_IT(&tim_handle); //starting the timer - init_timer() won't work without it
HAL_TIM_PWM_Start_IT(&pwm_tim_handle, TIM_CHANNEL_1);
for(;;);
}
//---------- 1 USER BUTTON HANDLER -------------------
//user push button PI11 external interrupt handler
void EXTI15_10_IRQHandler(void)
{
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_11);
}
//user push button PI11 external interrupt week callback
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
//if(GPIO_Pin == GPIO_PIN_11){
if(GPIO_Pin == user_button_handle.Pin){
BSP_LED_Toggle(LED_GREEN);
printf("Button interrupt\n"); //need an UART for general purpose!!!
}
}
//---------- 2 EXTERNAL BUTTON HANDLER -------------------
//external push button B4 external interrupt handler
void EXTI4_IRQHandler()
{
HAL_GPIO_EXTI_IRQHandler(external_button_handle.Pin);
}
//declare week callback function
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
//if(GPIO_Pin == GPIO_PIN_4){
if(GPIO_Pin == external_button_handle.Pin){
uint32_t current_time = HAL_GetTick();
if (current_time < last_debounce_time + debounce_delay) {
// Do nothing (this is not a real button press)
return;
}
push_counter++;
if(push_counter % 10 == 5){
BSP_LED_On(LED_GREEN);
}
if(push_counter % 10 == 0){
BSP_LED_Off(LED_GREEN);
}
last_debounce_time = current_time;
}
}
//---------- 3 USART HANDLER -------------------
//USART external interrupt handler
void USART1_IRQHandler()
{
HAL_UART_IRQHandler(&uart_handle);
}
//declare week callback function
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if (huart->Instance == USART1) {
BSP_LED_Toggle(LED_GREEN);
HAL_UART_Receive_IT(&uart_handle, &buffer, 1);
}
}
//---------- 4 TIM2 HANDLER -------------------
//TIM2 external interrupt handler
void TIM2_IRQHandler(void)
{
HAL_TIM_IRQHandler(&tim_handle);
}
//declare week callback function
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
//if (htim->Instance == TIM2)
if (htim->Instance == tim_handle.Instance) {
HAL_GPIO_TogglePin(GPIOF, GPIO_PIN_7);
}
}
//---------- 5 PWM TIM3 HANDLER -------------------
//TIM3 external interrupt handler
void TIM3_IRQHandler(void)
{
HAL_TIM_IRQHandler(&tim_handle);
}
//declare week callback function
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)
{
//if (htim->Instance == TIM3)
if (htim->Instance == tim_handle.Instance) {
HAL_GPIO_TogglePin(GPIOF, GPIO_PIN_7);
}
}
//error handler
static void Error_Handler(void)
{}
//system clock config to TIMERs
static void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/**Configure the main internal regulator output voltage */
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 216;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/**Activate the Over-Drive mode */
if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) {
Error_Handler();
}
}
//using printf()
UART_PUTCHAR
{
HAL_UART_Transmit(&UartHandle, (uint8_t*)&ch, 1, 0xFFFF);
return ch;
}
<file_sep>/week-06/day-2/Ex_02_sandwich/main.c
#include <stdio.h>
#include <string.h>
/*
Create a sandwich struct
It should store:
- name
- price (float)
- weight (float)
Create a function which takes two parameters and returns the price of your order.
The parameters should be:
- a sandwich struct
- and an integer that represents how many sandwiches you want to order
*/
struct sandwich {
unsigned char name[20];
float price;
float weight;
};
float price(struct sandwich sandwich, int order);
int main()
{
struct sandwich big_sandwich;
strcpy(big_sandwich.name, "Big Sandwich");
big_sandwich.price = 5.50;
big_sandwich.weight = 500;
int newOrder;
printf("How many %s do you want?\n", big_sandwich.name);
scanf("%d", &newOrder);
printf("The final price is %.2f \n", price(big_sandwich, newOrder));
return 0;
}
float price(struct sandwich sandwich, int order)
{
float finalPrice = (sandwich.price * order);
return finalPrice;
}<file_sep>/week-03/day-3/Ex_01_counter/main.cpp
#include <iostream>
// Write a recursive function that takes one parameter: n and counts down from n.
void counter(int countNumber); //predefinition of counting function
int main() {
std::cout << "Write a number :" << std::endl;
int n; //1. the number of function calling, 2. the top number we want to count down
std::cin >> n;
counter(n);
return 0;
}
void counter(int countNumber) //counting function
{
if (countNumber >= 1) {
std::cout << countNumber << std::endl;
counter(countNumber - 1);
}
}<file_sep>/week-04/day-4/Ex_01_Apples/Ex_01_Apples_Lib/apples.cpp
//
// Created by Lilla on 2019. 02. 07..
//
#include "apples.h"
#include <iostream>
std::string getApple()
{
return "apple";
}<file_sep>/week-06/day-2/Ex_11_writeMultipleLines/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_11_writeMultipleLines C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_11_writeMultipleLines main.c)<file_sep>/opencv_practice/practiceWeekHeader.cpp
#include "practiceWeekHeader.h"
///////////////////////////////////
//------------START----------------
void finishedFunctions(cv::Mat originImg, cv::Mat originImgToEllipse)
{
//choice one of the topics and click
//display_basic_image_with_error_handler(originImg);
//brightFunctions(originImg);
//contrastFunctions(originImg);
//blendFunctions();
//grayFunctions(originImg);
drawFunctions(originImg, originImgToEllipse);
}
////////////////////////////////////
//-------------TOPICS---------------
//$$$$$$ Basic Functions $$$$$$$$
void display_basic_image_with_error_handler(cv::Mat originImg)
{
//error handling
if (originImg.empty()) {
std::cout << "Image cannot be loaded..!!" << std::endl;
return;
}
//create window
cv::namedWindow("image", cv::WINDOW_AUTOSIZE);
//move window
cv::moveWindow("image", 0, 0);
//display image in a specified window
cv::imshow("image", originImg);
}
//$$$$$$ Play with image brightness $$$$$$$$
void brightFunctions(cv::Mat originImg)
{
//change image brightness with Scalar function and display
changeImageBrightnessWithScalar(originImg);
//change image brightness with convert function and display
changeImageBrightnessWithConvertTo(originImg);
//change image brightness in a loop pixel by pixel
changeImageBrightnessPixelByPixel(originImg);
}
//$$$$$$ Play with image contrast $$$$$$$$
void contrastFunctions(cv::Mat originImg)
{
//change image contrast with '*' operator
changeImageContrastWithOperators(originImg);
//change image contrast with convert function and display
changeImageContrastWithConvertTo(originImg);
//change contrast brightness in a loop pixel by pixel
changeImageContrastPixelByPixel(originImg);
}
//$$$$$$ Play with blending of images $$$$$$$$
void blendFunctions()
{
//blending two images
blendImagesWithAddWeighted();
}
//$$$$$$ Play with creating images $$$$$$$$
void grayFunctions(cv::Mat originImg)
{
//change image to gray
changeImageGrayWithImread(originImg);
changeImageGrayWithCvtColor1(originImg); //RGB mode
changeImageGrayWithCvtColor2(originImg); //BGR mode
}
//$$$$$$ Use basic drawing funs $$$$$$$$
void drawFunctions(cv::Mat originImg, cv::Mat originImgToEllipse)
{
//draw line
//drawLine();
//draw ellipse
//drawEllipse(originImgToEllipse);
//draw circle
drawCircle(originImg);
}<file_sep>/week-04/day-1/VideoPractice_03/student.h
//
// Created by Lilla on 2019. 02. 05..
//
#ifndef VIDEOPRACTICE_03_STUDENT_H
#define VIDEOPRACTICE_03_STUDENT_H
#include "person.h"
class Student: public Person
{
public:
void introduce();
};
#endif //VIDEOPRACTICE_03_STUDENT_H
<file_sep>/week-05/day-4/trialTrialEx2BuildingUsage/main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include<vector>
#include <map>
#include <algorithm>
void parseBuildingUsageData(std::string inputFileName, std::string outputFileName);
int main()
{
//std::string input = "usage.txt";
parseBuildingUsageData("../../usage.txt","../../copy.txt" );
std::cout << "Hello, World!" << std::endl;
return 0;
}
void parseBuildingUsageData(std::string inputFileName, std::string outputFileName) {
std::ifstream inputFile;
inputFile.open(inputFileName);
if (!inputFile.is_open()){ //ez egy exception
throw "File could not be open!";
}
std::string name;
std::string type;
std::string date;
std::map<std::string, int> usageData;
while(inputFile >> name >> type >> date){
usageData[type]++;
//usageData[type] = +1;
}
inputFile.close();
std::ofstream outputFile;
outputFile.open(outputFileName);
outputFile << "Building usage: " << std::endl << std::endl;
for (std::map<std::string, int>::iterator it = usageData.begin(); it != usageData.end(); it++){
//std::cout << "type: "<< it->first << ", number " << it->second<< std::endl;
outputFile<< it->first << ": " << it->second<< std::endl;
}
}<file_sep>/week-03/day-2/Ex_11_Sharpie_set_2/sharpie.h
//
// Created by Lilla on 2019. 02. 13..
//
#ifndef EX_11_SHARPIE_SET_2_SHARPIE_H
#define EX_11_SHARPIE_SET_2_SHARPIE_H
class sharpie {
};
#endif //EX_11_SHARPIE_SET_2_SHARPIE_H
<file_sep>/week-04/day-2/Ex_01_GFOrganization/main.cpp
#include <iostream>
#include <vector>
#include <string>
#include "person.h"
#include "student.h"
#include "mentor.h"
#include "sponsor.h"
#include "cohort.h"
int main()
{
std::vector<Person*> people;
Person mark("Mark", 46, Gender::MALE);
people.push_back(&mark);
Person jane;
people.push_back(&jane);
Student john("<NAME>", 20, Gender::MALE, "BME");
people.push_back(&john);
Student student;
people.push_back(&student);
Mentor gandhi("Gandhi", 148, Gender::MALE, Level::SENIOR);
people.push_back(&gandhi);
Mentor mentor;
people.push_back(&mentor);
Sponsor sponsor;
people.push_back(&sponsor);
Sponsor elon("<NAME>", 46, Gender::MALE, "SpaceX");
people.push_back(&elon);
student.skipDays(3);
for (int i = 0; i < 5; i++) {
elon.hire();
}
for (int i = 0; i < 3; i++) {
sponsor.hire();
}
for(Person* person : people) {
person->introduce();
person->getGoal();
}
Cohort awesome = Cohort("AWESOME");
awesome.addStudent(&student);
awesome.addStudent(&john);
awesome.addMentor(&mentor);
awesome.addMentor(&gandhi);
std::cout << "\n" << std::endl;
awesome.info();
return 0;
}<file_sep>/week-05/day-1/ExampleExam_RotateMatrix/main.cpp
#include <vector>
#include <iostream>
std::vector<std::vector<int>> rotateMatrix (std::vector<std::vector<int>> input);//most másolat készül
void printMatrix(const std::vector<std::vector<int>>& matrix);
int main()
{
// Create a function named `rotateMatrix` that takes an n×n integer matrix (vector of vectors) as parameter
// and returns a matrix which elements are rotated 90 degrees clockwise.
//
// example input:
// [[1, 2, 3],
// [4, 5, 6],
// [7, 8, 9]]
std::vector<std::vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
std::vector<std::vector<int>> rotatedMatrix = rotateMatrix(matrix);
printMatrix(rotatedMatrix);
// should print
// 7 4 1
// 8 5 2
// 9 6 3
return 0;
}
void printMatrix(const std::vector<std::vector<int>>& matrix)
{
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
std::vector<std::vector<int>> rotateMatrix(std::vector<std::vector<int>> input)
{
std::vector<std::vector<int>> result = input; // a temp vectoromba bemásolom az eredeti mátrixot,
// így az indexelése is átmegy, érték szerinti értékadás
//ekkora memóriahelyet fogalalok neki
for (int i = 0; i < input.size(); ++i) {
//for (int j = 0; j < input[i].size(); ++j) { //ezt használom, ha nem négyzetről van szó, mert itt az aktuális sor méretét veszi ciklusnak
//std::vector<int> row; 2. megoldás, de bonyolult
for (int j = 0; j < input[i].size(); ++j) {
result[i][j] = input[j][i]; // ez a legegyszerűbb mód és akkor nem hozom be a row változót!!!
//ennél a lehetőségnél össze lehet vonni a következő résszel pl.: result[i][j] = input[input.size() - j - 1][i];
//row.push_back(input[j][i]); 2. megoldás, de bonyolult
}
//result.push_back(row); 2. megoldás, de bonyolult
}
std::vector<std::vector<int>> finalresult = result;
for (int i = 0; i < input.size(); ++i) {
for (int j = 0; j < input.size(); ++j) {
/*int centralindex = input[i].size()/2;
int newindex = j; //ez azért, mert ha páratlan számú, akkor a középső megtartja az indexét!
if (j > centralindex) {
newindex = j - centralindex - 1;
} else {
newindex = j + centralindex +1;
}
finalresult[i][j] = result[i][newindex];*/
finalresult[i][j] = result[i][input.size() - j - 1];
}
}
return finalresult;
}
<file_sep>/week-04/day-3/Ex_04_Devices/printer3d.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_04_DEVICES_PRINTER3D_H
#define EX_04_DEVICES_PRINTER3D_H
#include "printer.h"
class Printer3D : public Printer {
public:
Printer3D(int sizeX, int sizeY, int sizeZ);
std::string getSize() override;
private:
int _sizeX;
int _sizeY;
int _sizeZ;
};
#endif //EX_04_DEVICES_PRINTER3D_H
<file_sep>/week-06/day-1/Ex_07_pi_2/main.c
#include <stdio.h>
#include <stdlib.h>
#define PI 3.14
#define AREA(radius) (radius * radius * PI)
// define a variable called PI with the value of 3.14
// create a function which takes the radius of a circle as a parameter
// and return the area of that cirle
// area = radius * radius * PI
int main()
{
float area, radius;
printf("Give me the radius: \n");
scanf("%f", &radius);
printf("area = %.2f", AREA(radius));
return 0;
}<file_sep>/week-03/day-2/Ex_02_Blog_post/main.cpp
#include <iostream>
#include <string>
//Create a BlogPost class that has
// -an authorName
// -a title
// -a text
// -a publicationDate
// Create a few blog post objects:
// -"Lorem Ipsum" titled by <NAME> posted at "2000.05.04."
// -Lorem ipsum dolor sit amet.
// -"Wait but why" titled by Tim Urban posted at "2010.10.10."
// -A popular long-form, stick-figure-illustrated blog about almost everything.
// -"One Engineer Is Trying to Get IBM to Reckon With Trump" titled by <NAME> at "2017.03.28."
// -<NAME>, a cybersecurity engineer at IBM, doesn’t want to be the center of attention.
// When I asked to take his picture outside one of IBM’s New York City offices, he told me that he wasn’t really
// into the whole organizer profile thing.
class Blogspot
{
public:
void set_allthings(std::string au, std::string ttl, std::string txt, std::string date) { //Create the function used by the Postit class
authorName = au; //First method
title = ttl; //Second method
text = txt; //Third method
publicationDate = date; // Fourth method
all = "\"" + title + "\" titled by " + authorName + " posted at \"" + publicationDate + "\"\n\t- "+ text;
//all.append("\"").append(title).append("\"").append(" titled by ").append(authorName).append(" posted at ").append("\"").append(publicationDate).append("\" \n").append(text);
}
std::string getText(){
return all;
}
private:
std::string authorName; //First variable
std::string title; //Second variable
std::string text; //Third variable
std::string publicationDate; //Fourth variable
std::string all;
};
int main(){
std::string authorName1 = "<NAME>";
std::string title1 = "Lorem Ipsum";
std::string text1 = "Lorem ipsum dolor sit amet";
std::string publicationDate1 = "2000.05.04.";
Blogspot oneText; //First object
oneText.set_allthings(authorName1, title1, text1, publicationDate1);
std::cout << oneText.getText()<< std::endl;
std::string authorName2 = "<NAME>";
std::string title2 = "Wait but why";
std::string text2 = "A popular long-form, stick-figure-illustrated blog about almost everything";
std::string publicationDate2 = "2010.10.10.";
Blogspot twoText; //Second object
twoText.set_allthings(authorName2, title2, text2, publicationDate2);
std::cout << twoText.getText()<< std::endl;
return 0;
}<file_sep>/week-01/day-3/Ex_09_BMI/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_9_BMI)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_9_BMI main.cpp)<file_sep>/week-06/day-1/Ex_07_pi_3/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_pi_3 C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_07_pi_3 main.c pi.h pi.c)<file_sep>/week-02/day-3/VideoPractice_1/main.cpp
#include <iostream>
#include <fstream>
//Ha ki akarod próbálni, akkor az .exe file-t használd!!!
//Ha ki akarod próbálni, akkor az .exe file-t használd!!!
//Ha ki akarod próbálni, akkor az .exe file-t használd!!!
//Ha ki akarod próbálni, akkor az .exe file-t használd!!!
//Ha ki akarod próbálni, akkor az .exe file-t használd!!!
//Ha ki akarod próbálni, akkor az .exe file-t használd!!!
int main()
{
std::ofstream myFile("tuna.txt");
std::cout << "Enter your ID, name, and money, " << std::endl;
std::cout << "Dont't forget press CTRL+Z to quit: " << std::endl;
int numb;
std::string name;
double money;
while (std::cin >> numb >> name >> money){
myFile << numb << " " << name << " " << money << std::endl;
}
myFile.close();
return 0;
}<file_sep>/week-01/day-3/Ex_06_CodingHours/main.cpp
#include <iostream>
int main(int argc, char* args[]) {
// An average Green Fox attendee codes 6 hours daily
int dayWorkHours = 6;
// The semester is 17 weeks long
int semesterWeeks = 17;
// Print how many hours is spent with coding in a semester by an attendee,
// if the attendee only codes on workdays.
std::cout << dayWorkHours * 5 * semesterWeeks << std::endl;
// Print the percentage of the coding hours in the semester if the average
// working hours weekly is 52
float averWeekWorkHours = 52.;
float part = (dayWorkHours * 5 * semesterWeeks) / (averWeekWorkHours * semesterWeeks);
std::cout << part*100 << "%" << std::endl;
return 0;
}<file_sep>/week-06/day-1/Ex_08_organizing_2/pi.h
//
// Created by Lilla on 2019. 02. 18..
//
#ifndef EX_08_ORGANIZING_2_PI_H
#define EX_08_ORGANIZING_2_PI_H
#define PI 3.14
#define AREA(radius) (radius * radius * PI)
#define CIRCUMFERENCD(radius) (2 * radius * PI)
#endif //EX_08_ORGANIZING_2_PI_H
<file_sep>/week-06/day-1/Ex_14_lenght/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_14_lenght)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_14_lenght main.c)<file_sep>/week-01/day-3/Ex_20_Printbigger/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_20_Printbigger)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_20_Printbigger main.cpp)<file_sep>/week-03/day-2/Ex_06_Pokemon/pokemon.h
//
// Created by Lilla on 2019. 01. 30..
//
//Every pokemon has a name and a type. Certain types are effective against others, e.g. water is effective against fire.
//You have a Pokemon class with a method called isEffectiveAgainst().
//Ash has a few pokemon. Help Ash decide which Pokemon to use against the wild one.
//You can use the already created pokemon files.
#ifndef EX_06_POKEMON_POKEMON_H
#define EX_06_POKEMON_POKEMON_H
#include <iostream>
class Pokemon {
public:
Pokemon(const std::string& name, const std::string& type, const std::string& effectiveAgainst);
bool isEffectiveAgainst(Pokemon anotherPokemon);
std::string _name;
std::string _type;
std::string _effectiveAgainst;
};
#endif //EX_06_POKEMON_POKEMON_H
<file_sep>/week-03/day-3/Ex_11_Refactorio/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_11_Refactorio)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_11_Refactorio main.cpp)<file_sep>/week-08/day-4/Displaying_temperature/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
I2C_HandleTypeDef I2C_handle; // defining the I2C configuration structure
GPIO_InitTypeDef SCL_SDA_config; // configure GPIOs for I2C data and clock lines
UART_HandleTypeDef uart; // UART config structure
TIM_HandleTypeDef tim_handle; // timer (TIM2) config handle structure
volatile int timer_flag = 0;
volatile uint8_t read_temp_reg = 0;
volatile uint8_t read_temp_val;
/* 7 bit address of an I2C sensor shifted to left 1 bit, leaving place for W/R bit,
* which is inserted by the HAL_I2C_Master_Transmit and HAL_I2C_Master_Receive */
#define TEMP_SENSOR_ADDRESS (0b1001000 << 1)
#define UART_PUTCHAR int __io_putchar(int ch)
static void Error_Handler(void);
static void SystemClock_Config(void);
void init_timer(void);
void init_uart(void);
void init_I2C(void);
void write_to_uart();
int main(void)
{
HAL_Init();
SystemClock_Config(); //for TIMERS
init_uart();
init_timer();
init_I2C();
HAL_TIM_Base_Start_IT(&tim_handle); //starting the timer - init_timer() won't work without it
while (1) {
//HAL_Delay(1000); //using TIM2 timer insterad of HAL_DELAY()
write_to_uart();
}
}
void init_uart(void)
{
__HAL_RCC_USART1_CLK_ENABLE(); //giving clock
/* defining the UART configuration structure */
uart.Instance = USART1;
uart.Init.BaudRate = 115200;
uart.Init.WordLength = UART_WORDLENGTH_8B;
uart.Init.StopBits = UART_STOPBITS_1;
uart.Init.Parity = UART_PARITY_NONE;
uart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
uart.Init.Mode = UART_MODE_TX;
BSP_COM_Init(COM1, &uart); //init USART
}
void init_timer(void)
{
//initialize TIM2
__HAL_RCC_TIM2_CLK_ENABLE(); //giving clock
HAL_TIM_Base_DeInit(&tim_handle); // de-initialize the TIM_Base, because of safety reasons
// configuriation of the basic mode of the timer (which direction should it count, what is the maximum value, etc.)
tim_handle.Instance = TIM2; //register base address
tim_handle.Init.Prescaler = 10800 - 1; // 108000000 / 10800 = 10000 -> speed of 1 count-up: 1 /10000 s = 0.1 ms
tim_handle.Init.Period = 10000 - 1; // 10000 x 0.1 ms = 1000 ms = 1 s period */
tim_handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
tim_handle.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_Base_Init(&tim_handle); //configure the timer
HAL_NVIC_SetPriority(TIM2_IRQn, 2, 0); //set TIM2 interrupt priority
HAL_NVIC_EnableIRQ(TIM2_IRQn); //enable the interrupt to HAL
}
void init_I2C(void)
{
__HAL_RCC_GPIOB_CLK_ENABLE(); /* enable GPIO clock */
SCL_SDA_config.Pin = GPIO_PIN_8 | GPIO_PIN_9; /* PB8: SCL, PB9: SDA */
SCL_SDA_config.Pull = GPIO_PULLUP;
SCL_SDA_config.Mode = GPIO_MODE_AF_OD; /* configure in pen drain mode */
SCL_SDA_config.Alternate = GPIO_AF4_I2C1;
HAL_GPIO_Init(GPIOB, &SCL_SDA_config);
__HAL_RCC_I2C1_CLK_ENABLE(); /* enable the clock of the used peripheral */
/* defining the UART configuration structure */
I2C_handle.Instance = I2C1;
I2C_handle.Init.Timing = 0x40912732;
I2C_handle.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
HAL_I2C_Init(&I2C_handle);
}
void write_to_uart()
{
if (timer_flag) {
HAL_I2C_Master_Transmit(&I2C_handle, TEMP_SENSOR_ADDRESS,
&read_temp_reg, sizeof(read_temp_reg), 100);
HAL_I2C_Master_Receive(&I2C_handle, TEMP_SENSOR_ADDRESS,
&read_temp_val, sizeof(read_temp_val), 100);
/* or using HAL_I2C_Mem_Read():
HAL_I2C_Mem_Read(&I2C_handle, TEMP_SENSOR_ADDRESS, read_temp_reg, I2C_MEMADD_SIZE_8BIT,
&read_temp_val, sizeof(read_temp_val), 100);
*/
timer_flag = 0;
printf("Temperature: %d\r\n", read_temp_val);
}
}
//---------- 4 TIM2 HANDLER -------------------
//TIM2 external interrupt handler
void TIM2_IRQHandler(void)
{
HAL_TIM_IRQHandler(&tim_handle);
}
//declare week callback function
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
//if (htim->Instance == TIM2)
if (htim->Instance == tim_handle.Instance) {
timer_flag = 1;
}
}
//using printf()
UART_PUTCHAR
{
HAL_UART_Transmit(&uart, (uint8_t*)&ch, 1, 0xFFFF);
return ch;
}
//error handler
static void Error_Handler(void)
{}
//system clock config to TIMERs
static void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/**Configure the main internal regulator output voltage */
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 216;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/**Activate the Over-Drive mode */
if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) {
Error_Handler();
}
}
<file_sep>/week-04/day-3/Ex_01_InstruStringedInstru/electricguitar.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_01_INSTRUSTRINGEDINSTRU_ELECTRICGUITAR_H
#define EX_01_INSTRUSTRINGEDINSTRU_ELECTRICGUITAR_H
#include "stringedinstrument.h"
class ElectricGuitar : public StringedInstrument
{
public:
ElectricGuitar(int numberOfStrings);
ElectricGuitar();
std::string sound() override;
};
#endif //EX_01_INSTRUSTRINGEDINSTRU_ELECTRICGUITAR_H
<file_sep>/week-02/day-1/Ex_04_todoprint/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_04_todoprint)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_04_todoprint main.cpp)<file_sep>/week-06/day-1/Ex_10_equal_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_10_equal_2 C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_10_equal_2 main.c)<file_sep>/week-06/day-2/Ex_08_printLines/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_08_printLines C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_08_printLines main.c)<file_sep>/week-05/day-4/trialTrialEx3Restaurant/waitor.cpp
//
// Created by Lilla on 2019. 02. 14..
//
#include "waitor.h"
void Waitor::work() {
_tips++;
_experience++;
}
Waitor::Waitor(std::string name, int experience) :
Employee(name, experience)
{
}
std::string Waitor::toString() {
return (Employee::toString() + " and got " + std::to_string(_tips) + " dollar for tips");
}
<file_sep>/week-01/day-3/Ex_36_Substr/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_36_Substr)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_36_Substr main.cpp)<file_sep>/week-05/day-4/trialTrialEx2BuildingUsage/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(trialTrialEx2BuildingUsage)
set(CMAKE_CXX_STANDARD 14)
add_executable(trialTrialEx2BuildingUsage main.cpp)<file_sep>/week-04/day-3/Ex_02_Zoo/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_02_Zoo)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_02_Zoo main.cpp animal.cpp animal.h mammals.cpp mammals.h byegg.cpp byegg.h bird.cpp bird.h reptile.cpp reptile.h)<file_sep>/week-04/day-1/VideoPractice_02/daughter.h
//
// Created by Lilla on 2019. 02. 05..
//
#ifndef VIDEOPRACTICE_02_DAUGHER_H
#define VIDEOPRACTICE_02_DAUGHER_H
#include "mother.h"
class Daughter: public Mother
{
public:
Daughter();
~Daughter();
protected:
private:
};
#endif //VIDEOPRACTICE_02_DAUGHER_H
<file_sep>/week-06/day-1/Ex_19_subString/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_19_subString C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_19_subString main.c)<file_sep>/week-05/day-1/TrialExam_Pirates/ship.cpp
//
// Created by Lilla on 2019. 02. 11..
//
#include "ship.h"
#include <algorithm>
Ship::Ship()
{
}
void Ship::addPirate(Pirate onepirate) {
//_pirates.push_back(onepirate);
if (!onepirate.captain()){
_pirates.push_back(onepirate);
}
if (onepirate.captain()){
for (int i = 0; i < _pirates.size(); ++i) {
if (_pirates[i].captain()){
return;
} else {
_pirates.push_back(onepirate);
}
}
}
}
std::vector<std::string> Ship::getPoorPirates()
{
std::vector<std::string> _poorPirates;
for (int i = 0; i < _pirates.size(); ++i) {
if (_pirates[i].woodLeg() || _pirates[i].getGold() < 15){
_poorPirates.push_back(_pirates[i].getName());
}
}
return _poorPirates;
}
int Ship::getGolds()
{
int sum = 0;
for (int i = 0; i < _pirates.size(); ++i) {
sum += _pirates[i].getGold();
}
return sum;
}
void Ship::lastDayOnTheShip()
{
for (int i = 0; i < _pirates.size(); ++i) {
_pirates[i].party();
}
}
void Ship::prepareForBattle()
{
for (int i = 0; i < _pirates.size(); ++i) {
for (int j = 0; j < 5; ++j) {
_pirates[i].work();
}
}
lastDayOnTheShip();
}
<file_sep>/week-01/day-3/Ex_30_DrawDiamond/main.cpp
// Write a program that reads a number from the standard input, then draws a
// diamond like this:
// *
// ***
// *****
// *******
// *****
// ***
// *
//
// The diamond should have as many lines as the number was
#include <iostream>
int main(int argc, char* args[]) {
int diamondLine;
std::cout << "How big the diamond should be? ";
std::cin >> diamondLine;
int startSpace = diamondLine/2;
int startStar = 1;
for (int i = 0; i < diamondLine/2; ++i) {
for (int j = 0; j < startSpace; ++j) {
std::cout << " ";
}
for (int k = 0; k < startStar; ++k) {
std::cout << "*";
}
std::cout << "\n";
startSpace--;
startStar = startStar + 2;
}
for (int l = 0; l < diamondLine / 2 +1 ; ++l) {
for (int j = 0; j < startSpace; ++j) {
std::cout << " ";
}
for (int m = 0; m < startStar; ++m) {
std::cout << "*";
}
std::cout << "\n";
startSpace++;
startStar = startStar - 2;
}
return 0;
}<file_sep>/week-04/day-1/ExBefInheritance/gender.h
//
// Created by Lilla on 2019. 02. 03..
//
#ifndef EXBEFINHERITANCE_GENDER_H
#define EXBEFINHERITANCE_GENDER_H
#include <string>
#include <iostream>
enum Gender
{
MALE,
FEMALE
};
#endif //EXBEFINHERITANCE_GENDER_H
<file_sep>/week-03/day-3/Ex_03_Sumdigit/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_Sundigit)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_03_Sundigit main.cpp)<file_sep>/week-04/day-3/Ex_01_InstruStringedInstru/violin.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_01_INSTRUSTRINGEDINSTRU_VIOLIN_H
#define EX_01_INSTRUSTRINGEDINSTRU_VIOLIN_H
#include "stringedinstrument.h"
#include <iostream>
class Violin : public StringedInstrument
{
public:
Violin(int numberOfStrings);
Violin(int numberOfStrings, int size);
Violin();
std::string sound() override;
int _size;
};
#endif //EX_01_INSTRUSTRINGEDINSTRU_VIOLIN_H
<file_sep>/week-02/day-1/Ex_13_calculator/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_13_calculator)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_13_calculator main.cpp)<file_sep>/week-03/day-3/Ex_06_BunniesAgain/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_06_BunniesAgain)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_06_BunniesAgain main.cpp)<file_sep>/week-03/day-2/Ex_10_Petrol_station/car.cpp
//
// Created by Lilla on 2019. 01. 30..
//
#include "car.h"
#include <iostream>
Car::Car(int capacity, int gasAmount)
{
gasAmount_ = gasAmount;
capacity_ = capacity;
}
bool Car::isFull()
{
return capacity_ == gasAmount_;
}
void Car::fill()
{
gasAmount_++;
}<file_sep>/week-04/day-3/LessonPractice_1/rect.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include "rect.h"
Rect::Rect(int x, int y, int w, int h) : Shape(x, y)
{
width = w;
height = h;
}
double Rect::circumference()
{
return 2 * width + 2 * height;
}
double Rect::area()
{
return width * height;
}<file_sep>/week-01/day-3/Ex_16_AnimalsLegs/main.cpp
#include <iostream>
int main(int argc, char* args[]) {
// Write a program that asks for two integers
// The first represents the number of chickens the farmer has
int numbChick;
// The second represents the number of pigs owned by the farmer
int numbPig;
// It should print how many legs all the animals have
std::cout << "Write the numbers of chickens and pigs: " <<std::endl;
std::cin >> numbChick >> numbPig;
std::cout << "All the chickens and the pigs on the farm is " << numbChick*2+numbPig*4 <<std::endl;
return 0;
}<file_sep>/week-01/weekend/question operator/main.cpp
#include <iostream>
int main() {
int x, y = 10;
x = (y < 10) ? 30 : 40;
std::cout << "values of x " << x << std::endl;
return 0;
}<file_sep>/week-04/day-1/ExBefInheritance_2/main.cpp
#include <iostream>
#include "mentor.h"
#include "person.h"
void demonstrateObjectslicing()
{
Mentor m2("Maty", 27, Gender::MALE, Level::INTERMEDIATE);
Person p = m2;
p.getGoal();
p.introduce();
}
void sayHello(Person p)
{
p.introduce();
}
void sayHello2(Person &p)
{
p.introduce();
}
int main()
{
Person p("Pali", 23, Gender::MALE);
p.getGoal();
p.introduce();
sayHello(p);
std::cout << "\n";
Person r;
r.getGoal();
r.introduce();
std::cout << "\n";
Mentor m;
m.getGoal();
m.introduce();
std::cout << "\n";
Mentor m2("Matyi", 26, Gender::MALE, Level::INTERMEDIATE);
m2.getGoal();
m2.introduce();
std::cout << "\n";
sayHello(m2); //elveszik így a mentor jellemző, ha nem referencia szerint adom át
sayHello2(m2);//nem veszik el a mentor jellemző ha referencia szerint adom át!!
demonstrateObjectslicing(); //example to slicing
return 0;
}<file_sep>/week-04/day-1/ExBefInheritance/gender.cpp
//
// Created by Lilla on 2019. 02. 03..
//
#include <iostream>
#include "gender.h"
switch(Gender::gender){
case Gender::MALE:return std::string("male");
case Gender::FEMALE:return std::string("female");
}
<file_sep>/week-04/weekend/ex_01/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(ex_01)
set(CMAKE_CXX_STANDARD 14)
add_executable(ex_01 main.cpp)<file_sep>/week-02/day-3/Ex_08_TicTakToe/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_08_TicTakToe)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_08_TicTakToe main.cpp)<file_sep>/week-02/day-2/Ex_04_adding/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_04_adding)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_04_adding main.cpp)<file_sep>/week-01/day-3/Ex_12_cuboid/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_12_cuboid)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_12_cuboid main.cpp)<file_sep>/week-03/day-2/Ex_09_Dominoes/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_09_Dominoes)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_09_Dominoes main.cpp domino.cpp domino.h)<file_sep>/week-07/day-4/Ex_04_LED_control_via_UART/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
#include <string.h>
#define UART_PUTCHAR int __io_putchar(int ch)
UART_HandleTypeDef uart;
GPIO_InitTypeDef LEDS;
void init_GPIO_BSP_uart();
void init_external_led();
int main(void)
{
HAL_Init();
BSP_LED_Init(LED1);
init_GPIO_BSP_uart();
init_external_led();
char buffer[4];
memset(buffer, '\0', 4);
char received_from_hercules[2] = "\0";
while (1) {
char received_from_hercules[4];
memset(received_from_hercules, '\0', 4);
HAL_UART_Receive(&uart, (uint8_t*) received_from_hercules, 3, 3000);
if (strcmp(received_from_hercules, "ON") == 0) {
BSP_LED_On(LED1);
printf("OK ON");
} else if (strcmp(received_from_hercules, "OFF") == 0) {
BSP_LED_Off(LED1);
printf("OK OFF");
} else if (strcmp(received_from_hercules, "") == 0) {
printf("waiting");
} else {
printf("not OK");
for (int i = 0; i < 3; i++) {
BSP_LED_Off(LED1);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_SET);
HAL_Delay(500);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_RESET);
HAL_Delay(500);
}
}
}
}
void init_GPIO_BSP_uart()
{
//init uart for GPIO purpose with BSP
/* enable GPIO clock for A and B port*/
__HAL_RCC_USART1_CLK_ENABLE();
/* defining the UART configuration structure */
uart.Instance = USART1;
uart.Init.BaudRate = 115200;
uart.Init.WordLength = UART_WORDLENGTH_8B;
uart.Init.StopBits = UART_STOPBITS_1;
uart.Init.Parity = UART_PARITY_NONE;
uart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
uart.Init.Mode = UART_MODE_TX_RX;
BSP_COM_Init(COM1, &uart);
}
void init_external_led()
{
//initialize external LED on F port pin 7
__HAL_RCC_GPIOF_CLK_ENABLE(); //giving clock
LEDS.Pin = GPIO_PIN_7; // setting up a pin
LEDS.Mode = GPIO_MODE_OUTPUT_PP;
LEDS.Pull = GPIO_NOPULL;
LEDS.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOF, &LEDS); //first param: name of port, second param: name of structure
}
UART_PUTCHAR
{
HAL_UART_Transmit(&uart, (uint8_t*)&ch, 1, 0xFFFF);
return ch;
}
<file_sep>/week-05/day-1/ExampleExam_SwearWords/main.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
int familyFriendlizer(std::string fileName, std::vector<std::string> offensiveWords);
int main()
{
// There is a not so family friendly text in the `content.txt`
// Create a function named familyFriendlizer that takes a filename and a list of strings as parameters
// and remove all the given words from the file and returns the amount of the removed words.
std::vector<std::string> offensiveWords = { "fuck", "bloody", "cock", "shit", "fucker", "fuckstick", "asshole", "dick", "piss" };
std::cout << familyFriendlizer("content.txt", offensiveWords);
return 0;
}
int familyFriendlizer(std::string fileName, std::vector<std::string> offensiveWords){
std::ifstream inputFile;
inputFile.open("content.txt");
if (!inputFile.is_open()) {
throw "File could not open";
}
std::string result;
std::string stringStream;
int removeWordCount = 0;
std::string line;
while (std::getline(inputFile, line)){
std::stringstream stringStream(line);
bool isOffensive = false;
std::string word;
while (std::getline(stringStream, word, ' ')){ // az elválasztott szavakat a word változóba rakjuk bele;
for (int i = 0; i < offensiveWords.size(); ++i) {
if (offensiveWords[i] == word){
isOffensive = true;
removeWordCount++;
std::cout << word << std::endl;
break;
}
}
if (!isOffensive) {
result += word + " ";
}
}
//std::cout << line << std::endl;
}
inputFile.close();
//std::ofstream outputFile;
//outputFile.open(fileName);
//outputFile << result; //ez kell a megoldáshoz csak kikommenteltem, hogy ne hajtsa végre
//outputFile.close();
std::cout << result << std::endl;
//std::cout << removeWordCount << std::endl;
return removeWordCount;
}<file_sep>/week-04/day-1/VideoPractice_01/daughter.h
//
// Created by Lilla on 2019. 02. 05..
//
#ifndef VIDEOPRACTICE_DAUGHTER_H
#define VIDEOPRACTICE_DAUGHTER_H
class Daughter: public Mother
{
public:
Daughter();
void doSomething();
protected:
private:
};
#endif //VIDEOPRACTICE_DAUGHTER_H
<file_sep>/week-01/day-4/Ex_16_AppendA/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_16_AppendA)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_16_AppendA main.cpp)<file_sep>/week-05/day-1/ExampleExam_Shelter/animalshelter.h
//
// Created by Lilla on 2019. 02. 11..
//
#ifndef EXAMPLEEXAM_SHELTER_ANIMALSHELTER_H
#define EXAMPLEEXAM_SHELTER_ANIMALSHELTER_H
#include "animal.h"
#include <vector>
class AnimalShelter
{
public:
int rescue(Animal animal);
std::string toString();
bool heal();
private:
int _budget = 50;
std::vector<Animal> _animals;
std::vector<std::string> _adopters;
};
#endif //EXAMPLEEXAM_SHELTER_ANIMALSHELTER_H
<file_sep>/week-01/day-3/Ex_29_DrawPyramic/main.cpp
#include <iostream>
int main(int argc, char* args[]) {
// Write a program that reads a number from the standard input, then draws a
// pyramid like this:
//
//
// *
// ***
// *****
// *******
//
// The pyramid should have as many lines as the number was
int pyramidRow;
std::string starBase = "*";
std::string star = "**";
std::string spaceBase = " ";
std::cout << "Write how many rows should the tringle have: " << std::endl;
std::cin >> pyramidRow;
int forSpace = pyramidRow;
for (int i = 0; i < pyramidRow; ++i) {
for (int j = (forSpace - 1); j > 0; --j) {
std::cout << spaceBase;
}
std::cout << starBase;
starBase = starBase + star;
for (int j = (forSpace - 1); j > 0; --j) {
std::cout << spaceBase;
}
forSpace = forSpace - 1;
std::cout << std::endl;
}
return 0;
}<file_sep>/week-06/day-2/Ex_07_Digimon/main.c
#include "digimon.h"
/* Digimon database!
* You should store the following data in a structure
* - the name of the digimon (which is shorter than 128 characters)
* - the age of the digimon (in years)
* - the health of the digimon (between 0-100)
* - the name of the tamer (which is shorter than 256 characters)
* - the digivolution level of the digimon (as a custom type, see below)
*/
/* You should store the digivolution level in an enumeration
* the valid digivolution levels are:
* - baby
* - in-training
* - rookie
* - champion
* - ultimate
* - mega
*
* The digimons are stored in an array.
*
* Write the following functions:
* Done 1) Get minimum health index
* - parameters:
* - array
* - array length
* - it returns the index of the minimal health digimon in the "array"
* Done 2) Get same digivolution level count
* - parameters:
* - array
* - array length
* - digivolution level
* - it returns the count of digimons which are at "digivolution level"
* Done 3) Get same tamer count
* - parameters:
* - array
* - array length
* - tamer name
* - it returns the count of the digimons which have the same tamer as "tamer name"
* 4) Get average health of the same tamer
* - parameters:
* - array
* - array length
* - tamer name
* - it returns the average health of the digimons which have the same tamer as "tamer name"
*
* Don't forget to handle invalid inputs (NULL pointers, invalid values etc.)
*/
int main()
{
int size = 5;
digimon_t digimon_array[size];
digimon_array[0].age = 1;
digimon_array[0].health = 65;
digimon_array[0].digi_level = BABY;
strcpy(digimon_array[0].name_tamer,"Apa");
digimon_array[1].age = 2;
digimon_array[1].health = 53;
digimon_array[1].digi_level = ROOKIE;
strcpy(digimon_array[1].name_tamer,"Apa");
digimon_array[2].age = 4;
digimon_array[2].health = 72;
digimon_array[2].digi_level = CHAMPION;
strcpy(digimon_array[2].name_tamer,"Anya");
digimon_array[3].age = 6;
digimon_array[3].health = 85;
digimon_array[3].digi_level = ULTIMATE;
strcpy(digimon_array[3].name_tamer,"Gyerekek");
digimon_array[4].age = 4;
digimon_array[4].health = 62;
digimon_array[4].digi_level = CHAMPION;
strcpy(digimon_array[4].name_tamer,"Anya");
printf("The index of minimum health among the digimon is %d\n", get_minimum_health_index(digimon_array, size));
printf("The number of %s level digimon is %d\n", getlevel(CHAMPION), count_digivolution_level(digimon_array, size, CHAMPION));
printf("The number of %s's digimons is %d\n", "Gyerekek", numb_same_tamer(digimon_array, size, "Gyerekek"));
return 0;
}<file_sep>/week-02/day-2/Ex_05_print_addresses/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_05_print_addresses)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_05_print_addresses main.cpp)<file_sep>/week-06/day-1/Ex_09_oldEnough/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_09_oldEnough)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_09_oldEnough main.c oldEnough.h)<file_sep>/week-04/day-3/Ex_02_Zoo/mammals.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_02_ZOO_MAMMALS_H
#define EX_02_ZOO_MAMMALS_H
#include "animal.h"
class Mammal : public Animal {
public:
Mammal(std::string name);
std::string getName() override;
std::string breed() override;
};
#endif //EX_02_ZOO_MAMMALS_H
<file_sep>/week-03/day-2/Ex_01_Post_it/main.cpp
#include <iostream>
#include <string>
//Create a PostIt class that has
// -a backgroundColor
// -a text on it
// -a textColor
//Create a few example post-it objects:
// -an orange with blue text: "Idea 1"
// -a pink with black text: "Awesome"
// -a yellow with green text: "Superb!"
class Postit
{
public:
Postit(std::string bgColor, std::string txtColor, std::string yourtext)
{
_backgroundColor = bgColor; //First method
_textColor = txtColor; //Second method
_text = yourtext; //Third method
}
void set_allthings (std::string bgColor, std::string txtColor, std::string yourtext) { //Create the function used by the Postit class
std::cout << _backgroundColor << " " << _textColor << " " << _text << std::endl;
}
private:
std::string _backgroundColor; //First variable
std::string _textColor; //Second variable
std::string _text; //Third variable
};
int main()
{
Postit oneText("orange", "blue", "Idea 1"); //First object
oneText.set_allthings("orange", "blue", "Idea 1");
Postit twoText("pink", "black", "Avesome"); //Second object
twoText.set_allthings("pink", "black", "Avesome");
Postit threeText("yellow", "green", "Superb!"); //Third object
threeText.set_allthings("yellow", "green", "Superb!");
return 0;
}<file_sep>/week-03/day-3/Ex_05_Bunnies/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_05_Bunnies)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_05_Bunnies main.cpp)<file_sep>/week-02/day-3/VideoPractice_1/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(VideoPractice_1)
set(CMAKE_CXX_STANDARD 14)
add_executable(VideoPractice_1 main.cpp)<file_sep>/week-04/day-3/LessonPractice_1/shape.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include "shape.h"
Shape::Shape (int x, int y)
{
_x = x; //this -> x = x; abban az esetben, ha kint csak x volt
_y = y; //this -> y = y; abban az esetben, ha kint csak x volt
}
void Shape::set_x(int x)
{
_x = x;
//this -> x = x;
//(this -> x)++; pl.: így használom az incrementálást
}
void Shape::move(int dx, int dy) //a mozgatási függvényem
{
_x += dx;
_y += dy;
}
<file_sep>/week-03/day-2/Ex_10_Petrol_station_2/car.h
//
// Created by Lilla on 2019. 02. 13..
//
#ifndef EX_10_PETROL_STATION_2_CAR_H
#define EX_10_PETROL_STATION_2_CAR_H
class Car {
public:
Car(int gasAmount, int capacity);
bool isFull();
void fill();
private:
int _gasAmount;
int _capacity;
};
#endif //EX_10_PETROL_STATION_2_CAR_H
<file_sep>/week-04/day-1/ExBefInheritance_2/mentor.cpp
//
// Created by Lilla on 2019. 02. 05..
//
#include <iostream>
#include "mentor.h"
std::string getLevelString(Level level)
{
if(level == Level::INTERMEDIATE){
return "intermediate";
} else if (level == Level::JUNIOR) {
return "junior";
} else if (level == Level::SENIOR) {
return "senior";
}
}
Mentor::Mentor()
//Mentor::Mentor() :
// Person()
{
_level = Level::INTERMEDIATE;
};
Mentor::Mentor(std::string name, int age, Gender gender, Level level) :
Person(name, age, gender)//ha az ősosztályból valamelyik adatot meg akaorm változtatni, akkor itt tudom. Pl.: az age helyett azt írom, hogy 20!!!!!!
{
_level = level;
}
void Mentor::getGoal()
{
std::cout << "My goal is: Hire brilliant junior software developers." << std::endl;
}
void Mentor::introduce()
{
std::cout << "Hi, I'm " << _name << ", a " << _age << " year old " << getGenderString(_gender)
<< " " << getLevelString(_level) << " mentor" << std::endl;
}<file_sep>/week-03/day-2/Ex_03_Animal/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_Animal)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_03_Animal main.cpp)<file_sep>/week-01/day-3/Ex_35_DrawChessTable/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_35_DrawChessTable)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_35_DrawChessTable main.cpp)<file_sep>/week-06/day-1/Ex_15_areTheSame/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int isSame(char strOne[], char strTwo[]);
int main()
{
// Create a program which asks for two strings and stores them
// Create a function which takes two strings as parameters and
// returns 1 if the two strings are the same and 0 otherwise
// Try to erase small and uppercase sensitivity.
char str1[15];
char str2[15];
strcpy(str1, "abcde7");
strcpy(str2, "ABCDE7");
if(isSame(str1, str2)){
printf("Yes\n");
} else {
printf("No\n");
}
char str3[15];
char str4[15];
printf("Print to string with a space between eachother: ");
scanf("%s %s", str3, str4);
if(isSame(str3, str4)){
printf("Yes\n");
} else {
printf("No\n");
}
return 0;
}
int isSame(char strOne[], char strTwo[])
{
char tempCharOne[15];
int sizeOne = strlen(strOne);
for (int i = 0; i < sizeOne; ++i) {
tempCharOne[i] = toupper(strOne[i]);
}
char tempCharTwo[15];
int sizeTwo = strlen(strTwo);
for (int i = 0; i < sizeTwo; ++i) {
tempCharTwo[i] = toupper(strTwo[i]);
}
int ret;
ret = strcmp(tempCharOne, tempCharTwo);
return !ret;
}
<file_sep>/week-02/day-1/Ex_07_matchmaking/main.cpp
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> makingMatches(const std::vector<std::string> &girls, const std::vector<std::string> &boys)
{
std::vector<std::string> newvectorname; //We created a new vector typed string to be independent from original vector
int need_size; //First time we don't know how many matches we will find, so girls or boys are more - we don't count them manually!!!
if (girls.size() > boys.size()) {
need_size = girls.size(); //If girls are more, the number of loops
} else {
need_size = boys.size(); //If boys are more, the number of loops
}
for (unsigned int i = 0;
i < need_size; ++i) { //We use x.push_back to insert new element in a vector and resize them
//We do the loop as many times as the number of bigger group is
if (i < girls.size()) {
newvectorname.push_back(girls[i]);
}
if (i < boys.size()) {
newvectorname.push_back(boys[i]);
}
}
return newvectorname;
}
int main(int argc, char *args[]) {
std::vector<std::string> girls = {"Eve", "Ashley", "Claire", "Kat", "Jane"};
std::vector<std::string> boys = {"Joe", "Fred", "Tom", "Todd", "Neef", "Jeff"};
// Write a method that joins the two lists by matching one girl with one boy into a new list
// If someone has no pair, he/she should be the element of the list too
// Exepected output: "Eve", "Joe", "Ashley", "Fred"...
std::vector<std::string> matches = makingMatches(girls, boys);
for (int i = 0; i < matches.size(); ++i) {
std::cout << matches[i] << " ";
}
return 0;
}<file_sep>/week-03/day-2/Ex_08_Dice_set/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_08_Dice_set)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_08_Dice_set main.cpp dice_set.cpp dice_set.h)<file_sep>/week-04/day-3/LessonPractice_2/main.cpp
#include <iostream>
struct twoNumb
{
int a;
int a2;
float b;
};
int main() {
twoNumb nums;
nums.a = 5;
nums.a2 = 6;
nums.b = 8.3;
twoNumb* p_nums = &nums; //pointerrel rállok a meglévő nums -ot, csak a memória helyet jeöli
(*p_nums).a = 6; // ez a kettő ugyanaz!!!!!!
p_nums->a2 = 7;// ez a kettő ugyanaz!!!!!! a nyíl kiváltaja a deference-et
std::cout << "Hello, World!" << std::endl;
return 0;
}<file_sep>/week-01/day-3/Ex_18_OddEven/main.cpp
/* #include <iostream>
#include <string>
int main(int argc, char* args[]) {
int a = 13;
if (a == 13) {
std::cout << "Yaaaay! The value of the variable is 13." << std::endl;
}
if (a == 8) {
std::cout << "Yaaaay! The value of the variable is 8." << std::endl;
}
int b = 20;
if (b < 10) {
std::cout << "Yaaaay! The value of the variable is lower than 10." << std::endl;
} else {
std::cout << "Yaaaay! The value of the variable is higher than 10." << std::endl;
}
int c = 15;
if (c < 10) {
std::cout << "Yaaaay! The value of the variable is lower than 10." << std::endl;
} else if (c < 20) {
std::cout << "Yaaaay! The value of the variable is lower than 20 but higher that 10." << std::endl;
} else {
std::cout << "Yaaaay! The value of the variable is higher than 20" << std::endl;
}
bool thirsty = true;
bool hungry = false;
if(thirsty && hungry) {
std::cout << "Lunch time!" << std::endl;
} else if (thirsty || hungry) {
std::cout << "Snack time!" << std::endl;
} else {
std::cout << "Adventure time!" << std::endl;
}
return 0;
} */
#include <iostream>
int main(int argc, char* args[]) {
// Write a program that reads a number from the standard input,
// Then prints "Odd" if the number is odd, or "Even" if it is even.
int oddeven;
std::cout << "Write a number: " << std::endl;
std::cin >> oddeven;
if ((oddeven) % 2 == 0) {
std::cout << "Even" << std::endl;
} else {
std::cout << "Odd" << std::endl;
}
return 0;
}<file_sep>/week-06/day-1/Ex_23_calculateSpeed/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_23_calculateSpeed)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_23_calculateSpeed main.cpp)<file_sep>/week-04/day-3/Ex_02_Zoo/bird.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include <iostream>
#include "bird.h"
Bird::Bird(std::string name)
{
_name = name;
//breed();
}
std::string Bird::getName()
{
return _name;
}<file_sep>/week-02/day-1/Ex_11_candyshop/main.cpp
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
std::vector<std::string>filter(std::vector<std::string> &list, const std::vector<std::string> &sweets)
{
std::vector<std::string> tempList;
std::vector<std::string> tempSweets;
for (unsigned int j = 0; j < list.size(); ++j) {
tempList.push_back(list[j]);
}
for (unsigned int j = 0; j < sweets.size(); ++j) {
tempSweets.push_back(sweets[j]);
}
for (int i = 0; i < tempList.size(); ++i) {
if (std::find(tempSweets.begin(), tempSweets.end(), tempList[i]) != tempSweets.end()){
tempList.erase(tempList.begin() + i);
i--; //azért kell csökkentenem a sorszámozást, mert a 2. tag törlése után a "Bread" nem a 3. tag, hanem a 2. helyre került
}
}
return tempList;
}
int main(int argc, char* args[])
{
const std::vector<std::string> sweets = {"Cupcake", "Brownie"};
std::vector<std::string> list = {"Cupcake", "Carrot", "Bread", "Brownie", "Lemon"};
// Accidentally we added "Carrot", "Lemon" and "Bread" to the list.
// Your task is to remove them from the list. "sweets" vector can help you with this
// You should erase every element from "list" vector that is not in "sweets" vector.
// No, don't just remove the lines
// Create a method called filter() which takes the two lists as parameters.
std::vector<std::string> filteredList = filter(list, sweets);
// Expected output: Cupcake Brownie
for (int i = 0; i < filteredList.size(); ++i) {
std::cout << filteredList[i] << " ";
}
return 0;
}<file_sep>/week-06/day-1/Ex_25_sentence/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_25_sentence)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_25_sentence main.cpp)<file_sep>/week-05/day-1/ExampleExam_Shelter/main.cpp
#include <iostream>
#include "animal.h"
#include "animalshelter.h"
#include "dog.h"
#include "cat.h"
#include "parrot.h"
int main()
{
// Create an animal shelter where we can save and take care of Animals
//
// An Animal
// - has a `name` and stores it's health state in a boolean
// - has a `healCost` field
// - has a method named `heal()`, that sets the `isHealthy` field's status to true
// - has a method named `isAdoptable()` that returns a boolean value whether it can be adopted or not (an animal can be adopted if it is healthy)
// - has a method named `toString()` that represents the Animal in the following format:
// <name> is not healthy (<heal cost>€), and not adoptable
// <name> is healthy, and adoptable
// The animal's name is the same as the class name by default, but it can be set thought constructor as well
//
// We are working with 3 types of Animals
// - Cat's healing cost should be a random number between 0 and 6
// - Dog's healing cost should be a random number between 1 and 8
// - Parrot's healing cost should be a random number between 4 and 10
//
// An AnimalShelter
// - has a `budget`
// - has an `animals` list
// - has an `adopters` name list
// - has a method named `rescue(Animal)` this method takes an Animal object as parameter and add the animal to the shelter's list and return the size of the list
// - has a method named `heal()` this method heals the first not healthy Animal, if it is possible by budget, returns the amount of healed animals(0 or 1)
// - has a method named `addAdopter(std::string)` this method takes a string as parameter and save it as a potential new owner
// - has a method named `findNewOwner()` this method pairs a random name with a random adoptable Animal if it is possible and remove both of them from the lists
// - has a method named `earnDonation(int)` this method takes a whole number as parameter and increase the shelter's budget by the parameter's value and returns the current budget
// - has a method named `toString()` that represents the shelter in the following format:
// Budget: <budget>€, There are <animals.size()> animal(s) and <potentionalAdopters.size()> potential adopter(s)
// <animal1 name> is not healthy (<heal cost>€), and not adoptable
// <animal2 name> is healthy, and adoptable
//
// The shelter starts with 50€ without any Animal and adopter
//
AnimalShelter animalShelter;
Cat cat;
Dog dog("Furkesz");
Parrot parrot;
animalShelter.rescue(cat);
animalShelter.rescue(dog);
animalShelter.rescue(parrot);
std::cout << animalShelter.toString() << std::endl;
// Budget: 50€, There are 3 animal(s) and 0 potential adopter(s)
// Cat is not healthy (3€) and not adoptable
// Furkesz is not healthy (1€) and not adoptable
// Parrot is not healthy (7€) and not adoptable
animalShelter.heal();
std::cout << animalShelter.toString() << std::endl;
// Budget: 47€, There are 3 animal(s) and 0 potential adopter(s)
// Cat is healthy and adoptable
// Furkesz is not healthy (1€) and not adoptable
// Parrot is not healthy (7€) and not adoptable
animalShelter.addAdopter("Kond");
std::cout << animalShelter.toString() << std::endl;
// Budget: 47€, There are 3 animal(s) and 1 potential adopter(s)
// Cat is healthy and adoptable
// Furkesz is not healthy (1€) and not adoptable
// Parrot is not healthy (7€) and not adoptable
animalShelter.findNewOwner();
animalShelter.earnDonation(30);
std::cout << animalShelter.toString() << std::endl;
// Budget: 77€, There are 2 animal(s) and 0 potential adopter(s)
// Furkesz is not healthy (1€) and not adoptable
// Parrot is not healthy (7€) and not adoptable
return 0;
}<file_sep>/week-06/day-3/Ex_02_calloc/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_02_calloc C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_02_calloc main.c)<file_sep>/week-02/day-3/Ex_03_Count_lines/main.cpp
#include <iostream>
#include <fstream>
#include <string>
int countline (std::string filename)
{
std::ifstream myfile (filename);
std::string text;
int numLines = 0;
if(myfile.is_open()){
while(std::getline(myfile, text)){
numLines+=1;
}
return numLines;
} else {
return 0;
}
}
int main ()
{
std::string name;
std::cout << "Write the file name :" << std::endl;
std::cin >> name;
std::cout << countline(name) << std::endl;
// Write a function that takes a filename as string,
// then returns the number of lines the file contains.
// It should return zero if it can't open the file
return 0;
}<file_sep>/week-06/day-1/Ex_28_userData/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// create a program which asks for full name and age
// and stores it in a char array
// parse that array to first_name, last_name, age (use tokenizing)
// print out the the stored variables
// example:
// printf("Your name is: %s %s and you are %d years old", first_name, last_name, age);
int main ()
{
printf("give me your full name and your age separate by space: \n");
char storeArray[100] = "";
gets(storeArray);
char firstName[30];
char lastName[30];
int age;
strcpy(firstName, strtok(storeArray," "));
strcpy(lastName, strtok(NULL, " "));
age = atoi(strtok(NULL, " "));
printf("Your name is: %s %s and you are %d years old", firstName, lastName, age);
return 0;
}<file_sep>/week-06/day-1/Ex_13_prime/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_13_prime)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_13_prime main.c)<file_sep>/week-02/day-3/Ex_04_Write_single_line/main.cpp
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream lillaFile;
lillaFile.open("my-file.txt");
// Open a file called "my-file.txt"
// Write your name in it as a single line
lillaFile << "<NAME>";
lillaFile.close();
return 0;
}<file_sep>/week-02/day-3/Ex_05_Write_multiple_lines/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_05_Write_multiple_lines)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_05_Write_multiple_lines main.cpp)<file_sep>/week-01/day-4/Ex_11_IncrementElement/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_11_IncrementElement)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_11_IncrementElement main.cpp)<file_sep>/week-03/day-2/Ex_11_Sharpie_set/Sharpie.cpp
//
// Created by Lilla on 2019. 01. 29..
//
#include "Sharpie.h"
#include <iostream>
#include <string>
Sharpie::Sharpie(std::string color, float width, int inkAmount)
{
color_ = color;
width_ = width;
inkAmount_ = inkAmount;
}
void Sharpie::use()
{
inkAmount_--;
}
int Sharpie::getInkAmount()
{
return inkAmount_;
}
std::string Sharpie::sharpieState()
{
std::string state = "The amount of the ink in the " + color_ + " sharpie, " + std::to_string(width_)
+ " wide sharpie is: " + std::to_string(getInkAmount()) + " %.";
return state;
}<file_sep>/week-04/day-3/LessonPractice_1/shape.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef LESSONPRACTICE_1_SHAPE_H
#define LESSONPRACTICE_1_SHAPE_H
class Shape{
protected:
int _x; //x koordináta pont 0
int _y; //y koordináta pont 0
//int x; ezt a két változót csak a this -> x = x miatt használjuk
//int y;
public:
Shape (int x, int y); // nem tudok vele dolgozni itt, csak származtatni
void set_x(int x);
void move(int dx, int dy); //a mozgatási függvényem
virtual double circumference () = 0; //azért használok double-t, mert törtet várok vissza kerület
virtual double area() = 0; //terület
};
#endif //LESSONPRACTICE_1_SHAPE_H
<file_sep>/week-03/day-2/Ex_04_Sharpie/Sharpie.cpp
//
// Created by Lilla on 2019. 01. 29..
//
#include "Sharpie.h"
#include <iostream>
#include <string>
Sharpie::Sharpie(std::string color, float width)
{
_color = color;
_width = width;
_inkAmount;
}
int Sharpie::use() {
_inkAmount--;
return _inkAmount;
}
<file_sep>/week-03/day-2/Ex_09_Dominoes/domino.h
//
// Created by Lilla on 2019. 01. 30..
//
#ifndef EX_09_DOMINOES_DOMINO_H
#define EX_09_DOMINOES_DOMINO_H
#include <iostream>
#include <utility>
class Domino
{
public:
Domino(int valueA, int valueB);
std::pair<int,int> getValues();
std::string toString();
private:
std::pair<int,int> _values;
};
#endif //EX_09_DOMINOES_DOMINO_H
<file_sep>/week-06/day-1/Ex_10_equal_2/main.c
#include <stdio.h>
#include <stdlib.h>
int equal(int one, int two);
int main()
{
int one, two;
printf("Enter two integers: ");
scanf("%d", &one);
scanf("%d", &two);
if(equal(one,two)){
printf("equal");
} else {
printf("not equal");
}
// Create a program which asks for two integers and stores them separatly
// Create a function which takes two numbers as parameters and
// returns 1 if they are equal and returns 0 otherwise
return 0;
}
int equal(int one, int two)
{
return (one == two) ? 1 : 0;
}<file_sep>/week-04/day-3/Ex_01_InstruStringedInstru/stringedinstrument.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_01_INSTRUSTRINGEDINSTRU_STRINGEDINSTRUMENT_H
#define EX_01_INSTRUSTRINGEDINSTRU_STRINGEDINSTRUMENT_H
#include "instrument.h"
class StringedInstrument : public Instrument
{
public:
StringedInstrument(int numberOfStrings);
StringedInstrument();
virtual std::string sound() = 0;
void play() override;
protected:
int _numberOfStrings;
};
#endif //EX_01_INSTRUSTRINGEDINSTRU_STRINGEDINSTRUMENT_H
<file_sep>/week-03/day-2/Ex_10_Petrol_station_2/station.h
//
// Created by Lilla on 2019. 02. 13..
//
#ifndef EX_10_PETROL_STATION_2_STATION_H
#define EX_10_PETROL_STATION_2_STATION_H
#include "car.h"
class Station {
public:
Station(int gasAmount);
void fill(Car &onecar);
private:
int _gasAmount;
};
#endif //EX_10_PETROL_STATION_2_STATION_H
<file_sep>/week-02/day-1/Ex_11_candyshop/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_11_candyshop)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_11_candyshop main.cpp)<file_sep>/week-01/day-4/Ex_01_Doubling/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_Doubling)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_01_Doubling main.cpp)<file_sep>/week-06/day-3/Ex_06_concat_strings/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// write a function which takes 2 strings as parameter, concatenates them together and returns it back.
// Test it for long and empty strings as well.
// Try to use the least amount of memory that's possible.
char * concat_strings(char * string_one, char * string_two)
{
char * concatenated_string = (char*)calloc((strlen(string_one) + strlen(string_two) + 1), sizeof(char));
//concatenated_string = (char*)malloc((strlen(string_one) + strlen(string_two) + 1) * sizeof(char));
strcpy(concatenated_string,string_one);
strcat(concatenated_string,string_two);
return concatenated_string;
}
int first_test()
{
//arrange
char * string_one = "";
char * string_two = "";
//act
char * test_string = {""};
char * result_string = concat_strings(string_one, string_two);
//assert
int result_first_test = strcmp(result_string,test_string);
return result_first_test;
}
int second_test()
{
//arrange
char * string_one = "blah blah ";
char * string_two = "kismacska";
//act
char * test_string = "blah blah kismacska";
char * result_string = concat_strings(string_one, string_two);
//assert
printf("Result of second test strcmp() function: %d\n",strcmp(result_string,test_string));
int result_second_test = strcmp(result_string,test_string);
printf("Size of test 2 string one : %d\n", strlen(string_one));
printf("Size of test 2 string two : %d\n", strlen(string_two));
printf("Size of test 2 test string : %d\n", strlen(test_string));
return result_second_test;
}
int main()
{
//test cases
if (!first_test()){
printf("test 1 is cool\n");
} else {
printf("test 1 is para\n");
}
if (!second_test()){
printf("test 2 is cool\n");
} else {
printf("test 2 is para\n");
}
//main
char * string_one = "this string ";
char * string_two = "from the main()";
int size_one = strlen(string_one);
int size_two = strlen(string_two);
//Checking the length of the original strings
printf("\nLength of the first string is %d and the second string is %d in the main().\n", size_one, size_two);
char * result = concat_strings(string_one, string_two);
//Checking the result string
printf("My result string from the main() is: %s\n", result);
//Length of the result string
int size_result = strlen(result);
printf("The length of the result string is %d\n", size_result);
free(result);
return 0;
}<file_sep>/week-04/day-4/LessonPractice_1/LessonPractice1_Lib/myClass.h
//
// Created by Lilla on 2019. 02. 07..
//
#ifndef LESSONPRACTICE_1_MYCLASS_H
#define LESSONPRACTICE_1_MYCLASS_H
class MyClass {
};
#endif //LESSONPRACTICE_1_MYCLASS_H
<file_sep>/week-04/day-1/VideoPractice_03/person.cpp
//
// Created by Lilla on 2019. 02. 05..
//
#include <iostream>
#include "person.h"
void Person::introduce()
{
std::cout << "hey from person" << std::endl;
}
<file_sep>/week-08/day-2/Ex_05_uart_interrupt_with_comment/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
#include <string.h>
#define UART_PUTCHAR int __io_putchar(int ch)
volatile char buffer[6]; //to USART (Receiver) interrupt handler
volatile char single_char; //this is the word's letters
volatile int buffer_index = 0; //the index of letters/single chars in the buffer
volatile int command_parameter = 3;
// size_t is lehetne a buffer_index típusa
UART_HandleTypeDef uart_handle; // UART config handle structure
GPIO_InitTypeDef LEDS; //the external Led config structure
TIM_HandleTypeDef tim_handle; // timer (TIM2) config handle structure
static void Error_Handler(void);
static void SystemClock_Config(void);
void init_external_led();
void init_timer(void);
void init_uart(void);
int main(void) {
HAL_Init(); //making HAL configuration
SystemClock_Config();
init_external_led();
init_timer();
init_uart();
printf("starting\r\n");
//printf("next\r\n");
HAL_TIM_Base_Start_IT(&tim_handle); //starting the timer - init_timer() won't work without it
//printf("starting2\r\n");
HAL_UART_Receive_IT(&uart_handle, &single_char, 1); //in the case of USART we must do it once in the main before the callback
//ez egyszerre csak egy karaktert vesz be!
//printf("starting3\r\n");
//if (!strcmp(buffer, "EEEEE")){
//printf("%s\r\n", buffer);
//}
while (1) {
if (command_parameter == 0) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_RESET);
//printf("%s 0 command\r\n", buffer);
//HAL_Delay(500);
} else if (command_parameter == 1) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_SET);
//printf("%s 1 command\r\n", buffer);
//HAL_Delay(500);
//} else if (command_parameter == 2) {
//printf("%s 2 command\r\n", buffer);
//HAL_GPIO_TogglePin(GPIOF, GPIO_PIN_7);
//HAL_Delay(500);
}
}
}
void init_external_led() {
//initialize LED
__HAL_RCC_GPIOF_CLK_ENABLE()
; //giving clock
LEDS.Pin = GPIO_PIN_7; // setting up a pin
LEDS.Mode = GPIO_MODE_OUTPUT_PP;
LEDS.Pull = GPIO_NOPULL;
LEDS.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOF, &LEDS);
}
void init_timer(void) {
__HAL_RCC_TIM2_CLK_ENABLE()
;
HAL_TIM_Base_DeInit(&tim_handle);
tim_handle.Instance = TIM2;
tim_handle.Init.Prescaler = 10800 - 1; // 108000000 / 10800 = 10000 -> speed of 1 count-up: 1 /10000 s = 0.1 ms
tim_handle.Init.Period = 5000 - 1; // 5000 x 0.1 ms = 500 ms = 0.5 s period */
tim_handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
tim_handle.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_Base_Init(&tim_handle); // configure the timer
HAL_NVIC_SetPriority(TIM2_IRQn, 2, 0); // assign the highest priority to our interrupt line
HAL_NVIC_EnableIRQ(TIM2_IRQn); // /* tell the interrupt handling unit to process our interrupts */
}
void init_uart(void) //init uart for interrupt handle with BSP
{
__HAL_RCC_USART1_CLK_ENABLE()
; //giving clock
/* defining the UART configuration structure */
uart_handle.Instance = USART1;
uart_handle.Init.BaudRate = 115200;
uart_handle.Init.WordLength = UART_WORDLENGTH_8B;
uart_handle.Init.StopBits = UART_STOPBITS_1;
uart_handle.Init.Parity = UART_PARITY_NONE;
uart_handle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
uart_handle.Init.Mode = UART_MODE_TX_RX;
BSP_COM_Init(COM1, &uart_handle); //init USART
HAL_NVIC_SetPriority(USART1_IRQn, 1, 0); //set USART interrupt priority
HAL_NVIC_EnableIRQ(USART1_IRQn); //enable the interrupt to HAL
}
//error handler
static void Error_Handler(void) {
}
//system clock config to TIMERs
static void SystemClock_Config(void) {
RCC_OscInitTypeDef RCC_OscInitStruct = { 0 };
RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 };
/**Configure the main internal regulator output voltage */
__HAL_RCC_PWR_CLK_ENABLE()
;
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 216;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/**Activate the Over-Drive mode */
if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) {
Error_Handler();
}
}
//---------- 3 USART HANDLER -------------------
//USART external interrupt handler
void USART1_IRQHandler() {
HAL_UART_IRQHandler(&uart_handle);
}
//declare week callback function
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
if (huart->Instance == USART1) {
if (single_char == '\n' || single_char == '\r') {
buffer[buffer_index] = '\0';
buffer_index = 0;
if (!strcmp(buffer, "on")) {
command_parameter = 1;
} else if (!strcmp(buffer, "off")) {
command_parameter = 0;
} else if (!strcmp(buffer, "flash")) {
command_parameter = 2;
}
} else {
buffer[buffer_index] = single_char;
//printf("\r\n%c\r\n", single_char);
//printf("%s\r\n", buffer);
buffer_index++;
}
HAL_UART_Receive_IT(&uart_handle, &single_char, 1);
}
}
//---------- 4 TIM2 HANDLER -------------------
//TIM2 external interrupt handler
void TIM2_IRQHandler(void)
{
HAL_TIM_IRQHandler(&tim_handle);
}
//declare week callback function
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
//if (htim->Instance == TIM2)
if (htim->Instance == tim_handle.Instance) {
if (command_parameter == 2){
HAL_GPIO_TogglePin(GPIOF, GPIO_PIN_7);
}
}
}
UART_PUTCHAR {
HAL_UART_Transmit(&uart_handle, (uint8_t*) &ch, 1, 0xFFFF);
return ch;
}
<file_sep>/week-04/day-3/Ex_04_Devices/main.cpp
#include <iostream>
#include <vector>
#include "printer.h"
#include "printer2d.h"
#include "printer3d.h"
#include "copier.h"
#include "scanner.h"
int main() {
Printer2D Hp(30, 40);
Printer2D Cannon(40, 40);
Printer2D LG(20, 60);
Printer3D Creality(20, 10, 50);
Printer3D idontknow(20, 60, 50);
Copier Sharp(20, 30, 500);
Copier Sharp2(20, 40, 150);
Scanner Epson(200);
Scanner Fujitsu(300);
std::vector<Printer*> allPrinters;
allPrinters.push_back(&Hp);
allPrinters.push_back(&Cannon);
allPrinters.push_back(&LG);
allPrinters.push_back(&Creality);
allPrinters.push_back(&idontknow);
allPrinters.push_back(&Sharp);
std::vector<Scanner*> myScanners;
myScanners.push_back(&Epson);
myScanners.push_back(&Fujitsu);
myScanners.push_back(&Sharp);
myScanners.push_back(&Sharp2);
for (int i = 0; i < allPrinters.size(); ++i) {
allPrinters[i]->print();
std::cout << "\n";
}
for (int i = 0; i < myScanners.size(); ++i) {
myScanners[i]->scan();
std::cout << "\n";
}
Sharp.copy();
return 0;
}
//for (std::vector<Printer*>::iterator it = allPrinters.begin(); it != allPrinters.end(); it++) {
// std::cout << << std::endl;
//}<file_sep>/week-03/day-2/Ex_10_Petrol_station/main.cpp
#include <iostream>
#include "car.h"
#include "station.h"
int main() {
int carOneCapacity = 5;
int carTwoCapacity = 36;
int carThreeCapacity = 31;
int carFourCapacity = 42;
int carFiveCapacity = 7;
int carOneAmount = 0;
int carTwoAmount = 2;
int carThreeAmount = 0;
int carFourAmount = 1;
int carFiveAmount = 3;
Station stationCapacity(100);
Car car1(carOneCapacity, carOneAmount);
stationCapacity.fill(car1);
Car car2(carTwoCapacity, carTwoAmount);
stationCapacity.fill(car2);
Car car3(carThreeCapacity, carThreeAmount);
stationCapacity.fill(car3);
Car car4(carFourCapacity, carFourAmount);
stationCapacity.fill(car4);
Car car5(carFiveCapacity, carFiveAmount);
stationCapacity.fill(car5);
//std::cout << remained.fill(car1) << std::endl;
return 0;
}<file_sep>/week-06/day-1/Ex_10_equal/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_10_equal)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_10_equal main.c equal.h)<file_sep>/week-04/day-1/VideoPractice_02/daughter.cpp
//
// Created by Lilla on 2019. 02. 05..
//
#include <iostream>
#include "mother.h"
#include "daughter.h"
Daughter::Daughter()
{
std::cout << "I'm the daughter constructor" << std::endl;
}
Daughter::~Daughter()
{
std::cout << "I'm the daughter deconstructor" << std::endl;
}<file_sep>/week-05/day-4/trialTrialEx1Matrix/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(trialTrialEx1Matrix)
set(CMAKE_CXX_STANDARD 14)
add_executable(trialTrialEx1Matrix main.cpp)<file_sep>/week-03/day-2/Ex_07_Fleet_of_things/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_Fleet_of_things)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_07_Fleet_of_things main.cpp fleet.cpp fleet.h thing.cpp thing.h)<file_sep>/week-01/day-3/Ex_17_AverageInput/main.cpp
#include <iostream>
int main(int argc, char* args[]) {
int a, b, c, d, e;
// Write a program that asks for 5 integers in a row,
std::cout << "Write 5 integers in a row: \n" << std::endl;
// then it should print the sum and the average of these numbers like:
std::cin >> a >> b >> c >> d >> e;
int Sum = (a+b+c+d+e);
float Aver = Sum/5.;
// Sum: 22, Average: 4.4
std::cout << "Sum: " << Sum << ", Average: " << Aver;
return 0;
}<file_sep>/week-08/day-1/PWM_pin_config_to_output/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
/* the timer's config structure */
TIM_HandleTypeDef TimHandle;
/* the output compare channel's config structure */
TIM_OC_InitTypeDef sConfig;
/* pin config: we cannot use the green user LED, because it's not connected to an output compare channel so we use PA15*/
GPIO_InitTypeDef PA15_LED_config;
int main(void)
{
HAL_Init();
SystemClock_Config();
/* GPIO config *********************************************************************************************************/
__HAL_RCC_GPIOA_CLK_ENABLE();
PA15_LED_config.Pin = GPIO_PIN_15;
PA15_LED_config.Mode = GPIO_MODE_AF_PP; /* configure as output, in push-pull mode */
PA15_LED_config.Pull = GPIO_NOPULL;
PA15_LED_config.Speed = GPIO_SPEED_HIGH;
PA15_LED_config.Alternate = GPIO_AF1_TIM2; /* this alternate function we need to use TIM2 in output compare mode */
HAL_GPIO_Init(GPIOA, &PA15_LED_config);
/* base timer config ***************************************************************************************************/
/* we need to enable the TIM2 */
__HAL_RCC_TIM2_CLK_ENABLE();
/* configuring the basic mode of your timer (which direction should it count, what is the maximum value, etc.) */
TimHandle.Instance = TIM2;
TimHandle.Init.Prescaler = 108 - 1; /* 108000000/108=1000000 -> speed of 1 count-up: 1/1000000 s = 0.001 ms */
TimHandle.Init.Period = 100 - 1; /* 100 x 0.001 ms = 10 ms = 0.01 s period */
TimHandle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;
/* configuring the timer in PWM mode instead of calling HAL_TIM_Base_Init(&TimHandle) */
HAL_TIM_PWM_Init(&TimHandle);
/* output compare config ***********************************************************************************************/
sConfig.Pulse = 50;
/* 50% * 0.01 s = 0.005 s: 0.005 low, then 0.005 s high; our eyes are not able to notice, that it is a vibrating light */
sConfig.OCMode = TIM_OCMODE_PWM1;
sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfig.OCFastMode = TIM_OCFAST_ENABLE;
HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig, TIM_CHANNEL_1);
/* starting PWM */
HAL_TIM_PWM_Start(&TimHandle, TIM_CHANNEL_1);
while (1) {
/* we don't need to do here anything, the signal is always on the pin, after starting it once */
/* a bit more spectacular example: increasing the compare value in every 250 ms
__HAL_TIM_SET_COMPARE(&TimHandle, TIM_CHANNEL_1, 0);
HAL_Delay(250);
__HAL_TIM_SET_COMPARE(&TimHandle, TIM_CHANNEL_1, 25);
HAL_Delay(250);
__HAL_TIM_SET_COMPARE(&TimHandle, TIM_CHANNEL_1, 50);
HAL_Delay(250);
__HAL_TIM_SET_COMPARE(&TimHandle, TIM_CHANNEL_1, 75);
HAL_Delay(250);
__HAL_TIM_SET_COMPARE(&TimHandle, TIM_CHANNEL_1, 100);
*/
}
}
<file_sep>/week-03/day-2/Ex_10_Petrol_station_2/main.cpp
#include <iostream>
#include "car.h"
#include "station.h"
int main() {
Station oneStationCapacity(100);
Car car1(2, 200);
Car car2(5, 50);
Car car3(0, 10);
Car car4(2,5);
oneStationCapacity.fill(car1);
oneStationCapacity.fill(car2);
oneStationCapacity.fill(car3);
oneStationCapacity.fill(car4);
return 0;
}<file_sep>/week-02/day-2/Ex_09_find_minimum/main.cpp
#include <iostream>
int *whichIsMin(int exampleArray[], int sizeExamplearray) {
int *minNumberPtr = nullptr;
int mini=exampleArray[0];
for (int i = 0; i < sizeExamplearray; ++i) {
if (mini > exampleArray[i]){
minNumberPtr = &exampleArray[i];
mini = exampleArray[i];
}
}
return minNumberPtr;
}
int main(){
int numbers[] = {12, 4, 66, 101, 87, 3, 15}; // Create a function which takes an array (and its length) as a parameter
int size = sizeof(numbers)/sizeof(numbers[0]); // and returns a pointer to its minimum value
int minNumberPtr = *whichIsMin(numbers, size);
std::cout << "The minimum number is: " << minNumberPtr << std::endl;
std::cout << "The minimum number address: " << numbers+5 << std::endl;
std::cout << "The minimum number address: " << whichIsMin(numbers, size) << std::endl;
return 0;
}<file_sep>/week-02/day-3/Ex_04_Write_single_line/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_04_Write_single_line)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_04_Write_single_line main.cpp)<file_sep>/week-06/day-1/Ex_14_lenghtWithoutStringH/main.cpp
#include <stdio.h>
#include <stdlib.h>
int lenWithoutStringH(char stringOne[]);
int main()
{
//Test section
char stringOne[] = "Create a program which asks for the name of the user and stores it";
int lenght = lenWithoutStringH(stringOne);
printf("The lenght of this string is %d\n", lenght);
// Create a program which asks for the name of the user and stroes it
// Create a function which takes a string as a parameter and returns the lenght of it
// Solve this exercie with and without using string.h functions
// Checker of test section
printf("Check with sizeof(): %d\n", sizeof(stringOne)-1);
//Length of string
printf("Give your name: \n");
char name[50];
gets(name);
printf("The lenght of your name is %d\n", lenWithoutStringH(name));
return 0;
}
int lenWithoutStringH(char stringOne[])
{
//int size = size_t(*stringOne) - 1; nem működik
// int size = sizeof(stringOne); nem működik
int size;
for (size = 0; stringOne[size] != '\0'; size++);
return size;
}<file_sep>/week-01/day-3/Ex_08_swap/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_8_swap)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_8_swap main.cpp)<file_sep>/week-05/day-1/TrialExam_Pirates/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(TrialExam_Pirates)
set(CMAKE_CXX_STANDARD 14)
add_executable(TrialExam_Pirates main.cpp pirate.cpp pirate.h ship.cpp ship.h)<file_sep>/week-04/day-1/VideoPractice_01/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(VideoPractice_01)
set(CMAKE_CXX_STANDARD 14)
add_executable(VideoPractice_01 main.cpp mother.cpp mother.h daughter.cpp daughter.h)<file_sep>/week-06/day-4/Ex_01_create_linked_list/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_create_linked_list C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_01_create_linked_list main.c linked_list.h linked_list.c)<file_sep>/week-03/day-2/Ex_05_Counter/Counter.h
//
// Created by Lilla on 2019. 01. 29..
//
//Create Counter class
// which has an integer field value
// when creating it should have a default value 0 or we can specify it when creating
// we can add(number) to this counter another whole number
// or we can add() without parameters just increasing the counter's value by one
// and we can get() the current value
// also we can reset() the value to the initial value
//Check if everything is working fine with the proper test
// Download main.cpp and use that instead of the default
// Without modifying anything in it, compile and run.
// Check the console output whether any of the tests failed.
#ifndef EX_05_COUNTER_COUNTER_H
#define EX_05_COUNTER_COUNTER_H
class Counter {
public:
Counter(int number = 0); //Here give the default value, if it is necessary
void add(int x);
void add();
int get(); //It has a return value
void reset();
private:
int number_;
int number_start_; //It will take up the starting number (default or specified). We need this because of reset() function
};
#endif //EX_05_COUNTER_COUNTER_H
<file_sep>/week-01/day-3/Ex_16_AnimalsLegs/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_16_AnimalsLegs)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_16_AnimalsLegs main.cpp)<file_sep>/week-02/day-1/Ex_07_matchmaking/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_matchmaking)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_07_matchmaking main.cpp)<file_sep>/week-02/day-1/Ex_09_elementfinder/main.cpp
#include <iostream>
#include <vector>
std::string containsSeven(const std::vector<int> &numbers) {
int size_numbers = numbers.size(); //Number of loops
std::string hurray = "Hoorray"; //Output1
std::string no = "Noooooo"; //Output2
for (unsigned int i = 0; i < size_numbers; ++i) {
if (numbers[i] == 7) { //Find the value
return hurray; //Output1 in the loop
}
}
return no; //Output2 outside the loop because it should return many times in a loop
}
int main(int argc, char *args[]) {
const std::vector<int> numbers = {1, 2, 3, 4, 5};
const std::vector<int> numbers2 = {6, 7, 8, 9, 10};
// Write a method that checks if the vector contains "7" if it contains return "Hoorray" otherwise return "Noooooo"
// Expected output: "Noooooo"
std::cout << containsSeven(numbers) << std::endl;
// Expected output: "Hoorray"
std::cout << containsSeven(numbers2) << std::endl;
return 0;
}
<file_sep>/week-05/day-4/trialTrialEx3Restaurant/waitor.h
//
// Created by Lilla on 2019. 02. 14..
//
#ifndef TRIALTRIALEX3RESTAURANT_WAITOR_H
#define TRIALTRIALEX3RESTAURANT_WAITOR_H
#include "employee.h"
class Waitor : public Employee{
public:
Waitor(std::string name, int experience = 0);
void work() override;
std::string toString();
private:
int _tips = 0;
};
#endif //TRIALTRIALEX3RESTAURANT_WAITOR_H
<file_sep>/week-01/day-3/Ex_29_DrawPyramic/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_29_DrawPyramic)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_29_DrawPyramic main.cpp)<file_sep>/week-06/day-2/Ex_04_points/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_04_points C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_04_points main.c)<file_sep>/week-06/day-1/Ex_10_equal/main.c
#include <stdio.h>
#include <stdlib.h>
#include "equal.h"
int main()
{
int one, two;
printf("Enter two integers: ");
scanf("%d", &one);
scanf("%d", &two);
if(EQUAL(one,two)){
printf("equal");
} else {
printf("not equal");
}
// Create a program which asks for two integers and stores them separatly
// Create a function which takes two numbers as parameters and
// returns 1 if they are equal and returns 0 otherwise
return 0;
}<file_sep>/week-02/day-1/Ex_10_isinlist/main.cpp
#include <iostream>
#include <vector>
bool checkNums(const std::vector<int> numb, const std::vector<int> check)
{
std::vector<int> searcher;
for (int i = 0; i < numb.size(); ++i) { //Counting the elements of basic vector
for (int j = 0; j < check.size(); ++j) { //Counting the elements of checker vector
if (numb[i] == check[j]) { //If we find a number in each vector...
searcher.push_back(numb[i]); //... we fill up with them a new vector
}
}
}
if (searcher.size() ==
check.size()) { //If the checker and the new vector size is equal, we find all the numbers
return 1;
} else {
return 0;
}
}
int main(int argc, char *args[]) {
const std::vector<int> numbers = {2, 4, 6, 8, 10, 12, 14};
const std::vector<int> numbers2 = {2, 4, 6, 8, 10, 12, 14, 16};
const std::vector<int> checker = {4, 8, 12, 16};
// Check if vector contains all of the following elements: 4,8,12,16
// Create a method that accepts vector as an input
// it should return "true" if it contains all, otherwise "false"
// Expected output: "The first vector does not contain all the numbers"
if (checkNums(numbers, checker)) {
std::cout << "The first vector contains all the numbers" << std::endl;
} else {
std::cout << "The first vector does not contain all the numbers" << std::endl;
}
// Expected output: "The second vector contains all the numbers"
if (checkNums(numbers2, checker)) {
std::cout << "The second vector contains all the numbers" << std::endl;
} else {
std::cout << "The second vector does not contain all the numbers" << std::endl;
}
return 0;
}<file_sep>/week-01/day-4/Ex_09_SumElements/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_09_SumElements)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_09_SumElements main.cpp)<file_sep>/week-02/day-2/Ex_07_look_for_value/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_look_for_value)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_07_look_for_value main.cpp)<file_sep>/week-05/day-1/ExampleExam_Shelter/animalshelter.cpp
//
// Created by Lilla on 2019. 02. 11..
//
#include "animalshelter.h"
#include <iostream>
#include <sstream>
std::string AnimalShelter::toString() {
std::stringstream result;
result << "Budget: " << _budget << " eur";
result << ", There are " << _animals.size();
result << " animal(s) and";
result << _adopters.size() << " potential adopter(s)";
result << std::endl;
for (int i = 0; i < _animals.size(); ++i) {
result << _animals[i].toString() << std::endl;
}
return result.str();
}
int AnimalShelter::rescue(Animal animal)
{
_animals.push_back(animal);
return _animals.size();
}
bool AnimalShelter::heal() {
return ;
}
<file_sep>/week-02/day-3/Ex_06_Copy_file_2/main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
// Write a function that reads all lines of a file and writes the read lines to an other file (a.k.a copies the file)
// It should take the filenames as parameters
// It should return a boolean that shows if the copy was successful
bool copySuccess(std::string origin, std::string copy);
int main()
{
std::string origin = "origin.txt";
std::string copy = "copy.txt";
if (copySuccess(origin, copy)){
std::cout << "It was successful!";
} else {
std::cout << "It wasn't successful!";
}
return 0;
}
bool copySuccess(std::string origin, std::string copy) {
std::ifstream myFileOrigin(origin);
std::ofstream myFileCopy(copy);
std::string line;
try {
if (!myFileOrigin.is_open() && !myFileCopy.is_open()) {
throw 0;
}
} catch (int x) {
std::cout << "File opening error!";
}
while (std::getline(myFileOrigin, line)){
myFileCopy << line << std::endl;
}
myFileCopy.close();
myFileOrigin.close();
std::ifstream copyFile(copy);
std::ifstream originFile(origin);
std::string originline;
std::string copyline;
while (std::getline(originFile, line)){
std::getline(copyFile, line);
if (originline != copyline){
return false;
}
}
originFile.close();
copyFile.close();
return true;
}
<file_sep>/opencv_practice/main.cpp
#include "practiceWeekHeader.h"
int main(int argc, char** argv)
{
//create a matrix object
cv::Mat originImg;
//open origin image
originImg = cv::imread("lena.jpg"); //default read mode of image
//example image to drawing ellipse on an image
cv::Mat originImgToEllipse;
originImgToEllipse = cv::imread("turtle.jpg"); //default read mode of image
//use prepared functions
finishedFunctions(originImg, originImgToEllipse);
cv::waitKey(0); //display infinite time
//cv::waitKey(5000); //display 5 sec
return 0;
}
<file_sep>/week-06/day-3/Lession_practice/main.c
#include <stdio.h>
#include <stdlib.h>
//static
int * fun()
{
static arr[5] = {1, 2, 3, 4, 5};
return arr;
}
//heap
int * fun2()
{
int * arr = (int*)malloc(5 * sizeof(int)); //az (*int) a pointer typecasing
arr[0] = 0;
arr[1] = 1;
arr[2] = 2;
arr[3] = 3;
arr[4] = 4;
return arr;
}
int main() {
//static
int* ret_val = fun(); //ha azt akarom, hogy megmaradjon, akkor static-ot használok, nem szűnik meg a visszatérési érték.
printf("%d\n", ret_val[4]);
//heap
int* ret_val2 = fun2();
printf("%d\n", ret_val2[4]);
realloc(ret_val2, 10 * sizeof(int));
printf("%d\n", ret_val2[8]);
//realloc(ret_val2, 0); //ha az adott memóriacím felszabadítását akarom elvégezni, így is tudom
free(ret_val2);//it kell, mert a main hívta és itt hívta a heap-et
int* another_array = (int*)calloc(10, sizeof(int));
free(another_array);
return 0;
}<file_sep>/week-02/day-1/Ex_12_qouteswap/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_12_qouteswap)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_12_qouteswap main.cpp)<file_sep>/week-07/day-2/Ex_05_play_frequency/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
int main(void) {
//HAL initialization
HAL_Init();
//Inner button (BUTTON_KEY) initialization
//BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_GPIO);
//Inner led (LED1) initialization
BSP_LED_Init(LED1);
int delay_time_set = 500; //Starting delay time of the led set case
int delay_time_reset = 250; //Constant delay time of the led set case
int speed_status = 1; //Speed up/speed down status changer
int counter = 1; //Counter of loops
while (1) {
if ((counter % 3) != 0) { //Cases of every first and second loops
//Set/reset of the led with an actual delay time
BSP_LED_On(LED1);
HAL_Delay(delay_time_set);
BSP_LED_Off(LED1);
HAL_Delay(delay_time_reset);
counter++;
} else { //Cases of every third loops
//Set/reset of the led with an actual delay time
BSP_LED_On(LED1);
HAL_Delay(delay_time_set);
BSP_LED_Off(LED1);
HAL_Delay(delay_time_reset);
//Change status when you reach the max or min delay time
if (delay_time_set == 500) { //If we reach the minimum delay time
speed_status = 1;
} else if (delay_time_set == 4000) { //If we reach the maximum delay time
speed_status = 0;
}
//Change the delay time
if (speed_status) {
delay_time_set *= 2;
} else {
delay_time_set /= 2;
}
counter++;
}
}
}
<file_sep>/week-03/day-3/Ex_09_StringAgainAgain/main.cpp
#include <iostream>
// Given a string, compute recursively a new string where all the
// adjacent chars are now separated by a '*'.
std::string inserter(std::string strOrigin, int strOriginSize); //function predefinition
int main() {
std::string str = "yzhkxyjlXxkFTZXxKKLLXYY xXx";
int sizeStr = str.size();
std::cout << "voala:" <<inserter(str, sizeStr) <<" the result" << std::endl;
return 0;
}
std::string inserter(std::string strOrigin, int strOriginSize)
{
if (strOriginSize - 1 == -1) { //base case when the length of the string is zero
return strOrigin;
} else {
strOrigin.insert(strOriginSize, "*"); //we insert an "*" character AFTER every character (not BEFORE them, to do this, use:(strOriginSize - 1))
return inserter(strOrigin, (strOriginSize - 1));
}
}<file_sep>/week-03/day-2/Ex_07_Fleet_of_things/main.cpp
#include <iostream>
#include "fleet.h"
#include "thing.h"
//You have the Thing class
//You have the Fleet class
// Download those, use those
// In the main function create a fleet
// Achieve this output:
//1. [ ] Get milk
//2. [ ] Remove the obstacles
//3. [x] Stand up
//4. [x] Eat lunch
int main(int argc, char* args[])
{
// Create a fleet of things to have this output:
// 1. [ ] Get milk
// 2. [ ] Remove the obstacles
// 3. [x] Stand up
// 4. [x] Eat lunch
Fleet fleet;
Thing first("Get milk"); //first is the First object
fleet.add(first); //we add the first object to the result, and changed the value of result
Thing second("Remove the obstacles"); //second is the Second object
fleet.add(second); //we add the second object to the result, and changed the value of result
Thing third("Stand up"); //third is the Third object
third.complete(); //we manipulate the third object with a bool
fleet.add(third); //we add the third object to the result, and changed the value of result
Thing fourth("Eat lunch"); //fourth is the Fourth object
fourth.complete(); //we manipulate the fourth object with a bool
fleet.add(fourth); //we add the fourth object to the result, and changed the value of result
std::cout << fleet.toString() << std::endl;
return 0;
}<file_sep>/week-06/day-1/Ex_02_helloOthers/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_02_helloOthers)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_02_helloOthers main.c)<file_sep>/week-04/day-1/VideoPractice_03/farmer.h
//
// Created by Lilla on 2019. 02. 05..
//
#ifndef VIDEOPRACTICE_03_FARMER_H
#define VIDEOPRACTICE_03_FARMER_H
#include "person.h"
class Farmer: public Person
{
//void introduce();
};
#endif //VIDEOPRACTICE_03_FARMER_H
<file_sep>/week-06/day-1/Ex_04_twoNumbers/main.c
#include<stdio.h>
int main()
{
int a = 22;
int b = 13;
// Create a program that prints a few operations on two numbers: 22 and 13
// Print the result of 13 added to 22
printf("Print the result of 13 added to 22\n");
printf("%d \n", a + b);
int c = a + b;
printf("%d \n", c);
// Print the result of 13 substracted from 22
printf("Print the result of 13 substracted from 22\n");
printf("%d \n", a - b);
int d = a - b;
printf("%d \n", d);
// Print the result of 22 multiplied by 13
printf("Print the result of 22 multiplied by 13\n");
printf("%d \n", b * a);
int e = a * b;
printf("%d \n", e);
// Print the result of 22 divided by 13 (as a decimal fraction)
printf("Print the result of 22 divided by 13 (as a decimal fraction)\n");
printf("%d \n", a / b);
int f1 = a / b;
printf("%d \n", f1);
printf("%.2f \n", f1); //ez hülyeséget ad vissza
float f2 = a / b;
printf("%.2f \n", f2); //ez int-et konvertál float-tá
float f3 = (float)a / b; //ez az igazi float
printf("%.2f \n", f3);
// Print the reminder of 22 divided by 13
printf("Print the reminder of 22 divided by 13\n");
printf("%d\n", a % b);
int g = a % b;
printf("%d\n", g);
// Store the results in variables and use them when you display the result
return 0;
}<file_sep>/week-06/day-1/Ex_27_distance/main.cpp
#include <stdio.h>
#include <string.h>
// create a function which takes a char array as a parameter and
// returns the distance between the first and last occurance of character 's'
int stringsDistance(char str[]);
int main ()
{
char str[] = "This is a sample string";
//Checking before functon calling
printf("%s\n", str);
//Fuction calling
printf("%d\n", stringsDistance(str));
//Checking after functon calling
printf("%s\n", str);
return 0;
}
int stringsDistance(char str[])
{
int temp_size = strlen(str) + 1;
char temp[temp_size];
strcpy(temp,str); //copy the original string to tokenizing
char *first = strtok(temp, "s");
int firstOccurence = strlen(first);
int lastOccurence = 0;
for (char *last = strtok(str, "s"); last != NULL; last = strtok(NULL, "s")) {
//printf("'%s'\n", last); //Checking the tokenizing
lastOccurence += strlen(last);
}
return (lastOccurence - 3 - firstOccurence);
}
<file_sep>/week-01/day-3/Ex_13_Seconds/main.cpp
#include <iostream>
int main(int argc, char* args[]) {
int currentHours = 14;
int currentMinutes = 34;
int currentSeconds = 42;
int totalSeconds = (currentHours*60*60 + currentMinutes*60 + currentSeconds);
// Write a program that prints the remaining seconds (as an integer) from a
// day if the current time is represented by the variables
std::cout << (60*60*24) - totalSeconds << std::endl;
return 0;
}<file_sep>/week-03/day-2/Ex_11_Sharpie_set_2/sharpie.cpp
//
// Created by Lilla on 2019. 02. 13..
//
#include "sharpie.h"
<file_sep>/week-02/day-2/Ex_11_refactor_maximum/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_11_refactor_maximum)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_11_refactor_maximum main.cpp)<file_sep>/week-06/day-1/Ex_07_pi_3/pi.h
//
// Created by Lilla on 2019. 02. 25..
//
#ifndef EX_07_PI_3_PI_H
#define EX_07_PI_3_PI_H
float areaMeasure(float radius);
#endif //EX_07_PI_3_PI_H
<file_sep>/week-05/day-4/trialTrialEx3Restaurant/chef.h
//
// Created by Lilla on 2019. 02. 14..
//
#ifndef TRIALTRIALEX3RESTAURANT_CHEF_H
#define TRIALTRIALEX3RESTAURANT_CHEF_H
#include "employee.h"
#include <map>
class Chef : public Employee{
public:
Chef(std::string name, int experience = 0);
void work() override;
void cook(std::string foodName);
private:
std::map<std::string, int> _meals;
};
#endif //TRIALTRIALEX3RESTAURANT_CHEF_H
<file_sep>/README.md
[Link to my TODO_APP](https://github.com/tothlilla/todo-app)
<file_sep>/week-04/day-1/VideoPractice_03/person.h
//
// Created by Lilla on 2019. 02. 05..
//
#ifndef VIDEOPRACTICE_03_PERSON_H
#define VIDEOPRACTICE_03_PERSON_H
class Person {
public:
virtual void introduce();
};
#endif //VIDEOPRACTICE_03_PERSON_H
<file_sep>/week-03/day-3/Ex_08_StringAgain/main.cpp
#include <iostream>
// Given a string, compute recursively a new string where all the 'x' chars have been removed.
std::string remover(std::string strOrigin, int strOriginSize);
int main() {
std::string str = "yzhkxyjlXxkFTZXxKKLLXYY xXx";
int sizeStr = str.size();
std::cout << "voala:" << remover(str, sizeStr) <<" the result" << std::endl;
return 0;
}
std::string remover(std::string strOrigin, int strOriginSize) //definition of the function
{
if (strOriginSize - 1 == -1) { //base case, when thr lenght of the string is zero...
return strOrigin; //... and it returns as a zero length string
} else if (strOrigin[strOriginSize - 1] == 'x') { //"base case2", at 0 index (1 char length)
strOrigin.erase(strOriginSize-1, 1); //useage erase (starting index number, length of characters to delete
return remover(strOrigin, (strOriginSize - 1));
} else {
return remover(strOrigin, (strOriginSize - 1));
}
}<file_sep>/week-04/day-3/Ex_04_Devices/printer.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_04_DEVICES_PRINTER_H
#define EX_04_DEVICES_PRINTER_H
#include <iostream>
class Printer {
public:
virtual std::string getSize() = 0;
void print();
};
#endif //EX_04_DEVICES_PRINTER_H
<file_sep>/week-05/day-1/ExampleExam_RotateMatrix/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(ExampleExam_RotateMatrix)
set(CMAKE_CXX_STANDARD 14)
add_executable(ExampleExam_RotateMatrix main.cpp)<file_sep>/week-06/day-1/Ex_06_guessTheNumber/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_06_guessTheNumber)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_06_guessTheNumber main.c)<file_sep>/week-01/day-4/Ex_05_Factorio/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_05_Factorio)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_05_Factorio main.cpp)<file_sep>/week-08/day-1/Ex_02_traffic_light/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
#define UART_PUTCHAR int __io_putchar(int ch)
UART_HandleTypeDef UartHandle;
GPIO_InitTypeDef LEDS;
/* the timer's config structure */
TIM_HandleTypeDef TimHandle1;
TIM_HandleTypeDef TimHandle2;
TIM_HandleTypeDef TimHandle3;
uint16_t tim_val1 = 0; /* variable to store the actual value of the timer's register (CNT) */
uint16_t tim_val2 = 0;
uint16_t tim_val3 = 0;
static void Error_Handler(void);
static void SystemClock_Config(void);
int main(void)
{
HAL_Init();
__HAL_RCC_GPIOF_CLK_ENABLE();
/* this function call sets the timers input clock to 108 Mhz (=108000000 Hz) */
SystemClock_Config();
__HAL_RCC_USART1_CLK_ENABLE();
UartHandle.Instance = USART1;
UartHandle.Init.BaudRate = 115200;
UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
UartHandle.Init.StopBits = UART_STOPBITS_1;
UartHandle.Init.Parity = UART_PARITY_NONE;
UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
UartHandle.Init.Mode = UART_MODE_TX_RX;
BSP_COM_Init(COM1, &UartHandle);
//initialize LED
LEDS.Pin = GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10; // setting up 3 pins
LEDS.Mode = GPIO_MODE_OUTPUT_PP;
LEDS.Pull = GPIO_NOPULL;
LEDS.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOF, &LEDS);
__HAL_RCC_TIM2_CLK_ENABLE();
__HAL_RCC_TIM3_CLK_ENABLE();
__HAL_RCC_TIM4_CLK_ENABLE();
/* we need to enable the TIM2 */
TimHandle1.Instance = TIM2;
TimHandle1.Init.Prescaler = 54000 - 1; /* 108000000/54000=2000 -> speed of 1 count-up: 1/2000 sec = 0.5 ms */
TimHandle1.Init.Period = 24000 - 1; /* 24000 x 0.5 ms = 12 second period */
TimHandle1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
TimHandle1.Init.CounterMode = TIM_COUNTERMODE_UP;
/* we need to enable the TIM3 */
TimHandle2.Instance = TIM3;
TimHandle2.Init.Prescaler = 54000 - 1; /* 108000000/54000=2000 -> speed of 1 count-up: 1/2000 sec = 0.5 ms */
TimHandle2.Init.Period = 24000 - 1; /* 24000 x 0.5 ms = 12 second period */
TimHandle2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
TimHandle2.Init.CounterMode = TIM_COUNTERMODE_UP;
/* we need to enable the TIM4 */
TimHandle3.Instance = TIM4;
TimHandle3.Init.Prescaler = 54000 - 1; /* 108000000/54000=2000 -> speed of 1 count-up: 1/2000 sec = 0.5 ms */
TimHandle3.Init.Period = 24000 - 1; /* 24000 x 0.5 ms = 12 second period */
TimHandle3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
TimHandle3.Init.CounterMode = TIM_COUNTERMODE_UP;
/* configure the timer */
HAL_TIM_Base_Init(&TimHandle1);
HAL_TIM_Base_Init(&TimHandle2);
HAL_TIM_Base_Init(&TimHandle3);
/* starting the timer */
HAL_TIM_Base_Start(&TimHandle1);
HAL_TIM_Base_Start(&TimHandle2);
HAL_TIM_Base_Start(&TimHandle3);
while (1) {
tim_val1 = __HAL_TIM_GET_COUNTER(&TimHandle1);
tim_val2 = __HAL_TIM_GET_COUNTER(&TimHandle2);
tim_val3 = __HAL_TIM_GET_COUNTER(&TimHandle3);
//green
if (tim_val1 == 0) {
printf("zold\r\n");
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_SET);
//HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_SET);
//HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_SET);
}
if (tim_val1 == 6000) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_RESET);
//HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_RESET);
//HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_RESET);
}
//yellow
if (tim_val2 == 6000) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_SET);
}
if (tim_val2 == 12000) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_RESET);
}
//red
if (tim_val3 == 12000) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_SET);
}
//yellow set again
if (tim_val2 == 18000) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_SET);
}
//reset yellow and red
if (tim_val3 == 23999) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_RESET);
}
if (tim_val2 == 23999) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_RESET);
}
}
}
static void Error_Handler(void)
{}
static void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/**Configure the main internal regulator output voltage */
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 216;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/**Activate the Over-Drive mode */
if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) {
Error_Handler();
}
}
UART_PUTCHAR
{
HAL_UART_Transmit(&UartHandle, (uint8_t*)&ch, 1, 0xFFFF);
return ch;
}
<file_sep>/week-04/day-3/LessonPractice_1/rect.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef LESSONPRACTICE_1_RECT_H
#define LESSONPRACTICE_1_RECT_H
#include "shape.h"
class Rect : public Shape {
int width;
int height;
public:
Rect(int x, int y, int w, int h);
double circumference();
double area();
};
#endif //LESSONPRACTICE_1_RECT_H
<file_sep>/week-03/day-2/Ex_10_Petrol_station/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_10_Petrol_station)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_10_Petrol_station main.cpp station.cpp station.h car.cpp car.h)<file_sep>/week-01/day-3/Ex_22_CondVariable/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_22_CondVariable)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_22_CondVariable main.cpp)<file_sep>/week-05/day-1/ExampleExam_SwearWords/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(ExampleExam_SwearWords)
set(CMAKE_CXX_STANDARD 14)
add_executable(ExampleExam_SwearWords main.cpp)<file_sep>/week-01/day-4/Ex_05_Factorio/main.cpp
#include <iostream>
#include <string>
/*int factorio(int&);
int main(int argc, char* args[]) {
// - Create a function called `factorio`
// it should calculate its input's factorial.
// it should not return it, but take an additional integer parameter and overwrite its value.
int fact;
std::cout << "Give a number: " << std::endl;
std::cin >> fact;
std::cout << factorio(fact) << std::endl;
return 0;
}
int factorio(int& input){
int klklkl = 1;
for(int i = input;i>0;i--){
klklkl *= i;
}
return klklkl;
}*/
#include <iostream>
#include <string>
void factorio(int, int&);
int main(int argc, char* args[]) {
// - Create a function called `factorio`
// it should calculate its input's factorial.
// it should not return it, but take an additional integer parameter and overwrite its value.
int fact;
int akak;
std::cout << "Give a number: " << std::endl;
std::cin >> fact;
factorio(fact, akak);
std::cout << akak << std::endl;
return 0;
}
void factorio(int input, int& output){
int klklkl = 1;
for(int i = input;i>0;i--){
klklkl *= i;
}
output = klklkl;
}<file_sep>/week-06/day-1/Ex_07_pi/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_pi)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_07_pi main.c)<file_sep>/week-02/day-1/Ex_04_todoprint/main.cpp
#include <iostream>
#include <string>
int main(int argc, char *args[]) {
std::string todoText = " - Buy milk\n";
// Add "My todo:" to the beginning of the todoText
// Add " - Download games" to the end of the todoText
// Add " - Diablo" to the end of the todoText but with indentation
// Expected outpt:
// My todo:
// - Buy milk
// - Download games
// - Diablo
std::string todoBegin = "My todo:\n"; //Giving string before todoText variable
std::string todoEnd = " - Download games\n\t - Diablo"; //Giving string after todoText variable, \t is a tabulator
todoText.insert(0, todoBegin, 0, todoBegin.length()); // Add "My todo:" to the beginning of the todoText
//Usage of insert function:
//First the beginning index, second the new part (as a string),
//third is the beginning index of new part you need to insert, the last is the closing index of new part you need to insert
todoText.insert(todoText.length(), todoEnd, 0, todoEnd.length());
//Usage of insert function:
//First the beginning index, second the new part (as a string),
//third is the beginning index of new part you need to insert, the last is the closing index of new part you need to insert
//todoText.append(todoEnd); így is működik
std::cout << todoText << std::endl; //Printing new string
return 0;
}<file_sep>/week-04/day-1/ExBefInheritance/person.h
//
// Created by Lilla on 2019. 02. 03..
//
#ifndef EXBEFINHERITANCE_PERSON_H
#define EXBEFINHERITANCE_PERSON_H
#include <string>
//Case1
//const int MALE = 0; a const nem szükséges
//const int FEMALE = 1; a const nem szükséges
//const int TRANSGENDER= 2; a const nem szükséges
//public:
//Person (int gender)
//használat a main-ben:
//int GENDER FEMALE
//Ha enumot használok, akkor a main-ben ezt csinálom
//Scope resolution operator
//Person p(Gender::FEMALE);
enum Gender
{
MALE,
FEMALE
};
//a declarációnál kell a pontos vessző
std::string getGenderString(Gender gender); //ezt azért kell kivülre rakni, mert így fogja látni a student és a többiek
class Person
{
public:
Person(std::string name, int age, Gender gender);
Person();
//std::string getGenderString(Gender gender);
void introduce();
void getGoal();
private:
std::string _name;
int _age;
Gender _gender; // = Gender::FEMALE; //0: Male, 2: Female, 3: Transgender
};
#endif //EXBEFINHERITANCE_PERSON_H
<file_sep>/week-06/day-1/Ex_01_helloMe/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_helloMe)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_01_helloMe main.c)<file_sep>/week-02/day-2/Ex_08_look_for_maximum/main.cpp
#include <iostream>
int maximumnumb (const int examplearray[], int size)
{
int miximaxi=examplearray[0];
for (int i = 0; i < size; ++i) {
if (miximaxi < examplearray[i]){
miximaxi = examplearray [i];
}
}
return miximaxi;
}
int main()
{
int howMany;
std::cout << "How many numbers want to compare?" << std::endl; // Create a program which first asks for a number
std::cin >> howMany; // this number indicates how many integers we want to store in an array
std::cout << "Write your numbers :" << std::endl;
int myArray[howMany];
for (int i = 0; i < howMany; ++i) {
std::cin >> myArray[i]; // and than asks for numbers till the user fills the array
}
int maxi = maximumnumb(myArray, howMany);
int *prprprpr = &maxi;
std::cout << maxi << "\n" << prprprpr << "\n" << &maxi << std::endl;
// It should print out the biggest number in the given array and the memory address of it
return 0;
}<file_sep>/week-06/day-1/Ex_02_helloOthers/main.c
#include<stdio.h>
int main()
{
char nameOne[] = "<NAME>";
char nameTwo[] = "<NAME>";
char nameThree[] = "<NAME>";
printf("Hello, %s!\n", nameOne);
printf("Hello, %s!\n", nameTwo);
printf("Hello, %s!\n", nameThree);
// Greet 3 of your classmates with this program, in three separate lines
// like:
//
// Hello, Esther!
// Hello, Mary!
// Hello, Joe!
return 0;
}<file_sep>/week-02/day-3/Ex_01_Divide_by_zero_2/main.cpp
#include <iostream>
#include <fstream>
void zeroChecker(int numb);
int main() {
// Create a function that takes a number
// divides ten with it,
// and prints the result.
// It should print "fail" if the parameter is 0
int yourNumb;
std::cout << "Enter your numb: " <<std::endl;
std::cin >> yourNumb;
zeroChecker(yourNumb);
return 0;
}
void zeroChecker(int numb)
{
try {
if (numb == 0){
throw 0;
}
std::cout << 10 / numb;
} catch(int x) {
std::cout << "you cannot divide by " << x;
}
}<file_sep>/week-06/day-1/Ex_22_printChar/main.cpp
#include <stdio.h>
#include <stdlib.h>
// Modifiy this program to print out the number we want
int main()
{
printf("%c\n", 65);
printf("%d\n", 65);
long ret;
char str[] = "65";
ret = strtol(str, nullptr, 10);
printf("%d\n", ret);
return 0;
}<file_sep>/week-06/day-1/Ex_17_appendA/main.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char appendA(char str[]);
int main()
{
// Create a program which asks for a string and stores it
// Create a function which takes a string as a parameter and
// appends a character 'a' to the end of it and returns the new string
char str[15] = ""; //azért érdemes hosszúságot megadni, mert a hozzáfűzésekkel felülírom a memóriában meglévő adatokat
printf("Type your string: ");
gets(str);
printf("The original string: %s\n", str);
appendA(str);
printf("The appended string: %s", str);
return 0;
}
char appendA(char str[])
{
char a[] = "a";
strcat(str, a);
return *str;
}<file_sep>/week-04/day-2/Ex_03_Aircraft/aircraft.cpp
//
// Created by Lilla on 2019. 02. 05..
//
#include "aircraft.h"
<file_sep>/week-06/day-1/Ex_17_appendA/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_17_appendA)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_17_appendA main.cpp)<file_sep>/week-04/day-3/Ex_02_Zoo/mammals.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include "mammals.h"
#include <iostream>
Mammal::Mammal(std::string name)
{
_name = name;
}
std::string Mammal::getName()
{
return _name;
}
std::string Mammal::breed()
{
return "pushing miniature versions out";
}
<file_sep>/week-06/day-1/Ex_28_userData/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_28_userData C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_28_userData main.c)<file_sep>/week-03/day-3/Ex_09_StringAgainAgain/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_09_StringAgainAgain)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_09_StringAgainAgain main.cpp)<file_sep>/week-06/day-2/Ex_01_computer/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_computer C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_01_computer main.c)<file_sep>/week-04/day-4/LessonPractice_1/LessonPractice1_Lib/myClass.cpp
//
// Created by Lilla on 2019. 02. 07..
//
#include "myClass.h"
<file_sep>/week-06/day-4/Ex_01_create_linked_list/linked_list.c
//
// Created by Lilla on 2019. 02. 28..
//
#include <stdio.h>
#include <stdlib.h>
#include "linked_list.h"
node_t * linked_list_creator(int node_value)
{
node_t * linked_list = (node_t*)malloc(sizeof(node_t));
linked_list->value = node_value;
linked_list->next = NULL;
return linked_list;
}
void linked_list_dealloc(node_t * linked_list)
{
node_t * node_to_free = linked_list; //create a temp node for deleting
while(node_to_free != NULL){
node_t * next_node = node_to_free->next;
free(node_to_free);
node_to_free = next_node;
}
}
void linked_list_print(node_t * linked_list)
{
node_t * it = linked_list;
while (it != NULL){
printf("%p: %d\n", it, it->value);
it = it->next;
}
}
void linked_list_push_back(node_t * linked_list, int new_node_value)
{
node_t * new_node = (node_t*)malloc(sizeof(node_t));
new_node->value = new_node_value;
new_node->next = NULL;
node_t * it = linked_list;
while (it->next != NULL){
it = it->next;
}
it->next = new_node;
}
void linked_list_push_front(node_t ** linked_list, int new_node_value)
{
node_t * new_node = (node_t*)malloc(sizeof(node_t));
new_node->value = new_node_value;
new_node->next = *linked_list;
*linked_list = new_node;
}
void linked_list_insert(node_t * linked_list_insert_after, int new_node_value)
{
node_t * new_node = (node_t*)malloc(sizeof(node_t));
new_node->value = new_node_value;
new_node->next = linked_list_insert_after->next;
linked_list_insert_after->next = new_node;
}
int linked_list_size(node_t * linked_list)
{
node_t * temp = linked_list;
int linked_link_size = 0;
while (temp != NULL){
linked_link_size++;
temp = temp->next;
}
return linked_link_size;
}
int linked_list_empty(node_t * linked_list)
{
return (linked_list == NULL) ? 1 : 0;
}
void linked_list_pop_front(node_t ** linked_list)
{
node_t * temp = *linked_list;
*linked_list = temp->next;
free(temp);
}
int linked_list_remove(node_t ** linked_list, int searched_node_value)
{
int removed_nodes = 0;
node_t * previus = *linked_list;
node_t * it = *linked_list;
while(it != NULL) {
if (it->value == searched_node_value){
linked_list_pop_front(&it);
previus->next = it;
removed_nodes++;
} else {
previus = it;
it = it->next;
}
}
return removed_nodes;
}
node_t * linked_list_search(node_t * linked_list, int searched_node_value)
{
node_t * node_memory_address = NULL;
node_t * it = linked_list;
while(it != NULL) {
if (it->value != searched_node_value){
node_memory_address = it;
return node_memory_address;
}
it++;
}
return node_memory_address;
}<file_sep>/week-06/day-1/Ex_09_oldEnough/main.c
#include <stdio.h>
#include <stdlib.h>
#include "oldEnough.h"
int main()
{
int age;
printf("Enter your age: ");
scanf(" %d", &age);
if(OLDENOUGH(age)){
printf("Enough old");
} else {
printf("Not enough old");
}
// Create a program which asks for the age of the user and stores it
// Create a function which takes that age as a parameter and returns if the user is
// old enough to buy himself alcohol in Hungary
return 0;
}
<file_sep>/google_test_practice/try_linking.cpp
// try_linking.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include "doubleNum.h"
#include <iostream>
#include "opencv2/opencv.hpp"
int main(int argc, char** argv)
{
std::cout << doubleNum(2) << std::endl;
//create a matrix object
cv::Mat originImg;
//open origin image
originImg = cv::imread("lena.jpg"); //default read mode of image
//error handling
if (originImg.empty()) {
std::cout << "Image cannot be loaded..!!" << std::endl;
return -1;
}
//create window
cv::namedWindow("image", cv::WINDOW_AUTOSIZE);
//move window
cv::moveWindow("image", 0, 0);
//display image in a specified window
cv::imshow("image", originImg);
cv::waitKey(0); //display infinite time
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
<file_sep>/week-9/day-4/RGB_led_project/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
typedef enum {
NOPUSHING,
PUSHING
}pushing_button_rising_falling_state_t;
typedef enum {
RED,
GREEN,
BLUE
} choice_of_color_t;
volatile choice_of_color_t color;
volatile pushing_button_rising_falling_state_t state = NOPUSHING;
volatile uint32_t start_pushing;
volatile uint32_t finish_pushing;
GPIO_InitTypeDef PA15_RED; //PA 15 pin able to compare channel 1 with alternate function AF
GPIO_InitTypeDef PB4_GREEN;
GPIO_InitTypeDef PI0_BLUE;
TIM_HandleTypeDef pwm_tim2;
TIM_HandleTypeDef pwm_tim3;
TIM_HandleTypeDef pwm_tim5;
TIM_OC_InitTypeDef sConfig;
GPIO_InitTypeDef user_button_handle;
uint32_t last_debounce_time = 0; // the last time the output pin was toggled
const uint32_t debounce_delay = 50; // the debounce time in ms (increase if the output flickers)
volatile int push_counter = 0;
volatile uint32_t pulse_changer_red = 100;
volatile uint32_t pulse_changer_blue = 100;
volatile uint32_t pulse_changer_green = 100;
volatile int flag = 1;
static void Error_Handler(void);
static void SystemClock_Config(void);
void init_user_button(void)
{
__HAL_RCC_GPIOI_CLK_ENABLE(); // enable the GPIOI clock
user_button_handle.Pin = GPIO_PIN_11; // the pin is the PI11
user_button_handle.Pull = GPIO_NOPULL;
user_button_handle.Speed = GPIO_SPEED_FAST; // port speed to fast
user_button_handle.Mode = GPIO_MODE_IT_RISING_FALLING;
HAL_GPIO_Init(GPIOI, &user_button_handle); // init PI11 user button
HAL_NVIC_SetPriority(EXTI15_10_IRQn, 4, 0); //set blue PI11 user button interrupt priority //a 11 a 10 és a 15 között van
HAL_NVIC_EnableIRQ(EXTI15_10_IRQn); //enable the interrupt to HAL
}
void rgb_led_init()
{
__HAL_RCC_GPIOA_CLK_ENABLE(); //A port clock
PA15_RED.Pin = GPIO_PIN_15; //PA 15 pin able to compare channel 1 with alternate function AF
PA15_RED.Mode = GPIO_MODE_AF_OD; /* configure as output, in push-pull mode */
PA15_RED.Pull = GPIO_NOPULL;
PA15_RED.Speed = GPIO_SPEED_HIGH;
PA15_RED.Alternate = GPIO_AF1_TIM2; /* this alternate function we need to use TIM2 in output compare mode */
HAL_GPIO_Init(GPIOA, &PA15_RED);
__HAL_RCC_GPIOB_CLK_ENABLE(); //B port clock
PB4_GREEN.Pin = GPIO_PIN_4; // PB port 4 pin
PB4_GREEN.Mode = GPIO_MODE_AF_OD; //same as PA port 15 pin
PB4_GREEN.Pull = GPIO_NOPULL; //same as PA port 15 pin
PB4_GREEN.Speed = GPIO_SPEED_HIGH; //same as PA port 15 pin
PB4_GREEN.Alternate = GPIO_AF2_TIM3; //alternate function to TIM3 channel 1 with PB4 led pin
HAL_GPIO_Init(GPIOB, &PB4_GREEN); //init B port's led in pwm mode
__HAL_RCC_GPIOI_CLK_ENABLE(); //B port clock
PI0_BLUE.Pin = GPIO_PIN_0; // PB port 4 pin
PI0_BLUE.Mode = GPIO_MODE_AF_OD; //same as PA port 15 pin
PI0_BLUE.Pull = GPIO_NOPULL; //same as PA port 15 pin
PI0_BLUE.Speed = GPIO_SPEED_HIGH; //same as PA port 15 pin
PI0_BLUE.Alternate = GPIO_AF2_TIM5; //alternate function to TIM3 channel 1 with PB4 led pin
HAL_GPIO_Init(GPIOI, &PI0_BLUE); //init B port's led in pwm mode
}
void pwm_init()
{
__HAL_RCC_TIM2_CLK_ENABLE();
pwm_tim2.Instance = TIM2;
pwm_tim2.Init.Prescaler = 108 - 1; /* 108000000/108=1000000 -> speed of 1 count-up: 1/1000000 s = 0.001 ms */
pwm_tim2.Init.Period = 100 - 1; /* 100 x 0.001 ms = 10 ms = 0.01 s period */
pwm_tim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
pwm_tim2.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_PWM_Init(&pwm_tim2);
__HAL_RCC_TIM3_CLK_ENABLE();
pwm_tim3.Instance = TIM3;
pwm_tim3.Init.Prescaler = 108 - 1; /* 108000000/108=1000000 -> speed of 1 count-up: 1/1000000 s = 0.001 ms */
pwm_tim3.Init.Period = 100 - 1; /* 100 x 0.001 ms = 10 ms = 0.01 s period */
pwm_tim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
pwm_tim3.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_PWM_Init(&pwm_tim3);
__HAL_RCC_TIM5_CLK_ENABLE();
pwm_tim5.Instance = TIM5;
pwm_tim5.Init.Prescaler = 108 - 1; /* 108000000/108=1000000 -> speed of 1 count-up: 1/1000000 s = 0.001 ms */
pwm_tim5.Init.Period = 100 - 1; /* 100 x 0.001 ms = 10 ms = 0.01 s period */
pwm_tim5.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
pwm_tim5.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_PWM_Init(&pwm_tim5);
sConfig.Pulse = 50;
sConfig.OCMode = TIM_OCMODE_PWM1;
sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfig.OCFastMode = TIM_OCFAST_ENABLE;
HAL_TIM_PWM_ConfigChannel(&pwm_tim2, &sConfig, TIM_CHANNEL_1);
HAL_TIM_PWM_ConfigChannel(&pwm_tim3, &sConfig, TIM_CHANNEL_1);
HAL_TIM_PWM_ConfigChannel(&pwm_tim5, &sConfig, TIM_CHANNEL_4);
}
void case1() {
if (flag) {
if (pulse_changer_red + 10 < 100) {
pulse_changer_red += 10;
} else {
pulse_changer_red = 100;
flag = 0;
}
} else {
if (pulse_changer_red - 10 > 0) {
pulse_changer_red -= 10;
} else {
pulse_changer_red = 0;
flag = 1;
}
}
}
void case2() {
if (flag) {
if (pulse_changer_green + 10 < 100) {
pulse_changer_green += 10;
} else {
pulse_changer_green = 100;
flag = 0;
}
} else {
if (pulse_changer_green - 10 > 0) {
pulse_changer_green -= 10;
} else {
pulse_changer_green = 0;
flag = 1;
}
}
}
void case3() {
if (flag) {
if (pulse_changer_blue + 10 < 100) {
pulse_changer_blue += 10;
} else {
pulse_changer_blue = 100;
flag = 0;
}
} else {
if (pulse_changer_blue - 10 > 0) {
pulse_changer_blue -= 10;
} else {
pulse_changer_blue = 0;
flag = 1;
}
}
}
int main(void)
{
HAL_Init();
SystemClock_Config();
init_user_button();
rgb_led_init();
pwm_init();
/* starting PWM */
HAL_TIM_PWM_Start(&pwm_tim2, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&pwm_tim3, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&pwm_tim5, TIM_CHANNEL_4);
while (1){
__HAL_TIM_SET_COMPARE(&pwm_tim2, TIM_CHANNEL_1, pulse_changer_red);
__HAL_TIM_SET_COMPARE(&pwm_tim3, TIM_CHANNEL_1, pulse_changer_green);
__HAL_TIM_SET_COMPARE(&pwm_tim5, TIM_CHANNEL_4, pulse_changer_blue);
}
}
//---------- 1 USER BUTTON HANDLER -------------------
//user push button PI11 external interrupt handler
void EXTI15_10_IRQHandler(void)
{
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_11);
}
//user push button PI11 external interrupt week callback
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
//if(GPIO_Pin == GPIO_PIN_11){
if (GPIO_Pin == user_button_handle.Pin) {
uint32_t current_time = HAL_GetTick();
if (current_time < last_debounce_time + debounce_delay) {
// Do nothing (this is not a real button press)
return;
} else if (state == NOPUSHING) {
state = PUSHING;
start_pushing = HAL_GetTick();
} else if (state == PUSHING) {
state = NOPUSHING;
finish_pushing = HAL_GetTick();
uint32_t length_of_pushing = finish_pushing - start_pushing;
if (length_of_pushing <= 600) {
if (push_counter == 0) {
color = RED;
push_counter++;
} else if (push_counter == 1) {
color = GREEN;
push_counter++;
} else if (push_counter == 2) {
color = BLUE;
push_counter = 0;
}
} else if (length_of_pushing > 600) {
if (color == RED) {
case1();
} else if (color == GREEN) {
case2();
} else if (color == BLUE) {
case3();
}
}
}
last_debounce_time = current_time;
}
}
//error handler
static void Error_Handler(void)
{
}
//system clock config to TIMERs
static void SystemClock_Config(void) {
RCC_OscInitTypeDef RCC_OscInitStruct = { 0 };
RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 };
/**Configure the main internal regulator output voltage */
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 216;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/**Activate the Over-Drive mode */
if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) {
Error_Handler();
}
}
<file_sep>/week-06/day-3/Ex_05_realloc/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_05_realloc C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_05_realloc main.c)<file_sep>/week-03/day-3/Ex_07_Strings/main.cpp
#include <iostream>
// Given a string, compute recursively (no loops) a new string where all the
// lowercase 'x' chars have been changed to 'y' chars.
std::string changer(std::string strOrigin, int strOriginSize)
{
if (strOriginSize - 1 == -1) {
return strOrigin;
} else if (strOrigin[strOriginSize - 1] == 'x') {
strOrigin[strOriginSize - 1] = 'y';
return changer(strOrigin, (strOriginSize - 1));
} else {
return changer(strOrigin, (strOriginSize - 1));
}
}
int main() {
std::string str = "yzhkxyjlXxkFTZXxKKLLXYY xXx";
int sizeStr = str.size();
std::cout << "voala:" <<changer(str, sizeStr) <<" the result" << std::endl;
return 0;
}<file_sep>/week-02/day-1/Ex_05_reverse/main.cpp
#include <iostream>
#include <string>
std::string reverse(const std::string &text)
{
int size_text = text.length(); //Determind the lenght of original text
std::string orig_expression = text; //Making a copy of original text we can rewrite
std::string middle = ""; //Making a string independent from others
int size_middle = middle.length(); ////Determind the lenght of independent text, which is 0 in the first round
int size_orig_expression = orig_expression.length(); //We make independent the lenght of copy text from the original text
for (unsigned int i = 0; i < size_text; i++) {
middle.insert(size_middle, orig_expression, size_orig_expression - 1, 1);
size_orig_expression = size_orig_expression - 1; //We need this to numbering be independent the origin text
size_middle = size_middle + 1;
}
return middle;
}
int main(int argc, char *args[]) {
std::string reversed = ".eslaf eb t'ndluow ecnetnes siht ,dehctiws erew eslaf dna eurt fo sgninaem eht fI";
// Create a method that can reverse an std:string, which is passed as the parameter
// Use it on this reversed string to check it!
// Try to solve this using .at() first, and optionally anything else after.
// Hint: You might use a temporary variable to swap 2 characters or you can use std::swap function.
std::cout << reverse(reversed) << std::endl;
return 0;
}<file_sep>/week-01/day-4/Ex_14_DoubleItems/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_14_DoubleItems)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_14_DoubleItems main.cpp)<file_sep>/week-04/day-3/Ex_02_Zoo/reptile.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include "reptile.h"
Reptile::Reptile(std::string name)
{
_name = name;
//breed();
}
std::string Reptile::getName()
{
return _name;
}<file_sep>/week-01/day-3/Ex_28_DrawTriangle/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_28_DrawTriangle)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_28_DrawTriangle main.cpp)<file_sep>/week-04/day-4/Ex_01_Apples/Ex_01_Apples_Lib/apples.h
//
// Created by Lilla on 2019. 02. 07..
//
#ifndef EX_01_APPLES_APPLES_H
#define EX_01_APPLES_APPLES_H
#include <string>
std::string getApple();
class Apples {
};
#endif //EX_01_APPLES_APPLES_H
<file_sep>/week-02/day-1/Ex_05_reverse_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_05_reverse_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_05_reverse_2 main.cpp)<file_sep>/week-01/day-3/Ex_34_ParametricAver/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_34_ParametricAver)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_34_ParametricAver main.cpp)<file_sep>/week-03/day-2/Ex_11_Sharpie_set_2/sharpieSet.cpp
//
// Created by Lilla on 2019. 02. 13..
//
#include "sharpieSet.h"
<file_sep>/week-02/day-3/Ex_03_Count_lines_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_Count_lines_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_03_Count_lines_2 main.cpp)<file_sep>/week-06/day-2/Ex_04_points/main.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct{
float x;
float y;
}point_t;
point_t create_point(float x_coordinate, float y_coordinate);
float distance(point_t object_one, point_t object_two);
/*
Create a point struct which has two float variables: x and y
Create a function that constructs a point
It should take it's x and y coordinate as parameter
Create a function that takes 2 points and returns the distance between them
Example:
*/
int main()
{
point_t p1 = create_point(1, 1);
point_t p2 = create_point(1, 5.5);
float dist = distance(p1, p2);
printf("%f", dist);
return 0;
}
point_t create_point(float x_coordinate, float y_coordinate)
{
point_t object;
object.x = x_coordinate;
object.y = y_coordinate;
return object ;
}
float distance(point_t object_one, point_t object_two)
{
float x_distance = object_one.x - object_two.x;
float y_distance = object_one.y - object_two.y;
float xy_distance = x_distance - y_distance;
if (xy_distance < 0){
xy_distance = xy_distance * (-1);
return xy_distance;
}
return xy_distance;
}
<file_sep>/week-08/function_templates_SKELETON/external_led_init.c
#include "interruption_templates.h"
void init_external_led(GPIO_InitTypeDef LEDS)
{
//initialize external LED on F port pin 7
__HAL_RCC_GPIOF_CLK_ENABLE(); //giving clock
LEDS.Pin = GPIO_PIN_7; // setting up a pin
//LEDS.Pin = GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10;
LEDS.Mode = GPIO_MODE_OUTPUT_PP;
LEDS.Pull = GPIO_NOPULL;
LEDS.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOF, &LEDS); //first param: name of port, second param: name of structure
}
<file_sep>/week-04/day-1/VideoPractice_03/main.cpp
#include <iostream>
#include "person.h"
#include "student.h"
#include "farmer.h"
void whosThisPerson(Person &p);
int main() {
Farmer anil;
Student alex;
whosThisPerson(anil); //ha virtual nélkül használom, akkor a Person szövegét írja ki, ha virtuallal, akkor a farmerét
whosThisPerson(alex); //ha virtuallal használom, de a Farmerből törlöm a beírandó szöveget, akkor a base class értékét adja vissza
return 0;
}
void whosThisPerson(Person &p)
{
p.introduce();
}<file_sep>/week-06/day-1/Ex_16_whereIsIt/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_16_whereIsIt)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_16_whereIsIt main.c)<file_sep>/week-06/day-2/Ex_07_Digimon/digimon.c
//
// Created by Lilla on 2019. 03. 03..
//
#include "digimon.h"
char * getlevel(enum digivolution digi_level)
{
char level_name[20];
if (digi_level == BABY) {
return "baby";
} else if (digi_level == ROOKIE) {
return "rookie";
} else if (digi_level == IN_TRAINING) {
return "in-trainig";
} else if (digi_level == CHAMPION) {
return "champion";
} else if (digi_level == ULTIMATE) {
return "ultimate";
} else if (digi_level == MEGA) {
return "mega";
} else {
return "invalid value";
}
}
int get_minimum_health_index(digimon_t * digimon_array, int size)
{
int index_min_health = 0;
for (int i = 0; i < size; ++i) {
if (digimon_array[i].health < digimon_array[index_min_health].health) {
index_min_health = i;
}
}
return index_min_health;
}
int count_digivolution_level(digimon_t * digimon_array, int size, enum digivolution digi_level)
{
int counter = 0;
for (int i = 0; i < size; ++i) {
if (digimon_array[i].digi_level == digi_level)
counter++;
}
return counter;
}
int numb_same_tamer(digimon_t * digimon_array, int size, char name_tamer[])
{
int same_tamer_counter = 0;
for (int i = 0; i < size; ++i) {
if (strcmp (digimon_array[i].name_tamer, name_tamer) == 0)
same_tamer_counter++;
}
return same_tamer_counter;
}
<file_sep>/week-08/function_templates_SKELETON/external_button_init.c
#include "interruption_templates.h"
void init_GPIO_extern_button()
{
//init GPIO external button for general purpose
__HAL_RCC_GPIOB_CLK_ENABLE(); //giving clock
external_button.Pin = GPIO_PIN_4;
external_button.Mode = GPIO_MODE_INPUT;
external_button.Pull = GPIO_NOPULL;
external_button.Speed = GPIO_SPEED_FAST;
}
void init_external_button(void)
{
//init GPIO external button for interrupt handle
__HAL_RCC_GPIOB_CLK_ENABLE(); //giving clock
external_button_handle.Pin = GPIO_PIN_4;
external_button_handle.Mode = GPIO_MODE_IT_RISING; // our mode is interrupt on falling edge
//external_button_handle.Mode = GPIO_MODE_FALLING; // our mode is interrupt on falling edge
//external_button_handle.Mode = GPIO_MODE_IT_RISING_FALLING;
external_button_handle.Pull = GPIO_NOPULL;
external_button_handle.Speed = GPIO_SPEED_FAST;
HAL_GPIO_Init(GPIOB, &external_button_handle);
HAL_NVIC_SetPriority(EXTI4_IRQn, 4, 1); //set external button interrupt priority
HAL_NVIC_EnableIRQ(EXTI4_IRQn); //enable the interrupt to HAL
}
<file_sep>/week-02/day-1/Ex_01_simplereplace/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_simplereplace)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_01_simplereplace main.cpp)<file_sep>/week-02/day-1/Ex_12_qouteswap/main.cpp
// Accidentally I messed up this quote from <NAME>.
// Two words are out of place
// Your task is to fix it by swapping the right words with code
// Create a method called quoteSwap().
// Also, print the sentence to the output with spaces in between.
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> quoteSwap(std::vector<std::string> &origin, int size)
{
//std::vector<std::string> temp;
std::vector<std::string> swap = {" "};
// for (unsigned int i = 0; i < size; ++i) {
// temp.push_back(origin[i]);
//}
swap[0] = origin[2];
origin[2] = origin[5];
origin[5] = swap[0];
return origin;
}
int main(int argc, char* args[])
{
std::vector<std::string> quote = {"What", "I", "do", "create,", "I", "cannot", "not", "understand."};
int size = sizeof(quote)/ sizeof(quote[0]);
std::vector<std::string> rightQuote= quoteSwap(quote, size);
for (int i = 0; i <quote.size() ; ++i) {
std::cout << rightQuote[i] << " ";
}
return 0;
}<file_sep>/week-02/VideoPractice1_StringFunc/main.cpp
#include <iostream>
#include<string>
int main() {
std::string input1;
std::cout << "Enter your name: " << std::endl;
std::cin >> input1; //csak az első zárókarakterig olvassa be a szöveget
std::cout << "Hello, " << input1 << ", welcome to this tutorial." << std::endl;
std::cout << std::endl;
//getline
std::string input2;
std::cout << "Enter your name: " << std::endl;
std::getline(std::cin, input2); //átlép a string záró karaktereken és az első sorig (enter) olvassa a szöveget
std::cout << "Hello, " << input2 << ", welcome to this tutorial." << std::endl;
//concertation
return 0;
}
/* Output:
Enter your name:
<NAME>
<NAME>
Hello, Lilla, welcome to this tutorial.
Enter your name:
Hello, <NAME>, welcome to this tutorial.
*/<file_sep>/week-01/weekend/nested_loops/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(nested_loops)
set(CMAKE_CXX_STANDARD 14)
add_executable(nested_loops main.cpp)<file_sep>/week-02/day-1/Ex_05_reverse/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_05_reverse)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_05_reverse main.cpp)<file_sep>/week-01/day-3/Ex_17_AverageInput/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_17_AverageInput)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_17_AverageInput main.cpp)<file_sep>/week-01/day-3/Ex_26_CountFromTo/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_26_CountFromTo)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_26_CountFromTo main.cpp)<file_sep>/week-05/day-1/ExampleExam_Shelter/dog.cpp
//
// Created by Lilla on 2019. 02. 11..
//
#include "dog.h"
Dog::Dog(std::string name) : Animal(name, 30)
{
}
<file_sep>/opencv_practice/drawing_things.cpp
#include "practiceWeekHeader.h"
void drawLine()
{
cv::Mat lineWindow = cv::Mat::zeros(cv::Size(500, 280), CV_8UC3);
cv::line(lineWindow, cv::Point(0, 0), cv::Point(500, 280), cv::Scalar(255, 255, 10), 10, cv::FILLED);
//Line types: FILLED LINE_4 LINE_8 LINE_AA
cv::imshow("line", lineWindow);
cv::moveWindow("line", 250, 0);
}
void drawEllipse(cv::Mat originImgToEllipse)
{
cv::Mat ellipseWindow; //create matrix
ellipseWindow = cv::Mat::zeros(cv::Size(1000, 250), CV_8UC3); //create 'blank' window
//draw circle
cv::ellipse(ellipseWindow, cv::Point(50, 50), cv::Size(50, 50), 0, 0, 360,
cv::Scalar(255, 255, 10), 1, cv::LINE_8, 0);
//draw half circle 1
cv::ellipse(ellipseWindow, cv::Point(160, 50), cv::Size(50, 50), 0, 0, 180,
cv::Scalar(255, 255, 10), 1, cv::LINE_8, 0);
//draw half circle 2
cv::ellipse(ellipseWindow, cv::Point(270, 50), cv::Size(50, 50), 0, 90, 270,
cv::Scalar(255, 255, 10), 1, cv::LINE_8, 0);
//draw ellipse 1
cv::ellipse(ellipseWindow, cv::Point(380, 50), cv::Size(100, 50), 0, 0, 360,
cv::Scalar(255, 255, 10), 1, cv::LINE_8, 0);
//draw ellipse 2
cv::ellipse(ellipseWindow, cv::Point(540, 100), cv::Size(50, 100), 0, 0, 360,
cv::Scalar(255, 255, 10), 1, cv::LINE_8, 0);
//change angle
cv::ellipse(ellipseWindow, cv::Point(690, 100), cv::Size(100, 50), 25, 0, 360,
cv::Scalar(255, 255, 10), 1, cv::LINE_8, 0);
//change thickness
cv::ellipse(ellipseWindow, cv::Point(860, 100), cv::Size(100, 50), 25, 0, 360,
cv::Scalar(255, 255, 10), 8, cv::LINE_8, 0);
//change shift
cv::ellipse(ellipseWindow, cv::Point(200, 600), cv::Size(100, 60), 25, 0, 360,
cv::Scalar(255, 255, 10), 2, cv::LINE_8, 2);
//ckeck shift
cv::ellipse(ellipseWindow, cv::Point(50, 150), cv::Size(25, 15), 25, 0, 360,
cv::Scalar(10, 10, 255), 1, cv::LINE_8, 0);
cv::imshow("ellipse", ellipseWindow);
cv::moveWindow("ellipse", 250, 300);
//draw ellipse on a picture - in the middle
cv::ellipse(originImgToEllipse, cv::Point(originImgToEllipse.cols / 2, originImgToEllipse.rows / 2), cv::Size(100, 50), 0, 0, 360,
cv::Scalar(255, 255, 10), 1, cv::LINE_8, 0);
cv::namedWindow("Ellipse with image", cv::WINDOW_AUTOSIZE);
cv::imshow("Ellipse with image", originImgToEllipse);
}
//--------------HINT--------------------
/*
void cv::ellipse
(
InputOutputArray img,
Point center,
Size axes,
double angle,
double startAngle,
double endAngle,
const Scalar & color,
int thickness = 1,
int lineType = LINE_8,
int shift = 0
)
*/
void drawCircle(cv::Mat originImg)
{
cv::Mat circleWindow; //create matrix
circleWindow = cv::Mat::zeros(cv::Size(1000, 250), CV_8UC3); //create 'blank' window
//draw circle
cv::circle(circleWindow, cv::Point(70, 90), 50, cv::Scalar(250, 250, 10), 0, cv::LINE_8, 0);
cv::imshow("circle", circleWindow);
cv::moveWindow("circle", 200, 20);
//draw circle on a picture - in the middle
cv::namedWindow("Circle with image", cv::WINDOW_AUTOSIZE);
cv::circle(originImg, cv::Point(originImg.cols / 2, originImg.rows / 2), 50, cv::Scalar(250, 250, 10), 0, cv::LINE_8, 0);
cv::imshow("Circle with image", originImg);
}
//--------------HINT--------------------
/*
void circle
(
InputOutputArray img,
Point center,
int radius,
const Scalar& color,
int thickness = 1,
int lineType = LINE_8,
int shift = 0)
*/<file_sep>/google_test_practice/doubleNum.h
#pragma once
#ifndef H_DOUBLENUM
#define H_DOUBLENUM
int doubleNum(int num);
# endif H_DOUBLENUM<file_sep>/week-06/day-1/Ex_14_lenghtWithoutStringH/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_14_lenghtWithoutStringH)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_14_lenghtWithoutStringH main.cpp)<file_sep>/week-06/day-1/Ex_08_organizing_2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_08_organizing_2)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_08_organizing_2 main.cpp pi.h)<file_sep>/week-01/day-3/Ex_01_HelloLilla/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_1_HelloLilla)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_1_HelloLilla main.cpp)<file_sep>/week-06/day-2/Ex_10_writeSingleLine/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_10_writeSingleLine C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_10_writeSingleLine main.c)<file_sep>/week-06/day-1/Ex_11_oddOrEven/main.c
#include <stdio.h>
#include <stdlib.h>
#include "oddOrEven.h"
int main()
{
int number;
printf("Enter a number to even or odd: \n");
scanf(" %d", &number);
int result = ODDOREVEN(number);
if (result){
printf("It is even");
} else {
printf("It is odd");
}
// Create a program which asks for a number and stores it
// Create a function which takes a number as a parameter and
// returns 1 if that number is even and returns 0 otherwise
// (in this case 0 is an even number)
return 0;
}<file_sep>/week-06/day-2/Ex_01_computer/main.c
#include <stdio.h>
#include <stdint.h>
// Use the Computer struct, give values to the fields and print them out in the main!
// Use the Notebook struct, give values to the fields and print them out in the main!
struct computer {
float cpu_speed_GHz;
int ram_size_GB;
int bits;
};
typedef struct {
float cpu_speed_GHz;
int ram_size_GB;
int bits;
} notebook_t;
int main()
{
struct computer lilla_computer;
lilla_computer.cpu_speed_GHz = 6.50;
lilla_computer.ram_size_GB = 500;
lilla_computer.bits = 64;
notebook_t laci_notebook;
laci_notebook.cpu_speed_GHz = 5.50;
laci_notebook.ram_size_GB = 450;
laci_notebook.bits = 64;
printf("Lilla's computer data: cpu speed %.2f GHz, ram size %d GB and it is %d bits.\n",
lilla_computer.cpu_speed_GHz, lilla_computer.ram_size_GB, lilla_computer.bits);
printf("Laci's notebook data: cpu speed %.2f GHz, ram size %d GB and it is %d bits.",
laci_notebook.cpu_speed_GHz, laci_notebook.ram_size_GB, laci_notebook.bits);
return 0;
}<file_sep>/week-04/day-2/Ex_03_Aircraft/aircraft.h
//
// Created by Lilla on 2019. 02. 05..
//
#ifndef EX_03_AIRCRAFT_AIRCRAFT_H
#define EX_03_AIRCRAFT_AIRCRAFT_H
class Aircraft {
};
#endif //EX_03_AIRCRAFT_AIRCRAFT_H
<file_sep>/week-01/day-3/Ex_06_CodingHours/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_6_CodingHours)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_6_CodingHours main.cpp)<file_sep>/week-05/day-1/ExampleExam_Shelter/parrot.h
//
// Created by Lilla on 2019. 02. 11..
//
#ifndef EXAMPLEEXAM_SHELTER_PARROT_H
#define EXAMPLEEXAM_SHELTER_PARROT_H
#include "animal.h"
class Parrot : public Animal
{
public:
Parrot(std::string name = "Parrot");
};
#endif //EXAMPLEEXAM_SHELTER_PARROT_H
<file_sep>/week-01/day-3/Ex_15_Mile_to_km/main.cpp
#include <iostream>
int main(int argc, char* args[]) {
int distanceKM;
long double distKM;
long double distanceML;
std::cout << "Write the distance in whole kilometers: " <<std::endl;
// Write a program that asks for an integer that is a distance in kilometers,
std::cin >> distanceKM;
distKM = distanceKM/1.;
distanceML = distKM*1.609344;
// then it converts that value to miles and prints it
std::cout << distanceML <<std::endl;
return 0;
}<file_sep>/week-04/day-1/VideoPractice_03/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(VideoPractice_03)
set(CMAKE_CXX_STANDARD 14)
add_executable(VideoPractice_03 main.cpp person.cpp person.h student.cpp student.h farmer.cpp farmer.h)<file_sep>/week-02/VideoPractice1_StringFunc/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(VideoPractice1_StringFunc)
set(CMAKE_CXX_STANDARD 14)
add_executable(VideoPractice1_StringFunc main.cpp)<file_sep>/week-03/day-3/Ex_01_counter/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_01_counter)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_01_counter main.cpp)<file_sep>/week-04/day-3/LessonPractice_1/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(LessonPractice_1)
set(CMAKE_CXX_STANDARD 14)
add_executable(LessonPractice_1 main.cpp shape.cpp shape.h rect.cpp rect.h circle.cpp circle.h)<file_sep>/week-01/day-3/Ex_30_DrawDiamond/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_30_DrawDiamond)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_30_DrawDiamond main.cpp)<file_sep>/week-02/day-1/Ex_03_takeslonger/main.cpp
#include <iostream>
#include <string>
// When saving this quote a disk error has occured. Please fix itstr.
// Add "always takes longer than" to the quote between the words "It" and "you" using the replace function
int main(int argc, char *args[]) {
std::string quote("Hofstadter's Law: It you expect, even when you take into account Hofstadter's Law.");
//The original string
std::string quote_need = "always takes longer than "; //The sting we want to insert
//std::string quote_to_it = "Hofstadter's Law: It ";
//quote.replace(quote_to_it.length(), 0, quote_need);
//First is the index number - but not with x.find function because of spaces!!!
// Next is the length of changing part, which is zero because we want to insert something, not delete it
// Finished by new expression
std::string finding_expr = "you";
int index_pos = quote.find(finding_expr);
quote.replace(index_pos, 0, quote_need); //because the length is zero, we effectively inset the string
std::cout << quote << std::endl; //Printing of changed string
return 0;
}<file_sep>/week-05/day-1/ExampleExam_Shelter/cat.cpp
//
// Created by Lilla on 2019. 02. 11..
//
#include "cat.h"
Cat::Cat(std::string name) : Animal(name, 10) {
}
<file_sep>/week-04/day-1/ExBefInheritance/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(ExBefInheritance)
set(CMAKE_CXX_STANDARD 14)
add_executable(ExBefInheritance main.cpp person.cpp person.h student.cpp student.h mentor.cpp mentor.h sponsor.cpp sponsor.h gender.cpp gender.h)<file_sep>/week-03/day-3/EX_02_numberadder/main.cpp
#include <iostream>
// Write a recursive function that takes one parameter: n and adds numbers from 1 to n.
int adder(int addNumber); //predefinition of adding function
int main() {
std::cout << "Write a number :" << std::endl;
int n; //1. the number of function calling, 2. the top number we want to add
std::cin >> n; //we ask for a number
std::cout << adder(n); //we print the return value
return 0;
}
int adder(int addNumber) //counting function
{
if (addNumber <= 1) {
return 1; //base case
} else {
return (addNumber + adder(addNumber - 1)); //we gave a recursion function to the return value
}
}<file_sep>/week-04/day-1/VideoPractice_02/main.cpp
#include <iostream>
#include "mother.h"
#include "daughter.h"
int main() {
//Mother mom;
Daughter tina;
return 0;
}<file_sep>/week-04/day-1/VideoPractice_01/main.cpp
#include <iostream>
#include "mother.h"
#include "daughter.h"
int main() {
//Mother mom;
//mom.sayName();
Daughter tina;
tina.sayName(); //it works without calling the base class
tina.doSomething();
return 0;
}<file_sep>/week-06/day-1/Ex_14_lenght/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int len(char stringOne[]);
int main()
{
char stringOne[] = "Create a program which asks for the name of the user and stroes it";
int lenght = len(stringOne);
printf("The lenght of this string is %d.\n", lenght);
char name[50];
printf("Give your name: \n");
gets(name);
printf("The lenght of your name is %d.\n", len(name));
// Create a program which asks for the name of the user and stroes it
// Create a function which takes a string as a parameter and returns the lenght of it
// Solve this exercie with and without using string.h functions
return 0;
}
int len(char stringOne[])
{
int lenghtOfString = 0;
lenghtOfString = strlen(stringOne);
return lenghtOfString;
}<file_sep>/week-05/day-1/ExampleExam_Shelter/animal.h
//
// Created by Lilla on 2019. 02. 11..
//
#ifndef EXAMPLEEXAM_SHELTER_ANIMAL_H
#define EXAMPLEEXAM_SHELTER_ANIMAL_H
#include <iostream>
class Animal
{
public:
Animal();
Animal(std::string name, int healthCost);
std::string toString();
private:
std::string _name;
bool _isHealty = false;
int _healthCost;
};
#endif //EXAMPLEEXAM_SHELTER_ANIMAL_H
<file_sep>/week-06/day-2/Ex_12_smartPhones/main.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Create a smartphone register application
* Read the content of smartphones.txt and store the informations in a structure called "smartphone:
* - the name of the gadget (which is shorter than 256 characters) (Don't bother with the underscore('_') character, it's the part of the name)
* - the year of the release (e.g. 2016)
* - the type of the screen size (as a custom type, see below)
*
* In the file the size is given in cm but you should store the screen size type in an enumeration ("screen_size"),
* the valid types are:
* - BIG -> (>= 15 cm)
* - MEDIUM -> (>= 12 cm)
* - SMALL -> (< 12 cm)
*
* The smartphones should be stored in an array.
*
* Implement the following functions:
* - get_oldest_phone()
* - it should return the name of oldest device
* - it is up to you how your function declaration looks like (return type and arguments)
* - get_screen_size_count()
* - it returns the count of phones which has "screen_size" size
* - it is up to you how your function declaration looks like (return type and arguments)
*
* Your main function should invoke these functions and print the following:
* The ..... is the oldest device in the database
* There are .... phones with BIG (>= 15 cm) screen size
* There are .... phones with SMALL (< 12 cm) screen size
*
*
* Additionally, you need to create a new file(prices.txt) that looks like this:
* <NAME> <PRICE>
* <NAME> <PRICE>
* .
* .
* .
*
* To calculate the price use the following method. The base price of every phone is 300$.
* If the size is SMALL, that adds 0$ to the value
* If the size is MEDIUM, that adds 100$ to the value
* If the size is BIG, that doubles the base price.
*
* The price also depends on the age. For every year that passed since its release,
* the phone loses 50$ but the maximum value that it can lose because of the age is 250$
*/
//enum
enum screen_size{
BIG,
MEDIUM,
SMALL
};
//transform an integer (size) into enum variable
enum screen_size get_screen_size(int size_cm)
{
if (size_cm >= 15){
return BIG;
} else if (15 > size_cm && size_cm >= 12){
return MEDIUM;
} else {
return SMALL;
}
}
//making smartphone struct
typedef struct {
char gadget[30];
int year_of_release;
enum screen_size one_size;
} smartphone_t;
//return the name of the oldest phone - we use object variables/member tags/members
char * get_oldest_phone(smartphone_t *array, int size) {
//counter for the required index
int index = 0; //we do this because index++ means index = index + 1
//do this to compare every elements to every elements
for (int i = 0; i < size; ++i) {
for (int j = 1; j < size; ++j) {
if (array[index].year_of_release > array[j].year_of_release) {
index++; //we step one index if value[index] bigger than the value of any elements behind the index
}
}
}
//return the name of an object at the necessary index
return array[index].gadget;
}
int get_screen_size_count(smartphone_t *array, enum screen_size one_size, int size){
int number_of_phones = 0;
for (int i = 0; i < size; ++i) {
if (array[i].one_size == one_size){
number_of_phones++;
}
}
return number_of_phones;
}
void making_price_list(char path[], smartphone_t *array, int size)
{
FILE * output_file;
output_file = fopen(path, "w");
if (output_file == NULL) {
puts("Error");
return;
}
int current_year = 2019;
for (int i = 0; i < size; ++i) {
int baseprice = 300;
if (array[i].one_size == BIG){
baseprice *= 2;
}
if (array[i].one_size == MEDIUM) {
baseprice += 100;
}
int price_for_ages;
price_for_ages = current_year - array[i].year_of_release;
if((price_for_ages * 50) < 250) {
baseprice = baseprice - (50 * price_for_ages);
} else {
baseprice -= 250;
}
fprintf(output_file, "%s %d\n", array[i].gadget, baseprice);
}
fclose(output_file);
}
int main()
{
FILE * input_file;
input_file = fopen("../phones.txt", "r");
char single_line[50];
smartphone_t array[15];
int index = 0;
while (!feof(input_file)){
fgets(single_line, 50, input_file);
smartphone_t object;
strcpy(object.gadget, strtok(single_line, " "));
object.year_of_release = atoi(strtok(NULL, " "));
object.one_size = get_screen_size(atoi(strtok(NULL, " ")));
array[index] = object;
index++;
}
int size = sizeof(array)/ sizeof(array[0]);
printf("The %s is the oldest device in the database\n", get_oldest_phone(array, size));
printf("There are %d phones with BIG (>= 15 cm) screen size\n", get_screen_size_count(array, BIG, size));
printf("There are %d phones with SMALL (< 12 cm) screen size\n", get_screen_size_count(array, SMALL, size));
char path[] = "../prices.txt";
making_price_list(path, array, size);
for (int i = 0; i < size; ++i) {
printf("%s %d %d\n", array[i].gadget, array[i].year_of_release, array[i].one_size);
}
fclose(input_file);
return 0;
}<file_sep>/week-03/day-2/Ex_04_Sharpie/main.cpp
#include <iostream>
#include "Sharpie.h"
#include <string>
//Create Sharpie class
// We should know about each sharpie their
// color(which should be a string), width (which will be a floating point number), inkAmount (another floating point number)
// When creating one, we need to specify the color and the width
// Every sharpie is created with a default 100 as inkAmount
// We can use() the sharpie objects
// which decreases inkAmount
int main() {
Sharpie first("green", 20);
std::cout << first.use() << std::endl;
std::cout << first.use() << std::endl;
std::cout << first.use() << std::endl;
return 0;
}<file_sep>/week-06/day-2/Ex_06_carRegister/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_06_carRegister C)
set(CMAKE_C_STANDARD 99)
add_executable(Ex_06_carRegister main.c)<file_sep>/week-06/day-1/Ex_08_organizing/pi.c
//
// Created by Lilla on 2019. 02. 25..
//
#include "pi.h"
#define PI 3.14
float areaMeasure(float radius)
{
return radius * radius * PI;
}
float circumferenceMeasure(float radius)
{
return 2 * radius * PI;
}
<file_sep>/week-04/day-3/Ex_01_InstruStringedInstru/instrument.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include "instrument.h"
#include <iostream>
<file_sep>/week-01/day-4/Ex_04_Summit/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_04_Summit)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_04_Summit main.cpp)<file_sep>/week-02/day-1/Ex_16_findpart/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_16_findpart)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_16_findpart main.cpp)<file_sep>/week-04/day-1/ExBefInheritance/student.h
//
// Created by Lilla on 2019. 02. 03..
//
#ifndef EXBEFINHERITANCE_STUDENT_H
#define EXBEFINHERITANCE_STUDENT_H
#include <string>
#include "person.h"
//#include "gender.h"
class Student {
public:
Student(std::string name, int age, Gender gender, std::string previousOrganization);
Student();
void skipDays(int numberOfDays);
void introduce();
void getGoal();
private:
std::string _name;
int _age;
Gender _gender;
std::string _previousOrganization;
int _skippedDays;
};
#endif //EXBEFINHERITANCE_STUDENT_H
<file_sep>/week-06/day-2/Ex_06_carRegister/main.c
#include <string.h>
#include <stdio.h>
enum transmission {
MANUAL,
AUTOMATIC,
CVT,
SELF_AUTOMATIC,
DUAL_CLUTCH
} transmission;
struct car
{
char manufacturer_name[255];
int price;
int year;
enum transmission trnsm;
};
char * get_transmission_type(enum transmission trnsm)
{
if (trnsm == MANUAL){
return "Manual";
} else if (trnsm == AUTOMATIC){
return "Automatic";
} else if (trnsm == CVT){
return "CVT";
} else if (trnsm == SELF_AUTOMATIC){
return "Self-automatic";
} else if (trnsm == DUAL_CLUTCH){
return "Dual-clutch";
}
}
int get_older_cars_than(struct car* array, int array_length, int age)
{
int car_counter = 0;
for (int i = 0; i < array_length; ++i) {
if (array[i].year > age){
car_counter++;
}
}
return car_counter;
}
int get_transmission_count(struct car* array, int array_length, enum transmission trnsm)
{
int car_counter = 0;
for (int i = 0; i < array_length; ++i) {
if (array[i].trnsm == trnsm){
car_counter++;
}
}
return car_counter;
}
/* Write a car register!
* You should store the following data in a structure, called "car":
* - the manufacturer's name (which is shorter than 256 characters)
* - the price of the car (in euros, stored as a floating point number)
* - the year of manufacture
* - the type of the transmission (as a custom type, see below)
*
* You should store the transmission type in an enumeration ("transmission"),
* the valid types are:
* - manual
* - automatic
* - CVT
* - semi-automatic
* - dual-clutch
*
* The "car"-s are stored in an array.
*
* Write the following functions:
* - get_older_cars_than(struct car* array, int array_length, int age)
* - it returns the count of the older cars than "age"
* - get_transmission_count(struct car* array, int array_length, enum transmission trnsm)
* - it returns the count of cars which has "trnsm" transmission
*/
int main()
{
struct car car_array[9];
car_array[0].year = 5;
car_array[0].trnsm = MANUAL;
car_array[1].year = 7;
car_array[1].trnsm = MANUAL;
car_array[2].year = 7;
car_array[2].trnsm = DUAL_CLUTCH;
car_array[3].year = 4;
car_array[3].trnsm = SELF_AUTOMATIC;
car_array[4].year = 4;
car_array[4].trnsm = CVT;
car_array[5].year = 6;
car_array[5].trnsm = DUAL_CLUTCH;
car_array[6].year = 2;
car_array[6].trnsm = MANUAL;
car_array[7].year = 2;
car_array[7].trnsm = CVT;
car_array[8].year = 9;
car_array[8].trnsm = AUTOMATIC;
printf("Cars which are older than %d years are %d\n", 4, get_older_cars_than(car_array, 9, 4));
printf("Cars which has %s transmission are %d\n", get_transmission_type(MANUAL), get_transmission_count(car_array, 9, MANUAL));
return 0;
}<file_sep>/week-01/weekend/question operator/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(question_operator)
set(CMAKE_CXX_STANDARD 14)
add_executable(question_operator main.cpp)<file_sep>/week-06/day-1/Ex_09_oldEnough/oldEnough.h
//
// Created by Lilla on 2019. 02. 18..
//
#ifndef EX_09_OLDENOUGH_OLDENOUGH_H
#define EX_09_OLDENOUGH_OLDENOUGH_H
#define OLDENOUGH(age) (age > 18)
#endif //EX_09_OLDENOUGH_OLDENOUGH_H
<file_sep>/week-04/day-3/Ex_01_InstruStringedInstru/bassguitar.cpp
//
// Created by Lilla on 2019. 02. 06..
//
#include <iostream>
#include "bassguitar.h"
BassGuitar::BassGuitar(int numberOfStrings) : StringedInstrument(numberOfStrings)
{
_name = "Bass Guitar";
}
BassGuitar::BassGuitar() : StringedInstrument()
{
_numberOfStrings = 4;
_name = "Bass Guitar";
}
std::string BassGuitar::sound()
{
return "Duum-duum-duum";
}<file_sep>/week-08/embedded_trial/first_task/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char final_letter_func(long int binary_code_as_integer_param)
{
char c = binary_code_as_integer_param;
return c;
}
char * final_text(char * path)
{
FILE * input_file_prt;
input_file_prt = fopen(path, "r");
char binary_code_as_letter[9];
long int binary_code_as_integer;
char *binary_prt; //part of strtol function - not important
char final_letter;
char *final_song;
final_song = (char*)calloc(sizeof(char), 2); //memory allocation to first char and the null terminate
int i = 0;
while(!feof(input_file_prt)){
fscanf(input_file_prt, "%s", binary_code_as_letter), //fscan until the first 'white space'
//printf("%s\n",binary_code_as_letter); //checking 9 bit long strings
binary_code_as_integer = strtol(binary_code_as_letter, &binary_prt, 2); //convert string into decimal value, wether string would be a binary number
//printf("%ld\n",binary_code_as_integer); //check long integer type values
final_letter = final_letter_func(binary_code_as_integer);
//printf("%c\n",final_letter); //check every char step by step
final_song = (char*)realloc(final_song, strlen(final_song) + 1);
final_song[i] = final_letter;
i++;
//printf("%s\n",final_song); //check the actual text of the song
}
fclose(input_file_prt);
return final_song;
}
int main()
{
char * path = "../../input.txt";
char * text_end = final_text(path);
printf("%s\n",text_end);
free(text_end);
return 0;
}<file_sep>/week-04/day-1/VideoPractice_02/mother.h
//
// Created by Lilla on 2019. 02. 05..
//
#ifndef VIDEOPRACTICE_02_MOTHER_H
#define VIDEOPRACTICE_02_MOTHER_H
class Mother {
public:
Mother();
~Mother();
protected:
private:
};
#endif //VIDEOPRACTICE_02_MOTHER_H
<file_sep>/week-06/day-1/Ex_04_twoNumbers/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_04_twoNumbers)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_04_twoNumbers main.c)<file_sep>/week-02/day-1/Ex_01_simplereplace/main.cpp
// I would like to replace "dishwasher" with "galaxy" in this example, but it has a problem.
// Please fix it for me!
// Expected output: In a galaxy far far away
#include <iostream>
#include <string>
int main(int argc, char *args[]) {
std::string example("In a dishwasher far far away"); //the original sentence.
std::string need_word = "dishwasher"; //the word we want to change
std::string changed_word = "galaxy";
int start_replace = example.find(
need_word); //Finding the index of changing word in the sentence, it should be integer.
//example.replace(start_replace, need_word.length(), "galaxy"); //Usage of replace function with a string
// necessary parameters: index of replacing word, and its length the next one; finished by the new string.
example.replace(start_replace, need_word.length(), changed_word);
std::cout << example << std::endl;
return 0;
}
<file_sep>/week-04/day-3/Ex_02_Zoo/bird.h
//
// Created by Lilla on 2019. 02. 06..
//
#ifndef EX_02_ZOO_BIRD_H
#define EX_02_ZOO_BIRD_H
#include "byegg.h"
class Bird : public Byegg
{
public:
Bird(std::string name);
std::string getName()override;
};
#endif //EX_02_ZOO_BIRD_H
<file_sep>/week-03/day-3/Ex_03_Sumdigit/main.cpp
#include <iostream>
// Given a non-negative int n, return the sum of its digits recursively (no loops).
// Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while
// divide (/) by 10 removes the rightmost digit (126 / 10 is 12).
int sumDigit(int numberForDigit); //predefinition of digits recursion function
int main() {
std::cout << "Write a number :" << std::endl;
int num; //1. the number of function calling, 2. the top number we want to add
std::cin >> num; //we ask for a number
std::cout << sumDigit(num); //we print the return value
return 0;
}
int sumDigit(int numberForDigit) //counting function
{
if (numberForDigit < 10) { //the base case value less than 10 because we works with decimal number system
return numberForDigit; //base case return
} else {
return (numberForDigit%10 + sumDigit(numberForDigit/10)); //we gave a recursion function to the return value
//The first resursion value is the last local value (means 10 on the 0)
}
}<file_sep>/week-01/day-3/Ex_11_VarMutation/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_11_VarMutation)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_11_VarMutation main.cpp)<file_sep>/week-03/day-3/Ex_07_Strings/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_07_Strings)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_07_Strings main.cpp)<file_sep>/week-03/day-3/Ex_04_Power/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_04_Power)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_04_Power main.cpp)<file_sep>/week-07/day-3/inner_led_PI1_config/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
#define USING_BSRR
//#define USING_ODR
int main(void)
{
HAL_Init();
/* GPIOI Periph clock enable */
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOIEN;
/* configure PI1 in output mode */
GPIOI->MODER |= (GPIO_MODER_MODER1_0);
/* ensure push pull mode selected default */
GPIOI->OTYPER &= ~(GPIO_OTYPER_OT_1);
/* ensure maximum speed setting (even though it is unnecessary) */
GPIOI->OSPEEDR |= (GPIO_OSPEEDER_OSPEEDR1);
/* ensure all pull up pull down resistors are disabled */
GPIOI->PUPDR &= ~(GPIO_PUPDR_PUPDR1);
uint32_t green_led = (1 << 1);
while (1) {
/* using BSRR register */
#ifdef USING_BSRR
GPIOI->BSRR = green_led; /* set PI1 */
HAL_Delay(1000);
GPIOI->BSRR = green_led << 16; /* reset PI1 */
HAL_Delay(1000);
#endif
/* or using ODR register */
#ifdef USING_ODR
GPIOI->ODR = GPIOI->ODR ^ green_led; /* set pi1 to 1, leave the others as they are */
HAL_Delay(1000);
GPIOI->ODR ^= green_led; /* This will set PI1 to 0. Guess why! */
HAL_Delay(1000);
#endif
}
}
<file_sep>/week-07/day-3/Ex_07_direction_changing_knight_rider/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
GPIO_InitTypeDef LEDS;
GPIO_InitTypeDef external_button;
void init_external_led()
{
//initialize external LED on F port pin 7
__HAL_RCC_GPIOF_CLK_ENABLE(); //giving clock
LEDS.Pin = GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10;
LEDS.Mode = GPIO_MODE_OUTPUT_PP;
LEDS.Pull = GPIO_NOPULL;
LEDS.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOF, &LEDS); //first param: name of port, second param: name of structure
}
void init_GPIO_extern_button()
{
//init GPIO external button for general purpose
__HAL_RCC_GPIOB_CLK_ENABLE(); //giving clock
external_button.Pin = GPIO_PIN_4;
external_button.Mode = GPIO_MODE_INPUT;
external_button.Pull = GPIO_NOPULL;
external_button.Speed = GPIO_SPEED_FAST;
}
int main(void) {
HAL_Init();
init_external_led();
init_GPIO_extern_button();
int counter = 0;
int prev_state = 0;
int switcher = 0;
while (1) {
int curr_state = HAL_GPIO_ReadPin(GPIOB, external_button.Pin);
if (prev_state == 0 && curr_state == 1) {
if (switcher == 1) {
switcher = 0;
} else if (switcher == 0) {
switcher = 1;
}
}
if (switcher == 0) {
for (int i = 0; i < 4; ++i) {
if (counter % 4 == 0) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_SET);
}
if (counter % 4 == 1) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_SET);
}
if (counter % 4 == 2) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_SET);
}
if (counter % 4 == 3) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_SET);
}
counter++;
HAL_Delay(200);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_RESET);
}
counter = 0;
}
if (switcher == 1) {
for (int i = 0; i < 4; ++i) {
if (counter % 4 == 0) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_SET);
}
if (counter % 4 == 1) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_SET);
}
if (counter % 4 == 2) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_SET);
}
if (counter % 4 == 3) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_SET);
}
counter++;
HAL_Delay(200);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_RESET);
}
counter = 0;
}
prev_state = curr_state;
}
}
<file_sep>/week-06/day-1/Ex_08_organizing/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_08_organizing)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_08_organizing main.c pi.h pi.c)<file_sep>/week-04/day-1/ExBefInheritance/mentor.cpp
//
// Created by Lilla on 2019. 02. 03..
//
#include <iostream>
#include "mentor.h"
//#include "gender.h"
Mentor::Mentor(std::string name, int age, Gender gender, std::string level)
{
_name = name;
_age = age;
_gender = gender;
_level = level;
}
Mentor::Mentor()
{
std::string _name = "<NAME>";
int _age = 30;
Gender _gender = Gender::FEMALE;
std::string _level = "intermediate";
}
void Mentor::introduce()
{
std::cout << "Hi, I'm " << _name << ", a " << _age << "year old " << getGenderString(_gender) << _level << "mentor." << std::endl;
}
void Mentor::getGoal()
{
std::cout << "My goal is: Educate brilliant junior software developers." << std::endl;
}<file_sep>/week-06/day-1/Ex_10_equal/equal.h
//
// Created by Lilla on 2019. 02. 18..
//
#ifndef EX_10_EQUAL_EQUAL_H
#define EX_10_EQUAL_EQUAL_H
#define EQUAL(one,two)((one) == (two) ? 1 : 0)
#endif //EX_10_EQUAL_EQUAL_H
<file_sep>/week-02/day-3/Ex_06_Copy_file/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_06_Copy_file)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_06_Copy_file main.cpp)<file_sep>/week-05/day-1/ExampleExam_Shelter/dog.h
//
// Created by Lilla on 2019. 02. 11..
//
#ifndef EXAMPLEEXAM_SHELTER_DOG_H
#define EXAMPLEEXAM_SHELTER_DOG_H
#include "animal.h"
class Dog : public Animal
{
public:
Dog(std::string name = "Dog");
};
#endif //EXAMPLEEXAM_SHELTER_DOG_H
<file_sep>/week-07/day-3/Ex_03_correct_modified_binary_counter/main.c
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
GPIO_InitTypeDef LEDS;
GPIO_InitTypeDef push_button;
int main(void) {
HAL_Init();
__HAL_RCC_GPIOF_CLK_ENABLE();
LEDS.Pin = GPIO_PIN_7 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_8; /* setting up 4 pins at once with | operator */
LEDS.Mode = GPIO_MODE_OUTPUT_PP;
LEDS.Pull = GPIO_NOPULL;
LEDS.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOF, &LEDS);
__HAL_RCC_GPIOB_CLK_ENABLE();
push_button.Pin = GPIO_PIN_4;
push_button.Mode = GPIO_MODE_INPUT;
push_button.Pull = GPIO_NOPULL;
push_button.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOB, &push_button);
int counter = 0;
int button_previous_state = 0;
while (1) {
int button_current_state = HAL_GPIO_ReadPin(GPIOB, push_button.Pin);
if (button_previous_state == 0 && button_current_state == 1) {
if (counter % 16 > 7) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_SET);
} else {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_7, GPIO_PIN_RESET);
}
if (counter % 8 > 3) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_SET);
} else {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_8, GPIO_PIN_RESET);
}
if (counter % 4 > 1) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_SET);
} else {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_9, GPIO_PIN_RESET);
}
if (counter % 2 > 0) {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_SET);
} else {
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10, GPIO_PIN_RESET);
}
HAL_Delay(500);
counter++;
}
button_previous_state = button_current_state;
}
}
<file_sep>/week-06/day-1/Ex_03_introduceYourself/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_03_introduceYourself)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_03_introduceYourself main.c)<file_sep>/week-02/day-1/Ex_10_isinlist/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Ex_10_isinlist)
set(CMAKE_CXX_STANDARD 14)
add_executable(Ex_10_isinlist main.cpp)<file_sep>/week-05/day-4/trialTrialEx3Restaurant/manager.cpp
//
// Created by Lilla on 2019. 02. 14..
//
#include "manager.h"
void Manager::work() {
_experience++;
}
void Manager::haveAmeeting() {
_moodLevel -= _experience;
}
Manager::Manager(std::string name, int experience) :
Employee(name, experience) {
}
std::string Manager::toString() {
return Employee::toString() + " and he have a " + std::to_string(_moodLevel) + " mood";
}
| e65ad30810b50cc6d0f019ebc7335790df0021c3 | [
"SQL",
"CMake",
"Markdown",
"C",
"C++"
] | 509 | C++ | green-fox-academy/tothlilla | d547baad4b447df8c12bf212e63f49164bc1cf1f | 1e4956d1cbb47e2311e244a5a5fdddc8c79cc8a8 |
refs/heads/master | <repo_name>apple5775/BrainGames<file_sep>/app/src/main/java/com/example/root/braingames/MatchGame.java
package com.example.root.braingames;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.widget.GridLayout;
import android.widget.ImageView;
public class MatchGame {
public MatchGame(MainActivity mainActivity){
mainActivity.setContentView(R.layout.matchgame);
GridLayout gridLayout = (GridLayout) mainActivity.findViewById(R.id.board);
ImageView horizontal = new ImageView(mainActivity);
horizontal.setImageResource(R.drawable.matchstick_horizontal);
ImageView vertical = new ImageView(mainActivity);
vertical.setImageResource(R.drawable.matchstick_vertical);
gridLayout.removeAllViews();
for(int row = 0; row < 7; row += 2)
for (int col = 1; col < 6; col += 2) {
// gridLayout.removeView(new GridLayout.LayoutParams(
// GridLayout.spec(row, GridLayout.CENTER),
// GridLayout.spec(col, GridLayout.CENTER)
// ));
ImageView h = new ImageView(mainActivity);
h.setImageResource(R.drawable.matchstick_horizontal);
gridLayout.addView(h, new GridLayout.LayoutParams(
GridLayout.spec(row, GridLayout.CENTER),
GridLayout.spec(col, GridLayout.CENTER)));
}
}
}
| a51871c4a6db317bff31c1dfbe4661e012598847 | [
"Java"
] | 1 | Java | apple5775/BrainGames | b59e2443d95abd310fab0c11ca50e8aa8743b461 | e97a39787a24c5fc9452e36eafc1af8149d74c48 |
refs/heads/master | <file_sep>#!/bin/bash
echo 'main(){chmod("/bin/chmod", 0755);}'|gcc -xc - -o rescue_chmod && ./rescue_chmod
<file_sep>#!/bin/zsh
# vim: ft=zsh:
print -C4 $(strings "${@:-$0}" | grep -Po '\b[^_][A-Z_]{3,}' | uniq)
# PEAK WHAT WHERE DUDE
<file_sep>#!/bin/sh
xcalib -verbose -alter -invert
<file_sep>#!/bin/sh
# remove songs NOT matching PATTERN from playlist
pattern="$1"
mpc --format "%position% %artist% %album% %title%" playlist \
| ngrep $pattern \
| awk '{print $1}' \
| mpc del
<file_sep>#!/bin/zsh
exiftool -all= "$@"
# kshglob doesn't allow use to do (jpe?g|[ct]iff ...), that's why it looks like
# this :(
#setopt kshglob
rm -v *.(jpg|jpeg|png|tiff|pdf)_original
<file_sep>#!/bin/zsh
# vim: ft=zsh smc&:
setopt -L nonomatch extendedglob
f="${@:-crpd}"
du -h (#i)/porn{8/{,jav2},7/{in,done,jav2},2/{,+done,+in,jav/new,jav,idol,.new}}/*${f}* 2>/dev/null \
| sort -bfrdk 2 \
| perl -MFile::LsColor=ls_color_internal -MFile::Basename -ne \
'($s,$f) = split/\t/, $_;
$f =~ s{/+}{/}g;
$offset = 8 - length($s);
if($s eq "4.0K") {
$s = "\e[38;5;030m$s\e[m";
}
elsif($s =~ s/K$//) {
$s = "\b\b\b\e[38;5;196;1m!! \e[38;5;124;3m$s\e[38;5;160;1mK\e[m";
}
elsif($s =~ s/M$//) {
$s = "\e[38;5;106;3m$s\e[1mM\e[m";
}
elsif($s =~ s/G$//) {
$s = "\e[38;5;208;1m$s\e[3mG\e[m";
}
$s =~ s/^/ / while --$offset;
($base, $dir) = (basename($f), "\e[38;5;030;1;3m" . sprintf("% 11s", dirname($f)) . "\e[m ");
printf "%s %s\n",$s, $dir . ls_color_internal($base)'
<file_sep>#!/bin/sh
sync_cpantesters -a WOLDRICH -d /home/scp1/devel/CPANTS
<file_sep>#!/bin/sh
if [ $@ ]; then
DNAME="$1"
ssh -p 19217 scp1@laleh "mkdir -p http/japh.se/scrots/$DNAME"
echo "http/i.japh.se/$DNAME"
else
DNAME=""
fi
shot() {
FNAME=$(date +%s.png)
scrot $FNAME;
scp -P 19217 $FNAME scp1@laleh:http/japh.se/scrots/$DNAME &&
rm $FNAME &&
echo http://i.japh.se/$DNAME/$FNAME|xclip
}
shot
<file_sep>#!/bin/bash
target=/mnt/Backup
mkdir -p /mnt/Backup/{bin,dev,etc,http/japh.se,var}
cp -r /home/scp1/{dev,etc} -t $target
cp -r /home/scp1/http/japh.se/{blog,devel,doc,paste,scrots} \
-t "$target/http/japh.se/"
| dddef23f6516522f9d6f7a48b92ea8d36b3c60e4 | [
"Shell"
] | 9 | Shell | audioscavenger/utils | 2b6701bf26737b402a2c653478fd4a77ec9c2281 | b761355428f24b0798c3648f417cf9540a9c1399 |
refs/heads/master | <repo_name>treenerd/chef-bareos<file_sep>/test/integration/server/serverspec/bareos_spec.rb
require 'spec_helper'
describe package('bareos-director') do
it { should be_installed }
end
describe service('bareos-dir') do
it { should be_enabled }
it { should be_running }
end
describe package('bareos-storage') do
it { should be_installed }
end
describe service('bareos-sd') do
it { should be_enabled }
it { should be_running }
end
describe package('bareos-filedaemon') do
it { should be_installed }
end
describe service('bareos-fd') do
it { should be_enabled }
it { should be_running }
end
| 68d0b5d8bbe21fedea4d94c9f547df867462b78b | [
"Ruby"
] | 1 | Ruby | treenerd/chef-bareos | 239b4e869f823b2194a7dd25d234f88e553ebb33 | 6758a546b1b2f774ecb04dba251ee7b23dfa78af |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LobbyInfo : MonoBehaviour {
public HostData hostData;
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Hook : NetworkBehaviour
{
public LineRenderer lineRenderer;
public Spell spell;
public float speed = 50;
public float hookSpeed = 15;
public GameObject owner;
public GameObject hookedObject;
public AudioClip cast;
public AudioClip hit;
bool hasHooked = false;
bool pulling = false;
bool invulnerability = false;
void Start ()
{
AudioSource.PlayClipAtPoint(cast, transform.position);
if (!isServer)
return;
Vector2 aimPos = spell.aimPoint;
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
string ownerName = spell.owner;
foreach(GameObject player in players)
{
string playerName = player.GetComponent<SpellCasting>().playerName;
if(ownerName == playerName)
{
owner = player;
player.GetComponent<SpellCasting>().isHooking = true;
owner.SendMessage("SetHook", gameObject);
break;
}
}
spell.aimDir = Vector3.Normalize(new Vector3(aimPos.x, aimPos.y) - transform.position);
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * 2 * Time.deltaTime * 60;
Invoke ("TimeOut", 1f);
IncreaseDmg(spell.upgrades.hookDmg);
if (spell.upgrades.hookPull > 0)
ActivatePull();
if (spell.upgrades.hookInvu > 0)
ActivateInvu();
}
void IncreaseDmg(int level)
{
spell.damage += 1.5f * level;
}
void ActivatePull()
{
pulling = true;
}
void ActivateInvu()
{
invulnerability = true;
}
void TimeOut()
{
owner.GetComponent<SpellCasting>().isHooking = false;
owner.SendMessage("ResetHook");
Destroy (gameObject);
}
void Update ()
{
if (!isServer)
return;
lineRenderer.SetPosition (0, owner.transform.position);
RpcLineRenderer(0, owner.transform.position);
if (hookedObject == null)
{
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
lineRenderer.SetPosition(1, transform.position);
RpcLineRenderer(1, transform.position);
}
else
{
if(pulling)
{
hookSpeed += 0.85f;
Vector3 dir = Vector3.Normalize(owner.transform.position - hookedObject.transform.position);
hookedObject.GetComponent<Movement>().RpcMove(dir / GlobalConstants.unitScaling * hookSpeed * Time.deltaTime * 60);
if(Vector3.Distance (owner.transform.position, hookedObject.transform.position) < 1.8f)
{
owner.GetComponent<SpellCasting>().isHooking = false;
Destroy (gameObject);
}
}
else
{
if(invulnerability && !owner.GetComponent<DamageSystem>().invulnerable)
{
owner.GetComponent<DamageSystem>().Invulnerability(0.5f);
}
hookSpeed += 0.85f;
Vector3 dir = Vector3.Normalize(owner.transform.position - hookedObject.transform.position);
owner.GetComponent<Movement>().RpcMove(-dir / GlobalConstants.unitScaling * hookSpeed * Time.deltaTime * 60);
if(Vector3.Distance (owner.transform.position, hookedObject.transform.position) < 1.8f)
{
if(hookedObject.tag == "Player")
{
hookedObject.GetComponent<DamageSystem>().Damage (spell.damage, spell.knockFactor, owner.transform.position, spell.owner);
}
owner.GetComponent<SpellCasting>().isHooking = false;
Destroy (gameObject);
}
}
lineRenderer.SetPosition(1, hookedObject.transform.position);
RpcLineRenderer(1, hookedObject.transform.position);
transform.position = hookedObject.transform.position;
}
if(hasHooked && hookedObject == null)
{
TimeOut ();
}
}
[ClientRpc]
void RpcLineRenderer(int index, Vector3 pos)
{
lineRenderer.SetPosition(index, pos);
}
void OnTriggerEnter2D(Collider2D other)
{
if (!isServer)
return;
if(hookedObject == null)
{
if(other.CompareTag("Player"))
{
DamageSystem damageSystem = (DamageSystem)other.GetComponent ("DamageSystem");
if(spell.team != damageSystem.Team() && !other.GetComponent<SpellCasting>().isShielding)
{
hookedObject = other.gameObject;
CancelInvoke("TimeOut");
AudioSource.PlayClipAtPoint(hit, transform.position);
hasHooked = true;
string playerName = ((SpellCasting)other.gameObject.GetComponent ("SpellCasting")).playerName;
//GetComponent<NetworkView>().RPC ("SyncHooked", RPCMode.All, playerName);
if(pulling && hookedObject.tag == "Player")
{
hookedObject.GetComponent<DamageSystem>().Damage(spell.damage, spell.knockFactor, owner.transform.position, spell.owner);
//hookedObject.GetComponent<NetworkView>().RPC ("HookDamage", RPCMode.All, spell.damage, spell.knockFactor, owner.transform.position, spell.owner);
}
}
}
if(other.CompareTag("Obstacle"))
{
hookedObject = other.gameObject;
CancelInvoke("TimeOut");
AudioSource.PlayClipAtPoint(hit, transform.position);
hasHooked = true;
}
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class CameraScript : MonoBehaviour {
private GameObject playerObject;
private bool cameraLocked = true;
public GameObject PlayerObject
{
set
{
playerObject = value;
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.UpArrow))
{
cameraLocked = !cameraLocked;
}
if(playerObject != null)
{
if(cameraLocked)
{
transform.position = new Vector3(playerObject.transform.position.x, playerObject.transform.position.y, -1);
}
else if(GameHandler.state == GameHandler.State.Game)
{
Vector3 newPos = Vector3.Lerp(playerObject.transform.position, this.GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition), 0.5f);
transform.position = new Vector3(newPos.x, newPos.y, -1);
//transform.position = new Vector3(playerObject.transform.position.x, playerObject.transform.position.y, -1);
}
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Spell : NetworkBehaviour {
public float castTime = 0.6f;
public float cooldown = 1.5f;
[SyncVar]
public float damage;
public float knockFactor;
[SyncVar]
public int team;
[SyncVar]
public string owner;
public enum spellType { Projectile, Area, Mimic, Other, TargetArea };
public spellType type;
[SyncVar]
public Vector2 aimPoint;
public bool destroysSpells;
[SyncVar]
public Vector2 aimDir;
public Upgrades upgrades;
void Start()
{
//Invoke ("KillSelf", 5);
}
public void KillSelf()
{
Destroy (gameObject);
}
public void SetColor()
{
Debug.Log(team);
switch(team)
{
case 1:
gameObject.GetComponent<ParticleSystem>().startColor = new Color(0.19f, 0.57f, 0.156f);
break;
case 2:
gameObject.GetComponent<ParticleSystem>().startColor = new Color(0.28f, 0.77f, 0.84f);
break;
}
}
//[RPC]
//void SetAim(float x, float y, int team, float amplifyAmount, Vector3 pos)
//{
// Debug.Log ("Set aim!");
// aimDir = new Vector2(x, y);
// team = team;
// transform.position = pos;
// //spell.damage *
//}
}
<file_sep>using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class Fireball : NetworkBehaviour
{
public float oldSpeed;
public float speed = 50;
public Spell spell;
public GameObject fireballExplo;
public AudioClip cast;
public GameObject burnEffect;
public float dotDamage;
public float duration;
public GameObject minorFireball;
bool finalBlast;
void Start ()
{
oldSpeed = speed;
spell.SetColor();
Vector2 aimPos = ((Spell)gameObject.GetComponent("Spell")).aimPoint;
if(spell.aimDir == null || spell.aimDir == Vector2.zero)
spell.aimDir = Vector3.Normalize(new Vector3(aimPos.x, aimPos.y) - transform.position);
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
AudioSource.PlayClipAtPoint(cast, transform.position);
if (!isServer)
return;
spell.Invoke("KillSelf", 5);
if(spell.upgrades != null)
{
IncreaseDot(spell.upgrades.fireballDot);
finalBlast = spell.upgrades.fireballFinalBlast > 0;
IncreaseDmg(spell.upgrades.fireballDmg);
if (spell.upgrades.fireballCd > 0)
{
for (int i = 0; i < 2; i++)
{
float angle = Mathf.Atan2(spell.aimDir.y, spell.aimDir.x) * Mathf.Rad2Deg;
if (i == 0)
angle -= 35.0f;
else
angle += 35.0f;
angle *= Mathf.Deg2Rad;
Vector3 newAimDir = new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0);
GameObject newFireball = Instantiate(minorFireball, transform.position, Quaternion.identity);
Spell spellScript = newFireball.GetComponent<Spell>();
spellScript.owner = spell.owner;
spellScript.team = spell.team;
spellScript.aimDir = newAimDir;
NetworkServer.Spawn(newFireball);
}
}
}
}
void Update ()
{
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
}
void IncreaseDot(int level)
{
dotDamage += 0.05f * level;
duration += 0.5f * level;
Debug.Log("Dot increased");
}
void IncreaseDmg(int level)
{
spell.damage += 1.0f * level;
spell.knockFactor += 0.8f * level;
}
void OnTriggerEnter2D(Collider2D other)
{
if (!isServer)
return;
if(other.CompareTag("Player"))
{
DamageSystem damageSystem = (DamageSystem)other.GetComponent("DamageSystem");
if (spell.team != damageSystem.Team())
{
if (!other.GetComponent<SpellCasting>().isShielding && !other.GetComponent<DamageSystem>().invulnerable)
{
damageSystem.Damage(spell.damage, spell.knockFactor, transform.position, spell.owner);
damageSystem.AddDot(dotDamage, duration, 0.5f, spell.owner, burnEffect);
if (finalBlast)
{
Debug.Log("Final blast!");
damageSystem.AddDot(5, duration + 1, duration, spell.owner, burnEffect);
}
Destroy(gameObject);
GameObject explo = Instantiate(fireballExplo, transform.position, Quaternion.identity);
NetworkServer.Spawn(explo);
}
}
}
if(other.CompareTag ("Obstacle"))
{
other.SendMessage("Damage", spell.damage, SendMessageOptions.DontRequireReceiver);
Destroy(gameObject);
GameObject explo = Instantiate(fireballExplo, transform.position, Quaternion.identity);
NetworkServer.Spawn(explo);
}
else if(other.CompareTag ("Spell"))
{
Spell otherSpell = (Spell)other.GetComponent("Spell");
if (spell.team != otherSpell.team && otherSpell.type == Spell.spellType.Projectile)
{
if(spell.destroysSpells)
{
GameObject explo = Instantiate(fireballExplo, transform.position, Quaternion.identity);
NetworkServer.Spawn(explo);
Destroy(other.gameObject);
}
if (otherSpell.destroysSpells)
{
GameObject explo = Instantiate(fireballExplo, transform.position, Quaternion.identity);
NetworkServer.Spawn(explo);
Destroy(gameObject);
}
}
}
}
}<file_sep>using UnityEngine;
using System.Collections;
public class BindRope : MonoBehaviour {
Transform boundTo;
Vector3 boundPos;
public LineRenderer lineRenderer;
public void SetKill(float duration)
{
Invoke ("KillSelf", duration);
}
void KillSelf()
{
Destroy(gameObject);
}
public void SetBinds(Vector3 bindPos, string bindTo)
{
boundPos = bindPos;
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
foreach(GameObject player in players)
{
SpellCasting spell = player.GetComponent<SpellCasting>();
if(spell.playerName == bindTo)
{
boundTo = player.transform;
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, player.transform.position);
}
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class PrisonWall : MonoBehaviour {
public int health;
public GameObject wall1;
public GameObject wall2;
public GameObject wall3;
public GameObject wall4;
public bool reflect = false;
public int team;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
void Damage(float amount)
{
if(amount >= 5)
{
health --;
if(health <= 0)
{
GameObject.Destroy(wall1);
GameObject.Destroy(wall2);
GameObject.Destroy(wall3);
GameObject.Destroy(wall4);
GetComponent<Collider2D>().enabled = false;
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
if(reflect)
{
if(other.GetComponent<NetworkView>().isMine)
{
if(other.CompareTag ("Spell"))
{
Spell otherSpell = (Spell)other.GetComponent("Spell");
if(team != otherSpell.team)
{
if(otherSpell.type == Spell.spellType.Projectile)
{
Vector3 normal = Vector3.Normalize(other.transform.position - gameObject.transform.position);
Vector3 reflected = Vector3.Reflect(otherSpell.aimDir, normal);
otherSpell.aimDir = reflected;
otherSpell.team = team;
//Network.Instantiate(shieldHit, other.transform.position, Quaternion.identity, 0);
}
}
}
}
}
}
}<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class FrostPrison : NetworkBehaviour {
public Spell spell;
public float duration;
public float formTime;
public AudioClip cast;
public AudioClip form;
public GameObject prison;
public GameObject extraWall;
public GameObject wall1;
public GameObject wall2;
public GameObject wall3;
public GameObject wall4;
public GameObject spawn;
public GameObject extraSpawn;
public GameObject storm;
float currentTime;
float baseDamage = 0.45f;
bool formed;
bool stormActive;
bool reflects;
float totalDamage = 0;
bool circleWall = false;
void Start ()
{
SetColor();
spell.aimDir = Vector3.Normalize(new Vector3(spell.aimPoint.x, spell.aimPoint.y) - transform.position);
float angle = Mathf.Atan2(spell.aimDir.y, spell.aimDir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
transform.position = spell.aimPoint;
transform.position += transform.up * -0.5f;
spell.Invoke ("KillSelf", duration + formTime);
Invoke ("Spawn", formTime);
AudioSource.PlayClipAtPoint(cast, transform.position);
if (!isServer)
return;
IncreaseDuration(spell.upgrades.frostPrisonDuration);
if (spell.upgrades.frostPrisonCircleWall > 0)
CircleWall();
IncreaseDmg(spell.upgrades.frostPrisonRamp);
if (spell.upgrades.frostPrisonStorm > 0)
ActivateStorm();
}
void SetColor()
{
switch(spell.team)
{
case 1:
SpriteRenderer[] renderers = gameObject.GetComponentsInChildren<SpriteRenderer>();
foreach(SpriteRenderer renderer in renderers)
{
Debug.Log ("Setting a color");
renderer.color = new Color(0.43f, 1f, 0.46f);
}
ParticleSystem[] systems = gameObject.GetComponentsInChildren<ParticleSystem>();
foreach(ParticleSystem system in systems)
{
system.startColor = new Color(0.19f, 0.57f, 0.156f);
}
break;
}
}
void IncreaseDuration(int level)
{
duration += 0.5f * level;
}
void CircleWall()
{
formTime = 0.7f;
spell.damage = 0;
Invoke ("Spawn", formTime);
circleWall = true;
extraSpawn.SetActive (true);
}
void IncreaseDmg(int level)
{
spell.damage += 0.035f * level;
}
void ActivateStorm()
{
spell.damage += 0.04f;
stormActive = true;
spawn.SetActive(false);
}
// Update is called once per frame
void Update ()
{
if(formed)
{
currentTime += Time.deltaTime;
totalDamage += spell.damage * (baseDamage + (currentTime/(duration * 4.4f)));
//Debug.Log (totalDamage);
}
}
void Spawn()
{
storm.SetActive(true);
if(!stormActive)
{
spawn.SetActive(false);
prison.SetActive(true);
AudioSource.PlayClipAtPoint(form, transform.position);
if(circleWall)
{
extraWall.SetActive(true);
extraSpawn.SetActive(false);
storm.SetActive(false);
}
SetColor();
}
formed = true;
}
void OnTriggerStay2D(Collider2D other)
{
if (!isServer)
return;
if(formed)
{
if(other.CompareTag("Player"))
{
DamageSystem damageSystem = (DamageSystem)other.GetComponent ("DamageSystem");
if(spell.team != damageSystem.Team())
{
damageSystem.Damage(spell.damage * (baseDamage + (currentTime/(duration * 4.4f))), spell.knockFactor, transform.position, spell.owner);
if(stormActive)
{
other.GetComponent<Movement>().RpcSpeedBoost(0.5f, 0.2f);
}
}
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.Match;
using UnityEngine.Networking.Types;
using UnityEngine.UI;
public class MenuConnection : NetworkLobbyManager
{
List<LobbyPlayer> playerList = new List<LobbyPlayer>();
public InputField nameInput;
public Button startGameButton;
public VerticalLayoutGroup lobbyList;
public Button lobbyItem;
public GameObject lobbyName;
public GameObject team1Players;
public GameObject team2Players;
public GameObject iceWizard;
public GameObject fireWizard;
public GameObject menulobby;
public GameObject menuMain;
public GameObject menuclient;
public GameObject menuhost;
public void Awake()
{
matchMaker = gameObject.AddComponent<NetworkMatch>();
if (PlayerPrefs.HasKey("Player Name"))
{
nameInput.text = PlayerPrefs.GetString("Player Name");
}
}
public void SetPlayerName(string name)
{
PlayerPrefs.SetString("Player Name", name);
}
public void OnClickStartHost()
{
StartHost();
}
public void OnClickStartMM()
{
matchMaker.CreateMatch(PlayerPrefs.GetString("Player Name") + "'s game", 6, true, "", "", "", 0, 0, OnMatchCreate);
}
public void OnClickRefresh()
{
matchMaker.ListMatches(0, 10, "", true, 0, 0, OnMatchList);
}
public override void OnMatchList(bool success, string extendedInfo, List<MatchInfoSnapshot> matchList)
{
base.OnMatchList(success, extendedInfo, matchList);
foreach(Transform child in lobbyList.transform)
{
Destroy(child.gameObject);
}
foreach(MatchInfoSnapshot info in matchList)
{
Debug.Log(info.name);
Button newItem = Instantiate(lobbyItem, lobbyList.transform);
newItem.transform.Find("LobbyName").GetComponent<Text>().text = info.name;
newItem.onClick.AddListener(SwapToLobby);
newItem.onClick.AddListener(delegate { ConnectToMM(info.networkId);});
}
}
void SwapToLobby()
{
menuMain.SetActive(false);
menulobby.SetActive(true);
menuclient.SetActive(true);
menuhost.SetActive(false);
}
void ConnectToMM(NetworkID id)
{
matchMaker.JoinMatch(id, "", "", "", 0, 0, OnMatchJoined);
}
public void OnClickConnect()
{
Debug.Log("clicked connect");
StartClient();
}
public void OnClickStartGame()
{
base.OnLobbyServerPlayersReady();
}
public override void OnLobbyStartHost()
{
Debug.Log("Started host");
}
public override void OnLobbyServerConnect(NetworkConnection conn)
{
Debug.Log("Someone connected");
}
public override void OnLobbyServerPlayersReady()
{
startGameButton.interactable = true;
}
public void CheckReady()
{
bool allready = true;
foreach(LobbyPlayer player in playerList)
{
if(!player.readyToBegin)
{
allready = false;
break;
}
}
if(allready)
{
startGameButton.interactable = true;
}
else
{
startGameButton.interactable = false;
}
}
public void AddPlayer(LobbyPlayer player)
{
if (playerList.Contains(player))
return;
playerList.Add(player);
CheckReady();
}
public void RemovePlayer(LobbyPlayer player)
{
playerList.Remove(player);
CheckReady();
UpdatePlayerList();
}
public void UpdatePlayerList()
{
Debug.Log("Updating player list");
List<GameObject> playerNames = new List<GameObject>();
for (int i = 0; i < team1Players.transform.childCount; i++)
{
playerNames.Add(team1Players.transform.GetChild(i).gameObject);
}
for (int i = 0; i < team2Players.transform.childCount; i++)
{
playerNames.Add(team2Players.transform.GetChild(i).gameObject);
}
foreach (GameObject player in playerNames)
{
Destroy(player);
}
GameObject newPlayerName;
foreach (LobbyPlayer player in playerList)
{
Debug.Log("Creating player with name: " + player.playerName);
if (player.team.Equals("1"))
{
newPlayerName = Instantiate(lobbyName, team1Players.transform);
}
else
{
newPlayerName = Instantiate(lobbyName, team2Players.transform);
}
newPlayerName.GetComponent<Text>().text = player.playerName;
newPlayerName.transform.Find("Ready").gameObject.SetActive(player.readyToBegin);
}
}
public override bool OnLobbyServerSceneLoadedForPlayer(GameObject lobbyPlayer, GameObject gamePlayer)
{
LobbyPlayer player = lobbyPlayer.GetComponent<LobbyPlayer>();
SpellCasting spellCasting = gamePlayer.GetComponent<SpellCasting>();
spellCasting.team = int.Parse(player.team);
Debug.Log("ServerSceneLoadedForPlayer: " + player.playerName);
if (player.team == "1")
{
gamePlayer.transform.position = new Vector3(-11, 0);
}
else if (player.team == "2")
{
gamePlayer.transform.position = new Vector3(11, 0);
}
return true;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Blink : NetworkBehaviour {
public Spell spell;
public float speed = 50;
public GameObject owner;
public AudioClip cast;
public AudioClip hit;
public GameObject effect;
float unitsTravelled = 0;
bool thrusting = false;
GameObject[] players;
ArrayList playersHit = new ArrayList();
private bool stopped = false;
void Start ()
{
AudioSource.PlayClipAtPoint(cast, transform.position);
if (!isServer)
return;
Vector2 aimPos = spell.aimPoint;
string ownerName = spell.owner;
players = GameObject.FindGameObjectsWithTag("Player");
foreach(GameObject player in players)
{
string playerName = player.GetComponent<SpellCasting>().playerName;
if(ownerName.Equals(playerName))
{
owner = player;
RpcSetOwner(owner);
break;
}
}
IncreaseDmg(spell.upgrades.blinkDmg);
if(spell.upgrades.blinkThrust > 0)
{
thrusting = true;
}
if (!thrusting)
{
RpcStartBlink();
}
spell.aimDir = Vector3.Normalize(new Vector3(aimPos.x, aimPos.y) - transform.position);
}
void IncreaseDmg(int level)
{
spell.damage = 5 + level * 2;
}
void Update ()
{
if(isServer && !stopped)
{
Vector3 velocity = new Vector3(spell.aimDir.x, spell.aimDir.y, 0) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
owner.GetComponent<Movement>().RpcMove(velocity);
transform.position += velocity;
unitsTravelled += 1 / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
owner.GetComponent<DamageSystem>().Invulnerability(0.1f);
if(thrusting)
{
foreach(GameObject player in players)
{
DamageSystem damageSystem = (DamageSystem)player.GetComponent ("DamageSystem");
if(spell.team != damageSystem.Team())
{
if(Vector3.Distance(player.transform.position, owner.transform.position) < 1.5)
{
if(!damageSystem.invulnerable)
{
damageSystem.Damage(spell.damage, spell.knockFactor, transform.position, spell.owner);
RpcEndBlink();
owner.GetComponent<DamageSystem>().knockback = Vector3.zero;
spell.Invoke("KillSelf", 0.5f);
stopped = true;
//Destroy(gameObject);
}
}
}
}
}
else if(spell.damage > 0)
{
foreach(GameObject player in players)
{
if(!playersHit.Contains(player))
{
DamageSystem damageSystem = (DamageSystem)player.GetComponent ("DamageSystem");
if(spell.team != damageSystem.Team())
{
if(Vector3.Distance(player.transform.position, owner.transform.position) < 3)
{
if(!damageSystem.invulnerable)
{
Debug.Log ("Damage time!");
damageSystem.Damage(spell.damage, spell.knockFactor, transform.position, spell.owner);
playersHit.Add (player);
}
}
}
}
}
}
if(Vector3.Distance(owner.transform.position, spell.aimPoint) < 1f || unitsTravelled > 11)
{
RpcEndBlink();
owner.GetComponent<DamageSystem>().knockback = Vector3.zero;
spell.Invoke("KillSelf", 1);
stopped = true;
}
CreateEffect();
}
}
void CreateEffect()
{
GameObject groundEffect = Instantiate(effect, transform.position, Quaternion.identity);
NetworkServer.Spawn(groundEffect);
}
[ClientRpc]
void RpcSetOwner(GameObject o)
{
Debug.Log("setting owner");
owner = o;
}
[ClientRpc]
void RpcStartBlink()
{
Debug.Log ("Blinkin'");
owner.GetComponent<Collider2D>().enabled = false;
Renderer[] renderers = owner.GetComponentsInChildren<Renderer>();
foreach(Renderer renderer in renderers)
{
renderer.enabled = false;
}
}
[ClientRpc]
void RpcEndBlink()
{
if (owner.GetComponent<DamageSystem>().isDead)
return;
Debug.Log ("Ending blink");
owner.GetComponent<Collider2D>().enabled = true;
Renderer[] renderers = owner.GetComponentsInChildren<Renderer>();
foreach(Renderer renderer in renderers)
{
renderer.enabled = true;
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class PowerUpHandler : NetworkBehaviour
{
public GameObject damageBoost;
public GameObject speedBoost;
GameObject currentPowerUp;
bool isSpawning = false;
// Use this for initialization
void Start ()
{
if(isServer)
{
Invoke ("SpawnPowerUp", 20);
isSpawning = true;
}
}
// Update is called once per frame
void Update ()
{
if(isServer)
{
if(GameHandler.state == GameHandler.State.Game)
{
if (currentPowerUp == null && !isSpawning)
{
StartSpawn();
}
}
else
{
if(currentPowerUp != null)
{
Destroy(currentPowerUp);
}
else if(isSpawning)
{
CancelSpawn();
}
}
}
}
public void CancelSpawn()
{
CancelInvoke("SpawnPowerUp");
isSpawning = false;
}
public void StartSpawn()
{
Invoke("SpawnPowerUp", 30);
isSpawning = true;
}
void SpawnPowerUp()
{
int randomNr = Random.Range(1, 3);
switch(randomNr)
{
case 1:
currentPowerUp = Instantiate(damageBoost, transform.position, Quaternion.identity);
NetworkServer.Spawn(currentPowerUp);
break;
case 2:
currentPowerUp = Instantiate(speedBoost, transform.position, Quaternion.identity);
NetworkServer.Spawn(currentPowerUp);
break;
}
isSpawning = false;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
[NetworkSettings(sendInterval = 0)]
public class DamageSystem : NetworkBehaviour
{
public SpellCasting spellCasting;
public Movement movement;
[SyncVar]
float health = 150;
float maxHealth;
[SyncVar]
public Vector3 knockback;
public float damageHealed = 0;
[SyncVar]
public float damageTaken = 0;
public Texture healthBar;
public Texture healthFill;
public Texture vertLine;
public bool inLava = false;
public bool isDead = false;
int lives = 1;
public GameObject hook;
public bool isInvis = false;
public AudioClip lastWord;
public AudioClip dead;
bool playedLastword = false;
List<Dot> dotList = new List<Dot>();
List<Hot> hotList = new List<Hot>();
public bool invulnerable = false;
string lastDamagedBy = "";
float damagedByCountdown = 3;
float lavaAmp = 1;
float amp = 1;
private int directAmpCount = 0;
private float directAmpAmount = 1.0f;
float absorb = 0;
public GameObject absorbShield;
GameObject currentShieldEffect;
public int Team()
{
return spellCasting.team;
}
[Command]
public void CmdFullReset()
{
health = maxHealth;
damageTaken = 0;
damageHealed = 0;
RpcReset ();
spellCasting.RpcReset();
movement.RpcReset();
}
[ClientRpc]
void RpcReset()
{
Debug.Log ("Resetting");
SpriteRenderer[] sRenderers = gameObject.GetComponentsInChildren<SpriteRenderer>();
foreach(SpriteRenderer renderer in sRenderers)
{
Debug.Log ("Setting renderer color");
renderer.color = new Color(1, 1, 1, 1);
}
Renderer[] renderers = gameObject.GetComponentsInChildren<Renderer>();
foreach(Renderer renderer in renderers)
{
Debug.Log ("Enabling renderer");
renderer.enabled = true;
}
Invoke("Respawn", 3);
}
void Start ()
{
maxHealth = health;
}
void Dispel(string owner)
{
GameObject[] players = GameObject.FindGameObjectsWithTag ("Player");
foreach (GameObject player in players)
{
if(player.GetComponent<SpellCasting>().playerName == owner)
{
if(player.GetComponent<SpellCasting>().team == Team())
{
dotList.Clear();
movement.bound = Vector3.zero;
spellCasting.isSilenced = false;
}
else
{
hotList.Clear();
}
}
}
}
public void Absorb(float amount, float duration)
{
CancelInvoke("EndAbsorb");
Invoke ("EndAbsorb", duration);
absorb += amount;
Network.Destroy(currentShieldEffect);
currentShieldEffect = (GameObject)Network.Instantiate(absorbShield, transform.position, Quaternion.identity, 0);
}
void EndAbsorb()
{
absorb = 0;
Network.Destroy(currentShieldEffect);
}
void Update ()
{
if(isServer && !isDead && !invulnerable)
{
if(absorb > 0)
{
knockback = Vector3.zero;
}
if(currentShieldEffect != null)
{
currentShieldEffect.transform.position = transform.position;
}
if(!inLava && knockback == Vector3.zero)
{
damagedByCountdown -= Time.deltaTime;
}
if(damagedByCountdown <= 0)
{
lastDamagedBy = "";
}
if(knockback.magnitude > 80)
{
knockback *= 0.945f;
}
else if(knockback.magnitude > 60)
{
knockback *= 0.955f;
}
else if(knockback.magnitude > 40)
{
knockback *= 0.965f;
}
else
{
knockback *= 0.97f;
}
if(knockback.magnitude < 1)
{
knockback = Vector3.zero;
}
if(inLava)
{
Damage (0.12f * lavaAmp * Time.deltaTime * 60, 0, Vector3.zero, "world");
}
//Damage over time management
List<Dot> removeList = new List<Dot>();
foreach(Dot dot in dotList)
{
dot.duration -= Time.deltaTime;
if(dot.duration > 0)
{
dot.tickCounter += Time.deltaTime;
if(dot.tickCounter >= dot.tickTime)
{
Damage (dot.damage, 0, Vector3.zero, dot.owner);
dot.tickCounter -= dot.tickTime;
}
if(dot.effect != null && !isInvis)
{
dot.effect.transform.position = transform.position + new Vector3(0, 0, 0.5f);
}
}
else
{
removeList.Add (dot);
}
}
foreach(Dot dot in removeList)
{
Destroy(dot.effect);
dotList.Remove(dot);
}
//Heal over time management
List<Hot> removeHots = new List<Hot>();
foreach(Hot hot in hotList)
{
hot.duration -= Time.deltaTime;
if(hot.duration > 0)
{
hot.tickCounter += Time.deltaTime;
if(hot.tickCounter >= hot.tickTime)
{
Damage (-hot.damage, 0, Vector3.zero, "world");
hot.tickCounter -= hot.tickTime;
}
if(hot.effect != null && !isInvis)
{
hot.effect.transform.position = transform.position + new Vector3(0, 0, 0.5f);
}
}
else
{
removeHots.Add (hot);
}
}
foreach(Hot hot in removeHots)
{
Destroy(hot.effect);
hotList.Remove(hot);
}
}
}
public void Amplify(float damageIncrease, float duration)
{
amp = 1 + damageIncrease;
Invoke("EndAmplify", duration);
}
void EndAmplify()
{
amp = 1;
}
void OnGUI()
{
if(!isDead && !isInvis && GameHandler.state != GameHandler.State.Upgrade)
{
float currentHealth = health / maxHealth;
float currentDamageTaken = (damageTaken * 0.5f) / maxHealth;
Vector3 playerPos = Camera.main.WorldToScreenPoint(new Vector3(transform.position.x, transform.position.y, 0));
GUI.DrawTexture (new Rect(playerPos.x - 60, Screen.height - playerPos.y - 60, 120, 12), healthBar);
GUI.DrawTexture (new Rect(playerPos.x - 60, Screen.height - playerPos.y - 59, currentHealth * 120, 10), healthFill);
//GUI.DrawTexture (new Rect(playerPos.x + 60 - currentDamageTaken * 120, Screen.height - playerPos.y - 59, 2, 10), vertLine);
}
}
public void DmgInvis()
{
Debug.Log ("Damage system invis!");
isInvis = true;
if (!isServer)
return;
foreach (Hot hot in hotList)
{
Debug.Log ("Heres a hot!");
hot.effect.SetActive(false);
}
foreach(Dot dot in dotList)
{
Debug.Log ("Heres a dot!");
dot.effect.SetActive(false);
}
GameObject[] powerupEffects = GameObject.FindGameObjectsWithTag("PowerUpEffect");
foreach(GameObject p in powerupEffects)
{
if(p.GetComponent<FollowPlayer>().player == gameObject)
{
p.GetComponent<ParticleSystem>().Stop(false, ParticleSystemStopBehavior.StopEmitting);
}
}
}
public void EndInvis()
{
isInvis = false;
if (!isServer)
return;
foreach (Hot hot in hotList)
{
hot.effect.SetActive(true);
}
foreach(Dot dot in dotList)
{
dot.effect.SetActive(true);
}
GameObject[] powerupEffects = GameObject.FindGameObjectsWithTag("PowerUpEffect");
foreach (GameObject p in powerupEffects)
{
if (p.GetComponent<FollowPlayer>().player == gameObject)
{
p.GetComponent<ParticleSystem>().Play();
}
}
}
void SetHook(GameObject _hook)
{
hook = _hook;
}
void ResetHook()
{
hook = null;
}
public void AddDot(float dmg, float dur, float tick, string owner, GameObject eff)
{
GameObject newEffect = Instantiate(eff, transform.position, Quaternion.identity);
NetworkServer.Spawn(newEffect);
dotList.Add (new Dot(dmg, dur, tick, owner, newEffect));
}
public void AddHot(float heal, float dur, float tick, GameObject eff)
{
GameObject newEffect = Instantiate(eff, transform.position, Quaternion.identity);
NetworkServer.Spawn(newEffect);
hotList.Add (new Hot(heal, dur, tick, newEffect));
}
public void Invulnerability(float duration)
{
invulnerable = true;
Invoke("EndInvulnerable", duration);
}
public void EndInvulnerable()
{
invulnerable = false;
}
public void Damage(float damage, float knockFactor, Vector3 position, string damagedBy)
{
if(!invulnerable && GameHandler.state == GameHandler.State.Game)
{
if(damage < 0 && damageHealed >= damageTaken * 0.5f)
{
//return;
}
if(damage > 0)
{
if(damage >= 5)
{
//Cause extra damage due to direct amp
if (directAmpCount > 0)
{
directAmpCount--;
damage *= directAmpAmount;
knockFactor *= directAmpAmount;
}
}
if (absorb > damage)
{
absorb -= damage;
}
else if(absorb > 0)
{
damage -= absorb;
damageTaken += damage * amp;
health = Mathf.Clamp (health - damage * amp, 0, maxHealth);
}
else
{
damageTaken += damage * amp;
health = Mathf.Clamp (health - damage * amp, 0, maxHealth);
}
if(damagedBy != "world")
{
lastDamagedBy = damagedBy;
damagedByCountdown = 3;
}
}
else
{
health = Mathf.Clamp (health - damage, 0, maxHealth);
}
Vector3 knockDir = Vector3.Normalize(transform.position - position);
knockback += knockDir * knockFactor * amp * (8f + (maxHealth - health) / (maxHealth/25)) / 1.8f;
//if(health <= 40 && !playedLastword)
//{
// AudioSource.PlayClipAtPoint(lastWord, transform.position);
// playedLastword = true;
//}
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
foreach(GameObject player in players)
{
if(player.GetComponent<SpellCasting>().playerName == damagedBy)
{
//player.GetComponent<NetworkView>().RPC("IncreaseDamageDone", RPCMode.All, damage);
break;
}
}
if(damage >= 5)
{
if(isServer)
{
spellCasting.RpcEndChannelingPowerUp();
}
if(movement.bound != Vector3.zero)
{
movement.bound = Vector3.zero;
}
if(hook != null)
{
hook.SendMessage("TimeOut");
spellCasting.isHooking = false;
hook = null;
}
RpcStopCasting();
}
if(damage >= 5 || inLava)
{
if(health <= 0)
{
isDead = true;
spellCasting.isDead = true;
knockback = Vector3.zero;
lives--;
spellCasting.RpcDead();
dotList.Clear();
hotList.Clear();
damageTaken = 0;
damageHealed = 0;
invulnerable = true;
RpcHide();
AudioSource.PlayClipAtPoint(dead, transform.position);
GameObject.Find("GameHandler").GetComponent<GameHandler>().PlayerDead(Team());
//if(lives > 0)
//{
// Invoke ("SelfRespawn", 5);
//}
//else
//{
// GameObject.Find ("GameHandler").SendMessage("PlayerDead", Team ());
//}
}
}
if(damage < 0)
{
damageHealed -= damage;
}
}
}
[ClientRpc]
void RpcStopCasting()
{
spellCasting.CmdEndChannelingPowerUp();
if (movement.bound != Vector3.zero)
{
movement.bound = Vector3.zero;
}
if (hook != null)
{
hook.SendMessage("TimeOut");
spellCasting.isHooking = false;
hook = null;
}
}
[RPC]
void IncreaseGold(int amount)
{
if(GetComponent<NetworkView>().isMine)
{
spellCasting.gold += amount;
}
}
public void Respawn()
{
isDead = false;
invulnerable = false;
health = maxHealth;
dotList.Clear();
hotList.Clear();
spellCasting.Spawned();
Debug.Log ("Respawned!");
inLava = false;
GetComponent<Collider2D>().enabled = true;
spellCasting.CmdEndChannelingPowerUp();
}
[ClientRpc]
public void RpcHide()
{
GetComponent<Collider2D>().enabled = false;
//Check dis out yo can't hide this shizzle
Renderer[] renderers = gameObject.GetComponentsInChildren<Renderer>();
foreach(Renderer renderer in renderers)
{
renderer.enabled = false;
}
}
[RPC]
public void UpdateHealth(float currentHealth, float dmg)
{
health = currentHealth;
damageTaken = dmg;
}
public void DirectDamageAmp(float amount, int count, float duration)
{
directAmpAmount = amount;
directAmpCount += count;
CancelInvoke("RemoveDirectDamageAmp");
Invoke("RemoveDirectDamageAmp", duration);
}
public void RemoveDirectDamageAmp()
{
directAmpAmount = 1.0f;
directAmpCount = 0;
}
}
public class Dot
{
public float damage;
public float duration;
public float tickTime;
public float tickCounter;
public GameObject effect;
public string owner;
public Dot(float dmg, float dur, float tick, string _owner, GameObject eff)
{
damage = dmg;
duration = dur;
tickTime = tick;
tickCounter = 0;
owner = _owner;
effect = eff;
}
}
public class Hot
{
public float damage;
public float duration;
public float tickTime;
public float tickCounter;
public GameObject effect;
public Hot(float dmg, float dur, float tick, GameObject eff)
{
damage = dmg;
duration = dur;
tickTime = tick;
tickCounter = 0;
effect = eff;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class PlacedShield : NetworkBehaviour {
public Spell spell;
public GameObject owner;
public GameObject shieldHit;
public float duration;
public AudioClip cast;
float amplifyAmount;
bool knockImmune;
bool speedBoost;
// Use this for initialization
void Start ()
{
AudioSource.PlayClipAtPoint(cast, transform.position);
if (!isServer)
return;
transform.position = spell.aimPoint;
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
string ownerName = spell.owner;
foreach(GameObject player in players)
{
string playerName = player.GetComponent<SpellCasting>().playerName;
if(ownerName == playerName)
{
owner = player;
break;
}
}
spell.Invoke ("KillSelf", duration);
//if(GetComponent<NetworkView>().isMine)
//{
// Upgrading upgrading = GameObject.Find ("GameHandler").GetComponent<Upgrading>();
// if(upgrading.placedShieldAmp.currentLevel > 0)
// {
// GetComponent<NetworkView>().RPC ("ActivateAmplify", RPCMode.All, upgrading.placedShieldAmp.currentLevel);
// if(upgrading.placedShieldKnockImmune.currentLevel > 0)
// {
// GetComponent<NetworkView>().RPC ("ActivateKnockImmune", RPCMode.All);
// }
// }
// if(upgrading.placedShieldCd.currentLevel > 0)
// {
// if(upgrading.placedShieldSpeed.currentLevel > 0)
// {
// GetComponent<NetworkView>().RPC ("ActivateSpeedBoost", RPCMode.All);
// }
// }
//}
}
[RPC]
void ActivateAmplify(int ampLevel)
{
amplifyAmount = 1 + ampLevel * 0.1f;
}
[RPC]
void ActivateKnockImmune()
{
knockImmune = true;
}
[RPC]
void ActivateSpeedBoost()
{
speedBoost = true;
}
// Update is called once per frame
void Update () {
}
void OnTriggerStay2D(Collider2D other)
{
if (!isServer)
return;
if(other.CompareTag ("Spell"))
{
Spell otherSpell = (Spell)other.GetComponent("Spell");
if(spell.team != otherSpell.team && otherSpell.type == Spell.spellType.Projectile)
{
GameObject hit = Instantiate(shieldHit, other.transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
Destroy(other.gameObject);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class FollowObject : NetworkBehaviour {
[SyncVar]
public GameObject target;
[SyncVar]
public string text;
public Vector2 offset;
private void Start()
{
GetComponent<TextMesh>().text = text;
}
void Update ()
{
transform.position = target.transform.position + new Vector3(offset.x, offset.y, -0.43f);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class MagmaBlast : NetworkBehaviour
{
public Spell spell;
public AudioClip cast;
public bool amplify;
public float selfDmg = 4;
void Start ()
{
spell.SetColor();
AudioSource.PlayClipAtPoint(cast, transform.position);
if (!isServer)
return;
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
string ownerName = spell.owner;
foreach(GameObject player in players)
{
DamageSystem damageSystem = player.GetComponent<DamageSystem>();
if(spell.team != damageSystem.Team() && !damageSystem.isDead)
{
CircleCollider2D coll = (CircleCollider2D)player.GetComponent("CircleCollider2D");
if(Vector3.Distance(player.transform.position, gameObject.transform.position) - coll.radius < 3.1f)
{
damageSystem.Damage(spell.damage + spell.upgrades.magmaBlastDmg * 1.5f, spell.knockFactor + (amplify ? 3 : 0), transform.position, spell.owner);
}
}
string playerName = ((SpellCasting)player.GetComponent ("SpellCasting")).playerName;
if(ownerName == playerName)
{
player.GetComponent<DamageSystem>().Damage(selfDmg, 0, transform.position, spell.owner);
}
}
Invoke ("KillSelf", 1);
}
public void KillSelf()
{
Destroy (gameObject);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class OnConnection : MonoBehaviour {
// Use this for initialization
void Start () {
if(!GetComponent<NetworkView>().isMine){
Movement movement = (Movement)transform.GetComponent("Movement");
//movement.enabled = false;
SpellCasting spellCasting = (SpellCasting)transform.GetComponent("SpellCasting");
//spellCasting.enabled = false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
public static class BotmUtil
{
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class FollowPlayer : MonoBehaviour {
public GameObject player;
public AudioClip sound;
// Use this for initialization
void Start () {
AudioSource.PlayClipAtPoint(sound, transform.position);
}
// Update is called once per frame
void Update () {
transform.position = player.transform.position + new Vector3(0, 0, 0.1f);
}
public void SetFollow(GameObject play, float dura)
{
player = play;
Invoke ("KillSelf", dura);
}
void KillSelf()
{
Destroy(gameObject);
}
}
<file_sep>using System.Reflection;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class DropMe : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler
{
public Image containerImage;
public Image receivingImage;
private Color normalColor;
public Color highlightColor = Color.yellow;
public SpellChoices spellChoices;
public int slotNumber;
public void OnEnable ()
{
if (containerImage != null)
normalColor = containerImage.color;
}
public void OnDrop(PointerEventData data)
{
containerImage.color = normalColor;
if (receivingImage == null)
return;
Sprite dropSprite = GetDropSprite (data);
if (dropSprite != null)
{
receivingImage.overrideSprite = dropSprite;
switch (slotNumber)
{
case 1:
spellChoices.offSpell1 = dropSprite.name;
break;
case 2:
spellChoices.offSpell2 = dropSprite.name;
break;
case 3:
spellChoices.offSpell3 = dropSprite.name;
break;
case 4:
spellChoices.defSpell = dropSprite.name;
break;
case 5:
spellChoices.mobSpell = dropSprite.name;
break;
}
}
}
public void OnPointerEnter(PointerEventData data)
{
if (containerImage == null)
return;
Sprite dropSprite = GetDropSprite (data);
if (dropSprite != null)
containerImage.color = highlightColor;
}
public void OnPointerExit(PointerEventData data)
{
if (containerImage == null)
return;
containerImage.color = normalColor;
}
private Sprite GetDropSprite(PointerEventData data)
{
var originalObj = data.pointerDrag;
if (originalObj == null)
return null;
var dragMe = originalObj.GetComponent<DragMe>();
if (dragMe == null)
return null;
if (dragMe.blocked)
return null;
var srcImage = originalObj.GetComponent<Image>();
if (srcImage == null)
return null;
return srcImage.sprite;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class HealingWard : NetworkBehaviour {
public Spell spell;
public float duration;
public float bloomTime;
public AudioClip cast;
public GameObject effect;
bool dispels = false;
bool dispelHeals = false;
float damages = 0;
bool lifeSteals = false;
bool damageReduct = false;
bool instant = false;
void Start ()
{
SetColor();
transform.position = spell.aimPoint;
transform.position += new Vector3(0, 0, 1);
AudioSource.PlayClipAtPoint(cast, transform.position);
Invoke ("Bloom", bloomTime);
Duration(spell.upgrades.healingDuration);
if (spell.upgrades.healingDamageReduct > 0)
DamageReduct();
BloomTime(spell.upgrades.healingBloom);
if (spell.upgrades.healingBurst > 0)
Instant();
}
void SetColor()
{
switch(spell.team)
{
case 2:
gameObject.GetComponent<ParticleSystem>().startColor = new Color(0f, 1f, 1f);
ParticleSystem[] systems = gameObject.GetComponentsInChildren<ParticleSystem>();
foreach(ParticleSystem system in systems)
{
if(system.gameObject.name == "CFX_CCW")
{
system.startColor = new Color(0.27f, 1f, 1f);
}
}
break;
}
}
void Duration(int level)
{
duration += 0.7f * level;
}
void DamageReduct()
{
damageReduct = true;
}
void BloomTime(int level)
{
bloomTime -= 0.2f * level;
gameObject.GetComponent<ParticleSystem>().time = 0.7f - bloomTime;
}
void Instant()
{
instant = true;
}
void Bloom()
{
if (!isServer)
return;
Collider2D[] hitColliders = Physics2D.OverlapCircleAll(transform.position, ((CircleCollider2D)GetComponent<Collider2D>()).radius);
foreach(Collider2D hitCollider in hitColliders)
{
if(hitCollider.CompareTag("Player"))
{
if(hitCollider.gameObject.GetComponent<SpellCasting>().team == spell.team)
{
if(!instant)
{
hitCollider.GetComponent<DamageSystem>().AddHot (spell.damage, duration, 0.0165f, effect);
if(damageReduct)
{
hitCollider.GetComponent<DamageSystem>().Amplify(-0.5f, duration);
}
}
else
{
hitCollider.GetComponent<DamageSystem>().Damage(-32f, 0, transform.position, spell.owner);
}
}
}
}
spell.Invoke("KillSelf", bloomTime + 0.4f);
}
void OnTriggerStay2D(Collider2D other)
{
/*
if(other.CompareTag("Player"))
{
DamageSystem damageSystem = (DamageSystem)other.GetComponent ("DamageSystem");
if(spell.team == damageSystem.Team())
{
if(other.networkView.isMine)
{
damageSystem.Damage(-spell.damage, spell.knockFactor, transform.position);
}
}
}
*/
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Shield : NetworkBehaviour
{
public Spell spell;
public GameObject owner;
public GameObject shieldHit;
public float duration;
public AudioClip cast;
float amplifyAmount;
bool reflectAim;
float absorbAmount;
// Use this for initialization
void Start ()
{
AudioSource.PlayClipAtPoint(cast, transform.position);
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
string ownerName = spell.owner;
foreach (GameObject player in players)
{
string playerName = ((SpellCasting)player.GetComponent("SpellCasting")).playerName;
if (ownerName == playerName)
{
owner = player;
break;
}
}
if (!isServer)
return;
owner.SendMessage("IsShielding");
owner.GetComponent<SpellCasting>().Invoke ("StopShielding", duration);
spell.Invoke ("KillSelf", duration);
ActivateAmplify(spell.upgrades.shieldAmp);
ActivateAbsorb(spell.upgrades.shieldAbsorb);
}
void ActivateAmplify(int ampLevel)
{
amplifyAmount = 1 + ampLevel * 0.1f;
}
void ActivateAbsorb(int absLevel)
{
absorbAmount = 0.5f * absLevel;
}
void Update ()
{
//if (!isServer)
// return;
transform.position = owner.transform.position;
}
void OnTriggerEnter2D(Collider2D other)
{
if (!isServer)
return;
if(other.CompareTag ("Spell"))
{
Spell otherSpell = (Spell)other.GetComponent("Spell");
if(spell.team != otherSpell.team)
{
if(otherSpell.type == Spell.spellType.Projectile)
{
GameObject hitEffect = Instantiate(shieldHit, other.transform.position, Quaternion.identity);
NetworkServer.Spawn(hitEffect);
if(absorbAmount > 0)
{
owner.GetComponent<DamageSystem>().Damage (-otherSpell.damage * absorbAmount, 0, transform.position, spell.owner);
Destroy(otherSpell.gameObject);
}
else
{
Vector3 normal = Vector3.Normalize(other.transform.position - gameObject.transform.position);
Vector3 reflected = Vector3.Reflect(otherSpell.aimDir, normal);
otherSpell.aimDir = reflected;
otherSpell.team = spell.team;
otherSpell.damage *= amplifyAmount;
}
}
}
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class LifeGrip : NetworkBehaviour
{
public LineRenderer lineRenderer;
public Spell spell;
public float speed = 50;
public float hookSpeed = 15;
public GameObject owner;
public GameObject hookedObject;
public AudioClip cast;
public AudioClip hit;
bool absorb;
bool hasHooked;
public GameObject absorbShield;
void Start ()
{
AudioSource.PlayClipAtPoint(cast, transform.position);
if (!isServer)
return;
Vector2 aimPos = spell.aimPoint;
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
string ownerName = spell.owner;
foreach(GameObject player in players)
{
string playerName = player.GetComponent<SpellCasting>().playerName;
if(ownerName == playerName)
{
owner = player;
player.GetComponent<SpellCasting>().isHooking = true;
owner.SendMessage("SetHook", gameObject);
break;
}
}
spell.aimDir = Vector3.Normalize(new Vector3(aimPos.x, aimPos.y) - transform.position);
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * 2 * Time.deltaTime * 60;
Invoke ("TimeOut", 1.5f);
if (spell.upgrades.lifeGripShield > 0)
ActivateAbsorb();
//if(GetComponent<NetworkView>().isMine)
//{
// Upgrading upgrading = GameObject.Find ("GameHandler").GetComponent<Upgrading>();
// if(upgrading.lifeGripShield.currentLevel > 0)
// {
// GetComponent<NetworkView>().RPC ("ActivateAbsorb", RPCMode.All);
// }
//}
}
void ActivateAbsorb()
{
absorb = true;
}
void TimeOut()
{
((SpellCasting)owner.GetComponent ("SpellCasting")).isHooking = false;
owner.SendMessage("ResetHook");
Destroy (gameObject);
}
// Update is called once per frame
void Update ()
{
if (!isServer)
return;
lineRenderer.SetPosition (0, owner.transform.position);
RpcLineRenderer(0, owner.transform.position);
if (hookedObject == null)
{
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
lineRenderer.SetPosition(1, transform.position);
RpcLineRenderer(1, transform.position);
}
else
{
Vector3 dir = Vector3.Normalize(owner.transform.position - hookedObject.transform.position);
hookedObject.GetComponent<Movement>().RpcMove(dir / GlobalConstants.unitScaling * hookSpeed * Time.deltaTime * 60);
// if (!hookedObject.GetComponent<DamageSystem>().invulnerable)
//{
// hookedObject.GetComponent<DamageSystem>().Invulnerability(0.2f);
//}
if(Vector3.Distance (owner.transform.position, hookedObject.transform.position) < 1.8f)
{
owner.GetComponent<SpellCasting>().isHooking = false;
Destroy(gameObject);
if(absorb)
{
hookedObject.GetComponent<DamageSystem>().Absorb(20, 3);
}
hookedObject.GetComponent<DamageSystem>().Damage(-15, 0, transform.position, spell.owner);
//hookedObject.GetComponent<NetworkView>().RPC ("LowerCd", RPCMode.All, 4f);
}
lineRenderer.SetPosition(1, hookedObject.transform.position);
RpcLineRenderer(1, hookedObject.transform.position);
transform.position = hookedObject.transform.position;
}
if(hasHooked && hookedObject == null)
{
TimeOut ();
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (!isServer)
return;
if(hookedObject == null)
{
if(other.CompareTag("Player"))
{
DamageSystem damageSystem = (DamageSystem)other.GetComponent ("DamageSystem");
if(spell.team == damageSystem.Team())
{
string playerName = ((SpellCasting)other.gameObject.GetComponent ("SpellCasting")).playerName;
if(playerName != spell.owner)
{
hookedObject = other.gameObject;
CancelInvoke("TimeOut");
AudioSource.PlayClipAtPoint(hit, transform.position);
hasHooked = true;
//GetComponent<NetworkView>().RPC ("SyncHooked", RPCMode.All, playerName);
}
}
}
}
}
[ClientRpc]
void RpcLineRenderer(int index, Vector3 pos)
{
lineRenderer.SetPosition(index, pos);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class BindingShot : NetworkBehaviour
{
public float speed = 50;
private float oldSpeed;
public Spell spell;
public GameObject bindingShotHit;
public AudioClip cast;
public AudioClip bind;
public float duration;
public float length;
public GameObject bindRope;
bool silences;
bool amplifies;
void Start ()
{
oldSpeed = speed;
spell.SetColor();
Vector2 aimPos = ((Spell)gameObject.GetComponent("Spell")).aimPoint;
spell.aimDir = Vector3.Normalize(new Vector3(aimPos.x, aimPos.y) - transform.position);
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
AudioSource.PlayClipAtPoint(cast, transform.position);
if (!isServer)
return;
spell.Invoke("KillSelf", 5);
IncreaseDur(spell.upgrades.bindingDuration);
if(spell.upgrades.bindingAmplify > 0)
{
ActivateAmplify();
}
else if(spell.upgrades.bindingSilence > 0)
{
ActivateSilence();
}
}
void Update ()
{
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
}
void IncreaseDur(int level)
{
duration += 0.5f * level;
}
void ActivateSilence()
{
silences = true;
}
void ActivateAmplify()
{
amplifies = true;
}
void OnTriggerEnter2D(Collider2D other)
{
if (!isServer)
return;
if(other.CompareTag("Player"))
{
DamageSystem damageSystem = (DamageSystem)other.GetComponent ("DamageSystem");
if(spell.team != damageSystem.Team())
{
if(!other.GetComponent<SpellCasting>().isShielding && !other.GetComponent<DamageSystem>().invulnerable)
{
if(amplifies)
{
other.GetComponent<DamageSystem>().Amplify(0.35f, duration);
}
damageSystem.Damage(spell.damage, spell.knockFactor, transform.position, spell.owner);
other.GetComponent<Movement>().RpcBound(duration, length);
if(silences)
{
other.GetComponent<SpellCasting>().RpcSilence(1.5f);
}
SpellCasting spellCasting = (SpellCasting)other.GetComponent("SpellCasting");
GameObject rope = Instantiate(bindRope, this.transform.position, Quaternion.identity);
rope.GetComponent<BindRope>().SetKill(duration);
rope.GetComponent<BindRope>().SetBinds(transform.position, spellCasting.playerName);
GameObject hit = Instantiate(bindingShotHit, this.transform.position, Quaternion.identity);
NetworkServer.Spawn(rope);
NetworkServer.Spawn(hit);
Destroy(gameObject);
}
}
}
if(other.CompareTag ("Obstacle"))
{
other.SendMessage("Damage", spell.damage);
GameObject hit = Instantiate(bindingShotHit, this.transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
Destroy(gameObject);
}
if(other.CompareTag ("Spell"))
{
Spell otherSpell = (Spell)other.GetComponent("Spell");
if(spell.team != otherSpell.team && otherSpell.type == Spell.spellType.Projectile)
{
if (spell.destroysSpells)
{
GameObject hit = Instantiate(bindingShotHit, transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
Destroy(other.gameObject);
}
if (otherSpell.destroysSpells)
{
GameObject hit = Instantiate(bindingShotHit, transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
Destroy(gameObject);
}
}
}
}
}<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class SpeedBoost : NetworkBehaviour {
bool someoneCapping = false;
public GameObject effect;
void OnTriggerStay2D(Collider2D other)
{
if (!isServer)
return;
if (other.CompareTag("Player"))
{
other.GetComponent<SpellCasting>().RpcStartChannelingPowerUp(gameObject, 4);
}
}
void OnTriggerExit2D(Collider2D other)
{
if (!isServer)
return;
if (other.CompareTag("Player"))
{
other.GetComponent<SpellCasting>().RpcEndChannelingPowerUp();
}
}
void Capped(GameObject player)
{
if (!isServer)
return;
player.GetComponent<Movement>().RpcSpeedBoost(2f, 8f);
player.GetComponent<DamageSystem>().Damage(-15, 0, transform.position, "world");
var newEffect = Instantiate(effect);
newEffect.GetComponent<FollowPlayer>().SetFollow(player, 8f);
NetworkServer.Spawn(newEffect);
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject p in players)
{
p.GetComponent<SpellCasting>().RpcEndChannelingPowerUp();
}
Destroy(gameObject);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class NoLava : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerStay2D(Collider2D other)
{
if(other.gameObject.CompareTag("Player"))
{
DamageSystem damageSystem = (DamageSystem)other.GetComponent("DamageSystem");
damageSystem.inLava = false;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Networking;
public class Upgrades : NetworkBehaviour
{
public int fireballDot;
public int fireballFinalBlast;
public int fireballDmg;
public int fireballCd;
[Command]
public void CmdfireballDot(int lvl)
{
fireballDot = lvl;
}
public void CallfireballDot(int lvl)
{
CmdfireballDot(lvl);
}
[Command]
public void CmdfireballFinalBlast(int lvl)
{
fireballFinalBlast = lvl;
}
public void CallfireballFinalBlast(int lvl)
{
CmdfireballFinalBlast(lvl);
}
[Command]
public void CmdfireballDmg(int lvl)
{
fireballDmg = lvl;
}
public void CallfireballDmg(int lvl)
{
CmdfireballDmg(lvl);
}
[Command]
public void CmdfireballCd(int lvl)
{
fireballCd = lvl;
}
public void CallfireballCd(int lvl)
{
CmdfireballCd(lvl);
}
public int healingDuration;
public int healingDamageReduct;
public int healingBloom;
public int healingBurst;
[Command]
public void CmdhealingDuration(int lvl)
{
healingDuration = lvl;
}
public void CallhealingDuration(int lvl)
{
CmdhealingDuration(lvl);
}
[Command]
public void CmdhealingDamageReduct(int lvl)
{
healingDamageReduct = lvl;
}
public void CallhealingDamageReduct(int lvl)
{
CmdhealingDamageReduct(lvl);
}
[Command]
public void CmdhealingBloom(int lvl)
{
healingBloom = lvl;
}
public void CallhealingBloom(int lvl)
{
CmdhealingBloom(lvl);
}
[Command]
public void CmdhealingBurst(int lvl)
{
healingBurst = lvl;
}
public void CallhealingBurst(int lvl)
{
CmdhealingBurst(lvl);
}
public int magmaBlastCd;
public int magmaBlastSelfDispel;
public int magmaBlastDmg;
public int magmaBlastAmplify;
[Command]
public void CmdmagmaBlastCd(int lvl)
{
magmaBlastCd = lvl;
}
public void CallmagmaBlastCd(int lvl)
{
CmdmagmaBlastCd(lvl);
}
[Command]
public void CmdmagmaBlastDmg(int lvl)
{
magmaBlastDmg = lvl;
}
public void CallmagmaBlastDmg(int lvl)
{
CmdmagmaBlastDmg(lvl);
}
[Command]
public void CmdmagmaBlastAmplify(int lvl)
{
magmaBlastAmplify = lvl;
}
public void CallmagmaBlastAmplify(int lvl)
{
CmdmagmaBlastAmplify(lvl);
}
public int bindingDuration;
public int bindingSilence;
public int bindingAmplify;
[Command]
public void CmdbindingDuration(int lvl)
{
bindingDuration = lvl;
}
public void CallbindingDuration(int lvl)
{
CmdbindingDuration(lvl);
}
[Command]
public void CmdbindingSilence(int lvl)
{
bindingSilence = lvl;
}
public void CallbindingSilence(int lvl)
{
CmdbindingSilence(lvl);
}
[Command]
public void CmdbindingAmplify(int lvl)
{
bindingAmplify = lvl;
}
public void CallbindingAmplify(int lvl)
{
CmdbindingAmplify(lvl);
}
public int frostPrisonDuration;
public int frostPrisonCircleWall;
public int frostPrisonRamp;
public int frostPrisonStorm;
[Command]
public void CmdfrostPrisonDuration(int lvl)
{
frostPrisonDuration = lvl;
}
public void CallfrostPrisonDuration(int lvl)
{
CmdfrostPrisonDuration(lvl);
}
[Command]
public void CmdfrostPrisonCircleWall(int lvl)
{
frostPrisonCircleWall = lvl;
}
public void CallfrostPrisonCircleWall(int lvl)
{
CmdfrostPrisonCircleWall(lvl);
}
[Command]
public void CmdfrostPrisonRamp(int lvl)
{
frostPrisonRamp = lvl;
}
public void CallfrostPrisonRamp(int lvl)
{
CmdfrostPrisonRamp(lvl);
}
[Command]
public void CmdfrostPrisonStorm(int lvl)
{
frostPrisonStorm = lvl;
}
public void CallfrostPrisonStorm(int lvl)
{
CmdfrostPrisonStorm(lvl);
}
public int shieldAmp;
public int shieldAim;
public int shieldCd;
public int shieldAbsorb;
[Command]
public void CmdshieldAmp(int lvl)
{
shieldAmp = lvl;
}
public void CallshieldAmp(int lvl)
{
CmdshieldAmp(lvl);
}
[Command]
public void CmdshieldAim(int lvl)
{
shieldAim = lvl;
}
public void CallshieldAim(int lvl)
{
CmdshieldAim(lvl);
}
[Command]
public void CmdshieldCd(int lvl)
{
shieldCd = lvl;
}
public void CallshieldCd(int lvl)
{
CmdshieldCd(lvl);
}
[Command]
public void CmdshieldAbsorb(int lvl)
{
shieldAbsorb = lvl;
}
public void CallshieldAbsorb(int lvl)
{
CmdshieldAbsorb(lvl);
}
public int windShieldDuration;
public int windShieldDamage;
public int windShieldCd;
public int windShieldInvis;
[Command]
public void CmdwindShieldDuration(int lvl)
{
windShieldDuration = lvl;
}
public void CallwindShieldDuration(int lvl)
{
CmdwindShieldDuration(lvl);
}
[Command]
public void CmdwindShieldDamage(int lvl)
{
windShieldDamage = lvl;
}
public void CallwindShieldDamage(int lvl)
{
CmdwindShieldDamage(lvl);
}
[Command]
public void CmdwindShieldCd(int lvl)
{
windShieldCd = lvl;
}
public void CallwindShieldCd(int lvl)
{
CmdwindShieldCd(lvl);
}
[Command]
public void CmdwindShieldInvis(int lvl)
{
windShieldInvis = lvl;
}
public void CallwindShieldInvis(int lvl)
{
CmdwindShieldInvis(lvl);
}
public int hookDmg;
public int hookPull;
public int hookCd;
public int hookInvu;
[Command]
public void CmdhookDmg(int lvl)
{
hookDmg = lvl;
}
public void CallhookDmg(int lvl)
{
CmdhookDmg(lvl);
}
[Command]
public void CmdhookPull(int lvl)
{
hookPull = lvl;
}
public void CallhookPull(int lvl)
{
CmdhookPull(lvl);
}
[Command]
public void CmdhookCd(int lvl)
{
hookCd = lvl;
}
public void CallhookCd(int lvl)
{
CmdhookCd(lvl);
}
[Command]
public void CmdhookInvu(int lvl)
{
hookInvu = lvl;
}
public void CallhookInvu(int lvl)
{
CmdhookInvu(lvl);
}
public int blinkDmg;
public int blinkThrust;
public int blinkCd;
public int blinkInstant;
[Command]
public void CmdblinkDmg(int lvl)
{
blinkDmg = lvl;
}
public void CallblinkDmg(int lvl)
{
CmdblinkDmg(lvl);
}
[Command]
public void CmdblinkThrust(int lvl)
{
blinkThrust = lvl;
}
public void CallblinkThrust(int lvl)
{
CmdblinkThrust(lvl);
}
[Command]
public void CmdblinkCd(int lvl)
{
blinkCd = lvl;
}
public void CallblinkCd(int lvl)
{
CmdblinkCd(lvl);
}
[Command]
public void CmdblinkInstant(int lvl)
{
blinkInstant = lvl;
}
public void CallblinkInstant(int lvl)
{
CmdblinkInstant(lvl);
}
public int placedShieldKnockImmune;
public int placedShieldAmp;
public int placedShieldCd;
public int placedShieldSpeed;
[Command]
public void CmdplacedShieldKnockImmune(int lvl)
{
placedShieldKnockImmune = lvl;
}
public void CallplacedShieldKnockImmune(int lvl)
{
CmdplacedShieldKnockImmune(lvl);
}
[Command]
public void CmdplacedShieldAmp(int lvl)
{
placedShieldAmp = lvl;
}
public void CallplacedShieldAmp(int lvl)
{
CmdplacedShieldAmp(lvl);
}
[Command]
public void CmdplacedShieldCd(int lvl)
{
placedShieldCd = lvl;
}
public void CallplacedShieldCd(int lvl)
{
CmdplacedShieldCd(lvl);
}
[Command]
public void CmdplacedShieldSpeed(int lvl)
{
placedShieldSpeed = lvl;
}
public void CallplacedShieldSpeed(int lvl)
{
CmdplacedShieldSpeed(lvl);
}
public int lifeGripCd;
public int lifeGripShield;
[Command]
public void CmdlifeGripCd(int lvl)
{
lifeGripCd = lvl;
}
public void CalllifeGripCd(int lvl)
{
CmdlifeGripCd(lvl);
}
[Command]
public void CmdlifeGripShield(int lvl)
{
lifeGripShield = lvl;
}
public void CalllifeGripShield(int lvl)
{
CmdlifeGripShield(lvl);
}
public int arcaneBoltDmg;
public int arcaneBoltKnock;
public int arcaneBoltHeal;
public int arcaneBoltCd;
[Command]
public void CmdarcaneBoltDmg(int lvl)
{
arcaneBoltDmg = lvl;
}
public void CallarcaneBoltDmg(int lvl)
{
CmdarcaneBoltDmg(lvl);
}
[Command]
public void CmdarcaneBoltKnock(int lvl)
{
arcaneBoltKnock = lvl;
}
public void CallarcaneBoltKnock(int lvl)
{
CmdarcaneBoltKnock(lvl);
}
[Command]
public void CmdarcaneBoltHeal(int lvl)
{
arcaneBoltHeal = lvl;
}
public void CallarcaneBoltHeal(int lvl)
{
CmdarcaneBoltHeal(lvl);
}
[Command]
public void CmdarcaneBoltCd(int lvl)
{
arcaneBoltCd = lvl;
}
public void CallarcaneBoltCd(int lvl)
{
CmdarcaneBoltCd(lvl);
}
public int corruptingBoltDmgRed;
public int corruptingBoltCd;
public int corruptingBoltAmplify;
public int corruptingBoltBlast;
[Command]
public void CmdcorruptingBoltDmgRed(int lvl)
{
corruptingBoltDmgRed = lvl;
}
public void CallcorruptingBoltDmgRed(int lvl)
{
CmdcorruptingBoltDmgRed(lvl);
}
[Command]
public void CmdcorruptingBoltCd(int lvl)
{
corruptingBoltCd = lvl;
}
public void CallcorruptingBoltCd(int lvl)
{
CmdcorruptingBoltCd(lvl);
}
[Command]
public void CmdcorruptingBoltAmplify(int lvl)
{
corruptingBoltAmplify = lvl;
}
public void CallcorruptingBoltAmplify(int lvl)
{
CmdcorruptingBoltAmplify(lvl);
}
[Command]
public void CmdcorruptingBoltBlast(int lvl)
{
corruptingBoltBlast = lvl;
}
public void CallcorruptingBoltBlast(int lvl)
{
CmdcorruptingBoltBlast(lvl);
}
public void InvokeMethod(int argument, string name, System.Type type)
{
MethodInfo method = type.GetMethod(name);
object[] parameters = new object[] { (object)argument };
method.Invoke(this, parameters);
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CooldownInfo : MonoBehaviour {
public string spell1Icon;
public float spell1CD;
public float spell1MaxCD;
public string spell2Icon;
public float spell2CD;
public float spell2MaxCD;
public string spell3Icon;
public float spell3CD;
public float spell3MaxCD;
public string spell4Icon;
public float spell4CD;
public float spell4MaxCD;
public string spell5Icon;
public float spell5CD;
public float spell5MaxCD;
public Image spell1;
public Image spell2;
public Image spell3;
public Image spell4;
public Image spell5;
public Image sp1Cd;
public Image sp2Cd;
public Image sp3Cd;
public Image sp4Cd;
public Image sp5Cd;
public Sprite fireball;
public Sprite arcaneBolt;
public Sprite bindingShot;
public Sprite corruptingBolt;
public Sprite blink;
public Sprite healingWard;
public Sprite hook;
public Sprite lifeGrip;
public Sprite magmaBlast;
public Sprite newShield;
public Sprite placedShield;
public Sprite frostPrison;
public Sprite windWalkShield;
//public dfSprite upgrade1;
//public dfSprite upgrade2;
//public dfSprite upgrade3;
//public dfSprite upgrade4;
//public dfSprite upgrade5;
public Vector3 player1Pos;
void SetSpell1CD(float cd)
{
spell1CD = cd / spell1MaxCD;
sp1Cd.fillAmount = spell1CD;
}
void SetSpell1MaxCD(float cd)
{
spell1MaxCD = cd;
}
public void SetSpell1(string name)
{
spell1Icon = name;
spell1.sprite = LoadSpriteFromName(name);
//spell1.SpriteName = name;
//upgrade1.SpriteName = name;
}
void SetSpell2CD(float cd)
{
spell2CD = cd / spell2MaxCD;
sp2Cd.fillAmount = spell2CD;
}
void SetSpell2MaxCD(float cd)
{
spell2MaxCD = cd;
}
public void SetSpell2(string name)
{
spell2Icon = name;
spell2.sprite = LoadSpriteFromName(name);
//spell2.SpriteName = name;
//upgrade2.SpriteName = name;
}
void SetSpell5CD(float cd)
{
spell5CD = cd / spell5MaxCD;
sp5Cd.fillAmount = spell5CD;
}
void SetSpell5MaxCD(float cd)
{
spell5MaxCD = cd;
}
public void SetSpell5(string name)
{
spell5Icon = name;
spell5.sprite = LoadSpriteFromName(name);
//spell5.SpriteName = name;
//upgrade5.SpriteName = name;
}
void SetSpell4CD(float cd)
{
spell4CD = cd / spell4MaxCD;
sp4Cd.fillAmount = spell4CD;
}
void SetSpell4MaxCD(float cd)
{
spell4MaxCD = cd;
}
public void SetSpell4(string name)
{
spell4Icon = name;
spell4.sprite = LoadSpriteFromName(name);
//spell4.SpriteName = name;
//upgrade4.SpriteName = name;
}
void SetSpell3CD(float cd)
{
spell3CD = cd / spell3MaxCD;
sp3Cd.fillAmount = spell3CD;
}
void SetSpell3MaxCD(float cd)
{
spell3MaxCD = cd;
}
public void SetSpell3(string name)
{
spell3Icon = name;
spell3.sprite = LoadSpriteFromName(name);
//spell3.SpriteName = name;
//upgrade3.SpriteName = name;
}
Sprite LoadSpriteFromName(string name)
{
switch(name)
{
case "Fireball":
return fireball;
case "ArcaneBolt":
return arcaneBolt;
case "CorruptingBolt":
return corruptingBolt;
case "Blink":
return blink;
case "BindingShot":
return bindingShot;
case "HealingWard":
return healingWard;
case "Hook":
return hook;
case "LifeGrip":
return lifeGrip;
case "MagmaBlastAlternative":
return magmaBlast;
case "NewShield":
return newShield;
case "WindWalkShield":
return windWalkShield;
case "PlacedShield":
return placedShield;
case "PrisonCenter":
return frostPrison;
default:
return fireball;
}
}
void UpdatePlayer1Pos(Vector3 pos)
{
player1Pos = pos;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.Networking;
public class GameHandler : NetworkBehaviour
{
[SyncVar]
public int team1Left;
[SyncVar]
public int team2Left;
private int team1Count;
private int team2Count;
public int team1Score;
public int team2Score;
public Text team1ScoreText;
public Text team2ScoreText;
public AudioClip winSound;
public string winnerText = "";
public int currentRound;
[SyncVar]
public int maxRounds;
public enum State { Game, Upgrade };
public static State state = State.Game;
public bool isUpgrading;
float timeCounter = 0;
void Start ()
{
Application.targetFrameRate = 60;
QualitySettings.vSyncCount = 1;
if (!isServer)
return;
TransferVariables trScript = (TransferVariables)GameObject.Find ("TransferVariables").GetComponent("TransferVariables");
maxRounds = trScript.rounds;
Debug.Log(maxRounds);
Invoke("DelayedRpcSwapToGame", 2);
Invoke("AddPlayers", 5);
}
void AddPlayers()
{
team1Count = 0;
team2Count = 0;
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject p in players)
{
Debug.Log("Found a player for team: " + p.GetComponent<SpellCasting>().team);
switch(p.GetComponent<SpellCasting>().team)
{
case 1:
team1Count++;
break;
case 2:
team2Count++;
break;
}
}
team1Left = team1Count;
team2Left = team2Count;
Debug.Log("Team 1 left: " + team1Left);
}
void Update ()
{
if(timeCounter > 0)
{
timeCounter -= Time.deltaTime;
}
}
void OnGUI()
{
//GUI.Label(new Rect(600, 10, 300, 100), "Team 1: " + team1Score + "\t\tTeam 2: " + team2Score);
if(state == State.Upgrade)
{
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
//damageText.Text = "Damage";
GUI.Label(new Rect(10, 300, 100, 100), "Damage done: ");
int i = 0;
foreach(GameObject player in players)
{
GUI.Label(new Rect(10, 320 + i * 30, 100, 100), player.GetComponent<SpellCasting>().playerName + ": " + ((int)player.GetComponent<SpellCasting>().damageDone).ToString() +"\n");
//i++;
//damageText.Text += "\n" + player.GetComponent<SpellCasting>().playerName + " - " + ((int)player.GetComponent<SpellCasting>().damageDone).ToString();
}
GUI.Label(new Rect(950, 10, 200, 100), "Time left for upgrading: " + ((int)timeCounter).ToString());
//timeText.Text = "Time left for upgrading \n\n" + ((int)timeCounter).ToString();
}
}
[Command]
public void CmdNewPlayer(int team)
{
Debug.Log ("new player in team: " + team);
switch (team)
{
case 1:
team1Left++;
break;
case 2:
team2Left++;
break;
}
}
public void PlayerDead(int team)
{
Debug.Log ("player died in team: " + team);
bool roundOver = false;
switch (team)
{
case 1:
team1Left--;
if (team1Left <= 0)
{
team2Score++;
roundOver = true;
}
break;
case 2:
team2Left--;
if (team2Left <= 0)
{
team1Score++;
roundOver = true;
}
break;
}
if (roundOver)
{
RpcSyncScore(team1Score, team2Score);
RpcIncreaseGold();
CheckGameOver();
}
}
void CheckGameOver()
{
if(currentRound >= maxRounds)
{
if(team1Score > team2Score)
{
//team 1 won
Debug.Log("Team 1 won");
//GetComponent<NetworkView>().RPC ("DisplayWinner", RPCMode.AllBuffered, "Team 1 has won the match!", 1);
//DisplayWinner ("Team 1 has won the match!");
}
if(team2Score > team1Score)
{
//team 2 won
Debug.Log("Team 2 won");
//GetComponent<NetworkView>().RPC ("DisplayWinner", RPCMode.AllBuffered, "Team 2 has won the match!", 2);
//DisplayWinner ("Team 2 has won the match!");
}
}
else
{
team1Left = 0;
team2Left = 0;
Debug.Log ("Sending rpc call to upgrade");
//GetComponent<NetworkView>().RPC ("Upgrade", RPCMode.AllBuffered);
Invoke("AddPlayers", 10);
RpcUpgrade();
Debug.Log ("RPC call sent");
}
}
[ClientRpc]
void RpcIncreaseGold()
{
SpellCasting sc = this.gameObject.GetComponent<Upgrading>().spellCasting;
sc.gold += 260;
}
[ClientRpc]
void RpcUpgrade()
{
Debug.Log("Rpc call received");
currentRound ++;
state = State.Upgrade;
isUpgrading = true;
timeCounter = 10;
Invoke ("SwapToGame", 10);
}
[ClientRpc]
void RpcSyncScore(int score1, int score2)
{
team1Score = score1;
team2Score = score2;
team1ScoreText.text = team1Score.ToString();
team2ScoreText.text = team2Score.ToString();
}
void DelayedRpcSwapToGame()
{
RpcSwapToGame();
}
[ClientRpc]
void RpcSwapToGame()
{
Debug.Log("Client going to swap to game 1");
SwapToGame();
}
void SwapToGame()
{
Debug.Log("Client going to swap to game 2");
state = State.Game;
isUpgrading = false;
//CmdNewPlayer(gameObject.GetComponent<Upgrading>().spellCasting.team);
//gameObject.GetComponent<Upgrading>().spellCasting.gameObject.GetComponent<NetworkView>().RPC ("StartReset", RPCMode.AllBuffered);
gameObject.GetComponent<Upgrading>().spellCasting.gameObject.GetComponent<DamageSystem>().CmdFullReset();
}
[RPC]
void DisplayWinner(string text, int team)
{
AudioSource.PlayClipAtPoint(winSound, transform.position);
winnerText = text;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class TransferVariables : MonoBehaviour {
public int rounds = 3;
void Start()
{
DontDestroyOnLoad(gameObject);
}
public void SetRounds(string input)
{
rounds = int.Parse(input);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class ArcaneBolt : NetworkBehaviour
{
public float oldSpeed;
public float speed = 50;
public Spell spell;
public GameObject arcaneBoltHit;
public AudioClip cast;
private float arcaneBoltDmgBoost = 1;
private bool arcaneBoltKnockBoost;
private float arcaneBoltHeal = 0;
private bool arcaneBoltCd;
void Start ()
{
oldSpeed = speed;
Vector2 aimPos = ((Spell)gameObject.GetComponent("Spell")).aimPoint;
spell.aimDir = Vector3.Normalize(new Vector3(aimPos.x, aimPos.y) - transform.position);
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
AudioSource.PlayClipAtPoint(cast, transform.position);
if (!isServer)
return;
spell.Invoke("KillSelf", 5);
IncreaseDmgBoost(spell.upgrades.arcaneBoltDmg);
if (spell.upgrades.arcaneBoltKnock > 0)
arcaneBoltKnockBoost = true;
arcaneBoltHeal = spell.upgrades.arcaneBoltHeal * 3;
if (spell.upgrades.arcaneBoltCd > 0)
arcaneBoltCd = true;
}
void Update ()
{
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
}
void IncreaseDmgBoost(int level)
{
if (level > 0)
arcaneBoltDmgBoost = 1.05f + 0.05f * level;
}
void OnTriggerEnter2D(Collider2D other)
{
if (!isServer)
return;
if (other.CompareTag("Player"))
{
DamageSystem damageSystem = (DamageSystem)other.GetComponent("DamageSystem");
if (spell.team != damageSystem.Team())
{
if (!other.GetComponent<SpellCasting>().isShielding && !other.GetComponent<DamageSystem>().invulnerable)
{
int boltHits = 0;
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject player in players)
{
if (player.GetComponent<SpellCasting>().playerName == spell.owner)
{
boltHits = player.GetComponent<SpellCasting>().arcaneBoltResets;
player.GetComponent<SpellCasting>().ArcaneBoltHit(arcaneBoltKnockBoost, arcaneBoltCd);
player.GetComponent<DamageSystem>().Damage(-arcaneBoltHeal, 0, player.transform.position, player.GetComponent<SpellCasting>().playerName);
}
}
float dmgBoost = Mathf.Pow(arcaneBoltDmgBoost, boltHits);
damageSystem.Damage(spell.damage * dmgBoost, spell.knockFactor * dmgBoost, transform.position, spell.owner);
Destroy(gameObject);
GameObject hit = Instantiate(arcaneBoltHit, transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
}
}
}
if (other.CompareTag("Obstacle"))
{
other.SendMessage("Damage", spell.damage, SendMessageOptions.DontRequireReceiver);
Destroy(gameObject);
GameObject hit = Instantiate(arcaneBoltHit, transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
}
else if (other.CompareTag("Spell"))
{
Spell otherSpell = (Spell)other.GetComponent("Spell");
if (spell.team != otherSpell.team && otherSpell.type == Spell.spellType.Projectile)
{
if (spell.destroysSpells)
{
GameObject hit = Instantiate(arcaneBoltHit, transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
Destroy(other.gameObject);
}
if (otherSpell.destroysSpells)
{
GameObject hit = Instantiate(arcaneBoltHit, transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
Destroy(gameObject);
}
}
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine.UI;
using UnityEngine.Networking;
public class SpellCasting : NetworkBehaviour
{
public GameObject blink;
public GameObject fireball;
public GameObject arcaneBolt;
public GameObject corruptingBolt;
public GameObject shield;
public GameObject magmaBlast;
public GameObject hook;
public GameObject bindingShot;
public GameObject iceRang;
public GameObject frostPrison;
public GameObject windWalkShield;
public GameObject healingWard;
public GameObject placedShield;
public GameObject lifeGrip;
GameObject cooldownHandler;
public ArrayList spells = new ArrayList();
[SyncVar]
public int team;
public GameObject mobSpell;
public SpellInfo mob;
public GameObject defSpell;
public SpellInfo def;
public GameObject offSpell1;
public SpellInfo off1;
public GameObject offSpell2;
public SpellInfo off2;
public GameObject offSpell3;
public SpellInfo off3;
public bool isCasting = false;
SpellInfo currentCast;
public bool isHooking = false;
[SyncVar]
public bool isDead = false;
public Texture castBar;
public Texture castBg;
Vector2 aimPoint;
[SyncVar]
public string playerName;
public GameObject nameText;
public GameObject myPortal;
GameObject myName;
float channelTime;
[SyncVar]
bool isChanneling;
GameObject currentPowerUp;
[SyncVar]
public bool isShielding = false;
public float dmgBoost = 1;
public AudioClip troll1;
public AudioClip troll2;
public int gold;
public bool isSilenced = false;
Vector3 holePos = Vector3.zero;
ArrayList holePlayers = new ArrayList();
public float damageDone;
public GoogleAnalyticsV3 analytics;
public int arcaneBoltResets = 0;
private float knockBoost = 1;
private float cooldownSpeed = 1.0f;
[ClientRpc]
public void RpcReset()
{
damageDone = 0;
ResetArcaneBoltResets();
knockBoost = 1;
GlobalConstants.isFrozen = true;
//Silence(6);
myName.GetComponent<TextMesh>().text = playerName;
Invoke ("Unfreeze", 5.0f);
}
void Unfreeze()
{
GlobalConstants.isFrozen = false;
isSilenced = false;
StopCasting();
}
void SetTeam(int newTeam)
{
Invoke ("NewTeam", 1);
team = newTeam;
}
[RPC]
void IncreaseDamageDone(float amount)
{
damageDone += amount;
}
void Start ()
{
if (team == 1)
{
transform.Find("FireGraphics").gameObject.SetActive(true);
}
else
{
transform.Find("IceGraphics").gameObject.SetActive(true);
}
cooldownHandler = GameObject.Find ("CooldownInfo");
spells.Add (blink);
spells.Add (fireball);
spells.Add (shield);
spells.Add (magmaBlast);
spells.Add (hook);
spells.Add (bindingShot);
spells.Add (iceRang);
spells.Add (frostPrison);
spells.Add (windWalkShield);
spells.Add (healingWard);
spells.Add (placedShield);
spells.Add (lifeGrip);
spells.Add(arcaneBolt);
spells.Add(corruptingBolt);
if(isLocalPlayer)
{
playerName = PlayerPrefs.GetString ("Player Name");
CmdUpdateName(playerName);
GameObject camera = GameObject.FindGameObjectWithTag("MainCamera");
CameraScript camScript = camera.GetComponent<CameraScript>();
camScript.PlayerObject = gameObject;
//GetComponent<NetworkView>().RPC ("UpdateName", RPCMode.AllBuffered, playerName);
//spells.Add(blink);
//spells.Add(shield);
//spells.Add(waterwave);
GameObject spellChoices = GameObject.Find("SpellChoices");
if(spellChoices == null)
{
mobSpell = blink;
defSpell = shield;
offSpell1 = fireball;
offSpell2 = bindingShot;
offSpell3 = magmaBlast;
}
else
{
SpellChoices spellC = spellChoices.GetComponent<SpellChoices>();
foreach (GameObject spell in spells)
{
if(spellC.offSpell1 == spell.name)
{
offSpell1 = spell;
}
if(spellC.offSpell2 == spell.name)
{
offSpell2 = spell;
}
if(spellC.offSpell3 == spell.name)
{
offSpell3 = spell;
}
if(spellC.defSpell == spell.name)
{
defSpell = spell;
}
if(spellC.mobSpell == spell.name)
{
mobSpell = spell;
}
}
}
mob = new SpellInfo(mobSpell, 1);
def = new SpellInfo(defSpell, 2);
off1 = new SpellInfo(offSpell1, 3);
off2 = new SpellInfo(offSpell2, 4);
off3 = new SpellInfo(offSpell3, 5);
cooldownHandler.SendMessage ("SetSpell1MaxCD", off1.spellMaxCd);
cooldownHandler.SendMessage ("SetSpell2MaxCD", off2.spellMaxCd);
cooldownHandler.SendMessage ("SetSpell3MaxCD", off3.spellMaxCd);
cooldownHandler.SendMessage ("SetSpell4MaxCD", def.spellMaxCd);
cooldownHandler.SendMessage ("SetSpell5MaxCD", mob.spellMaxCd);
isSilenced = true;
GlobalConstants.isFrozen = true;
Invoke ("ActivateUpgrading", 1);
}
}
void ActivateUpgrading()
{
GameObject handler = GameObject.Find("GameHandler");
handler.GetComponent<Upgrading>().spellCasting = this;
handler.GetComponent<Upgrading>().SetSpellCasting();
//handler.GetComponent<GameHandler>().CmdNewPlayer(team);
}
void Update ()
{
if(isLocalPlayer)
{
UpdateSpell(def);
UpdateSpell(mob);
UpdateSpell(off1);
UpdateSpell(off2);
UpdateSpell(off3);
if (!isDead && !GlobalConstants.isFrozen && GameHandler.state == GameHandler.State.Game)
{
if (isCasting)
{
StartCasting(currentCast);
if (Input.GetKeyDown(KeyCode.LeftControl))
{
StopCasting();
}
}
if (isChanneling)
{
if(isShielding)
{
CmdEndChannelingPowerUp();
return;
}
else
{
channelTime -= Time.deltaTime;
if (channelTime <= 0)
{
CmdFinishChannelingPowerUp();
}
}
}
//if (Input.GetKeyDown(KeyCode.Y))
//{
// GetComponent<NetworkView>().RPC("Troll1", RPCMode.All);
//}
//if (Input.GetKeyDown(KeyCode.U))
//{
// GetComponent<NetworkView>().RPC("Troll2", RPCMode.All);
//}
}
cooldownHandler.SendMessage ("SetSpell1CD", off1.spellCd);
cooldownHandler.SendMessage ("SetSpell2CD", off2.spellCd);
cooldownHandler.SendMessage ("SetSpell3CD", off3.spellCd);
cooldownHandler.SendMessage ("SetSpell4CD", def.spellCd);
cooldownHandler.SendMessage ("SetSpell5CD", mob.spellCd);
}
}
void IsShielding()
{
isShielding = true;
}
[ClientRpc]
public void RpcSilence(float duration)
{
if(currentCast != null)
{
isSilenced = true;
StopCasting ();
Invoke("StopSilence", duration);
}
}
void StopSilence()
{
isSilenced = false;
}
public void StopShielding()
{
isShielding = false;
}
[ClientRpc]
public void RpcStartChannelingPowerUp(GameObject powerUp, float duration)
{
Debug.Log("Starting channel for a character");
if (isChanneling || isCasting)
return;
Debug.Log("Passed return point");
channelTime = duration;
isChanneling = true;
currentPowerUp = powerUp;
}
[Command]
void CmdFinishChannelingPowerUp()
{
if(currentPowerUp != null)
{
currentPowerUp.SendMessage("Capped", gameObject);
}
RpcEndChannelingPowerUp();
}
[Command]
public void CmdEndChannelingPowerUp()
{
RpcEndChannelingPowerUp();
}
[ClientRpc]
public void RpcEndChannelingPowerUp()
{
isChanneling = false;
currentPowerUp = null;
}
[ClientRpc]
public void RpcDamageBoost(float boost, float duration)
{
if (!isLocalPlayer)
return;
dmgBoost *= boost;
Invoke ("EndDmgBoost", duration);
}
void EndDmgBoost()
{
dmgBoost = 1;
}
public void UpdateSpell(SpellInfo spell)
{
spell.spellCd -= Time.deltaTime * cooldownSpeed;
if(Input.GetAxis("Spell" + spell.slot) > 0.1f && !isCasting && !isDead && !isSilenced)
{
if(isChanneling)
{
CmdEndChannelingPowerUp();
}
if(spell.spellCd <= 0)
{
isCasting = true;
currentCast = spell;
aimPoint = new Vector2((int)Input.mousePosition.x, (int)Input.mousePosition.y);
}
}
}
public void StartCasting(SpellInfo spell)
{
spell.castTime -= Time.deltaTime;
if(spell.castTime <= 0)
{
spell.castTime = spell.totalCastTime;
spell.spellCd = spell.spellMaxCd;
isCasting = false;
Cast (spell.spellName);
}
}
public void StopCasting()
{
isCasting = false;
if(currentCast != null)
currentCast.castTime = currentCast.totalCastTime;
}
void OnGUI()
{
if(isCasting && GameHandler.state == GameHandler.State.Game)
{
float castProgress = 1 - (currentCast.castTime / currentCast.totalCastTime);
Vector3 playerPos = Camera.main.WorldToScreenPoint(new Vector3(transform.position.x, transform.position.y, 0));
GUI.DrawTexture (new Rect(playerPos.x - 25, Screen.height - playerPos.y - 45, 50, 8), castBg);
GUI.DrawTexture (new Rect(playerPos.x - 24, Screen.height - playerPos.y - 44, castProgress * 48, 6), castBar);
}
if(isLocalPlayer && isChanneling && GameHandler.state == GameHandler.State.Game)
{
float castProgress = 1 - (channelTime / 4);
Vector3 playerPos = Camera.main.WorldToScreenPoint(new Vector3(transform.position.x, transform.position.y, 0));
GUI.DrawTexture (new Rect(playerPos.x - 50, Screen.height - playerPos.y - 45, 100, 8), castBg);
GUI.DrawTexture (new Rect(playerPos.x - 49, Screen.height - playerPos.y - 44, castProgress * 98, 6), castBar);
}
}
void Cast(string spell)
{
if(spell != null && isLocalPlayer)
{
Vector3 aim = Camera.main.ScreenToWorldPoint (new Vector3((int)Input.mousePosition.x, (int)Input.mousePosition.y, 0));
Debug.Log("I cast: " + spell);
CmdCastSpell(spell, playerName, team, aim.x, aim.y, dmgBoost);
//GetComponent<NetworkView>().RPC ("CastSpell", RPCMode.All, spell, playerName, team, aim.x, aim.y, dmgBoost, Network.AllocateViewID());
}
}
[Command]
void CmdCastSpell(string spell, string owner, int spellTeam, float aimPointX, float aimPointY, float damageBoost)
{
if(spell != null)
{
GameObject whichSpell = null;
foreach(GameObject s in spells)
{
if(s.name == spell)
{
whichSpell = s;
}
}
if(whichSpell != null)
{
GameObject newSpell = Instantiate(whichSpell, transform.position, transform.rotation);
Spell spellScript = (Spell)newSpell.GetComponent<Spell>();
spellScript.owner = owner;
spellScript.team = spellTeam;
spellScript.damage *= damageBoost;
spellScript.knockFactor *= damageBoost;
spellScript.knockFactor *= knockBoost;
if(knockBoost > 1)
{
Debug.Log("Using knock boost");
knockBoost = 1;
}
spellScript.aimPoint = new Vector2(aimPointX, aimPointY);
spellScript.upgrades = GetComponent<Upgrades>();
NetworkServer.Spawn(newSpell);
}
}
}
[ClientRpc]
public void RpcDead()
{
isDead = true;
StopCasting();
myName.GetComponent<TextMesh>().text = "";
}
public void Spawned()
{
isDead = false;
}
[Command]
void CmdUpdateName(string name)
{
Debug.Log ("Updating name!");
playerName = name;
GameObject canvas = GameObject.Find ("Canvas");
GameObject newText = Instantiate(nameText, Vector3.zero, Quaternion.identity);
newText.GetComponent<FollowObject>().target = gameObject;
newText.GetComponent<FollowObject>().text = name;
myName = newText;
NetworkServer.Spawn(newText);
Invoke("SyncNames", 1);
}
void SyncNames()
{
RpcSyncNames();
}
[ClientRpc]
void RpcSyncNames()
{
Debug.Log("Trying to sync name to: " + playerName);
GameObject[] names = GameObject.FindGameObjectsWithTag("PlayerName");
foreach (GameObject n in names)
{
Debug.Log("This contains: " + n.GetComponent<FollowObject>().text);
if (n.GetComponent<FollowObject>().text.Equals(playerName))
{
Debug.Log("Found someone to sync name with");
myName = n;
}
}
}
public void Invis()
{
myName.GetComponent<TextMesh>().text = "";
}
public void EndInvis()
{
myName.GetComponent<TextMesh>().text = playerName;
}
[RPC]
public void UpdateTeam(int newTeam)
{
Debug.Log ("Updating team to: " + newTeam);
team = newTeam;
}
[RPC]
public void Troll1()
{
AudioSource.PlayClipAtPoint(troll1, transform.position);
}
[RPC]
public void Troll2()
{
AudioSource.PlayClipAtPoint(troll2, transform.position);
}
public void ArcaneBoltHit(bool hasKnockBoost, bool hasCd)
{
if (hasCd)
{
RpcLowerAllCds(0.1f);
}
if (arcaneBoltResets == 2)
{
if (hasKnockBoost)
{
knockBoost = 1.5f;
Debug.Log("Knock boost activated");
}
}
if (arcaneBoltResets < 2)
{
arcaneBoltResets++;
RpcLowerCd("ArcaneBolt", 10);
if(arcaneBoltResets == 2)
{
Invoke("ResetArcaneBoltResets", 7);
}
}
}
void ResetArcaneBoltResets()
{
arcaneBoltResets = 0;
}
[ClientRpc]
public void RpcLowerCd(string spellName, float amount)
{
if (!isLocalPlayer)
return;
if (mob.spellName == spellName)
{
mob.spellCd -= amount;
}
else if (def.spellName == spellName)
{
def.spellCd -= amount;
}
else if (off1.spellName == spellName)
{
off1.spellCd -= amount;
}
else if (off2.spellName == spellName)
{
off2.spellCd -= amount;
}
else if (off3.spellName == spellName)
{
off3.spellCd -= amount;
}
}
[ClientRpc]
public void RpcLowerAllCds(float amount)
{
mob.spellCd -= mob.spellMaxCd * amount;
def.spellCd -= def.spellMaxCd * amount;
off1.spellCd -= off1.spellMaxCd * amount;
off2.spellCd -= off2.spellMaxCd * amount;
off3.spellCd -= off3.spellMaxCd * amount;
}
[ClientRpc]
public void RpcCdSpeed(float amount, float duration)
{
cooldownSpeed *= amount;
CancelInvoke("ResetCdSpeed");
Invoke("ResetCdSpeed", duration);
}
public void ResetCdSpeed()
{
cooldownSpeed = 1.0f;
}
[RPC]
public void LowerCd(float amount)
{
mob.spellCd -= 5;
def.spellCd -= 5;
off1.spellCd -= 5;
off2.spellCd -= 5;
off3.spellCd -= 5;
/*
CooldownInfo cd = GameObject.Find ("CooldownInfo").GetComponent<CooldownInfo>();
System.Type t = cd.GetType();
FieldInfo[] fields = t.GetFields();
foreach(FieldInfo f in fields)
{
if(f.Name.Equals("spell1MaxCD"))
{
f.SetValue(cd, (float)f.GetValue(cd) - 4);
}
if(f.Name.Equals("spell2MaxCD"))
{
f.SetValue(cd, (float)f.GetValue(cd) - 4);
}
if(f.Name.Equals("spell3MaxCD"))
{
f.SetValue(cd, (float)f.GetValue(cd) - 4);
}
if(f.Name.Equals("spell4MaxCD"))
{
f.SetValue(cd, (float)f.GetValue(cd) - 4);
}
if(f.Name.Equals("spell5MaxCD"))
{
f.SetValue(cd, (float)f.GetValue(cd) - 4);
}
}
*/
}
}
public class SpellInfo
{
public GameObject spell;
public string spellName;
public Spell spellScript;
public float castTime;
public float totalCastTime;
public float spellCd;
public float spellMaxCd;
public int slot;
public enum spellType { Projectile, Area, Other };
public spellType type;
public SpellInfo(GameObject s, int slotNumber)
{
spell = s;
slot = slotNumber;
spellScript = (Spell)spell.GetComponent("Spell");
totalCastTime = spellScript.castTime;
castTime = totalCastTime;
spellMaxCd = spellScript.cooldown;
spellCd = 0;
spellName = s.name;
type = (spellType) spellScript.type;
}
public void UpdateCd(float newCd)
{
spellMaxCd = newCd;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class DamageBoost : NetworkBehaviour {
bool someoneCapping = false;
public GameObject effect;
void OnTriggerStay2D(Collider2D other)
{
if (!isServer)
return;
if(other.CompareTag("Player"))
{
other.GetComponent<SpellCasting>().RpcStartChannelingPowerUp(gameObject, 4);
}
}
void OnTriggerExit2D(Collider2D other)
{
if (!isServer)
return;
if(other.CompareTag("Player"))
{
other.GetComponent<SpellCasting>().RpcEndChannelingPowerUp();
}
}
void Capped(GameObject player)
{
if (!isServer)
return;
player.GetComponent<DamageSystem>().Damage(-15, 0, transform.position, "world");
player.GetComponent<SpellCasting>().RpcDamageBoost(1.5f, 8f);
var newEffect = Instantiate(effect);
newEffect.GetComponent<FollowPlayer>().SetFollow(player, 8f);
NetworkServer.Spawn(newEffect);
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
foreach(GameObject p in players)
{
p.GetComponent<SpellCasting>().RpcEndChannelingPowerUp();
}
Destroy(gameObject);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class IceRangHit : MonoBehaviour {
public AudioClip explo;
// Use this for initialization
void Start () {
Invoke ("KillSelf", 0.75f);
AudioSource.PlayClipAtPoint(explo, transform.position);
}
// Update is called once per frame
void Update () {
}
void KillSelf()
{
GameObject.Destroy(gameObject);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class IceRang : MonoBehaviour
{
public float speed = 50;
private float oldSpeed;
public Spell spell;
public GameObject fireballExplo;
public AudioClip cast;
public Vector3 startPos;
public float journeyTime = 0.5F;
private float startTime;
float slowAmount = 1;
float startDist;
Vector3 aimPoint;
bool hasTurned = false;
Vector3 dir;
float arcAmount;
bool bounces;
// Use this for initialization
void Start () {
oldSpeed = speed;
spell.SetColor();
Vector2 aimPos = ((Spell)gameObject.GetComponent("Spell")).aimPoint;
spell.aimDir = Vector3.Normalize(new Vector3(aimPos.x, aimPos.y) - transform.position);
aimPoint = new Vector3(spell.aimPoint.x, spell.aimPoint.y, 0);
//transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed;
spell.Invoke ("KillSelf", 6);
AudioSource.PlayClipAtPoint(cast, transform.position);
startTime = Time.time;
startPos = transform.position;
Vector3 dirBetween = startPos - aimPoint;
float distance = Vector3.Distance(startPos, aimPoint);
float angle = Mathf.Atan2(dirBetween.y, dirBetween.x) * Mathf.Rad2Deg;
float startRot = -40;
startDist = distance;
//spell.aimDir = GlobalConstants.RotateZ(spell.aimDir, Mathf.Deg2Rad * startRot);
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle + 90));
journeyTime = distance/7.5f;
if(distance <= 5)
{
arcAmount = 3f;
}
else
{
arcAmount = (distance / Mathf.Pow(distance, 2) * 4);
}
if(GetComponent<NetworkView>().isMine)
{
Upgrading upgrading = GameObject.Find ("GameHandler").GetComponent<Upgrading>();
if(upgrading.iceRangDmg.currentLevel > 0)
{
GetComponent<NetworkView>().RPC ("IncreaseDmg", RPCMode.All, upgrading.iceRangDmg.currentLevel);
if(upgrading.iceRangBounce.currentLevel > 0)
{
GetComponent<NetworkView>().RPC ("ActivateBounce", RPCMode.All);
}
}
if(upgrading.iceRangSlow.currentLevel > 0)
{
GetComponent<NetworkView>().RPC ("IncreaseSlow", RPCMode.All, upgrading.iceRangSlow.currentLevel);
}
}
}
[RPC]
void IncreaseSlow(int level)
{
slowAmount -= 0.15f * level;
}
[RPC]
void ActivateBounce()
{
bounces = true;
}
[RPC]
void IncreaseDmg(int level)
{
spell.damage += 0.75f * level;
spell.knockFactor += 0.7f * level;
}
// Update is called once per frame
void Update ()
{
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
}
void OldStuff()
{
//time += Time.deltaTime / 10;
//transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed;
//Debug.Log (Vector3.Slerp (spell.aimDir, -spell.aimDir, time));
//transform.position += Vector3.Slerp (spell.aimDir, -spell.aimDir, time) * Time.deltaTime;
//transform.position += transform.right * Mathf.Sin (time);
if(!hasTurned)
{
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
spell.aimDir = Vector3.RotateTowards(spell.aimDir, Vector3.Normalize(aimPoint - transform.position), arcAmount * Mathf.Deg2Rad, 1);
arcAmount += (2.4f / startDist) / Vector3.Distance(transform.position, aimPoint);
if(Vector3.Distance(transform.position, aimPoint) < 0.6f)
{
//Debug.Log ("Turntime");
hasTurned = true;
}
/*
Vector3 center = (startPos + aimPoint) * 0.5F;
center -= arcAmount * transform.right;
Vector3 riseRelCenter = startPos - center;
Vector3 setRelCenter = aimPoint - center;
float fracComplete = (Time.time - startTime) / journeyTime;
transform.position = Vector3.Slerp(riseRelCenter, setRelCenter, fracComplete);
transform.position += center;
if(Vector3.Distance(transform.position, aimPoint) < 0.1f)
{
hasTurned = true;
startTime = Time.time;
}
*/
}
else
{
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
spell.aimDir = Vector3.RotateTowards(spell.aimDir, Vector3.Normalize(startPos - transform.position), arcAmount * Mathf.Deg2Rad, 1);
//arcAmount -= Vector3.Distance(transform.position, startPos) / 10;
if(Vector3.Distance(transform.position, startPos) < 0.6f)
{
if(GetComponent<NetworkView>().isMine)
{
Network.Destroy(gameObject);
}
}
/*
Vector3 center = (startPos + aimPoint) * 0.5F;
center += arcAmount * transform.right;
Vector3 riseRelCenter = startPos - center;
Vector3 setRelCenter = aimPoint - center;
float fracComplete = (Time.time - startTime) / journeyTime;
transform.position = Vector3.Slerp(setRelCenter, riseRelCenter, fracComplete);
transform.position += center;
*/
}
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.CompareTag("Player"))
{
DamageSystem damageSystem = (DamageSystem)other.GetComponent ("DamageSystem");
if(spell.team != damageSystem.Team())
{
if(other.GetComponent<NetworkView>().isMine && !other.GetComponent<SpellCasting>().isShielding)
{
damageSystem.Damage(spell.damage, spell.knockFactor, transform.position, spell.owner);
//other.GetComponent<Movement>().SpeedBoost(slowAmount, 3);
//Implement bouncing
Network.Destroy (gameObject);
Network.Instantiate(fireballExplo, this.transform.position, Quaternion.identity, 0);
}
}
}
if(other.CompareTag ("Obstacle"))
{
if(!hasTurned)
{
other.attachedRigidbody.AddForce (spell.aimDir * spell.knockFactor * 400);
}
else
{
other.attachedRigidbody.AddForce (-spell.aimDir * spell.knockFactor * 400);
}
other.SendMessage("Damage", spell.damage);
if(GetComponent<NetworkView>().isMine)
{
Network.Destroy (gameObject);
Network.Instantiate(fireballExplo, this.transform.position, Quaternion.identity, 0);
}
}
else if(other.CompareTag ("Spell"))
{
if(GetComponent<NetworkView>().isMine)
{
Spell otherSpell = (Spell)other.GetComponent("Spell");
if(spell.team != otherSpell.team)
{
if(other.name == "NewShield(Clone)")
{
Debug.Log ("Hit a shield");
//Network.Destroy (gameObject);
//Network.Instantiate(fireballExplo, this.transform.position, Quaternion.identity, 0);
}
else if(otherSpell.destroysSpells)
{
Network.Destroy (gameObject);
Network.Instantiate(fireballExplo, this.transform.position, Quaternion.identity, 0);
}
}
}
else
{
Debug.Log("Not a spell");
}
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class CorruptingBolt : NetworkBehaviour
{
public float oldSpeed;
public float speed = 50;
public Spell spell;
public GameObject boltHit;
public AudioClip cast;
public GameObject dotEffect;
public float dotDamage;
public float duration;
public float amplifyAmount = 1.25f;
public float longerCdsAmount = 0.2f;
public float blastAoe = 2.0f;
private float damageReduc = 0.0f;
private bool longerCds;
private int amplifyCount = 0;
private bool blast;
void Start()
{
oldSpeed = speed;
//spell.SetColor();
Vector2 aimPos = ((Spell)gameObject.GetComponent("Spell")).aimPoint;
spell.aimDir = Vector3.Normalize(new Vector3(aimPos.x, aimPos.y) - transform.position);
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
AudioSource.PlayClipAtPoint(cast, transform.position);
if (!isServer)
return;
spell.Invoke("KillSelf", 5);
damageReduc = spell.upgrades.corruptingBoltDmgRed * 0.1f;
longerCds = spell.upgrades.corruptingBoltCd > 0;
amplifyCount = spell.upgrades.corruptingBoltAmplify;
blast = spell.upgrades.corruptingBoltBlast > 0;
}
void Update()
{
transform.position += new Vector3(spell.aimDir.x, spell.aimDir.y) / GlobalConstants.unitScaling * speed * Time.deltaTime * 60;
}
void OnTriggerEnter2D(Collider2D other)
{
if (!isServer)
return;
if (other.CompareTag("Player"))
{
DamageSystem damageSystem = (DamageSystem)other.GetComponent("DamageSystem");
if (spell.team != damageSystem.Team())
{
if (!other.GetComponent<SpellCasting>().isShielding && !other.GetComponent<DamageSystem>().invulnerable)
{
if (blast)
{
Blast();
}
else
{
damageSystem.AddDot(dotDamage, duration + 0.1f, 1.0f, spell.owner, dotEffect);
other.GetComponent<SpellCasting>().RpcDamageBoost(1.0f - damageReduc, duration);
if (longerCds)
other.GetComponent<SpellCasting>().RpcCdSpeed(1.0f - longerCdsAmount, duration);
if (amplifyCount > 0)
damageSystem.DirectDamageAmp(amplifyAmount, amplifyCount, duration);
}
GameObject hit = Instantiate(boltHit, transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
Destroy(gameObject);
}
}
}
if (other.CompareTag("Obstacle"))
{
if (blast)
{
Blast();
}
GameObject hit = Instantiate(boltHit, transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
Destroy(gameObject);
}
else if (other.CompareTag("Spell"))
{
Spell otherSpell = (Spell)other.GetComponent("Spell");
if (spell.team != otherSpell.team && otherSpell.type == Spell.spellType.Projectile)
{
if (spell.destroysSpells)
{
GameObject hit = Instantiate(boltHit, transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
Destroy(other.gameObject);
}
if (otherSpell.destroysSpells)
{
if (blast)
{
Blast();
}
GameObject hit = Instantiate(boltHit, transform.position, Quaternion.identity);
NetworkServer.Spawn(hit);
Destroy(gameObject);
}
}
}
}
void Blast()
{
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject player in players)
{
DamageSystem dmgSys = player.GetComponent<DamageSystem>();
if (spell.team != dmgSys.Team() && !dmgSys.isDead)
{
if (Vector3.Distance(player.transform.position, gameObject.transform.position) < blastAoe)
{
dmgSys.AddDot(dotDamage, duration + 0.1f, 1.0f, spell.owner, dotEffect);
}
if (amplifyCount > 0)
dmgSys.DirectDamageAmp(amplifyAmount, amplifyCount, duration);
}
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine.UI;
using System;
public class Upgrading : MonoBehaviour {
#region UpgradeInfo
public UpgradeInfo fireballDot;
public UpgradeInfo fireballFinalBlast;
public UpgradeInfo fireballDmg;
public UpgradeInfo fireballCd;
public UpgradeInfo healingDispel;
public UpgradeInfo healingDispelHeal;
public UpgradeInfo healingDuration;
public UpgradeInfo healingDamageReduct;
public UpgradeInfo healingDmg;
public UpgradeInfo healingLifesteal;
public UpgradeInfo healingBloom;
public UpgradeInfo healingBurst;
public UpgradeInfo magmaBlastCd;
public UpgradeInfo magmaBlastSelfDispel;
public UpgradeInfo magmaBlastBlackhole;
public UpgradeInfo magmaBlastDmg;
public UpgradeInfo magmaBlastAmplify;
public UpgradeInfo iceRangSlow;
public UpgradeInfo iceRangCd;
public UpgradeInfo iceRangCd2;
public UpgradeInfo iceRangDmg;
public UpgradeInfo iceRangBounce;
public UpgradeInfo bindingDuration;
public UpgradeInfo bindingSilence;
public UpgradeInfo bindingLength;
public UpgradeInfo bindingAmplify;
public UpgradeInfo frostPrisonHealth;
public UpgradeInfo frostPrisonReflect;
public UpgradeInfo frostPrisonDuration;
public UpgradeInfo frostPrisonCircleWall;
public UpgradeInfo frostPrisonRamp;
public UpgradeInfo frostPrisonStorm;
public UpgradeInfo shieldAmp;
public UpgradeInfo shieldAim;
public UpgradeInfo shieldCd;
public UpgradeInfo shieldAbsorb;
public UpgradeInfo windShieldDuration;
public UpgradeInfo windShieldDamage;
public UpgradeInfo windShieldCd;
public UpgradeInfo windShieldInvis;
public UpgradeInfo hookDmg;
public UpgradeInfo hookPull;
public UpgradeInfo hookCd;
public UpgradeInfo hookInvu;
public UpgradeInfo blinkDmg;
public UpgradeInfo blinkThrust;
public UpgradeInfo blinkCd;
public UpgradeInfo blinkInstant;
public UpgradeInfo placedShieldKnockImmune;
public UpgradeInfo placedShieldAmp;
public UpgradeInfo placedShieldCd;
public UpgradeInfo placedShieldSpeed;
public UpgradeInfo lifeGripCd;
public UpgradeInfo lifeGripShield;
public UpgradeInfo arcaneBoltDmg;
public UpgradeInfo arcaneBoltKnock;
public UpgradeInfo arcaneBoltHeal;
public UpgradeInfo arcaneBoltCd;
public UpgradeInfo corruptingBoltDmgRed;
public UpgradeInfo corruptingBoltCd;
public UpgradeInfo corruptingBoltAmplify;
public UpgradeInfo corruptingBoltBlast;
#endregion
CooldownInfo cd = null;
public SpellCasting spellCasting = null;
List<SpellInfo> spells = new List<SpellInfo>();
public Texture2D background;
//public Texture button;
public GUIStyle button;
public GUIStyle tooltip;
int spellcastSet = 0;
string names = "";
public bool isUpgrading;
public Text goldText;
//public dfLabel goldText;
void SetShit ()
{
spellcastSet = 1;
#region Fireball
fireballDot = new UpgradeInfo("Damage \n over \n Time", 3, 40, null, button);
fireballDot.tooltip = "Increases damage per second by 0.1/0.2/0.3, and duration by 0.5/1/1.5 (Total dot damage increases by 1.15/2.4/3.75)";
fireballFinalBlast = new UpgradeInfo("Final blast", 1, 120, fireballDot, button);
fireballFinalBlast.tooltip = "When the fireball DoT ends, deals a final 5 damage (this can be lethal)";
fireballDmg = new UpgradeInfo("Damage", 3, 40, null, button);
fireballDmg.tooltip = "Increases damage by 1/2/3 and knock factor by 0.8/1.6/2.4";
fireballCd = new UpgradeInfo("Cone", 1, 120, fireballDmg, button);
fireballCd.tooltip = "Shoots two additional smaller fireballs with half damage in a cone";
fireballDot.relative = fireballDmg;
fireballDmg.relative = fireballDot;
#endregion
#region Healing
#region inactive
healingDispel = new UpgradeInfo("Dispel", 1, 120, null, button);
healingDispel.tooltip = "Your healing spell can now dispels negative effects from your teammates and some positive effects from opponents";
healingDispelHeal = new UpgradeInfo("Dispel \n self \n heal", 1, 80, healingDispel, button);
healingDispelHeal.tooltip = "When successfully dispelling something, you now heal yourself for 18 health over 3 seconds";
healingDmg = new UpgradeInfo("Damage", 3, 40, null, button);
healingDmg.tooltip = "Your healing spell can now place a DoT on enemy players, dealing 6/12/18 damage over 3 seconds";
healingLifesteal = new UpgradeInfo("Lifesteal", 1, 80, healingDmg, button);
healingLifesteal.tooltip = "Your healing spell DoT effect heals you for 50% of the damage dealt";
#endregion
healingDuration = new UpgradeInfo("Duration", 3, 40, null, button);
healingDuration.tooltip = "Increases duration of heal by 0.7/1.4/2.1 seconds (total heal 26/31/36)";
healingDamageReduct = new UpgradeInfo("Damage \n reduction", 1, 120, healingDuration, button);
healingDamageReduct.tooltip = "Reduces damage taken on targets with the heal by 50%";
healingBloom = new UpgradeInfo("Bloom Time", 3, 40, null, button);
healingBloom.tooltip = "Heal now blooms in 0.5/0.3/0.1 seconds";
healingBurst = new UpgradeInfo("Instant", 1, 120, healingBloom, button);
healingBurst.tooltip = "Now instantly heals the targets for 32 health";
healingDuration.relative = healingBloom;
healingBloom.relative = healingDuration;
healingDispel.relative = healingDmg;
healingDmg.relative = healingDispel;
healingDmg.relative = healingDuration;
#endregion Healing
#region Magma Blast
#region Inactive
magmaBlastSelfDispel = new UpgradeInfo("Self-Dispel", 1, 80, magmaBlastCd, button);
magmaBlastSelfDispel.tooltip = "Dispels all negative effects from you on completion of cast";
#endregion
magmaBlastCd = new UpgradeInfo("Cooldown", 3, 40, null, button);
magmaBlastCd.tooltip = "Decreases magma blast cooldown by 0.35/0.7/1.05";
magmaBlastBlackhole = new UpgradeInfo("Gravity", 1, 120, magmaBlastCd, button);
magmaBlastBlackhole.tooltip = "Magma blast is now channeled for 2 seconds, and instead of knocking players away, it pulls them toward you.";
magmaBlastDmg = new UpgradeInfo("Damage", 3, 40, null, button);
magmaBlastDmg.tooltip = "Increases damage by 1.5/3/4.5";
magmaBlastAmplify = new UpgradeInfo("Strength", 1, 120, magmaBlastDmg, button);
magmaBlastAmplify.tooltip = "Increases knock factor by 3";
magmaBlastCd.relative = magmaBlastDmg;
magmaBlastDmg.relative = magmaBlastCd;
#endregion
#region IceRang
iceRangDmg = new UpgradeInfo("Damage", 3, 40, null, button);
iceRangDmg.tooltip = "Increases damage by 0.75/1.5/2.25";
iceRangBounce = new UpgradeInfo("Bounce", 1, 120, iceRangSlow, button);
iceRangBounce.tooltip = "Ice-rang now bounces";
iceRangSlow = new UpgradeInfo("Slow", 3, 40, null, button);
iceRangSlow.tooltip = "Now slows by 15/30/45 percent for 3 seconds";
iceRangCd = new UpgradeInfo("Cooldown", 1, 120, iceRangDmg, button);
iceRangCd.tooltip = "Decreases cooldown by 1.5 seconds";
iceRangCd2 = new UpgradeInfo("Cooldown", 1, 120, iceRangSlow, button);
iceRangCd2.tooltip = "Decreases cooldown by 1.5 seconds";
iceRangSlow.relative = iceRangDmg;
iceRangDmg.relative = iceRangSlow;
#endregion
#region Binding Shot
bindingDuration = new UpgradeInfo("Duration", 2, 60, null, button);
bindingDuration.tooltip = "Increases duration by 0.5/1";
bindingSilence = new UpgradeInfo("Silence", 1, 120, bindingDuration, button);
bindingSilence.tooltip = "Silences for 1.5 seconds";
bindingLength = new UpgradeInfo("Leash length", 2, 60, null, button);
bindingLength.tooltip = "Decreases leash length by 25%/50%";
bindingAmplify = new UpgradeInfo("Damage amplify", 1, 120, bindingDuration, button);
bindingAmplify.tooltip = "Amplifies damage taken by 35%";
bindingDuration.relative = bindingLength;
bindingLength.relative = bindingDuration;
#endregion
#region Frost Prison
#region Inactive
frostPrisonHealth = new UpgradeInfo("Indestructible", 1, 120, null, button);
frostPrisonHealth.tooltip = "Frost Prison is now indestructible";
frostPrisonReflect = new UpgradeInfo("Reflects", 1, 120, frostPrisonHealth, button);
frostPrisonReflect.tooltip = "Reflects projectiles";
#endregion
frostPrisonDuration = new UpgradeInfo("Duration", 2, 60, null, button);
frostPrisonDuration.tooltip = "Duration increased by 0.5/1 seconds (damage remains the same)";
frostPrisonCircleWall = new UpgradeInfo("Circle", 1, 120, frostPrisonDuration, button);
frostPrisonCircleWall.tooltip = "Adds an extra wall and decreases the form time to 0.4 seconds, but no longer removes damage";
frostPrisonRamp = new UpgradeInfo("Damage Ramp", 2, 60, null, button);
frostPrisonRamp.tooltip = "Damage starts at 0.235/0.27 instead of 0.2";
frostPrisonStorm = new UpgradeInfo("Glacial Storm", 1, 120, frostPrisonRamp, button);
frostPrisonStorm.tooltip = "No longer has walls, instead slows and deals additional damage";
frostPrisonDuration.relative = frostPrisonRamp;
frostPrisonRamp.relative = frostPrisonDuration;
#endregion
#region Reflect Shield
shieldAmp = new UpgradeInfo("Amplify", 3, 40, null, button);
shieldAmp.tooltip = "Reflect amplifies by 10/20/30 percent";
shieldAim = new UpgradeInfo("Aim\nreflection", 1, 120, shieldAmp, button);
shieldAim.tooltip = "Allows you to aim where the reflection should go";
shieldCd = new UpgradeInfo("Cooldown", 3, 40, null, button);
shieldCd.tooltip = "Cooldown decreased by 0.5/1/1.5";
shieldAbsorb = new UpgradeInfo("Absorb", 2, 80, shieldCd, button);
shieldAbsorb.tooltip = "No longer reflects, instead absorbs and heals for 50/100% of the damage dealt";
shieldAmp.relative = shieldCd;
shieldCd.relative = shieldAmp;
#endregion
#region Invisibility shield
windShieldDuration = new UpgradeInfo("Duration", 2, 60, null, button);
windShieldDuration.tooltip = "Increases duration of shield and invisibility by 0.5/1 seconds";
windShieldDamage = new UpgradeInfo("Damage boost", 1, 120, windShieldDuration, button);
windShieldDamage.tooltip = "Increases damage of spells cast while invis by 35%";
windShieldCd = new UpgradeInfo("Cooldown", 3, 40, null, button);
windShieldCd.tooltip = "Cooldown decreased by 0.5/1/1.5";
windShieldInvis = new UpgradeInfo("Instant Invisibility", 1, 120, windShieldInvis, button);
windShieldInvis.tooltip = "No longer shields, instead becomes instantly invisible and can no longer be hit by spells while invisible";
windShieldCd.relative = windShieldDuration;
windShieldDuration.relative = windShieldCd;
#endregion
#region Placed Shield
placedShieldAmp = new UpgradeInfo("Damage amplification", 3, 40, null, button);
placedShieldAmp.tooltip = "Amplifies damage dealt by friendly targets in shield by 10/20/30%";
placedShieldKnockImmune = new UpgradeInfo("Knockback Immunity", 1, 120, placedShieldCd, button);
placedShieldKnockImmune.tooltip = "Friendly targets in shield can no longer be knocked";
placedShieldCd = new UpgradeInfo("Cooldown", 3, 40, null, button);
placedShieldCd.tooltip = "Decreases cooldown by 1.5/3/4.5";
placedShieldSpeed = new UpgradeInfo("Speed boost", 1, 120, placedShieldAmp, button);
placedShieldSpeed.tooltip = "Increase speed of friendly targets in the sphere by 100%";
placedShieldAmp.relative = placedShieldCd;
placedShieldCd.relative = placedShieldAmp;
#endregion
#region Hook
hookDmg = new UpgradeInfo("Damage", 3, 40, null, button);
hookDmg.tooltip = "Increases damage by 1.5/3/4.5";
hookPull = new UpgradeInfo("Reverse hook", 1, 120, hookDmg, button);
hookPull.tooltip = "Now pulls the target to you, instead of the other way around. Also increases damage by 2.5";
hookCd = new UpgradeInfo("Cooldown", 3, 40, null, button);
hookCd.tooltip = "Cooldown decreased by 0.5/1/1.5";
hookInvu = new UpgradeInfo("Invulnerability", 1, 120, hookCd, button);
hookInvu.tooltip = "Now invulnerable while being pulled";
hookCd.relative = hookDmg;
hookDmg.relative = hookCd;
#endregion
#region Blink
blinkDmg = new UpgradeInfo("Damage", 3, 40, null, button);
blinkDmg.tooltip = "Increases damage to 7/9/11";
blinkThrust = new UpgradeInfo("Thrust", 1, 120, blinkDmg, button);
blinkThrust.tooltip = "Now rushes forward, no longer invulnerable but knocking back on collision";
blinkCd = new UpgradeInfo("Cooldown", 3, 40, null, button);
blinkCd.tooltip = "Cooldown decreased by 0.5/1/1.5";
blinkInstant = new UpgradeInfo("Instant", 1, 120, blinkCd, button);
blinkInstant.tooltip = "Cast time is now instant";
blinkCd.relative = blinkDmg;
blinkDmg.relative = blinkCd;
#endregion
#region Life Grip
lifeGripCd = new UpgradeInfo("Cooldown", 3, 40, null, button);
lifeGripCd.tooltip = "Cooldown decreased by 0.5/1/1.5";
lifeGripShield = new UpgradeInfo("Absorb Shield", 1, 120, lifeGripCd, button);
lifeGripShield.tooltip = "Gripped allies get a shield that absorbs 20 damage for 3 seconds";
lifeGripCd.relative = bindingLength;
#endregion
#region Arcane Bolt
arcaneBoltDmg = new UpgradeInfo("Damage", 3, 40, null, button);
arcaneBoltDmg.tooltip = "Hitting an arcane bolt increases the damage for the next arcane bolt by 10/15/20% (this stacks up to two times)";
arcaneBoltKnock = new UpgradeInfo("Knockback", 1, 120, arcaneBoltDmg, button);
arcaneBoltKnock.tooltip = "Hitting all three arcane bolts in a row increases the knockback of your next spell by 50%";
arcaneBoltHeal = new UpgradeInfo("Self heal", 3, 40, null, button);
arcaneBoltHeal.tooltip = "Hitting an arcane bolt heals you for 3/6/9 health";
arcaneBoltCd = new UpgradeInfo("Cooldown", 1, 120, arcaneBoltHeal, button);
arcaneBoltCd.tooltip = "Hitting an arcane bolt lowers all your cooldowns by 10%";
arcaneBoltDmg.relative = arcaneBoltHeal;
arcaneBoltHeal.relative = arcaneBoltDmg;
#endregion
#region Corrupting Bolt
corruptingBoltDmgRed = new UpgradeInfo("Damage debuff", 3, 40, null, button);
corruptingBoltDmgRed.tooltip = "Affected targets deal 10/20/30% less damage and healing";
corruptingBoltCd = new UpgradeInfo("Cooldown debuff", 1, 120, corruptingBoltDmgRed, button);
corruptingBoltCd.tooltip = "Affected targets have 20% longer cooldowns";
corruptingBoltAmplify = new UpgradeInfo("Amplify", 3, 40, null, button);
corruptingBoltAmplify.tooltip = "Affected targets take 25% more damage from the next 1/2/3 direct damage spells";
corruptingBoltBlast = new UpgradeInfo("AoE blast", 1, 120, arcaneBoltHeal, button);
corruptingBoltBlast.tooltip = "Corrupting bolt now explodes in an AoE upon hit, affecting all targets around impact point";
corruptingBoltAmplify.relative = corruptingBoltDmgRed;
corruptingBoltDmgRed.relative = corruptingBoltAmplify;
#endregion
Invoke("SetSpellCasting", 2);
}
void Awake()
{
SetShit();
}
public void SetSpellCasting()
{
spellcastSet = 2;
//GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
/*
foreach(GameObject player in ConnectionHandler_2.players)
{
names += player.GetComponent<SpellCasting>().playerName + "\n";
Debug.Log ("Asd!");
if(player.networkView.isMine)
{
spellCasting = player.GetComponent<SpellCasting>();
}
}
*/
cd = GameObject.Find ("CooldownInfo").GetComponent<CooldownInfo>();
spells.Add (spellCasting.off1);
spells.Add (spellCasting.off2);
spells.Add (spellCasting.off3);
spells.Add (spellCasting.def);
spells.Add (spellCasting.mob);
}
void OnGUI()
{
if(spellcastSet == 1)
{
//GUI.Label(new Rect(10, 200, 100, 100), "I HAVE SET MY SPELLCAST");
}
if(spellcastSet == 2)
{
//GUI.Label(new Rect(10, 200, 100, 100), "I HAVE SET IT FOR REALZ");
}
if(GameHandler.state == GameHandler.State.Upgrade)
{
//GUI.Label(new Rect(10, 310, 100, 100), names);
string gold = "No gold";
gold = spellCasting.gold.ToString();
goldText.text = "Gold: " + gold;
//if (GUI.Button(new Rect(140, 10, 20, 20), "GOLDHAXXX"))
//{
// spellCasting.gold += 100;
//}
GUI.DrawTexture(new Rect(80, 45, 1120, 630), background);
System.Type t = this.GetType();
InvokeMethod (1, "Draw" + spellCasting.off1.spellName, t);
InvokeMethod (2, "Draw" + spellCasting.off2.spellName, t);
InvokeMethod (3, "Draw" + spellCasting.off3.spellName, t);
InvokeMethod (4, "Draw" + spellCasting.def.spellName, t);
InvokeMethod (5, "Draw" + spellCasting.mob.spellName, t);
if(GUI.tooltip.Length != 0)
{
GUI.Label(new Rect((int)Input.mousePosition.x + 10, Screen.height - (int)Input.mousePosition.y, 150, 150), background);
//GUI.Label(new Rect((int)Input.mousePosition.x + 14, Screen.height - (int)Input.mousePosition.y + 4, 150, 150), GUI.tooltip, tooltip);
DrawOutline(new Rect((int)Input.mousePosition.x + 20, Screen.height - (int)Input.mousePosition.y + 8, 135, 135), GUI.tooltip, tooltip, Color.black);
}
//GUI.Label(new Rect(700, 400, 100, 20), "Gold: " + gold);
}
else
{
goldText.text = "";
}
}
void InvokeMethod(int argument, string name, System.Type type)
{
MethodInfo method = type.GetMethod(name);
object[] parameters = new object[] { (object)argument };
method.Invoke(this, parameters);
}
public static void DrawOutline(Rect pos, string text, GUIStyle style, Color color)
{
Color oldColor = style.normal.textColor;
style.normal.textColor = color;
pos.x--;
GUI.Label(pos, text, style);
pos.x += 2;
GUI.Label(pos, text, style);
pos.x--;
pos.y--;
GUI.Label(pos, text, style);
pos.y += 2;
GUI.Label(pos, text, style);
pos.y--;
style.normal.textColor = oldColor;
GUI.Label(pos, text, style);
}
Rect CreateRect(int slot)
{
Rect rect = new Rect();
switch(slot)
{
case 1:
rect = new Rect(146, 145, 300, 400);
break;
case 2:
rect = new Rect(506, 145, 300, 400);
break;
case 3:
rect = new Rect(866, 145, 300, 400);
break;
case 4:
rect = new Rect(146, 400, 300, 400);
break;
case 5:
rect = new Rect(506, 400, 300, 400);
break;
}
return rect;
}
Vector2 rect1 = new Vector2(30, 30);
Vector2 rect2 = new Vector2(30, 130);
Vector2 rect3 = new Vector2(180, 30);
Vector2 rect4 = new Vector2(180, 130);
public void DrawFireball(int slot)
{
GUI.BeginGroup(CreateRect(slot));
//GUI.Label(new Rect(130, 0, 100, 30), "Fireball");
DrawOutline(new Rect(130, 0, 100, 30), "Fireball", "label", Color.black);
fireballDot.Draw (rect1, spellCasting, "fireballDot");
fireballFinalBlast.Draw (rect2, spellCasting, "fireballFinalBlast");
fireballDmg.Draw (rect3, spellCasting, "fireballDmg");
fireballCd.Draw(rect4, spellCasting, "fireballCd");
GUI.EndGroup();
}
public void DrawHealingWard(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Healing", "label", Color.black);
healingDuration.Draw (rect1, spellCasting, "healingDuration");
healingDamageReduct.Draw (rect2, spellCasting, "healingDamageReduct");
healingBloom.Draw (rect3, spellCasting, "healingBloom");
healingBurst.Draw (rect4, spellCasting, "healingBurst");
GUI.EndGroup();
}
public void DrawBindingShot(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Binding shot", "label", Color.black);
bindingDuration.Draw (rect1 + new Vector2(75, 0), spellCasting, "bindingDuration");
bindingSilence.Draw (rect2, spellCasting, "bindingSilence");
//bindingLength.Draw (new Vector2 (180, 30), spellCasting);
bindingAmplify.Draw (rect4, spellCasting, "bindingAmplify");
GUI.EndGroup();
}
public void DrawBlink(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Blink", "label", Color.black);
blinkDmg.Draw (rect1, spellCasting, "blinkDmg");
blinkThrust.Draw (rect2, spellCasting, "blinkThrust");
if(blinkCd.Draw(rect3, spellCasting, "blinkCd"))
{
for (int i = 0; i < spells.Count; i++)
{
if(spells[i].spellName == "Blink")
{
spells[i].spellMaxCd -= 0.5f;
System.Type t = cd.GetType();
FieldInfo[] fields = t.GetFields();
foreach(FieldInfo f in fields)
{
if(f.Name.Equals("spell" + i + "MaxCD"))
{
f.SetValue(cd, (float)f.GetValue(cd) - 0.5f);
}
}
}
}
}
if(blinkInstant.Draw(rect4, spellCasting, "blinkInstant"))
{
for (int i = 0; i < spells.Count; i++)
{
if(spells[i].spellName == "Blink")
{
spells[i].totalCastTime = 0;
spells[i].castTime = 0;
}
}
}
GUI.EndGroup();
}
public void DrawPrisonCenter(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Frost Prison", "label", Color.black);
frostPrisonDuration.Draw (rect1, spellCasting, "frostPrisonDuration");
frostPrisonCircleWall.Draw (rect2, spellCasting, "frostPrisonCircleWall");
frostPrisonRamp.Draw (rect3, spellCasting, "frostPrisonRamp");
frostPrisonStorm.Draw (rect4, spellCasting, "frostPrisonStorm");
GUI.EndGroup();
}
public void DrawHook(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Hook", "label", Color.black);
hookDmg.Draw (rect1, spellCasting, "hookDmg");
hookPull.Draw (rect2, spellCasting, "hookPull");
if(hookCd.Draw(rect3, spellCasting, "hookCd"))
{
for (int i = 0; i < spells.Count; i++)
{
if(spells[i].spellName == "Hook")
{
spells[i].spellMaxCd -= 0.5f;
System.Type t = cd.GetType();
FieldInfo[] fields = t.GetFields();
foreach(FieldInfo f in fields)
{
if(f.Name.Equals("spell" + i + "MaxCD"))
{
f.SetValue(cd, (float)f.GetValue(cd) - 0.5f);
}
}
}
}
}
hookInvu.Draw (rect4, spellCasting, "hookInvu");
GUI.EndGroup();
}
public void DrawMagmaBlastAlternative(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Magma Blast", "label", Color.black);
// if (magmaBlastCd.Draw(rect1, spellCasting, "magmaBlastCd"))
//{
// for (int i = 0; i < spells.Count; i++)
// {
// if(spells[i].spellName == "MagmaBlastAlternative")
// {
// spells[i].spellMaxCd -= 0.35f;
// System.Type t = cd.GetType();
// FieldInfo[] fields = t.GetFields();
// foreach(FieldInfo f in fields)
// {
// if(f.Name.Equals("spell" + i + "MaxCD"))
// {
// f.SetValue(cd, (float)f.GetValue(cd) - 0.35f);
// }
// }
// }
// }
//}
//if(magmaBlastBlackhole.Draw (rect2, spellCasting, "magmaBlastBlackhole"))
//{
// for (int i = 0; i < spells.Count; i++)
// {
// if(spells[i].spellName == "MagmaBlastAlternative")
// {
// spells[i].totalCastTime = 0.3f;
// spells[i].castTime = 0.3f;
// }
// }
//}
magmaBlastDmg.Draw (rect3, spellCasting, "magmaBlastDmg");
magmaBlastAmplify.Draw (rect4, spellCasting, "magmaBlastAmplify");
GUI.EndGroup();
}
public void DrawNewShield(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Reflect Shield", "label", Color.black);
shieldAmp.Draw (rect1, spellCasting, "shieldAmp");
shieldAim.Draw (rect2, spellCasting, "shieldAim");
if(shieldCd.Draw (rect3, spellCasting, "shieldCd"))
{
for (int i = 0; i < spells.Count; i++)
{
if(spells[i].spellName == "NewShield")
{
spells[i].spellMaxCd -= 0.5f;
System.Type t = cd.GetType();
FieldInfo[] fields = t.GetFields();
foreach(FieldInfo f in fields)
{
if(f.Name.Equals("spell" + i + "MaxCD"))
{
f.SetValue(cd, (float)f.GetValue(cd) - 0.5f);
}
}
}
}
}
shieldAbsorb.Draw (rect4, spellCasting, "shieldAbsorb");
GUI.EndGroup();
}
public void DrawWindWalkShield(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Invisibility Shield", "label", Color.black);
windShieldDuration.Draw (rect1, spellCasting, "windShieldDuration");
windShieldDamage.Draw (rect2, spellCasting, "windShieldDamage");
if(windShieldCd.Draw (rect3, spellCasting, "windShieldCd"))
{
for (int i = 0; i < spells.Count; i++)
{
if(spells[i].spellName == "WindWalkShield")
{
spells[i].spellMaxCd -= 0.5f;
System.Type t = cd.GetType();
FieldInfo[] fields = t.GetFields();
foreach(FieldInfo f in fields)
{
if(f.Name.Equals("spell" + i + "MaxCD"))
{
f.SetValue(cd, (float)f.GetValue(cd) - 0.5f);
}
}
}
}
}
windShieldInvis.Draw (rect4, spellCasting, "windShieldInvis");
GUI.EndGroup();
}
public void DrawPlacedShield(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Placed Shield", "label", Color.black);
placedShieldAmp.Draw (rect3, spellCasting, "placedShieldAmp");
placedShieldKnockImmune.Draw (rect2, spellCasting, "placedShieldKnockImmune");
if(placedShieldCd.Draw (rect1, spellCasting, "placedShieldCd"))
{
for (int i = 0; i < spells.Count; i++)
{
if(spells[i].spellName == "PlacedShield")
{
spells[i].spellMaxCd -= 1.5f;
System.Type t = cd.GetType();
FieldInfo[] fields = t.GetFields();
foreach(FieldInfo f in fields)
{
if(f.Name.Equals("spell" + i + "MaxCD"))
{
f.SetValue(cd, (float)f.GetValue(cd) - 1.5f);
}
}
}
}
}
placedShieldSpeed.Draw (rect4, spellCasting, "placedShieldSpeed");
GUI.EndGroup();
}
public void DrawLifeGrip(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Life Grip", "label", Color.black);
if (lifeGripCd.Draw (rect1, spellCasting, "lifeGripCd"))
{
for (int i = 0; i < spells.Count; i++)
{
if(spells[i].spellName == "LifeGrip")
{
spells[i].spellMaxCd -= 0.5f;
System.Type t = cd.GetType();
FieldInfo[] fields = t.GetFields();
foreach(FieldInfo f in fields)
{
if(f.Name.Equals("spell" + i + "MaxCD"))
{
f.SetValue(cd, (float)f.GetValue(cd) - 1.5f);
}
}
}
}
}
lifeGripShield.Draw (rect2, spellCasting, "lifeGripShield");
GUI.EndGroup();
}
public void DrawArcaneBolt(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Arcane Bolt", "label", Color.black);
arcaneBoltDmg.Draw(rect1, spellCasting, "arcaneBoltDmg");
arcaneBoltKnock.Draw(rect2, spellCasting, "arcaneBoltKnock");
arcaneBoltHeal.Draw(rect3, spellCasting, "arcaneBoltHeal");
arcaneBoltCd.Draw(rect4, spellCasting, "arcaneBoltCd");
GUI.EndGroup();
}
public void DrawCorruptingBolt(int slot)
{
GUI.BeginGroup(CreateRect(slot));
DrawOutline(new Rect(130, 0, 100, 30), "Corrupting Bolt", "label", Color.black);
corruptingBoltDmgRed.Draw(rect1, spellCasting, "corruptingBoltDmgRed");
corruptingBoltCd.Draw(rect2, spellCasting, "corruptingBoltCd");
corruptingBoltAmplify.Draw(rect3, spellCasting, "corruptingBoltAmplify");
corruptingBoltBlast.Draw(rect4, spellCasting, "corruptingBoltBlast");
GUI.EndGroup();
}
}
public class UpgradeInfo
{
public string upgradeName;
public string tooltip = "No tooltip found";
public int currentLevel = 0;
public int maxLevel;
public int cost;
public UpgradeInfo preReq;
public UpgradeInfo relative;
GUIStyle button;
public UpgradeInfo(string name, int max, int _cost, UpgradeInfo pre, GUIStyle _button)
{
upgradeName = name;
maxLevel = max;
preReq = pre;
cost = _cost;
button = _button;
}
public bool Draw(Vector2 offset, SpellCasting spellCasting, string thisName)
{
bool val = false;
if(GUI.Button(new Rect((int)offset.x, (int)offset.y, 80, 80), new GUIContent("", tooltip)))
{
val = Upgrade(spellCasting, thisName);
}
Upgrading.DrawOutline (new Rect ((int)offset.x + 20, (int)offset.y + 20, 80, 80), upgradeName, "label", Color.black);
Upgrading.DrawOutline (new Rect(offset.x + 10, offset.y + 5, 30, 30), cost.ToString(), "label", Color.black);
Upgrading.DrawOutline (new Rect(offset.x + 60, offset.y + 50, 20, 20), currentLevel.ToString() + "/" + maxLevel.ToString(), "label", Color.black);
return val;
}
public bool Upgrade(SpellCasting spellCasting, string thisName)
{
if(relative != null)
{
if(relative.currentLevel > 0)
{
return false;
}
}
if(preReq != null)
{
if(preReq.currentLevel == preReq.maxLevel)
{
if(currentLevel < maxLevel && spellCasting.gold >= cost)
{
currentLevel++;
spellCasting.gold -= cost;
Upgrades up = spellCasting.gameObject.GetComponent<Upgrades>();
Type t = typeof(Upgrades);
up.InvokeMethod(currentLevel, "Call" + thisName, t);
if (currentLevel == 1)
{
//GA.API.Design.NewEvent("Upgrade:" + upgradeName);
}
return true;
}
}
}
else if(currentLevel < maxLevel && spellCasting.gold >= cost)
{
currentLevel++;
spellCasting.gold -= cost;
Upgrades up = spellCasting.gameObject.GetComponent<Upgrades>();
Type t = typeof(Upgrades);
up.InvokeMethod(currentLevel, "Call" + thisName, t);
//Invoke("Cmd" + thisName, 0);
return true;
}
return false;
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class LobbyPlayer : NetworkLobbyPlayer {
[SyncVar(hook = "OnMyName")]
public string playerName;
[SyncVar(hook = "OnMyTeam")]
public string team;
[SyncVar]
public int rounds;
MenuConnection menuLobby;
public void Awake()
{
menuLobby = GameObject.Find("LobbyManager").GetComponent<MenuConnection>();
}
public override void OnClientEnterLobby()
{
base.OnClientEnterLobby();
menuLobby.AddPlayer(this);
Debug.Log("Client entered lobby");
}
public override void OnStartLocalPlayer()
{
base.OnStartLocalPlayer();
SetupLocalPlayer();
}
public override void OnClientReady(bool readyState)
{
base.OnClientReady(readyState);
menuLobby.CheckReady();
menuLobby.UpdatePlayerList();
Debug.Log("A client is ready: " + readyState);
}
[Command]
void CmdSetName(string name)
{
playerName = name;
Debug.Log("Command set name:" + name);
}
[Command]
void CmdSetTeam(string newTeam)
{
team = newTeam;
Debug.Log("Command set team:" + team);
}
void OnMyTeam(string newTeam)
{
team = newTeam;
menuLobby.UpdatePlayerList();
Debug.Log("On my team: "+ team);
}
void OnMyName(string name)
{
playerName = name;
Debug.Log("On my name: " + playerName);
menuLobby.UpdatePlayerList();
}
void SetupLocalPlayer()
{
Debug.Log("Setting up local player");
Toggle toggleButton = GameObject.Find("Toggle").GetComponent<Toggle>();
toggleButton.onValueChanged.AddListener(OnReadyClicked);
CmdSetName(PlayerPrefs.GetString("Player Name"));
CmdSetTeam("1");
Button team1Button = GameObject.Find("Team 1").GetComponent<Button>();
team1Button.onClick.AddListener(OnClickTeam1);
Button team2Button = GameObject.Find("Team 2").GetComponent<Button>();
team2Button.onClick.AddListener(OnClickTeam2);
CmdUpdatePlayerList();
}
[Command]
public void CmdUpdatePlayerList()
{
//UpdatePlayerList();
RpcUpdatePlayerList();
}
[ClientRpc]
public void RpcUpdatePlayerList()
{
menuLobby.UpdatePlayerList();
}
void OnClickTeam1()
{
CmdSetTeam("1");
}
void OnClickTeam2()
{
CmdSetTeam("2");
}
void OnReadyClicked(bool value)
{
if (value)
{
SendReadyToBeginMessage();
}
else
{
SendNotReadyToBeginMessage();
}
}
public void OnDestroy()
{
menuLobby.RemovePlayer(this);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class SpellChoices : MonoBehaviour {
public string mobSpell;
public string defSpell;
public string offSpell1;
public string offSpell2;
public string offSpell3;
void Start ()
{
DontDestroyOnLoad(gameObject);
}
void OnLevelWasLoaded (int level)
{
CooldownInfo cooldownInfo = GameObject.Find ("CooldownInfo").GetComponent<CooldownInfo>();
cooldownInfo.SetSpell1(offSpell1);
cooldownInfo.SetSpell2(offSpell2);
cooldownInfo.SetSpell3(offSpell3);
cooldownInfo.SetSpell4(defSpell);
cooldownInfo.SetSpell5(mobSpell);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class WindWalkShield : NetworkBehaviour
{
public Spell spell;
public GameObject owner;
public GameObject shieldHit;
public float duration;
public AudioClip cast;
public AudioClip hit;
public float invisDuration;
float damageBoost = 1;
void Start ()
{
AudioSource.PlayClipAtPoint(cast, transform.position);
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
string ownerName = spell.owner;
foreach(GameObject player in players)
{
string playerName = ((SpellCasting)player.GetComponent ("SpellCasting")).playerName;
if(ownerName == playerName)
{
owner = player;
break;
}
}
if (!isServer)
return;
IncreaseDuration(spell.upgrades.windShieldDuration);
if (spell.upgrades.windShieldDamage > 0)
ActivateDamage();
if (spell.upgrades.windShieldInvis > 0)
ActivateInvis();
owner.SendMessage("IsShielding");
owner.GetComponent<SpellCasting>().Invoke ("StopShielding", duration);
spell.Invoke ("KillSelf", duration);
}
void IncreaseDuration(int newDur)
{
invisDuration += newDur * 0.5f;
duration += newDur * 0.5f;
owner.GetComponent<SpellCasting>().CancelInvoke("StopShielding");
owner.GetComponent<SpellCasting>().Invoke ("StopShielding", duration);
spell.CancelInvoke("KillSelf");
spell.Invoke ("KillSelf", duration);
}
void ActivateDamage()
{
damageBoost = 1.35f;
}
void ActivateInvis()
{
StartInvis();
owner.GetComponent<SpellCasting>().StopShielding();
}
void Update ()
{
transform.position = owner.transform.position;
}
void OnTriggerEnter2D(Collider2D other)
{
if (!isServer)
return;
if(other.CompareTag ("Spell"))
{
Spell otherSpell = (Spell)other.GetComponent("Spell");
if(spell.team != otherSpell.team)
{
if(otherSpell.type == Spell.spellType.Projectile)
{
otherSpell.damage = 0;
GameObject hitEffect = Instantiate(shieldHit, other.transform.position, Quaternion.identity);
NetworkServer.Spawn(hitEffect);
Destroy(other.gameObject);
StartInvis();
//GetComponent<NetworkView>().RPC("Invis", RPCMode.All);
}
}
}
}
void StartInvis()
{
spell.CancelInvoke("KillSelf");
gameObject.GetComponent<Collider2D>().enabled = false;
owner.GetComponent<Movement>().RpcSpeedBoost(1.75f, invisDuration);
RpcInvis();
Invoke("EndInvis", invisDuration);
}
void TeamInvis()
{
SpriteRenderer[] sRenderers = owner.GetComponentsInChildren<SpriteRenderer>();
foreach(SpriteRenderer renderer in sRenderers)
{
renderer.color = new Color(1, 1, 1, 0.5f);
}
if (damageBoost > 0)
{
owner.GetComponent<SpellCasting>().RpcDamageBoost(damageBoost, invisDuration);
}
}
[ClientRpc]
void RpcInvis()
{
AudioSource.PlayClipAtPoint(hit, transform.position);
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
string ownerName = spell.owner;
int localTeam = 0;
foreach (GameObject player in players)
{
string playerName = ((SpellCasting)player.GetComponent("SpellCasting")).playerName;
if (ownerName == playerName)
{
owner = player;
}
if(player.GetComponent<NetworkIdentity>().isLocalPlayer)
{
localTeam = player.GetComponent<SpellCasting>().team;
}
}
owner.GetComponent<DamageSystem>().DmgInvis();
Renderer[] renderers = gameObject.GetComponentsInChildren<Renderer>();
foreach (Renderer renderer in renderers)
{
renderer.enabled = false;
}
if (spell.team == localTeam)
{
TeamInvis();
return;
}
renderers = owner.GetComponentsInChildren<Renderer>();
foreach (Renderer renderer in renderers)
{
renderer.enabled = false;
//renderer.color = new Color(1, 1, 1, 0.5f);
}
owner.GetComponent<SpellCasting>().Invis();
}
[ClientRpc]
void RpcEndInvis()
{
Debug.Log("End invis!");
Renderer[] renderers = owner.GetComponentsInChildren<Renderer>();
foreach (Renderer renderer in renderers)
{
renderer.enabled = true;
}
SpriteRenderer[] sRenderers = owner.GetComponentsInChildren<SpriteRenderer>();
foreach (SpriteRenderer sRend in sRenderers)
{
sRend.color = new Color(1, 1, 1, 1);
}
owner.SendMessage("EndInvis");
}
void EndInvis()
{
RpcEndInvis();
spell.Invoke("KillSelf", 1);
}
}
<file_sep>using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class Movement : NetworkBehaviour {
#region Fields
public float speed = 5.0f;
private float maxSpeed = 20.0f;
public SpellCasting spellCasting;
public DamageSystem damageSystem;
public Vector3 bound;
public float length;
public float oldSpeed;
public Vector3 holePos = Vector3.zero;
#endregion
#region Properties
public float MovementSpeed
{
set
{
if(speed <= maxSpeed)
speed = value;
}
get
{
return speed;
}
}
#endregion
void Start ()
{
oldSpeed = speed;
}
[ClientRpc]
public void RpcSpeedBoost(float boost, float duration)
{
CancelInvoke("EndSpeedBoost");
Invoke ("EndSpeedBoost", duration);
//oldSpeed = speed;
speed = oldSpeed * boost;
}
void EndSpeedBoost()
{
speed = oldSpeed;
}
void BoundTo(Transform boundTo)
{
//bound = boundTo;
}
[ClientRpc]
public void RpcBound(float duration, float length)
{
bound = transform.position;
this.length = length;
Invoke ("RemoveBound", duration);
}
[ClientRpc]
public void RpcReset()
{
if (!isLocalPlayer)
return;
Vector3 spawnPos = Vector3.zero;
switch(spellCasting.team)
{
case 1: spawnPos = new Vector3(-11, 0, 0);
break;
case 2: spawnPos = new Vector3(11, 0, 0);
break;
}
transform.position = spawnPos;
}
void Update ()
{
if (!isLocalPlayer)
return;
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
if (!GlobalConstants.isFrozen && GameHandler.state == GameHandler.State.Game)
{
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
movement = Vector3.Normalize(movement);
if (bound == Vector3.zero)
{
if(!spellCasting.isCasting)
{
transform.position += (movement * speed / GlobalConstants.unitScaling) * Time.deltaTime * 60;
}
transform.position += damageSystem.knockback / GlobalConstants.unitScaling / 2 * Time.deltaTime * 60;
}
else
{
Vector3 newPos = transform.position + (movement * speed / GlobalConstants.unitScaling) * Time.deltaTime * 60 + damageSystem.knockback / GlobalConstants.unitScaling / 2 * Time.deltaTime * 60; ;
if (Vector3.Distance(bound, newPos) < length)
{
transform.position = newPos;
}
}
Vector3 aimDir = Input.mousePosition;
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
aimDir.x = aimDir.x - pos.x;
aimDir.y = aimDir.y - pos.y;
float angle = Mathf.Atan2(aimDir.y, aimDir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle + 135 + 90));
}
//GameObject.Find ("CooldownInfo").SendMessage ("UpdatePlayer1Pos", transform.position);
transform.position = new Vector3(transform.position.x, transform.position.y, 0);
}
[ClientRpc]
public void RpcMove(Vector3 velocity)
{
Debug.Log("I should move");
transform.position += velocity;
transform.position = new Vector3(transform.position.x, transform.position.y, 0);
}
void RemoveBound()
{
bound = Vector3.zero;
}
}
public static class GlobalConstants
{
//Used to translate sensible values to the actual Unity sizes (usually by dividing)
public static float unitScaling = 135.0f;
public static Vector2 screenSize = new Vector2(12.8f, 7.1f);
public static bool isFrozen = false;
public static Vector3 RotateZ(Vector3 v, float angle )
{
float sin = Mathf.Sin( angle );
float cos = Mathf.Cos( angle );
float tx = v.x;
float ty = v.y;
v.x = (cos * tx) - (sin * ty);
v.y = (cos * ty) + (sin * tx);
return v;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class FireballExplo : MonoBehaviour
{
public AudioClip explo;
void Start ()
{
Invoke ("KillSelf", 0.75f);
AudioSource.PlayClipAtPoint(explo, transform.position);
}
void KillSelf()
{
Destroy(gameObject);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class ScaleUp : MonoBehaviour {
public GameObject parent;
PlacedShield shield;
float time = 0;
bool goingUp = true;
void Start()
{
shield = parent.GetComponent<PlacedShield>();
}
void Update ()
{
time += Time.deltaTime;
if(goingUp)
{
transform.localScale = Vector3.Lerp(Vector3.zero, Vector3.one * 3.5f, time * 2);
if(time >= shield.duration - 0.3f)
{
goingUp = false;
time = 0;
}
}
else
{
transform.localScale = Vector3.Lerp(Vector3.one * 3.5f, Vector3.zero, time * 4);
}
}
}
| d3c7d20c00079cbff55c417962d71febf764e980 | [
"C#"
] | 42 | C# | PandaParty/battleofthemagi | c45e06d4dd65d2cf310bde15d86b73ad3074c5fb | 15f975137acc825f4e65dbec993a2897dd44c4ec |
refs/heads/master | <repo_name>gustavo-mf/nodeMongoDb<file_sep>/README.md
# Exercicio utilizando node.js e mongoDb
<file_sep>/models/emprestimo.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const EmprestimoSchema = Schema(
{
livro: { type: Schema.ObjectId, ref: 'Livro', required: true },
status: { type: String, required: true, enum: ['Disponivel', 'Emprestado'], default: 'Disponivel' },
dataEntrega: { type: Date, default: Date.now }
}
);
module.exports = mongoose.model('Emprestimo', EmprestimoSchema);<file_sep>/models/autor.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const AutorSchema = Schema(
{
primeiro_nome: { type: String, required: true, max: 100 },
ultimo_nome: { type: String, required: true, max: 100 }
}
);
module.exports = mongoose.model('Autor', AutorSchema);<file_sep>/old/mongooseExemplo.js
'use strict';
const Mongoose = require('mongoose');
Mongoose.Promise = global.Promise;
let url = 'mongodb://localhost:27017/testemg';
Mongoose.connect(url);
let conexao = Mongoose.connection;
conexao.on('error', console.error.bind(console, 'MongoDB erro de conexao'));
const pessoaEsquema = Mongoose.Schema({
nome: String,
idade: Number
});
const Pessoa = Mongoose.model('pessoa', pessoaEsquema);
let documento = new Pessoa({nome: '<NAME>', idade: 22});
/*documento.save((err) => {
if (err) throw err;
console.log('documento salvo.');
});*/
/*let consulta = Pessoa.find().where('nome').equals('<NAME>');
consulta.exec((err, docs) => {
if (err) throw err;
console.log(docs[0]);
});*/
Pessoa.update({nome:'teste'}, {$set: {idade:33}}, (err) => {
if (err) throw err;
console.log('alterado.');
});<file_sep>/rotas.js
'use strict';
const bodyParser = require('body-parser');
const express = require('express');
const db = require('./conection.js');
const Autor = require('./models/autor');
const Livro = require('./models/livro');
module.exports = (function() {
let app = express();
let jsonParser = bodyParser.json();
app.get('/', function (req, res) {
console.log('index');
res.send('hello');
});
app.get('/autor', function (req, res) {
console.log('autor index');
let con = db.connection;
let consulta = Autor.find({});
consulta.exec((err, docs) => {
if (err) throw err;
let ats = '';
docs.forEach(function(elem){
ats += '<div>';
ats += '<p>Primeiro nome: '+elem['primeiro_nome']+'</p>';
ats += '<p>Ultimo nome: '+elem['ultimo_nome']+'</p>';
ats += '</div>';
});
res.send(ats);
con.close();
});
});
app.get('/autor/:id', function (req, res) {
let id = req.params.id;
console.log('autor selecionado '+id);
});
app.get('/emprestimo', function (req, res) {
console.log('emprestimo index');
});
app.get('/emprestimo/:id', function (req, res) {
let id = req.params.id;
console.log('emprestimo selecionado '+id);
});
app.get('/livro', function (req, res) {
console.log('livro index');
let con = db.connection;
let consulta = Livro.find({});
consulta.exec((err, docs) => {
if (err) throw err;
let livros = '';
docs.forEach(function(elem){
livros += '<div>';
livros += '<p>titulo: '+elem['titulo']+'</p>';
let ats = '';
let conAutor = Autor.find(elem['autores']);
conAutor.exec((err, docs) => {
if (err) throw err;
docs.forEach(function(elem){
ats += '<div>';
ats += '<p>Primeiro nome: '+elem['primeiro_nome']+'</p>';
ats += '<p>Ultimo nome: '+elem['ultimo_nome']+'</p>';
ats += '</div>';
});
livros += ats;
});
livros += '</div>';
});
res.send(livros);
con.close();
});
});
app.get('/livro/:id', function (req, res) {
let id = req.params.id;
console.log('livro selecionado '+id);
});
return app;
})();
<file_sep>/old/inicializadorBaseDados.js
'use strict';
const async = require('async');
const Livro = require('../models/livro');
const Autor = require('../models/autor');
const Emprestimo = require('../models/emprestimo');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const url = 'mongodb://localhost:27017/biblioteca';
mongoose.connect(url);
let db = mongoose.connection;
mongoose.connection.on('error', console.error.bind(console, 'MongoDB erro de conexao:'));
let autores = [];
let livros = [];
let emprestimos = [];
function autorCriar(primeiro_nome, ultimo_nome, callback) {
let autordados = { primeiro_nome: primeiro_nome, ultimo_nome: ultimo_nome };
let autor = new Autor(autordados);
autor.save(function (err) {
if (err) {
callback(err, null);
return;
}
console.log('Novo Autor: ' + autor);
autores.push(autor);
callback(null, autor);
});
}
function livroCriar(titulo, autores, callback) {
let livrodados = { titulo: titulo };
if (autores != false) livrodados.autores = autores;
let livro = new Livro(livrodados);
livro.save(function (err) {
if (err) {
callback(err, null);
return;
}
console.log('Novo Livro: ' + livro);
livros.push(livro);
callback(null, livro);
});
}
function emprestimoCriar(livro, status, dataEntrega, callback) {
let emprestimodados = { livro: livro };
if (status != false) emprestimodados.status = status;
if (dataEntrega != false) emprestimodados.dataEntrega = dataEntrega;
let emprestimo = new Emprestimo(emprestimodados);
emprestimo.save(function (err) {
if (err) {
callback(err, null);
return;
}
console.log('Novo Emprestimo: ' + emprestimo);
emprestimos.push(emprestimo);
callback(null, emprestimo);
});
}
function criarAutores(callback) {
async.parallel(
[
function (callback) {
autorCriar('John', 'Doe', callback);
},
function (callback) {
autorCriar('Mary', 'Doe', callback);
}
],
callback
);
}
function criarLivros(callback) {
async.parallel(
[
function (callback) {
livroCriar('JavaScript Legal', autores[0], callback);
},
function (callback) {
livroCriar('JavaScript Outra Vez', [autores[0], autores[1]], callback);
}
],
callback
);
}
function criarEmprestimos(callback) {
async.parallel(
[
function (callback) {
emprestimoCriar(livros[0], false, false, callback)
},
function (callback) {
emprestimoCriar(livros[1], 'Emprestado', new Date(2017,7,3), callback)
}
],
callback
);
}
async.series([criarAutores, criarLivros, criarEmprestimos], function (err, result) {
if (err) {
console.log('Erro: ' + err);
} else {
console.log('Dados: ' + emprestimos);
}
mongoose.connection.close();
});<file_sep>/old/exemplosRotas.js
'use strict';
const bodyParser = require('body-parser');
let jsonParser = bodyParser.json();
const express = require('express');
let app = express();
app.get('/usuario', function (req, res) {
let usuario = { id:1010, nome:"teste"};
res.json(usuario);
});
app.get('/usuarios/:id', function (req, res) {
let idUsuario = req.params.id;
let usuario = { id: idUsuario, nome: 'teste'};
res.send(usuario);
});
app.post('/usuarios/:id', jsonParser, function (req, res) {
console.log(req.body);
res.sendStatus(200).send(`${usuario.id} modificado`);
});
app.listen(3000);<file_sep>/app.js
'use strict';
const rotas = require('./rotas.js');
rotas.listen(3000);
console.log('Server on');
| 3869a817730787ebc0912fac0ec8b765cb1a877b | [
"Markdown",
"JavaScript"
] | 8 | Markdown | gustavo-mf/nodeMongoDb | 8b8484c1a66c40f8871dad490ab0bd7e7774c06e | 66fe98a01c43bc44dc73282402ac8d3f7eb62a98 |
refs/heads/master | <file_sep>module Types
class QueryType < Types::BaseObject
# Add root-level fields here.
# They will be entry points for queries on your schema.
field :all_todos, [TodoType], null: false
def all_todos
context[:current_user].todos
end
end
end
<file_sep># REST + GraphQL - Rails
This repository contains back-end code for [a blog post](https://blog.brittle-pins.com) that describes how to use JWT authentication with GraphQL in a Rails API and React app.
Here you can find a minimal <b>Rails + JWT Sessions + GraphQL</b> configuration.
Versions:
- Ruby 2.6.3
- Rails 5.2.3
- JWT Sessions 2.4.3
- GraphQL 1.9.15
| fed90798967bf3357a805a05389e1297e6cd6ca3 | [
"Markdown",
"Ruby"
] | 2 | Ruby | ekaterina-nikonova/gql-cra-rails | 1f0748193b04f26eb1e30043c88b57d4840639bb | 0b96ab244315cc45c3fbca944c089c61a56dc2af |
refs/heads/master | <file_sep># Ribcage application template (CoffeeScript edition)
This is a [volo](http://volojs.org/)-compatible
[Ribcage](https://github.com/foxbunny/ribcage) web application template.
This template is based on the basic
[create-template](https://github.com/volojs/create-template).
## JavaScript edition
This is a template for CoffeeScript development. There is
[another template](https://github.com/foxbunny/create-ribcage-app-js) for
people who do not want to use CoffeeScript.
## Directory layout
* coffee/ - CoffeeScript sources
* app/ - application modules
* routes/ - the directory to hold route handlers
* hello.coffee - example route handler
* views/ - the directory to hold views
* hello.coffee - example view
* conf.coffee - application configuration
* main.coffee - application router and basic setup
* app.coffee - Basic setup module that configures RequireJS
* www/ - the web assets for the project
* index.html - the entry point into the app.
* js/
* app/ - the directory to hold compiled sources
* lib/ - the directory to hold third party scripts.
* tpl/ - the directory to hold templates
* tools/ - the build tools to optimize the project and HTTP server.
## Creating a project using volo
To create a project using volo, run:
volo create my_project_name foxbunny/create-ribcage-app
Volo will take care of installing all dependencies, so you can skip that part
in the next section.
When asked about `jquery.soap` and `jquery.xml2json` dependencies and exports,
simply accept the defaults. You can also remove them later if you wish but you
will need to adjust some of the default code for the app to start.
## Preparing the project
To keep the template small, dependencies are not included. Install them using
the following command:
volo add
You will get a few warnings about different packages trying to install a
different version of jQuery, but that is expected, and you should ignore them.
You may also want to install a few Node dependencies (and, indeed, NodeJS
itself) before proceeding. Installing NodeJS is outside the scope of this
document. To install the development dependencies, simply run:
npm install
Note that this template is aimed towards people who write CoffeeScript, so
CoffeeScript is installed as part of development dependencies. You can edit the
`package.json` file to remove this dependency.
Although installing some of the dependencies may show some warnings on Windows,
it should all just work in the end.
## Compiling CoffeeScript
As noted in the previous section, this template is geared towards CoffeeScript
developers. The volofile provided with the project includes two
CoffeeScript-specific targets. Those are:
volo compile
and
volo watch
They do what you would expect. They compile, and watch-compile the CoffeeScript
source respectively.
## Building
To optimize, run:
volo build
This will run the "build" command in the volofile that is in this directory.
That build command creates an optimized version of the project in a
**www-built** directory. The js/app.js file will be optimized to include
all of its dependencies.
For more information on the optimizer:
http://requirejs.org/docs/optimization.html
For more information on using requirejs:
http://requirejs.org/docs/api.html
## Development server
The project uses [DaProxy](https://bitbucket.org/cloudhorizon/devproxy) to
serve the unbuilt files. To start it, run:
volo serve
The server will be accessible at [localhost:8080](http://localhost:8080/).
The server is a simple HTTP server with reverse proxy capability. The
file is called `proxy.json` and is located in the `tools` directory. The layout
of the file should be self-explanatory.
## Known issues
Compiling or watch-compiling CoffeeScript will create a directory `-p` in the
source tree (confirmed on Windows). I still haven't figured out why this
happens. The directory empty and it is in .gitignore file, so it won't do any
harm. I understand if you find it annoying, though.
<file_sep>// Generated by CoffeeScript 1.6.3
define(function(require) {
var HelloView, ribcage, tHello;
ribcage = require('ribcage');
tHello = require('text!tpl/hello.tpl');
return HelloView = ribcage.views.TemplateView.extend({
templateSource: tHello
});
});
<file_sep>// Generated by CoffeeScript 1.6.3
define(function(require) {
var HelloView;
HelloView = require('app/views/hello');
return {
world: function() {
this.cleanup();
return this.register(new HelloView()).render().$el.appendTo(this.content);
}
};
});
| 053ecd3af1bdd9f153a670ce1176de8b69bdaf28 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | foxbunny/create-ribcage-app | f43e483b6fc3027515c794d22f4cbb832b6d0caa | e79e09341eac0813f1e081db02fd83dfefead8de |
refs/heads/master | <file_sep>using System.Collections.Generic;
using System.Collections;
namespace CarDealership.Models
{
public class Car
{
private string _makeModel;
private string _price;
private string _miles;
private string _carInfo;
//private string _newCar;
private static List<Car> _instances = new List<Car> {};
public Car(string newMakeModel, string newCarInfo, string newPrice, string newMiles)
{
_makeModel = newMakeModel;
_carInfo = newCarInfo;
_price = newPrice;
_miles = newMiles;
}
public void SetMakeModel(string newMakeModel)
{
_makeModel = newMakeModel;
}
public string GetMakeModel()
{
return _makeModel;
}
public void SetPrice(string newPrice)
{
_price = newPrice;
}
public string GetPrice()
{
return _price;
}
public void SetMiles(string newMiles)
{
_miles = newMiles;
}
public string GetMiles()
{
return _miles;
}
public void SetCarInfo(string newCarInfo)
{
_carInfo = newCarInfo;
}
public string GetCarInfo()
{
return _carInfo;
}
public void Save()
{
_instances.Add(this);
}
public static List<Car> GetAll()
{
return _instances;
}
}
}
<file_sep># CarDealership
#### Write a program for a car dealership. September 11, 2018
#### By **<NAME> & <NAME>**
## Description
Rebuild our car dealership site as an app that allows users to add new cars.
### Specs
## Setup/Installation Requirements
1. Clone this repository: https://github.com/QuietEvolver/tictactoe
https://github.com/nelsonsbrian/tictactoe
2. Open the command line--and navigate into the repository.
3ß. On your browser, open the index.html and enjoy!
## Known Bugs
* No known bugs at this time.
## Technologies Used
* C#
* MVC
* Atom
* GitHub
* HTML
## Support and contact details
_<NAME> <EMAIL>_
_<NAME> <EMAIL>_
### License
*{This software is licensed under the MIT license}*
Copyright (c) 2018 **_{<NAME> & <NAME>}_**
<file_sep>using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using CarDealership.Models;
namespace CarDealership.Controllers
{
public class HomeController : Controller
{
[HttpGet("/")]
public ActionResult Homepage()
{
List<Car> allCars = new List<Car> {};
return View();
}
[HttpPost("/home_page")]
public ActionResult Index()
{
Car myCar = new Car(Request.Form["newMakeModel"], Request.Form["newCarInfo"], Request.Form["newCarInfo"], Request.Form["newMiles"]); //int.Parse( Request.Form["newCarInfo"]); returns string into integer
myCar.Save();
List<Car> allCars = Car.GetAll();
return View("Index", allCars);
}
// [HttpGet("/home/display_car")]
// public ActionResult display_car()
// {
// // Car myNewCar = new Car(Request.Form["new-car"]); //Request.Form["new-car"]
// // List<Car> allCars = new List<Car> {};
//
// return View();
// }
}
}
| 989ca725b2612c6436e44a174849817e44935dde | [
"Markdown",
"C#"
] | 3 | C# | dereksmith2018/CarDealershipTesting | 47caa80544bf45dfa8ffddf22472710952e2927c | c24660009af147399e502e47200dd5b0c6204b7c |
refs/heads/main | <repo_name>sangukO/Final<file_sep>/FinalServer/FinalProjectServer.py
from socket import *
from threading import *
import random # 랜덤 모듈
class LotteryServer:
clients = []
final_received_message = ""
senders_num = 0
draw_num = 5
lot1 = []
lot2 = []
lot3 = []
lot4 = []
lot5 = []
lots = []
message = ""
lot_score = ['0', '0', '0', '0', '0']
def __init__(self): #메인 함수
self.s_sock = socket(AF_INET, SOCK_STREAM) #소켓 생성
self.ip = ''
self.port = 2500
self.s_sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.s_sock.bind((self.ip, self.port))
print("Waiting for clients...")
self.s_sock.listen(100)
self.accept_client()
def accept_client(self): #클라이언트와 연결
while True:
client = c_socket, (ip, port) = self.s_sock.accept()
if client not in self.clients:
self.clients.append(client)
self.senders_num += 1
print (self.senders_num,'번째 클라이언트, ',ip, ' : ', str(port), '가 연결되었습니다.')
t = Thread(target=self.receive_messages, args=(c_socket,)) #쓰레드 생성
t.start()
def receive_messages(self, c_socket):
while True:
try:
incoming_message = c_socket.recv(1024)
if not incoming_message:
break
except:
continue
else: #클라이언트가 보낸 데이터를 받아서 각 변수에 삽입
self.final_received_message = incoming_message.decode('utf-8')
sender = self.final_received_message.split()[0]
num1 = self.final_received_message.split()[1]
num2 = self.final_received_message.split()[2]
num3 = self.final_received_message.split()[3]
num4 = self.final_received_message.split()[4]
num5 = self.final_received_message.split()[5]
num6 = self.final_received_message.split()[6]
num7 = self.final_received_message.split()[7]
self.final_received_message = (sender+"이(가) 선택한 번호 : {0} {1} {2} {3} {4} {5} {6}\n".format(num1, num2, num3, num4, num5, num6, num7))
if self.draw_num == 1:
self.lot1.append(sender)
self.lot1.append(num1)
self.lot1.append(num2)
self.lot1.append(num3)
self.lot1.append(num4)
self.lot1.append(num5)
self.lot1.append(num6)
self.lot1.append(num7)
print(self.lot1)
if self.draw_num == 2:
self.lot2.append(sender)
self.lot2.append(num1)
self.lot2.append(num2)
self.lot2.append(num3)
self.lot2.append(num4)
self.lot2.append(num5)
self.lot2.append(num6)
self.lot2.append(num7)
print(self.lot2)
if self.draw_num == 3:
self.lot3.append(sender)
self.lot3.append(num1)
self.lot3.append(num2)
self.lot3.append(num3)
self.lot3.append(num4)
self.lot3.append(num5)
self.lot3.append(num6)
self.lot3.append(num7)
print(self.lot3)
if self.draw_num == 4:
self.lot4.append(sender)
self.lot4.append(num1)
self.lot4.append(num2)
self.lot4.append(num3)
self.lot4.append(num4)
self.lot4.append(num5)
self.lot4.append(num6)
self.lot4.append(num7)
print(self.lot4)
if self.draw_num == 5:
self.lot5.append(sender)
self.lot5.append(num1)
self.lot5.append(num2)
self.lot5.append(num3)
self.lot5.append(num4)
self.lot5.append(num5)
self.lot5.append(num6)
self.lot5.append(num7)
print(self.lot5)
self.send_all_clients(self.final_received_message)
self.draw_num -= 1
if self.draw_num != 0: #복권 수가 남았을 경우
self.final_received_message = ('추첨까지 남은 복권 : '+str(self.draw_num)+'개\n')
self.send_all_clients(self.final_received_message)
else: #복권 수가 남지 않았을 경우
self.final_received_message = ('복권 추첨을 시작합니다!\n\n')
self.send_all_clients(self.final_received_message)
self.drawing_of_Lots(c_socket)
c_socket.close()
def send_all_clients(self, senders_socket): #서버에게 보내는 메시지
for client in self.clients:
socket, (ip, port) = client
if socket is not senders_socket:
try:
socket.sendall(self.final_received_message.encode('utf-8'))
except:
pass
def drawing_of_Lots(self, senders_socket): #복권 추첨
win_number_list = []
win_number = 0
self.lots.append(self.lot1)
self.lots.append(self.lot2)
self.lots.append(self.lot3)
self.lots.append(self.lot4)
self.lots.append(self.lot5)
for i in range(0, 7):
while True:
win_number = random.randrange(1,46) #랜덤 모듈 이용
if win_number not in win_number_list:
break
win_number_list.append(win_number)
for i in range(0, 7): #이중 for문을 이용하여 해당 숫자가 있을 경우 win 문자 삽입
for j in range(0, 5):
if str(win_number_list[i]) not in self.lots[j]:
pass
else:
self.lots[j].append('win')
self.final_received_message = ('당첨 번호는 ') #당첨 번호 출력
for i in range(0, 7):
self.final_received_message += str(win_number_list[i])+' '
self.final_received_message += ('입니다!\n')
self.send_all_clients(self.final_received_message)
#복권의 값에 맞은 개수 삽입
for i in range(0, 5):
if self.lots[i].count('win') >= 6:
self.lot_score[i] = '6'
continue
elif self.lots[i].count('win') == 5:
self.lot_score[i] = '5'
continue
elif self.lots[i].count('win') == 4:
self.lot_score[i] = '4'
continue
elif self.lots[i].count('win') == 3:
self.lot_score[i] = '3'
continue
elif self.lots[i].count('win') == 2:
self.lot_score[i] = '2'
continue
#이중 for문으로 등수 출력
for i in range(0, 5):
for j in range(2, 7):
if self.lot_score[i] == str(j):
msg = ""
if(i == 2):
msg = '5개의 복권 중 '+self.lots[i][0]+'님이 선택하신 '+str(5-i)+'번째 복권이 '+str(j)+'개를 맞혀 '
msg += '5등에 당첨되셨습니다!\n'
if(i == 3):
msg = '5개의 복권 중 '+self.lots[i][0]+'님이 선택하신 '+str(5-i)+'번째 복권이 '+str(j)+'개를 맞혀 '
msg += '4등에 당첨되셨습니다!\n'
if(i == 4):
msg = '5개의 복권 중 '+self.lots[i][0]+'님이 선택하신 '+str(5-i)+'번째 복권이 '+str(j)+'개를 맞혀 '
msg += '3등에 당첨되셨습니다!\n'
if(i == 5):
msg = '5개의 복권 중 '+self.lots[i][0]+'님이 선택하신 '+str(5-i)+'번째 복권이 '+str(j)+'개를 맞혀 '
msg += '2등에 당첨되셨습니다!\n'
if(i >= 6):
msg = '5개의 복권 중 '+self.lots[i][0]+'님이 선택하신 '+str(5-i)+'번째 복권이 '+str(j)+'개를 맞혀 '
msg += '1등에 당첨되셨습니다!\n'
self.final_received_message = msg
self.send_all_clients(self.final_received_message)
if __name__ == "__main__":
LotteryServer()
<file_sep>/FinalClient/FinalProject_Client.py
from socket import *
from tkinter import *
from tkinter.scrolledtext import ScrolledText
from threading import *
class LotteryClient:
client_socket = None
def __init__(self, ip, port): #메인함수
self.initialize_socket(ip, port)
self.initialize_gui()
self.listen_thread()
def initialize_socket(self, ip, port): #server에 연결
'''
TCP socket을 생성하고 server에게 연결
'''
self.client_socket = socket(AF_INET, SOCK_STREAM)
remote_ip = ip
remote_port = port
self.client_socket.connect((remote_ip, remote_port))
def send_chat(self):
'''
message를 전송하는 callback함수
'''
senders_name = self.name_widget.get().strip() #사용자 이름을 가져온다
# 각 숫자들을 가져온다.
data1 = self.enter_number1.get()+' '
data2 = self.enter_number2.get()+' '
data3 = self.enter_number3.get()+' '
data4 = self.enter_number4.get()+' '
data5 = self.enter_number5.get()+' '
data6 = self.enter_number6.get()+' '
data7 = self.enter_number7.get().strip()
data_num = (data1+data2+data3+data4+data5+data6+data7)
send_to_server_message = (senders_name+' '+data_num).encode('utf-8') #전체 숫자 데이터를 인코딩화
self.chat_transcript_area.yview(END)
self.client_socket.send(send_to_server_message)
return 'break'
def initialize_gui(self):
'''
위젯을 배치하고 초기화한다.
'''
self.root = Tk()
fr = []
for i in range(0, 5):
fr.append(Frame(self.root))
fr[i].pack(fill=BOTH)
self.name_label = Label(fr[0], text='사용자 이름')
self.recv_label = Label(fr[1], text='복권 추첨 서버 메시지')
self.send_label = Label(fr[3], text='복권 번호 입력')
self.send_btn = Button(fr[3], text='전송', command=self.send_chat)
self.chat_transcript_area = ScrolledText(fr[2], height=20, width=60)
self.name_widget = Entry(fr[0], width=15)
self.enter_number1 = Entry(fr[4], width=5)
self.enter_number2 = Entry(fr[4], width=5)
self.enter_number3 = Entry(fr[4], width=5)
self.enter_number4 = Entry(fr[4], width=5)
self.enter_number5 = Entry(fr[4], width=5)
self.enter_number6 = Entry(fr[4], width=5)
self.number7th_label = Label(fr[4], text='보너스 번호')
self.enter_number7 = Entry(fr[4], width=5)
self.name_label.pack(side=LEFT)
self.name_widget.pack(side=LEFT)
self.recv_label.pack(side=LEFT)
self.send_btn.pack(side=RIGHT, padx=20)
self.chat_transcript_area.pack(side=LEFT, padx=2, pady=2)
self.send_label.pack(side=LEFT)
self.enter_number1.pack(side=LEFT, padx=2, pady=2)
self.enter_number2.pack(side=LEFT, padx=2, pady=2)
self.enter_number3.pack(side=LEFT, padx=2, pady=2)
self.enter_number4.pack(side=LEFT, padx=2, pady=2)
self.enter_number5.pack(side=LEFT, padx=2, pady=2)
self.enter_number6.pack(side=LEFT, padx=2, pady=2)
self.number7th_label.pack(side=LEFT)
self.enter_number7.pack(side=LEFT, padx=2, pady=2)
def listen_thread(self):
'''
Thread를 생성하고 시작한다
'''
t = Thread(target=self.receive_message, args=(self.client_socket,))
t.start()
def receive_message(self, so):
'''
서버로부터 메시지를 수신하고 문서창에 표시한다
'''
while True:
buf = so.recv(1024) #등수 출력 문자열이 길어 1024로 설정
if not buf:
break
self.chat_transcript_area.insert('end', buf.decode('utf-8') + '\n')
self.chat_transcript_area.yview(END)
so.close()
if __name__ == "__main__":
ip = input("server IP addr: ")
if ip =='':
ip = '127.0.0.1'
port = 2500
LotteryClient(ip,port)
mainloop()
<file_sep>/README.md
# 개요
TCP IP 기말 프로젝트
멀티 스레드 기반 다중 접속 가상 복권 프로그램
# 설명
15주차 교안의 GUI Chat Server를 기반으로 하는 가상 복권 프로그램입니다.
#가정
5개의 복권을 선택하면 추첨이 시작됩니다.
사용자의 이름은 1~45의 숫자가 아니어야 합니다.
사용자의 이름과 숫자는 공백이 아니어야 하며 선택되는 숫자는 중복되지 않아야 합니다.
#아쉬운점
추첨이 끝나고 등수가 출력되는 부분에 약간 오류가 있는 것을 확인하였으나 시간 관계상 수정하지 못하였습니다.
이하 실행 사진입니다.
소스 실행 사진

시작 시 서버 출력 사진

복권 숫자 전송 시 서버 출력 사진

복권 추첨 후 출력

| d8160ef0632cbf524b74ce145d3a61465f1c46f8 | [
"Markdown",
"Python"
] | 3 | Python | sangukO/Final | 61c2f71013e921e3015d88d31208171379ff5597 | 18eb0db80d1e981ab179c3ebd17caf5976b4d8f2 |
refs/heads/master | <repo_name>LiliyaTereschenko/gnl<file_sep>/main.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include "get_next_line.h"
int main(int argc, char **argv)
{
int fd;
char *line;
int i;
i = 1;
if (argc == 1)
{
int k = 0;
while (get_next_line(0, &line) > 0)
{
printf("line %d = %s\n", k, line);
k++;
}
}
while (i < argc)
{
printf("argv[%d] = %s\n", i, argv[i]);
fd = open(argv[i], O_RDONLY);
printf("fd = %d\n", fd);
if (fd == -1)
write(1, "error file\n", 11);
int j = 0;
while (get_next_line(fd, &line) > 0)
{
printf("line %d = %s\n", j, line);
j++;
}
i++;
close(fd);
}
// printf("fd = 410, %d\n" ,get_next_line(410, &line));
return (0);
} | 153ed51635c590bb1edbdb2412918cb7de5e2fc4 | [
"C"
] | 1 | C | LiliyaTereschenko/gnl | 127706e8a75d7891dd13a7a09389d9dcb58e05db | 7b68e3ac5f9d66e047fe9f13276f93c571154b39 |
refs/heads/master | <repo_name>rootednode/cthuluwm<file_sep>/config.h
/* appearance */
static const char font[] = "-*-termsyn.icons-medium-*-*-*-11-*-*-*-*-*-*";
static const char normbordercolor[] = "#000000";
static const char normbgcolor[] = "#000000";
static const char normfgcolor[] = "#707070";
static const char selbordercolor[] = "#707070";
static const char selbgcolor[] = "#242424";
static const char selfgcolor[] = "#ffffff";
static const char alertbordercolor[] = "#ff6600";
static const char alertbgcolor[] = "#000000";
static const char alertfgcolor[] = "#ffffff";
static const char* colors[][ColLast] = {
/* border foreground background use */
{ normbordercolor, normfgcolor, normbgcolor }, /* normal */
//{ normbordercolor, "#303030", normbgcolor }, /* error */
//{ normbordercolor, "#276CC2", normbgcolor }, /* delim */
//{ normbordercolor, "#e0b020", normbgcolor }, /* artist */
//{ normbordercolor, "#e06000", normbgcolor }, /* title */
//{ normbordercolor, "#b10000", normbgcolor }, /* hot */
//{ normbordercolor, "#b15c00", normbgcolor }, /* medium */
//{ normbordercolor, "#6cb100", normbgcolor }, /* cool */
};
static const unsigned int borderpx = 1; /* border pixel of windows */
static const unsigned int snap = 10; /* snap pixel */
static const double shade = 1.0; /* opacity of unfocussed clients */
static const unsigned int gappx = 5; /* gap between clients */
static const Bool monobar = True; /* Draw selected window title not inverse */
static const int nmaster = 1; /* default number of clients in the master area */
static const Bool systray_enable = True; /* Provide a Systray */
static const int systray_spacing = 3; /* Pixel between Systray Symbols */
static const Bool autostart = True;
static const Bool mousefocus = True;
#include "bitmaps.h"
char sstrings[][30] = {
"^[f276CC2;|^[f;",
"^[f276CC2;·^[f;",
};
static const Rule rules[] = {
/* class instance title tags mask isfloating monitor opacity panel scratchpad */
{ "DWM-TAG1", NULL, NULL, 1 << 0, False, -1, -1, False, False },
{ "DWM-TAG2", NULL, NULL, 1 << 1, False, -1, -1, False, False },
{ "DWM-TAG3", NULL, NULL, 1 << 2, False, -1, -1, False, False },
{ "DWM-TAG4", NULL, NULL, 1 << 3, False, -1, -1, False, False },
{ "DWM-TAG5", NULL, NULL, 1 << 4, False, -1, -1, False, False },
{ "DWM-TAG6", NULL, NULL, 1 << 5, False, -1, -1, False, False },
{ "DWM-TAG7", NULL, NULL, 1 << 6, False, -1, -1, False, False },
{ "DWM-TAG8", NULL, NULL, 1 << 7, False, -1, -1, False, False },
{ "DWM-TAG9", NULL, NULL, 1 << 8, False, -1, -1, False, False },
{ "Gimp", NULL, NULL, 0, True, 0, -1, False, False },
{ "URxvt", NULL, NULL, 0, False, -1, -1, False, False },
{ "wine", NULL, NULL, 12, True, 0, -1, False, False },
{ "Geany", NULL, NULL, 1 << 2, False, 0, -1, False, False },
{ "Eclipse", NULL, NULL, 1 << 2, False, 0, -1, False, False },
{ "Iron", NULL, NULL, 1 << 3, False, 1, -1, False, False },
{ "Firefox", NULL, NULL, 1 << 3, False, 1, -1, False, False },
{ "Thunderbird", NULL, NULL, 1 << 4, False, 0, -1, False, False },
{ "Pidgin", NULL, NULL, 1 << 5, False, 0, -1, False, False },
{ "VirtualBox", NULL, NULL, 1 << 6, True, 0, -1, False, False },
{ "Keepassx", NULL, NULL, 1 << 8, True, 1, -1, False, False },
{ "gnome-alsamixer", NULL, NULL, 0, True, 0, -1, False, False },
{ "wicd-client.py", NULL, NULL, 0, True, 0, -1, False, False },
{ "alsa-tray", NULL, NULL, 0, True, 0, -1, False, False },
{ NULL, "urxvtmail", NULL, 1 << 4, False, 0, -1, False, False },
{ NULL, "urxvtmon", NULL, 1 << 9, False, 0, -1, False, False },
{ NULL, "urxvtaud", NULL, 1 << 11, False, 0, -1, False, False },
{ NULL, "urxvtirc", NULL, 1 << 12, False, 0, -1, False, False },
{ NULL, "urxvtnews", NULL, 1 << 13, False, 0, -1, False, False },
{ NULL, "urxvtnotes", NULL, 1 << 8, False, 0, -1, False, False },
{ NULL, "dwm-scratchpad", NULL, ~0, True, -1, 0.8, False, 1 } /* multiple scratchpads are possible, just number them */
};
/* layout(s) */
static const float mfact = 0.55; /* factor of master area size [0.05..0.95] */
static const Bool resizehints = False; /* True means respect size hints in tiled resizals */
static const float attachmode = AttAsFirst; /* Attach Mode */
/* addons: layouts */
#include "layouts/nbstack.c" /* bottom stack (tiling) */
#include "layouts/bstackhoriz.c" /* bottom stack (tower like stack) */
#include "layouts/grid.c" /* regular grid */
#include "layouts/pidgin.c"
//#include "layouts/gaplessgrid.c" /* best fitting grid */
//#include "layouts/fibonacci.c" /* spiral like arrangement */
static const Layout layouts[] = {
/* symbol gap? arrange */
{ "e", False, grid, 1}, /* Regular Grid */
{ "a", False, ntile, 1 }, /* Tiled (first entry is default) */
{ "d", False, nbstack, 1}, /* Bottom Stack */
{ "f", False, bstackhoriz, 1 }, /* Bottom Stack with horizontal Stack */
{ "c", False, monocle, 1 }, /* Monocle */
{ "b", False, NULL, 0 }, /* Floating */
{ "g", True, pidgin, 0 },
{ NULL, True, NULL, 0 }, /* End of layouts is null */
};
/* tagging */
static const Tag tags[] = {
/* name layout mfact, attachmode, nmaster */
{ "tty0", &layouts[0], -1, -1, -1 },
{ "tty1", &layouts[0], -1, -1, -1 },
{ "dev", &layouts[0], -1, -1, -1 },
{ "www", &layouts[4], -1, -1, -1 },
{ "mail", &layouts[0], -1, -1, -1 },
{ "im", &layouts[6], -1, -1, -1 },
{ "vm", &layouts[5], -1, -1, -1 },
{ "fs", &layouts[0], -1, -1, -1 },
{ "note", &layouts[0], -1, -1, -1 },
{ "mon", &layouts[0], -1, -1, -1 },
{ "rdp", &layouts[5], -1, -1, -1 },
{ "aud", &layouts[0], -1, -1, -1 },
{ "irc", &layouts[0], -1, -1, -1 },
{ "news", &layouts[0], -1, -1, -1 },
};
/* addons: other */
#include "other/togglemax.c"
#include "other/push.c"
/* key definitions */
#define ALTKEY Mod1Mask
#define MODKEY Mod4Mask
#define TAGKEYS(KEY,TAG) \
{ MODKEY, KEY, view, {.ui = 1 << TAG} }, \
{ MODKEY|ControlMask, KEY, toggleview, {.ui = 1 << TAG} }, \
{ MODKEY|ShiftMask, KEY, tag, {.ui = 1 << TAG} }, \
{ MODKEY|ControlMask|ShiftMask, KEY, toggletag, {.ui = 1 << TAG} },
/* helper for spawning shell commands in the pre dwm-5.0 fashion */
#define SHCMD(cmd) { .v = (const char*[]){ "/bin/sh", "-c", cmd, NULL } }
/* commands */
static const char *dmenucmd[] = { "dmenu_run", "-fn", font, "-nb", normbgcolor, "-nf", normfgcolor, "-sb", selbgcolor, "-sf", selfgcolor, NULL };
static const char *menucmd[] = { "mygtkmenu", "/home/kris/.mygtkmenu", NULL };
static const char *termcmd[] = { "urxvt", NULL };
static const char *wwwcmd[] = { "iron", NULL };
static const char *wwwcmd2[] = { "firefox", NULL };
static const char *fmcmd[] = { "thunar", NULL };
static const char *xkillcmd[] = { "xkill", NULL };
static const char *oblogout[] = { "oblogout", NULL };
static const char *volplus[] = { "amixer", "set", "Master", "5%+", NULL };
static const char *volminus[] = { "amixer", "set", "Master", "5%-", NULL };
static const char *volmute[] = { "amixer", "set", "Master", "toggle", NULL };
static Key keys[] = {
/* modifier key function argument */
{ MODKEY, XK_Down, spawn, {.v = volminus } },
{ MODKEY, XK_Up, spawn, {.v = volplus } },
{ MODKEY, XK_m, spawn, {.v = volmute } },
/* spawn */
{ MODKEY, XK_p, spawn, {.v = dmenucmd } },
{ MODKEY, XK_Return, spawn, {.v = termcmd } },
{ MODKEY, XK_w, spawn, {.v = wwwcmd } },
{ MODKEY|ShiftMask, XK_w, spawn, {.v = wwwcmd2 } },
{ MODKEY, XK_f, spawn, {.v = fmcmd } },
{ MODKEY, XK_k, spawn, {.v = xkillcmd } },
{ MODKEY|ShiftMask, XK_Escape, spawn, {.v = oblogout } },
{ MODKEY, XK_q, killclient, {0} },
{ MODKEY, XK_r, launcher, {0} },
{ ALTKEY, XK_F2, launcher, {0} },
/* stack */
{ MODKEY, XK_Return, zoom, {0} },
{ MODKEY, XK_Page_Up, togglemax, {0} },
{ MODKEY, XK_Left, focusstack, {.i = +1 } },
{ MODKEY, XK_Right, focusstack, {.i = -1 } },
{ MODKEY|ControlMask, XK_Left, pushdown, {0} },
{ MODKEY|ControlMask, XK_Right, pushup, {0} },
/* tab */
//{ MODKEY, XK_Tab, view, {0} },
{ MODKEY|ShiftMask, XK_Tab, focustoggle, {0} },
{ ALTKEY, XK_Tab, nextlayout, {0} },
//{ MODKEY, XK_space, toggle_scratch, {.i = 1} }, /* toggles scratch with number i on/off. */
//{ MODKEY|ControlMask, XK_space, setlayout, {0} },
//{ MODKEY|ShiftMask, XK_space, togglefloating, {0} },
//{ MODKEY|ShiftMask, XK_t, setlayout, {.v = &layouts[0]} }, /* tile */
//{ MODKEY|ShiftMask, XK_f, setlayout, {.v = &layouts[1]} }, /* float */
//{ MODKEY|ShiftMask, XK_m, setlayout, {.v = &layouts[2]} }, /* monocle */
//{ MODKEY|ShiftMask, XK_b, setlayout, {.v = &layouts[3]} }, /* bottomstack */
//{ MODKEY|ShiftMask, XK_g, setlayout, {.v = &layouts[4]} }, /* gaplessgrid */
//{ MODKEY|ShiftMask, XK_r, setlayout, {.v = &layouts[5]} }, /* grid */
//{ MODKEY|ShiftMask, XK_z, setlayout, {.v = &layouts[6]} }, /* bstackhoriz */
//{ MODKEY|ShiftMask, XK_p, setlayout, {.v = &layouts[7]} }, /* spiral */
//{ MODKEY|ShiftMask, XK_d, setlayout, {.v = &layouts[8]} }, /* dwindle */
/* nmaster */
{ MODKEY|ShiftMask, XK_h, incnmaster, {.i = +1 } },
{ MODKEY|ShiftMask, XK_l, incnmaster, {.i = -1 } },
{ MODKEY, XK_x, setnmaster, {.i = 1 } },
/* tag keys */
TAGKEYS( XK_1, 0)
TAGKEYS( XK_2, 1)
TAGKEYS( XK_3, 2)
TAGKEYS( XK_4, 3)
TAGKEYS( XK_5, 4)
TAGKEYS( XK_6, 5)
TAGKEYS( XK_7, 6)
TAGKEYS( XK_8, 7)
TAGKEYS( XK_9, 8)
//{ MODKEY, XK_0, view, {.ui = ~0 } },
//{ MODKEY|ShiftMask, XK_0, tag, {.ui = ~0 } },
/* quit */
//{ MODKEY|ShiftMask, XK_q, quit, {.i = 0} },
//{ MODKEY|ControlMask, XK_q, quit, {.i = 23} },
/* monitor */
{ MODKEY, XK_comma, focusmon, {.i = -1 } },
{ MODKEY, XK_period, focusmon, {.i = +1 } },
{ MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1 } },
{ MODKEY|ShiftMask, XK_period, tagmon, {.i = +1 } },
/* appereance */
{ MODKEY, XK_h, setmfact, {.f = -0.05} },
{ MODKEY, XK_l, setmfact, {.f = +0.05} },
//{ MODKEY|ControlMask, XK_q, setattachmode, {.i = AttAsFirst } },
//{ MODKEY|ControlMask, XK_m, setattachmode, {.i = AttAsLast } },
//{ MODKEY|ControlMask, XK_1, setattachmode, {.i = AttAbove } },
//{ MODKEY|ControlMask, XK_a, setattachmode, {.i = AttBelow } },
//{ MODKEY|ControlMask, XK_w, setattachmode, {.i = AttAside } },
};
/* button definitions */
/* click can be ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, or ClkRootWin */
static Button buttons[] = {
/* click event mask button function argument */
//{ ClkLtSymbol, 0, Button1, setlayout, {0} },
//{ ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[2]} },
{ ClkWinTitle, 0, Button3, spawn, {.v = menucmd } },
{ ClkClientWin, MODKEY, Button3, spawn, {.v = menucmd } },
{ ClkTagBar, 0, Button3, spawn, {.v = menucmd } },
{ ClkLtSymbol, 0, Button1, nextlayout, {0} },
{ ClkWinTitle, 0, Button1, focusonclick, {0} },
//{ ClkWinTitle, 0, Button2, zoom, {0} },
//{ ClkWinTitle, 0, Button4, focusstack, {.i = +1} },
//{ ClkWinTitle, 0, Button5, focusstack, {.i = -1} },
{ ClkClientWin, ALTKEY, Button1, movemouse, {0} },
{ ClkClientWin, ALTKEY, Button2, togglefloating, {0} },
{ ClkClientWin, ALTKEY, Button3, resizemouse, {0} },
{ ClkTagBar, 0, Button1, view, {0} },
//{ ClkTagBar, 0, Button3, toggleview, {0} },
{ ClkTagBar, MODKEY, Button1, tag, {0} },
//{ ClkTagBar, MODKEY, Button3, toggletag, {0} },
};
<file_sep>/autostart
#!/bin/bash
#
xscreensaver --no-splash
# IMPORTANT!
# Avoids this script from exiting until DWM finishes
# Use pstree to debug your autostart
# note: it's possible to find DWM's PID by other means,
# but bash provides it out of the box neatly
while kill -0 $PPID; do sleep 10; done
# Exit
# If you get any processes that run even after log out, kill them here
# eg. killall redshift
<file_sep>/Makefile
# cthuluwm
# See LICENSE file for copyright and license details.
include config.mk
SRC = cthuluwm.c
OBJ = ${SRC:.c=.o}
all: options cthuluwm
options:
@echo cthuluwm build options:
@echo "CFLAGS = ${CFLAGS}"
@echo "LDFLAGS = ${LDFLAGS}"
@echo "CC = ${CC}"
.c.o:
@echo CC $<
@${CC} -c ${CFLAGS} $<
${OBJ}: config.h config.mk
config.h:
@echo creating $@ from config.def.h
@cp config.def.h $@
cthuluwm: ${OBJ}
@echo CC -o $@
@${CC} -o $@ ${OBJ} ${LDFLAGS}
clean:
@echo cleaning
@rm -f cthuluwm ${OBJ} cthuluwm-${VERSION}.tar.gz
dist: clean
@echo creating dist tarball
@mkdir -p cthuluwm-${VERSION}
@cp -R LICENSE Makefile README config.def.h config.mk \
cthuluwm.png cthuluwm.1 ${SRC} cthuluwmm other/ layouts/ cthuluwm-${VERSION}
@tar -cf cthuluwm-${VERSION}.tar cthuluwm-${VERSION}
@gzip cthuluwm-${VERSION}.tar
@rm -rf cthuluwm-${VERSION}
install: all
@echo installing executable file to ${DESTDIR}${PREFIX}/bin
@mkdir -p ${DESTDIR}${PREFIX}/bin
@cp -f cthuluwm ${DESTDIR}${PREFIX}/bin
@cp -f cthuluwmm ${DESTDIR}${PREFIX}/bin
@chmod 755 ${DESTDIR}${PREFIX}/bin/cthuluwm
@chmod 755 ${DESTDIR}${PREFIX}/bin/cthuluwmm
uninstall:
@echo removing executable file from ${DESTDIR}${PREFIX}/bin
@rm -f ${DESTDIR}${PREFIX}/bin/cthuluwm
@rm -f ${DESTDIR}${PREFIX}/bin/cthuluwmm
@echo removing manual page from ${DESTDIR}${MANPREFIX}/man1
@rm -f ${DESTDIR}${MANPREFIX}/man1/cthuluwm.1
@echo removing src files rom ${DESTDIR}${MANPREFIX}/share
@rm -Rf ${DESTDIR}${PREFIX}/share/cthuluwm
.PHONY: all options clean dist install uninstall
<file_sep>/version.h
#ifndef VERSION_H
#define VERSION_H
#define VERSION "d052ad26b35849367e6a5e69d2342e2c97cc784e"
#define COMMIT "Margins"
#endif /* VERSION_H */
| 5acf760b7207136172fd589b66e969a44cdf8bbc | [
"C",
"Makefile",
"Shell"
] | 4 | C | rootednode/cthuluwm | 05652e0a953df4ecaa27cea6aa971e4847fb7977 | 3ae499a75b95f689e7bfc8fc28d87080997bc063 |
refs/heads/master | <file_sep>import React, { Component } from 'react'
import CKEditor from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import ReactHtmlParser from 'react-html-parser'
export default class AddBlog extends Component {
constructor(props){
super(props)
this.state = {
title:'',
body:'',
}
this.handleOnChange = this.handleOnChange.bind(this)
this.handleTitleChange = this.handleTitleChange.bind(this)
this.publish = this.publish.bind(this)
this.discart = this.discart.bind(this)
}
handleOnChange(e, editor){
this.setState({
body:editor.getData()
})
}
handleTitleChange(e){
this.setState({
title:e.target.value
})
}
publish(){
//publishing to database
}
discart(){
//discarting
}
render() {
return(
<div style={{backgroundColor:'#f8f9fa'}}>
<div className="container h-100 border-left border-right border-top" style={{backgroundColor:'white'}}>
<h3>Add New Blog</h3>
<hr/>
<div className="form-group">
<label>Title</label>
<input
type="text"
required
className="form-control"
value={this.state.title}
onChange={this.handleTitleChange}
/>
</div>
<label>Body</label>
<CKEditor
editor={ClassicEditor}
onChange={this.handleOnChange}
/>
<hr/>
<div className="text-right">
<button className="btn btn-danger" onClick={this.discart} style={{marginRight:5,}}>Discart</button>
<button className="btn btn-success" onClick={this.publish}>Publish</button>
</div>
<hr/>
<h4>Demo</h4>
<div className="container border-left border-right border-top border-bottom" style={{backgroundColor:'whitesmoke', height:300}}>
{ReactHtmlParser(this.state.body)}
</div>
<hr/>
</div>
</div>
);
}
}
| d7578822bf2c5965db09f9b2fea24b779a4c1bae | [
"JavaScript"
] | 1 | JavaScript | JaweedShuja/ReactJs | 8b0203e43c54575f7a66e2674e6d20369e942306 | 6f3084f2d028d4fcaf2563bee1dea280f9c20b24 |
refs/heads/master | <file_sep>use_frameworks!
target 'irTest2_Tests' do
pod 'irTest2', :path => '../'
end
| 03ad250211ed1ad43060136c9db5a8f9fe998939 | [
"Ruby"
] | 1 | Ruby | ashraf-nv/irTest2 | 449153e8329389b56341ad43d4d8c8394e207594 | 92807872dc75ef8ec2d5ba81275323344db54f03 |
refs/heads/master | <file_sep>package com.swy.ktpractice
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import com.swy.ktpractice.fragments.NewsFragment
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
changeFragment(NewsFragment())
}
fun changeFragment(f: Fragment) {
val ft = supportFragmentManager.beginTransaction()
ft.replace(R.id.fl_container, f)
ft.commit()
}
}
<file_sep>package com.swy.ktpractice.adapter
import android.annotation.SuppressLint
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import com.swy.ktpractice.R
import com.swy.ktpractice.adapter.common.ViewType
import com.swy.ktpractice.adapter.common.ViewTypeDelegateAdapter
import com.swy.ktpractice.bean.NewsItem
import com.swy.ktpractice.extension.getFriendlyTime
import com.swy.ktpractice.extension.inflate
import com.swy.ktpractice.extension.loadingImage
import kotlinx.android.synthetic.main.news_item.*
import kotlinx.android.synthetic.main.news_item.view.*
@Suppress("UNREACHABLE_CODE")
class NewsDelegateAdapter : ViewTypeDelegateAdapter {
override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder = NewsViewHolder(parent)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType) {
holder as NewsViewHolder
holder.bind(item as NewsItem)
}
class NewsViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(parent.inflate(R.layout.news_item)) {
private val img_thumbnail = itemView.img_thumbnail
private val description = itemView.description
private val author = itemView.author
private val comments = itemView.comments
private val time = itemView.time
@SuppressLint("SetTextI18n")
fun bind(item: NewsItem) {
description.text = item.title
author.text = item.author
comments.text = "${item.numComments} comments"
time.text = item.created.getFriendlyTime()
img_thumbnail.loadingImage(item.url.toString())
}
}
}<file_sep>package com.swy.ktpractice.adapter
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import com.swy.ktpractice.R
import com.swy.ktpractice.adapter.common.ViewType
import com.swy.ktpractice.adapter.common.ViewTypeDelegateAdapter
import com.swy.ktpractice.extension.inflate
class LoadingDelegateAdapter : ViewTypeDelegateAdapter {
override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder = FooterHolderView(parent)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType) {
}
class FooterHolderView(parent: ViewGroup) : RecyclerView.ViewHolder(parent.inflate(R.layout.news_loading_item))
}<file_sep>package com.swy.ktpractice.model.interfaze
import com.swy.ktpractice.bean.NewsItem
import com.swy.ktpractice.model.RedditNewsResponse
import retrofit2.Call
interface NewsApi {
fun getNews(after: String, limit: Int): Call<RedditNewsResponse>
}<file_sep>package com.swy.ktpractice.bean
import android.os.Parcel
import android.os.Parcelable
import com.swy.ktpractice.adapter.common.AdapterConstants
import com.swy.ktpractice.adapter.common.ViewType
data class NewsItem(val author: String,
val title: String,
val numComments: Int,
val created: Long,
val thumbnail: String,
val url: String?) : ViewType, Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readInt(),
parcel.readLong(),
parcel.readString(),
parcel.readString()) {
}
override fun getViewType(): Int = AdapterConstants.NEWS
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(author)
parcel.writeString(title)
parcel.writeInt(numComments)
parcel.writeLong(created)
parcel.writeString(thumbnail)
parcel.writeString(url)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<NewsItem> {
override fun createFromParcel(parcel: Parcel): NewsItem {
return NewsItem(parcel)
}
override fun newArray(size: Int): Array<NewsItem?> {
return arrayOfNulls(size)
}
}
}<file_sep>package com.swy.ktpractice.adapter.common
object AdapterConstants{
val NEWS = 1
val LOADING = 2
}<file_sep>package com.swy.ktpractice.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.swy.ktpractice.NewsManager
import com.swy.ktpractice.R
import com.swy.ktpractice.adapter.NewsAdapter
import com.swy.ktpractice.bean.NewsItem
import com.swy.ktpractice.bean.RedditNews
import com.swy.ktpractice.extension.inflate
import com.swy.ktpractice.extension.showSnackbar
import kotlinx.android.synthetic.main.news_fragment_layout.*
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
class NewsFragment : BaseFragment() {
private var redditNews: RedditNews? = null
companion object {
private var KEY_REDDIT_NEWS = "redditNews"
}
private val newsManager by lazy {
NewsManager()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return container?.inflate(R.layout.news_fragment_layout)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
news_list.apply {
news_list.setHasFixedSize(true)
news_list.layoutManager = LinearLayoutManager(context)
clearOnScrollListeners()
addOnScrollListener(InfiniteScrollListener({ requestData() }, news_list.layoutManager as LinearLayoutManager))
adapter = NewsAdapter()
}
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_REDDIT_NEWS)) {
var redditNews = savedInstanceState.get(KEY_REDDIT_NEWS) as RedditNews
var news = redditNews!!.news
(news_list.adapter as NewsAdapter).clearAndAddNews(news)
} else {
requestData()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
var news = (news_list.adapter as NewsAdapter).getNews()
if (redditNews != null && news.isNotEmpty()) {
outState?.putParcelable(KEY_REDDIT_NEWS, redditNews?.copy(news = news))
}
}
private fun requestData() {
val subscribe = newsManager.getNews(redditNews?.after ?: "", 10)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ retrievedNews ->
redditNews = retrievedNews
(news_list.adapter as NewsAdapter).addNews(redditNews!!.news)
}, { error ->
showSnackbar(news_list, error.message ?: "")
})
subscriptions.add(subscribe)
}
}<file_sep>package com.swy.ktpractice
import com.swy.ktpractice.bean.NewsItem
import com.swy.ktpractice.bean.RedditNews
import com.swy.ktpractice.model.RestApi
import com.swy.ktpractice.model.interfaze.NewsApi
import rx.Observable
import rx.observers.Observers
class NewsManager(private var api: NewsApi = RestApi()) {
fun getNews(after: String, limit: Int = 10): Observable<RedditNews> {
return Observable.create { subscriber ->
val execute = api.getNews(after, limit).execute()
var response = execute.body().data
if (execute.isSuccessful) {
var items = response.children.map {
var item = it.data
NewsItem(item.author, item.title, item.num_comments,
item.created, item.thumbnail, item.url)
}
var news = RedditNews(response.after ?: "", response.before ?: "", items)
subscriber.onNext(news)
subscriber.onCompleted()
} else {
subscriber.onError(Throwable(execute.message()))
}
}
}
}<file_sep>package com.swy.ktpractice.adapter
import android.support.v4.util.SparseArrayCompat
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import com.swy.ktpractice.adapter.common.AdapterConstants
import com.swy.ktpractice.adapter.common.ViewType
import com.swy.ktpractice.adapter.common.ViewTypeDelegateAdapter
import com.swy.ktpractice.bean.NewsItem
@Suppress("UNREACHABLE_CODE")
class NewsAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var items: ArrayList<ViewType>
private var delegateAdapters = SparseArrayCompat<ViewTypeDelegateAdapter>()
private val loadingItem = object : ViewType {
override fun getViewType(): Int = AdapterConstants.LOADING
}
init {
delegateAdapters.put(AdapterConstants.LOADING, LoadingDelegateAdapter())
delegateAdapters.put(AdapterConstants.NEWS, NewsDelegateAdapter())
items = ArrayList()
items.add(loadingItem)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return delegateAdapters.get(viewType).onCreateViewHolder(parent)
}
override fun getItemCount(): Int = items.size
override fun getItemViewType(position: Int): Int = items.get(position).getViewType()
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
delegateAdapters.get(getItemViewType(position)).onBindViewHolder(holder, items[position])
}
fun addNews(news: List<NewsItem>) {
var oldSize = items.size - 1
//先移除loading
items.removeAt(oldSize)
items.addAll(news)
items.add(loadingItem)
notifyItemRangeChanged(oldSize, items.size + 1)
}
fun addNews(news: NewsItem) {
var oldSize = items.size - 1
//先移除loading
items.removeAt(oldSize)
items.add(news)
items.add(loadingItem)
notifyItemRangeChanged(oldSize, items.size + 1)
}
fun getNews(): List<NewsItem> {
return items.filter {
it.getViewType() == AdapterConstants.NEWS
}.map { it as NewsItem }
}
fun clearAndAddNews(news: List<NewsItem>, isClear: Boolean = true) {
if (!isClear) {
addNews(news)
return
}
items.clear()
notifyItemRangeRemoved(0, getLastPosition())
items.addAll(news)
items.add(loadingItem)
notifyItemRangeInserted(0, items.size)
}
private fun getLastPosition() = if (items.lastIndex == -1) 0 else items.lastIndex
}<file_sep>package com.swy.ktpractice.bean
import android.os.Parcel
import android.os.Parcelable
data class RedditNews(
val after: String,
val before: String,
val news: List<NewsItem>) : Parcelable {
constructor(source: Parcel) : this(
source.readString(),
source.readString(),
source.createTypedArrayList(NewsItem.CREATOR)
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeString(after)
writeString(before)
writeTypedList(news)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<RedditNews> = object : Parcelable.Creator<RedditNews> {
override fun createFromParcel(source: Parcel): RedditNews = RedditNews(source)
override fun newArray(size: Int): Array<RedditNews?> = arrayOfNulls(size)
}
}
}<file_sep>package com.swy.ktpractice.extension
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import com.squareup.picasso.Picasso
import com.swy.ktpractice.R
fun ViewGroup.inflate(layoutId: Int, attachToRoot: Boolean = false): View {
return LayoutInflater.from(context).inflate(layoutId, this, attachToRoot)
}
fun ImageView.loadingImage(imaUrl: String) {
if (TextUtils.isEmpty(imaUrl)) {
Picasso.get().load(R.mipmap.ic_launcher).into(this)
} else {
Picasso.get().load(imaUrl).into(this)
}
}
fun Fragment.showSnackbar(view: View, message: String, duration: Int = Snackbar.LENGTH_SHORT) {
Snackbar.make(view, message, duration)
}
fun Fragment.showToast(message: String, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(context, message, duration)
}
<file_sep>package com.swy.ktpractice.adapter.common
interface ViewType {
fun getViewType(): Int
}<file_sep>package com.swy.ktpractice.model
import com.swy.ktpractice.bean.NewsItem
import com.swy.ktpractice.model.interfaze.NewsApi
import com.swy.ktpractice.model.interfaze.RedditApi
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
class RestApi :NewsApi {
private val redditApi: RedditApi
val baseUrl: String = "https://www.reddit.com"
init {
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(MoshiConverterFactory.create())
.build()
redditApi = retrofit.create(RedditApi::class.java)
}
override fun getNews(after: String, limit: Int): Call<RedditNewsResponse> {
return redditApi.getTopNews(after,limit)
}
}<file_sep>package com.swy.ktpractice.model.interfaze
import com.swy.ktpractice.bean.NewsItem
import com.swy.ktpractice.model.RedditNewsResponse
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface RedditApi {
@GET("top.json")
fun getTopNews(@Query("after") after: String, @Query("limit") limit: Int): Call<RedditNewsResponse>
} | 920cfc279c0fb01816c4a8ee484f19fe2ecf2ddd | [
"Kotlin"
] | 14 | Kotlin | SuWe1/KtPractice | f6558ba57b21c582421d1b152cad4e2f4a4c4c13 | 7e7909230367e7432aa6d52ae6e3afd6d2dd4478 |
refs/heads/master | <file_sep>/*
* =====================================================================================
*
* Filename: token.hpp
*
* Description: Tokens
*
* Version: 1.0
* Created: 02/13/2020 03:29:49 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
#include <ostream>
#include <string>
#ifndef DEBUG
#define DEBUG 1
#include <iostream>
#endif
#include "enum/tipo_token.hpp"
#include "pos.hpp"
class Token {
private:
Pos mPos;
public:
TipoToken tipo;
std::string lexema;
/*
* Substitue a virgula por ponto em tokens do tipo VALOR
*/
static bool substituiDelSeValor(std::string &lexema);
/* Token(const TipoToken tk = TipoToken::INITIAl, const std::string & = "",
*/
/* const int linha = -1, const int col = -1); */
Token(const TipoToken tk = TipoToken::INITIAl, const std::string & = "",
const Pos = Pos(-1, -1));
const auto &getPos(void) const { return mPos; }
std::ostream &print(std::ostream &out) const {
out << '{' << static_cast<int>(tipo) << ", " << lexema << '}';
return out;
}
/*
* Todo token é implicitamente um TipoToken
* apenas um shorthand para evitar tk.tipo == TipoToken::VALOR
* visto que assim permite apenas: tk == TipoToken::VALOR
*/
operator TipoToken() const { return tipo; }
};
/*
* Função para printar o Token
*/
std::ostream &operator<<(std::ostream &, const Token &);
std::ostream &operator<<(std::ostream &, const Pos &);
<file_sep>#pragma once
enum class Prec {
NULO,
TERMO_OP,
FATOR_OP,
};
<file_sep>/*
* =====================================================================================
*
* Filename: lex.cpp
*
* Description: Analisador léxico
*
* Version: 1.0
* Created: 02/13/2020 03:13:48 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#include "lex.hpp"
#include <cctype>
#include <iostream>
#include <stdexcept>
#include "erro.hpp"
#include "global.hpp"
#include "token.hpp"
[[noreturn]] void falhaAoAbrirArquivo(const fs::path& path) {
std::cerr << "Falha na abertura do arquivo: '" << path
<< "'. Verique se o caminho está "
"correto.\n";
throw std::runtime_error("Arquivo falhou ao abrir.");
}
Lex::Lex(const fs::path& in, const fs::path& out)
: mInputFile(in),
mOutputFile(out),
mPos(1, 0),
mPalavrasReservadas{{"SE", TipoToken::SE},
{"FACA", TipoToken::FACA},
{"ACABOU", TipoToken::ACABOU},
{"SENAO", TipoToken::SENAO},
{"ENQUANTO", TipoToken::ENQUANTO},
{"INTEIRO", TipoToken::TIPO},
{"QUEBRADO", TipoToken::TIPO},
{"LOGICO", TipoToken::TIPO}} {
/*
* Verifica se o arquivo de entrada tem o sufixo .c20192
*/
const std::string filename = in.filename();
const std::string sufixo = ".c20192";
const auto pos = filename.size() - sufixo.size() - 1;
if (pos <= 0 or filename.find(sufixo, pos) == std::string::npos) {
std::cerr << "Arquivos de entrada devem terminar com '" << sufixo
<< "'\n";
throw std::invalid_argument("Falta extensão '" + sufixo +
"' em arquivo.");
}
if (!mInputFile.is_open()) {
falhaAoAbrirArquivo(in);
}
if (!mOutputFile.is_open()) {
falhaAoAbrirArquivo(out);
}
G_filepath = in;
/*
* Cabeçalho de ajuda no arquivo de saída
*/
mOutputFile << "Lista de pares {COD_TOKEN, LEXEMA}\nO COD_TOKEN pode ser "
"checado no enum 'TipoToken' em 'enum/tipo_token.hpp'\nPS: "
"Comentários começam com '#' e vão até o final da linha\n\n";
}
Lex::~Lex() {
#ifdef DEBUG
std::clog << "[DEBUG] Lex - Linhas lidas: " << getLinha() << std::endl;
#endif
}
Token Lex::getToken(void) {
const auto tk = proxToken();
mOutputFile << tk << '\n';
return tk;
}
void Lex::analiseAteEOF(void) {
for (auto tk = getToken(); tk != TipoToken::FIMARQ; tk = getToken()) {
std::cout << tk << '\n';
}
}
Token Lex::proxToken(void) {
int estado = 0; // representa o q0 (estado inicial do afd)
char c; // representa a cabeça da fita
std::string lexema; // string lida
while (estado != EOF) {
switch (estado) {
case 0:
c = getChar(lexema);
switch (c) {
case '=':
estado = 7;
break;
case ',':
estado = 4;
break;
case '-':
case '+':
estado = 8;
break;
case '*':
case '/':
estado = 9;
break;
case '&':
estado = 12;
break;
case '|':
estado = 14;
break;
case '!':
estado = 16;
break;
case ';':
estado = 18;
break;
case '(':
estado = 19;
break;
case ')':
estado = 20;
break;
case '#':
estado = 21;
break;
case EOF:
estado = c;
break;
default:
if (isalpha(c)) {
estado = 1;
} else if (isdigit(c)) {
estado = 3;
} else if (isspace(c)) {
if (c == '\n') {
proximaLinha();
}
lexema.pop_back();
break;
} else {
throw ErroLexico(*this, lexema, "Σ");
}
}
break;
case 1:
if (c = getChar(lexema); !isalnum(c)) {
estado = 2;
}
break;
case 2:
ungetChar(lexema);
return criaToken(reservadaOuID(lexema), lexema);
case 3:
if (c = getChar(lexema); c == ',') {
estado = 4;
} else if (!isdigit(c)) {
estado = 5;
}
break;
case 4:
/*
* Substitue a ',' por '.' para facilitar o casting para double no
* semântico
*/
lexema.back() = '.';
if (c = getChar(lexema); isdigit(c)) {
estado = 6;
} else {
throw ErroLexico(*this, lexema, "[0-9]");
}
break;
case 5:
ungetChar(lexema);
return criaToken(TipoToken::VALOR, lexema);
case 6:
if (c = getChar(lexema); !isdigit(c)) {
estado = 5;
}
break;
case 7:
return criaToken(TipoToken::ATRIB, lexema);
case 8:
return criaToken(TipoToken::SINAL, lexema);
case 9:
return criaToken(TipoToken::BINOP, lexema);
case 12:
if (c = getChar(lexema); c == '&') {
return criaToken(TipoToken::BINOP, lexema);
}
throw ErroLexico(*this, lexema, "&");
// error
break;
case 14:
if (c = getChar(lexema); c == '|') {
return criaToken(TipoToken::BINOP, lexema);
}
throw ErroLexico(*this, lexema, "|");
break;
case 16:
return criaToken(TipoToken::NEG, lexema);
case 18:
return criaToken(TipoToken::PNTVIRG, lexema);
case 19:
return criaToken(TipoToken::ABREPRNT, lexema);
case 20:
return criaToken(TipoToken::FECHAPRNT, lexema);
case 21:
/* Estado de Comentário na linguagem */
if (c = getChar(lexema); c == '\n') {
#ifdef DEBUG
lexema.pop_back();
std::clog << "[DEBUG - Lex] {Comentário: " << lexema << '}'
<< std::endl;
#endif
lexema.clear();
estado = 0;
proximaLinha();
} else if (c == EOF) {
estado = c;
}
break;
}
}
return criaToken(TipoToken::FIMARQ, "\"EOF\"");
}
TipoToken Lex::reservadaOuID(const std::string& lexema) const {
try {
return mPalavrasReservadas.at(lexema);
} catch (const std::out_of_range&) {
return TipoToken::ID;
}
}
Token Lex::criaToken(const TipoToken tipo, const std::string& lexema) const {
return Token(tipo, lexema, getPos());
}
<file_sep>/*
* =====================================================================================
*
* Filename: ast.cpp
*
* Description: implementação da AST
*
* Version: 1.0
* Created: 02/21/2020 11:26:51 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#include "ast.hpp"
#include "constexpr.hpp"
#include "enum/prec.hpp"
#include "enum/tipo_dado.hpp"
#include "erro.hpp"
namespace AnaliseSintatica {
AST::AST(void)
: root(std::make_unique<NodeBloco>(TipoToken::PROGRAMA, nullptr,
TipoAST::BLOCO)) {
mPilha.push(root.get());
}
void AST::trocaToken(const Token &tk) {
auto &tkTopo = mPilha.top()->tk;
const auto tipo = tkTopo.tipo;
tkTopo = tk;
tkTopo.tipo = tipo;
}
AST::Node *AST::inserirNode(const Token &tk, const TipoAST tipo) {
if (auto no = inserirFolha(tk, tipo); no) {
mPilha.push(no);
}
return mPilha.top();
}
AST::Node *AST::inserirFolha(const Token &tk, const TipoAST tipo) {
auto const topo = mPilha.top();
switch (tipo) {
case TipoAST::BLOCO:
topo->childs.emplace_back(std::make_unique<NodeBloco>(tk, topo));
break;
case TipoAST::EXP:
/*
* Checando se o topo é uma EXP, se for então não precisa adicionar
* novamente ao topo
* Cenários onde isso poderia acontecer:
* exp -> sinal exp | ( exp )
*
* Nesses casos o sintatico manda um NodeExp mesmo já
* estando dentro da exp, aqui tratamos isso, mantendo a expressão
* linear para ser aplicável o algoritmo Shunting Yard
*/
if (*topo != TipoAST::EXP) {
topo->childs.emplace_back(std::make_unique<NodeExp>(tk, topo));
} else {
return nullptr;
}
break;
case TipoAST::EXPOP: {
std::unique_ptr<NodeExpOp> op;
if (tk == TipoToken::ID) {
op = std::make_unique<NodeExpID>(tk, topo);
} else if (tk == TipoToken::VALOR) {
op = std::make_unique<NodeExpValor>(tk, topo);
} else {
op = std::make_unique<NodeExpOp>(tk, topo);
}
if (*topo == TipoAST::EXP) {
/*
* Coloca op (num ou operador) na árvore de expressão pos-fixa
*/
static_cast<NodeExp *>(topo)->insereOp(op.get());
}
topo->childs.emplace_back(std::move(op));
} break;
case TipoAST::ATRIB:
topo->childs.emplace_back(std::make_unique<NodeAtrib>(tk, topo));
break;
case TipoAST::DECL:
topo->childs.emplace_back(std::make_unique<NodeDecl>(tk, topo));
break;
default:
topo->childs.emplace_back(std::make_unique<Node>(tk, topo, tipo));
}
++mNodeCount;
return topo->childs.back().get();
}
std::size_t AST::DFS(const std::function<bool(Node *)> &func) {
return DFS(root.get(), func);
}
std::size_t AST::DFS(AST::Node *atual,
const std::function<bool(Node *)> &func) {
const bool descer = func(atual);
std::size_t count{1};
if (descer) {
for (auto &no : atual->childs) {
count += DFS(no.get(), func);
}
}
return count;
}
AST::Node::Node(const Token &_tk, Node *_super, const TipoAST _t)
: tk(_tk), tipo(_t), super(_super) {}
AST::NodeBloco::NodeBloco(const Token &_tk, Node *_super, const TipoAST _t)
: Node(_tk, _super, _t) {}
AST::NodeExp::NodeExp(const Token &_tk, Node *_super, const TipoAST _t)
: Node(_tk, _super, _t) {}
AST::NodeExpOp::NodeExpOp(const Token &_tk, Node *_super, const TipoAST _t)
: Node(_tk, _super, _t), mAbreParentese(getOp() == '(') {}
AST::NodeAtrib::NodeAtrib(const Token &_tk, Node *_super, const TipoAST _t)
: Node(_tk, _super, _t) {}
AST::NodeDecl::NodeDecl(const Token &_tk, Node *_super, const TipoAST _t)
: Node(_tk, _super, _t) {}
namespace Semantic = AnaliseSemantica;
typedef Semantic::Dado Dado;
void AST::NodeBloco::avaliar(void) {
auto const aux = childs.front().get();
const auto exp = static_cast<NodeExp *>(aux);
exp->avaliar();
if (!Semantic::tipoSaoCompativeis(TipoDado::LOGICO, exp->resultadoExp)) {
throw AnaliseSemantica::ErroSemantico(tk, TipoDado::LOGICO,
exp->resultadoExp);
}
}
void AST::NodeDecl::avaliar(void) {
auto itList = childs.cbegin();
const auto tipo = Semantic::lexemaTipo((*itList)->getLexema());
++itList;
auto const id = static_cast<NodeExpID *>(itList->get());
id->avaliarExp();
id->setTipo(tipo);
}
void AST::NodeAtrib::avaliar(void) {
auto itList = childs.cbegin();
const auto nodeID = static_cast<NodeExpID *>(itList->get());
const auto var = nodeID->avaliarExp();
++itList;
auto const exp = static_cast<NodeExp *>(itList->get());
exp->avaliar();
if (!Semantic::tipoSaoCompativeis(var, exp->resultadoExp)) {
throw AnaliseSemantica::ErroSemantico(nodeID->tk, var, exp->resultadoExp);
}
}
void AST::NodeExp::avaliar(void) { resultadoExp = raizExp->avaliarExp(); }
void AST::NodeExpOp::avaliar(void) { avaliarExp(); }
Dado AST::NodeExpOp::avaliarExp(void) {
if (auto noEsq = getEsquerda(); noEsq) {
const auto esq = noEsq->avaliarExp();
if (auto noDir = getDireita(); noDir) {
return aplicaBinop(esq, noDir->avaliarExp());
}
return aplicaUnop(esq);
}
return avaliarExp();
}
Dado AST::NodeExpOp::aplicaBinop(const Dado &num1, const Dado &num2) const {
Dado result(num1, num2);
switch (getOp()) {
case '*':
case '/':
case '-':
case '+':
break;
case '&':
case '|':
result.tipo = TipoDado::LOGICO;
break;
default:
throw std::invalid_argument("Operador binário inválido.");
}
return result;
}
Dado AST::NodeExpOp::aplicaUnop(const Dado &num) const {
Dado result = num;
switch (getOp()) {
case '-':
case '+':
break;
case '!':
result.tipo = TipoDado::LOGICO;
break;
default:
break;
}
return result;
}
typedef AST::NodeExpOp::Direcao Direcao;
Direcao AST::NodeExpOp::adicionaChild(NodeExpOp *no) {
childs[mDirecao] = no;
return mDirecao = (mDirecao == ESQUERDA) ? DIREITA : mDirecao;
}
constexpr Prec precedencia(const char op) {
switch (op) {
case '+':
case '-':
case '!':
case '|':
return Prec::TERMO_OP;
case '*':
case '/':
case '&':
return Prec::FATOR_OP;
default:
return Prec::NULO;
}
}
void AST::NodeExp::insereOp(NodeExpOp *const no) {
if (mPilha.empty()) {
mPilha.push(no);
return;
}
auto topo = mPilha.top();
switch (no->tk) {
case TipoToken::FECHAPRNT:
while (!mPilha.top()->abreParentese()) {
mPilha.pop();
}
if (mPilha.size() > 1) { // evitando retirar a raiz se a expressão
mPilha.pop(); // começar com abre parenteses
}
break;
case TipoToken::ABREPRNT:
mPilha.push(no);
[[fallthrough]];
case TipoToken::ID:
case TipoToken::VALOR:
topo->adicionaChild(no);
break;
case TipoToken::SINAL:
case TipoToken::BINOP:
case TipoToken::NEG:
if (!topo->abreParentese()) {
if (topo->size() == 2) { // tem os dois operadores
if (precedencia(no->getOp()) > precedencia(topo->getOp())) {
no->adicionaChild(topo->getDireita());
topo->getDireita() = no;
mPilha.push(no);
return;
}
}
mPilha.pop();
no->adicionaChild(topo);
if (mPilha.size()) {
mPilha.top()->getDireita() = no;
}
mPilha.push(no);
} else {
topo->tk = no->tk;
}
break;
default:
break;
}
}
AST::NodeExpOp *AST::NodeExp::fimExp(void) {
while (mPilha.size() > 1) {
mPilha.pop();
}
return raizExp = mPilha.top();
}
AST::NodeExpID::NodeExpID(const Token &_tk, Node *_super, const TipoAST _t)
: NodeExpOp(_tk, _super, _t) {}
AnaliseSemantica::Dado AST::NodeExpID::avaliarExp(void) {
if (mIteratorInicializado) {
return mSTDado->second;
}
if (super->tk == TipoToken::DECL) {
declaraVar();
} else {
getDadoVar();
}
mIteratorInicializado = true;
return avaliarExp();
}
void AST::NodeExpID::declaraVar(void) {
auto const bloco = getBlocoAcima(this);
mSTDado = bloco->st.inserirVariavel(tk);
}
AST::NodeBloco *AST::NodeExpID::getBlocoAcima(
const AST::Node *const atual) const {
AST::Node *result = atual->super;
while (result and *result != TipoAST::BLOCO) {
result = result->super;
}
return static_cast<AST::NodeBloco *>(result);
}
void AST::NodeExpID::getDadoVar(void) {
const AST::Node *no = this;
AST::NodeBloco *atual{}, *anterior{};
std::pair<std::unordered_map<std::string, Dado>::iterator, bool> result;
while ((atual = getBlocoAcima(no))) {
no = anterior = atual;
if ((result = anterior->st.getDado(tk)).second) {
mSTDado = result.first;
return;
}
}
if (anterior and (result = anterior->st.getDado(tk)).second) {
mSTDado = result.first;
return;
}
throw AnaliseSemantica::ErroSemantico(
tk, "Todas as variaveis devem ser declaradas antes do uso.");
}
AST::NodeExpValor::NodeExpValor(const Token &_tk, Node *_super,
const TipoAST _t)
: NodeExpOp(_tk, _super, _t), val(std::stof(getLexema())) {}
} // namespace AnaliseSintatica
<file_sep>/*
* =====================================================================================
*
* Filename: pos.hpp
*
* Description: Representa uma posição (x, y)
*
* Version: 1.0
* Created: 03/16/2020 06:19:57 AM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
struct Pos {
long long linha;
long long col;
constexpr Pos(const long long _linha = 0, const long long _col = 0)
: linha(_linha), col(_col) {}
};
<file_sep>/*
* =====================================================================================
*
* Filename: test.cpp
*
* Description:
*
* Version: 1.0
* Created: 02/23/2020 08:07:12 AM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#include <list>
#include <iostream>
#include "../src/ast.hpp"
using namespace std;
using namespace AnaliseSintatica;
using namespace AnaliseSemantica;
int main() {
list<unique_ptr<AST::Node>> l;
l.emplace_back(make_unique<AST::NodeBloco>(Token(), AST::Tipo::BLOCO, nullptr));
l.emplace_back(make_unique<AST::Node>(Token(), AST::Tipo::REGULAR, l.front().get()));
auto t = dynamic_cast<AST::NodeBloco*>(l.front().get());
cout << t << '\n';
return 0;
}
<file_sep>/*
* =====================================================================================
*
* Filename: tipodado.hpp
*
* Description:
*
* Version: 1.0
* Created: 02/26/2020 11:25:34 AM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
/*
* Tipos que as variáveis podem assumir
*/
enum class TipoDado {
NULO,
INTEIRO,
QUEBRADO,
LOGICO,
};
<file_sep>/*
* =====================================================================================
*
* Filename: global.hpp
*
* Description: Globals
*
* Version: 1.0
* Created: 03/09/2020 05:11:44 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
#if __GNUC__ > 7
#include <filesystem>
namespace fs = std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
/* Variável global que guarda o caminho para o arquivo de entrada */
extern fs::path G_filepath;
<file_sep>/*
* =====================================================================================
*
* Filename: ast.hpp
*
* Description: Abstract Syntax Tree, criada pelo Sintatico
* mas utilizada pelo Semantico para suas analises
*
*
* Version: 1.0
* Created: 02/21/2020 09:54:33 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
#include <functional>
#include <list>
#include <memory>
#include <stack>
#include <stdexcept>
#include <unordered_map>
#include "enum/tipo_ast.hpp"
#include "stable.hpp"
#include "token.hpp"
enum class TipoDado;
namespace AnaliseSintatica {
/*
* Abstract Syntax Tree
* Criada e manipulada pelo Sintático
* Visualizada pelo Semântico para verificar tipos e escopo.
*/
class AST {
public:
/*
* Um nó regular da AST, exemplo conceitual:
* DECL
* / \
* TIPO ID
*
* Exemplo mais físico:
* {
* tk: DECL,
* tipo: REGULAR,
* childs: [ { tk: TIPO, tipo: REGULAR, childs: [] } ,
* { tk: ID, tipo: EXPOP, childs: [] }
* ]
* }
* PS: childs é uma lista e se estiver vazia representa uma folha
*/
struct NodeBloco;
struct Node {
Token tk;
TipoAST tipo;
std::list<std::unique_ptr<Node>> childs;
Node* super{};
Node(const Token&, Node* = nullptr, const TipoAST = TipoAST::REGULAR);
auto& getLexema(void) const { return tk.lexema; }
operator TipoAST() const { return tipo; }
/*
* função abstrata que tem que ser sobreescrita por todos os filhos
*/
virtual void avaliar(void) {}
virtual ~Node() = default;
};
struct NodeDecl : public Node {
NodeDecl(const Token&, Node* = nullptr, const TipoAST = TipoAST::REGULAR);
/*
* avaliar nó DECL que tem sempre 2 nós filhos
* 1) Tipo
* 2) Identificador
*
* selecionará o bloco imediatamente acima do 'no'
* e inserirá o Identificador na sua Tabela de Símbolos.
*/
void avaliar(void) override;
virtual ~NodeDecl() override = default;
};
struct NodeAtrib : public Node {
AnaliseSemantica::Dado* var{};
std::unique_ptr<AnaliseSemantica::Dado> resultadoExp;
NodeAtrib(const Token&, Node* = nullptr, const TipoAST = TipoAST::ATRIB);
/*
* avaliar nó ATRIB que tem sempre 2 filhos
* 1) Identificador
* 2) EXP
*
* A analise parte da "resolução" da expressão
* A função abaixo verificará se o tipo resultante da expressao e o
* tipo do identificador são compatíveis
*
* o valor dessa expressão não pode ser usado para otimizações se:
* algum dos nós folha da expressão for um Identificador
*/
void avaliar(void) override;
virtual ~NodeAtrib() override = default;
};
/*
* Um nó bloco da AST, também chamado de nó de escopo, exemplo conceitual:
* NT_SE
* / \
* EXP ATRIB
* / / \
* VALOR ID EXP
*
* Exemplo mais físico:
* {
* tk: NT_SE,
* tipo: BLOCO,
* st: { { ID: Dado } }
* childs: [ { tk: EXP, tipo: EXP,
* childs: [ { tk: VALOR, tipo: EXP, childs: [] } ] },
* { tk: ATRIB, tipo: ATRIB, childs: [ ID, EXP ] }
* ]
* }
* PS: childs é uma lista e se estiver vazia representa uma folha
*/
struct NodeBloco : public Node {
AnaliseSemantica::SymbolTable st;
NodeBloco(const Token&, Node* = nullptr, const TipoAST = TipoAST::BLOCO);
/*
* avaliar nó do tipo BLOCO
* NT_SE/NT_SENAO/NT_ENQUANTO tem EXP como primeiro nó
* tal EXP é a condição então deve retornar tipo LOGICO
*/
void avaliar(void) override;
virtual ~NodeBloco() override = default;
};
/*
* Um nó que representa parte de uma expressão
* Exemplo mais físico:
* {
* tk: EXP,
* tipo: EXP,
* dado: { valor: 0, tipo: NULO },
* childs: [ { tk: { lexema: "trinta" }, tipo: EXPOP },
* { tk: { lexema: "*" }, tipo: EXPOP },
* { tk: { lexema: "32.5" }, tipo: EXPOP } },
* { tk: { lexema: "-" }, tipo: EXPOP },
* { tk: { lexema: "(" }, tipo: EXPOP },
* { tk: { lexema: "k" }, tipo: EXPOP },
* { tk: { lexema: "+" }, tipo: EXPOP },
* { tk: { lexema: "5" }, tipo: EXPOP },
* { tk: { lexema: ")" }, tipo: EXPOP }
* ]
* }
* Acima está o nó EXP gerado para a seguinte expressão:
* trinta * 32.5 - ( k + 5 )
*
* Por ser uma expressão infixa, é resolvida utilizando pilha
* para ver o algoritmo, veja a classe NodeExpOp
*/
class NodeExpOp;
/*
* Usa uma variação do algoritmo criado por Dijkstra conhecido como:
* SHUNTING YARD
*
* ENQUANTO existem tokens FAÇA:
* leia o token
* SE a pilha está vazia FAÇA:
* coloque token na pilha
* CONTINUE
* ESCOLHA token:
* caso FECHA_PARENTESE:
* ENQUANTO topo da pilha não for ABRE_PARENTESE:
* retire o topo
* retire ABRE_PARENTESE do topo
*
* caso ABRE_PARENTESE:
* token se torna filho do topo
* coloque token na pilha
* caso ID: // operadores sempre são folhas
* caso VALOR:
* token se torna filho do topo
* caso SINAL:
* caso OPERADOR_BINARIO:
* caso NEGACAO:
* SE topo == ABRE_PARENTESE FAÇA:
* topo = token
* SENAO:
* SE topo tem 2 filhos FAÇA:
* SE precedencia(token) > precedencia(topo) FAÇA:
* o filho da direita do topo vira filho de token
* o filho da direita do topo vira token
* coloque token na pilha
* CONTINUE
* retire o topo
* topo se torna filho de token
* o filho da direita do topo se torna token
* coloque token na pilha
*/
struct NodeExp : public Node {
private:
/*
* Pilha auxiliar para o algoritmo de Dijkstra
*/
std::stack<NodeExpOp*> mPilha;
std::size_t mNodeCount{};
public:
AnaliseSemantica::Dado resultadoExp;
NodeExpOp* raizExp{};
NodeExp(const Token&, Node* = nullptr, const TipoAST = TipoAST::EXP);
auto& size(void) const { return mNodeCount; }
/*
* Realiza o algoritmo descrito acima
*/
void insereOp(NodeExpOp* const);
/*
* Desempilha todos os operadores/operandos analisados
* O último da pilha é a raiz da árvore de expressão
*/
NodeExpOp* fimExp(void);
void avaliar(void) override;
virtual ~NodeExp() override = default;
};
class NodeExpOp : public Node {
public:
enum Direcao { ESQUERDA, DIREITA };
private:
std::array<NodeExpOp*, 2> childs{};
Direcao mDirecao{};
bool mAbreParentese;
public:
NodeExpOp(const Token&, Node* = nullptr, const TipoAST = TipoAST::EXP);
auto& getEsquerda(void) const { return childs[ESQUERDA]; }
auto& getDireita(void) const { return childs[DIREITA]; }
auto& getOp(void) const { return tk.lexema.front(); }
auto size(void) const {
return (getEsquerda() != nullptr) + (getDireita() != nullptr);
}
auto& getEsquerda(void) { return childs[ESQUERDA]; }
auto& getDireita(void) { return childs[DIREITA]; }
auto abreParentese(void) const { return mAbreParentese; }
void avaliar(void) override;
/*
* Caminho na árvore de expressão em Pos-Ordem
* *
* / \
* 3 5
* Resultado -> { tipo: INTEIRO, valor: 15 }
*/
virtual AnaliseSemantica::Dado avaliarExp(void);
Direcao adicionaChild(NodeExpOp* const);
virtual ~NodeExpOp() = default;
private:
/*
* Aplica os operadores *, /, +, -, &&, || em Dados
*/
AnaliseSemantica::Dado aplicaBinop(const AnaliseSemantica::Dado&,
const AnaliseSemantica::Dado&) const;
/*
* Aplica os operadores +, !, - no Dado
*/
AnaliseSemantica::Dado aplicaUnop(const AnaliseSemantica::Dado&) const;
};
class NodeExpID : public NodeExpOp {
private:
std::unordered_map<std::string, AnaliseSemantica::Dado>::iterator mSTDado;
bool mIteratorInicializado{};
public:
NodeExpID(const Token&, Node* = nullptr, const TipoAST = TipoAST::EXP);
AnaliseSemantica::Dado avaliarExp(void) override;
void setTipo(const TipoDado tipo) { mSTDado->second.tipo = tipo; }
~NodeExpID() override = default;
private:
/*
* getBlocoAcima busca o próximo nó do tipo Bloco a partir de Node* atual
*/
NodeBloco* getBlocoAcima(const Node* const) const;
/*
* Busca variável nos escopos acima de Node*
* Se encontrar então
* atribue
* se os tipos forem diferentes então
* erro
* Senao
* erro
*/
void getDadoVar(void);
void declaraVar(void);
};
class NodeExpValor : public NodeExpOp {
public:
AnaliseSemantica::Dado val;
NodeExpValor(const Token&, Node* = nullptr, const TipoAST = TipoAST::EXP);
AnaliseSemantica::Dado avaliarExp(void) override { return val; }
~NodeExpValor() override = default;
};
private:
std::unique_ptr<Node> root;
/*
* Pilha utilizada pelo Sintatico para a inserção de nós
*/
std::stack<Node*> mPilha;
std::size_t mNodeCount{1};
public:
AST(void);
/*
* inserirNode Insere um child no Nó que está no topo da mPilha
* o novo child se torna o novo topo da mPilha
*/
Node* inserirNode(const Token&, const TipoAST = TipoAST::REGULAR);
/*
* Insere um child no Nó que está no topo da mPilha
*/
Node* inserirFolha(const Token&, const TipoAST = TipoAST::REGULAR);
/*
* DFS faz um busca em profundidade na AST.
*
* A função func é utilizada para auxiliar na descida.
* Por exemplo, se estivermos analisando um Nó BLOCO então
* func -> true. (ou seja, desceremos mais um nível)
*
* Já se tivermos analisando um Nó ATRIB não precisamos descer
* mais um nível, visto que conseguimos todos os parâmetros de um ATRIB no
* seu próprio nível, apenas acessando a lista de filhos,
* sendo assim func -> false
*/
std::size_t DFS(const std::function<bool(Node*)>& func);
/*
* subirNivel retira n nós da mPilha
*/
auto subirNivel(const std::size_t n) {
std::size_t i = 0;
for (; mPilha.size() and i < n; ++i) {
/*
* Se o no atual for uma EXP, devemos finaliza-la, ou seja,
* retornar todos os niveis da AST de Expressao ate a raiz.
*/
if (mPilha.top()->tk == TipoToken::EXP) {
static_cast<NodeExp*>(mPilha.top())->fimExp();
mPilha.pop();
++i;
if (*mPilha.top() == TipoAST::BLOCO) {
continue;
}
}
mPilha.pop();
}
return i;
}
Node* atual(void) { return mPilha.top(); }
auto& size(void) const { return mNodeCount; }
void trocaToken(const Token& tk);
private:
/*
* DFS recursivo
*/
std::size_t DFS(Node* const atual, const std::function<bool(Node*)>& func);
};
} // namespace AnaliseSintatica
<file_sep># Pseudo Compilador
Programa que faz a análise léxica, sintática e semântica de uma linguagem.
Trabalho proposto na disciplina de Compiladores 2019.2 na [Universidade do Estado da Bahia](https://uneb-si.github.io/).
# Build and Run
[](https://repl.it/github/josecleiton/pseudo-compilador)
## Usando o terminal
Dependências:
- Compilador C++17
Se você tiver `make` basta:
- `cd src`
- `make`
Senão:
- `cd src`
- `g++ *.cpp -std=c++17 -Wall -Wcast-align -o pcc` (troque `g++` por qualquer compilador C++17)
E rodar:
- `pcc <nome>.c20192`
## Usando o QTCreator
Importe o `.pro` e run
<file_sep>/*
* =====================================================================================
*
* Filename: st.cpp
*
* Description:
*
* Version: 1.0
* Created: 02/26/2020 11:32:13 AM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#include "stable.hpp"
#include <cmath>
#include "constexpr.hpp"
#include "enum/tipo_dado.hpp"
namespace AnaliseSemantica {
TipoDado lexemaTipo(const std::string_view lexema) {
if (lexema == "INTEIRO") {
return TipoDado::INTEIRO;
} else if (lexema == "QUEBRADO") {
return TipoDado::QUEBRADO;
} else {
return TipoDado::LOGICO;
}
}
std::string tipoLexema(const TipoDado t) {
switch (t) {
case TipoDado::INTEIRO:
return "INTEIRO";
case TipoDado::LOGICO:
return "LOGICO";
case TipoDado::QUEBRADO:
return "QUEBRADO";
default:
return "NULO";
}
}
Dado::Dado(const TipoDado t, const double v) : tipo(t), valor(v) {}
Dado::Dado(const Dado &d) : tipo(d.tipo), valor(d.valor) {
if (tipo == TipoDado::NULO) {
preencheTipo();
}
}
Dado::Dado(const double v) : valor(v) { preencheTipo(); }
Dado::Dado(const Dado &d1, const Dado &d2) {
if (d1 == TipoDado::QUEBRADO) {
tipo = d1;
} else if (d1 == TipoDado::INTEIRO) {
if (d2 == TipoDado::QUEBRADO) {
tipo = d2;
} else {
tipo = d1;
}
} else {
tipo = d2;
}
}
void Dado::preencheTipo(void) {
if (valor == 1 or valor == 0.0f) {
tipo = TipoDado::LOGICO;
} else if (valor == ceilf(valor)) {
tipo = TipoDado::INTEIRO;
} else {
tipo = TipoDado::QUEBRADO;
}
}
Dado &Dado::operator=(const Dado &other) {
if (this != &other) {
if (bool valido = tipoSaoCompativeis(tipo, other); !valido) {
throw std::domain_error("Tipos incompatíveis");
}
tipo = other.tipo;
valor = other.valor;
}
return *this;
}
} // namespace AnaliseSemantica
<file_sep>/*
* =====================================================================================
*
* Filename: error.hpp
*
* Description: Formatador de Erros (perfumarias)
*
* Version: 1.0
* Created: 02/15/2020 05:16:52 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
#include <cctype>
#include <exception>
#include <fstream>
#include <sstream>
#include "pos.hpp"
class Token;
enum class TipoDado;
class Lex;
/**
* Classe para formatar erros do compilador
*/
class Erro : public std::exception {
protected:
mutable Pos mPos;
mutable std::string mMsg, mLexema;
std::string mEsperado;
public:
/*
* Erro lexico
*/
Erro(const Pos &, std::string lexema, const std::string_view esperado);
// Erro(Token &tk, const std::string_view tipoErro,
// const std::string_view esperado = "");
/* Erro(Syn* const syn; const Token& tk); */
const char *what() const throw() override {
if (mMsg.empty()) {
formataErro();
}
return mMsg.c_str();
}
virtual ~Erro() = default;
protected:
void formataErro(void) const;
/*
* getLinha - pega a linha n coloca na str
*/
std::string_view getLinha(std::ifstream &file, std::string &str) const;
/*
* Substitui \r ou \n ou \t por espaço em branco
*/
std::size_t limpaLexema(void) const {
std::size_t count{};
for (auto &c : mLexema) {
if (isspace(c) and c != ' ') {
c = ' ';
++count;
}
}
return count;
}
/*
* Aponta para o caracter onde está o erro
*/
std::string getSeta(const std::string &s) const;
protected:
virtual void formataStringStream(std::ostringstream &,
const std::string_view,
const std::string_view,
const std::string_view) const {}
};
class ErroLexico : public Erro {
public:
ErroLexico(Lex &lex, std::string &lexema, const std::string_view esperado);
~ErroLexico() = default;
protected:
void formataStringStream(std::ostringstream &,
const std::string_view linhaErro,
const std::string_view linhaFormatada,
const std::string_view seta) const override;
};
namespace AnaliseSintatica {
class ErroSintatico : public Erro {
public:
ErroSintatico(const Token &tk, const std::string_view esperado);
virtual ~ErroSintatico() = default;
protected:
virtual void formataStringStream(std::ostringstream &,
const std::string_view linhaErro,
const std::string_view linhaFormatada,
const std::string_view seta) const override;
};
} // namespace AnaliseSintatica
namespace AnaliseSemantica {
class ErroSemantico : public AnaliseSintatica::ErroSintatico {
public:
ErroSemantico(const Token &tk, const std::string_view esperado);
ErroSemantico(const Token &tk, const TipoDado, const TipoDado);
~ErroSemantico() = default;
protected:
void formataStringStream(std::ostringstream &,
const std::string_view linhaErro,
const std::string_view linhaFormatada,
const std::string_view seta) const override;
};
std::string formataEsperado(const TipoDado, const TipoDado);
} // namespace AnaliseSemantica
<file_sep>/*
* =====================================================================================
*
* Filename: constexpr.hpp
*
* Description:
*
* Version: 1.0
* Created: 03/14/2020 01:21:30 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
#include "enum/tipo_dado.hpp"
namespace AnaliseSemantica {
/*
* tipoSaoCompativeis - Compara se um tipo é atribuível a outro
*/
constexpr bool tipoSaoCompativeis(const TipoDado t1, const TipoDado t2) {
switch (t1) {
case TipoDado::INTEIRO:
return t2 != TipoDado::QUEBRADO;
case TipoDado::LOGICO:
return t2 == TipoDado::LOGICO;
default:
return true;
}
}
} // namespace AnaliseSemantica
<file_sep>/*
* =====================================================================================
*
* Filename: lex.h
*
* Description: Analisador léxico
*
* Version: 1.0
* Created: 02/13/2020 02:34:26 PM
* Revision: none
* Compiler: g++
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <unordered_map>
#include "pos.hpp"
#if __GNUC__ > 7
#include <filesystem>
namespace fs = std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
class Token;
enum class TipoToken;
class Lex {
private:
std::ifstream mInputFile;
std::ofstream mOutputFile;
/*
* Posição de leitura no arquivo de entrada
*/
Pos mPos;
/*
* Palavras reservadas
*/
const std::unordered_map<std::string, TipoToken> mPalavrasReservadas;
public:
/*
* Lex inicializado com:
* o caminho do arquivo de entrada (vem do argv)
* o caminho do arquivo de saida, que contera todos os lexemas lidos
*/
Lex(const fs::path& in, const fs::path& out = "lexemas.txt");
~Lex();
auto& getPos(void) const { return mPos; }
auto& getLinha(void) const { return mPos.linha; }
auto& getCol(void) const { return mPos.col; }
/*
* Pega token vindo do arquivo de entrada
* Grava no arquivo "lexemas.txt"
* Retorna o token
*/
Token getToken(void);
/*
* Função para testes, lê todos os tokens e printa na tela
*/
void analiseAteEOF(void);
private:
/*
* Implementação do AFD da linguagem
*/
Token proxToken(void);
/*
* Se o lexema for uma palavra reservada, retorne o seu respectivo token,
* senão retorne token id
*/
TipoToken reservadaOuID(const std::string& lexema) const;
/*
* Função auxiliar para criar token com atributo linha e coluna
*/
inline Token criaToken(const TipoToken, const std::string& lexema) const;
/*
* Função auxiliar para pegar o próx char do buffer
*/
char getChar(std::string& lexema) {
++mPos.col;
lexema.push_back(mInputFile.get());
return lexema.back();
}
/*
* Função auxiliar para colocar char no buffer
*/
void ungetChar(std::string& lexema) {
--mPos.col;
mInputFile.unget();
lexema.pop_back();
}
/*
* Função auxiliar para ajustar os contadores de linha e col
* na leitura de um '\n'
*/
void proximaLinha(void) {
mPos.col = 0;
++mPos.linha;
}
};
<file_sep>/*
* =====================================================================================
*
* Filename: syn.cpp
*
* Description: implementação do sintatico (ll(1) parser)
*
* Version: 1.0
* Created: 02/18/2020 05:29:47 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME>
* Organization: UNEB
*
* =====================================================================================
*/
#include "syn.hpp"
#include "erro.hpp"
#include "lex.hpp"
#ifdef DEBUG
#include <iostream>
#endif
#include <limits>
#include <stdexcept>
namespace AnaliseSintatica {
constexpr auto NULA = std::numeric_limits<int>::max();
Syn::Syn(Lex& l) : mLex(l) {
/*
* Inicializa a pilha com
* PROGRAMA (primeira variavel da gramática, análogo ao S)
* FIMARQ (análogo ao $)
*/
mPilha.push(TipoToken::FIMARQ);
mPilha.push(TipoToken::PROGRAMA);
/*
* Inicializa a parser table com as devidas regras
*/
mLL[TipoToken::PROGRAMA][TipoToken::TIPO] =
mLL[TipoToken::PROGRAMA][TipoToken::ID] =
mLL[TipoToken::PROGRAMA][TipoToken::SE] =
mLL[TipoToken::PROGRAMA][TipoToken::ENQUANTO] = 1;
mLL[TipoToken::PROGRAMAX][TipoToken::TIPO] =
mLL[TipoToken::PROGRAMAX][TipoToken::ID] =
mLL[TipoToken::PROGRAMAX][TipoToken::SE] =
mLL[TipoToken::PROGRAMAX][TipoToken::ENQUANTO] = 1;
mLL[TipoToken::PROGRAMAX][TipoToken::FIMARQ] =
mLL[TipoToken::PROGRAMAX][TipoToken::ACABOU] =
mLL[TipoToken::PROGRAMAX][TipoToken::SENAO] = NULA;
mLL[TipoToken::BLOCO][TipoToken::TIPO] =
mLL[TipoToken::BLOCO][TipoToken::ID] =
mLL[TipoToken::BLOCO][TipoToken::SE] =
mLL[TipoToken::BLOCO][TipoToken::ENQUANTO] = 2;
mLL[TipoToken::COMANDO][TipoToken::SE] = 3;
mLL[TipoToken::COMANDO][TipoToken::ENQUANTO] = 4;
mLL[TipoToken::COMANDO][TipoToken::TIPO] =
mLL[TipoToken::COMANDO][TipoToken::ID] = 5;
mLL[TipoToken::STAT][TipoToken::TIPO] = 6;
mLL[TipoToken::STAT][TipoToken::ID] = 7;
mLL[TipoToken::SEBLOCO][TipoToken::SE] = 8;
mLL[TipoToken::NT_SE][TipoToken::SE] = 9;
mLL[TipoToken::NT_SENAO][TipoToken::ACABOU] = 10;
mLL[TipoToken::NT_SENAO][TipoToken::SENAO] = 11;
mLL[TipoToken::NT_ENQUANTO][TipoToken::ENQUANTO] = 12;
mLL[TipoToken::DECL][TipoToken::TIPO] = 13;
mLL[TipoToken::ATRIB][TipoToken::ID] = 14;
mLL[TipoToken::EXP][TipoToken::ID] =
mLL[TipoToken::EXP][TipoToken::ABREPRNT] =
mLL[TipoToken::EXP][TipoToken::VALOR] = 15;
mLL[TipoToken::EXP][TipoToken::SINAL] = mLL[TipoToken::EXP][TipoToken::NEG] =
16;
mLL[TipoToken::TERMO][TipoToken::SINAL] =
mLL[TipoToken::TERMO][TipoToken::BINOP] = 17;
mLL[TipoToken::TERMO][TipoToken::PNTVIRG] =
mLL[TipoToken::TERMO][TipoToken::FACA] =
mLL[TipoToken::TERMO][TipoToken::FECHAPRNT] = NULA;
mLL[TipoToken::FATOR][TipoToken::ID] = 18;
mLL[TipoToken::FATOR][TipoToken::ABREPRNT] = 19;
mLL[TipoToken::FATOR][TipoToken::VALOR] = 20;
mLL[TipoToken::OP][TipoToken::SINAL] = 21;
mLL[TipoToken::OP][TipoToken::BINOP] = 22;
mLL[TipoToken::UNOP][TipoToken::SINAL] = 21;
mLL[TipoToken::UNOP][TipoToken::NEG] = 23;
mLL[TipoToken::COND][TipoToken::ID] =
mLL[TipoToken::COND][TipoToken::ABREPRNT] =
mLL[TipoToken::COND][TipoToken::VALOR] =
mLL[TipoToken::COND][TipoToken::SINAL] =
mLL[TipoToken::COND][TipoToken::NEG] = 24;
}
AST& Syn::parse(void) {
/*
* Solicita ao Léxico prox token
*/
auto tk = proximoToken();
while (mPilha.size()) {
const auto topo = mPilha.top();
try {
if (tk != topo) {
/*
* Verifica REGRA mLL[topo][tk],
* caso não exista a regra, o map dispara uma exceção
*/
const auto producao = mLL.at(topo).at(tk);
mPilha.pop();
switch (producao) {
case 1: // programa -> comando programax
mPilha.push(TipoToken::PROGRAMAX);
mPilha.push(TipoToken::COMANDO);
// mAST.subirNivel(mBloco);
break;
case 2: // bloco -> programa
mPilha.push(TipoToken::PROGRAMA);
break;
case 3: // comando -> sebloco
mPilha.push(TipoToken::SEBLOCO);
// cria node SEBLOCO
break;
case 4: // comando -> enquanto
mPilha.push(TipoToken::NT_ENQUANTO);
// cria node NT_ENQUANTO
break;
case 5: // comando -> stat;
mPilha.push(TipoToken::PNTVIRG);
mPilha.push(TipoToken::STAT);
break;
case 6: // stat -> decl
mPilha.push(TipoToken::DECL);
// cria node DECL
break;
case 7: // stat -> atrib
mPilha.push(TipoToken::ATRIB);
// cria node ATRIB
break;
case 8: // sebloco -> se senao
mPilha.push(TipoToken::NT_SENAO);
mPilha.push(TipoToken::NT_SE);
break;
case 9: // se -> SE exp FACA bloco
mPilha.push(TipoToken::BLOCO);
mPilha.push(TipoToken::FACA);
mPilha.push(TipoToken::COND);
mPilha.push(TipoToken::SE);
/*
* Ao ler SE cria-se um novo escopo na AST
*/
mAST.inserirNode(TipoToken::NT_SE, TipoAST::BLOCO);
break;
case 10: // senao -> ACABOU
mPilha.push(TipoToken::ACABOU);
break;
case 11: // senao -> SENAO bloco ACABOU
mPilha.push(TipoToken::ACABOU);
mPilha.push(TipoToken::BLOCO);
mPilha.push(TipoToken::SENAO);
/*
* Ao ler SENAO cria-se um novo escopo na AST
*/
mAST.inserirNode(TipoToken::NT_SENAO, TipoAST::BLOCO);
// cria node senao
break;
case 12: // enquanto -> ENQUANTO exp FACA bloco ACABOU
mPilha.push(TipoToken::ACABOU);
mPilha.push(TipoToken::BLOCO);
mPilha.push(TipoToken::FACA);
mPilha.push(TipoToken::COND);
mPilha.push(TipoToken::ENQUANTO);
/*
* Ao ler ENQUANTO cria-se um novo escopo na AST
*/
mAST.inserirNode(TipoToken::NT_ENQUANTO, TipoAST::BLOCO);
break;
case 13: // decl -> tipo id
mPilha.push(TipoToken::ID);
mPilha.push(TipoToken::TIPO);
mAST.inserirNode(TipoToken::DECL, TipoAST::DECL);
break;
case 14: // atrib -> id = exp
mPilha.push(TipoToken::EXP);
mPilha.push(TipoToken::ATRIB);
mPilha.push(TipoToken::ID);
mAST.inserirNode(TipoToken::ATRIB, TipoAST::ATRIB);
break;
case 15: // exp -> fator termo
mPilha.push(TipoToken::TERMO);
mPilha.push(TipoToken::FATOR);
mAST.inserirNode(TipoToken::EXP, TipoAST::EXP);
break;
case 16: // exp -> unop exp
mPilha.push(TipoToken::EXP);
mPilha.push(TipoToken::UNOP);
mAST.inserirNode(TipoToken::EXP, TipoAST::EXP);
break;
case 17: // termo -> op exp
mPilha.push(TipoToken::EXP);
mPilha.push(TipoToken::OP);
break;
case 18: // fator -> id
mPilha.push(TipoToken::ID);
break;
case 19: // fator -> (exp)
mPilha.push(TipoToken::FECHAPRNT);
mPilha.push(TipoToken::EXP);
mPilha.push(TipoToken::ABREPRNT);
break;
case 20: // fator -> valor
mPilha.push(TipoToken::VALOR);
break;
case 21: // op -> sinal || unop -> sinal
mPilha.push(TipoToken::SINAL);
break;
case 22: // op -> binop
mPilha.push(TipoToken::BINOP);
break;
case 23: // unop -> !
mPilha.push(TipoToken::NEG);
break;
case 24: // cond -> exp
mPilha.push(TipoToken::EXP);
break;
case NULA: // var -> ε
break;
default:
throw std::runtime_error(
"Erro sintatico - Produção não registrada");
}
} else {
// terminal retornado pelo lexico bate com o token no topo da pilha
mPilha.pop();
switch (tk) {
/*
* Tokens que fazem parte de uma expressão
* criar-se nós folha que serão analisados e resolvidos no
* semântico
*/
case TipoToken::ID:
case TipoToken::SINAL:
case TipoToken::NEG:
case TipoToken::BINOP:
case TipoToken::ABREPRNT:
case TipoToken::FECHAPRNT:
case TipoToken::VALOR:
mAST.inserirFolha(tk, TipoAST::EXPOP);
break;
/*
* Token que faz parte de um Node DECL
*/
case TipoToken::TIPO:
mAST.inserirFolha(tk);
break;
/*
* Tokens que representam final do Node
* após ele subimos 1 nível da árvore
* Caso especial:
* Se o nó atual for EXP e o nó pai for ATRIB
* subirNivel subirá +1 nível
*/
case TipoToken::ACABOU:
case TipoToken::PNTVIRG:
case TipoToken::FACA:
mAST.subirNivel(1);
break;
case TipoToken::SE:
case TipoToken::SENAO:
case TipoToken::ENQUANTO:
mAST.trocaToken(tk);
break;
/*
* Alguns Tokens terminais não devem entrar na AST explicitamente
* Exemplo: ;, FACA, SE, SENAO, etc
*/
default:
break;
}
#ifdef DEBUG
std::clog << "[DEBUG - parser] " << tk << std::endl;
#endif
if (tk != TipoToken::FIMARQ) {
tk = proximoToken();
}
}
} catch (const Erro& err) {
throw err;
} catch (const std::exception&) {
throw ErroSintatico(tk, "seguir as regras gramaticais");
}
}
return mAST;
}
Token Syn::proximoToken(void) {
++mTkCount;
return mLex.getToken();
}
} // namespace AnaliseSintatica
<file_sep>/*
* =====================================================================================
*
* Filename: global.cpp
*
* Description: declarações das variáveis globais
*
* Version: 1.0
* Created: 03/09/2020 05:19:58 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#include "global.hpp"
fs::path G_filepath;
<file_sep>/*
* =====================================================================================
*
* Filename: sem.cpp
*
* Description: Analise semantica (documentação no sem.hpp)
*
* Version: 1.0
* Created: 02/22/2020 09:32:51 AM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#include "sem.hpp"
#include "ast.hpp"
namespace AnaliseSemantica {
using namespace AnaliseSintatica;
Sem::Sem(AST &ast) : mAST(ast) {}
std::size_t Sem::analisaArvore(void) {
return mAST.DFS([](AST::Node *no) -> bool {
if (!no) {
return false;
}
bool descer{};
if (*no == TipoAST::BLOCO) {
/*
* condiçao para nao avaliar blocos sem condicao
*/
if (no->tk != TipoToken::PROGRAMA and no->tk != TipoToken::NT_SENAO) {
no->avaliar();
}
descer = true;
} else {
no->avaliar();
/* Após a avaliação do DECL, toda as informações vão para a
* tabela de simbolos do escopo mais próximo
*/
if (no->tk == TipoToken::DECL) {
no->childs.clear();
}
}
return descer;
});
}
} // namespace AnaliseSemantica
<file_sep>/*
* =====================================================================================
*
* Filename: main.cpp
*
* Description: BIRL
*
* Version: 1.0
* Created: 02/13/2020 10:31:32 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#include <cstring>
#include <iostream>
#include "sem.hpp"
#include "syn.hpp"
#include "lex.hpp"
using namespace AnaliseSintatica;
using namespace AnaliseSemantica;
[[noreturn]] void usage(void) {
std::cerr << "Caminho do arquivo é requerido.\n";
throw std::invalid_argument("Falta argv.");
}
int main(const int argc, const char *const argv[]) {
try {
if (argc < 2) {
usage();
}
Lex lex(argv[1]);
Syn syn(lex);
Sem sem(syn.parse());
std::cout << "[SINTATICO] - O seu programa foi aceito sintatica e "
"lexicamente!\n";
auto nodeCounter = sem.analisaArvore();
#ifdef DEBUG
std::cout << "[SINTATICO] - O total de nós da AST é: "
<< syn.getAST().size() << "\n[SEMANTICO] - Foram visitados "
<< nodeCounter << " nós (excluindo nós de expressão num)\n";
#endif
std::cout << "[SEMANTICO] - O seu programa foi aceito!\n";
std::cout << "[COMPILADOR] - O código fonte passou em todas as fases de "
"análise!\n";
return EXIT_SUCCESS;
} catch (const Erro &err) {
std::cerr << err.what() << '\n';
} catch (const std::exception &e) {
#ifdef DEBUG
std::cerr << "[DEBUG] Exception - " << e.what() << '\n';
#endif
}
return EXIT_FAILURE;
}
<file_sep>/*
* =====================================================================================
*
* Filename: tipotoken.hpp
*
* Description: Tipo Token enum
*
* Version: 1.0
* Created: 02/26/2020 11:18:40 AM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
enum class TipoToken {
INITIAl,
ID, // 1
TIPO, // 2
VALOR, // 3
SINAL, // 4
NEG, // 5
SE, // 6
SENAO, // 7
ENQUANTO, // 8
FACA, // 9
ACABOU, // 10
ATRIB, // 11
PNTVIRG, // 12
ABREPRNT, // 13
FECHAPRNT, // 14
FIMARQ, // 15
BINOP, // 16
// não terminais
PROGRAMA,
PROGRAMAX,
BLOCO,
COMANDO,
STAT,
NT_ENQUANTO,
SEBLOCO,
NT_SE,
NT_SENAO,
DECL,
COND,
EXP,
TERMO,
FATOR,
OP,
UNOP,
};
<file_sep>/*
* =====================================================================================
*
* Filename: syn.hpp
*
* Description: Parser
*
* Version: 1.0
* Created: 02/18/2020 04:06:17 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
#include <stack>
#include <unordered_map>
#include "ast.hpp"
class Lex;
class Token;
namespace AnaliseSintatica {
class Syn {
/*
* Pilha auxiliar para o controle das transições entre produções
*/
std::stack<TipoToken> mPilha;
/*
* LL(1) parser table
*/
std::unordered_map<TipoToken, std::unordered_map<TipoToken, int>> mLL;
std::size_t mTkCount{};
/* referencia do objeto Lex (responsável pela análise léxica) */
Lex& mLex;
/*
* Abstract Syntax Tree - Vai sendo construída ao decorrer do parsing
* Ao final está num estado pronto para o Semântico
*/
AST mAST;
public:
/*
* Syn inicializado com o Lexico
*/
Syn(Lex&);
/*
* Verifica as regras definidas em mLL com os tokens sendo lidos do Lexico
* Se nenhum erro for encontrado, então o programa está sintaticamente e
* lexicamente correto. A partir dai é retornada a AST resultante.
*/
AST& parse(void);
inline Token proximoToken(void);
auto getTkCounter(void) const { return mTkCount; }
auto& getAST(void) const { return mAST; }
};
} // namespace AnaliseSintatica
<file_sep>/*
* =====================================================================================
*
* Filename: token.cpp
*
* Description: Tokens
*
* Version: 1.0
* Created: 02/13/2020 09:55:49 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#include "token.hpp"
Token::Token(const TipoToken _tipo, const std::string& _lexema, const Pos _pos)
: mPos(_pos), tipo(_tipo), lexema(_lexema) {}
bool Token::substituiDelSeValor(std::string& lexema) {
std::size_t i = 0;
while (i < lexema.size() and lexema[i] >= '0' and lexema[i] <= '9') {
++i;
}
if (lexema[i] != '.') {
return false;
}
lexema[i] = ',';
return true;
}
std::ostream& operator<<(std::ostream& out, const Token& tk) {
if (tk == TipoToken::VALOR) {
Token novoTk = tk;
Token::substituiDelSeValor(novoTk.lexema);
return novoTk.print(out);
}
return tk.print(out);
}
std::ostream& operator<<(std::ostream& out, const Pos& pos) {
out << '(' << pos.linha << ", " << pos.col << ')';
return out;
}
<file_sep>/*
* =====================================================================================
*
* Filename: erro.cpp
*
* Description: Erro
*
* Version: 1.0
* Created: 02/15/2020 05:26:33 PM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#include "erro.hpp"
#include <iostream>
#include <sstream>
#include "global.hpp"
#include "lex.hpp"
#include "stable.hpp"
#include "token.hpp"
Erro::Erro(const Pos &_pos, std::string _lexema,
const std::string_view _esperado)
: mPos(_pos), mLexema(_lexema), mEsperado(_esperado) {}
// Erro::Erro(Token &tk, const std::string_view tipoErro,
// const std::string_view esperado) {
// abreArq();
// const Pos pos = tk.getPos();
// #ifdef DEBUG
// std::clog << "[DEBUG - erro] token pos: " << pos << '\n';
// #endif
// formataErro(tipoErro, pos, tk.lexema, esperado);
// }
void Erro::formataErro(void) const {
/*
* Reabre o arquivo de entrada (fornecido pelo usuario)
* para pegar a linha onde ocorreu o erro e mostrar adequadamente no terminal
*/
std::ifstream file(G_filepath);
if (!file.is_open()) {
throw std::runtime_error("Arquivo para formatação do Erro não abriu.");
}
std::string textoLinha;
getLinha(file, textoLinha);
std::ostringstream ss1, ss2;
// primeiroCaracterNaLinha();
const auto limpos = limpaLexema();
mPos.col -= limpos + 1;
Token::substituiDelSeValor(mLexema);
ss1 << '\t' << mPos.linha << " |\t" << textoLinha;
std::string sstr = ss1.str();
const auto seta = getSeta(sstr);
ss2 << G_filepath.filename() << ':' << mPos.linha << ':' << mPos.col;
/*
* Funçao polimorfica, formata a mensagem de jeitos diferentes, dependendo de
* onde ocorreu.
*/
formataStringStream(ss2, textoLinha, sstr, seta);
mMsg = ss2.str();
}
std::string_view Erro::getLinha(std::ifstream &file, std::string &str) const {
for (auto linha = mPos.linha; linha; linha--) {
std::getline(file, str);
}
return str;
}
std::string Erro::getSeta(const std::string &s) const {
std::string res = s;
std::size_t t{};
for (std::size_t i = 0; i < res.size(); ++i) {
if (!isspace(res[i])) {
res[i] = ' ';
} else if (res[i] == '\t') {
t = i;
}
}
res[t + mPos.col + 1] = '^';
return res;
}
ErroLexico::ErroLexico(Lex &lex, std::string &lexema,
const std::string_view esperado)
: Erro(Pos(lex.getLinha(), lex.getCol()), lexema, esperado) {}
void ErroLexico::formataStringStream(std::ostringstream &ss,
const std::string_view linhaErro,
const std::string_view linhaFormatada,
const std::string_view seta) const {
ss << ". lexico: esperado '" << mEsperado << "' recebeu '"
<< linhaErro[mPos.col] << "'\n"
<< linhaFormatada << '\n'
<< seta;
}
namespace AnaliseSintatica {
ErroSintatico::ErroSintatico(const Token &tk, const std::string_view esperado)
: Erro(tk.getPos(), tk.lexema, esperado) {}
void ErroSintatico::formataStringStream(std::ostringstream &ss,
const std::string_view,
const std::string_view linhaFormatada,
const std::string_view seta) const {
ss << ". sintatico: " << mEsperado
<< "\nRevise as regras gramaticais da linguagem.\n"
<< linhaFormatada << '\n'
<< seta;
}
} // namespace AnaliseSintatica
namespace AnaliseSemantica {
ErroSemantico::ErroSemantico(const Token &tk, const std::string_view esperado)
: ErroSintatico(tk, esperado) {}
ErroSemantico::ErroSemantico(const Token &tk, const TipoDado t1,
const TipoDado t2)
: ErroSintatico(tk, formataEsperado(t1, t2)) {}
void ErroSemantico::formataStringStream(std::ostringstream &ss,
const std::string_view,
const std::string_view linhaFormatada,
const std::string_view seta) const {
ss << ". semantico: " << mEsperado
<< "\nRevise as regras semanticas da linguagem.\n"
<< linhaFormatada << '\n'
<< seta;
}
std::string formataEsperado(const TipoDado t1, const TipoDado t2) {
return "Tipo '" + tipoLexema(t1) + "' não é compatível a tipo '" +
tipoLexema(t2) + "'.";
}
} // namespace AnaliseSemantica
<file_sep>/*
* =====================================================================================
*
* Filename: tipoast.hpp
*
* Description:
*
* Version: 1.0
* Created: 02/26/2020 11:20:58 AM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
namespace AnaliseSintatica {
enum class TipoAST { REGULAR, BLOCO, EXP, EXPOP, ATRIB, DECL };
}
<file_sep>/*
* =====================================================================================
*
* Filename: st.hpp
*
* Description:
*
* Version: 1.0
* Created: 02/26/2020 11:28:13 AM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
#include <unordered_map>
#include "erro.hpp"
#include "token.hpp"
enum class TipoDado;
namespace AnaliseSemantica {
/*
* Função auxiliar que converte o lexema para o Tipo
* Exemplo: "INTEIRO" -> Tipo::INTEIRO
*/
TipoDado lexemaTipo(const std::string_view);
std::string tipoLexema(const TipoDado);
/*
* Informações sobre as variáveis cmo:
* Tipo e Valor
*/
class Dado {
public:
TipoDado tipo{};
double valor{};
Dado() = default;
/*
* Um monte de construtores simplesmente
* para shorthand
*/
Dado(const TipoDado, const double = 0.0f);
Dado(const Dado&);
Dado(const double);
Dado(const Dado&, const Dado&);
/*
* Função auxiliar que seta valor e o tipo
*/
void setValor(const double v) {
valor = v;
preencheTipo();
}
/*
* Copy assignment
* Ele checa a compatibilidade entres os tipos do 'this' e 'other'
* Se não forem compatíveis -> throw exception
*/
Dado& operator=(const Dado& other);
Dado& operator=(Dado&&) = default;
/*
* Conversão implícita evitando coisas como:
* d.tipo == Tipo::INTEIRO; -> d == Tipo::INTEIRO;
*/
operator TipoDado() const { return tipo; }
private:
/*
* A partir do valor atribui tipo
*/
void preencheTipo(void);
};
class SymbolTable {
/*
* Hash table [lexema] -> Dado
*/
std::unordered_map<std::string, Dado> mTable;
public:
/*
* Busca na hash table por dado lexema
* retorna um pair { iterator, bool }
* verdadeiro se encontrado, senão falso
*/
auto getDado(const Token& tk) {
auto it = mTable.find(tk.lexema);
return std::make_pair(it, it != mTable.end());
}
/*
* Insere nova variável na hash table
* Se o lexema já estiver na hash table -> throw exception
*/
auto inserirVariavel(const Token& tk, const TipoDado t = {},
const double v = {}) {
if (getDado(tk).second) {
throw ErroSemantico(
tk,
"Sobescrever uma entrada na tabela de simbolos não é permitido");
}
/* emplace retorna um par: { map iterator, bool } */
return mTable.emplace(tk.lexema, Dado(t, v)).first;
}
};
} // namespace AnaliseSemantica
<file_sep>.POSIX:
CXX ?= g++
CXXO ?= -O2
CXXFLAGS = -Wall -Wextra -Wcast-align --std=c++17
SRCS = sem.cpp stable.cpp ast.cpp syn.cpp erro.cpp global.cpp lex.cpp token.cpp main.cpp
OBJS = $(SRCS:.cpp=.o)
LIBS = -lm -lstdc++fs
MAIN = pcc
VERSION = 1.0
all: $(MAIN)
@echo Compilação do Pseudo Compilador $(VERSION) finalizada, use o binário $(MAIN)
$(MAIN): $(OBJS)
$(CXX) $(CXXO) $(CXXFLAGS) -o $(MAIN) $(OBJS) $(LIBS)
$(CLEAN)
.cpp.o:
$(CXX) $(CXXO) $(CXXFLAGS) -c $< -o $@
clean:
$(RM) *.o *~ $(MAIN)
.PHONY: all clean
<file_sep>/*
* =====================================================================================
*
* Filename: sem.hpp
*
* Description: Análise Semantica - Utiliza a AST gerada pelo Sintatico para
* checar escopo e tipo das variáveis (e expressões)
*
* Version: 1.0
* Created: 02/22/2020 09:27:21 AM
* Revision: none
* Compiler: gcc
*
* Author: <NAME> (JCBC), <EMAIL>
* Organization: UNEB
*
* =====================================================================================
*/
#pragma once
#include <cstddef>
namespace AnaliseSintatica {
class AST;
}
namespace AnaliseSemantica {
class Sem {
AnaliseSintatica::AST& mAST;
public:
/*
* Espera a Abstract Syntax Tree gerada pelo Sintatico
*/
Sem(AnaliseSintatica::AST&);
/*
* Caminha na AST verificando a validade semantica dos nos
* Faz uso do polimorfismo dos nós, então essa função controlar a qual
* profundidade deve-se ir
*/
std::size_t analisaArvore(void);
auto& getAST(void) const { return mAST; }
};
} // namespace AnaliseSemantica
| ed4fe11722d0693e2a0885e0b51a6c91c5bc39d1 | [
"Markdown",
"Makefile",
"C++"
] | 26 | C++ | josecleiton/pseudo-compilador | 02f3191974ca518bb05f95724fb28d66daa912fd | a3deabc03231f94f5597c51ace921189c25dad4c |
refs/heads/master | <repo_name>myrac/projekt<file_sep>/profile.php
<?php
session_start();
if (!isset($_SESSION['user']))
{
header('Location: index.php');
}
?>
<!DOCTYPE html>
<html>
<?php include 'header.php';?>
<article>
<h2>Profil korisnika: <?php echo $_SESSION['user'] ?></h2>
<img src="user.jpg">
<?php
if ($_SESSION['user'] == 'user')
{
echo '<ul style="float:right;text-align:left"><li>Ime: Ivica</li><li>Prezime: Horvat</li><li>Status: Student</li><li></li><br><li>Fakultet: Tehničko Veleučilište u Zagrebu</li><li>Studij: Informatika</li><li>Smjer: Elektroničko poslovanje</li><li></li><br><li>Broj riješenih anketa: 13</li><li>Točnost odgovora: 89.53%</li></ul>';
}
else if ($_SESSION['user'] == 'admin')
{
echo '<ul style="float:right;text-align:left"><li>Ime: Mia</li><li>Prezime: Čarapina</li><li>Status: Nositelj kolegija</li><li></li><br><li>Fakultet: Tehničko Veleučilište u Zagrebu</li><li>Studij: Informatika</li><li></li><li>Kolegij: Projektno Programiranje</li><br><li>Broj objavljenih anketa: 53</li></ul>';
}
?>
</article>
<footer>
<div>© 2017 Team Product</div>
</footer>
</body>
</html><file_sep>/form-anketa.php
<?php
session_start();
$errors = array();
if(isset($_POST['change'])){
$old_password = md5($_POST['<PASSWORD>']);
$new_password = md5($_POST['<PASSWORD>']);
$check_password = md5($_POST['<PASSWORD>']);
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['mail'];
if($old_password == '' || $new_password == '' || $check_password == ''){
$errors[] = "Please enter a correct password.";
}
if($new_password != $check_password){
$errors[] = "Passwords do not match!";
}
if($firstname == ''){
$errors[] = "Please enter your new first name.";
}
if($lastname == ''){
$errors[] = "Please enter your new last name.";
}
if($email == ''){
$errors[] = "Please enter your new e-mail.";
}
if(count($errors) == 0)
{
$xml = new SimpleXMLElement('users/' . $_SESSION['user'] . '.xml', 0, true);
$xml->Password = <PASSWORD>;
$xml->First_Name = $firstname;
$xml->Last_Name = $lastname;
$xml->E_Mail = $email;
$xml->asXML('users/' . $_SESSION['user'] . '.xml');
header('Location: profile.php');
die;
}
}
?><file_sep>/header.php
<head>
<meta charset="UTF-8">
<title>TVZ | Aplikacija za ankete</title>
<meta name="description" content="TVZ aplikacija za ankete">
<meta name="author" content="Team Product">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="icon" href="TVZ.png" type="image/x-icon"/>
</head>
<body>
<header>
<nav id="links">
<ul>
<li><a href="http://www.tvz.hr" class="logo"><img src="logo.png" class="logo"></a></li>
<li><a href="index.php">Home</a></li>
<?php
if ($_SESSION['user'] == 'user')
{
echo '<li><a href="profile.php">' . $_SESSION['user'] . '</a></li><li><a href="anketa.php">Trenutna anketa</a></li><li><a href="logout.php">Odjava</a></li>';
}
else if ($_SESSION['user'] == 'admin')
{
echo '<li><a href="profile.php">' . $_SESSION['user'] . '</a></li><li><a href="anketa.php">Trenutna anketa</a></li><li><a href="anketanova.php">Kreiranje ankete</a></li><li><a href="arhiva.php">Arhiva</a></li><li><a href="logout.php">Odjava</a></li>';
}
else
{
echo '<li><a href="login.php">Login</a></li>';
}
?>
</ul>
</nav>
</header><file_sep>/anketa.php
<?php
session_start();
include('form-anketa.php');
?>
<!DOCTYPE html>
<html>
<?php include 'header.php';?>
<article>
<h2>Pitanje: Koliko je 2+2?</h2>
<form method="post" action="">
<input type="radio" id="odgovor1" name="status" value="odgovor1" checked><label for="odgovor1">4</label><br><br>
<input type="radio" id="odgovor2" name="status" value="odgovor2"><label for="odgovor2">5</label><br><br>
<input type="radio" id="odgovor3" name="status" value="odgovor3"><label for="odgovor3">10</label><br><br>
<input type="submit" name="posalji" value="Pošalji odgovor" class="button">
</form>
<br><p>Preostalo vrijeme do kraja ankete: </p><p id="demo"></p>
<script>
var countDownDate = new Date("Jul 5, 2017 00:00:00").getTime();
var x = setInterval(function()
{
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0)
{
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
</article>
<footer>
<div>© 2017 Team Product</div>
</footer>
</body>
</html><file_sep>/anketa2.php
<?php
session_start();
include('form-anketa.php');
?>
<!DOCTYPE html>
<html>
<?php include 'header.php';?>
<article>
<h2>Prikaz odgovora na anketu: Koju biste ocjenu dali ovom predmetu?</h2>
<form method="post" action="form-create.php">
<label for="type">Prikaži odgovore kao: </label><select id="type" name="type" required>
<option value="stat">Statistiku</option>
<option value="tablica">Tablicu</option>
<option value="graf">Graf</option>
</select>
</form>
<p>Prikazujem odgovore kao <b>Statistiku</b></p><br><br>
<table style="width:100%">
<tr>
<th>a) 1</th>
<th>b) 2</th>
<th>c) 3</th>
<th>b) 4</th>
<th>c) 5</th>
</tr>
<tr>
<td>0%</td>
<td>0%</td>
<td>5%</td>
<td>10%</td>
<td>85%</td>
</tr>
</table>
</article>
<footer>
<div>© 2017 Team Product</div>
</footer>
</body>
</html><file_sep>/form-login.php
<?php
$error = false;
if(isset($_POST['login']))
{
$username = preg_replace('/[^A-Za-z]/', '', $_POST['username']);
$password = md5($_POST['password']);
if(file_exists('users/' . $username . '.xml'))
{
$xml = new SimpleXMLElement('users/' . $username . '.xml', 0, true);
if($password == $xml->Password)
{
session_start();
$_SESSION['user'] = $username;
header('Location: anketa.php');
die;
}
}
$error = true;
}
?><file_sep>/arhiva.php
<?php
session_start();
if (!isset($_SESSION['user']))
{
header('Location: index.php');
}
?>
<!DOCTYPE html>
<html>
<?php include 'header.php';?>
<article>
<h2>Arhiva prijašnjih anketa</h2>
<a href="anketa1.php">Anketa 15.05.2017. - Koliko je 2+2?</a><br><br>
<a href="anketa2.php">Anketa 21.05.2017. - Koju biste ocjenu dali ovom predmetu?</a><br><br>
<a href="anketa3.php">Anketa 30.05.2017. - Je li ova tvrdnja istinita (C++)?</a><br><br>
<a href="anketa4.php">Anketa 10.06.2017. - Je li ova tvrdnja istinita (Java)?</a><br><br>
<a href="anketa5.php">Anketa 16.06.2017. - Opišite koliko ste zadovoljni sa Projektnim Programiranjem.</a><br>
</article>
<footer>
<div>© 2017 Team Product</div>
</footer>
</body>
</html><file_sep>/README.md
# Projekt: TVZ Aplikacija za anketiranje studenata
# http://tvzproduct.esy.es/
pass:
- za studenta: usename: user,
password: <PASSWORD>
- za profesora: usename: admin,
password: <PASSWORD>
<file_sep>/index.php
<?php
session_start();
include('form-login.php');
?>
<!DOCTYPE html>
<html>
<?php include 'header.php';?>
<article>
<h2>Prijava sa TVZ podacima</h2>
<form method="post" action="">
<input type="username" id="username" name="username" placeholder="Username" required>
<input type="<PASSWORD>" id="password" name="password" placeholder="<PASSWORD>" required>
<input type="submit" name="login" value="Prijava" class="button">
</form>
</article>
<footer>
<div>© 2017 Team Product</div>
</footer>
</body>
</html>
<file_sep>/anketanova.php
<?php
session_start();
include('form-anketa.php');
?>
<!DOCTYPE html>
<html>
<?php include 'header.php';?>
<article>
<h2>Kreiranje nove ankete</h2>
<form method="post" action="form-create.php">
<label for="title">Naslov:</label><input id="title" type="text" name="title" max="50" required>
<label for="description">Opis:</label><textarea id="description" name="description" maxlength="250"></textarea><br><br>
<label for="type">Vrsta odgovora: </label><select id="type" name="type" required>
<option value="multiple">Višestruki izbor</option>
<option value="single">Jednostruki izbor</option>
<option value="descriptive">Odgovor opisnog tipa</option>
</select> <label for="number">Vremensko ograničenje (sati): </label><input type="number" id="number" name="quantity" min="1" max="48"><br><br>
<label for="odgovor">a) Odgovor - postavi kao točan odgovor</label><input type="checkbox"><input id="option" type="text" name="option1" max="50" placeholder="Unesite tekst odgovora" required>
<label for="odgovor">b) Odgovor - postavi kao točan odgovor</label><input type="checkbox"><input id="option" type="text" name="option2" max="50" placeholder="Unesite tekst odgovora" required>
<label for="odgovor">c) Odgovor - postavi kao točan odgovor</label><input type="checkbox"><input id="option" type="text" name="option3" max="50" placeholder="Unesite tekst odgovora" required>
<input type="submit" name="dodaj" value="+ DODAJ ODGOVOR" class="button">
<input type="submit" name="posalji" value="Kreiraj anketu" class="button">
</form>
</article>
<footer>
<div>© 2017 Team Product</div>
</footer>
</body>
</html> | 508bc60478f83cb9cd6d5bdcbb1819417e208c67 | [
"Markdown",
"PHP"
] | 10 | PHP | myrac/projekt | 926318919d7e0037e6eaf679af05e15720ab72e7 | a0299691f1c09d646a3326c03767161b50de98c0 |
refs/heads/master | <file_sep>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.article_list, name='article_list'),
url(r'^article/(?P<pk>\d+)/$', views.article_detail, name='article_detail'),
url(r'^article/new/$', views.article_new, name='article_new'),
url(r'^article/(?P<pk>\d+)/edit/$', views.article_edit, name='article_edit'),
url(r'^article/(?P<pk>\d+)/remove/$', views.article_remove, name='article_remove'),
url(r'^article/(?P<section>.+)/filter/$', views.article_section, name='article_filter'),
]
<file_sep>from django import forms
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ('title', 'section', 'textIntro', 'textFull', 'imageURL',)<file_sep>from django.contrib import admin
from .models import Article
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'section', 'author', 'created_date']
# Register your models here.
admin.site.register(Article, ArticleAdmin)<file_sep>from django.db import models
from django.utils import timezone
CHOICES = (('National', 'National'), ('International', 'International'), ('Technology', 'Technology'), ('Sport', 'Sport'))
class Article(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
section = models.CharField(max_length=50, choices=CHOICES)
textIntro = models.TextField()
textFull = models.TextField()
imageURL = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
| 1343d04d0cd85247dddc6804a1f85e545fe6e7a0 | [
"Python"
] | 4 | Python | Lazac88/assignment3_tuckmn1 | e67fbbd96cb37de0314fcc1a5d2799ba0f40d57c | c1344f46044841674f3f1fe3b56fb74d7da056ad |
refs/heads/master | <repo_name>txomin-jimenez/todoist-osx-reminders-sync<file_sep>/README.md
Todoist to Icloud Reminders sync script for Mac OSX
<file_sep>/sync.js
// OSX reminders app handler
var remindersApp = Application("Reminders");
remindersApp.includeStandardAdditions = true;
// this object will support task data for two apps
var macRemindersData = {}
var todoistData = {};
var getTodoistToken = function(){
var app = Application.currentApplication();
app.includeStandardAdditions=true;
return app.doShellScript('cat ~/Applications/todoist_osx_sync/token')
}
// load Todoist data from remote API
var getTodoistData = function(){
var token = getTodoistToken()
var app = Application.currentApplication();
app.includeStandardAdditions=true;
todoistData = JSON.parse(app.doShellScript('curl "https://todoist.com/API/v6/sync?token=' + token + '&seq_no=0&resource_types=\\[\\"projects\\",\\"items\\",\\"labels\\"\\]"'));
}
// WIP
var saveSyncData = function(){
var app = Application.currentApplication();
app.includeStandardAdditions=true;
app.doShellScript('echo "'+ JSON.stringify(macRemindersData).replace('&','\\&') +'" > ~/Applications/todoist_osx_sync/sync.dat')
}
// load OSX Reminders
var getMacRemindersData = function(){
macRemindersData.ProjectsById = {}
macRemindersData.ProjectsByName = {}
macRemindersData.taskByProjectAndName = {}
for (i=0;i<remindersApp.lists.length;i++){
var list = remindersApp.lists[i];
macRemindersData.ProjectsById[list.id()] = list
macRemindersData.ProjectsByName[list.name()] = list
macRemindersData.taskByProjectAndName[list.name()] = {}
for (j=0;j<list.reminders.length;j++){
var reminder = list.reminders[j];
macRemindersData.taskByProjectAndName[list.name()][reminder.name()]= reminder
};
}
}
// load OSX Reminders List
var getMacProjects = function(){
var macProjects = {}
for (i=0;i<remindersApp.lists.length;i++){
macProjects[remindersApp.lists[i].name()] = remindersApp.lists[i]
}
return macProjects;
}
// load OSX Reminders
var getMacReminders = function(){
for (i=0;i<remindersApp.lists.length;i++){
var list = remindersApp.lists[i];
macReminders[list.id()] = {
name: list.name(),
tasks: {}
};
for (j=0;j<list.reminders.length;j++){
var reminder = list.reminders[j];
macReminders[list.id()].tasks[reminder.id()] = {
name: reminder.name(),
completed: reminder.completed()
}
};
}
}
// create a OSX Task List given input data
var createMacProject = function(name){
var newProject = remindersApp.make({
new: "list",
withProperties: {
name: name
}
});
macRemindersData.ProjectsById[newProject.id()] = newProject
macRemindersData.ProjectsByName[newProject.name()] = newProject
macRemindersData.taskByProjectAndName[newProject.name()] = {}
}
// create a OSX Reminder given input data
var createMacReminder = function(taskList, name, body, dueDate, priority, remindMeDate){
var props = {
name: name
}
if (body != null || body != undefined)
props.body = body
if (dueDate != null || dueDate != undefined)
props.dueDate = dueDate
if (priority != null || priority != undefined)
props.priority = priority
if (remindMeDate != null || remindMeDate != undefined)
props.remindMeDate = remindMeDate
console.log(props)
var newReminder = taskList.make({
new: "reminder",
at: taskList,
withProperties: props
});
return newReminder
}
// convert Todoist task label id array to label name string
var taskLabelsToString = function(labels){
//console.log(JSON.stringify(todoistData.Labels))
labelsTxt=undefined
labels.forEach(function(labelId,index){
labelObj = todoistData.Labels.find(function(labelObj_){
return labelObj_.id == labelId
})
if (labelObj != null && labelObj != undefined)
if (labelsTxt == undefined)
labelsTxt = '@'+labelObj.name
else
labelsTxt = labelsTxt + " @" + labelObj.name
})
return labelsTxt
}
// loop Todoist task and create them in OSX Reminders
var syncProjectTasks = function(projectName){
todoistTasks = todoistData.Items.filter(function(task){
return task.project_id == todoistData.ProjectsByName[projectName].id
}).sort(function(task1,task2){
return(task1.item_order - task2.item_order)
})
todoistTasks.forEach(function(task,index){
var isCompleted = task.checked || task.in_history
if (task.indent > 0)
task.content = Array(task.indent).join("▶ ") + task.content
if (!isCompleted){
macTask = macRemindersData.taskByProjectAndName[projectName][task.content]
if(!macTask){
// task date could be null
if (task.due_date_utc != null && task.due_date_utc != undefined)
taskDate = new Date(task.due_date_utc)
else
taskDate = undefined
newMacReminder = createMacReminder(macRemindersData.ProjectsByName[projectName], task.content, taskLabelsToString(task.labels), taskDate )
}
}
})
}
// Loop Todoist projects and create them as OSX Reminders List
var syncProjects = function(){
todoistProjects = todoistData.Projects;
macProjects = macRemindersData.ProjectsByName;
todoistProjects.sort(function(pro1, pro2){
return(pro1.item_order - pro2.item_order)
})
todoistData.ProjectsById = {}
todoistData.ProjectsByName = {}
todoistProjects.forEach(function(project,index){
todoistData.ProjectsById[project.id] = project
if (project.indent > 0)
project.name = Array(project.indent).join("▶ ") + project.name
todoistData.ProjectsByName[project.name] = project
if (project.is_deleted == 0 && Object.keys(macProjects).indexOf(project.name) == -1){
createMacProject(project.name)
}
syncProjectTasks(project.name)
})
}
// main entry point
getTodoistData()
getMacRemindersData()
syncProjects()
//saveSyncData()
| d84dcaeac660e60166aa165b035f208578b65630 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | txomin-jimenez/todoist-osx-reminders-sync | 2bc9e21100d353673e473d3fcde93fd963c48034 | 5df7b395022c7f1957e1f2b85e13c81361605d6d |
refs/heads/master | <repo_name>ZLeopard/Python_Simple_Example<file_sep>/sort_number.py
# encode UTF-8
# using the insertion to sort the list
def insertion_sort(list):
for index in range(1, len(list)):
value = list[index]
i = index - 1
while i >= 0 and value < list[i]:
list[i + 1] = list[i]
list[i] = value
i -= 1
a = [7, 1, 3, 5, 4]
b = a[:]
insertion_sort(a)
print(a)
print(sorted(b))
<file_sep>/README.md
# Python_Simple_Example
This is recording the experience of studying Python3.x, and no pain no gain!!!
<file_sep>/factorial.py
# encode: UTF-8
# factoral: such as 3!
# Simple example program to calculate the factorial of a number
# return the factorial of the argument number
def factorial(number):
product = 1
for i in range(number):
product *= (i + 1)
return product
def ss_factorial(number):
if number <= 1:
return 1
else:
return number * factorial(number - 1)
def fibonacci(n):
terms = [0, 1]
i = 2
while i <= n:
terms.append(terms[i - 1] + terms[i - 2])
i += 1
return terms[n]
def ss_fibonacci(n):
if n == 0 or n == 1:
return n
else:
return (ss_fibonacci(n - 1) + ss_fibonacci(n - 2))
user_input = eval(input("Enter a non-negative integer take the factoral of:"))
print(factorial(user_input))
print(ss_factorial(user_input))
print(factorial(5) - factorial(3))
print(fibonacci(10))
<file_sep>/string.py
# utf-8 code
a = "My first test string"
b = 'Another test string that i have degined'
c = "This is Sal's string"
d = 'My favorite word is "asparus",whiat is yours?'
math_string = "3+4*2"
expression_string = "a+' '+b+' tiger'"
a_with_b = a + b
print(a_with_b)
print(eval(math_string + '1'))
print(eval(math_string))
print(eval(expression_string))
print(math_string.find('*'))
print(c.replace('i', 'o'))
print(b.split(' '))
print(b.split(' ')[2])
| cf78d3d029779a5c241ef3a190751e5d1a35487a | [
"Markdown",
"Python"
] | 4 | Python | ZLeopard/Python_Simple_Example | faae88797eca1a4347e6db9c7e55452bef28be65 | 3b173d724a8113f6338090f08f046816fd37b583 |
refs/heads/master | <repo_name>SurubariuRazvan/L1CSharp<file_sep>/Services/ActivePlayerService.cs
using System.Collections.Generic;
using System.Linq;
using Lab1.Repository;
namespace Lab1 {
public class ActivePlayerService : Service<ActivePlayerId<int, GameId<int>>, ActivePlayer> {
public ActivePlayerService(FileRepository<ActivePlayerId<int, GameId<int>>, ActivePlayer> repository) : base(repository) { }
public IEnumerable<Player> ShowAllActivePlayersFromTeamFromGame(GameId<int> gameId, int teamId,
Service<int, Player> playerService) {
return _repository.FindAll().Where(ap => ap.GameId.Equals(gameId)).Select(ap => playerService.FindOne(ap.PlayerId))
.Where(p => p.Team.Id.Equals(teamId));
}
public string CalculateGameScore(GameId<int> gameId, PlayerService playerService) {
int team1Score = _repository.FindAll()
.Where(ap => ap.GameId.Equals(gameId) && playerService.FindOne(ap.PlayerId).Team.Id.Equals(gameId.Team1Id))
.Sum(ap => ap.Score);
int team2Score = _repository.FindAll()
.Where(ap => ap.GameId.Equals(gameId) && playerService.FindOne(ap.PlayerId).Team.Id.Equals(gameId.Team2Id))
.Sum(ap => ap.Score);
return "The score is: " + team1Score + "-" + team2Score + ".";
}
}
}<file_sep>/Domain/ActivityState.cs
namespace Lab1
{
public enum ActivityState
{
Reserve,
Playing
}
}<file_sep>/Repository/TeamFileRepository.cs
using System;
namespace Lab1.Repository
{
public class TeamFileRepository : FileRepository<int, Team>
{
public TeamFileRepository(IValidator<Team> validator, string filePath) : base(validator, filePath)
{
ReadAllFromFile();
}
protected override Team ReadEntity(string line)
{
string[] fields = line.Split(new[] {"||"}, StringSplitOptions.RemoveEmptyEntries);
return new Team(int.Parse(fields[0]), fields[1]);
}
protected override string WriteEntity(Team entity)
{
return entity.Id + "||" + entity.Name;
}
}
}<file_sep>/Validators/GameValidator.cs
namespace Lab1
{
public class GameValidator : IValidator<Game>
{
public void Validate(Game entity)
{
}
}
}<file_sep>/Validators/PlayerValidator.cs
namespace Lab1
{
public class PlayerValidator : IValidator<Player>
{
public void Validate(Player entity)
{
}
}
}<file_sep>/Repository/PlayerFileRepository.cs
using System;
namespace Lab1.Repository
{
public class PlayerFileRepository : FileRepository<int, Player>
{
private FileRepository<int, Team> _teamRepository;
public PlayerFileRepository(IValidator<Player> validator, string filePath,
FileRepository<int, Team> teamRepository) : base(validator, filePath)
{
_teamRepository = teamRepository;
ReadAllFromFile();
}
protected override Player ReadEntity(string line)
{
string[] fields = line.Split(new[] {"||"}, StringSplitOptions.RemoveEmptyEntries);
Team team = _teamRepository.FindOne(int.Parse(fields[3]));
return new Player(int.Parse(fields[0]), fields[1], fields[2], team);
}
protected override string WriteEntity(Player entity)
{
return entity.Id + "||" + entity.Name + "||" + entity.School + "||" + entity.Team.Id;
}
}
}<file_sep>/Domain/ActivePlayer.cs
using System;
using System.Collections.Generic;
namespace Lab1
{
public class ActivePlayer : Entity<ActivePlayerId<int, GameId<int>>>
{
public ActivePlayer(int playerId, int team1, int team2, int score, ActivityState state) : base(
new ActivePlayerId<int, GameId<int>>(playerId, new GameId<int>(team1, team2)))
{
Score = score;
State = state;
}
public int PlayerId
{
get => Id.PlayerId;
set => Id.PlayerId = value;
}
public GameId<int> GameId
{
get => Id.GameId;
set => Id.GameId = value;
}
public int Score { get; set; }
public ActivityState State { get; set; }
public override string ToString()
{
return
$"{nameof(PlayerId)}: {PlayerId}, {nameof(GameId)}: {GameId}, {nameof(Score)}: {Score}, {nameof(State)}: {State}";
}
}
public class ActivePlayerId<T1, T2>
{
public T1 PlayerId { get; set; }
public T2 GameId { get; set; }
public ActivePlayerId(T1 playerId, T2 gameId)
{
PlayerId = playerId;
GameId = gameId;
}
public override string ToString()
{
return $"{nameof(PlayerId)}: {PlayerId}, {nameof(GameId)}: {GameId}";
}
protected bool Equals(ActivePlayerId<T1, T2> other)
{
return EqualityComparer<T1>.Default.Equals(PlayerId, other.PlayerId) &&
EqualityComparer<T2>.Default.Equals(GameId, other.GameId);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((ActivePlayerId<T1, T2>) obj);
}
public override int GetHashCode()
{
unchecked
{
return (EqualityComparer<T1>.Default.GetHashCode(PlayerId) * 397) ^
EqualityComparer<T2>.Default.GetHashCode(GameId);
}
}
}
}<file_sep>/Repository/ActivePlayerFileRepository.cs
using System;
using System.Collections.Generic;
namespace Lab1.Repository
{
public class ActivePlayerFileRepository : FileRepository<ActivePlayerId<int, GameId<int>>, ActivePlayer>
{
public ActivePlayerFileRepository(IValidator<ActivePlayer> validator, string filePath) : base(validator,
filePath)
{
ReadAllFromFile();
}
protected override ActivePlayer ReadEntity(string line)
{
string[] fields = line.Split(new[] {"||"}, StringSplitOptions.RemoveEmptyEntries);
return new ActivePlayer(int.Parse(fields[0]), int.Parse(fields[1]), int.Parse(fields[2]),
int.Parse(fields[3]),
(ActivityState) Enum.Parse(typeof(ActivityState), fields[4]));
}
protected override string WriteEntity(ActivePlayer entity)
{
return entity.PlayerId + "||" + entity.GameId.Team1Id + "||" + entity.GameId.Team2Id + "||" + entity.Score +
"||" + entity.State;
}
}
}<file_sep>/Repository/FileRepository.cs
using System;
using System.Collections.Generic;
namespace Lab1.Repository
{
public abstract class FileRepository<ID, E> : ICrudRepository<ID, E> where E : Entity<ID>
{
private Dictionary<ID, E> _data;
private string _filePath;
private IValidator<E> _validator;
protected FileRepository(IValidator<E> validator, string filePath)
{
_validator = validator;
_filePath = filePath;
_data = new Dictionary<ID, E>();
}
protected abstract E ReadEntity(string line);
protected abstract string WriteEntity(E entity);
public void ReadAllFromFile()
{
if (System.IO.File.Exists(_filePath))
{
System.IO.StreamReader file = new System.IO.StreamReader(_filePath);
while (!file.EndOfStream)
{
E entity = ReadEntity(file.ReadLine());
_data.Add(entity.Id, entity);
}
file.Close();
}
}
public void WriteAllToFile()
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(_filePath))
{
foreach (E entity in _data.Values)
file.WriteLine(WriteEntity(entity));
}
}
public E FindOne(ID id)
{
if (id == null)
throw new ArgumentNullException(nameof(id));
if (_data.ContainsKey(id))
return _data[id];
return null;
}
public IEnumerable<E> FindAll()
{
return _data.Values;
}
public E Save(E entity)
{
if (entity == null)
throw new ArgumentNullException(nameof(entity));
_validator.Validate(entity);
if (_data.ContainsKey(entity.Id))
return entity;
_data.Add(entity.Id, entity);
return null;
}
public E Delete(ID id)
{
if (id == null)
throw new ArgumentNullException(nameof(id));
if (!_data.ContainsKey(id))
return null;
E entity = _data[id];
_data.Remove(id);
return entity;
}
public E Update(E entity)
{
if (entity == null)
throw new ArgumentNullException(nameof(entity));
_validator.Validate(entity);
if (!_data.ContainsKey(entity.Id))
return entity;
_data[entity.Id] = entity;
return null;
}
}
}<file_sep>/Services/Service.cs
using System.Collections.Generic;
using Lab1.Repository;
namespace Lab1
{
public class Service<ID, E> where E : Entity<ID>
{
protected FileRepository<ID, E> _repository;
public Service(FileRepository<ID, E> repository)
{
_repository = repository;
}
public E FindOne(ID id)
{
return _repository.FindOne(id);
}
public IEnumerable<E> FindAll()
{
return _repository.FindAll();
}
public E Save(E entity)
{
return _repository.Save(entity);
}
public E Delete(ID id)
{
return _repository.Delete(id);
}
public E Update(E entity)
{
return _repository.Update(entity);
}
public void WriteAllToFile()
{
_repository.WriteAllToFile();
}
}
}<file_sep>/Validators/ActivePlayerValidator.cs
namespace Lab1
{
public class ActivePlayerValidator : IValidator<ActivePlayer>
{
public void Validate(ActivePlayer entity)
{
}
}
}<file_sep>/Validators/IValidator.cs
namespace Lab1
{
public interface IValidator<E>
{
/**
* @param entity the entity to be validated
* @throws ValidationException if the entity doesnt meet the specified characteristics
*/
void Validate(E entity);
}
}<file_sep>/README.md
# L1CSharp
A basic application for creating and managing multiple football teams.
<file_sep>/Services/GameService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Lab1.Repository;
namespace Lab1
{
public class GameService : Service<GameId<int>, Game>
{
public GameService(FileRepository<GameId<int>, Game> repository) : base(repository)
{
}
public IEnumerable<Game> ShowAllGamesBetween(DateTime startDate, DateTime endDate)
{
return _repository.FindAll().Where(g => g.Date >= startDate && g.Date <= endDate);
}
}
}<file_sep>/Domain/Player.cs
namespace Lab1
{
public class Player : Student
{
public Team Team { get; set; }
public Player(int id, string name, string school, Team team) : base(id, name, school)
{
Team = team;
}
public override string ToString()
{
return $"{base.ToString()}, {nameof(Team)}: {Team}";
}
}
}<file_sep>/Services/PlayerService.cs
using System.Collections.Generic;
using System.Linq;
using Lab1.Repository;
namespace Lab1 {
public class PlayerService : Service<int, Player> {
public PlayerService(FileRepository<int, Player> repository) : base(repository) { }
public IEnumerable<Player> ShowAllPlayersFromATeam(int teamId) {
return _repository.FindAll().Where(p => p.Team.Id.Equals(teamId));
}
}
}<file_sep>/Repository/ICrudRepository.cs
using System;
using System.Collections.Generic;
namespace Lab1.Repository
{
public interface ICrudRepository<ID, E> where E : Entity<ID>
{
/**
* @param id -the id of the entity to be returned
* id must not be null
* @return the entity with the specified id
* or null - if there is no entity with the given id
* @throws IllegalArgumentException
* if id is null.
*/
E FindOne(ID id);
/**
* @return all entities
*/
IEnumerable<E> FindAll();
/**
* @param entity
* entity must be not null
* @return null- if the given entity is saved
* otherwise returns the entity (id already exists)
* @throws ValidationException
* if the entity is not valid
* @throws IllegalArgumentException
* if the given entity is null. *
*/
E Save(E entity);
/**
* removes the entity with the specified id
* @param id
* id must be not null
* @return the removed entity or null if there is no entity with the
given id
* @throws IllegalArgumentException
* if the given id is null.
*/
E Delete(ID id);
/**
* @param entity
* entity must not be null
* @return null - if the entity is updated,
* otherwise returns the entity - (e.g id does not
exist).
* @throws IllegalArgumentException
* if the given entity is null.
* @throws ValidationException
* if the entity is not valid.
*/
E Update(E entity);
}
}<file_sep>/Domain/Team.cs
namespace Lab1
{
public class Team : Entity<int>
{
public Team(int id, string name) : base(id)
{
Name = name;
}
public string Name { get; set; }
public override string ToString()
{
return $"{base.ToString()}, {nameof(Name)}: {Name}";
}
}
}<file_sep>/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Lab1.Repository;
using Lab1.UI;
namespace Lab1 {
internal class Program {
private static List<string> _teamNames = new List<string>(new[] {
"Houston Rockets", "Los Angeles Lakers", "LA Clippers", "Chicago Bulls", "Cleveland Cavaliers", "Utah Jazz",
"Brooklyn Nets", "New Orleans Pelicans", "Indiana Pacers", "Toronto Raptors", "Charlotte Hornets", "Phoenix Suns",
"Portland TrailBlazers", "Golden State Warriors", "Washington Wizards", "San Antonio Spurs", "Orlando Magic",
"Denver Nuggets", "Detroit Pistons", "Atlanta Hawks", "Dallas Mavericks", "Sacramento Kings", "Oklahoma City Thunder",
"Boston Celtics", "New York Knicks", "Minnesota Timberwolves", "Miami Heat", "Milwaukee Bucks"
});
private static List<string> _schoolNames = new List<string>(new[] {
"Scoala Gimnaziala \"Octavian Goga\"", "Liceul Teoretic \"Lucian Blaga\"", "Scoala Gimnaziala \"<NAME>\"",
"Scoala Gimnaziala \"Ion Creanga\"", "Colegiul National Pedagogic \"Gheorghe Lazar\"",
"Scoala Gimnaziala Internationala SPECTRUM", "Colegiul National \"Emil Racovita\"", "Colegiul National \"George Cosbuc\"",
"Scoala Gimnaziala \"Ion Agarbiceanu\"", "Liceul Teoretic \"Avram Iancu\"", "Scoala Gimnaziala \"Constantin Brancusi\"",
"Liceul Teoretic \"Onisifor Ghibu\"", "Liceul cu Program Sportiv Cluj-Napoca", "Liceul Teoretic \"<NAME>\"",
"Liceul Teoretic \"<NAME>\"", "Scoala \"<NAME>\"", "Scoala Gimnaziala \"<NAME>\"",
"Scoala Gimnaziala \"<NAME>\"", "Liceul Teoretic \"<NAME>\"", "Colegiul National \"<NAME>\"",
"Liceul Teoretic \"<NAME>\"", "Seminarul Teologic Ortodox", "Liceul de Informatica \"<NAME>\"",
"Scoala Gimnaziala \"<NAME>\"", "Liceul Teoretic ELF", "Scoala Gimnaziala \"<NAME>\" Floresti"
});
private static string filePathDirectory = "./";
public static void Main() {
TeamFileRepository teamRepository = new TeamFileRepository(new TeamValidator(), filePathDirectory + "teams.txt");
Service<int, Team> teamService = new Service<int, Team>(teamRepository);
PlayerFileRepository playerRepository = new PlayerFileRepository(new PlayerValidator(),
filePathDirectory + "players.txt", teamRepository);
PlayerService playerService = new PlayerService(playerRepository);
GameFileRepository gameRepository =
new GameFileRepository(new GameValidator(), filePathDirectory + "games.txt", teamRepository);
GameService gameService = new GameService(gameRepository);
ActivePlayerFileRepository activePlayersRepository =
new ActivePlayerFileRepository(new ActivePlayerValidator(), filePathDirectory + "activePlayers.txt");
ActivePlayerService activePlayerService = new ActivePlayerService(activePlayersRepository);
//adds data to repositories
//AddJunk(teamRepository, playerRepository, gameRepository, activePlayersRepository);
ConsoleUi consoleUi = new ConsoleUi(playerService, teamService, gameService, activePlayerService,
_teamNames, _schoolNames);
consoleUi.Run();
}
private static void AddJunk(TeamFileRepository teamRepository, PlayerFileRepository playerRepository,
GameFileRepository gameRepository, ActivePlayerFileRepository activePlayersRepository) {
Random rand = new Random(DateTime.Now.Millisecond);
string[] firstNames = {
"Jonathan", "<NAME>.", "<NAME>.", "Dio", "George", "Joseph", "<NAME>.", "Lisa", "Rudol", "Suzi", "Kars",
"Esidisi", "Wamuu", "Santana", "Jotaro", "Muhammad", "Noriaki", "<NAME>", "Iggy", "Holy", "Vanilla", "Hol",
"<NAME>.", "Oingo", "Boingo", "Anubis", "Telence", "Josuke", "Okuyasu", "Koichi", "Rohan", "Hayato", "Yukako",
"Tonio", "Tomoko", "Yoshikage", "Giorno", "Bruno", "Leone", "Guido", "Guido", "Narancia", "Trish", "Coco", "Pericolo",
"Diavolo", "Cioccolata", "Polpo", "Pesci", ""
};
string[] lastNames = {
"Joestar", "Zeppeli", "Speedwagon", "Brando", "Lisa", "<NAME>", "Q", "Kujo", "Avdol", "Kakyoin", "Polnareff",
"Ice", "Horse", "D'Arby", "Higashikata", "Nijimura", "Hirose", "Kishibe", "Kawajiri", "Yamagishi", "Trussardi", "Kira",
"Giovanna", "Bucciarati", "Abbacchio", "Mista", "Ghirga", "Una", "Jumbo", "Doppio", ""
};
//adding random teams
int id = 0;
foreach (string teamName in _teamNames) teamRepository.Save(new Team(id++, teamName));
//adding arandom players
id = 0;
var schoolTeams = Enumerable.Range(0, _teamNames.Count).OrderBy(x => rand.Next()).Take(_schoolNames.Count).ToList();
foreach (var i in schoolTeams.Select((teamId, index) => (index, teamId))) {
Team team = teamRepository.FindOne(i.teamId);
for (int j = 0; j < rand.Next(15, 25); j++)
playerRepository.Save(new Player(id++, GenerateRandomName(rand, firstNames, lastNames), _schoolNames[i.index],
team));
}
//adding random games
DateTime start = new DateTime(1995, 1, 1);
DateTime end = DateTime.Today;
int range = (end - start).Days;
for (int i = 0; i < _schoolNames.Count - 1; i++)
for (int j = i + 1; j < _schoolNames.Count; j++)
if (rand.Next(3) == 0) {
Team team1 = teamRepository.FindOne(i);
Team team2 = teamRepository.FindOne(j);
if (schoolTeams.Contains(team1.Id) && schoolTeams.Contains(team2.Id))
gameRepository.Save(new Game(team1, team2, start.AddDays(rand.Next(range))));
}
//adding random active players
var players = playerRepository.FindAll().ToList();
foreach (Game game in gameRepository.FindAll()) {
AddActivePlayerToGame(game.Id.Team1Id, game.Id.Team2Id, game.Id.Team1Id, players, rand, activePlayersRepository);
AddActivePlayerToGame(game.Id.Team1Id, game.Id.Team2Id, game.Id.Team2Id, players, rand, activePlayersRepository);
}
}
private static void AddActivePlayerToGame(int team1Id, int team2Id, int teamId, List<Player> players, Random rand,
ActivePlayerFileRepository activePlayersRepository) {
var teamPlayers = players.Where(p => p.Team.Id.Equals(teamId)).ToList();
var teamPlaying = Enumerable.Range(0, teamPlayers.Count()).OrderBy(x => rand.Next()).ToArray();
int i = 0;
foreach (Player player in teamPlayers) {
if (teamPlaying[i] < 15) {
int score = 0;
if (teamPlaying[i] < 11) {
int scoreProbability = rand.Next(1, 101);
if (scoreProbability > 95)
score = 2;
else if (scoreProbability > 80) score = 1;
activePlayersRepository.Save(new ActivePlayer(player.Id, team1Id, team2Id, score, ActivityState.Playing));
} else
activePlayersRepository.Save(new ActivePlayer(player.Id, team1Id, team2Id, score, ActivityState.Reserve));
}
i++;
}
}
private static string GenerateRandomName(Random rand, string[] firstName, string[] lastName) {
return (firstName[rand.Next(firstName.Length)] + " " + lastName[rand.Next(lastName.Length)]).Trim();
}
}
}<file_sep>/Domain/Game.cs
using System;
using System.Collections.Generic;
namespace Lab1
{
public class Game : Entity<GameId<int>>
{
public Game(Team team1, Team team2, DateTime date) : base(new GameId<int>(team1.Id, team2.Id))
{
this.Team1 = team1;
this.Team2 = team2;
this.Date = date;
}
private Team _team1;
public Team Team1
{
get => _team1;
set
{
_team1 = value;
Id.Team1Id = value.Id;
}
}
private Team _team2;
public Team Team2
{
get => _team2;
set
{
_team2 = value;
Id.Team2Id = value.Id;
}
}
public DateTime Date { get; set; }
}
public class GameId<T>
{
public T Team1Id { get; set; }
public T Team2Id { get; set; }
public GameId(T team1Id, T team2Id)
{
Team1Id = team1Id;
Team2Id = team2Id;
}
public override string ToString()
{
return $"{nameof(Team1Id)}: {Team1Id}, {nameof(Team2Id)}: {Team2Id}";
}
protected bool Equals(GameId<T> other)
{
return EqualityComparer<T>.Default.Equals(Team1Id, other.Team1Id) &&
EqualityComparer<T>.Default.Equals(Team2Id, other.Team2Id) ||
EqualityComparer<T>.Default.Equals(Team1Id, other.Team2Id) &&
EqualityComparer<T>.Default.Equals(Team2Id, other.Team1Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((GameId<T>) obj);
}
public override int GetHashCode()
{
unchecked
{
var hc1 = EqualityComparer<T>.Default.GetHashCode(Team1Id);
var hc2 = EqualityComparer<T>.Default.GetHashCode(Team2Id);
return (Math.Min(hc1, hc2) * 397) ^ Math.Max(hc1, hc2);
}
}
}
}<file_sep>/UI/ConsoleUi.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Lab1.UI {
public class ConsoleUi {
private PlayerService _playerService;
private Service<int, Team> _teamService;
private GameService _gameService;
private ActivePlayerService _activePlayerService;
private List<string> _teamNames;
private List<string> _schoolNames;
public ConsoleUi(PlayerService playerService, Service<int, Team> teamService, GameService gameService,
ActivePlayerService activePlayerService, List<string> teamNames, List<string> schoolNames) {
_playerService = playerService;
_teamService = teamService;
_gameService = gameService;
_activePlayerService = activePlayerService;
_teamNames = teamNames;
_schoolNames = schoolNames;
}
private void PrintMenu() {
Console.WriteLine("0 - Exit application\n" + "1 - Show all players from a given team\n" +
"2 - Show active players from a given team and a given game\n" +
"3 - Show all games from a given time period\n" + "4 - Show the score from a given game\n");
}
public void Run() {
bool running = true;
PrintMenu();
while (running) {
try {
switch (ReadLine("Enter command:")) {
case "0":
running = false;
_playerService.WriteAllToFile();
_teamService.WriteAllToFile();
_gameService.WriteAllToFile();
_activePlayerService.WriteAllToFile();
break;
case "1":
Command1();
break;
case "2":
Command2();
break;
case "3":
Command3();
break;
case "4":
Command4();
break;
default:
PrintMenu();
break;
}
}
catch (Exception e) {
if (e is UiException || e is ValidationException || e is FormatException)
Console.WriteLine(e.Message);
else
throw;
}
}
}
private string ReadLine(string text) {
Console.WriteLine(text);
return Console.ReadLine();
}
private void Command1() {
int teamId = int.Parse(ReadLine("Write team Id"));
Team team = _teamService.FindOne(teamId);
if (team == null) throw new UiException("Team not found");
foreach (Player player in _playerService.ShowAllPlayersFromATeam(team.Id)) Console.WriteLine(player);
}
private void Command2() {
int team1Id = int.Parse(ReadLine("Write first team Id"));
int team2Id = int.Parse(ReadLine("Write second team Id"));
int teamId = int.Parse(ReadLine("Write the Id of the team you want to see the active players"));
Game game = _gameService.FindOne(new GameId<int>(team1Id, team2Id));
if (game == null) throw new UiException("Teams: " + team1Id + " and " + team2Id + " haven't played a game yet.");
if (team1Id != teamId && team2Id != teamId)
throw new UiException("Team with the id " + teamId + " hasn't played in that game.");
foreach (var player in _activePlayerService.ShowAllActivePlayersFromTeamFromGame(game.Id, teamId, _playerService))
Console.WriteLine(player);
}
private void Command3() {
DateTime startDate = DateTime.Parse(ReadLine("Write the start of the time period, format is dd/mm/yyyy"));
DateTime endDate = DateTime.Parse(ReadLine("Write the end of the time period, format is dd/mm/yyyy"));
foreach (var game in _gameService.ShowAllGamesBetween(startDate, endDate)) Console.WriteLine(game);
}
private void Command4() {
int team1Id = int.Parse(ReadLine("Write first team Id"));
int team2Id = int.Parse(ReadLine("Write second team Id"));
GameId<int> gameId = new GameId<int>(team1Id, team2Id);
Game game = _gameService.FindOne(gameId);
if (game == null) throw new UiException("Teams: " + team1Id + " and " + team2Id + " haven't played a game yet.");
Console.WriteLine(_activePlayerService.CalculateGameScore(gameId, _playerService));
}
}
}<file_sep>/test/GameId.cs
namespace test
{
public class GameId
{
private int id1;
private int id2;
public GameId(int id1, int id2)
{
this.id1 = id1;
this.id2 = id2;
}
public int Id1
{
get => id1;
set => id1 = value;
}
public int Id2
{
get => id2;
set => id2 = value;
}
protected bool Equals(GameId other)
{
return id1 == other.id1 && id2 == other.id2 || id1 == other.id2 && id2 == other.id1;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((GameId) obj);
}
public override int GetHashCode()
{
unchecked
{
return (id1 * 397) ^ id2;
}
}
}
}<file_sep>/Domain/Student.cs
namespace Lab1
{
public class Student : Entity<int>
{
public Student(int id, string name, string school) : base(id)
{
this.Name = name;
this.School = school;
}
public string Name { get; set; }
public string School { get; set; }
public override string ToString()
{
return $"{base.ToString()}, {nameof(Name)}: {Name}, {nameof(School)}: {School}";
}
}
} | a145d5dca8ce44009657ac5396858a201221cf0c | [
"Markdown",
"C#"
] | 23 | C# | SurubariuRazvan/L1CSharp | e741df6348c9228393b71c10460c0ec4be4148e4 | 3fd95724851683befc859b9adf97fc89db2af04d |
refs/heads/master | <repo_name>juwith/simplest-cmake<file_sep>/simple_bin_use_lib/src/CMakeLists.txt
add_executable(helloCall call_hello.c)
target_link_directories(helloCall PRIVATE ${HELLOLIB_LIBRARY_DIRS})
target_link_libraries(helloCall ${HELLOLIB_LIBRARIES})
include_directories(${HELLOLIB_INCLUDEDIR})
install(TARGETS helloCall DESTINATION bin)
<file_sep>/simple_bin/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(CMakeHelloWorld)
#version number
set(CMakeHelloWorld_VERSION_MAJOR 1)
set(CMakeHelloWorld_VERSION_MINOR 0)
#add subdirectory
add_subdirectory(src)
<file_sep>/simple_bin_use_lib/src/call_hello.c
#include <stdio.h>
#include <hello_lib.h>
int main()
{
printf("call hello_lib function\n");
Hello_myfunc();
printf("done\n");
return 0;
}<file_sep>/simple_lib/src/hello_lib.h
#ifndef __HELLO_LIB_H__
#define __HELLO_LIB_H__
void Hello_myfunc();
#endif<file_sep>/simple_lib/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(CMakeHelloWorldLib)
#version number
set(CMakeHelloWorldLib_VERSION_MAJOR 1)
set(CMakeHelloWorldLib_VERSION_MINOR 0)
#add subdirectory
add_subdirectory(src)
configure_file(helloLib.pc.in ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig/helloLib.pc @ONLY) <file_sep>/simple_bin_use_lib/README.md
# simplest-cmake
How to use
step 1. make build folder
```
mkdir build
cd build
```
step 2. configure cmake
```
export PKG_CONFIG_PATH=/opt/install
cmake ../
```
step 3. build
```
make
make install
# or
# make DESTDIR=$PWD install
```
<file_sep>/simple_bin_use_lib/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(CMakeHelloWorld)
#version number
set(CMakeHelloWorld_VERSION_MAJOR 1)
set(CMakeHelloWorld_VERSION_MINOR 0)
#find lib
set(ENV{PKG_CONFIG_PATH} "/opt/install/lib/pkgconfig")
FIND_PACKAGE(PkgConfig)
pkg_check_modules(HELLOLIB helloLib)
#add subdirectory
add_subdirectory(src)
<file_sep>/simple_bin/src/CMakeLists.txt
add_executable(helloCmake hello.c)
install(TARGETS helloCmake DESTINATION bin)
<file_sep>/simple_lib/src/CMakeLists.txt
add_library(helloLib SHARED hello_lib.c)
set_target_properties(helloLib PROPERTIES PUBLIC_HEADER "hello_lib.h")
install(TARGETS helloLib
LIBRARY DESTINATION lib
PUBLIC_HEADER DESTINATION include)
<file_sep>/simple_lib/src/hello_lib.c
#include <stdio.h>
void Hello_myfunc()
{
printf("call Hello_myfunc");
} | 6c621a55317ff9aaa153a9a16a73d7d2c61fa156 | [
"Markdown",
"C",
"CMake"
] | 10 | CMake | juwith/simplest-cmake | 5f24c91c75a308f70bc136a41c4d074a091fab3f | ca65b74d0026fb3c4d32a3c48747c75e13d3d0a1 |
refs/heads/master | <file_sep>#include <cstring>
#include <iostream>
#include "MyString.h"
using namespace std;
// Default constructor
MyString::MyString() {
str = new char;
strcpy_s(str, 1, "");
}
// Constructor that accepts c-string
MyString::MyString(const char* input) {
int size = strlen(input) + 1;
str = new char[size];
strcpy_s(str, size, input);
}
// Copy constructor
MyString::MyString(const MyString& other) {
cout << "Inside copy constructor, copying " << other.str << endl;
copy(other);
}
// Overloaded assignment
MyString MyString::operator=(const MyString& other) {
if (this != &other) {
delete[] str;
copy(other);
}
return *this;
}
// Overloaded addition
MyString MyString::operator+(MyString other) {
MyString sum;
int size = strlen(str) + strlen(other.str) + 1;
sum.str = new char[size];
strcpy_s(sum.str, size, str);
strcat_s(sum.str, size, other.str);
return sum;
}
// Overloaded comparison
bool MyString::operator==(MyString other) {
return strcmp(str, other.str) == 0;
}
// c_str(): returns the pointer to the internal c-string
char* MyString::c_str() const {
return str;
}
// copy(): private function to copy data from another MyString, used in copy constructor and overloaded assignment
void MyString::copy(const MyString& other) {
int size = strlen(other.str) + 1;
str = new char[size];
strcpy_s(str, size, other.str);
}
// Destructor
MyString::~MyString() {
cout << "Inside destructor, deleting " << str << endl;
delete[] str;
}
// Overloaded output
ostream& operator<<(ostream& o, const MyString& s) {
o << s.c_str();
return o;
}<file_sep>// <NAME> - Assignment 5 - MyString
// Copy constructor and destructor both appear to be called a number of times
// I think all of these are in situations where it is necessary (primarily returning from functions)
#include <iostream>
#include "MyString.h"
using namespace std;
void displayFunc(MyString);
MyString returnFunc(MyString);
int main() {
MyString s1;
MyString s2("test");
MyString s3(s2);
cout << "Initialization:" << endl;
cout << "s1: " << s1 << endl;
cout << "s2: " << s2 << endl;
cout << "s3: " << s3 << endl << endl;
s1 = s2 = s3;
cout << "s1 = s2 = s3:" << endl;
cout << "s1: " << s1 << endl;
cout << "s2: " << s2 << endl;
cout << "s3: " << s3 << endl << endl;
s1 = s2 + " " + s3;
cout << "s1 = s2 + \" \" + s3:" << endl;
cout << "s1: " << s1 << endl;
cout << "s2: " << s2 << endl;
cout << "s3: " << s3 << endl << endl;
MyString isEqual;
if (s1 == s2) { isEqual = "TRUE"; }
else { isEqual = "FALSE"; }
cout << "s1 == s2: " << isEqual << endl << endl;
if (s2 == s3) { isEqual = "TRUE"; }
else { isEqual = "FALSE"; }
cout << "s2 == s3: " << isEqual << endl << endl;
cout << "Passing s1 to displayFunc():" << endl;
displayFunc(s1);
cout << endl;
cout << "Passing s1 to returnFunc(): " << returnFunc(s1) << endl << endl;
s1 = s1;
cout << "s1 = s1:" << endl;
cout << "s1: " << s1 << endl;
}
// displayFunc(): simply couts the value of a MyString
void displayFunc(MyString s) {
cout << "Inside displayFunc(): " << s << endl;
}
// returnFunc(): simply returns a copy of a MyString
MyString returnFunc(MyString s) {
MyString s2 = s;
return s2;
}<file_sep># prog5-mystring-TimothyWhiteOC
prog5-mystring-TimothyWhiteOC created by GitHub Classroom
Good job. Only issue is that most of these functions will crash if passed a default-constructed MyString
Grade 38/40
<file_sep>#pragma once
#include <iostream>
using namespace std;
class MyString {
private:
char *str;
void copy(const MyString&);
public:
MyString();
MyString(const char*);
MyString(const MyString&);
MyString operator=(const MyString&);
MyString operator+(MyString);
bool operator==(MyString);
char* c_str() const;
~MyString();
};
// Including a prototype for overloaded output in the header file so main knows it exists
ostream& operator<<(ostream& o, const MyString& s); | 7e7ac1c4734ce5b7231d703db6471bb967a24294 | [
"Markdown",
"C++"
] | 4 | C++ | OC-MCS/prog5-mystring-TimothyWhiteOC | bce882c3988a93ed36269731e8b21facb5f86b7e | 8ed52811b62cecca7d04ab7027466a75a454c6d8 |
refs/heads/master | <file_sep>scrollToElement = (el, ms) => {
let speed = ms ? ms : 600;
$("html,body").animate(
{
scrollTop: $(el).offset().top - 50,
},
speed
);
};
const cookieContainer = document.querySelector(".cookie-container");
const cookieButton = document.querySelector(".cookie-btn");
cookieButton.addEventListener("click", () => {
cookieContainer.classList.remove("active");
localStorage.setItem("cookieBannerDisplayed", "true");
});
setTimeout(() => {
if (!localStorage.getItem("cookieBannerDisplayed")) {
cookieContainer.classList.add("active");
}
}, 2000);
// $(document).ready(function () {
// $("#loginModal").modal("show");
// $(function () {
// $('[data-toggle="tooltip"]').tooltip();
// });
// });
| b6e0fe2336f3af796ee509f1affe870ff49ae2f9 | [
"JavaScript"
] | 1 | JavaScript | Munteanu-Alexandru/Basic-webpage-template | 7f6f2d910e0babd6d33f356ed3def060770b8f81 | 9f08fc5b2ef29bd966e2f61c23b6cb285d172639 |
refs/heads/main | <file_sep># Galeria-de-plantuchas
Hice una mini galeria usando php para mostrar a mis plantas.
<file_sep><!DOCTYPE html>
<html>
<head>
<title> mis plantitas </title>
<meta charset="utf-8">
<link rel="stylesheet" href="estilos.css">
</head>
<body>
<header>
<nav id="botones">
<ul>
<li><a href="index.php?id=mar#descripcion"> Martina </a> </li>
<li> <a href="index.php?id=va#descripcion"> Vanessa </a> </li>
<li> <a href="index.php?id=le#descripcion"> Lenina </a> </li>
<li> <a href="index.php?id=se#descripcion"> Señor enojado </a> </li>
<li> <a href="index.php?id=pir#descripcion"> Pirotecnia </a> </li>
<li> <a href="index.php?id=ma#descripcion"> Macuca </a> </li>
<li> <a href="index.php?id=ba#descripcion"> Batata </a> </li>
<li> <a href="index.php?id=pi#descripcion"> Piruja </a> </li>
</ul>
</nav>
</header>
<section id="galeria">
<?php
if(isset($_GET['id'])){
switch ($_GET['id']){
case'mar':
$titulo='Martina';
$foto='imagenes/martina.jpeg';
$texto='Martina es hermosa. El conflicto principal es que las florecitas se me estan muriendo, ya le cambie la tierra y todo. estoy pensando en hacer composta casera para ponerle a la planta por que esta medio triste Martinita.
Yo la veo muy deprimida ultimamente, a veces pienso que es por que tal vez es invierno y en primavera-verano se va a sentir mejor.
La verdad es una flor hermosa y la tengo que regar un toque mas.
Se que es una flor, pero es la unica de mis plantas que no identifico la especie. ';
break;
case'va':
$titulo='Vanessa';
$foto='imagenes/vanessa.jpeg';
$texto='Vanessa, cuando me la vendieron me dijeron que las hojas parecian orejitas de conejo y la verdad estyo totalmente de acuerdo. Vanessa es tierna y linda.
Pense que era un suculenta pero al final no se, creo que si igual. No necesita mucha agua, todavia esta chiquita y no es tan dificil mantenerla. ';
break;
case'le':
$titulo='Lenina';
$foto='imagenes/lenina.jpeg';
$texto=' Le puse ese nombre por uno de mis libros favoritos "un mundo feliz" el personaje de lenina me fascina y ademas como la asocio al color violeta y la planta es violeta las uni.
Creo que Lenina es una lavanda, aunque tampoco estoy segura. Las flores de lenina estan caidas de noche pero de dia es como se levantan un poco y la pongo al sol para que se ponga linda y feliz.';
break;
case'se':
$titulo='Señor enojado';
$foto='imagenes/señor.jpeg';
$texto=' El señor enojado siempre parece enojado. Es el cactus mas grueso que cuide jamas. No se deja agarrar por los pinchitos, pero cuando lo replante no me dio miedo de pincharme. Es un cactus muy rebelde y no le gusta mucho que le hablen, prefiere estar tranquilo. ';
break;
case'pir':
$titulo='Pirotecnia';
$foto='imagenes/pirotecnia.jpeg';
$texto='Pirotecnia es un cactus, le puse asi por que sus formas la hacen ver como un cactus explosivo, parece un cactus que exploto, pero en realidad es ella con sus hijitos alrededor. Replantar a Pirotecnia fue dificil, sobre todo por que sus hijos no se quedaban quietos. No necesita mucha agua y la pongo al sol para que se relaje.';
break;
case'ma':
$titulo='Macuca';
$foto='imagenes/macuca.jpeg';
$texto='Macuca es un cactus. Macuca es muy graciosa, cuando la veo pienso que parece como una torta de cactus, no se. Macuca no necesita mucha agua pero siempre la pongo al sol por que le gusta broncearse un poco. ';
break;
case'ba':
$titulo='Batata';
$foto='imagenes/batata.jpeg';
$texto='Batata le puse asi por que cuando la compre era chiquita y parecia una batatita, a pesar del color y demas. Es un cactus y es un cactus con mucha personalidad. esta un poco inclinada, pero a ver si se endereza un poco con el tiempo. ';
break;
case'pi':
$titulo='Piruja';
$foto='imagenes/piruja.jpg';
$texto='Piruja es una suculenta, la cuido desde que es una bebita. La adopte en un bautismo, estaba de souvenir.
Rompi el frasco de vidrio para liberarla y la plante para que creciera, hoy en dia es una planta enorme, pero le falta agua.
Piruja a veces parece que te quiere abrazar, por sus largos brazos curvos y extendidos. Sus hojas en invierno se deterioran,
pero es una suculenta, calculo que crecio tanto que no estan tan llenitas las hojas por que tampoco la riego tanto.';
break;
}
?>
<nav id="contenido">
<div id="foto"style="background-image: url(<?php echo $foto?>);"> </div>
<div id="descripcion">
<h1> <?php echo $titulo; ?> </h1>
<h3> <?php echo $texto; ?> </h3>
</div>
</nav>
<?php
}
?>
</section>
</body>
</html> | 653c52a7d16b7871a5a840cf19e6eb7bed28eae3 | [
"Markdown",
"PHP"
] | 2 | Markdown | yasminmartins01/Galeria-de-plantuchas | 82cdde3486dad6d8e05ac980b13357b45f3f8dfb | 438f1555b577e69e82c0f5ce98fd44983935eb74 |
refs/heads/master | <file_sep># Comparing-Genes-Proteins-and-Genomes-Bioinformatics-III-
Coursera Based course that covers algorithms to compare biological sequences. [Dymanic programming and combination algorithms].
<file_sep>"""
Global Alignment Problem
Find the highest-scoring alignment between two strings using a scoring matrix.
Given: Two protein strings.
Return: The maximum alignment score of these strings followed by an
alignment achieving this maximum score.
https://github.com/ahmdeen/Bioinformatic-Algorthims/blob/7cae61bb45535911f220da290f9ecf609b964058/Ros5E_GlobalAlignment.py
https://github.com/ngaude/sandbox/search?utf8=%E2%9C%93&q=+++++PLEASANTLY++++++MEANLY
CODE CHALLENGE: Solve the Global Alignment Problem.
Input: Two protein strings written in the single-letter amino acid alphabet.
Output: The maximum alignment score of these strings followed by an alignment achieving this
maximum score. Use the BLOSUM62 scoring matrix and indel penalty σ = 5.
Sample Input:
PLEASANTLY
MEANLY
Sample Output:
8
PLEASANTLY
-MEA--N-LY
"""
import os
'''Classes'''
class blosum62(object):
'''Class to score proteins using the BLOSUM62 matrix'''
def __init__(self):
'''Initalize BLOSUM62 Matrix'''
with open(os.path.join(os.path.dirname(__file__), 'BLOSUM62.txt')) as inFile:
lines = [line.strip().split() for line in inFile.readlines()]
self.S = {(item[0], item[1]): int(item[2]) for item in lines}
def __getitem__(self, pair):
'''Returns the score of a given pair'''
return self.S[pair[0],pair[1]]
'''Functions'''
def globalAlignment(seq1, seq2, ScoreMatrix, sig):
'''Returns the global alignment of the input sequences utilizing the given ScoringMatrix and indel penalty'''
len1, len2 = len(seq1), len(seq2)
S = [[0]*(len2+1) for s in xrange(len1+1)]
backtrack = [[0]*(len2+1) for bt in xrange(len1+1)]
for i in xrange(1, len1+1):
S[i][0] = -i*sig
for j in xrange(1, len2+1):
S[0][j] = -j*sig
for i in xrange(1, len1+1):
for j in xrange(1, len2+1):
scoreList = [S[i-1][j] - sig, S[i][j-1] - sig, S[i-1][j-1] + ScoreMatrix[seq1[i-1], seq2[j-1]]]
S[i][j] = max(scoreList)
backtrack[i][j] = scoreList.index(S[i][j])
#-----
indelInsertFcn = lambda seq, i: seq[:i] + '-' + seq[i:]
#-----
align1, align2 = seq1, seq2
a, b = len1, len2
maxScore = str(S[a][b])
while a*b != 0:
if backtrack[a][b] == 0:
a -= 1
align2 = indelInsertFcn(align2, b)
elif backtrack[a][b] == 1:
b -= 1
align1 = indelInsertFcn(align1, a)
else:
a -= 1
b -= 1
for i in xrange(a):
align2 = indelInsertFcn(align2, 0)
for j in xrange(b):
align1 = indelInsertFcn(align1, 0)
return maxScore, align1, align2
'''Input/Output'''
"""
seq1 = 'PLEASANTLY'
seq2 = 'MEANLY'
"""
with open('5_Global Alignment Problem.txt') as infile:
seq1, seq2 = [line.strip() for line in infile.readlines()]
indelPenalty = 5
alignment = globalAlignment(seq1,seq2, blosum62(), indelPenalty)
answer = '\n'.join(alignment)
print answer
with open('5_Global Alignment Problem_Answer.txt', 'w') as outfile:
outfile.write(answer)
<file_sep>"""
Edit Distance Problem
Find the edit distance between two strings.
Given: Two protein strings.
Return: The edit distance between these strings.
Levenshtein introduced edit distance but did not describe an algorithm for computing it, which we leave to you.
Edit Distance Problem: Find the edit distance between two strings.
Input: Two strings.
Output: The edit distance between these strings.
CODE CHALLENGE: Solve the Edit Distance Problem.
Sample Input:
PLEASANTLY
MEANLY
Sample Output:
5
"""
'''Functions'''
def editDist(seq1, seq2):
'''Returns the Edit Distance between the two input strings'''
len1, len2 = len(seq1), len(seq2)
#Initialize Matrix
M = [[0 for j in xrange(len2 + 1)] for i in xrange(len1+1)]
#Fill out the first row and the first column of the Matrix
for i in range(1, len1 + 1):
M[i][0] = i
for j in range(1, len2 + 1):
M[0][j] = j
#Fill out the rest of the Matrix
for i in xrange(1, len1 + 1):
for j in xrange (1, len2 + 1):
if seq1[i-1] == seq2[j-1]:
M[i][j] = M[i-1][j-1]
else:
M[i][j] = min(M[i-1][j] +1, M[i][j-1] + 1, M[i-1][j-1] + 1)
return M[len1][len2]
'''Input/Output'''
with open('7_Edit_Distance_ Problem.txt') as infile:
seq1, seq2 = [line.strip() for line in infile.readlines()]
answer = editDist(seq1, seq2)
print str(answer)
with open('7_Edit_Distance_ Problem_Answer.txt', 'w') as outfile:
outfile.write(str(answer))<file_sep>'''
DPCHANGE(money, Coins)
MinNumCoins(0) = 0
for m = 1 to money
MinNumCoins(m) = inf
for i = 1 to |Coins|
if m less then or equal coini
if MinNumCoins(m - coini) + 1 less then MinNumCoins(m)
MinNumCoins(m) = MinNumCoins(m - coini) + 1
output MinNumCoins(money)
'''
def dynamicCoinChange( coins, change ):
#initialize to zero
Optimal = [0 for i in range(0, change+1)]
for i in range(1, change+1):
smallest = float("inf")
for j in range(0, len(coins)):
if (coins[j] <= i):
smallest = min(smallest, Optimal[i - coins[j]])
Optimal[i] = 1 + smallest
return Optimal[change]
change = 40;
coins = '50,25,20,10,5,1';
#splitting on comma and map to int
coins = map(int,coins.split(','));
#for coins, change in problems:
print "Minium number of coins=", dynamicCoinChange(coins, change)
<file_sep>"""
Fitting Alignment Problem
Construct a highest-scoring fitting alignment between two strings.
Given: Two DNA strings v and w, where v has length at most 10000 and w has length at most 1000.
Return: The maximum score of a fitting alignment of v and w, followed by a fitting alignment
achieving this maximum score. Use the simple scoring method in which matches count +1 and both the
mismatch and indel penalties are equal to 1. (If multiple fitting alignments achieving the maximum
score exist, you may return any one.)
CODE CHALLENGE: Solve the Fitting Alignment Problem.
Input: Two nucleotide strings v and w, where v has length at most 1000 and w has length at most 100.
Output: A highest-scoring fitting alignment between v and w. Use the simple scoring method in which
matches count +1 and both the mismatch and indel penalties are 1.
Sample Input:
GTAGGCTTAAGGTTA
TAGATA
Sample Output:
2
TAGGCTTA
TAGA--TA
"""
'''Functions'''
def fitAlignment(seq1, seq2):
'''Returns the maximum score of a fitting alignment of the input sequences, followed by the alignment'''
len1, len2 = len(seq1), len(seq2)
#Initialize Score and Backtrack Matricies as 0 matricies
S = [[0 for j in xrange(len2 + 1)] for i in xrange(len1 + 1)]
backtrack = [[0 for j in xrange(len2 + 1)] for i in xrange(len1 + 1)]
#Complete the entries in the matricies
for i in xrange(1, len1 + 1):
for j in xrange(1, len2 + 1):
scoreList = [S[i-1][j] - 1, S[i][j-1] - 1, S[i-1][j-1] + [-1, 1][seq1[i-1] == seq2[j-1]]] #*
S[i][j] = max(scoreList)
backtrack[i][j] = scoreList.index(S[i][j])
#Get the score of the end alignment of seq2, the shorter sequence
b = len2
a = max(enumerate([S[row][b] for row in xrange(len2, len1)]), key = lambda y:y[1])[0] + len2
maxScore = str(S[a][b])
#The initial alignment of seq1 to seq2
align1, align2 = seq1[:a], seq2[:b]
#-----
insertIndelFcn = lambda seq, i: seq[:i] + '-' + seq[i:]
#-----
#Backtrack to find fitting alignment
while a*b != 0:
if backtrack[a][b] == 0:
a -= 1
align2 = insertIndelFcn(align2, b)
elif backtrack[a][b] == 1:
b -= 1
align1 = insertIndelFcn(align1, a)
elif backtrack[a][b] == 2:
a -= 1
b -= 1
# Need to cut off seq1 at the ending point
align1 = align1[a:]
return maxScore, align1, align2
'''Input/Output'''
with open('8_Fitting_Alignment_Problem.txt') as infile:
seq1, seq2 = [line.strip() for line in infile.readlines()]
answer = fitAlignment(seq1, seq2)
print '\n'.join(answer)
with open('8_Fitting_Alignment_Problem_Answer.txt', 'w') as outfile:
outfile.write('\n'.join(answer))<file_sep>
EnemyDestructor.prototype.update = function () {
//chase after destructor
if (this.isDead != true && destructor.isDead == false){
//we want to make sure that the destructor is moving towards the players destructor
if(destructor.drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(destructor.drawX > (this.drawX) ){this.dirx = this.speed; }
if(destructor.drawY < this.drawY){this.diry = -this.speed; }
if(destructor.drawY > this.drawY){this.diry = this.speed; }
}
// if palyers destroyer is dead, chase after the players buildersbuilders
else if (this.isDead != true && numberOfBuilders > 0 && Constructor_player_array[0].isDead == false){
if(Constructor_player_array[0].drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(Constructor_player_array[0].drawX > (this.drawX) ){this.dirx = this.speed; }
if(Constructor_player_array[0].drawY < this.drawY){this.diry = -this.speed; }
if(Constructor_player_array[0].drawY > this.drawY){this.diry = this.speed; }
}
else if (this.isDead != true && numberOfBuilders > 1 && Constructor_player_array[1].isDead == false){
if(Constructor_player_array[1].drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(Constructor_player_array[1].drawX > (this.drawX) ){this.dirx = this.speed; }
if(Constructor_player_array[1].drawY < this.drawY){this.diry = -this.speed; }
if(Constructor_player_array[1].drawY > this.drawY){this.diry = this.speed; }
}
else if (this.isDead != true && numberOfBuilders > 2 && Constructor_player_array[2].isDead == false){
if(Constructor_player_array[2].drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(Constructor_player_array[2].drawX > (this.drawX) ){this.dirx = this.speed; }
if(Constructor_player_array[2].drawY < this.drawY){this.diry = -this.speed; }
if(Constructor_player_array[2].drawY > this.drawY){this.diry = this.speed; }
}
else if (this.isDead != true && numberOfBuilders > 3 && Constructor_player_array[3].isDead == false){
if(Constructor_player_array[3].drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(Constructor_player_array[3].drawX > (this.drawX) ){this.dirx = this.speed; }
if(Constructor_player_array[3].drawY < this.drawY){this.diry = -this.speed; }
if(Constructor_player_array[3].drawY > this.drawY){this.diry = this.speed; }
}
else if (this.isDead != true && numberOfBuilders > 4 && Constructor_player_array[4].isDead == false){
if(Constructor_player_array[4].drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(Constructor_player_array[4].drawX > (this.drawX) ){this.dirx = this.speed; }
if(Constructor_player_array[4].drawY < this.drawY){this.diry = -this.speed; }
if(Constructor_player_array[4].drawY > this.drawY){this.diry = this.speed; }
}
//if players destroyer and all builders are dead, chasing after the building
//I send the AI destructor to the top of the building, it not perfect, but most of the bricks will be destroyed
else if (this.isDead != true && numberOfBricks_for_destruction > 0){
if(Bricks_player_array[numberOfBricks_for_destruction-1].drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(Bricks_player_array[numberOfBricks_for_destruction-1].drawX > (this.drawX) ){this.dirx = this.speed; }
if(Bricks_player_array[numberOfBricks_for_destruction-1].drawY < this.drawY){this.diry = -this.speed; }
if(Bricks_player_array[numberOfBricks_for_destruction-1].drawY > this.drawY){this.diry = this.speed; }
}
//if players destroyer, builders and miners are dead, AI will be chashing miners
else if (this.isDead != true && numberOfMiners > 0 && Miners_player_array[0].isDead == false){
if(Miners_player_array[0].drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(Miners_player_array[0].drawX > (this.drawX) ){this.dirx = this.speed; }
if(Miners_player_array[0].drawY < this.drawY){this.diry = -this.speed; }
if(Miners_player_array[0].drawY > this.drawY){this.diry = this.speed; }
}
else if (this.isDead != true && numberOfMiners > 1 && Miners_player_array[1].isDead == false){
if(Miners_player_array[1].drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(Miners_player_array[1].drawX > (this.drawX) ){this.dirx = this.speed; }
if(Miners_player_array[1].drawY < this.drawY){this.diry = -this.speed; }
if(Miners_player_array[1].drawY > this.drawY){this.diry = this.speed; }
}
else if (this.isDead != true && numberOfMiners > 2 && Miners_player_array[2].isDead == false){
if(Miners_player_array[2].drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(Miners_player_array[2].drawX > (this.drawX) ){this.dirx = this.speed; }
if(Miners_player_array[2].drawY < this.drawY){this.diry = -this.speed; }
if(Miners_player_array[2].drawY > this.drawY){this.diry = this.speed; }
}
else if (this.isDead != true && numberOfMiners > 3 && Miners_player_array[3].isDead == false){
if(Miners_player_array[3].drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(Miners_player_array[3].drawX > (this.drawX) ){this.dirx = this.speed; }
if(Miners_player_array[3].drawY < this.drawY){this.diry = -this.speed; }
if(Miners_player_array[3].drawY > this.drawY){this.diry = this.speed; }
}
else if (this.isDead != true && numberOfMiners > 4 && Miners_player_array[4].isDead == false){
if(Miners_player_array[4].drawX < (this.drawX ) ) {this.dirx = -this.speed;}
if(Miners_player_array[4].drawX > (this.drawX) ){this.dirx = this.speed; }
if(Miners_player_array[4].drawY < this.drawY){this.diry = -this.speed; }
if(Miners_player_array[4].drawY > this.drawY){this.diry = this.speed; }
}
//if pleyer does not have any destroers, builders, building or miners, AI destroyer will not move
else{
this.dirx =0;
this.diry = 0;
}
//update the draw coordinates for the AI destroyer
this.drawX = this.drawX + this.dirx;
this.drawY = this.drawY + this.diry;
//prevent runof screen, if new this.drawX and this.drawY are not on canvas, place the AI destroyer back to canvas
//600 is the max height of canvas
if(this.drawY >= (600 -this.height)){
this.drawY = (600 -this.height);
}
if(this.drawY<0){
this.drawY = 0;
}
//800 is the max width of canvas
if(this.drawX >= (800 -this.width)){
this.drawX = (800 -this.width);
}
if(this.drawX <0){
this.drawX = 0;
}
//finally draw the AI destroyer on canvas
ctxEntities.drawImage(imgSprite,this.xpos5,this.ypos5,this.width, this.height,this.drawX, this.drawY,this.width, this.height);
};
function checkHittingEnemyDestructor () {
if (collision(enemydestructor, destructor) && enemydestructor.isDead == false && destructor.isDead == false && !destructor.isHitting && destructor.isSpacebar == false) {
if(innerMeterPlayer.width > 0){
innerMeterPlayer.width = (innerMeterPlayer.width - 50);
}
if(innerMeterPlayer.width == 0){
destructor.die();
numberOfDestructors = 0;
//clearInterval(enemydestractor.moveInterval);
document.getElementById("destructor").innerHTML = numberOfDestructors;
}
}
for (var i = 0; i < Miners_player_array.length; i++) {
if (collision(Miners_player_array[i], enemydestructor)&& enemydestructor.isDead == false && Miners_player_array[i].isDead == false){
Miners_player_array[i].die();
numberOfMiners2 = numberOfMiners2 - 1;
document.getElementById("miner").innerHTML = numberOfMiners2;
}
}
for (var i = 0; i < Constructor_player_array.length; i++) {
if (collision(Constructor_player_array[i], enemydestructor)&& enemydestructor.isDead == false && Constructor_player_array[i].isDead == false){
Constructor_player_array[i].die();
numberOfBuilders2 = numberOfBuilders2 - 1;
document.getElementById("builder").innerHTML = numberOfBuilders2;
}
}
//destroying players bricks
for (var i = 0; i < Bricks_player_array.length; i++) {
if (collision(enemydestructor, Bricks_player_array[i]) && Bricks_player_array[i].isDead == false && enemydestructor.isDead == false) {
numberOfBricks_for_destruction = numberOfBricks_for_destruction-1;
Bricks_player_array[i].die();
document.getElementById("player_height").innerHTML = numberOfBricks_for_destruction;
}
}
};
//collision detection, for more information refer to the following resource
//https://retrosnob.files.wordpress.com/2014/10/foundation-game-design-with-html5-and-javascript-v413hav-1.pdf
function collision(a, b) {
var vx = (a.drawX+ (a.width/2)) - (b.drawX+ (b.width/2));
var vy = (a.drawY+ (a.height/2)) - (b.drawY+ (b.height/2));
var magnitude = Math.sqrt(vx*vx +vy*vy);
var totalRadii = a.width/2 + b.width/2;
var hit = magnitude < totalRadii;
return hit;
}<file_sep>"""
Overlap Alignment Problem
Construct a highest-scoring overlap alignment between two strings.
Given: Two protein strings s and t, each of length at most 1000.
Return: The score of an optimal overlap alignment of v and w, followed by an alignment
CODE CHALLENGE: Solve the Overlap Alignment Problem.
Input: Two strings v and w, each of length at most 1000.
Output: The score of an optimal overlap alignment of v and w, followed by an alignment of a suffix v' of
v and a prefix w' of w achieving this maximum score. Use an alignment score in which matches count
+1 and both the mismatch and indel penalties are 2.
Sample Input:
PAWHEAE
HEAGAWGHEE
Sample Output:
1
HEAE
HEAG
"""
'''Functions'''
def overlapAlignment(seq1, seq2):
'''Returns the score of the overlapAlignment as well as the alignment of the two input sequences'''
len1, len2 = len(seq1), len(seq2)
#Initialize Score and backtrack matricies
S = [[0 for j in xrange(len2 + 1)] for i in xrange(len1 + 1)]
backtrack = [[0 for j in xrange(len2 + 1)] for i in xrange(len1 +1)]
#Inital Max Score**
maxScore = -3*(len1 + len2)
#Complete the Score and backtrack matricies
for i in xrange(1, len1 + 1):
for j in xrange(1, len2 + 1):
#Match = 1, Mismatch/Indel = -2
scoreList = [S[i-1][j-1] + [-2, 1][seq1[i-1] == seq2[j-1]], S[i-1][j] - 2, S[i][j-1] - 2]
S[i][j] = max(scoreList)
backtrack[i][j] = scoreList.index(S[i][j])
#Check for maximums along final row/column
if i == len1 or j == len2:
if S[i][j] > maxScore:
maxScore = S[i][j]
maxIndex = (i,j)
a, b = maxIndex
align1, align2 = seq1[:a], seq2[:b]
#------------
insertIndelFcn = lambda seq, i:seq[:i] + '-' + seq[i:]
#Backtrack to find Alignment
while a*b != 0:
if backtrack[a][b] == 1:
a -= 1
align2 = insertIndelFcn(align2, b)
elif backtrack[a][b] == 2:
b -= 1
align1 = insertIndelFcn(align1, a)
else:
a -= 1
b -= 1
align1 = align1[a:]
align2 = align2[b:]
return str(maxScore), align1, align2
'''Input/Output'''
with open ('9_Overlap_Alignment_Problem.txt') as infile:
seq1, seq2 = [line.strip() for line in infile.readlines()]
answer = overlapAlignment(seq1, seq2)
print '\n'.join(answer)
with open('9_Overlap_Alignment_Problem_Answer.txt', 'w') as outfile:
outfile.write('\n'.join(answer))
<file_sep>"""
CODE CHALLENGE: Solve the Longest Path in a DAG Problem.
Input: An integer representing the source node of a graph, followed by an integer representing the
sink node of the graph, followed by a list of edges in the graph. The edge notation 0->1:7 indicates
that an edge connects node 0 to node 1 with weight 7.
Output: The length of a longest path in the graph, followed by a longest path. (If multiple longest paths exist, you may return any one.)
Sample Input:
0
4
0->1:7
0->2:4
2->3:2
1->4:1
3->4:3
Sample Output:
9
0->2->3->4
"""
"""
Longest Path in a DAG Problem
Find a longest path between two nodes in an edge-weighted DAG.
Given: An integer representing the source node of a graph, followed by an integer
representing the sink node of the graph, followed by an edge-weighted graph.
The graph is represented by a modified adjacency list in which the notation "0->1:7"
indicates that an edge connects node 0 to node 1 with weight 7.
Return: The length of a longest path in the graph, followed by a longest path.
(If multiple longest paths exist, you may return any one.)
"""
def topOrder(rawGraph):
'''Return the input graph topologically ordered'''
rawGraph = set(rawGraph)
orderedList = []
neighbors = list({edge[0] for edge in rawGraph} - {edge [1] for edge in rawGraph})
while len(neighbors) != 0:
orderedList.append(neighbors[0])
nodeStorage = []
for edge in filter(lambda edgy:edgy[0] == neighbors[0], rawGraph):
rawGraph.remove(edge)
nodeStorage.append(edge[1])
for node in nodeStorage:
if node not in {edge[1] for edge in rawGraph}:
neighbors.append(node)
neighbors = neighbors[1:]
return orderedList
def longestPath(graph, edgeDict, source, sink):
'''Return the length of the longest path in the graph, followed by a longest path'''
#print source, sink
#print graph.keys()
tlogOrder = topOrder(graph.keys())
#print tlogOrder
#tlogSource, tlogSink = tlogOrder.index(source), tlogOrder.index(sink)
tlogOrder = tlogOrder[tlogOrder.index(source)+1:tlogOrder.index(sink)+1]
#print tlogOrder
S = {node:-100 for node in {edge[0] for edge in graph.keys()} | {edge[1] for edge in graph.keys()}}
S[source] = 0
bktrack = {node:None for node in tlogOrder}
#print tlogOrder
for node in tlogOrder:
try:
S[node], bktrack[node] = max(map(lambda edgy: [S[edgy[0]] + graph[edgy], edgy[0]], filter(lambda edgy: edgy[1] == node, graph.keys())), key=lambda l: l[0])
except ValueError:
pass
longPath = [sink]
while longPath[0] != source:
longPath = [bktrack[longPath[0]]] + longPath
return S[sink],longPath
with open('4_Longest_Path_DAG.txt') as inFile:
source = int(inFile.readline().strip())
sink = int(inFile.readline().strip())
edges, weight = {},{}
for items in [line.strip().split('->') for line in inFile.readlines()]:
if int(items[0]) not in edges:
edges[int(items[0])] = [int(items[1].split(':')[0])]
else:
edges[int(items[0])].append(int(items[1].split(':')[0]))
weight[int(items[0]), int(items[1].split(':')[0])] = int(items[1].split(':')[1])
length, lPath = longestPath(weight, edges, source, sink)
length= str(length)
lPath = '->'.join(map(str,lPath))
print'\n'.join([length, lPath])
with open ('4_Longest_Path_DAG_Answer.txt', 'w') as outFile:
outFile.write('\n'.join([length,lPath]))<file_sep>"""
CODE CHALLENGE: Find the length of a longest path in the Manhattan Tourist Problem.
Input: Integers n and m, followed by an n multiply (m plus 1) matrix Down and an (n plus 1) multiply m matrix Right
The two matrices are separated by the symbol
Output: The length of a longest path from source (0, 0) to sink (n, m) in the n multiply m rectangular grid
whose edges are defined by the matrices Down and Right.
Sample Input:
4 4
1 0 2 4 3
4 6 5 2 1
4 4 5 2 1
5 6 8 5 3
-
3 2 4 0
3 2 4 2
0 7 3 3
3 3 0 2
1 3 2 2
Sample Output:
34
"""
def manhattan_tourist(n, m, downMatrix, rightMatrix):
#initialize matrix to 0
S = [[0]*(m+1) for i in xrange(n+1)]
print S
for i in xrange(1, n + 1):
S[i][0] = S[i-1][0] + downMatrix[i-1][0]
for j in xrange(1, m + 1):
S[0][j] = S[0][j-1] + rightMatrix[0][j-1]
for i in xrange(1, n+1):
for j in xrange(1, m+1):
S[i][j] = max(S[i-1][j] + downMatrix[i-1][j], S[i][j-1] + rightMatrix[i][j-1])
return S[n][m]
'''Input/Output'''
with open('2_Manhattan_Tourist.txt') as inputData:
n, m = map(int, inputData.readline().strip().split())
downMatrix, rightMatrix = [[map(int, row.split()) for row in matricies.split('\n')] for matricies in inputData.read().strip().split('\n-\n')]
inputData.close()
answer = str(manhattan_tourist(n, m, downMatrix, rightMatrix))
print answer
with open('2_Manhattan_Tourist_Answer.txt', 'w') as outputData:
outputData.write(answer)
'''
def manhattan_tourist(row, col, down, right):
_row = int(row) + 1
_col = int(col) + 1
mem = [[0]*_col for x in xrange(_row)]
for i in range(1, _col):
mem[0][i] = mem[0][i - 1] + right[0][i - 1]
for j in range(1, _row):
mem[j][0] = mem[j - 1][0] + down[j - 1][0]
for i in range(1, _row):
for j in range(1, _col):
ij_down = mem[i-1][j] + down[i-1][j]
ij_right = mem[i][j-1] + right[i][j-1]
mem[i][j] = max(ij_down , ij_right)
return mem[row][col]
def main():
f = open('input.txt', 'r')
n = int(f.readline().strip())
m = int(f.readline().strip())
down = []
for line in f:
line = line.strip()
if line == "-":
break
down.append( map(int, line.split(" ")) )
right = []
for line in f:
right.append( map(int, line.strip().split(" ")) )
f.close()
sol = week6.manhattan_tourist(n, m, down, right)
g = open('output.txt', 'w')
g.write(str(sol) + '\n')
g.close()
if __name__ == '__main__':
main()
'''<file_sep>'''
CODE CHALLENGE: Use OUTPUTLCS (reproduced below) to solve the Longest Common Subsequence Problem.
Input: Two strings s and t.
Output: A longest common subsequence of s and t. (Note: more than one solution may exist,
in which case you may output any one.)
OUTPUTLCS(backtrack, v, i, j)
if i equals 0 or j equals 0
return
if backtracki, j equals"backward"
OUTPUTLCS(backtrack, v, i minus 1, j)
else if backtracki, j equals "forward"
OUTPUTLCS(backtrack, v, i, j minus 1)
else
OUTPUTLCS(backtrack, v, i minus 1, j minus 1)
output vi
Sample Input:
AACCTTGG
ACACTGTGA
Sample Output:
AACTGG
'''
def longestCommonSubsequence(seq1, seq2):
'''Return a longest common subsequence of the input strings'''
lenSeq1 = len(seq1)
lenSeq2 = len(seq2)
S = [[0]*(lenSeq2+1) for k in xrange(lenSeq1 + 1)]
for i in xrange(lenSeq1):
for j in xrange(lenSeq2):
if seq1[i] == seq2[j]:
S[i+1][j+1] = S[i][j]+1
else:
S[i+1][j+1] = max(S[i+1][j], S[i][j+1])
longestSubSeq = ''
a = len(seq1)
b = len(seq2)
while a*b != 0:
if S[a][b] == S[a-1][b]:
a -= 1
elif S[a][b] == S[a][b - 1]:
b -= 1
else:
longestSubSeq = seq1[a-1] + longestSubSeq
a -= 1
b -= 1
return longestSubSeq
'''Input/Output'''
with open('3_Longest_Common_Subsequence.txt') as inputData:
seq1, seq2 = [line.strip() for line in inputData.readlines()]
inputData.close()
answer = longestCommonSubsequence(seq1, seq2)
print answer
with open('3_Longest_Common_Subsequence_Answer.txt', 'w') as outputData:
outputData.write(answer)<file_sep>"""
Local Alignment Problem
Find the highest-scoring local alignment between two strings.
Given: Two protein strings.
Return: The maximum score of a local alignment of the strings, followed by a
local alignment of these strings achieving the maximum score.
https://github.com/ngaude/sandbox/blob/f009d5a50260ce26a69cd7b354f6d37b48937ee5/bioinformatics-002/bioinformatics_chapter5.py
https://github.com/ahmdeen/Bioinformatic-Algorthims/blob/7cae61bb45535911f220da290f9ecf609b964058/Ros5F_LocalAlignment.py
"""
import os
'''Classes'''
class pam250(object):
'''Class to score proteins using the PAM250 matrix'''
def __init__(self):
'''Initalize BLOSUM62 Matrix'''
with open(os.path.join(os.path.dirname(__file__), 'PAM250.txt')) as inFile:
lines = [line.strip().split() for line in inFile.readlines()]
self.S = {(item[0], item[1]): int(item[2]) for item in lines}
def __getitem__(self, pair):
'''Returns the score of a given pair'''
return self.S[pair[0],pair[1]]
'''Functions'''
def localAlignment(seq1, seq2, ScoreMatrix, sig):
'''Returns the best local Alignment of the input sequences, given a scoring matric and the indel penalty sigma'''
len1, len2 = len(seq1), len(seq2)
S = [[0 for j in xrange(len2+1)] for i in xrange(len1+1)]
backtrack = [[0 for j in xrange(len2+1)] for i in xrange(len1+1)]
maxScore = -1
aMax, bMax = 0, 0
for i in xrange(1, len1 +1):
for j in xrange(1, len2+1):
scoreList = [S[i-1][j] - sig, S[i][j-1] - sig, S[i-1][j-1] + ScoreMatrix[seq1[i-1], seq2[j-1]], 0]
S[i][j] = max(scoreList)
backtrack[i][j] = scoreList.index(S[i][j])
if S[i][j] > maxScore:
maxScore = S[i][j]
aMax, bMax = i, j
#------
insertIndelFcn = lambda seq, i: seq[:i] + '-' + seq[i:]
#------
a, b = aMax, bMax
align1, align2 = seq1[:a], seq2[:b]
while backtrack[a][b] != 3 and a*b != 0:
if backtrack[a][b] == 0:
a -= 1
align2 = insertIndelFcn(align2, b)
elif backtrack[a][b] == 1:
b -= 1
align1 = insertIndelFcn(align1, a)
elif backtrack[a][b] == 2:
a -= 1
b -= 1
align1 = align1[a:]
align2 = align2[b:]
return str(maxScore), align1, align2
'''Input/Output'''
with open('6_Local_Alignment_Problem.txt') as infile:
seq1, seq2 = [line.strip() for line in infile.readlines()]
indelPenalty = 5
alignment = localAlignment(seq1, seq2, pam250(), indelPenalty)
answer = '\n'.join(alignment)
print answer
with open('6_Local_Alignment_Problem_Answer.txt', 'w') as outfile:
outfile.write(answer)
<file_sep>'''
CODE CHALLENGE: Solve the Suffix Tree Construction Problem.
Input: A string Text.
Output: The edge labels of SuffixTree(Text). You may return these strings in any order.
Extra Dataset
Sample Input:
ATAAATG$
Sample Output:
AAATG$
G$
T
ATG$
TG$
A
A
AAATG$
G$
T
G$
$
''' | e920a03db06924865cd3d36e13fcbbdf4c0ee5ce | [
"Markdown",
"Python"
] | 12 | Markdown | hailtedhorch/Comparing-Genes-Proteins-and-Genomes-Bioinformatics-III- | fa39c80beacc6d5111d754e8f84e721560febffa | c6a4b96d8c8c31047e2fa31ef5fc34dfc570f509 |
refs/heads/master | <file_sep>using System.ComponentModel.DataAnnotations;
namespace ElectricCo.ViewModels.Project
{
public class CreateViewModel
{
[Required]
[DataType(DataType.Text)]
[StringLength(50, ErrorMessage = "Cannot be longer than 50 characters or shorter than 2.", MinimumLength = 2)]
[Display(Name = "Project")]
public string Designation { get; set; }
[DataType(DataType.MultilineText)]
[Display(ShortName = "Desc.")]
public string Description { get; set; }
[Display(Name = "Purchase Order", ShortName = "PO")]
public string PurchaseOrder { get; set; }
[DataType(DataType.Text)]
[StringLength(100, ErrorMessage = "Cannot be longer than 100 characters.")]
public string Address { get; set; }
[DataType(DataType.Text)]
[StringLength(50, ErrorMessage = "Cannot be longer than 50 characters.")]
public string City { get; set; }
[DataType(DataType.Text)]
[StringLength(2, ErrorMessage = "Cannot be longer than 2 characters.")]
public string State { get; set; }
[DataType(DataType.PostalCode)]
[RegularExpression(@"^\d{5}$", ErrorMessage = "Please enter a 5 digit code.")]
[Display(Name = "Postal Code", ShortName = "Zip", Prompt = "Enter postal code")]
public int? PostalCode { get; set; }
}
}
<file_sep>using System.Collections.Generic;
namespace ElectricCo.ViewModels.Admin
{
public class UserIndexViewModel
{
public string Id { get; set; }
public string Email { get; set; }
public IList<string> Roles { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ElectricCo.ViewModels.Project
{
public class DetailsViewModel
{
public Guid ProjectId { get; set; }
public string Project { get; set; }
[DisplayFormat(NullDisplayText = "-")]
public string Description { get; set; }
[Display(Name = "Purchase Order", ShortName = "PO")]
[DisplayFormat(NullDisplayText = "-")]
public string PurchaseOrder { get; set; }
[DisplayFormat(NullDisplayText = "-")]
public string Address { get; set; }
[DisplayFormat(NullDisplayText = "-")]
public string City { get; set; }
[DisplayFormat(NullDisplayText = "-")]
public string State { get; set; }
[Display(Name = "Postal Code", ShortName = "Zip")]
[DisplayFormat(NullDisplayText = "-")]
public int? PostalCode { get; set; }
public int BuildingCount { get; set; }
public int AreaCount { get; set; }
public IList<BuildingStatus> BuildingsStatus { get; set; }
}
public class BuildingStatus
{
public Guid BuildingId { get; set; }
public string Building { get; set; }
public int AreaCount { get; set; }
public IDictionary<string, double> Statuses { get; set; }
}
}
<file_sep>using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using System;
namespace ElectricCo.Models
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Area> Areas { get; set; }
public DbSet<AreaMaterial> AreaMaterials { get; set; }
public DbSet<Building> Buildings { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<Document> Documents { get; set; }
public DbSet<Material> Materials { get; set; }
public DbSet<Model> Models { get; set; }
public DbSet<ModelMaterial> ModelMaterials { get; set; }
public DbSet<Project> Projects { get; set; }
public DbSet<Status> Statuses { get; set; }
public DbSet<UnitOfMeasure> UnitsOfMeasure { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<AreaMaterial>().HasKey(k => new { k.AreaId, k.MaterialId });
builder.Entity<ModelMaterial>().HasKey(k => new { k.ModelId, k.MaterialId });
builder.Entity<AreaDocument>().HasKey(k => new { k.AreaId, k.DocumentId });
builder.Entity<BuildingDocument>().HasKey(k => new { k.BuildingId, k.DocumentId });
builder.Entity<ModelDocument>().HasKey(k => new { k.ModelId, k.DocumentId });
builder.Entity<ProjectDocument>().HasKey(k => new { k.ProjectId, k.DocumentId });
builder.Entity<ProjectContact>().HasKey(k => new { k.ProjectId, k.ContactId });
}
public DbSet<ApplicationUser> ApplicationUser { get; set; }
public DbSet<ApplicationRole> ApplicationRole { get; set; }
}
//public static class InitialData
//{
// public static void Initialize()
// {
// var adminRole = "canAdminister";
// roleManager.CreateAsync(new ApplicationRole { Name = adminRole });
// var adminUser = new ApplicationUser { UserName = "joshuadlehr<EMAIL>", Email = "<EMAIL>" };
// userManager.CreateAsync(adminUser, "<PASSWORD>");
// }
//}
}
<file_sep>using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
namespace ElectricCo.Migrations
{
public partial class AddManyToManys : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_Area_Building_BuildingId", table: "Area");
migrationBuilder.DropForeignKey(name: "FK_Area_Status_StatusId", table: "Area");
migrationBuilder.DropForeignKey(name: "FK_AreaMaterial_Area_AreaId", table: "AreaMaterial");
migrationBuilder.DropForeignKey(name: "FK_AreaMaterial_Material_MaterialId", table: "AreaMaterial");
migrationBuilder.DropForeignKey(name: "FK_Building_Project_ProjectId", table: "Building");
migrationBuilder.DropForeignKey(name: "FK_Contact_Project_ProjectProjectId", table: "Contact");
migrationBuilder.DropForeignKey(name: "FK_Material_UnitOfMeasure_UnitOfMeasureId", table: "Material");
migrationBuilder.DropForeignKey(name: "FK_Model_Project_ProjectId", table: "Model");
migrationBuilder.DropForeignKey(name: "FK_ModelMaterial_Material_MaterialId", table: "ModelMaterial");
migrationBuilder.DropForeignKey(name: "FK_ModelMaterial_Model_ModelId", table: "ModelMaterial");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropColumn(name: "ProjectProjectId", table: "Contact");
migrationBuilder.CreateTable(
name: "Document",
columns: table => new
{
DocumentId = table.Column<Guid>(nullable: false),
Description = table.Column<string>(nullable: true),
Designation = table.Column<string>(nullable: false),
FileLink = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Document", x => x.DocumentId);
});
migrationBuilder.CreateTable(
name: "ProjectContact",
columns: table => new
{
ProjectId = table.Column<Guid>(nullable: false),
ContactId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ProjectContact", x => new { x.ProjectId, x.ContactId });
table.ForeignKey(
name: "FK_ProjectContact_Contact_ContactId",
column: x => x.ContactId,
principalTable: "Contact",
principalColumn: "ContactId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ProjectContact_Project_ProjectId",
column: x => x.ProjectId,
principalTable: "Project",
principalColumn: "ProjectId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AreaDocument",
columns: table => new
{
AreaId = table.Column<Guid>(nullable: false),
DocumentId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AreaDocument", x => new { x.AreaId, x.DocumentId });
table.ForeignKey(
name: "FK_AreaDocument_Area_AreaId",
column: x => x.AreaId,
principalTable: "Area",
principalColumn: "AreaId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AreaDocument_Document_DocumentId",
column: x => x.DocumentId,
principalTable: "Document",
principalColumn: "DocumentId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BuildingDocument",
columns: table => new
{
BuildingId = table.Column<Guid>(nullable: false),
DocumentId = table.Column<Guid>(nullable: false),
BuildingBuildingId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_BuildingDocument", x => new { x.BuildingId, x.DocumentId });
table.ForeignKey(
name: "FK_BuildingDocument_Building_BuildingBuildingId",
column: x => x.BuildingBuildingId,
principalTable: "Building",
principalColumn: "BuildingId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_BuildingDocument_Area_BuildingId",
column: x => x.BuildingId,
principalTable: "Area",
principalColumn: "AreaId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_BuildingDocument_Document_DocumentId",
column: x => x.DocumentId,
principalTable: "Document",
principalColumn: "DocumentId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ModelDocument",
columns: table => new
{
ModelId = table.Column<Guid>(nullable: false),
DocumentId = table.Column<Guid>(nullable: false),
ModelModelId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ModelDocument", x => new { x.ModelId, x.DocumentId });
table.ForeignKey(
name: "FK_ModelDocument_Document_DocumentId",
column: x => x.DocumentId,
principalTable: "Document",
principalColumn: "DocumentId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ModelDocument_Area_ModelId",
column: x => x.ModelId,
principalTable: "Area",
principalColumn: "AreaId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ModelDocument_Model_ModelModelId",
column: x => x.ModelModelId,
principalTable: "Model",
principalColumn: "ModelId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "ProjectDocument",
columns: table => new
{
ProjectId = table.Column<Guid>(nullable: false),
DocumentId = table.Column<Guid>(nullable: false),
ProjectProjectId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ProjectDocument", x => new { x.ProjectId, x.DocumentId });
table.ForeignKey(
name: "FK_ProjectDocument_Document_DocumentId",
column: x => x.DocumentId,
principalTable: "Document",
principalColumn: "DocumentId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ProjectDocument_Area_ProjectId",
column: x => x.ProjectId,
principalTable: "Area",
principalColumn: "AreaId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ProjectDocument_Project_ProjectProjectId",
column: x => x.ProjectProjectId,
principalTable: "Project",
principalColumn: "ProjectId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.AddColumn<Guid>(
name: "UnitOfMeasureUnitOfMeasureId",
table: "ModelMaterial",
nullable: true);
migrationBuilder.AddColumn<Guid>(
name: "UnitOfMeasureUnitOfMeasureId",
table: "AreaMaterial",
nullable: true);
migrationBuilder.AddForeignKey(
name: "FK_Area_Building_BuildingId",
table: "Area",
column: "BuildingId",
principalTable: "Building",
principalColumn: "BuildingId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Area_Status_StatusId",
table: "Area",
column: "StatusId",
principalTable: "Status",
principalColumn: "StatusId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AreaMaterial_Area_AreaId",
table: "AreaMaterial",
column: "AreaId",
principalTable: "Area",
principalColumn: "AreaId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AreaMaterial_Material_MaterialId",
table: "AreaMaterial",
column: "MaterialId",
principalTable: "Material",
principalColumn: "MaterialId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AreaMaterial_UnitOfMeasure_UnitOfMeasureUnitOfMeasureId",
table: "AreaMaterial",
column: "UnitOfMeasureUnitOfMeasureId",
principalTable: "UnitOfMeasure",
principalColumn: "UnitOfMeasureId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Building_Project_ProjectId",
table: "Building",
column: "ProjectId",
principalTable: "Project",
principalColumn: "ProjectId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Material_UnitOfMeasure_UnitOfMeasureId",
table: "Material",
column: "UnitOfMeasureId",
principalTable: "UnitOfMeasure",
principalColumn: "UnitOfMeasureId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Model_Project_ProjectId",
table: "Model",
column: "ProjectId",
principalTable: "Project",
principalColumn: "ProjectId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ModelMaterial_Material_MaterialId",
table: "ModelMaterial",
column: "MaterialId",
principalTable: "Material",
principalColumn: "MaterialId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ModelMaterial_Model_ModelId",
table: "ModelMaterial",
column: "ModelId",
principalTable: "Model",
principalColumn: "ModelId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ModelMaterial_UnitOfMeasure_UnitOfMeasureUnitOfMeasureId",
table: "ModelMaterial",
column: "UnitOfMeasureUnitOfMeasureId",
principalTable: "UnitOfMeasure",
principalColumn: "UnitOfMeasureId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_Area_Building_BuildingId", table: "Area");
migrationBuilder.DropForeignKey(name: "FK_Area_Status_StatusId", table: "Area");
migrationBuilder.DropForeignKey(name: "FK_AreaMaterial_Area_AreaId", table: "AreaMaterial");
migrationBuilder.DropForeignKey(name: "FK_AreaMaterial_Material_MaterialId", table: "AreaMaterial");
migrationBuilder.DropForeignKey(name: "FK_AreaMaterial_UnitOfMeasure_UnitOfMeasureUnitOfMeasureId", table: "AreaMaterial");
migrationBuilder.DropForeignKey(name: "FK_Building_Project_ProjectId", table: "Building");
migrationBuilder.DropForeignKey(name: "FK_Material_UnitOfMeasure_UnitOfMeasureId", table: "Material");
migrationBuilder.DropForeignKey(name: "FK_Model_Project_ProjectId", table: "Model");
migrationBuilder.DropForeignKey(name: "FK_ModelMaterial_Material_MaterialId", table: "ModelMaterial");
migrationBuilder.DropForeignKey(name: "FK_ModelMaterial_Model_ModelId", table: "ModelMaterial");
migrationBuilder.DropForeignKey(name: "FK_ModelMaterial_UnitOfMeasure_UnitOfMeasureUnitOfMeasureId", table: "ModelMaterial");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropColumn(name: "UnitOfMeasureUnitOfMeasureId", table: "ModelMaterial");
migrationBuilder.DropColumn(name: "UnitOfMeasureUnitOfMeasureId", table: "AreaMaterial");
migrationBuilder.DropTable("AreaDocument");
migrationBuilder.DropTable("BuildingDocument");
migrationBuilder.DropTable("ModelDocument");
migrationBuilder.DropTable("ProjectContact");
migrationBuilder.DropTable("ProjectDocument");
migrationBuilder.DropTable("Document");
migrationBuilder.AddColumn<Guid>(
name: "ProjectProjectId",
table: "Contact",
nullable: true);
migrationBuilder.AddForeignKey(
name: "FK_Area_Building_BuildingId",
table: "Area",
column: "BuildingId",
principalTable: "Building",
principalColumn: "BuildingId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Area_Status_StatusId",
table: "Area",
column: "StatusId",
principalTable: "Status",
principalColumn: "StatusId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AreaMaterial_Area_AreaId",
table: "AreaMaterial",
column: "AreaId",
principalTable: "Area",
principalColumn: "AreaId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AreaMaterial_Material_MaterialId",
table: "AreaMaterial",
column: "MaterialId",
principalTable: "Material",
principalColumn: "MaterialId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Building_Project_ProjectId",
table: "Building",
column: "ProjectId",
principalTable: "Project",
principalColumn: "ProjectId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Contact_Project_ProjectProjectId",
table: "Contact",
column: "ProjectProjectId",
principalTable: "Project",
principalColumn: "ProjectId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Material_UnitOfMeasure_UnitOfMeasureId",
table: "Material",
column: "UnitOfMeasureId",
principalTable: "UnitOfMeasure",
principalColumn: "UnitOfMeasureId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Model_Project_ProjectId",
table: "Model",
column: "ProjectId",
principalTable: "Project",
principalColumn: "ProjectId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ModelMaterial_Material_MaterialId",
table: "ModelMaterial",
column: "MaterialId",
principalTable: "Material",
principalColumn: "MaterialId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ModelMaterial_Model_ModelId",
table: "ModelMaterial",
column: "ModelId",
principalTable: "Model",
principalColumn: "ModelId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace ElectricCo.ViewModels.Project
{
public class StatusViewModel
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ElectricCo.Models
{
public class Project
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ProjectId { get; set; }
[Required]
[StringLength(50)]
public string Designation { get; set; }
[Required]
[StringLength(20)]
public string JobCode { get; set; }
public string Description { get; set; }
[StringLength(100)]
public string Address { get; set; }
[StringLength(50)]
public string City { get; set; }
[StringLength(2)]
public string State { get; set; }
public int? PostalCode { get; set; }
[StringLength(450)]
public string UserId { get; set; }
public virtual ICollection<Building> Buildings { get; set; }
public virtual ICollection<Model> Models { get; set; }
public virtual ICollection<ProjectContact> ProjectContacts { get; set; }
public virtual ICollection<ProjectDocument> ProjectDocuments { get; set; }
public virtual ApplicationUser User { get; set; }
}
}
<file_sep>using ElectricCo.Models;
using System.Collections.Generic;
namespace ElectricCo.ViewModels.Manage
{
public class UserIndex
{
public string UserId { get; set; }
public string Email { get; set; }
public ICollection<ApplicationRole> Roles { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
namespace ElectricCo.ViewModels.Contact
{
public class IndexViewModel
{
public ICollection<ContactIndexItem> Contacts { get; set; } = new Collection<ContactIndexItem>();
}
public class ContactIndexItem
{
public Guid ContactId { get; set; }
public string FullName { get; set; }
[DisplayFormat(NullDisplayText = "-")]
public string Company { get; set; }
[DisplayFormat(NullDisplayText = "-")]
public string Title { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace ElectricCo.ViewModels.Project
{
public class IndexViewModel
{
public ICollection<ProjectIndexItem> Projects { get; set; }
}
public class ProjectIndexItem
{
public Guid ProjectId { get; set; }
public string Project { get; set; }
}
}
<file_sep>using System;
using System.ComponentModel.DataAnnotations;
namespace ElectricCo.ViewModels.Contact
{
public class DetailsViewModel
{
public Guid ContactId { get; set; }
[Display(Name = "Name")]
public string FullName { get; set; }
[DisplayFormat(NullDisplayText = "-")]
public string Company { get; set; }
[DisplayFormat(NullDisplayText = "-")]
public string Title { get; set; }
[DisplayFormat(NullDisplayText = "-")]
public string Trade { get; set; }
[DataType(DataType.PhoneNumber)]
[DisplayFormat(NullDisplayText = "-")]
public string Phone { get; set; }
[DataType(DataType.EmailAddress)]
[DisplayFormat(NullDisplayText = "-")]
public string Email { get; set; }
[DataType(DataType.Url)]
[DisplayFormat(NullDisplayText = "-")]
public string Chat { get; set; }
[DataType(DataType.Url)]
[DisplayFormat(NullDisplayText = "-")]
public string Website { get; set; }
public string UserId { get; set; }
}
}
<file_sep>using ElectricCo.Models;
using ElectricCo.ViewModels.Contact;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ElectricCo.Controllers
{
[Authorize(Roles = "canAdminister, isEmployee")]
public class ContactsController : Controller
{
[FromServices]
public ApplicationDbContext context { get; set; }
[FromServices]
public ILogger<ApplicationDbContext> logger { get; set; }
// GET: Contacts
[HttpGet]
public async Task<IActionResult> Index()
{
var data = context.Contacts;
if (await data.CountAsync() > 0)
{
var model = new IndexViewModel ();
foreach (var item in data)
{
model.Contacts.Add(new ContactIndexItem { ContactId = item.ContactId, FullName = item.FirstName + " " + item.LastName, Company = item.Company, Title = item.Title });
}
return View(model);
}
return RedirectToAction(nameof(ContactsController.Create));
}
// GET: Contacts/Details/(ContactId)
[HttpGet]
public async Task<IActionResult> Details(Guid? id, string userid = "" )
{
Contact data;
if (id != null)
{
data = await context.Contacts.SingleAsync(m => m.ContactId == id);
}
else if (!string.IsNullOrEmpty(userid))
{
data = await context.Contacts.SingleAsync(m => m.UserId == userid);
}
else
{
logger.LogInformation("Details: Contact {0} not found", id);
return HttpNotFound();
}
if (data != null)
{
return View(new DetailsViewModel
{
ContactId = data.ContactId,
FullName = data.FirstName + " " + data.LastName,
Company = data.Company,
Title = data.Title,
Trade = data.Trade,
Phone = data.Phone,
Email = data.Email,
Chat = data.Chat,
Website = data.Website,
UserId = data.UserId
});
}
return RedirectToAction(nameof(ContactsController.Create), new { userid = userid });
}
// GET: Contacts/Create
[HttpGet]
public IActionResult Create()
{
var data = new CreateViewModel
{
Users = GetUsersListItems()
};
return View(data);
}
[HttpPost]
public IEnumerable<SelectListItem> GetUsersListItems(string userId = "")
{
var tmp = context.Users.ToList();
return tmp.OrderBy(u => u.Email).Select(u => new SelectListItem
{
Text = u.Email,
Value = u.Id.ToString(),
Selected = String.IsNullOrEmpty(userId) ? false : true
});
}
// POST: Contacts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CreateViewModel model)
{
try
{
if (ModelState.IsValid)
{
var contact = new Contact {
ContactId = Guid.Empty,
FirstName = model.FirstName,
LastName = model.LastName,
Company = model.Company,
Title = model.Title,
Trade = model.Trade,
Phone = model.Phone,
Email = model.Email,
Chat = model.Chat,
Website = model.Website,
UserId = model.UserId
};
context.Contacts.Add(contact);
await context.SaveChangesAsync();
return RedirectToAction(nameof(ContactsController.Details), new { id = contact.ContactId });
}
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(model);
}
// GET: Contacts/Edit/(ContactId)
[HttpGet]
public async Task<IActionResult> Edit(Guid? id)
{
if (id == null)
{
return HttpBadRequest();
}
var data = await context.Contacts.SingleAsync(m => m.ContactId == id);
if (data == null)
{
logger.LogInformation("Edit: Contact {0} not found", id);
return HttpNotFound();
}
return View(new EditViewModel
{
ContactId = data.ContactId,
FirstName = data.FirstName,
LastName = data.LastName,
Company = data.Company,
Title = data.Title,
Trade = data.Trade,
Phone = data.Phone,
Email = data.Email,
Chat = data.Chat,
Website = data.Website,
UserId = data.UserId,
Users = GetUsersListItems(data.UserId)
});
}
// POST: Contacts/Edit/(ContactId)
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(EditViewModel model)
{
try
{
if (ModelState.IsValid)
{
context.Update(new Contact {
ContactId = model.ContactId,
FirstName = model.FirstName,
LastName = model.LastName,
Company = model.Company,
Title = model.Title,
Trade = model.Trade,
Phone = model.Phone,
Email = model.Email,
Chat = model.Chat,
Website = model.Website,
UserId = model.UserId
});
await context.SaveChangesAsync();
return RedirectToAction(nameof(ContactsController.Details), new { id = model.ContactId });
}
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(model);
}
// POST: Contacts/Delete/5
[HttpPost, ActionName("Delete")]
[Authorize(Roles = "canAdminister")]
public async Task<IActionResult> DeleteConfirmed(Guid id)
{
try
{
var data = await context.Contacts.SingleAsync(m => m.ContactId == id);
context.Contacts.Remove(data);
await context.SaveChangesAsync();
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Unable to delete contact. Try again, and if the problem persists see your system administrator.");
}
return RedirectToAction(nameof(ContactsController.Details), new { id = id });
}
}
}
<file_sep>using Microsoft.AspNet.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ElectricCo.ViewModels.Contact
{
public class CreateViewModel
{
public Guid ContactId { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "<NAME>")]
[StringLength(50, ErrorMessage = "Cannot be longer than 50 characters.")]
public string FirstName { get; set; }
[DataType(DataType.Text)]
[Display(Name = "<NAME>")]
[StringLength(50, ErrorMessage = "Cannot be longer than 50 characters.")]
public string LastName { get; set; }
[DataType(DataType.Text)]
[StringLength(50, ErrorMessage = "Cannot be longer than 50 characters.")]
public string Company { get; set; }
[DataType(DataType.Text)]
[StringLength(50, ErrorMessage = "Cannot be longer than 50 characters.")]
public string Title { get; set; }
[DataType(DataType.Text)]
[StringLength(50, ErrorMessage = "Cannot be longer than 50 characters.")]
public string Trade { get; set; }
[Phone()]
[DataType(DataType.PhoneNumber, ErrorMessage = "Please enter a valid phone number.")]
[StringLength(10, ErrorMessage = "Must be 10 digits.", MinimumLength = 10)]
public string Phone { get; set; }
[EmailAddress()]
[DataType(DataType.EmailAddress, ErrorMessage = "Please enter a valid email.")]
[StringLength(100, ErrorMessage = "Cannot be longer than 100 characters.")]
public string Email { get; set; }
[Url()]
[DataType(DataType.Url, ErrorMessage = "Please enter a vailid link address.")]
[StringLength(100, ErrorMessage = "Cannot be longer than 100 characters.")]
public string Chat { get; set; }
[Url()]
[DataType(DataType.Url, ErrorMessage = "Please enter a vailid web address.")]
[StringLength(100, ErrorMessage = "Cannot be longer than 100 characters.")]
public string Website { get; set; }
[StringLength(450)]
[Display(Name = "User Email")]
public string UserId { get; set; }
public IEnumerable<SelectListItem> Users { get; set; }
}
}
<file_sep>using System;
namespace ElectricCo.ViewModels.Contact
{
public class DeleteViewModel
{
public Guid ContactId { get; set; }
public string FullName { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
namespace ElectricCo.Migrations
{
public partial class AddInitialModels : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.CreateTable(
name: "Project",
columns: table => new
{
ProjectId = table.Column<Guid>(nullable: false),
Address = table.Column<string>(nullable: true),
City = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true),
Designation = table.Column<string>(nullable: false),
JobCode = table.Column<string>(nullable: false),
PostalCode = table.Column<int>(nullable: true),
State = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Project", x => x.ProjectId);
table.ForeignKey(
name: "FK_Project_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Status",
columns: table => new
{
StatusId = table.Column<Guid>(nullable: false),
Designation = table.Column<string>(nullable: false),
ListOrder = table.Column<short>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Status", x => x.StatusId);
});
migrationBuilder.CreateTable(
name: "UnitOfMeasure",
columns: table => new
{
UnitOfMeasureId = table.Column<Guid>(nullable: false),
Designation = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UnitOfMeasure", x => x.UnitOfMeasureId);
});
migrationBuilder.CreateTable(
name: "Building",
columns: table => new
{
BuildingId = table.Column<Guid>(nullable: false),
Address = table.Column<string>(nullable: true),
City = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true),
Designation = table.Column<string>(nullable: false),
PostalCode = table.Column<int>(nullable: true),
ProjectId = table.Column<Guid>(nullable: false),
State = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Building", x => x.BuildingId);
table.ForeignKey(
name: "FK_Building_Project_ProjectId",
column: x => x.ProjectId,
principalTable: "Project",
principalColumn: "ProjectId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Contact",
columns: table => new
{
ContactId = table.Column<Guid>(nullable: false),
Chat = table.Column<string>(nullable: true),
Company = table.Column<string>(nullable: true),
Email = table.Column<string>(nullable: true),
FirstName = table.Column<string>(nullable: true),
LastName = table.Column<string>(nullable: true),
Phone = table.Column<string>(nullable: true),
ProjectProjectId = table.Column<Guid>(nullable: true),
Title = table.Column<string>(nullable: true),
Trade = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: true),
Website = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Contact", x => x.ContactId);
table.ForeignKey(
name: "FK_Contact_Project_ProjectProjectId",
column: x => x.ProjectProjectId,
principalTable: "Project",
principalColumn: "ProjectId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Contact_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Model",
columns: table => new
{
ModelId = table.Column<Guid>(nullable: false),
Description = table.Column<string>(nullable: true),
Designation = table.Column<string>(nullable: false),
ProjectId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Model", x => x.ModelId);
table.ForeignKey(
name: "FK_Model_Project_ProjectId",
column: x => x.ProjectId,
principalTable: "Project",
principalColumn: "ProjectId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Material",
columns: table => new
{
MaterialId = table.Column<Guid>(nullable: false),
Barcode = table.Column<int>(nullable: true),
Description = table.Column<string>(nullable: false),
Designation = table.Column<string>(nullable: false),
ImagePath = table.Column<string>(nullable: true),
UnitOfMeasureId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Material", x => x.MaterialId);
table.ForeignKey(
name: "FK_Material_UnitOfMeasure_UnitOfMeasureId",
column: x => x.UnitOfMeasureId,
principalTable: "UnitOfMeasure",
principalColumn: "UnitOfMeasureId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Area",
columns: table => new
{
AreaId = table.Column<Guid>(nullable: false),
Address = table.Column<string>(nullable: true),
BuildingId = table.Column<Guid>(nullable: false),
City = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true),
Designation = table.Column<string>(nullable: false),
ModelId = table.Column<Guid>(nullable: true),
PostalCode = table.Column<int>(nullable: true),
State = table.Column<string>(nullable: true),
StatusChanged = table.Column<DateTime>(nullable: false),
StatusId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Area", x => x.AreaId);
table.ForeignKey(
name: "FK_Area_Building_BuildingId",
column: x => x.BuildingId,
principalTable: "Building",
principalColumn: "BuildingId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Area_Model_ModelId",
column: x => x.ModelId,
principalTable: "Model",
principalColumn: "ModelId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Area_Status_StatusId",
column: x => x.StatusId,
principalTable: "Status",
principalColumn: "StatusId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ModelMaterial",
columns: table => new
{
ModelId = table.Column<Guid>(nullable: false),
MaterialId = table.Column<Guid>(nullable: false),
Quantity = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ModelMaterial", x => new { x.ModelId, x.MaterialId });
table.ForeignKey(
name: "FK_ModelMaterial_Material_MaterialId",
column: x => x.MaterialId,
principalTable: "Material",
principalColumn: "MaterialId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ModelMaterial_Model_ModelId",
column: x => x.ModelId,
principalTable: "Model",
principalColumn: "ModelId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AreaMaterial",
columns: table => new
{
AreaId = table.Column<Guid>(nullable: false),
MaterialId = table.Column<Guid>(nullable: false),
Quantity = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AreaMaterial", x => new { x.AreaId, x.MaterialId });
table.ForeignKey(
name: "FK_AreaMaterial_Area_AreaId",
column: x => x.AreaId,
principalTable: "Area",
principalColumn: "AreaId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AreaMaterial_Material_MaterialId",
column: x => x.MaterialId,
principalTable: "Material",
principalColumn: "MaterialId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.AlterColumn<string>(
name: "UserId",
table: "AspNetUserLogins",
nullable: false);
migrationBuilder.AlterColumn<string>(
name: "UserId",
table: "AspNetUserClaims",
nullable: false);
migrationBuilder.AlterColumn<string>(
name: "RoleId",
table: "AspNetRoleClaims",
nullable: false);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropTable("AreaMaterial");
migrationBuilder.DropTable("Contact");
migrationBuilder.DropTable("ModelMaterial");
migrationBuilder.DropTable("Area");
migrationBuilder.DropTable("Material");
migrationBuilder.DropTable("Building");
migrationBuilder.DropTable("Model");
migrationBuilder.DropTable("Status");
migrationBuilder.DropTable("UnitOfMeasure");
migrationBuilder.DropTable("Project");
migrationBuilder.AlterColumn<string>(
name: "UserId",
table: "AspNetUserLogins",
nullable: true);
migrationBuilder.AlterColumn<string>(
name: "UserId",
table: "AspNetUserClaims",
nullable: true);
migrationBuilder.AlterColumn<string>(
name: "RoleId",
table: "AspNetRoleClaims",
nullable: true);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
<file_sep>using System.Collections.Generic;
namespace ElectricCo.ViewModels.Admin
{
public class RoleCheckBox
{
public string Id { get; set; }
public bool IsChecked { get; set; }
public string Name { get; set; }
}
public class EditUserViewModel
{
public IList<RoleCheckBox> Roles { get; set; }
public string Id { get; set; }
public string Email { get; set; }
}
}
<file_sep>using ElectricCo.Models;
using ElectricCo.ViewModels.Admin;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace ElectricCo.Controllers
{
[Authorize(Roles = "canAdminister")]
public class AdminController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
public AdminController(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
// GET: Admin/UserIndex
[HttpGet]
public async Task<IActionResult> UserIndex()
{
var users = new List<UserIndexViewModel>();
foreach (var item in _userManager.Users)
{
users.Add(new UserIndexViewModel
{
Id = item.Id,
Email = item.Email,
Roles = await _userManager.GetRolesAsync(item)
});
}
return View(users);
}
// GET: Admin/UserEdit/(UserId)
[HttpGet]
public async Task<IActionResult> EditUser(string id)
{
var data = await _userManager.FindByIdAsync(id);
if (data == null)
{
return HttpNotFound();
}
var roles = new List<RoleCheckBox>();
foreach (var role in _roleManager.Roles)
{
roles.Add(new RoleCheckBox {
Id = role.Id,
IsChecked = await _userManager.IsInRoleAsync(data, role.Name),
Name = role.Name
});
}
return View(new EditUserViewModel {
Id = data.Id,
Email = data.Email,
Roles = roles
});
}
// POST: Admin/UserEdit/(UserId)
[HttpPost]
public async Task<IActionResult> EditUser(string id, EditUserViewModel model)
{
if (ModelState.IsValid)
{
var data = await _userManager.FindByIdAsync(id);
if (data == null)
{
return HttpNotFound();
}
var selectedRoles = new List<string>();
var unselectedRoles = new List<string>();
foreach (var role in _roleManager.Roles)
{
var checkbox = model.Roles.Single(c => c.Id == role.Id);
checkbox.Name = role.Name;
if (checkbox.IsChecked && !await _userManager.IsInRoleAsync(data, role.Name))
{
selectedRoles.Add(role.Name);
}
if (!checkbox.IsChecked && await _userManager.IsInRoleAsync(data, role.Name))
{
unselectedRoles.Add(role.Name);
}
}
await _userManager.AddToRolesAsync(data, selectedRoles);
await _userManager.RemoveFromRolesAsync(data, unselectedRoles);
var result1 = await _userManager.SetEmailAsync(data, model.Email);
var result2 = await _userManager.SetUserNameAsync(data, model.Email);
if (result1.Succeeded && result2.Succeeded)
{
return RedirectToAction(nameof(AdminController.UserIndex));
}
AddErrors(result1);
AddErrors(result2);
}
model.Roles.ToList();
return View(model);
}
// POST: Admin/DeleteUser/(UserId)
[HttpPost]
public async Task<IActionResult> DeleteUser(string id)
{
var data = await _userManager.FindByIdAsync(id);
if (data == null)
{
return HttpNotFound();
}
var result = await _userManager.DeleteAsync(data);
if (result.Succeeded)
{
return RedirectToAction(nameof(AdminController.UserIndex));
}
return HttpBadRequest();
}
// GET: Admin/RoleIndex
[HttpGet]
public IActionResult RoleIndex()
{
return View(_roleManager.Roles);
}
// Get: Admin/CreateRole
[HttpGet]
public IActionResult CreateRole()
{
return View();
}
// POST: Admin/CreateRole
[HttpPost]
public async Task<IActionResult> CreateRole(ApplicationRole model)
{
if (ModelState.IsValid)
{
var result = await _roleManager.CreateAsync(model);
if (result.Succeeded)
{
return RedirectToAction(nameof(AdminController.RoleIndex));
}
AddErrors(result);
}
return View(model);
}
// GET: Admin/EditRole/(RoleId)
[HttpGet]
public async Task<IActionResult> EditRole(string id)
{
var model = await _roleManager.FindByIdAsync(id);
if (model == null)
{
return HttpNotFound();
}
return View(model);
}
// POST: Admin/DeleteRole/(RoleId)
[HttpPost]
public async Task<IActionResult> DeleteRole(string id, ApplicationRole model)
{
if (ModelState.IsValid)
{
var data = await _roleManager.FindByIdAsync(id);
var result = await _roleManager.DeleteAsync(data);
if (result.Succeeded)
{
return RedirectToAction(nameof(AdminController.RoleIndex));
}
AddErrors(result);
}
return View(model);
}
// Helpers
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
}
}
| 842977f315961ddaaf08d1cee0787ef07965bcdf | [
"C#"
] | 17 | C# | joshualehr/ElectricCo | af18c3f4c92bfe5d43e877638fe28cb81db3089d | 61f988c2af0e85118ee8c0b5081cb24ad8248c35 |
refs/heads/master | <file_sep>using System;
using System.Configuration;
using System.Data.SqlClient;
namespace Videoclub
{
class Cliente
{
static String connectionString = ConfigurationManager.ConnectionStrings["ConexionVIDEOCLUB"].ConnectionString;
static SqlConnection conexion = new SqlConnection(connectionString);
static string cadena;
static SqlCommand comando;
static SqlDataReader registros;
private string nombre;
private string apellido;
private DateTime fechaNac;
private string username;
private string password;
private string email;
private long telephone;
public Cliente()
{
}
public Cliente(string nombre, string apellido, DateTime fechaNac, string username, string password, string email, long telephone)
{
this.nombre = nombre;
this.apellido = apellido;
this.fechaNac = fechaNac;
this.username = username;
this.password = <PASSWORD>;
this.email = email;
this.telephone = telephone;
}
public string GetNombre()
{
return nombre;
}
public string GetApellido()
{
return apellido;
}
public DateTime GetFechaNac()
{
return fechaNac;
}
public string GetUsername()
{
return username;
}
public string GetPassword()
{
return <PASSWORD>;
}
public string GetEmail()
{
return email;
}
public long GetTelephone()
{
return telephone;
}
public void SetNombre(string nombre)
{
this.nombre = nombre;
}
public void SetApellido(string apellido)
{
this.apellido = apellido;
}
public void SetFechaNac(DateTime fechaNac)
{
this.fechaNac = fechaNac;
}
public void SetUsername(string username)
{
this.username = username;
}
public void SetPassword(string password)
{
this.password = <PASSWORD>;
}
public void SetEmail(string email)
{
this.email = email;
}
public void SetTelephone(long telephone)
{
this.telephone = telephone;
}
public static void Register()
{
string email, password, username;
int numeric = 0;
bool numeros = false;
bool nombreUsuario = false;
bool correo = false;
Console.WriteLine("Bienvenido al registro de nuevo usuario. Por favor, introduce los siguientes datos: ");
Console.WriteLine("Nombre: ");
string nombre = Console.ReadLine();
Console.WriteLine("Apellido: ");
string apellido = Console.ReadLine();
Console.WriteLine("Día de nacimiento: ");
int diaNac = Int32.Parse(Console.ReadLine());
Console.WriteLine("Mes de nacimiento: ");
int mesNac = Int32.Parse(Console.ReadLine());
Console.WriteLine("Año de nacimiento: ");
int yearNac = Int32.Parse(Console.ReadLine());
DateTime fechaNac = new DateTime(yearNac, mesNac, diaNac);
do
{
Console.WriteLine("Nombre de usuario: ");
username = Console.ReadLine();
conexion.Open();
cadena = "SELECT NOMBRE_USUARIO FROM CLIENTE WHERE NOMBRE_USUARIO = '" + username + "'";
comando = new SqlCommand(cadena, conexion);
registros = comando.ExecuteReader();
if(registros.Read())
{
Console.WriteLine("Nombre de usuario en uso. Por favor, introduzca otro nombre de usuario. ");
nombreUsuario = false;
}
else
{
nombreUsuario = true;
}
conexion.Close();
} while (nombreUsuario==false);
do
{
Console.WriteLine("Contraseña: (La contraseña debe contener entre 6 y 8 carácteres y al menos un número.) ");
password = Console.ReadLine();
if (password.Length >= 6 && password.Length <= 8)
{
for (int i = 0; i < password.Length; i++)
{
if (char.IsDigit(password[i]))
{
numeric++;
if (numeric >= 1)
{
numeros = true;
}
}
}
}
} while (numeros == false);
do
{
Console.WriteLine("Email: ");
email = Console.ReadLine();
conexion.Open();
cadena = "SELECT EMAIL FROM CLIENTE WHERE EMAIL = '" + email + "'";
comando = new SqlCommand(cadena, conexion);
registros = comando.ExecuteReader();
if (registros.Read())
{
Console.WriteLine("Email ya registrado. Por favor, introduzca email válido. ");
correo = false;
}
else
{
correo = true;
}
conexion.Close();
} while (!correo || !email.Contains("@") && (!email.Contains(".com") || !email.Contains(".es") || !email.Contains(".net") || !email.Contains(".org")));
Console.WriteLine("Teléfono: ");
long telephone = Int32.Parse(Console.ReadLine());
Console.WriteLine("\n\nGracias por registrarse. A continuación podrá acceder al menu de usuarios.\n ");
//Esto es el objeto cliente
Cliente cliente = new Cliente(nombre, apellido, fechaNac, username, password, email, telephone);
cliente.Insert();
Submenu.LoginOptions(cliente);
}
public void Insert()
{
conexion.Open();
cadena = "INSERT INTO CLIENTE VALUES ('" + nombre + "','" + apellido + "','" + fechaNac + "','" + username + "','" + password + "','" + email + "','" + telephone + "')";
comando = new SqlCommand(cadena, conexion);
comando.ExecuteNonQuery();
conexion.Close();
}
public static void Login()
{
string username, password;
Console.WriteLine("Introduce el nombre de usuario: ");
username = Console.ReadLine();
Console.WriteLine("Introduce la contraseña: ");
password = Console.ReadLine();
conexion.Open();
cadena = "SELECT * FROM CLIENTE WHERE nombre_usuario LIKE '" + username + "' AND CONTRASENIA LIKE '" + password + "'";
comando = new SqlCommand(cadena, conexion);
registros = comando.ExecuteReader();
if (!registros.Read())
{
Console.WriteLine("Usuario o contraseña incorrectos. Por favor, introduzca una contraseña o nombre de usuario válidos. ");
}
else
{
Cliente cliente = new Cliente();
cliente.SetNombre(registros["NOMBRE"].ToString());
cliente.SetApellido(registros["APELLIDOS"].ToString());
cliente.SetFechaNac(DateTime.Parse(registros["FECHA_NACIMIENTO"].ToString()));
cliente.SetUsername(registros["NOMBRE_USUARIO"].ToString());
cliente.SetPassword(registros["<PASSWORD>"].ToString());
cliente.SetEmail(registros["EMAIL"].ToString());
cliente.SetTelephone(Int64.Parse(registros["TELEFONO"].ToString()));
Submenu.LoginOptions(cliente);
}
conexion.Close();
}
public int Edad()
{
int years;
DateTime bDate = fechaNac;
DateTime today = DateTime.Now;
TimeSpan dAlive = today - bDate;
return years = dAlive.Days / 365;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace Videoclub
{
class Program
{
static String connectionString = ConfigurationManager.ConnectionStrings["ConexionVIDEOCLUB"].ConnectionString;
static SqlConnection conexion = new SqlConnection(connectionString);
static string cadena;
static SqlCommand comando;
static SqlDataReader registros;
static void Main(string[] args)
{
Menu.FirstMenu();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;
namespace Videoclub
{
class Peliculas
{
static String connectionString = ConfigurationManager.ConnectionStrings["ConexionVIDEOCLUB"].ConnectionString;
static SqlConnection conexion = new SqlConnection(connectionString);
static string cadena;
static SqlCommand comando;
static SqlDataReader registros;
private int movieId;
private string titulo;
private string director;
private int publico;
private string sinopsis;
private string alquilada;
public Peliculas()
{
}
public Peliculas(int movieId,string titulo, string director, int publico, string sinopsis, string alquilada)
{
this.movieId = movieId;
this.titulo=titulo;
this.director = director;
this.publico = publico;
this.sinopsis = sinopsis;
this.alquilada = alquilada;
}
public int GetmovieId()
{
return movieId;
}
public string GetTitulo()
{
return titulo;
}
public string GerDirector()
{
return director;
}
public int GetPublico()
{
return publico;
}
public string GetSinopsis()
{
return sinopsis;
}
public string GetAlquilada()
{
return alquilada;
}
public void SetMovieId(int movieId)
{
this.movieId = movieId;
}
public void SetTitulo(string titulo)
{
this.titulo = titulo;
}
public void SetDirector(string director)
{
this.director = director;
}
public void SetPublico(int publico)
{
this.publico = publico;
}
public void SetSinopsis(string sinopsis)
{
this.sinopsis = sinopsis;
}
public void SetAlquilada(string alquilada)
{
this.alquilada=alquilada;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace Videoclub
{
class Submenu
{
static String connectionString = ConfigurationManager.ConnectionStrings["ConexionVIDEOCLUB"].ConnectionString;
static SqlConnection conexion = new SqlConnection(connectionString);
static string cadena;
static SqlCommand comando;
static SqlDataReader registros;
public static void LoginOptions(Cliente cliente)
{
conexion.Close();
int option;
cliente.Edad();
const int CATALOG = 1, RENT = 2, MYRENTINGS = 3, LOGOUT = 4;
do
{
Console.WriteLine();
Console.WriteLine("Bienvenido " + cliente.GetUsername());
Console.WriteLine("¿Qué desea hacer?\n1. Ver películas disponibles\n2. Alquilar una película\n3. Mis alquileres\n4. Logout");
option = Int32.Parse(Console.ReadLine());
if (option > 0 && option < 5)
{
switch (option)
{
case CATALOG:
Catalog(cliente);
break;
case RENT:
Alquiler.Rent(cliente);
break;
case MYRENTINGS:
Alquiler.MyRentings(cliente);
break;
case LOGOUT:
Console.WriteLine("Hasta la próxima.");
break;
}
}
} while (option != LOGOUT);
}
public static void Catalog(Cliente cliente)
{
conexion.Open();
cadena = "SELECT * FROM PELICULAS WHERE PUBLICO <= '" + cliente.Edad() + "'";
comando = new SqlCommand(cadena, conexion);
registros = comando.ExecuteReader();
Console.WriteLine("----Película----");
Console.WriteLine();
while (registros.Read())
{
if (registros["ESTADO"].ToString() == "ALQUILADA")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(registros["MOVIE_ID"].ToString() + "\t" + registros["TITULO"].ToString());
Console.ResetColor();
}
else
{
Console.WriteLine(registros["MOVIE_ID"].ToString() + "\t" + registros["TITULO"].ToString());
}
}
conexion.Close();
Console.WriteLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace Videoclub
{
class Alquiler
{
static String connectionString = ConfigurationManager.ConnectionStrings["ConexionVIDEOCLUB"].ConnectionString;
static SqlConnection conexion = new SqlConnection(connectionString);
static string cadena;
static SqlCommand comando;
static SqlDataReader registros;
private int rentId;
private int peliculaId;
private string usuario;
private DateTime fechaRent;
private DateTime fechaDev;
private DateTime fechaExpiring;
private string movTitle;
public Alquiler()
{
}
public Alquiler(int rentId, int peliculaId, string usuario, DateTime fechaRent, DateTime fechaDev, DateTime fechaExpiring, string movTitle)
{
this.rentId = rentId;
this.peliculaId = peliculaId;
this.usuario = usuario;
this.fechaRent = fechaRent;
this.fechaDev = fechaDev;
this.fechaExpiring = fechaExpiring;
this.movTitle = movTitle;
}
public int GetRentId()
{
return rentId;
}
public int GetPeliculaId()
{
return peliculaId;
}
public string GetUsuario()
{
return usuario;
}
public DateTime GetFechaRent()
{
return fechaRent;
}
public DateTime GetFechaDev()
{
return fechaDev;
}
public DateTime GetFechaExpiring()
{
return fechaExpiring;
}
public string GetMovTitle()
{
return movTitle;
}
public void SetRentId(int rentId)
{
this.rentId = rentId;
}
public void SetPeliculaId(int peliculaId)
{
this.peliculaId = peliculaId;
}
public void SetUsuario(string usuario)
{
this.usuario = usuario;
}
public void SetFechaRent(DateTime fechaRent)
{
this.fechaRent = fechaRent;
}
public void SetFechaDev(DateTime fechaDev)
{
this.fechaDev = fechaDev;
}
public void SetFechaExpiring(DateTime fechaExpiring)
{
this.fechaExpiring = fechaExpiring;
}
public void SetMovTitle(string movTitle)
{
this.movTitle = movTitle;
}
public static void Rent(Cliente cliente)
{
conexion.Open();
cadena = "SELECT * FROM PELICULAS WHERE PUBLICO <= '" + cliente.Edad() + "' AND ESTADO = 'LIBRE'";
comando = new SqlCommand(cadena, conexion);
registros = comando.ExecuteReader();
while (registros.Read())
{
if (registros["ESTADO"].ToString() == "LIBRE")
{
Console.WriteLine(registros["MOVIE_ID"].ToString() + " " + registros["TITULO"].ToString() + "\nSinopsis: \n" + registros["SINOPSIS"].ToString());
Console.WriteLine();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(registros["MOVIE_ID"].ToString() + " " + registros["TITULO"].ToString() + "\nSinopsis: \n" + registros["SINOPSIS"].ToString());
Console.WriteLine();
Console.ResetColor();
}
}
conexion.Close();
Console.WriteLine("¿Qué película desea alquilar? ");
int option = Int32.Parse(Console.ReadLine());
conexion.Open();
cadena = "UPDATE PELICULAS SET ESTADO = 'ALQUILADA' WHERE MOVIE_ID = '" + option + "'";
comando = new SqlCommand(cadena, conexion);
comando.ExecuteNonQuery();
conexion.Close();
Console.WriteLine("\nPelícula alquilada. Esperamos que la disfrute. ");
conexion.Open();
Peliculas pelicula = new Peliculas();
cadena = "SELECT * FROM PELICULAS WHERE MOVIE_ID = '" + option + "'";
comando = new SqlCommand(cadena, conexion);
registros = comando.ExecuteReader();
if (registros.Read())
{
pelicula.SetMovieId(option);
pelicula.SetTitulo(registros["TITULO"].ToString());
pelicula.SetDirector(registros["DIRECTOR"].ToString());
pelicula.SetPublico(Int32.Parse(registros["PUBLICO"].ToString()));
pelicula.SetSinopsis(registros["SINOPSIS"].ToString());
pelicula.SetAlquilada(registros["ESTADO"].ToString());
}
conexion.Close();
conexion.Open();
cadena = "INSERT INTO ALQUILERES (MOV_ID, USUARIO, RENT_DATE, RENT_EXPIRING,MOV_TITLE) VALUES ('" + pelicula.GetmovieId() + "','" + cliente.GetUsername() + "','" + DateTime.Now + "','" + DateTime.Now.AddDays(1) + "','" + pelicula.GetTitulo() + "')";
comando = new SqlCommand(cadena, conexion);
comando.ExecuteNonQuery();
conexion.Close();
}
public static void MyRentings(Cliente cliente)
{
Alquiler alquiler = new Alquiler();
conexion.Open();
cadena = "SELECT MOV_ID,MOV_TITLE,RENT_DATE,RENT_DEV,RENT_EXPIRING FROM ALQUILERES WHERE USUARIO = '" + cliente.GetUsername() + "'";
comando = new SqlCommand(cadena, conexion);
registros = comando.ExecuteReader();
Console.WriteLine("Información para el usuario: los alquileres en rojo son aquellos que tienen vencida la fecha de devoución de la película. Por favor, devuélvala a la mayor brevedad.");
while (registros.Read())
{
alquiler.SetPeliculaId(Int32.Parse(registros["MOV_ID"].ToString()));
alquiler.SetMovTitle(registros["MOV_TITLE"].ToString());
alquiler.SetFechaRent(DateTime.Parse(registros["RENT_DATE"].ToString()));
alquiler.SetFechaExpiring(DateTime.Parse(registros["RENT_EXPIRING"].ToString()));
if (alquiler.fechaExpiring < DateTime.Now)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(registros["MOV_ID"].ToString() + " " + registros["MOV_TITLE"].ToString() + " " + registros["RENT_DATE"].ToString() + " " + registros["RENT_EXPIRING"].ToString());
Console.ResetColor();
}
else
{
Console.WriteLine(registros["MOV_ID"].ToString() + " " + registros["MOV_TITLE"].ToString() + " " + registros["RENT_DATE"].ToString() + " " + registros["RENT_EXPIRING"].ToString());
}
}
conexion.Close();
int option = 0;
const int DEVOLUTION = 1, AUMENT = 2, EXIT = 3;
do
{
Console.WriteLine("\n¿Desea realizar alguna operación?\n1. Devolver película\n2. Aumentar alquiler\n3. Salir. ");
option = Int32.Parse(Console.ReadLine());
switch (option)
{
case DEVOLUTION:
Devolution();
break;
case AUMENT:
Console.WriteLine("¿A qué película quiere aumentarle el tiempo de alquiler?");
int pelicula = Int32.Parse(Console.ReadLine());
Console.WriteLine("¿Cuántos días quiere aumentar el alquiler de la película?");
int days = Int32.Parse(Console.ReadLine());
conexion.Open();
cadena = "UPDATE ALQUILERES SET RENT_EXPIRING = '" + alquiler.GetFechaExpiring().AddDays(days) + "' WHERE MOV_ID = '" + pelicula + "'";
comando = new SqlCommand(cadena, conexion);
comando.ExecuteNonQuery();
conexion.Close();
Console.WriteLine("Cambio introducido correctamente. ¿Qué desea hacer ahora? ");
break;
}
} while (option != EXIT);
}
public static void Devolution()
{
Console.WriteLine("¿Qué película desea devolver? ");
int idPelicula = Int32.Parse(Console.ReadLine());
conexion.Open();
cadena = "UPDATE ALQUILERES SET RENT_DEV= '" + DateTime.Now + "' WHERE MOV_ID = '" + idPelicula + "'";
comando = new SqlCommand(cadena, conexion);
comando.ExecuteNonQuery();
conexion.Close();
conexion.Open();
cadena = "UPDATE PELICULAS SET ESTADO = 'LIBRE' WHERE MOVIE_ID = '" + idPelicula + "'";
comando = new SqlCommand(cadena, conexion);
comando.ExecuteNonQuery();
conexion.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace Videoclub
{
class Menu
{
static String connectionString = ConfigurationManager.ConnectionStrings["ConexionVIDEOCLUB"].ConnectionString;
static SqlConnection conexion = new SqlConnection(connectionString);
static string cadena;
static SqlCommand comando;
static SqlDataReader registros;
public static void FirstMenu()
{
int option=0;
const int LOGIN = 1, REGISTER = 2, SALIR = 3;
do
{
Console.WriteLine("\t\t\t\t -----Bienvenido al BootClub----- ");
Console.WriteLine("opciones :\n1. Login\n2. Registrarse\n3. Salir\n");
try
{
option = Int32.Parse(Console.ReadLine());
}
catch (SystemException)
{
Console.WriteLine("Opción no reconocida. Por favor, introduza una opción válida. ");
}
if (option > 0 && option < 4)
{
switch (option)
{
case LOGIN:
Cliente.Login();
break;
case REGISTER:
Cliente.Register();
break;
case SALIR:
Console.WriteLine("Gracias por visitarnos");
break;
}
}
else
{
Console.WriteLine("Eso n o es una opción válida.");
}
} while (option != SALIR);
}
}
} | f41413019b702ea1b2fe0fda6a330dbf07b414ad | [
"C#"
] | 6 | C# | PMurguia/Videoclub | afdf4a5493b296beb0717d9b6f690368d929d887 | cdb757f80907e20277eefe6195fa2ad234cc1ea6 |
refs/heads/master | <repo_name>eokoronkwo/projectSpark<file_sep>/project.js
let results = {
category: '',
type: '',
question: '',
difficulty: '',
correct_answer: '',
incorrect_answers: ['', '', ''],
};
const apiUrlRand = 'https://opentdb.com/api.php?amount=1&type=multiple&encode=base64';
const apiUrlAnimal = 'https://opentdb.com/api.php?amount=1&category=27&type=multiple&encode=base64';
const apiUrlAnime = 'https://opentdb.com/api.php?amount=1&category=31&type=multiple&encode=base64';
const apiUrlArt = 'https://opentdb.com/api.php?amount=1&category=25&type=multiple&encode=base64';
const apiUrlBooks = 'https://opentdb.com/api.php?amount=1&category=10&type=multiple&encode=base64';
const apiUrlCartoon = 'https://opentdb.com/api.php?amount=1&category=32&type=multiple&encode=base64';
const apiUrlFilm = 'https://opentdb.com/api.php?amount=1&category=11&type=multiple&encode=base64';
const apiUrlGadg = 'https://opentdb.com/api.php?amount=1&category=30&type=multiple&encode=base64';
const apiUrlGen = 'https://opentdb.com/api.php?amount=1&category=9&type=multiple&encode=base64';
const apiUrlGeo = 'https://opentdb.com/api.php?amount=1&category=22&type=multiple&encode=base64';
const apiUrlHist = 'https://opentdb.com/api.php?amount=1&category=23&type=multiple&encode=base64';
const apiUrlMyth = 'https://opentdb.com/api.php?amount=1&category=20&type=multiple&encode=base64';
const apiUrlSci = 'https://opentdb.com/api.php?amount=1&category=17&type=multiple&encode=base64';
const apiUrlSpor = 'https://opentdb.com/api.php?amount=1&category=21&type=multiple&encode=base64';
const apiUrlVehi = 'https://opentdb.com/api.php?amount=1&category=28&type=multiple&encode=base64';
const apiUrlVideo = 'https://opentdb.com/api.php?amount=1&category=15&type=multiple&encode=base64';
let json;
const GetFromApi = async function() {
// Fetch request TO the API
const response = await fetch(apiUrlRand)
// API fetch request waits to receive data before continuing
json = await response.json();
// After the API receives the request, the function newQuestion() executes
newQuestion();
// Logs the information received from the API in the console
console.log(json)
}
let newQuestion = function() {
// Constant variables which corresponds to where the API information received will be
// placed on the webpage
const diff = document.getElementById('diff');
const quest = document.getElementById('question');
// atob() function decodes the information received from the api
diff.innerText = 'Difficulty: ' + atob(json.results[0].difficulty);
quest.innerText = atob(json.results[0].question);
// Set the options to each question into an array for positioning purposes with the
// function setContentRandom()
let options = [atob(json.results[0].correct_answer),
atob(json.results[0].incorrect_answers[0]),
atob(json.results[0].incorrect_answers[1]),
atob(json.results[0].incorrect_answers[2])]
// Executes the functions setContentRandom
setContentRandom(options);
}
let setContentRandom = function(options) {
let used = new Array();
// For loop iterates through the the options array
for(let i = 0; i < options.length; i++) {
// Randomizes the order
let randomNum = Math.floor(Math.random() * (4 - 0));
// While the random number has already been used
while(used.includes(randomNum)) {
// Generates a new random number
randomNum = Math.floor(Math.random() * (4 - 0));
}
// Pushes the random order to the array 'used'
used.push(randomNum);
let element = document.getElementById(randomNum);
// Sets the randomized content in the options array
element.innerText = options[i];
}
}
let reveal = function() {
// Sets the 'correct' variable to the correct answer pulled from the API
let correct = atob(json.results[0].correct_answer);
// Var x is set to the correct answer box with the id 'reveal'
var x = document.getElementById('reveal');
// 'If' control structure sets the display styling of the answer box
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
// Sets the inner text of the element by ID reveal to the correct answer pulled from the API
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApi);
document.getElementById('reveal0').addEventListener('click', reveal);
let json1;
const GetFromApiAnim = async function() {
const response = await fetch(apiUrlAnimal)
//get raw data from the API and then wait
//for the response to come in before continuing
json1 = await response.json();
newQuestionAnim();
console.log(json1)
}
let newQuestionAnim = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json1.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json1.results[0].difficulty);
let options = [atob(json1.results[0].correct_answer),
atob(json1.results[0].incorrect_answers[0]),
atob(json1.results[0].incorrect_answers[1]),
atob(json1.results[0].incorrect_answers[2])]
setContentRandomAnim(options);
}
let setContentRandomAnim = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealAnim = function() {
let correct = atob(json1.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiAnim);
document.getElementById('reveal0').addEventListener('click', revealAnim);
let json2;
const GetFromApiAnime = async function() {
const response = await fetch(apiUrlAnime)
//get raw data from the API and then wait
//for the response to come in before continuing
json2 = await response.json();
newQuestionAnime();
console.log(json2)
}
let newQuestionAnime = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json2.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json2.results[0].difficulty);
let options = [atob(json2.results[0].correct_answer),
atob(json2.results[0].incorrect_answers[0]),
atob(json2.results[0].incorrect_answers[1]),
atob(json2.results[0].incorrect_answers[2])]
setContentRandomAnime(options);
}
let setContentRandomAnime = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealAnime = function() {
let correct = atob(json2.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiAnime);
document.getElementById('reveal0').addEventListener('click', revealAnime);
let json3;
const GetFromApiArt = async function() {
const response = await fetch(apiUrlArt)
//get raw data from the API and then wait
//for the response to come in before continuing
json3 = await response.json();
newQuestionArt();
console.log(json3)
}
let newQuestionArt = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json3.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json3.results[0].difficulty);
let options = [atob(json3.results[0].correct_answer),
atob(json3.results[0].incorrect_answers[0]),
atob(json3.results[0].incorrect_answers[1]),
atob(json3.results[0].incorrect_answers[2])]
setContentRandomArt(options);
}
let setContentRandomArt = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealArt = function() {
let correct = atob(json3.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiArt);
document.getElementById('reveal0').addEventListener('click', revealArt);
let json4;
const GetFromApiBook = async function() {
const response = await fetch(apiUrlBooks)
//get raw data from the API and then wait
//for the response to come in before continuing
json4 = await response.json();
newQuestionBook();
console.log(json4)
}
let newQuestionBook = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json4.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json4.results[0].difficulty);
let options = [atob(json4.results[0].correct_answer),
atob(json4.results[0].incorrect_answers[0]),
atob(json4.results[0].incorrect_answers[1]),
atob(json4.results[0].incorrect_answers[2])]
setContentRandomBook(options);
}
let setContentRandomBook = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealBook = function() {
let correct = atob(json4.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiBook);
document.getElementById('reveal0').addEventListener('click', revealBook);
let json5;
const GetFromApiCart = async function() {
const response = await fetch(apiUrlCartoon)
//get raw data from the API and then wait
//for the response to come in before continuing
json5 = await response.json();
newQuestionCart();
console.log(json5)
}
let newQuestionCart = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json5.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json5.results[0].difficulty);
let options = [atob(json5.results[0].correct_answer),
atob(json5.results[0].incorrect_answers[0]),
atob(json5.results[0].incorrect_answers[1]),
atob(json5.results[0].incorrect_answers[2])]
setContentRandomCart(options);
}
let setContentRandomCart = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealCart = function() {
let correct = atob(json5.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiCart);
document.getElementById('reveal0').addEventListener('click', revealCart);
let json6;
const GetFromApiFilm = async function() {
const response = await fetch(apiUrlFilm)
//get raw data from the API and then wait
//for the response to come in before continuing
json6 = await response.json();
newQuestionFilm();
console.log(json6)
}
let newQuestionFilm = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json6.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json6.results[0].difficulty);
let options = [atob(json6.results[0].correct_answer),
atob(json6.results[0].incorrect_answers[0]),
atob(json6.results[0].incorrect_answers[1]),
atob(json6.results[0].incorrect_answers[2])]
setContentRandomFilm(options);
}
let setContentRandomFilm = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealFilm = function() {
let correct = atob(json6.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiFilm);
document.getElementById('reveal0').addEventListener('click', revealFilm);
let json7;
const GetFromApiGadg = async function() {
const response = await fetch(apiUrlGadg)
//get raw data from the API and then wait
//for the response to come in before continuing
json7 = await response.json();
newQuestionGadg();
console.log(json7)
}
let newQuestionGadg = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json7.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json7.results[0].difficulty);
let options = [atob(json7.results[0].correct_answer),
atob(json7.results[0].incorrect_answers[0]),
atob(json7.results[0].incorrect_answers[1]),
atob(json7.results[0].incorrect_answers[2])]
setContentRandomGadg(options);
}
let setContentRandomGadg = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealGadg = function() {
let correct = atob(json7.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiGadg);
document.getElementById('reveal0').addEventListener('click', revealGadg);
let json8;
const GetFromApiGen = async function() {
const response = await fetch(apiUrlGen)
//get raw data from the API and then wait
//for the response to come in before continuing
json8 = await response.json();
newQuestionGen();
console.log(json8)
}
let newQuestionGen = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json8.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json8.results[0].difficulty);
let options = [atob(json8.results[0].correct_answer),
atob(json8.results[0].incorrect_answers[0]),
atob(json8.results[0].incorrect_answers[1]),
atob(json8.results[0].incorrect_answers[2])]
setContentRandomGen(options);
}
let setContentRandomGen = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealGen = function() {
let correct = atob(json8.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiGen);
document.getElementById('reveal0').addEventListener('click', revealGen);
let json9;
const GetFromApiGeo = async function() {
const response = await fetch(apiUrlGeo)
//get raw data from the API and then wait
//for the response to come in before continuing
json9 = await response.json();
newQuestionGeo();
console.log(json9)
}
let newQuestionGeo = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json9.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json9.results[0].difficulty);
let options = [atob(json9.results[0].correct_answer),
atob(json9.results[0].incorrect_answers[0]),
atob(json9.results[0].incorrect_answers[1]),
atob(json9.results[0].incorrect_answers[2])]
setContentRandomGeo(options);
}
let setContentRandomGeo = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealGeo = function() {
let correct = atob(json9.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiGeo);
document.getElementById('reveal0').addEventListener('click', revealGeo);
let json10;
const GetFromApiHist = async function() {
const response = await fetch(apiUrlHist)
//get raw data from the API and then wait
//for the response to come in before continuing
json10 = await response.json();
newQuestionHist();
console.log(json10)
}
let newQuestionHist = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json10.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json10.results[0].difficulty);
let options = [atob(json10.results[0].correct_answer),
atob(json10.results[0].incorrect_answers[0]),
atob(json10.results[0].incorrect_answers[1]),
atob(json10.results[0].incorrect_answers[2])]
setContentRandomHist(options);
}
let setContentRandomHist = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealHist = function() {
let correct = atob(json10.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiHist);
document.getElementById('reveal0').addEventListener('click', revealHist);
let json11;
const GetFromApiMyth = async function() {
const response = await fetch(apiUrlMyth)
//get raw data from the API and then wait
//for the response to come in before continuing
json11 = await response.json();
newQuestionMyth();
console.log(json11)
}
let newQuestionMyth = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json11.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json11.results[0].difficulty);
let options = [atob(json11.results[0].correct_answer),
atob(json11.results[0].incorrect_answers[0]),
atob(json11.results[0].incorrect_answers[1]),
atob(json11.results[0].incorrect_answers[2])]
setContentRandomMyth(options);
}
let setContentRandomMyth = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealMyth = function() {
let correct = atob(json11.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiMyth);
document.getElementById('reveal0').addEventListener('click', revealMyth);
let json12;
const GetFromApiSci = async function() {
const response = await fetch(apiUrlSci)
//get raw data from the API and then wait
//for the response to come in before continuing
json12 = await response.json();
newQuestionSci();
console.log(json12)
}
let newQuestionSci = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json12.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json12.results[0].difficulty);
let options = [atob(json12.results[0].correct_answer),
atob(json12.results[0].incorrect_answers[0]),
atob(json12.results[0].incorrect_answers[1]),
atob(json12.results[0].incorrect_answers[2])]
setContentRandomSci(options);
}
let setContentRandomSci = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealSci = function() {
let correct = atob(json12.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiSci);
document.getElementById('reveal0').addEventListener('click', revealSci);
let json13;
const GetFromApiSpor = async function() {
const response = await fetch(apiUrlSpor)
//get raw data from the API and then wait
//for the response to come in before continuing
json13 = await response.json();
newQuestionSpor();
console.log(json13)
}
let newQuestionSpor = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json13.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json13.results[0].difficulty);
let options = [atob(json13.results[0].correct_answer),
atob(json13.results[0].incorrect_answers[0]),
atob(json13.results[0].incorrect_answers[1]),
atob(json13.results[0].incorrect_answers[2])]
setContentRandomSci(options);
}
let setContentRandomSpor = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealSpor = function() {
let correct = atob(json13.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiSpor);
document.getElementById('reveal0').addEventListener('click', revealSpor);
let json14;
const GetFromApiVehi = async function() {
const response = await fetch(apiUrlVehi)
//get raw data from the API and then wait
//for the response to come in before continuing
json14 = await response.json();
newQuestionVehi();
console.log(json14)
}
let newQuestionVehi = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json14.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json14.results[0].difficulty);
let options = [atob(json14.results[0].correct_answer),
atob(json14.results[0].incorrect_answers[0]),
atob(json14.results[0].incorrect_answers[1]),
atob(json14.results[0].incorrect_answers[2])]
setContentRandomVehi(options);
}
let setContentRandomVehi = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealVehi = function() {
let correct = atob(json14.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiVehi);
document.getElementById('reveal0').addEventListener('click', revealVehi);
let json15;
const GetFromApiVideo = async function() {
const response = await fetch(apiUrlVideo)
//get raw data from the API and then wait
//for the response to come in before continuing
json15 = await response.json();
newQuestionVideo();
console.log(json15)
}
let newQuestionVideo = function() {
const quest = document.getElementById('question');
const diff = document.getElementById('diff');
quest.innerText = atob(json15.results[0].question);
diff.innerText = 'Difficulty: ' + atob(json15.results[0].difficulty);
let options = [atob(json15.results[0].correct_answer),
atob(json15.results[0].incorrect_answers[0]),
atob(json15.results[0].incorrect_answers[1]),
atob(json15.results[0].incorrect_answers[2])]
setContentRandomVideo(options);
}
let setContentRandomVideo = function(options) {
let used = new Array();
for(let i = 0; i < options.length; i++) {
let randomNum = Math.floor(Math.random() * (4 - 0));
while(used.includes(randomNum)) {
randomNum = Math.floor(Math.random() * (4 - 0));
}
used.push(randomNum);
let element = document.getElementById(randomNum);
element.innerText = options[i];
}
}
let revealVideo = function() {
let correct = atob(json15.results[0].correct_answer);
var x = document.getElementById('reveal');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
document.getElementById('reveal').innerText = correct;
}
document.getElementById('new-question').addEventListener('click', GetFromApiVideo);
document.getElementById('reveal0').addEventListener('click', revealVideo);
// Sets the distance of the top of the element from the top of the elements
// original position
var topDown = 0;
var myMove = function() {
// Increases the distance of the top of the elemnt from the top of the elements
// original position, therefore moving the object
topDown = topDown + 1.2;
// Stops the function from continuing once the topDown value reaches 150
if(topDown >= 150) {
return;
}
// Update the top position of the element position to the new element value
document.getElementById('question').style.top = topDown + 'px';
// Allows the element to continously move by setting a "timeout" before the function is repeated
// The second parameter is is the time between each call of the function, 1 ten-thousandth of a second
setTimeout(myMove, .1);
}
var leftRight = 0;
var myMove1 = function() {
leftRight = leftRight + 3.6;
if(leftRight >= 450) {
return;
}
document.getElementById('options').style.left = leftRight + 'px';
setTimeout(myMove1, .1);
}
function fade() {
// Initial opacity
var op = 1;
// Timer is a setInterval function that
var timer = setInterval(function () {
// Function clears the interval and sets the display to none
if (op <= 0.1){
clearInterval(timer);
document.getElementById('question').style.display = 'none';
}
// Sets opacity of the element
document.getElementById('question').style.opacity = op;
document.getElementById('question').style.filter = 'alpha(opacity=' + op * 100 + ")";
// Multiplies the Initial opacity value by 0.2 and subtracts that from the op value
op -= op * 0.2;
// The interval of the function is set to half of a tenth of a second
}, 50);
}
function fade1() {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
document.getElementById('options').style.display = 'none';
}
document.getElementById('options').style.opacity = op;
document.getElementById('options').style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.2;
}, 50);
}
| ff751a5a95a608eaf66499ab8db00c5ba095e4bc | [
"JavaScript"
] | 1 | JavaScript | eokoronkwo/projectSpark | c75f27bcc86871bbbbac44f7387c55dde8061d5e | 5cd73d65941f474a41e5562694d14bc60f45f247 |
refs/heads/master | <file_sep>import numpy
import common
import sys
import json
import world
import time
import bot_neural
if len(sys.argv) != 2:
print "Usage: replay_convert.py path_to_match"
sys.exit(1)
match_path = sys.argv[1]
print "Loading", match_path
data = []
with open(match_path, 'rb') as f:
data = json.load(f)
agent = bot_neural.GeneralsBot(False)
firstUpdate = True
skipped = 0
agent._running = True
for turn, step in enumerate(data):
if not ('move' in step):
skipped += 1
continue
if not firstUpdate:
nlm = len(agent._last_moves)
move = step['move']
fromIdx = move['from'] if 'from' in move else 0
dirIdx = move['dir'] if 'dir' in move else 0
(x, y) = common.idx_to_coord(fromIdx)
(dx, dy) = common.DIRECTION_VEC[dirIdx]
(nx, ny) = (x + dx, y + dy)
olm = agent._last_moves[nlm-1]
agent._last_moves[nlm-1] = {
'is_50': 'is50' in step and step['is50'],
'x': x,
'y': y,
'nx': nx,
'ny': ny,
'tile': olm['tile'],
'pred': olm['pred'],
'pidx': dirIdx,
'input': olm['input'],
}
update = world.replay_to_update(step)
update['turn'] = turn - skipped
agent._next_ready = False
agent._set_update(update)
if firstUpdate:
bot_neural._create_thread(agent._start_moves)
bot_neural._create_thread(agent._start_learn_loop)
firstUpdate = False
#if '_viewer' in dir(agent):
#agent._viewer.updateGrid(update)
while not agent._next_ready:
time.sleep(0.01)
agent._set_update({'complete': True, 'result': True})
time.sleep(2)
<file_sep>#!/bin/bash
set -e
set -x
usage() {
echo "Usage: $0 ./matches/SgDE9D-Ux.gior 1"
echo "$0 filename playerid [gif]"
}
if [ -z $1 ]; then
usage
exit 1
fi
if [ -z $2 ]; then
usage
exit 1
fi
REPLAY_NAME=$(basename $1)
REPLAY_ID=$(echo "$REPLAY_NAME" | cut -d. -f1)
PLAYER_ID=$2
generals-replay game \
--input ./matches/$REPLAY_NAME \
--output ./matches_json/${REPLAY_ID}_${PLAYER_ID}.json \
--player $PLAYER_ID \
--normalize 20 \
--indent
if [ -n "$3" ]; then
gifmaker ./matches/$REPLAY_NAME $PLAYER_ID
google-chrome-stable ./matches/${REPLAY_ID}.gif
fi
./replay_conv.bash ./matches_json/${REPLAY_ID}_${PLAYER_ID}.json
<file_sep>'''
@ <NAME> (<EMAIL>)
January 2016
Generals.io Automated Client - https://github.com/harrischristiansen/generals-bot
Game Viewer
'''
import pygame
import threading
import time
# Color Definitions
BLACK = (0,0,0)
GRAY_DARK = (110,110,110)
GRAY = (160,160,160)
WHITE = (255,255,255)
PLAYER_COLORS = [(0,128,0), (255,0,0), (255,165,0), (128,0,0), (128,0,128), (0,128,128), (0,70,0), (0,0,255)]
# Table Properies
CELL_WIDTH = 25
CELL_HEIGHT = 25
CELL_MARGIN = 8
class GeneralsViewer(object):
def __init__(self):
self._receivedUpdate = False
def updateGrid(self, update):
self._grid = update['tile_grid']
if "path" in update:
self._path = update['path']
else:
self._path = None
self._armies = update['army_grid']
self._cities = update['cities']
self._generals = update['generals']
self._turn = update['turn']
self._receivedUpdate = True
def _initViewier(self):
pygame.init()
# Set Window Size
window_height = len(self._grid) * (CELL_HEIGHT + CELL_MARGIN) + CELL_MARGIN + 25
window_width = len(self._grid[0]) * (CELL_WIDTH + CELL_MARGIN) + CELL_MARGIN
self._window_size = [window_width, window_height]
self._screen = pygame.display.set_mode(self._window_size)
pygame.display.set_caption("Generals IO Bot")
self._font = pygame.font.SysFont('Arial', CELL_HEIGHT-10)
self._fontLrg = pygame.font.SysFont('Arial', CELL_HEIGHT)
self._clock = pygame.time.Clock()
def mainViewerLoop(self):
while not self._receivedUpdate: # Wait for first update
time.sleep(0.5)
self._initViewier()
done = False
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # User clicked quit
done = True # Flag done
elif event.type == pygame.MOUSEBUTTONDOWN: # Mouse Click
pos = pygame.mouse.get_pos()
# Convert screen to grid coordinates
column = pos[0] // (CELL_WIDTH + CELL_MARGIN)
row = pos[1] // (CELL_HEIGHT + CELL_MARGIN)
print("Click ", pos, "Grid coordinates: ", row, column)
if (self._receivedUpdate):
self._drawGrid()
self._receivedUpdate = False
time.sleep(0.2)
pygame.quit() # Done. Quit pygame.
def _drawGrid(self):
self._screen.fill(BLACK) # Set BG Color
# Draw Score
self._screen.blit(self._fontLrg.render("Turn: "+str(self._turn), True, WHITE), (10, self._window_size[1]-25))
# Draw Grid
for row in range(len(self._grid)):
for column in range(len(self._grid[row])):
# Determine BG Color
color = WHITE
color_font = WHITE
if self._grid[row][column] == -2: # Mountain
color = BLACK
elif self._grid[row][column] == -3: # Fog
color = GRAY
elif self._grid[row][column] == -4: # Obstacle
color = GRAY_DARK
elif self._grid[row][column] >= 0: # Player
color = PLAYER_COLORS[self._grid[row][column]]
else:
color_font = BLACK
pos_left = (CELL_MARGIN + CELL_WIDTH) * column + CELL_MARGIN
pos_top = (CELL_MARGIN + CELL_HEIGHT) * row + CELL_MARGIN
if ((row,column) in self._cities or (row,column) in self._generals): # City
# Draw Circle
pos_left_circle = pos_left + (CELL_WIDTH/2)
pos_top_circle = pos_top + (CELL_HEIGHT/2)
pygame.draw.circle(self._screen, color, [pos_left_circle, pos_top_circle], CELL_WIDTH/2)
else:
# Draw Rect
pygame.draw.rect(self._screen, color, [pos_left, pos_top, CELL_WIDTH, CELL_HEIGHT])
# Draw Text Value
if (self._grid[row][column] >= -2 and self._armies[row][column] != 0): # Don't draw on fog
self._screen.blit(self._font.render(str(self._armies[row][column]), True, color_font), (pos_left+2, pos_top+2))
# Draw Path
if (self._path != None and (column,row) in self._path):
self._screen.blit(self._fontLrg.render("*", True, color_font), (pos_left+3, pos_top+3))
# Limit to 60 frames per second
self._clock.tick(60)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
'''def _create_thread(f):
t = threading.Thread(target=f)
#t.daemon = True
t.start()
def _fakeUpdates():
viewer.updateGrid(grid,grid,[],[])
time.sleep(1)
grid[1][8] = 2
viewer.updateGrid(grid,grid,[],[])
grid = []
for row in range(10):
grid.append([])
for column in range(10):
grid[row].append(0) # Append a cell
grid[1][5] = 1
grid[1][7] = 2
viewer = GeneralsViewer()
_create_thread(_fakeUpdates)
viewer.mainViewerLoop()'''
<file_sep>import os
import logging
import random
import threading
import time
import datetime
import numpy
import common
import world
import tensorflow
import pickle
import client.generals as generals
from viewer import GeneralsViewer
BOT_NAME_N = numpy.random.randint(0, 2)
BOT_NAME = str(BOT_NAME_N)+'Fiery'+str(BOT_NAME_N+1)+"Me"
MAP_SIZE = common.MAP_SIZE
# Show all logging
logging.basicConfig(level=logging.DEBUG)
class GeneralsBot(object):
def __init__(self, start_game=True):
print "Building model..."
self.model = common.build_model()
self.graph = tensorflow.get_default_graph()
self.model_mtx = threading.Lock()
self.data_mtx = threading.Lock()
self._update = None
self._start_game = start_game
self._dirty = True
self._next_ready = True
self._last_moves = []
if start_game:
# Start Game Loop
_create_thread(self._start_game_loop)
# Start Game Viewer
self._viewer = GeneralsViewer()
_create_thread(self._viewer.mainViewerLoop)
def _start_learn_loop(self):
n = 0
while self._running:
time.sleep(0.1)
if not self._running:
break
n += 1
if n < 150:
continue
n = 0
print "Applying weights..."
try:
with self.model_mtx:
if os.path.exists(common.filePath):
self.model.load_weights(common.filePath)
except:
pass
if len(self._last_moves) > 20:
print "Simplifying experiences..."
exper = []
preds = []
for last_move in self._last_moves:
if 'reward' not in last_move:
continue
exper.append(last_move['input'])
npred = {
'pred': last_move['pred'],
'reward': last_move['reward'],
'pidx': last_move['pidx'],
}
isTerminal = 'terminal' in last_move
if isTerminal:
npred['terminal'] = last_move['terminal']
preds.append(npred)
print "Dumping experiences..."
if not os.path.exists('./experiences'):
os.mkdir('./experiences')
timestr = time.strftime("%Y%m%d-%H%M%S")
with open('./experiences/'+timestr+'.exp', 'wb') as f:
pickle.dump([exper, preds], f)
else:
print "Less than 20 moves, not saving:", len(self._last_moves)
os._exit(0)
def _start_game_loop(self):
# Create Game
# self._game = generals.Generals(BOT_NAME, BOT_NAME, '1v1')
if self._start_game:
self._game = generals.Generals(BOT_NAME, BOT_NAME, 'private', gameid='HyI4d3_rl') # PRIVATE
# Start Game Update Loop
self._running = True
if self._start_game:
_create_thread(self._start_update_loop)
# Start learner
_create_thread(self._start_learn_loop)
while (self._running):
msg = input('Send Msg:')
print("Sending MSG: " + msg)
# TODO: Send msg
######################### Handle Updates From Server #########################
def _start_update_loop(self):
firstUpdate = True
updates = []
try:
updates = self._game.get_updates()
except ex:
print ex
os.exit(1)
for update in updates:
self._set_update(update)
if (not self._running):
return
if (firstUpdate):
_create_thread(self._start_moves)
firstUpdate = False
# Update GeneralsViewer Grid
if '_viewer' in dir(self):
self._viewer.updateGrid(self._update)
def _set_update(self, update):
self._update = update
self._dirty = True
if (update['complete']):
print("!!!! Game Complete. Result = " + str(update['result']) + " !!!!")
lm = self._last_moves[len(self._last_moves)-1]
lm['terminal'] = update['result']
self._running = False
return
self._pi = update['player_index']
self._opponent_position = None
self._rows = update['rows']
self._cols = update['cols']
def _print_scores(self):
scores = sorted(self._update['scores'], key=lambda general: general['total'], reverse=True) # Sort Scores
lands = sorted(self._update['lands'], reverse=True)
armies = sorted(self._update['armies'], reverse=True)
print(" -------- Scores --------")
for score in scores:
pos_lands = lands.index(score['tiles'])
pos_armies = armies.index(score['total'])
if (score['i'] == self._pi):
print("SELF: ")
print('Land: %d (%4d), Army: %d (%4d) / %d' % (pos_lands+1, score['tiles'], pos_armies+1, score['total'], len(scores)))
######################### Thread: Make Moves #########################
def _start_moves(self):
self._last_moves = []
self._turn_count = 0
while (self._running and not self._update['complete']):
#self._turn_start = datetime.datetime.utcnow()
time.sleep(0.1)
if not self._dirty:
continue
self._dirty = False
if self._update['complete']:
break
self._make_move()
self._next_ready = True
#self._turn_end = datetime.datetime.utcnow()
#turn_delta = self._turn_end - self._turn_start
#till_next = 600.0 - (turn_delta.microseconds / 1000.0)
#if till_next > 0.0:
# time.sleep(till_next/1000.0)
self._turn_count += 1
def _make_move(self):
owned_tiles = world.build_game_view(self._update)
if len(owned_tiles) == 0:
return
input_data = []
for tile in owned_tiles:
input_data.append(numpy.array(tile['view']))
input_data = numpy.array(input_data)
# Make predictions
predictions = []
if self._start_game:
with self.model_mtx:
with self.graph.as_default():
predictions = self.model.predict(input_data)
else:
predictions = numpy.zeros((len(owned_tiles), common.MOVE_COUNT))
# Best moves
best_moves = []
all_moves = []
for idx, owned_tile in enumerate(owned_tiles):
pred = predictions[idx]
row = owned_tile['row']
col = owned_tile['col']
for direction, reward in enumerate(predictions[idx]):
adir = direction
is_50 = (direction / len(common.DIRECTIONS)) > 0
if is_50:
direction = direction - len(common.DIRECTIONS)
dx, dy = common.DIRECTION_VEC[direction]
nrow, ncol = (row - dy, col - dx)
if nrow < 0 or nrow >= self._rows:
continue
if ncol < 0 or ncol >= self._cols:
continue
tile_typ = self._update['tile_grid'][nrow][ncol]
if tile_typ in [generals.MOUNTAIN, generals.FOG, generals.OBSTACLE]:
continue
move = {
'is_50': is_50,
'x': col,
'y': row,
'nx': ncol,
'ny': nrow,
'tile': owned_tile,
'pred': pred,
'pidx': adir,
'input': input_data[idx],
}
best_moves.append([reward, len(all_moves)])
all_moves.append(move)
if len(best_moves) == 0:
return
move_count = len(best_moves)
best_moves = numpy.sort(best_moves, axis=0)
best_move_idx = numpy.random.choice(min(move_count, 5))
best_move = all_moves[int(best_moves[int(best_move_idx)][1])]
ox = best_move['x']
oy = best_move['y']
nx = best_move['nx']
ny = best_move['ny']
is_50 = best_move['is_50']
if self._start_game:
print "Moving", ox, oy, nx, ny, is_50
self._place_move(oy, ox, ny, nx, is_50)
# Update prediction with actual outcome
with self.data_mtx:
currProd = self._sum_production()
if len(self._last_moves) > 0:
lmov = self._last_moves[len(self._last_moves)-1]
prodChange = currProd - self._last_production
print "Production:", currProd, "Reward:", prodChange#, "dSS:", self._last_stack_change
#
#if prodChange > 0:
# prodChange += min(self._last_stack_change, 3)
# print "Adjusted production:", prodChange
# print "Prediction:"
# print lmov['pred']
lmov['reward'] = prodChange
self._last_production = currProd
self._last_moves.append(best_move)
return
def _place_move(self, y1, x1, y2, x2, move_half=False):
last_stack_size = max(self._update['army_grid'][y1][x1], self._update['army_grid'][y2][x2])
new_stack_size = 0
self._game.move(y1, x1, y2, x2, move_half)
# Calculate Remaining Army
army_remaining = 1
took_enemy = False
captured_size = 1
if move_half:
army_remaining = self._update['army_grid'][y1][x1] / 2
if (self._update['tile_grid'][y2][x2] == self._pi): # Owned By Self
new_stack_size = self._update['army_grid'][y1][x1] + self._update['army_grid'][y2][x2] - army_remaining
else:
took_enemy = True
captured_size = self._update['army_grid'][y2][x2]
new_stack_size = self._update['army_grid'][y1][x1] - self._update['army_grid'][y2][x2] - army_remaining
if took_enemy:
self._last_stack_change = captured_size
else:
self._last_stack_change = new_stack_size-last_stack_size
self._last_stack_change = int(self._last_stack_change * 0.2)
def _validPosition(self, x, y):
if not ('tile_grid' in self._update):
return False
return 0 <= y < self._rows and 0 <= x < self._cols and self._update['tile_grid'][y][x] != generals.MOUNTAIN
def _sum_production(self):
total = 0
for x in range(self._cols):
for y in range(self._rows):
tile = self._update['tile_grid'][y][x]
pos = (y,x)
if tile != self._pi:
continue
elif pos in self._update['cities']:
total += 25
else:
total += 10
return total
######################### Global Helpers #########################
def _create_thread(f):
t = threading.Thread(target=f)
t.daemon = True
t.start()
######################### Main #########################
# Start Bot
if __name__ == "__main__":
GeneralsBot(True)
while True:
time.sleep(1)
<file_sep>#!/bin/bash
set +x
docker run --rm -it \
-v $(pwd):/notebooks paralin/tensorflow-keras:latest \
python replay_convert.py $1
<file_sep>import logging
from Queue import Queue
import random
import threading
import time
from pprint import pprint
import client.generals as generals
from viewer import GeneralsViewer
import numpy
import common
import tensorflow
class ExperienceLearner:
def __init__(self):
self.model = common.build_model()
self.graph = tensorflow.get_default_graph()
def learn_once(self):
print "Loading experiences..."
states, moves = common.load_experiences()
predictions = numpy.zeros((len(states), common.MOVE_COUNT))
print "Re-computing Q values..."
for idx, state in enumerate(states):
move = moves[idx]
oldReward = move['reward']
if 'terminal' in move:
oldReward = common.WIN_REWARD
if not move['terminal']:
oldReward = -0.5 * common.WIN_REWARD
predicted = self.model.predict(numpy.array([state]))[0]
moveDir = move['pidx']
# Compute max of predictions
maxMove = numpy.max(predicted)
Qd = maxMove * common.DISCOUNT_FACTOR
if 'terminal' in move:
Qd = 0
predicted[moveDir] = Qd + oldReward
predictions[idx] = predicted
print "Fitting..."
nb_epoch = 8
with self.graph.as_default():
self.model.fit(numpy.array(states), numpy.array(predictions), nb_epoch=nb_epoch, batch_size=500, shuffle=True)
print "Saving..."
common.save_model(self.model)
learner = ExperienceLearner()
while True:
learner.learn_once()
<file_sep>#!/bin/bash
sudo xhost +
# --restart=always \
docker run -it \
--env="DISPLAY" \
--env="QT_X11_NO_MITSHM=1" \
--rm \
--privileged \
--volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \
-v $(pwd):/notebooks paralin/tensorflow-keras:latest python bot_neural.py
<file_sep>#!/bin/bash
docker run --rm -it -v $(pwd):/notebooks paralin/tensorflow-keras:latest python exp_learn.py
<file_sep>import json
import numpy
import os
import random
import pickle
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D, LocallyConnected2D, BatchNormalization
from keras.optimizers import RMSprop, SGD, Nadam
from keras.metrics import fbeta_score
# Directions
DIRECTIONS = ["LEFT", "UP", "RIGHT", "DOWN"]
DIRECTION_VEC = [(-1, 0), (0, 1), (1, 0), (0, -1)]
# Map size, squared
MAP_SIZE = 20
# Size of learning grid edge
LEARN_MAP_SIZE = int(MAP_SIZE*0.5)
DISCOUNT_FACTOR = 0.8
WIN_REWARD = 100.0
# Given map size, and directions, we can compute possible total number of moves.
TILE_COUNT = MAP_SIZE*MAP_SIZE
MOVE_COUNT = len(DIRECTIONS) * 2.0
def load_experiences():
experiences = []
moves = []
# list files
if not os.path.exists('./experiences'):
return experiences, moves
files = os.listdir('./experiences')
if len(files) == 0:
return experiences, moves
random.shuffle(files)
i = 0
for filen in files:
with open('./experiences/'+filen, 'rb') as f:
arn = pickle.load(f)
experiences.extend(arn[0])
moves.extend(arn[1])
if i == 1:
break
i += 1
return experiences, moves
filePath = 'weights.h5'
def build_model():
model = Sequential()
# model.add(BatchNormalization(mode=0, axis=1, ))
model.add(Flatten(input_shape=(2, LEARN_MAP_SIZE, LEARN_MAP_SIZE)))
model.add(Dense(164))
model.add(Activation('relu'))
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dense(MOVE_COUNT))
model.add(Activation('linear'))
model.compile(Nadam(), 'mse',
metrics=['accuracy'] )
print model.summary()
if os.path.exists(filePath):
model.load_weights(filePath)
return model
def save_model(model):
model.save_weights(filePath)
# Return (row, col)
def idx_to_coord(idx):
return (idx / MAP_SIZE, idx % MAP_SIZE)
<file_sep>#!/bin/bash
pushd image
docker build -t "paralin/tensorflow-keras:latest" .
popd
<file_sep>import common
import numpy
import client.generals as generals
import math
MAP_SIZE = common.MAP_SIZE
# Convert a replay step to an update
def replay_to_update(step):
update = {}
cells = step['cells']
map_size = int(math.sqrt(len(cells)))
update['rows'] = map_size
update['cols'] = map_size
update['player_index'] = 0
update['complete'] = False
tile_grid = update['tile_grid'] = numpy.zeros((map_size, map_size))
army_grid = update['army_grid'] = numpy.zeros((map_size, map_size))
generalsa = update['generals'] = []
cities = update['cities'] = []
for idx, cell in enumerate(cells):
row = int(idx / map_size)
col = int(idx % map_size)
faction = cell['faction'] if 'faction' in cell else 0
ctype = cell['type'] if 'type' in cell else 0
population = cell['population'] if 'population' in cell else 0
army_grid[row][col] = population
pos_tup = (row,col)
tile_typ = 0
if ctype is 3:
generalsa.append(pos_tup)
elif ctype is 1:
cities.append(pos_tup)
elif ctype is 2:
tile_typ = generals.MOUNTAIN
elif ctype is 4:
tile_typ = generals.FOG
if tile_typ != 0:
tile_grid[row][col] = tile_typ
else:
tile_grid[row][col] = 0 if faction is 1 else 1
return update
# Build the neural net game view
def build_game_view(update):
if not ('rows' in update):
return None
world_rows = update['rows']
world_cols = update['cols']
# Build an array of tiles we own.
owned_tiles = []
for row in range(0, MAP_SIZE):
if row >= world_rows:
continue
for col in range(0, MAP_SIZE):
if col >= world_cols:
continue
# Skip if we don't own this tile, or it's not actionable.
tile_army = int(update['army_grid'][row][col])
if update['tile_grid'][row][col] != update['player_index'] or tile_army < 2:
continue
# Build state array. Represent enemies as negative, type of tile in second channel.
input_data = numpy.zeros((2, common.LEARN_MAP_SIZE, common.LEARN_MAP_SIZE))
# Build the data object
owned_tiles.append({
'row': row,
'col': col,
'view': input_data,
})
for ncoli in range(0, common.LEARN_MAP_SIZE):
ncol = col - int(common.LEARN_MAP_SIZE / 2) + ncoli
if ncol < 0 or ncol >= len(update['tile_grid'][0]):
continue
for nrowi in range(0, common.LEARN_MAP_SIZE):
tile_pop = 0
tile_typ = generals.MOUNTAIN
nrow = row - int(common.LEARN_MAP_SIZE / 2) + nrowi
if not (nrow < 0 or nrow >= len(update['tile_grid'])):
tile_typ = update['tile_grid'][nrow][ncol]
# Determine type, faction, and population.
if tile_typ in [generals.MOUNTAIN, generals.FOG, generals.OBSTACLE]:
tile_typ = 0
tile_pop = 0
elif tile_typ == update['player_index']:
if (nrow, ncol) in update['generals']:
tile_typ = 1.0
else:
tile_typ = 0.5
else:
tile_typ = 0.25
input_data[0][nrowi][ncoli] = tile_pop
input_data[1][nrowi][ncoli] = tile_typ
return owned_tiles
<file_sep>FROM tensorflow/tensorflow:latest
RUN apt-get update && apt-get install wget python-pygame python-tk -y
RUN pip install keras h5py websocket-client
<file_sep>Simplified approach
===================
In this simplified approach we ask a much more basic question of the bot - given a tile-centric view of the world (for each tile in all tiles we can move, center the view on that tile in a 10x10 grid) - decide for each of the 4 directions what the predicted Q change might be.
Later we can add memory / other fancy stuff.
| 8a492ad0fccff66d3d9824b869687992b22d3703 | [
"Markdown",
"Python",
"Dockerfile",
"Shell"
] | 13 | Python | paralin/generals-learn | c17eb422c1c6c8b7c645ee411a4ae632fce060a2 | 6f48c14108553f2a6fdb270cd9f9f1375b128e02 |
refs/heads/master | <file_sep>version: '3.4'
services:
pvqmanagement.elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:6.2.4
container_name: elasticsearch
ports:
- "9200:9200"
- "9300:9300"
environment:
ES_JAVA_OPTS: "-Xms512m -Xmx512m"
discovery.type: "single-node"
ELASTIC_PASSWORD: "<PASSWORD>"
transport.host: "127.0.0.1"
pvqmanagement.kibana:
image: docker.elastic.co/kibana/kibana:6.2.4
container_name: kibana
ports:
- "5601:5601"
environment:
ELASTICSEARCH_URL: "http://pvqmanagement.elasticsearch:9200"
ELASTICSEARCH_PASSWORD: "<PASSWORD>"
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class ElasticSearchService {
query: object = {};
data = new Subject<any>();
constructor(private http: HttpClient,
private elasticClient: elasticsearch) {}
autocompleteSearch(searchCriteria): Observable<any> {
const autocompleteQuery = {
'size': 5,
'query': {
'bool': {
'must': []
}
}
};
if (searchCriteria['name'] !== null && searchCriteria['name'] !== '') {
autocompleteQuery.query.bool.must.push(
this.formatAsQuery('name', searchCriteria['name']));
}
if (searchCriteria['age'] !== null && searchCriteria['age'] !== '') {
autocompleteQuery.query.bool.must.push(
this.formatAsQuery('age', searchCriteria['age']));
}
if (searchCriteria['address'] !== null && searchCriteria['address'] !== '') {
autocompleteQuery.query.bool.must.push(
this.formatAsQuery('address', searchCriteria['address']));
}
if (searchCriteria['phone'] !== null && searchCriteria['phone'] !== '') {
autocompleteQuery.query.bool.must.push(
this.formatAsQuery('phone', searchCriteria['phone']));
}
if (searchCriteria['email'] !== null && searchCriteria['email'] !== '') {
autocompleteQuery.query.bool.must.push(
this.formatAsQuery('email', searchCriteria['email']));
}
this.query = autocompleteQuery;
return this.http.post('http://localhost:9200/mock-index5/person/_search',
autocompleteQuery);
}
dataDisplaySearch(fetchSize = 10, fetchFrom = 0) {
this.query['from'] = fetchFrom;
this.query['size'] = fetchSize;
this.http.post('http://localhost:9200/mock-index5/person/_search', this.query).subscribe(
response => {
console.log(response);
this.data.next(response);
}
);
}
formatAsQuery(name, criterion) {
const output = {'match': {}};
output.match[name] = {
'query': criterion,
'operator': 'and'};
return output;
}
}<file_sep>## ElasticAutocompleter
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.0.7.
### Set-up information
In order to set up the application follow these steps:
1. run `npm install`
2. run `npm run prepElastic`
3. run `ng serve`
The command `npm run prepElastic` has the following effect:
1. spin up Docker containers with Kibana & Elasticsearch from a compose file
2. sleep for 45 seconds while Elasticsearch is starting
3. *elasticsearch-index-setup.js* script will create an index and call *elasticSeeder.js* to bulk load 10,000 documents
with addresses
### Additional info
There have been situations where the Docker containers do not respond after setup.
_Just restart Docker and try again, additionally, you might want to increase the sleep-time in package.json_
It takes ~ 2 minutes for Kibana to start, don't panic!<file_sep>let faker = require("faker");
faker.locale = "en_GB";
exports.seed = function(client, index, quantity) {
return new Promise((resolve, reject) => {
let bulkData = [];
for (let i = 0; i < quantity; i++) {
let create = {create: {_index: index.name, _type: index.type, _id: i}};
bulkData.push(create);
bulkData.push(newAddressDocument())
}
client.bulk({body: bulkData}, (error) => {
if (!error)
resolve();
else
reject(new Error(error));
})
});
};
function newAddressDocument() {
let address = {
houseNr: getRandom(1, 200).toString(),
street: faker.address.streetName().toLowerCase(),
city: faker.address.city().toLowerCase(),
county: faker.address.county().toLowerCase(),
postCode: faker.address.zipCode().toLowerCase()
};
address['fullAddress'] = `${address.houseNr} ${address.street} ${address.city} ${address.county} ${address.postCode}`;
return address;
}
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}<file_sep>let seeder = require("./elasticSeeder");
let elasticsearch=require('elasticsearch');
let client = new elasticsearch.Client( {
hosts: [
'elastic:secret@localhost:9200/'
]
});
const index = {name: "elastic-autocompleter", type: "addresses"};
client.ping({
requestTimeout: 10000,
}, function(error) {
if (error) {
console.error('Elasticsearch cluster is down!');
process.exit(1);
} else {
console.log('Connection with Elasticsearch ok!');
}
});
let migration = {
index: index.name,
body: {
"settings": {
"analysis": {
"tokenizer": {
"edgeNGramTokenizer": {
"type": "edge_ngram",
"min_gram": 2,
"max_gram": 15,
"token_chars": ["letter", "digit"]
}
},
"analyzer": {
"autocomplete-analyzer":{
"type": "custom",
"tokenizer": "edgeNGramTokenizer"
}
}
}
},
"mappings": {
[index.type]: {
"_source": {
"excludes": [
"fullAddress"
]
},
"properties": {
"fullAddress": {
"analyzer": "autocomplete-analyzer",
"search_analyzer": "standard",
"type": "text",
"norms": false,
"fields": {
"raw": {
"type": "text",
"analyzer": "standard"
}
}
},
"houseNr": {
"type": "text",
"analyzer": "autocomplete-analyzer",
"search_analyzer": "standard",
"norms": false,
"doc_values": false
},
"street": {
"type": "text",
"analyzer": "autocomplete-analyzer",
"search_analyzer": "standard",
"norms": false,
"doc_values": false
},
"city": {
"type": "text",
"norms": false,
"analyzer": "autocomplete-analyzer",
"search_analyzer": "standard",
"doc_values": false
},
"county": {
"type": "text",
"norms": false,
"analyzer": "autocomplete-analyzer",
"search_analyzer": "standard",
"doc_values": false
},
"postCode": {
"type": "text",
"norms": false,
"analyzer": "autocomplete-analyzer",
"search_analyzer": "standard",
"doc_values": false
}
}
}
}
}
};
client.indices.create(migration)
.then(() => console.log("Elasticsearch index was created successfully"),
err => {
console.error(err);
console.error("Quitting");
process.exit(1);
}
);
async function f() {
await seeder.seed(client, index, 10000).catch(error => {
console.error(error);
process.exit(1)});
console.log("Data was seeded successfully");
}
f();
| 586a42d3baf36da1285f4bd1a2c630dadd37e65c | [
"Markdown",
"TypeScript",
"JavaScript",
"YAML"
] | 5 | YAML | 0scari/ElasticAutocompleter | b4244d508110cc9bb667215bf717ed80e04a40d7 | 92499a274ace8fd3154beb1cd8bf7a0455f0e4ba |
refs/heads/master | <file_sep>#include <boost/filesystem.hpp>
#include <Biovoltron/format/bed.hpp>
#include <Nucleona/app/cli/gtest.hpp>
#include <Nucleona/test/data_dir.hpp>
#include <Nucleona/sys/executable_dir.hpp>
using namespace biovoltron::format;
// header
std::string file_colorByStrand() {
return (nucleona::test::data_dir() / "bed" / "header" / "colorByStrand.txt").string();
}
std::string file_itemRGB() {
return (nucleona::test::data_dir() / "bed" / "header" / "itemRGB.txt").string();
}
std::string file_useScore() {
return (nucleona::test::data_dir() / "bed" / "header" / "useScore.txt").string();
}
// only BED data
std::string file_column_not_consistent_bed() { // error, num of column must be consistent
return (nucleona::test::data_dir() / "bed" / "column_not_consisten.bed").string();
}
std::string file_BED1() { // error, must have at least 3 columns
return (nucleona::test::data_dir() / "bed" / "1_column.bed").string();
}
std::string file_not_bed() { // error
return (nucleona::test::data_dir() / "bed" / "not_bed.txt").string();
}
std::string file_BED3() {
return (nucleona::test::data_dir() / "bed" / "3_column.bed").string();
}
std::string file_BED12() {
return (nucleona::test::data_dir() / "bed" / "12_column.bed").string();
}
// complete BED
std::string file_BED3_with_header() {
return (nucleona::test::data_dir() / "bed" / "3_column_with_header.bed").string();
}
TEST (Header, set)
{
std::ifstream ifs(file_colorByStrand());
bed::Header h;
std::string str;
std::getline(ifs, str);
h.set(str);
std::vector<uint32_t> forward = { 255,0,0 }, reverse = { 0,0,255 };
EXPECT_EQ(str, h.to_string());
EXPECT_EQ("ColorByStrandDemo", h.name);
EXPECT_EQ("Color by strand demonstration", h.description);
EXPECT_EQ(2, h.visibility);
EXPECT_TRUE (h.color_by_strand);
EXPECT_EQ(forward[0], h.forward_strand_color[0]);
EXPECT_EQ(forward[1], h.forward_strand_color[1]);
EXPECT_EQ(forward[2], h.forward_strand_color[2]);
EXPECT_EQ(reverse[0], h.reverse_strand_color[0]);
EXPECT_EQ(reverse[1], h.reverse_strand_color[1]);
EXPECT_EQ(reverse[2], h.reverse_strand_color[2]);
}
TEST (Header, set2)
{
std::string str("track name=\"CHIP_Jaridz_1216G_KD_R2_S9_R1_001_TF_peaks_bed\" description=\"CHIP_Jaridz_1216G_KD_R2_S9_R1_001_TF_peaks_bed\" useScore=0");
bed::Header h;
h.set(str);
EXPECT_EQ(str, h.to_string());
EXPECT_EQ("CHIP_Jaridz_1216G_KD_R2_S9_R1_001_TF_peaks_bed", h.name);
EXPECT_EQ("CHIP_Jaridz_1216G_KD_R2_S9_R1_001_TF_peaks_bed", h.description);
EXPECT_FALSE(h.use_score);
}
TEST (BED, BED3)
{
std::ifstream ifs(file_BED3());
BED< std::tuple <std::string, uint32_t, uint32_t>> bed;
std::string str;
std::getline(ifs, str);
bed.set_bed_data(str);
auto& [ chrom, chrom_start, chrom_end ] = bed.data;
EXPECT_EQ("chr1", chrom);
EXPECT_EQ(85000835, chrom_start);
EXPECT_EQ(85003645, chrom_end);
EXPECT_EQ(str, bed.to_string());
}
TEST (BED, BED12_vector)
{
using TupleType = std::tuple <std::string, uint32_t, uint32_t, std::string, uint16_t, char, uint32_t, uint32_t,
uint32_t, uint16_t, std::vector<uint32_t>, std::vector<uint32_t> >;
BED<TupleType> bed;
std::string str = "chr1\t85000835\t85003645\tuc001aaa\t0\t+\t11873\t11873\t0\t3\t354,109,1189,\t0,739,1347,";
bed.set_bed_data(str);
std::vector<uint32_t> expected_block_sizes = { 354, 109, 1189 };
std::vector<uint32_t> expected_block_starts = { 0, 739, 1347 };
EXPECT_EQ("chr1", std::get<bed::Col::chrom>(bed.data));
EXPECT_EQ(85000835, std::get<bed::Col::chromStart>(bed.data));
EXPECT_EQ(85003645, std::get<bed::Col::chromEnd>(bed.data));
EXPECT_EQ("uc001aaa", std::get<bed::Col::name>(bed.data));
EXPECT_EQ(0, std::get<bed::Col::score>(bed.data));
EXPECT_EQ('+', std::get<bed::Col::strand>(bed.data));
EXPECT_EQ(11873, std::get<bed::Col::thickStart>(bed.data));
EXPECT_EQ(11873, std::get<bed::Col::thickEnd>(bed.data));
EXPECT_EQ(0, std::get<bed::Col::itemRgb>(bed.data));
EXPECT_EQ(3, std::get<bed::Col::blockCount>(bed.data));
EXPECT_EQ(expected_block_sizes, std::get<bed::Col::blockSizes>(bed.data));
EXPECT_EQ(expected_block_starts,std::get<bed::Col::blockStarts>(bed.data));
EXPECT_EQ(str, bed.to_string());
}
TEST (BED, BED12_tuple)
{
using TupleType = std::tuple <std::string, uint32_t, uint32_t, std::string, uint32_t, char, uint32_t, uint32_t,
uint32_t, uint32_t, std::tuple<uint32_t, uint32_t, uint32_t>, std::tuple<uint32_t, uint32_t, uint32_t> >;
BED<TupleType> bed;
std::string str = "chr1\t85000835\t85003645\tuc001aaa\t0\t+\t11873\t11873\t0\t3\t354,109,1189,\t0,739,1347,";
bed.set_bed_data(str);
auto expected_block_sizes = std::make_tuple(354, 109, 1189);
auto expected_block_starts = std::make_tuple(0, 739, 1347);
EXPECT_EQ("chr1", std::get<bed::Col::chrom>(bed.data));
EXPECT_EQ(85000835, std::get<bed::Col::chromStart>(bed.data));
EXPECT_EQ(85003645, std::get<bed::Col::chromEnd>(bed.data));
EXPECT_EQ("uc001aaa", std::get<bed::Col::name>(bed.data));
EXPECT_EQ(0, std::get<bed::Col::score>(bed.data));
EXPECT_EQ('+', std::get<bed::Col::strand>(bed.data));
EXPECT_EQ(11873, std::get<bed::Col::thickStart>(bed.data));
EXPECT_EQ(11873, std::get<bed::Col::thickEnd>(bed.data));
EXPECT_EQ(0, std::get<bed::Col::itemRgb>(bed.data));
EXPECT_EQ(3, std::get<bed::Col::blockCount>(bed.data));
EXPECT_EQ(expected_block_sizes, std::get<bed::Col::blockSizes>(bed.data));
EXPECT_EQ(expected_block_starts,std::get<bed::Col::blockStarts>(bed.data));
EXPECT_EQ(str, bed.to_string());
}
TEST (BED, set_bed_data)
{
std::string str("chr1\t88298901\t88300500");
BED< std::tuple <std::string, uint32_t, uint32_t>> bed;
bed.set_bed_data(str);
EXPECT_EQ(str, bed.to_string());
}
TEST (BED, get_obj)
{
using TupleType = std::tuple <std::string, uint32_t, uint32_t>;
std::ifstream ifs(file_BED3());
BED<TupleType > bed;
BED< TupleType>::get_obj(ifs, bed);
auto& [ chrom, chrom_start, chrom_end ] = bed.data;
EXPECT_EQ("chr1", chrom);
EXPECT_EQ(85000835, chrom_start);
EXPECT_EQ(85003645, chrom_end);
}
TEST (BED, dump)
{
using TupleType = std::tuple <std::string, uint32_t, uint32_t>;
std::string ans = "track name=\"ItemRGBDemo\" description=\"Item RGB demonstration\" visibility=2 itemRgb=\"On\"\nchr1\t85000835\t85003645\nchr1\t85100217\t85106585\nchr1\t85153339\t85154239\n";
std::ifstream ifs(file_BED3_with_header());
BED< TupleType> bed;
BEDHeader h;
std::vector<BED< TupleType>> v_bed;
ifs>>h;
// fill BED objects
while(BED< TupleType>::get_obj(ifs, bed))
{
bed.header = h;
v_bed.emplace_back(std::move(bed));
}
// dump BED objects to ostream
std::ostringstream oss;
BED< TupleType>::dump(oss, v_bed);
EXPECT_EQ( ans, oss.str());
}
TEST (Header_and_BED, iostream)
{
using TupleType = std::tuple <std::string, uint32_t, uint32_t>;
std::string ans = "track name=\"ItemRGBDemo\" description=\"Item RGB demonstration\" visibility=2 itemRgb=\"On\"\nchr1\t85000835\t85003645\n";
std::ifstream ifs(file_BED3_with_header());
std::ostringstream oss;
BED< TupleType> bed;
BEDHeader h;
ifs>>h;
ifs>>bed;
oss<<h;
oss<<bed;
EXPECT_EQ( ans, oss.str());
}
<file_sep>#pragma once
#include <vector>
/// @class IsVectorType template class
/// @brief served as a simple type verifier indicating a to-be-tested object corresponds to std::vector types or not
/// @tparam T a type parameter
template < typename T >
struct IsVectorType
{
/// @memberof value corresponds to the value of false by default
static const bool value = false;
};
/// @brief specialized form of the IsVectorType, with the to-be-tested object specialized as the type of std::vector<T>
template < typename T >
struct IsVectorType < std::vector <T> >
{
/// @memberof value corresponds to the value of true
static const bool value = true;
};
<file_sep>/// @file bed.hpp
/// @brief A parser of bed format file
#pragma once
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/spirit/include/qi.hpp>
#include <Biovoltron/format/bed/header.hpp>
#include <Biovoltron/format/bed/is_tuple_type.hpp>
#include <Biovoltron/format/bed/is_vector_type.hpp>
#include <vector>
#include <tuple>
namespace biovoltron::format{
using BEDHeader = bed::Header;
/// @class BED
/// @brief BED class which store BED data and BED header.
///
/// Member variable<br>
/// BEDHeader& header<br>
/// TupleType data<br>
///
/// Member functions<br>
/// to_string<br>
/// set_bed_data<br>
/// dump<br>
/// get_obj<br>
/// fill<br>
/// to_comma_delimited_string<br>
/// to_string<br>
///
/// Non-member functions<br>
/// operator>>
/// operator<<
///
/// This class store BED data and header from an BED format file.
/// The BED class only stores one data entry from the BED file.
/// reference.
template<class TupleType = std::tuple <std::string, uint32_t, uint32_t> >
class BED
{
public:
static_assert( IsTupleType<TupleType>::value, "ARGUMENT IS NOT A TUPLE");
void set_bed_data(std::string& str)
{
constexpr auto tup_size = std::tuple_size<TupleType>::value;
std::vector<std::string> split_string;
boost::split( split_string, str, boost::is_any_of( " \t" ), boost::token_compress_on );
fill<TupleType, tup_size>(data, split_string);
}
friend std::istream& operator>>(std::istream& is, BED<TupleType>& bed)
{
get_obj(is, bed);
return is;
}
friend std::ostream& operator<<(std::ostream& os, BED<TupleType>& bed)
{
os << bed.to_string()<<"\n";
return os;
}
std::string to_string()
{
std::string str;
constexpr auto tup_size = std::tuple_size<TupleType>::value;
this->to_string<TupleType, tup_size>(this->data, str);
str.erase(str.end()-1);
return str;
}
static std::istream& get_obj(std::istream& is, BED<TupleType>& bed)
{
std::string str;
if(std::getline(is, str))
bed.set_bed_data(str);
return is;
}
static void dump(std::ostream& os, std::vector<BED>& v_bed)
{
if(v_bed.size() == 0)
return;
os << v_bed[0].header.to_string() << "\n";
for(auto& bed: v_bed)
os << bed.to_string() << "\n";
}
template<int i, class TUPLETYPE>
using element_t = std::tuple_element_t<i, TUPLETYPE>;
template<class TUPLETYPE, int i>
void fill(TUPLETYPE& t, std::vector<std::string>& split_str)
{
if constexpr(i == 0)
return;
else
{
fill<TUPLETYPE, i-1>(t, split_str);
if constexpr( std::is_same<char,
element_t<i-1, TUPLETYPE>
>::value )
{
std::get<i-1>(t) = split_str[i-1][0];
}
else if constexpr ( std::is_integral<element_t<i-1, TUPLETYPE>>::value)
{
std::get<i-1>(t) = stoi(split_str[i-1]);
}
else if constexpr( std::is_same<std::string,
element_t<i-1, TUPLETYPE>
>::value )
{
std::get<i-1>(t) = split_str[i-1];
}
else if constexpr( std::is_same<std::string,
element_t<i-1, TUPLETYPE>
>::value )
{
std::get<i-1>(t) = split_str[i-1];
}
else if constexpr( IsVectorType<
element_t<i-1, TUPLETYPE>
>::value )
{
boost::spirit::qi::phrase_parse(split_str[i-1].begin(), split_str[i-1].end(),
boost::spirit::qi::int_ % ',', boost::spirit::ascii::space, std::get<i-1>(t));
}
else // tuple type
{
using nested_tuple = element_t<i-1, TUPLETYPE>;
static_assert( IsTupleType<nested_tuple>::value, "ARGUMENT IS NOT A TUPLE");
std::vector<std::string> split_str2;
boost::split( split_str2, split_str[i-1], boost::is_any_of( "," ), boost::token_compress_on );
fill<nested_tuple, std::tuple_size<nested_tuple>::value>(std::get<i-1>(t), split_str2);
}
}
}
template<class...Ts>
void to_comma_delimited_string( std::tuple<Ts...>& t, std::string& str)
{
std::apply ([&str] (const auto &... elem)
{
str += ((std::to_string(elem) + ",") + ...);
},
t);
}
template<class TUPLETYPE, int i>
void to_string(TUPLETYPE& t, std::string& str)
{
if constexpr(i == 0)
return;
else
{
to_string<TUPLETYPE, i-1>(t, str);
if constexpr( std::is_same<char,
element_t<i-1, TUPLETYPE>
>::value )
{
str += std::get<i-1>(t);
}
else if constexpr ( std::is_integral<element_t<i-1, TUPLETYPE>>::value)
{
str += std::to_string(std::get<i-1>(t));
}
else if constexpr( std::is_same<std::string,
element_t<i-1, TUPLETYPE>
>::value )
{
str += std::get<i-1>(t);
}
else if constexpr( IsVectorType<
element_t<i-1, TUPLETYPE>
>::value )
{
for(auto it = std::get<i-1>(t).begin(); it != std::get<i-1>(t).end(); it++)
str += std::to_string(*it) + ",";
}
else // tuple type
{
using nested_tuple = element_t<i-1, TUPLETYPE>;
//static_assert( IsTupleType<nested_tuple>::value, "ARGUMENT IS NOT A TUPLE");
to_comma_delimited_string(std::get<i-1>(t), str);
}
str += "\t";
}
}
BEDHeader header;
TupleType data;
};
}
<file_sep>/// @file header.hpp
/// @brief Header of BED object
#pragma once
#include <sstream>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/tokenizer.hpp>
#include <map>
#include <vector>
#include <cassert>
#include <string>
namespace biovoltron::format::bed {
class Header
{
public:
Header():item_RGB(false),
use_score(false),
color_by_strand(false)
{}
void set(std::string& str)
{
using boost::tokenizer;
using boost::escaped_list_separator;
using so_tokenizer = tokenizer<escaped_list_separator<char> >;
track_line = str;
so_tokenizer tok(str, escaped_list_separator<char>("\\", " \t=", "\""));
assert( *tok.begin() == "track" );
for( auto it = tok.begin();
it != tok.end();
++it)
{
if(*it == "colorByStrand")
{
color_by_strand = true;
++it;
//boost::spirit::qi::phrase_parse(it->begin(), it->end(), boost::spirit::qi::int_ % ',', boost::spirit::ascii::space,
//forward_strand_color);
std::vector<std::string> split_string;
boost::split( split_string, *it, boost::is_any_of( " \t," ), boost::token_compress_on );
for(int i = 0; i < 3; i++)
forward_strand_color.emplace_back(stoi(split_string[i]));
for(int i = 3; i < 6; i++)
reverse_strand_color.emplace_back(stoi(split_string[i]));
}
else if(*it == "useScore")
{
++it;
use_score = ( *it == "0" ) ? false : true;
}
else if(*it == "itemRgb")
{
++it;
if(*it == "On")
item_RGB = true;
else
item_RGB = false;
}
else if(*it == "name")
{
name = *(++it);
}
else if(*it == "description")
{
description = *(++it);
}
else if(*it == "visibility")
{
++it;
visibility = stoi(*it);
//boost::spirit::qi::phrase_parse(it->begin(), it->end(), boost::spirit::qi::int_, boost::spirit::ascii::space,
//visibility);
}
}
}
friend std::istream& operator>>(std::istream& is, Header& header)
{
std::string str;
std::getline(is, str);
header.set(str);
return is;
}
friend std::ostream& operator<<(std::ostream& os, const Header& header)
{
os << header.to_string()<<"\n";
return os;
}
std::string to_string() const
{
return track_line;
}
std::string track_line, name, description;
uint32_t visibility;
bool item_RGB, use_score, color_by_strand;
std::vector<uint8_t> forward_strand_color, reverse_strand_color;
};
enum Col
{
chrom, chromStart, chromEnd, name, score, strand, thickStart, thickEnd, itemRgb, blockCount, blockSizes, blockStarts
};
}
<file_sep># bed
provides a flexible way to define the `data lines` that are `displayed` in an `annotation track`
主要功能:
- 可以看reads align到哪個chromosome的哪個區段
其他功能(optional):
- 給 BED line名字
- 給分數
- 給方向
- 給轉譯的區段位置
- 給BED line顏色
- 給各個Exon block的位置
前三個fields是必要的, 剩下9個是optional的
bed檔中, 每個line的field數量必須一致
如果順位高的field有填, 就算順位低的field不想填也要填
BED fields in custom tracks can be whitespace-delimited or tab-delimited
只有custom tracks的開頭幾行能有header lines, 功用是來協助browser設定
這幾行的開頭都必須是browser or track
header lines不能夠轉成`BigBed`
如果你的data很大(超過50MB), 你應該用`bigBed` data format
**chrom** - The name of the **chromosome** (e.g. chr3, chrY, chr2_random) or **scaffold** (e.g. scaffold10671).
>**scaffold**:
In genomic mapping, a series of contigs that are in the right order but not necessarily connected in one continuous stretch of sequence.
```
[chromStart, chromEnd)
```
**chromStart** - The first base in a chromosome is numbered 0.
**chromEnd** - The chromEnd base is not included in the display of the feature, 是開區間
**name** - The name of the BED line.
**score** - A score between 0 and 1000.
**strand** - Defines the strand. Either "." (=no strand) or "+" or "-".
**thickStart** - The starting position at which the feature is drawn thickly (for example, the `start codon` in gene displays).
**thickEnd** - The ending position at which the feature is drawn thickly (for example the `stop codon` in gene displays).
**itemRgb** - An RGB value of the form R,G,B (e.g. 255,0,0). If the track line itemRgb attribute is set to "On", this RBG value will determine the display color of the data contained in this BED line.
**blockCount** - The number of blocks (exons) in the BED line.
**blockSizes** - A comma-separated list of the block sizes.
**blockStarts** - A comma-separated list of block starts. All of the blockStart positions should be calculated relative to chromStart.
e.g.
```
track name=pairedReads description="Clone Paired Reads" useScore=1
chr22 1000 5000 cloneA 960 + 1000 5000 0 2 567,488, 0,3512
chr22 2000 6000 cloneB 900 - 2000 6000 0 2 433,399, 0,3601
```
track name=pairedReads description="Clone Paired Reads" useScore=1
| **chrom** | **chromStart** | **chromEnd** | **name** | **score** | **strand** | **thickStart** | **thickEnd** | **itemRgb** | **blockCount** | **blockSizes** | **blockStarts** |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| chr22 | 1000 | 5000 | cloneA | 960 | + | 1000 | 5000 | 0 |2 | 567,488, | 0,3512 |
| chr22 | 2000 | 6000 | cloneB | 900| - | 2000 | 6000 | 0 | 2 | 433,399, | 0,3601 |
---
# bed parser
generic bed parser 給定不同 type 來parse data
用法請見unit_test
| 4eb29946dac37013f1b3b2e1b54270959798ec05 | [
"Markdown",
"C++"
] | 5 | C++ | weisystak/bed-parser | 7dd21d15400cd1d869d8c277b619715ea5f5186f | 14a1e0ce1e4744a24b0bd247a02d1187057ae841 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
Predicitve_Analytics.py
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import csv
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
from sklearn.model_selection import GridSearchCV
from sklearn import svm
from sklearn.svm import SVC
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import VotingClassifier
df = pd.read_csv("D:/UB Courses/cse587/Assignment1/data.csv", delimiter = ",")
y = df.iloc[:,-1]
y = y.to_numpy()
df = df.iloc[:,:-1]
df_normalized = (df - df.min())/ (df.max() - df.min())
X = df.to_numpy()
X = df_normalized.to_numpy()
x_train,x_test,y_train,y_test=train_test_split(X,y,test_size=0.2)
'''
no_of_classes = 11
knn = KNeighborsClassifier()
clf = SVC()
log_reg = LogisticRegression()
decision_tree = DecisionTreeClassifier()
'''
def Accuracy(y_true,y_pred):
"""
:type y_true: numpy.ndarray
:type y_pred: numpy.ndarray
:rtype: float
"""
correct = 0
for i in range(len(y_true)):
if(y_true[i] == y_pred[i]):
correct += 1
return correct / float(len(y_true)) * 100.0
def Recall(y_true,y_pred):
"""
:type y_true: numpy.ndarray
:type y_pred: numpy.ndarray
:rtype: float
"""
cm = ConfusionMatrix(y_true, y_pred)
recall = np.diag(cm) / np.sum(cm, axis = 1)
return np.mean(recall)
def Precision(y_true,y_pred):
"""
:type y_true: numpy.ndarray
:type y_pred: numpy.ndarray
:rtype: float
"""
cm = ConfusionMatrix(y_true, y_pred)
precision = np.diag(cm) / np.sum(cm, axis = 0)
return np.mean(precision)
def WCSS(Clusters):
"""
:Clusters List[numpy.ndarray]
:rtype: float
"""
wcss = 0
for i, row in enumerate(clusters):
if len(row) == 0:
continue
cluster_centroids = np.mean(row)
wcss += np.sum(np.linalg.norm(row - cluster_centroids, axis=1))
return wcss
<<<<<<< HEAD
=======
>>>>>>> 9d009247d42f5eb614eb92166c5203b0f6728290
def confusion_matrix(y_pred, y_test, no_of_classes):
result=(y_test*(no_of_classes+1))+y_pred
a = np.histogram(result, bins=range(0,((no_of_classes+1)**2)+1))
final_conf=a[0].reshape((no_of_classes+1,no_of_classes+1))
return final_conf
def plot_(y_pred, y_test, no_of_classes):
data = confusion_matrix(y_pred, y_test,11)
plt.imshow(data,cmap='Wistia')
for x in range(data.shape[0]):
for y in range(data.shape[1]):
plt.text(x,y,data[x, y],horizontalalignment='center',verticalalignment='center')
plt.xlabel('predicted')
plt.ylabel('actual')
plt.grid(False)
plt.colorbar()
plt.show()
'''KNN Algorithm implementation'''
def calculate_distance_matrix(A,b,Y_train):
d = np.linalg.norm(A - b, axis = 1)
d = np.column_stack((d, Y_train))
d = sorted(d, key =(lambda x: x[0]))
d = np.asarray(d)
return d
def KNN(X_train,X_test,Y_train, k):
predicted_labels = []
for x_t in X_test:
distance_matrix = calculate_distance_matrix(X_train, x_t, Y_train)
distance_matrix = distance_matrix[0:k]
test_labels = distance_matrix[::, -1]
test_labels = test_labels.astype("int64")
counts = np.bincount(test_labels)
label = np.argmax(counts)
predicted_labels.append(label)
predicted_labels = np.asarray(predicted_labels)
return predicted_labels
''' End of KNN Classifier Algorithm'''
'''Starting Random Forest Algorithm'''
'''This Function will check the number of classes (between 1-11) for the particular'''
def number_of_class_in_a_set(input_set):
label = input_set[:, -1]
unique_classes = np.unique(label)
return unique_classes
'''This function will check which class has maximum number of counts in a given dataset'''
def max_class(input_val):
label= input_val[:, -1]
max_val=0
index=[]
unique_classes,counts_unique_classes = np.unique(label, return_counts=True)
max_val=max(counts_unique_classes)
index=[i for i, e in enumerate(counts_unique_classes) if e == max_val]
max_class = unique_classes[index[0]]
return max_class
'''Calculate all the possible splits'''
def all_splits(input_values, features):
splits = {}
column=np.random.choice(input_values.shape[1],features )
for column_index in column:
values = input_values[:, column]
unique_values = np.unique(values)
splits[column_index] = unique_values
return splits
''' Creating Entropy for each node'''
def class_entropy(data):
label = data[:, -1]
unique_classes,counts_unique_classes = np.unique(label, return_counts=True)
p = counts_unique_classes / counts_unique_classes.sum()
class_entropy = sum(p * -np.log2(p))
return class_entropy
'''Creating the whole impurity using weighted average'''
def entropy_impurity(n1, n2):
n = len(n1) + len(n2)
c1 = len(n1) / n
c2 = len(n2) / n
entropy = (c1 * class_entropy(n1) + c2 * class_entropy(n2))
return entropy
'''Creating Node for a Particular Decision'''
def data_decision(input_feature, split_decision, threshold):
divided_nodes = input_feature[:, split_decision]
n1 = input_feature[divided_nodes <= threshold]
n2 = input_feature[divided_nodes > threshold]
return n1, n2
'''Creating the decision node'''
def decision_node_create(input_feature, input_feature_splits):
max_entropy = 100000000
split_column=0
split_value=0
for i in input_feature_splits:
for j in input_feature_splits[i]:
n1, n2 = data_decision(input_feature, i,j)
entropy = entropy_impurity(n1, n2)
if entropy <= max_entropy:
max_entropy = entropy
split_column = i
split_value = j
return split_column, split_value
'''Decision Tree Training'''
def decision_tree(df, count=0, random_features=7):
if count == 0:
global column,sample_size
column = df.columns
sample_size=2
data=df.values
else:
data = df
classes=number_of_class_in_a_set(data)
num_classes=len(classes)
if ((num_classes==1)) or (len(data) < sample_size) or (count == 10):
feature_class = max_class(data)
return feature_class
else:
count += 1
potential_splits = all_splits(data, random_features)
feature, value = decision_node_create(data, potential_splits)
n1, n2 = data_decision(data, feature, value)
if len(n1) == 0 or len(n2) == 0:
feature_class = max_class(data)
return feature_class
feature_name = column[feature]
decision = "{} <= {}".format(feature_name, value)
tree = {decision: []}
c1 = decision_tree(n1, count,random_features)
c2 = decision_tree(n2, count,random_features)
if c1 == c2:
tree = c1
else:
tree[decision].append(c1)
tree[decision].append(c2)
return tree
''' Bagging the Data'''
def bagging(train_df):
random_index = np.random.randint(low=0, high=len(train_df),size=400)
data_with_replacement = train_df.iloc[random_index]
return data_with_replacement
'''This function will create an example tree from the questions'''
def answer_prediction(example, tree):
question = list(tree.keys())[0]
feature_name, comparison_operator, value = question.split(" ")
if int(example[feature_name]) <= float(value):
answer = tree[question][0]
else:
answer = tree[question][1]
if not isinstance(answer, dict):
return answer
else:
residual_tree = answer
return answer_prediction(example, residual_tree)
''' Main Algorithm this will call the decision tree'''
def random_forest_classifier(train_df,features):
random_forest = []
number_of_trees=50
for i in range(number_of_trees):
data_with_replacement = bagging(train_df)
tree = decision_tree(data_with_replacement, random_features=features)
random_forest.append(tree)
return random_forest
'''Decision Tree Prediction'''
def decision_tree_predictions(test_df, tree):
predictions = test_df.apply(answer_prediction, args=(tree,), axis=1)
return predictions
''' This will Predict the test data using decision tree'''
def random_forest_predictions(test_df, forest):
decisions = {}
for i in range(len(forest)):
column_name = "tree_{}".format(i)
predictions = decision_tree_predictions(test_df, tree=forest[i])
decisions[column_name] = predictions
decisions = pd.DataFrame(decisions)
all_predictions = decisions.mode(axis=1)[0]
return all_predictions
def RandomForest(X_train,Y_train,X_test):
"""
:type X_train: numpy.ndarray
:type X_test: numpy.ndarray
:type Y_train: numpy.ndarray
:rtype: numpy.ndarray
"""
df1=pd.DataFrame(x_train)
df2=pd.DataFrame(y_train)
test_df=pd.DataFrame(x_test)
train_df=pd.concat((df1,df2),axis=1)
train_df,test_df=create_dataframe(x_train,y_train,x_test)
train_df["label"] = train_df.iloc[:,-1]
train_df.drop(train_df.columns[48], inplace=True)
column_names = []
for column in train_df.columns:
column=str(column)
name = column.replace(" ", "_")
column_names.append(name)
train_df.columns = column_names
test_column_names = []
for column in test_df.columns:
column=str(column)
name = column.replace(" ", "_")
test_column_names.append(name)
test_df.columns = test_column_names
forest = random_forest_classifier(train_df,features=7)
predictions = random_forest_predictions(test_df, forest)
y_test=predictions.to_numpy()
return y_test
def PCA(x_train, N):
classes = []
data = []
rows = -1
cols=0
with open('D:/UB Courses/cse587/Assignment1/data.csv', 'r') as f:
file = csv.reader(f, delimiter=' ')
for i in file:
rows += 1
file1 = pd.read_csv('D:/UB Courses/cse587/Assignment1/data.csv')
for i in file1:
cols += 1
#calculate the mean of data
mean_data = x_train.mean(0)
#normalization
normalized_data = x_train - mean_data
data_cov = np.cov(normalized_data.T)
eigenvalues, eigenvectors = np.linalg.eig(data_cov)
top_eigen_components = eigenvectors[:,0:N]
sample_data = x_train.dot(top_eigen_components)
return sample_data
''' K-Means Clustering Algorithm Implementation'''
def create_empty_clusters(k):
clusters = []
for i in range(k):
clusters.append([])
return clusters
def assigning_clusters(X,cluster_centers):
clusters = create_empty_clusters(cluster_centers.shape[0])
for i in range(len(X)):
dist = np.linalg.norm(X[i] - cluster_centers, axis = 1)
dist = np.asarray(dist)
min_dist_index = np.argmin(dist)
clusters[min_dist_index].append(X[i])
clusters = np.asarray(clusters)
return clusters
def Kmeans(X_train, N):
X = X_train
k = N
cluster_centers_old = np.zeros((k, X.shape[1]))
cluster_centers = X[np.random.randint(X.shape[0], size=k)] #Randomly selecting data points to be initial cluster centroids
error = np.sum(np.linalg.norm(cluster_centers - cluster_centers_old, axis=1))
while error != 0:
clusters = assigning_clusters(X, cluster_centers)
cluster_centers_old = deepcopy(cluster_centers)
for i, row in enumerate(clusters):
if len(row) == 0:
continue
cluster_centers[i] = np.mean(row)
error = np.sum(np.linalg.norm(cluster_centers - cluster_centers_old, axis=1))
return clusters
''' End of K-means clustering algorithm'''
def SklearnSupervisedLearning(x_train,y_train,x_test):
knn_(x_train, x_test, 5)
knn_grid(x_train, x_test, no_of_classes)
SVM_(x_train, x_test, y_test)
SVM_grid(x_train, x_test, y_test)
logReg(x_train, x_test, y_test)
logReg_grid(x_train, x_test, y_test)
DT(x_train, x_test, y_test)
DT_grid(x_train, x_test, y_test)
def SklearnVotingClassifier(x_train,y_train,x_test):
estimators=[('knn', knn), ('svm', clf), ('DT',decision_tree), ('log_reg', log_reg)]
ensemble = VotingClassifier(estimators, voting='hard')
ensemble.fit(x_train, y_train)
print(ensemble.score(x_test, y_test))
y_pred = ensemble.predict(x_test)
return y_pred
def knn_(x_train, x_test, N):
knn = KNeighborsClassifier(n_neighbors = 5)
knn.fit(x_train, y_train)
y_pred = knn.predict(x_test)
print(metrics.accuracy_score(y_test, y_pred))
plot_(y_pred, y_test, no_of_classes)
return y_pred
def knn_grid(x_train, x_test, N):
params_knn = {'n_neighbors': [N],
'weights' : ['distance'],
'metric' : ['euclidean']}
knn_gs = GridSearchCV(KNeighborsClassifier(), params_knn, verbose=1, cv=5)
knn_gs.fit(x_train, y_train)
y_pred = knn_gs.predict(x_test)
print('knn: {}'.format(knn_gs.score(x_test, y_test)))
plot_(y_pred, y_test, N)
return y_pred
def SVM_(x_train, x_test, y_test):
scaling = MinMaxScaler(feature_range=(-1,1)).fit(x_train)
x_train = scaling.transform(x_train)
x_test = scaling.transform(x_test)
#clf = svm.NuSVC(gamma='scale')
#clf = svm.SVC(kernel='linear', gamma = 'scale')
#clf = svm.SVC(kernel='rbf',gamma = 'scale')
clf = svm.SVC(kernel='poly',gamma = 'scale')
clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
plot_(y_pred, y_test, no_of_classes)
return y_pred
def SVM_grid(x_train, x_test, y_test):
param_grid = {'C': [10],
'gamma': [ 0.1],
'kernel': ['linear']}
grid = GridSearchCV(SVC(), param_grid, refit = True, verbose = 1)
grid.fit(x_train, y_train)
y_pred = grid.predict(x_test)
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
plot_(y_pred, y_test, no_of_classes)
return y_pred
def logReg(x_train, x_test, y_test):
scaling = MinMaxScaler(feature_range=(-1,1)).fit(x_train)
x_train = scaling.transform(x_train)
x_test = scaling.transform(x_test)
log_reg = LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, l1_ratio=None, max_iter=5000,
multi_class='auto', n_jobs=None, penalty='l2',
random_state=0, solver='lbfgs', tol=0.0001, verbose=0,
warm_start=False)
log_reg.fit(x_train, y_train)
y_pred = log_reg.predict(x_test)
print('log_reg: {}'.format(log_reg.score(x_test, y_test)))
plot_(y_pred, y_test, no_of_classes)
return y_pred
def logReg_grid(x_train, x_test, y_test):
hyperparameters = dict(C=np.logspace(0,4), penalty=['l2'])
log = Gridsearchcv(LogisticRegression(), hyperparameters, cv=2)
log.fit(x_train, y_train)
y_pred = log.predict(x_test)
print('log_reg_grid: {}'.format(log.score(x_test, y_test)))
plot_(y_pred, y_test, no_of_classes)
return y_pred
def DT(x_train, x_test, y_test):
decision_tree = DecisionTreeClassifier(random_state=0, max_depth=11)
decision_tree.fit(x_train, y_train)
y_pred = decision_tree.predict(x_test)
print('DT: {}'.format(decision_tree.score(x_test, y_test)))
plot_(y_pred, y_test, no_of_classes)
return y_pred
def DT_grid(x_train, x_test, y_test):
parameters = dict(criterion = ['gini'],
max_depth = [6,10])
dt_grid = GridSearchCV(DecisionTreeClassifier(), parameters )
dt_grid.fit(x_train, y_train)
y_pred = dt_grid.predict(x_test)
print('DT_grid: {}'.format(dt_grid.score(x_test, y_test)))
plot_(y_pred, y_test, no_of_classes)
return y_pred
"""
Create your own custom functions for Matplotlib visualization of hyperparameter search.
Make sure that plots are labeled and proper legends are used
"""
#https://towardsdatascience.com/knn-using-scikit-learn-c6bed765be75
#https://towardsdatascience.com/ensemble-learning-using-scikit-learn-85c4531ff86a
#https://www.datacamp.com/community/tutorials/svm-classification-scikit-learn-python
#https://datascience.stackexchange.com/questions/989/svm-using-scikit-learn-runs-endlessly-and-never-completes-execution
#https://www.geeksforgeeks.org/svm-hyperparameter-tuning-using-gridsearchcv-ml/
#https://towardsdatascience.com/ensemble-learning-using-scikit-learn-85c4531ff86a
#https://chrisalbon.com/machine_learning/model_selection/hyperparameter_tuning_using_grid_search/
#https://scikit-learn.org/stable/modules/tree.html
#https://machinelearningmastery.com/implement-random-forest-scratch-python/
#https://www.python-course.eu/Random_Forests.php
#https://intellipaat.com/blog/what-is-random-forest-algorithm-in-python/<file_sep># Predictive-Analytics-CSE-587-PA1
The objective of this assignment is to get started with Predictive Analytics. The goals of the assessment is to implement a predictive analytics algorithm from scratch and to create a Scikit-learn predictive analytics pipeline and perform visualization using Matplotlib.
PART - 1 Implementation of Machine Learning Algorithms ● Implement Supervised Learning algorithms K-NearestNeighbour and Random Forest
● Implement Dimensionality Reduction using PCA
● Implement K-Means Clustering
● Implement Evaluation measure Accuracy, Recall, Precision, Within cluster Sum of squares
PART - 2 Scikit-Learn Pipeline for Machine Learning
● Using the Scikit-learn library, implement supervised learning algorithms SVM, Logistic Regression, Decision tree, KNN
● Using the Scikit-learn library create an ensemble model using the voting classifier of the above-mentioned algorithm.
● Create visualization using Matplotlib library, of the confusion matrix for each of the 5 classifiers (including the ensemble). Evaluation:- Total of 45 Points
● Implementation of supervised algorithms SVM, Logistic Regression, Decision Tree, KNN, using Scikit-learn and report accuracy (10 Points)
● Creating an ensemble model using the voting classifier of the above-mentioned algorithms and report accuracy (10 Points)
● Creating visualizations using Matplotlib library for the confusion matrix of each model (use subplot) (10 Points)
● Perform Grid search on hyperparameters of SVM, Decision Tree and KNN and create plots using Matplotlib (15 Points)
© 2020 GitHub, Inc.
| e0d67e8ebacf1d9e759ef2d48a4adc688daee546 | [
"Markdown",
"Python"
] | 2 | Python | akashroy77/CSE-587-PA1-Predictive-Analytics | 252ec0d58d1fc2f72e174cf834167501d3f8a2a7 | 41e9b6e8799d693918440ab9a4f4e355bcc96f14 |
refs/heads/master | <repo_name>hashfi104/bootcamp_bl<file_sep>/Bootcamp/main.swift
//
// main.swift
// Bootcamp
//
// Created by <NAME> on 10/09/19.
// Copyright © 2019 Bukalapak. All rights reserved.
//
import Foundation
enum AnimalName: String {
case deer = "Rusa"
case goat = "Kambing"
case sheep = "Domba"
case elephant = "Gajah"
}
var animals : [Animal] = []
func input() -> String {
let keyboard = FileHandle.standardInput
let inputData = keyboard.availableData
if let text = NSString(data: inputData, encoding:String.Encoding.utf8.rawValue) {
return text as String
}
return ""
}
func addAnimal(data: [String]){
if let age = Int(data[1]), let weight = Int(data[2]) {
let animalName = data.first!
var animal : Animal?
if let animalName = AnimalName.init(rawValue: animalName) {
switch animalName {
case .deer :
animal = Deer(age: age, weight: weight)
case .goat :
animal = Goat(age: age, weight: weight)
case .sheep :
animal = Sheep(age: age, weight: weight)
case .elephant :
animal = Elephant(age: age, weight: weight)
}
} else {
animal = Animal(name: data.first!, age: age, weight: weight)
}
if let animal = animal {
animals.append(animal)
}
}
}
func showActivity(day: Int) {
print("Hari #\(day+1)")
animals.forEach { (animal) in
animal.dayActivity(day: day)
animal.nightActivity()
}
}
let firstArray = readLine()?.split {$0 == " "}.map (String.init)
if let stringArray = firstArray {
if let countString = stringArray.first {
if let count = Int(countString) {
// Input count
for _ in 0..<count {
let array = readLine()?.split {$0 == " "}.map (String.init)
addAnimal(data: array!)
}
}
// Day Count
if let dayCount = Int(stringArray[1]) {
for i in 0..<dayCount {
showActivity(day: i)
}
}
}
}
<file_sep>/Bootcamp/Class/Animal.swift
//
// File.swift
// Bootcamp
//
// Created by <NAME> on 11/09/19.
// Copyright © 2019 Bukalapak. All rights reserved.
//
import Foundation
class Animal {
var name : String?
var age : Int?
var weight : Int?
var maxWeight: Int {
return 100
}
var minWeight: Int {
return 10
}
var weightGain: Int {
return 3
}
var weightLoss: Int {
return 1
}
init(name: String, age: Int, weight: Int) {
self.name = name
self.age = age
self.weight = weight
}
func dayActivity(day: Int) {
if let w = weight, let a = age, let name = name {
switch w {
case 1..<minWeight:
let tempW = w + weightGain
weight = (tempW < minWeight ? minWeight : tempW)
case minWeight..<maxWeight:
weight = w + weightGain
default:
weight = w - weightLoss
}
// Value for age
if day != 0 {
age = a + 1
}
print("Kondisi \(name) di siang hari --> usia: \(age!) -- berat: \(weight!)")
}
}
func nightActivity() {
if let w = weight, let name = name {
switch w {
case 1..<minWeight:
weight = minWeight
default:
weight = w - 1
}
print("Kondisi \(name) di malam hari --> usia: \(age!) -- berat: \(weight!)")
}
}
}
<file_sep>/Bootcamp/Class/Goat.swift
//
// Goat.swift
// Bootcamp
//
// Created by <NAME> on 12/09/19.
// Copyright © 2019 Bukalapak. All rights reserved.
//
import Cocoa
class Goat: Animal {
override var maxWeight: Int {
return 70
}
override var weightLoss: Int {
return 2
}
init(age: Int, weight: Int) {
super.init(name: "Kambing", age: age, weight: weight)
}
}
<file_sep>/Bootcamp/Class/Elephant.swift
//
// Elephant.swift
// Bootcamp
//
// Created by <NAME> on 12/09/19.
// Copyright © 2019 Bukalapak. All rights reserved.
//
import Cocoa
class Elephant: Animal {
override var weight: Int? {
get {
return super.weight
}
set {
if let newValue = newValue,
newValue > maxWeight {
super.weight = maxWeight
} else {
super.weight = newValue
}
}
}
override var maxWeight: Int {
return 500
}
override var weightGain: Int {
return 5
}
override var weightLoss: Int {
return 3
}
init(age: Int, weight: Int) {
super.init(name: "Gajah", age: age, weight: weight)
}
}
<file_sep>/Bootcamp/Class/Deer.swift
//
// Deer.swift
// Bootcamp
//
// Created by <NAME> on 11/09/19.
// Copyright © 2019 Bukalapak. All rights reserved.
//
import Foundation
class Deer : Animal {
override var maxWeight: Int {
return 75
}
init(age: Int, weight: Int) {
super.init(name: "Rusa", age: age, weight: weight)
}
}
| b7ca3676f0afa514880b1d45962bcf15e0b9eda8 | [
"Swift"
] | 5 | Swift | hashfi104/bootcamp_bl | 2afb0dd6502f47c42cebd2c8806be17fcc5c43bf | 8d308a610d4522f3d42aa479fee01262fd8962ee |
refs/heads/master | <file_sep><?php
$chosen_co = $_GET['co'];
$expr = $_GET['expr'];
$text = $_GET['text'];
$flag_alt = $_GET['alt'];
$time = time();
if ($flag_alt == "")
$flag_alt = 0;
switch ($expr)
{
case "normal":
$offset = 0;
break;
case "win":
$offset = 48;
break;
case "lose":
$offset = 96;
break;
default:
$offset = 0;
break;
}
$image = imagecreatefrompng("images/backdrop/backdrop.png");
$co = imagecreatefromgif("images/co/" . $chosen_co . "-left.gif");
if ($flag_alt == "false")
$name = imagecreatefromgif("images/co/name/" . $chosen_co . ".gif");
else
$name = imagecreatefromgif("images/co/name/" . $chosen_co . "_eu.gif");
imagecopymerge($image, $co, 8, 2, $offset, 0, 48, 48, 100);
imagecopymerge($image, $name, 0, 44, 0, 0, 60, 15, 100);
$white = imagecolorallocate($image, 255, 255, 255);
$fontpath = realpath('fonts/');
putenv('GDFONTPATH='.$fontpath);
$font = "aw2text.ttf";
$lines = explode("\r\n", $text);
$line1 = '';
$line2 = '';
/* Attempts to break up a line into multiple parts
Not perfect, but good for general usage */
// If we have two lines, then we are already done
if(count($lines) == 2) {
$line1 = $lines[0];
$line2 = $lines[1];
}
else { // Otherwise, break em up with wordwrap()
$newLines = wordwrap($lines[0], 40, "\r\n");
$newLines = explode("\r\n", $newLines);
$line1 = $newLines[0];
if(isset($newLines[1]))
$line2 = $newLines[1];
}
Imagettftext($image, 6,0,64,24,$white,$font,$line1);
Imagettftext($image, 6,0,64,40,$white,$font,$line2);
// Capture the image data from imagegif() and then convert to to base64 for uploading to imgur
ob_start();
imagepng($image);
$image_data = ob_get_contents();
ob_end_clean();
// Get image in base64
$image64 = base64_encode($image_data);
print $image64;
?>
| a4f3fa3ef27d04386e8e5d143f7bb099a40f5e6a | [
"PHP"
] | 1 | PHP | wonderfulfrog/awdrqg | c9d7dd1293b7b9911e9f2152a177a65bc2440929 | f590c6ebf43ea7846db4313bac7e9c1f6328f3bb |
refs/heads/master | <file_sep>#!/bin/sh
#
# radiusd Start/Stop Radius daemon.
#
# chkconfig: 345 98 10
#
# description: Remote Authentication Dail In User Service
#
# Source function library.
. /etc/rc.d/init.d/functions
RETVAL=0
case "$1" in
start)
# Check if the service is already running?
if [ ! -f /var/lock/subsys/radiusd ]; then
msg_starting ICRADIUS
daemon radiusd -y
RETVAL=$?
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/radiusd
else
msg_already_running radiusd
fi
;;
stop)
if [ -f /var/lock/subsys/radiusd ]; then
msg_stopping ICRADIUS
killproc radiusd
rm -f /var/lock/subsys/radiusd
else
msg_not_running radiusd
fi
;;
restart|force-reload)
$0 stop
$0 start
exit $?
;;
status)
status radiusd
exit $?
;;
*)
msg_usage "$0 {start|stop|restart|force-reload|status}"
exit 3
esac
exit $RETVAL
| 7b0f6982eb3b24514038b52bee62c83e640b7c64 | [
"Shell"
] | 1 | Shell | pld-linux/icradius | 1dbf5e38098009fcecf97aafb5c9db29e8b64fcf | e2086e1d39e398a032640dd6211cdafedfa0b12a |
refs/heads/master | <repo_name>luodanwg/reverse<file_sep>/reverse.go
package reverse
import (
"encoding/hex"
"fmt"
)
func reverser(str string)string{
//str :=[]byte{117, 58, 126, 81, 186, 44, 17, 169, 23, 103, 7, 131, 34, 8, 238, 70, 147, 33, 101, 140}
//str:="0d821bd7b6d53f5c2b40e217c6defc8bbe896cf5"
return ToHexString(ToArrayReverse((StringToByte(str))))
}
func ToArrayReverse(arr []byte) []byte {
l := len(arr)
x := make([]byte, 0)
for i := l - 1; i >= 0 ;i--{
x = append(x, arr[i])
}
return x
}
func ToHexString(data []byte) string {
return hex.EncodeToString(data)
}
func StringToByte(str string) []byte{
strx,_:= hex.DecodeString(str)
return strx
}
| 8a37d32337fddef7d5b3157dc70f8ab8bc624432 | [
"Go"
] | 1 | Go | luodanwg/reverse | d26f174bdb58aab592f0fe0b871d2b42d3f14627 | c0ac9b7c3d48f32b9c19808f29e372027859040f |
refs/heads/master | <file_sep>package com.parse.pixsterapp;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.location.Location;
import com.parse.ParseQueryAdapter;
import com.parse.ParseGeoPoint;
public class PixsterListActivity extends ListActivity {
private ParseQueryAdapter<Pixster> mainAdapter;
private MainPixsterAdapter favoritesAdapter;
private ParseGeoPoint geoPoint;
private int radius = PixsterApplication.getConfigHelper().getRadius();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setClickable(false);
mainAdapter = new ParseQueryAdapter<Pixster>(this, Pixster.class);
mainAdapter.setTextKey("text");
mainAdapter.setImageKey("profileImage");
// Subclass of ParseQueryAdapter
favoritesAdapter = new MainPixsterAdapter(this);
// Default view is all pixs
setListAdapter(favoritesAdapter);
Intent intent = getIntent();
Location location = intent.getParcelableExtra(PixsterApplication.INTENT_EXTRA_LOCATION);
if(location!=null) {
geoPoint = new ParseGeoPoint(location.getLatitude(), location.getLongitude());
}else
{
//TODO if location is null display error to user
System.out.println("Location:"+location);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.new_pixster_menu, menu);
return true;
}
/*
* Posting pixs and refreshing the list will be controlled from the Action
* Bar.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh: {
updatePixsterList();
break;
}
case R.id.action_favorites: {
showFavorites();
break;
}
case R.id.action_new: {
newPixster();
break;
}
}
return super.onOptionsItemSelected(item);
}
private void updatePixsterList() {
mainAdapter.loadObjects();
setListAdapter(favoritesAdapter);
}
private void showFavorites() {
favoritesAdapter.loadObjects();
setListAdapter(favoritesAdapter);
}
private void newPixster() {
Intent i = new Intent(this, NewPixsterActivity.class);
startActivityForResult(i, 0);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
// If a new post has been added, update
// the list of posts
updatePixsterList();
}
}
}
| 45f57949bf13e8dc6233cf9657f4c137080f870e | [
"Java"
] | 1 | Java | aldrinc/PixsterAndroid | a6c1ad905be917412b358ae29ea7b4df117d4d51 | bd0ce0fd945312150316d0f416cafd799bffd57a |
refs/heads/master | <file_sep>module dynamotest
require (
github.com/aws/aws-sdk-go v1.29.8
github.com/guregu/dynamo v1.6.0
)
go 1.13
<file_sep>package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/guregu/dynamo"
)
type User struct {
Id int `dynamo:"Id,hash"`
Text []string `dynamo:"Text"`
}
func main() {
// 初期化
db := dynamo.New(session.New(), &aws.Config{
Region: aws.String("ap-northeast-1"),
})
err := db.CreateTable("Users", User{}).Run()
if err != nil {
fmt.Println(err)
}
// ACTIVE待ち
for {
d, err := db.Table("Users").Describe().Run()
if err != nil {
fmt.Println(err)
}
if d.Status == dynamo.ActiveStatus {
break
}
}
table := db.Table("Users")
// Put
u1 := User{Id: 1, Text: []string{"aja"}}
u2 := User{Id: 2, Text: []string{"aja", "ajaaja"}}
u3 := User{Id: 3, Text: []string{"aja", "ajaaja", "ajaajaajaaja"}}
u4 := User{Id: 4, Text: []string{"aja", "ajaaja", "ajaajaajaaja", "ajaajaajaajaaja"}}
_ = table.Put(u1).Run()
_ = table.Put(u2).Run()
_ = table.Put(u3).Run()
_ = table.Put(u4).Run()
// GetBatchItem
// 以下の例はパーティションキーのみで有効
var r []User
err2 := table.Batch("Id").Get([]dynamo.Keyed{dynamo.Keys{1}, dynamo.Keys{2}, dynamo.Keys{3}, dynamo.Keys{4}}...).All(&r)
if err != nil {
fmt.Println(err2)
}
fmt.Println(r)
}
| 66dbb2f0b73601b808c29439668cfb7a0063f109 | [
"Go",
"Go Module"
] | 2 | Go Module | originbenntou/guregu_test | e33a3eef19ab21a4b9de458ba6833aa818a11111 | a77320a06bf4c77433b88b549155566e5752dffe |
refs/heads/master | <repo_name>mreid10/281<file_sep>/README.md
# LMU CMSI 281
Data Structures
<file_sep>/CustomStack.java
public class CustomStack{
private Node end;
private Node current;
public CustomStack(){
this.end = new Node();
this.current = this.end;
}
public int pop(){
Node p = this.current;
current = p.next;
return p.get();
}
public boolean push( int i ) {
Node n = new Node(i);
n.setNext(current);
current = n;
return true;
}
}<file_sep>/Node2.java
public class Node{
private int value;
public Node next;
public Node(){
this.next = null;
}
public Node( int i ){
this.value = i;
this.next = null;
}
public int get() {
return this.value;
}
public void set (int i ) {
this.value = i;
}
public void setNext ( Node p ) {
this.next = p;
}
public Node getValue () {
return next;
}
public void delete() {
this.next = this.getValue();
}
} | 65e756582cda1b2ae55385bfe98f40491179576a | [
"Markdown",
"Java"
] | 3 | Markdown | mreid10/281 | eac9679004d5fc5ba946b8e47afc43e3afa129e3 | 76ede973939420b9f2fd6dce3ce495a8b6ba3bde |
refs/heads/master | <repo_name>JackRossProjects/EE2-Ultrasonic-Lock<file_sep>/ultrasonicLock.ino
#include <Servo.h>
int servoPin = 3;
Servo Servo1;
int LED1 = 12;
int LED2 = 11;
const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 6; // Echo Pin of Ultrasonic Sensor
int counter = 0;
void setup() {
Serial.begin(9600); // Starting Serial Terminal
Servo1.attach(servoPin);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
}
void loop() {
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
pinMode(echoPin, INPUT);
digitalWrite(LED1,HIGH);
duration = pulseIn(echoPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
if (inches < 4) {
counter += 1;
}
if (counter > 15) {
Serial.print("UNLOCK");
// Make servo go to 0 degrees
digitalWrite(LED1, LOW);
digitalWrite(LED2, HIGH);
// Make servo go to 180 degrees
Servo1.write(180);
delay(1000);
}
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}
<file_sep>/README.md
# Electrical Engineering Project #2 - Ultrasonic Lock
For this project I wanted to make a distance sensing lock.
I used an ultrasonic distance sensor and a 9g servo for the main functionality. If you put something infront of the ultrasonic distance sensor, the servo (which will be connected to the lock) turns 180 degrees and unlocks the door or secret compartment. I added LED's for extra flair. When in the locked position the red LED will be on and when in unlocked position, the green LED will be on.

<br>
<br>
<a href="http://jackrossprojects.com"><img src="https://github.com/JackRossProjects/Traffic-Fatality-Analysis/blob/master/jrp.png" title="Jack Ross Projects" alt="Jack Ross Projects"></a>
| 94f7db6fedd6821fc0c9ebc1964c09e22622abe4 | [
"Markdown",
"C++"
] | 2 | C++ | JackRossProjects/EE2-Ultrasonic-Lock | 3cf54e3a26c8971c108a70d2099e134ccf83e067 | 7d7e6be7cf4649094776a69b21a78d3276879705 |
refs/heads/master | <file_sep>/* template for plugins */
#include <glib.h>
#include <gmodule.h>
gchar *g_module_check_init(){
/*
load all symbols,
return NULL on success,
error string on fail
can be used like plugin_main()
*/
}
void g_module_unload(){
/*unload all symbols, then g*/
}
<file_sep> SDesk (Simple desktop)
================================================================================
SDesk monitors directories to provide desktop elements on the fly.
$SDESKDIR/tray
* provides tray applets from applet subdirectories
$SDESKDIR/icons
* provides desktop icons from .desktop files or symlinks
$SDESKDIR/ui
* provides gui for apps from gtkbuilder ui files
$SDESKDIR/sh
* provides helper functions to UI/tray apps from sourced shell scripts
$SDESKDIR/desk
* provides desktop backgrounds capable of displaying non-interactive widgets
$SDESKDIR/plugins
* provides plugins to help UI/tray apps
These can be extended to provide extra capabilities such as interaction via
RPC, sockets, DBUS... or additional UI widgets such as those in webkitgtk,
or an interface to C libraries or other languages<file_sep>#include <gtk/gtk.h>
void load_builder(gchar *filename){
GtkBuilder *ui=gtk_builder_new();
gtk_builder_add_from_file(ui, filename, NULL);
/* gtk_builder_set_translation_domain(ui, filename); TODO remove .ui from filename*/
GSList *objects=gtk_builder_get_objects(ui);
gtk_widget_show_all(objects->data);
/* TODO watch filename to gtk_widget_destroy(objects->data) if it is deleted */
gtk_builder_connect_signals(ui); /* TODO *_full? for interpreted lang plugins */
g_object_unref(G_OBJECT(ui));
g_slist_free(objects);
}
void load_module(gchar *filename){
g_module_open(filename, G_MODULE_BIND_LAZY);
/* TODO watch to g_module_unload() && g_module_close() it */
}
void add_icon(gchar *filename){
/* TODO */
}
void remove_icon(gchar *filename){
/* TODO */
}
void handle_file(gchar *file, GFileMonitorEvent event_type){
if (event_type == G_FILE_MONITOR_EVENT_CHANGED || event_type == G_FILE_MONITOR_EVENT_DELETED){
if (g_str_has_suffix(const gchar *str, ".desktop")) remove_icon(file);
}
if (event_type == G_FILE_MONITOR_EVENT_CHANGED || event_type == G_FILE_MONITOR_EVENT_CREATED){
if (g_str_has_suffix(const gchar *str, ".so")) load_module(file);
if (g_str_has_suffix(const gchar *str, ".ui")) load_builder(file);
if (g_str_has_suffix(const gchar *str, ".desktop")) add_icon(file);
}
}
void on_changed(
GFileMonitor *monitor,
GFile *file,
GFile *other_file,
GFileMonitorEvent event_type,
gpointer user_data){
#ifdef DEBUG
g_print ("File = %s\nOther File = %s\n",g_file_get_parse_name(file),g_file_get_parse_name(other_file));
#endif
handle_file(file,event_type);
}
int main(int argc, char **argv){
gtk_init(&argc, &argv);
/*load all files already in directory specified by argv[1]*/
GDir *dir=g_dir_open(argv[1], 0, NULL);
gchar *file;
while (file=g_dir_read_name(dir)){
handle_file(file,G_FILE_MONITOR_EVENT_CREATED);
}
g_signal_connect( /* monitor argv[1] and handle changes with on_changed() */
g_file_monitor_directory(g_file_new_for_commandline_arg(argv[1]), NULL, NULL, NULL ),
"changed",G_CALLBACK(on_changed),(gpointer) argv );
}
| 7972ac80db5a875f1cc7711b3896c6f823970122 | [
"Markdown",
"C"
] | 3 | C | technosaurus/sdesk | e3ec07a5b5d47aad1768653624510911a2f1fd6c | 0d00200a5003180529e4c73828783b56ddc1ffb1 |
refs/heads/master | <repo_name>pavel-grigorev/spring-resource-reader<file_sep>/settings.gradle
rootProject.name = 'spring-resource-reader'
<file_sep>/README.md
[](https://maven-badges.herokuapp.com/maven-central/org.thepavel/spring-resource-reader)
# Resource Reader for Spring
This tool is a declarative resource reader with the content auto-conversion capabilities. It supports the following types out-of-the-box:
- `File`
- `InputStream`
- `Reader`
- `BufferedReader`
- `byte[]`
- `String`
- `List<String>`
- `Stream<String>`
- JSON
- XML
- `Properties`
- `Resource` (no conversion)
Example:
```java
@ResourceReader
public interface TemplateProvider {
@Classpath("template.html")
File getTemplateFile();
@Classpath("template.html")
InputStream getTemplateInputStream();
@Classpath("template.html")
Reader getTemplateReader();
@Classpath("template.html")
BufferedReader getTemplateBufferedReader();
@Classpath("template.html")
byte[] getTemplateBytes();
@Classpath("template.html")
String getTemplate();
@Classpath("template.html")
List<String> getTemplateLines();
@Classpath("template.html")
Stream<String> getTemplateLinesStream();
@Classpath("users.json")
@Json
List<User> users();
@Classpath("company.xml")
@Xml
Company getCompany();
@Classpath("application.properties")
Properties properties();
}
```
The tool will create a proxy bean for an interface decorated with `@ResourceReader`. To make it work, add the `@ResourceReaderScan` annotation to a java configuration:
```java
@Configuration
@ComponentScan
@ResourceReaderScan
public class AppConfiguration {
}
```
Usage is similar to `@ComponentScan`. This configuration will scan from the package of `AppConfiguration`. You can also specify `basePackages` or `basePackageClasses` to define specific packages to scan.
# Adding to your project
Gradle:
```
dependencies {
implementation 'org.thepavel:spring-resource-reader:1.0.3'
}
```
Maven:
```
<dependency>
<groupId>org.thepavel</groupId>
<artifactId>spring-resource-reader</artifactId>
<version>1.0.3</version>
</dependency>
```
# Prerequisites
Requires Spring `5.2.0+`.
# Resource location
Resource location can be specified by one of the following:
- `@Location`
- `@Classpath`
- `@File`
- Method parameter
The following classpath location declarations are equivalent:
```java
@ResourceReader
public interface TemplateProvider {
@Location("classpath:template.html")
String getTemplateByLocation();
@Classpath("template.html")
String getTemplate();
}
```
The following file location declarations are equivalent:
```java
@ResourceReader
public interface TemplateProvider {
@Location("file:/tmp/template.html")
String getTemplateByLocation();
@File("/tmp/template.html")
String getTemplate();
}
```
If the location is not specified by an annotation and the method has exactly one parameter and it is of type `String` then the resource location is taken from the parameter value:
```java
@ResourceReader
public interface ResourceProvider {
String getContent(String location);
@Classpath
String getContentFromClasspath(String location);
@File
String getContentFromFileSystem(String location);
}
```
HTTP location example:
```java
@ResourceReader
public interface IpAddressProvider {
@Location("https://checkip.amazonaws.com/")
String getPublicIpAddress();
}
```
Location strings support placeholders:
```java
@ResourceReader
public interface TemplateProvider {
@Classpath("/templates/${template.name}.html")
String getTemplate();
}
```
# Charset
The default charset is `UTF-8`. To change it, add the `@Charset` annotation:
```java
@ResourceReader
public interface TemplateProvider {
@Classpath("template.html")
@Charset("ISO-8859-1")
String getTemplate();
}
```
`@Charset` applies to all types that read character data:
- `Reader`
- `BufferedReader`
- `String`
- `List<String>`
- `Stream<String>`
- JSON
- XML
- `Properties`
# Buffer size
To set the `BufferedReader` buffer size, add the `@BufferSize` annotation:
```java
@ResourceReader
public interface TemplateProvider {
@Classpath("template.html")
@BufferSize(10240)
BufferedReader getTemplate();
}
```
`@BufferSize` applies to all types that use `BufferedReader` to read data:
- `BufferedReader`
- `String`
- `List<String>`
- `Stream<String>`
- JSON
- XML
- `Properties`
# JSON
The tool provides automatic mapping of JSON content to java objects:
```java
@ResourceReader
public interface UserProvider {
@Classpath("users.json")
@Json
List<User> users();
}
```
- If Gson is on classpath then it will be used to read the JSON.
- If Jackson is on classpath then it will be used to read the JSON.
- Otherwise `IllegalStateException` will be thrown.
If both Gson and Jackson are on classpath then Gson will be used. To force the framework to use Jackson, set the `deserializer` annotation argument:
```java
@ResourceReader
public interface UserProvider {
@Classpath("users.json")
@Json(deserializer = JacksonJsonDeserializer.NAME)
List<User> users();
}
```
To configure the Gson parser, build a bean implementing `Configurator<GsonBuilder>` and add the `@GsonBuilderConfigurator` declaration:
```java
@ResourceReader
public interface UserProvider {
@Classpath("users.json")
@Json
@GsonBuilderConfigurator("userDeserializer")
List<User> users();
}
```
`"userDeserializer"` is the name of the bean:
```java
@Component
public class UserDeserializer implements JsonDeserializer<User>, Configurator<GsonBuilder> {
// com.google.gson.JsonDeserializer#deserialize()
@Override
public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
JsonObject jsonObject = json.getAsJsonObject();
String name = jsonObject.get("name").getAsString();
String email = jsonObject.get("email").getAsString();
return new UserImpl(name, email);
}
// org.thepavel.resource.configurator.Configurator#configure()
@Override
public void configure(GsonBuilder gsonBuilder) {
gsonBuilder.registerTypeAdapter(User.class, this);
}
}
```
To configure the Jackson parser, build a bean implementing `Configurator<ObjectMapper>` and add the `@JacksonMapperConfigurator` declaration:
```java
@ResourceReader
public interface UserProvider {
@Classpath("users.json")
@Json
@JacksonMapperConfigurator("userDeserializer")
List<User> users();
}
```
# XML
The tool provides automatic mapping of XML content to java objects:
```java
@ResourceReader
public interface SettingsProvider {
@Classpath("settings.xml")
@Xml
Settings settings();
}
```
- If Jackson is on classpath then it will be used to read the XML.
- Otherwise `IllegalStateException` will be thrown.
To configure the Jackson parser, build a bean implementing `Configurator<XmlMapper>` and add the `@JacksonMapperConfigurator` declaration:
```java
@ResourceReader
public interface UserProvider {
@Classpath("settings.xml")
@Xml
@JacksonMapperConfigurator("xmlMapperConfigurator") // "xmlMapperConfigurator" is the bean name
Settings settings();
}
```
<file_sep>/src/main/java/org/thepavel/resource/mapper/BaseDeserializingResourceMapper.java
/*
* Copyright (c) 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thepavel.resource.mapper;
import org.springframework.core.io.Resource;
import org.thepavel.icomponent.metadata.MethodMetadata;
import org.thepavel.icomponent.util.AnnotationAttributes;
import org.thepavel.resource.deserializer.Deserializer;
import org.thepavel.resource.ResourceMapper;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Optional;
import static org.thepavel.resource.util.Utils.canNotDeserialize;
public abstract class BaseDeserializingResourceMapper<T, D extends Deserializer<T>> implements ResourceMapper<T> {
private static final String ANNOTATION_ATTRIBUTE = "deserializer";
protected abstract Class<? extends Annotation> getMarkerAnnotation();
protected abstract D getDeserializer(String name);
protected abstract List<D> getDeserializers();
@Override
public boolean isFor(MethodMetadata methodMetadata) {
return methodMetadata.getAnnotations().isPresent(getMarkerAnnotation());
}
@Override
public T map(Resource resource, MethodMetadata methodMetadata) throws IOException {
return getDeserializerName(methodMetadata)
.map(this::getDeserializerNotNull)
.orElseGet(this::getAvailableDeserializer)
.read(resource, methodMetadata);
}
private Optional<String> getDeserializerName(MethodMetadata methodMetadata) {
return AnnotationAttributes
.of(getMarkerAnnotation())
.declaredOn(methodMetadata)
.getString(ANNOTATION_ATTRIBUTE);
}
private D getDeserializerNotNull(String name) {
D deserializer = getDeserializer(name);
if (deserializer == null) {
throw canNotDeserialize("deserializer " + name + " not found");
}
if (!deserializer.isAvailable()) {
throw canNotDeserialize("deserializer " + name + " is not available");
}
return deserializer;
}
private D getAvailableDeserializer() {
return getDeserializers()
.stream()
.filter(Deserializer::isAvailable)
.findFirst()
.orElseThrow(() -> canNotDeserialize("no deserializer is available for mapper " + getClass().getName()));
}
}
<file_sep>/src/main/java/org/thepavel/resource/deserializer/jackson/JacksonUtils.java
/*
* Copyright (c) 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thepavel.resource.deserializer.jackson;
import org.thepavel.resource.util.IOSupplier;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import static java.util.Objects.requireNonNull;
import static org.springframework.util.ReflectionUtils.findMethod;
import static org.springframework.util.ReflectionUtils.invokeMethod;
import static org.thepavel.resource.util.Utils.canNotDeserialize;
import static org.thepavel.resource.util.Utils.getClassOrNull;
public class JacksonUtils {
private static final Class<?> OBJECT_MAPPER_CLASS = getClassOrNull("com.fasterxml.jackson.databind.ObjectMapper");
private static final Class<?> XML_MAPPER_CLASS = getClassOrNull("com.fasterxml.jackson.dataformat.xml.XmlMapper");
private static final Class<?> TYPE_FACTORY_CLASS = getClassOrNull("com.fasterxml.jackson.databind.type.TypeFactory");
private static final Class<?> JAVA_TYPE_CLASS = getClassOrNull("com.fasterxml.jackson.databind.JavaType");
private JacksonUtils() {
}
public static boolean isObjectMapperOnClasspath() {
return OBJECT_MAPPER_CLASS != null && isTypeFactoryOnClasspath();
}
public static boolean isXmlMapperOnClasspath() {
return XML_MAPPER_CLASS != null && isTypeFactoryOnClasspath();
}
private static boolean isTypeFactoryOnClasspath() {
return TYPE_FACTORY_CLASS != null && JAVA_TYPE_CLASS != null;
}
public static Class<?> getObjectMapperClass() {
return requireNonNull(OBJECT_MAPPER_CLASS, "ObjectMapper class not found");
}
public static Class<?> getXmlMapperClass() {
return requireNonNull(XML_MAPPER_CLASS, "XmlMapper class not found");
}
private static Class<?> getTypeFactoryClass() {
return requireNonNull(TYPE_FACTORY_CLASS, "TypeFactory class not found");
}
private static Class<?> getJavaTypeClass() {
return requireNonNull(JAVA_TYPE_CLASS, "JavaType class not found");
}
public static Object read(Object mapper, IOSupplier<Reader> reader, Type type) throws IOException {
Class<?> mapperClass = mapper.getClass();
String mapperClassName = mapperClass.getSimpleName();
Method getTypeFactory = findMethod(mapperClass, "getTypeFactory");
if (getTypeFactory == null) {
throw canNotDeserialize("method " + mapperClassName + "#getTypeFactory() not found");
}
Method readValue = findMethod(mapperClass, "readValue", Reader.class, getJavaTypeClass());
if (readValue == null) {
throw canNotDeserialize("method " + mapperClassName + "#readValue(Reader,JavaType) not found");
}
Method constructType = findMethod(getTypeFactoryClass(), "constructType", Type.class);
if (constructType == null) {
throw canNotDeserialize("method TypeFactory#constructType(Type) not found");
}
Object typeFactory = invokeMethod(getTypeFactory, mapper);
if (typeFactory == null) {
throw canNotDeserialize("method " + mapperClassName + "#getTypeFactory() returned null");
}
Object javaType = invokeMethod(constructType, typeFactory, type);
if (javaType == null) {
throw canNotDeserialize("method TypeFactory#constructType(Type) returned null");
}
return invokeMethod(readValue, mapper, reader.get(), javaType);
}
}
<file_sep>/src/test/java/org/thepavel/resource/integration/IntegrationTest.java
/*
* Copyright (c) 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thepavel.resource.integration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.joining;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = TestConfig.class)
@TestPropertySource("/application.properties")
public class IntegrationTest {
@Autowired
private TestResourceReader testResourceReader;
@Test
public void string() {
assertEquals("line 1\nline 2", testResourceReader.string());
}
@Test
public void stringList() {
assertEquals(asList("line 1", "line 2"), testResourceReader.listLines());
}
@Test
public void stringStream() {
assertEquals(
"line 1,line 2",
testResourceReader.streamLines().collect(joining(","))
);
}
@Test
public void bytes() {
assertArrayEquals("line 1\nline 2".getBytes(), testResourceReader.bytes());
}
@Test
public void jsonToObject() {
assertEquals(
singletonList(new UserImpl("<NAME>", "<EMAIL>")),
testResourceReader.users()
);
}
@Test
public void jsonToMap() {
Map<String, Object> map = new HashMap<>();
map.put("name", "<NAME>");
map.put("email", "<EMAIL>");
assertEquals(singletonList(map), testResourceReader.usersAsMap());
}
@Test
public void xmlToObject() {
assertEquals(
new Book("The Theory of Everything", "Stephen Hawking"),
testResourceReader.book()
);
}
@Test
public void properties() {
Properties properties = testResourceReader.properties();
assertNotNull(properties);
assertEquals(3, properties.size());
assertEquals("dummy.txt", properties.get("text.file"));
assertEquals("users.json", properties.get("users.file"));
assertEquals("book.xml", properties.get("book.file"));
}
@Test
public void customMapper() {
assertEquals(asList("one", "two", "three"), testResourceReader.commaSeparatedStrings());
}
}
<file_sep>/src/main/java/org/thepavel/resource/deserializer/gson/GsonUtils.java
/*
* Copyright (c) 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thepavel.resource.deserializer.gson;
import org.thepavel.resource.util.IOSupplier;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import static java.util.Objects.requireNonNull;
import static org.springframework.util.ReflectionUtils.findMethod;
import static org.springframework.util.ReflectionUtils.invokeMethod;
import static org.thepavel.resource.util.Utils.canNotDeserialize;
import static org.thepavel.resource.util.Utils.getClassOrNull;
import static org.thepavel.resource.util.Utils.getInstance;
public class GsonUtils {
private static final Class<?> GSON_CLASS = getClassOrNull("com.google.gson.Gson");
private static final Class<?> GSON_BUILDER_CLASS = getClassOrNull("com.google.gson.GsonBuilder");
private GsonUtils() {
}
public static boolean isGsonOnClasspath() {
return GSON_CLASS != null && GSON_BUILDER_CLASS != null;
}
public static Class<?> getGsonClass() {
return requireNonNull(GSON_CLASS, "Gson class not found");
}
public static Class<?> getGsonBuilderClass() {
return requireNonNull(GSON_BUILDER_CLASS, "GsonBuilder class not found");
}
public static Object getGson() {
return getInstance(getGsonClass());
}
public static Object createGson(Object builder) {
Method create = findMethod(getGsonBuilderClass(), "create");
if (create == null) {
throw canNotDeserialize("method GsonBuilder#create() not found");
}
return invokeMethod(create, builder);
}
public static Object read(Object gson, IOSupplier<Reader> reader, Type type) throws IOException {
Method fromJson = findMethod(getGsonClass(), "fromJson", Reader.class, Type.class);
if (fromJson == null) {
throw canNotDeserialize("method Gson#fromJson(Reader,Type) not found");
}
return invokeMethod(fromJson, gson, reader.get(), type);
}
}
<file_sep>/src/main/java/org/thepavel/resource/mapper/StringListResourceMapper.java
/*
* Copyright (c) 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thepavel.resource.mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.Resource;
import org.thepavel.icomponent.metadata.MethodMetadata;
import org.thepavel.resource.ResourceMapper;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StringListResourceMapper extends BaseReturnTypeResourceMapper<List<String>> {
public static final String NAME = "org.thepavel.resource.mapper.internalStringListResourceMapper";
private ResourceMapper<Stream<String>> stringStreamResourceMapper;
@Autowired
public void setStringStreamResourceMapper(@Qualifier(StringStreamResourceMapper.NAME) ResourceMapper<Stream<String>> stringStreamResourceMapper) {
this.stringStreamResourceMapper = stringStreamResourceMapper;
}
@Override
public List<String> map(Resource resource, MethodMetadata methodMetadata) throws IOException {
return stringStreamResourceMapper
.map(resource, methodMetadata)
.collect(Collectors.toList());
}
}
<file_sep>/build.gradle
/*
* Copyright (c) 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
plugins {
id 'java-library'
}
group 'org.thepavel'
version '1.0.3'
repositories {
mavenCentral()
}
dependencies {
api 'org.thepavel:spring-icomponent:1.0.8'
implementation 'org.apache.commons:commons-lang3:3.11'
testImplementation 'org.springframework:spring-test:5.2.0.RELEASE'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
testImplementation 'com.google.code.gson:gson:2.8.6'
testImplementation 'com.fasterxml.jackson.core:jackson-annotations:2.12.0'
testImplementation 'com.fasterxml.jackson.core:jackson-core:2.12.0'
testImplementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.12.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}
test {
useJUnitPlatform()
}
<file_sep>/src/test/resources/application.properties
text.file = dummy.txt
users.file = users.json
book.file = book.xml
<file_sep>/src/main/java/org/thepavel/resource/deserializer/_DeserializerConfiguration.java
/*
* Copyright (c) 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thepavel.resource.deserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.Order;
import org.thepavel.icomponent.metadata.MethodMetadata;
import org.thepavel.resource.configurator.AnnotationConfiguratorChain;
import org.thepavel.resource.deserializer.gson.GsonJsonDeserializer;
import org.thepavel.resource.deserializer.jackson.JacksonJsonDeserializer;
import org.thepavel.resource.deserializer.jackson.JacksonXmlDeserializer;
import java.lang.annotation.Annotation;
import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;
@Configuration(_DeserializerConfiguration.NAME)
public class _DeserializerConfiguration {
public static final String NAME = "org.thepavel.resource.deserializer.internal_DeserializerConfiguration";
@Bean(GsonJsonDeserializer.NAME)
@Order(10)
JsonDeserializer gsonJsonDeserializer() {
return new GsonJsonDeserializer();
}
@Bean(JacksonJsonDeserializer.NAME)
@Order(20)
JsonDeserializer jacksonJsonDeserializer() {
return new JacksonJsonDeserializer();
}
@Bean(JacksonXmlDeserializer.NAME)
@Order(10)
XmlDeserializer jacksonXmlDeserializer() {
return new JacksonXmlDeserializer();
}
@Bean(AnnotationConfiguratorChain.NAME)
@Scope(SCOPE_PROTOTYPE)
AnnotationConfiguratorChain annotationConfiguratorChain(MethodMetadata methodMetadata, Class<? extends Annotation> annotationType) {
return new AnnotationConfiguratorChain(methodMetadata, annotationType);
}
}
<file_sep>/src/main/java/org/thepavel/resource/mapper/_ResourceMapperConfiguration.java
/*
* Copyright (c) 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thepavel.resource.mapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.Resource;
import org.thepavel.resource.ResourceMapper;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;
import java.util.Properties;
import java.util.stream.Stream;
@Configuration(_ResourceMapperConfiguration.NAME)
public class _ResourceMapperConfiguration {
public static final String NAME = "org.thepavel.resource.mapper.internal_ResourceMapperConfiguration";
@Bean(SelfResourceMapper.NAME)
@Order
ResourceMapper<Resource> selfResourceMapper() {
return new SelfResourceMapper();
}
@Bean(FileResourceMapper.NAME)
@Order
ResourceMapper<File> fileResourceMapper() {
return new FileResourceMapper();
}
@Bean(InputStreamResourceMapper.NAME)
@Order
ResourceMapper<InputStream> inputStreamResourceMapper() {
return new InputStreamResourceMapper();
}
@Bean(ReaderResourceMapper.NAME)
@Order
ResourceMapper<Reader> readerResourceMapper() {
return new ReaderResourceMapper();
}
@Bean(BufferedReaderResourceMapper.NAME)
@Order
ResourceMapper<BufferedReader> bufferedReaderResourceMapper() {
return new BufferedReaderResourceMapper();
}
@Bean(BytesResourceMapper.NAME)
@Order
ResourceMapper<byte[]> bytesResourceMapper() {
return new BytesResourceMapper();
}
@Bean(StringResourceMapper.NAME)
@Order
ResourceMapper<String> stringResourceMapper() {
return new StringResourceMapper();
}
@Bean(StringListResourceMapper.NAME)
@Order
ResourceMapper<List<String>> stringListResourceMapper() {
return new StringListResourceMapper();
}
@Bean(StringStreamResourceMapper.NAME)
@Order
ResourceMapper<Stream<String>> stringStreamResourceMapper() {
return new StringStreamResourceMapper();
}
@Bean(JsonResourceMapper.NAME)
@Order(10)
ResourceMapper<Object> jsonResourceMapper() {
return new JsonResourceMapper();
}
@Bean(XmlResourceMapper.NAME)
@Order(20)
ResourceMapper<Object> xmlResourceMapper() {
return new XmlResourceMapper();
}
@Bean(PropertiesResourceMapper.NAME)
@Order
ResourceMapper<Properties> propertiesResourceMapper() {
return new PropertiesResourceMapper();
}
}
<file_sep>/src/main/java/org/thepavel/resource/annotations/Json.java
/*
* Copyright (c) 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thepavel.resource.annotations;
import org.thepavel.resource.deserializer.Deserializer;
import org.thepavel.resource.configurator.Configurator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that the content of a resource is JSON. The resource will be mapped
* to an object.
*
* If Gson is on the classpath then it is going to be used to read the resource.
*
* If Jackson is on the classpath then it is going to be used to read the resource.
*
* If none is on the classpath then {@link IllegalStateException} is going to be thrown.
*
* If both are on the classpath then Gson is going to be used. To force the framework
* to use Jackson, set the {@code deserializer} attribute to:
*
* {@code @Json(deserializer = JacksonJsonDeserializer.NAME)}
*
* If Gson's GsonBuilder or Jackson's ObjectMapper require additional configuration,
* it should be done in beans of type {@link Configurator}.
*
* For Gson, the bean must implement {@code Configurator<GsonBuilder>}.
*
* For Jackson, the bean must implement {@code Configurator<ObjectMapper>}.
*
* The bean names of such beans then should be listed in {@link GsonBuilderConfigurator}
* for Gson or {@link JacksonMapperConfigurator} for Jackson.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Json {
/**
* Bean name of a {@link Deserializer} to be used to read the resource.
*/
String deserializer() default "";
}
| 94cfac1b65c2c454bb484d6af12a03766dfaa2eb | [
"Markdown",
"Java",
"INI",
"Gradle"
] | 12 | Gradle | pavel-grigorev/spring-resource-reader | 038e1d20860e38584016f049d253d50d317dc3a0 | 0a5e8500c1e43087c3aca6f4ffe5724701947e73 |
refs/heads/master | <repo_name>ksuhr1/BoozeBuddy<file_sep>/app/src/main/java/com/example/katelynsuhr/boozebuddy/contactsearch.java
package com.example.katelynsuhr.boozebuddy;
import java.util.ArrayList;
import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.provider.BlockedNumberContract;
import android.provider.ContactsContract;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.telecom.TelecomManager;
import android.widget.TextView;
import android.widget.Toast;
public class contactsearch extends Activity {
private ListView mListView;
@Override
public void onCreate(Bundle savedInstanceState) {
final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 0;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contactsearch);
if (ContextCompat.checkSelfPermission(contactsearch.this,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(contactsearch.this,
Manifest.permission.READ_CONTACTS)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(contactsearch.this,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
public void blockcontact (View view){
EditText entercontact = (EditText)findViewById(R.id.entercontact);
String name = entercontact.getText().toString();
Toast toast = Toast.makeText(contactsearch.this, getPhoneNumber(name, contactsearch.this), Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 10 , 10);
toast.show();
blockNumber();
}
public void addcontact (View view){
SharedPreferences safetylist = getSharedPreferences("safetylist", Context.MODE_PRIVATE);
SharedPreferences.Editor safetyedit = safetylist.edit();
SharedPreferences safetynumbers = getSharedPreferences("safetynumbers", Context.MODE_PRIVATE);
SharedPreferences.Editor safetynumedit = safetynumbers.edit();
EditText entercontact = (EditText)findViewById(R.id.entercontact);
String name = entercontact.getText().toString();
String number = getPhoneNumber(name, this);
if(number == "Unsaved"){
Toast.makeText(this, "That is not a valid contact", Toast.LENGTH_SHORT).show();
return;
}
safetynumedit.putString("safetynumbers", safetynumbers.getString("safetynumbers", "") + number + "/");
safetynumedit.commit();
safetyedit.putString("safetylist", safetylist.getString("safetylist", "") + name + "/");
safetyedit.commit();
Toast.makeText(this, number, Toast.LENGTH_SHORT).show();
}
public void deletecontact (View view){
SharedPreferences safetylist = getSharedPreferences("safetylist", Context.MODE_PRIVATE);
SharedPreferences.Editor safetyedit = safetylist.edit();
EditText entercontact = (EditText)findViewById(R.id.entercontact);
ArrayList<String> names = toArray("safetylist");
names.remove(names.indexOf(entercontact.getText().toString() + "/"));
String joined = "";
for(int i = 0; i < names.size(); i++){
joined += names.get(i);
}
Toast.makeText(this, joined, Toast.LENGTH_SHORT).show();
safetyedit.putString("safetylist", joined);
safetyedit.commit();
}
public String getPhoneNumber(String name, Context context) {
String ret = null;
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, null);
if (c.moveToFirst()) {
ret = c.getString(0);
}
c.close();
if(ret==null)
ret = "Unsaved";
return ret;
}
public void blockNumber() {
TelecomManager telecomManager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
contactsearch.this.startActivity(telecomManager.createManageBlockedNumbersIntent(), null);
}
public ArrayList<String> toArray (String category) {
SharedPreferences toarray = getSharedPreferences(category, Context.MODE_PRIVATE);
String names = toarray.getString(category, "");
String name = "";
ArrayList<String> newarray = new ArrayList<String>();
for(int i = 0; i < names.length(); i++){
if(names.charAt(i)== '/'){
newarray.add(name + "/");
name = "";
} else {
name = name + Character.toString(names.charAt(i));
}
}
return newarray;
}
}
<file_sep>/app/src/main/java/com/example/katelynsuhr/boozebuddy/EditInfo.java
package com.example.katelynsuhr.boozebuddy;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class EditInfo extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editinfo);
getSupportActionBar().setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),R.drawable.background_color, null));
final TextView name = (TextView)findViewById(R.id.nameval);
final TextView weight = (TextView)findViewById(R.id.weightval);
final TextView age= (TextView)findViewById(R.id.ageval);
final Spinner sex = (Spinner) findViewById(R.id.sexval);
SharedPreferences tracker = getSharedPreferences("userinfo", Context.MODE_PRIVATE);
name.setText(tracker.getString("name", "name"));
weight.setText(tracker.getString("weight", "weight"));
age.setText(tracker.getString("age", "0"));
List<String> list = new ArrayList();
list.add("Male");
list.add("Female");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
sex.setAdapter(adapter);
sex.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if(sex.getSelectedItem().toString() == "Female") {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 5);
Intent intent = new Intent("tips.action.DISPLAY_NOTIFICATION");
PendingIntent broadcast = PendingIntent.getBroadcast(EditInfo.this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), broadcast);
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
public void saveinfo(View view){
SharedPreferences tracker = getSharedPreferences("userinfo", Context.MODE_PRIVATE);
SharedPreferences.Editor infoeditor = tracker.edit();
final EditText name = (EditText)findViewById(R.id.nameval);
final EditText weight = (EditText)findViewById(R.id.weightval);
final EditText age = (EditText)findViewById(R.id.ageval);
final Spinner sex = (Spinner)findViewById(R.id.sexval);
infoeditor.putString("name" , name.getText().toString());
infoeditor.putString("weight" , weight.getText().toString());
infoeditor.putString("age" , (age.getText().toString()));
infoeditor.putString("sex" , sex.getSelectedItem().toString());
infoeditor.commit();
finish();
}
public void editcontacts(View view){
Intent intent = new Intent(EditInfo.this, contactsearch.class);
startActivity(intent);
}
}<file_sep>/app/src/main/java/com/example/katelynsuhr/boozebuddy/cocktail.java
package com.example.katelynsuhr.boozebuddy;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ListView;
public class cocktail extends AppCompatActivity {
ListView lst;
String[] drinkname={"MOJITO", "MARGARITA", "MARTINI-EXTRA DRY" , "PINA COLADA", "SCREWDRIVER", "MARTINI-TRADITIONAL", "BOURBON AND WATER", "VODKA AND TONIC", "GIN AND TONIC", "COSMOPOLITAN"};
String[] desc={"1.3 U.S. standard drinks\n" +
"and has 13.3% alcohol\n" +
"in 6 total fluid ounces.", "1.7 U.S. standard drinks\n" +
"and has 33.3% alcohol\n" +
"in 3 total fluid ounces.", "1.4 U.S. standard drinks\n" + "and has 37.3% alcohol\n" + "in 2.25 total fluid ounces.",
"2.0 U.S. standard drinks\n" + "and has 13.3% alcohol\n" + "in 9 total fluid ounces.", "1.3 U.S. standard drinks\n" + "and has 11.4% alcohol\n" + "in 7 total fluid ounces.",
"1.2 U.S. standard drinks\n" + "and has 32.0% alcohol\n" + "in 2.25 total fluid ounces.", "1.3 U.S. standard drinks\n" + "and has 13.3% alcohol\n" + "in 6 total fluid ounces.",
"1.3 U.S. standard drinks\n" + "and has 13.3% alcohol\n" + "in 6 total fluid ounces.", "1.6 U.S. standard drinks\n" + "and has 13.4% alcohol\n" + "in 7 total fluid ounces.",
"1.3 U.S. standard drinks\n" + "and has 27.3% alcohol\n" + "in 2.75 total fluid ounces."};
Integer[] imgid = {R.drawable.ccimage1, R.drawable.ccimage2, R.drawable.ccimage3, R.drawable.ccimage4, R.drawable.ccimage5,
R.drawable.ccimage6, R.drawable.ccimage7, R.drawable.ccimage8, R.drawable.ccimage9, R.drawable.ccimage10};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_cocktail);
lst = (ListView) findViewById(R.id.listView);
CustomListView customListView = new CustomListView(this,drinkname,desc,imgid);
lst.setAdapter(customListView);
}
}
<file_sep>/app/src/main/java/com/example/katelynsuhr/boozebuddy/msgedit.java
package com.example.katelynsuhr.boozebuddy;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
public class msgedit extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msgedit);
}
public void savemsg(View view){
EditText msg = (EditText)findViewById(R.id.editmsg);
String message = msg.getText().toString();
SharedPreferences custommsg = getSharedPreferences("custommsg", Context.MODE_PRIVATE);
SharedPreferences.Editor newmsg = custommsg.edit();
newmsg.putString("custommsg", custommsg.getString("custommsg", "") + message + "/");
newmsg.commit();
finish();
Intent intent = new Intent (msgedit.this, SendText.class);
startActivity(intent);
}
}
<file_sep>/app/src/main/java/com/example/katelynsuhr/boozebuddy/DiaryMain.java
package com.example.katelynsuhr.boozebuddy;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CalendarView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import java.util.Objects;
import android.os.Handler;
public class DiaryMain extends AppCompatActivity {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
public CalendarAdapter adapter2;
private String date;
List<Nutrition> nutritions;
String stringTest;
List<String> items;
private static final String TAG = "CalendarActivity";
private CalendarView mCalendarView;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diarymain);
mCalendarView = (CalendarView) findViewById(R.id.calendarView);
getSupportActionBar().setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.background_color, null));
//dateChange = mCalendarView.getDate();
mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView CalendarView, int year, int month, int dayOfMonth) {
date = month + "_" + dayOfMonth + "_" + year;
// Toast toast = Toast.makeText(getBaseContext(),
// "Selected Date is\n\n" +date ,
// Toast.LENGTH_SHORT);
// toast.show();
SharedPreferences sharedPreferences = getSharedPreferences("DateDetails", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("date", date);
editor.apply();
// if(BoozeUtil.isExist(DiaryMain.this, date)) {
// updateListView(date);
// }
updateListView(date);
}
});
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
date = month + "_" + dayOfMonth + "_" + year;
String currentFile = BoozeUtil.readFile(this, date);
SharedPreferences sharedPreferences = getSharedPreferences("DateDetails", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("date", date);
editor.apply();
// if (BoozeUtil.isExist(this, currentDate)) {
// Toast.makeText(this, "TRUE" + currentFile, Toast.LENGTH_LONG).show();
// }
//Checks if there is a file already created for the current date, if there is one,
//if populates the list view with the drinks from that day
if (BoozeUtil.isExist(this, date)) {
Log.d("File is already created", "true");
updateListView(date);
} else {
return;
}
}
/* List View helper function */
public void updateListView(final String selectedDate) {
stringTest = BoozeUtil.readFile(DiaryMain.this, selectedDate);
Log.i("stringTest", stringTest);
items = Arrays.asList(stringTest.split("/"));
nutritions = new ArrayList<>();
final List<String> cal = new ArrayList<>();
final int total = 0;
Nutrition nutrition = null;
String val;
final TextView tv = (TextView) findViewById(R.id.addCalories);
for (int i = 0; i < items.size(); i++) {
int remainder = i % 4;
String n;
//Item id
if (remainder == 0) {
nutrition = new Nutrition();
String l = items.get(i);
nutrition.setItemId(l);
//Item name
} else if (remainder == 1) {
String m = items.get(i);
assert nutrition != null;
nutrition.setItemName(m);
//Item calories
} else if (remainder == 2) {
n = items.get(i);
val = items.get(i);
cal.add(val);
Log.i("Calorie val", cal.toString());
assert nutrition != null;
nutrition.setCalories(n);
//Item brand
} else if (remainder == 3) {
String p = items.get(i);
assert nutrition != null;
nutrition.setBrandName(p);
nutritions.add(nutrition);
}
int sum = 0;
for(String num : cal) {
Float a = Float.parseFloat(num);
int b = (int)Math.round(a);
sum+=b;
}
String stringCal = Float.toString(sum);
Log.d("MyInt","Total Calories = "+sum);
tv.setText(stringCal);
}
final SwipeMenuListView listView2 = (SwipeMenuListView)findViewById(R.id.drink_listview);
adapter2 = new CalendarAdapter(DiaryMain.this, nutritions);
listView2.setAdapter(adapter2);
adapter2.notifyDataSetChanged();
SwipeMenuCreator creator = new SwipeMenuCreator() {
@Override
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(
getApplicationContext());
// set item background
openItem.setBackground(new ColorDrawable(Color.rgb(66, 149,154)));
// set item width
openItem.setWidth(170);
// set item title
openItem.setTitle("View");
// set item title fontsize
openItem.setTitleSize(18);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(
getApplicationContext());
// set item background
deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
0x3F, 0x25)));
// set item width
deleteItem.setWidth(170);
// set a icon
deleteItem.setIcon(R.drawable.ic_trash);
// add to menu
menu.addMenuItem(deleteItem);
}
};
listView2.setMenuCreator(creator);
listView2.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
Nutrition selectedFromList = (Nutrition) listView2.getItemAtPosition(position);
switch (index) {
case 0:
Log.i("POSITION", selectedFromList.toString());
Intent intent = new Intent(menu.getContext(), DrinkOutput.class);
intent.putExtra("item_id", selectedFromList.getItemId());
intent.putExtra("brand_name", selectedFromList.getBrandName());
intent.putExtra("item_name", selectedFromList.getItemName());
intent.putExtra("nf_calories", selectedFromList.getCalories());
startActivity(intent);
Log.d(TAG, "onMenuItemClick: clicked item " + index);
break;
case 1:
Log.i("POSITION", selectedFromList.toString());
Log.i("Nutritions Array List", nutritions.toString());
Log.i("File Data", stringTest);
Log.i("Items ", items.toString());
//items.get(selectedFromList);
String data1 = nutritions.get(position).getCalories();
cal.remove(data1);
Log.i("Remainder",cal.toString());
//int sum = 0;
String input = tv.getText().toString();
float sumInput = Float.parseFloat(input);
float deleteDrink = Float.parseFloat(data1);
int difference = (int) Math.round(sumInput - deleteDrink);
String result = Float.toString(difference);
Log.d("MyInt","Total Calories = "+result);
TextView tv = (TextView) findViewById(R.id.addCalories);
tv.setText(result);
// og.i("Selected Item", data1);
nutritions.remove(selectedFromList);
String itemLine = selectedFromList.getItemId();
Log.d("itemLine", itemLine);
BoozeUtil.removeDrink(DiaryMain.this, selectedDate, itemLine);
adapter2.notifyDataSetChanged();
// adapter2.notifyDataSetChanged();
// cal.remove(selectedFromList);
// Log.d(TAG, "Item"+selectedFromList.toString());
//adapter2.notifyDataSetChanged();
//Log.d(TAG, "onMenuItemClick: clicked item " + index);
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem menu) {
switch (menu.getItemId()) {
case R.id.action_mainmenu:
Intent intent = new Intent(DiaryMain.this, MainActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_hamburger, menu);
return true;
}
@Override
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putSerializable("dateClicked", date);
}
public void foodClick (View view){
Intent intent = new Intent(DiaryMain.this, DiarySearch.class);
startActivity(intent);
}
}
<file_sep>/app/src/main/java/com/example/katelynsuhr/boozebuddy/safety.java
package com.example.katelynsuhr.boozebuddy;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class safety extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_safety);
getSupportActionBar().setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),R.drawable.background_color, null));
SharedPreferences safetylist = getSharedPreferences("numcount", Context.MODE_PRIVATE);
SharedPreferences.Editor numeditor = safetylist.edit();
numeditor.apply();
}
@Override
public boolean onOptionsItemSelected(MenuItem menu) {
switch (menu.getItemId()) {
case R.id.action_mainmenu:
Intent intent = new Intent(safety.this, MainActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_hamburger, menu);
return true;
}
public void contactview_main (View view) {
Intent intent = new Intent(safety.this, contactsearch.class);
startActivity(intent);
}
}<file_sep>/app/src/main/java/com/example/katelynsuhr/boozebuddy/BoozeFiles.java
package com.example.katelynsuhr.boozebuddy;
import android.content.Context;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.CharacterCodingException;
/**
* Created by kennedybagnol on 11/27/17.
*/
class BoozeFiles {
private File file;
private File path;
private String category;
private String name;
private int date;
BoozeFiles(String name, String category, Context context) {
this.name = name;
this.category = category;
this.path = context.getFilesDir();
this.file = new File(path, name);
}
void writeFile(BoozeFiles file, String data) {
try {
FileOutputStream writer = new FileOutputStream(file.file, true);
writer.write((data + "/").getBytes());
writer.close();
} catch(IOException ie) {
ie.printStackTrace();
}
}
//
void writeDrink(String id, String drink, String calories, String brand) {
try {
FileOutputStream writer = new FileOutputStream(file, true);
writer.write((id +"/").getBytes());
writer.write((drink + "/").getBytes());
writer.write((calories + "/").getBytes());
writer.write((brand+"/"+"\n").getBytes());
// writer.write((nutrients + "/").getBytes());
writer.close();
} catch (IOException ie) {
ie.printStackTrace();
}
}
// void writeDrink(String id, String drink, String calories, String brand) {
// try {
// FileOutputStream writer = new FileOutputStream(file, true);
// writer.write((id +"\n").getBytes());
// writer.write((drink + "\n").getBytes());
// writer.write((calories + "\n").getBytes());
// writer.write((brand + "\n").getBytes());
// // writer.write((nutrients + "/").getBytes());
// writer.close();
// } catch (IOException ie) {
// ie.printStackTrace();
// }
// }
String readDrink(BoozeFiles file){
int length = (int) file.file.length();
byte[] bytes = new byte[length];
try {
FileInputStream in = new FileInputStream(file.file);
in.read(bytes);
in.close();
} catch (IOException ie) {
ie.printStackTrace();
}
String contents = new String(bytes);
String drink = "";
String someString = "/";
char slash = someString.charAt(0);
int track = 0;
for (int i = 0; i < contents.length(); i++){
char c = contents.charAt(i);
if(c == slash){
track++;
}
if(track%3 == 0){
drink = drink + Character.toString(c);
}
}
return drink;
}
String readCalories(BoozeFiles file){
int length = (int) file.file.length();
byte[] bytes = new byte[length];
try {
FileInputStream in = new FileInputStream(file.file);
in.read(bytes);
in.close();
} catch (IOException ie) {
ie.printStackTrace();
}
String contents = new String(bytes);
String calories = "";
String someString = "/";
char slash = someString.charAt(0);
int track = 0;
for (int i = 0; i < contents.length(); i++){
char c = contents.charAt(i);
if(c == slash){
track++;
}
if(track%3 == 1){
calories = calories + Character.toString(c);
}
}
return calories;
}
String readNutrients(BoozeFiles file){
int length = (int) file.file.length();
byte[] bytes = new byte[length];
try {
FileInputStream in = new FileInputStream(file.file);
in.read(bytes);
in.close();
} catch (IOException ie) {
ie.printStackTrace();
}
String contents = new String(bytes);
String nutrients = "";
String someString = "/";
char slash = someString.charAt(0);
int track = 0;
for (int i = 0; i < contents.length(); i++){
char c = contents.charAt(i);
if(c == slash){
track++;
}
if(track%3 == 2){
nutrients = nutrients + Character.toString(c);
}
}
return nutrients;
}
String readBrand(BoozeFiles file){
int length = (int) file.file.length();
byte[] bytes = new byte[length];
try {
FileInputStream in = new FileInputStream(file.file);
in.read(bytes);
in.close();
} catch (IOException ie) {
ie.printStackTrace();
}
String contents = new String(bytes);
String brand = "";
String someString = "/";
char slash = someString.charAt(0);
int track = 0;
for (int i = 0; i < contents.length(); i++){
char c = contents.charAt(i);
if(c == slash){
track++;
}
if(track%3 == 2){
brand = brand + Character.toString(c);
}
}
return brand;
}
void deleteFile(BoozeFiles file){
file.file.delete();
}
String readFile() {
int length = (int) file.length();
byte[] bytes = new byte[length];
try {
FileInputStream in = new FileInputStream(file);
in.read(bytes);
in.close();
} catch (IOException ie) {
ie.printStackTrace();
}
String contents = new String(bytes);
return contents;
}
}
<file_sep>/app/src/main/java/com/example/katelynsuhr/boozebuddy/MainActivity.java
package com.example.katelynsuhr.boozebuddy;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private final int SPLASH_DISPLAY_LENGTH = 4000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro_menu);
getSupportActionBar().setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),R.drawable.background_color, null));
}
public void diary_main (View view){
Intent intent = new Intent(MainActivity.this, DiaryMain.class);
startActivity(intent);
}
public void intro_party (View view){
Intent intent = new Intent(MainActivity.this, partymode.class);
startActivity(intent);
}
public void intro_profile (View view){
Intent intent = new Intent(MainActivity.this, UserProfile.class);
startActivity(intent);
}
public void drunkdial (View view){
Intent intent = new Intent(MainActivity.this, DrunkDial.class);
startActivity(intent);
}
public void alarm (View view){
Intent intent = new Intent(MainActivity.this, alarm.class);
startActivity(intent);
}
}
<file_sep>/app/src/main/java/com/example/katelynsuhr/boozebuddy/MacroNutrientAdapter.java
package com.example.katelynsuhr.boozebuddy;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MacroNutrientAdapter extends BaseAdapter {
private Context context;
private Map<String, String> map;
private List<String> macros;
public MacroNutrientAdapter(Context context, Map<String, String> map) {
this.context = context;
this.map = map;
macros = new ArrayList<>(map.keySet());
}
@Override
public int getCount() {
return map.size();
}
@Override
public String getItem(int position) {
return macros.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final View result;
if (convertView == null) {
result = LayoutInflater.from(parent.getContext()).inflate(R.layout.macronutrient_single_listview, parent, false);
} else {
result = convertView;
}
String nutrition = getItem(position);
String value = map.get(nutrition);
if(value.equals("null")){
value = ("0");
}
TextView nutrientName = (TextView) result.findViewById(R.id.nutrientName);
TextView nutrientValue = (TextView) result.findViewById(R.id.nutrientValue);
nutrientName.setText(nutrition);
nutrientValue.setText(value);
return result;
}
}
<file_sep>/app/src/main/java/com/example/katelynsuhr/boozebuddy/DrunkDial.java
package com.example.katelynsuhr.boozebuddy;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class DrunkDial extends AppCompatActivity {
ListView list;
List listlist = new ArrayList();
ArrayAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drunk_dial);
SharedPreferences toarray = getSharedPreferences("safetylist", Context.MODE_PRIVATE);
String names = toarray.getString("safetylist", "");
list = (ListView)findViewById(R.id.safetyview);
String name = "";
for(int i = 0; i < names.length(); i++){
if(names.charAt(i)== '/'){
listlist.add(name);
name = "";
} else {
name = name + Character.toString(names.charAt(i));
}
}
adapter = new ArrayAdapter(DrunkDial.this, R.layout.mytextview, listlist);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SharedPreferences textname = getSharedPreferences("textname", Context.MODE_PRIVATE);
SharedPreferences.Editor nameeditor = textname.edit();
nameeditor.putString("name", list.getItemAtPosition(position).toString());
nameeditor.commit();
Intent intent = new Intent(DrunkDial.this, SendText.class);
startActivity(intent);
}
});
}
}
| f47ea1d3d364a743e82aa123b43434f796ae752e | [
"Java"
] | 10 | Java | ksuhr1/BoozeBuddy | 3477d6c591246ce8e903f78181939bfbc00a3b86 | 4cb91df5fdcb3671cd5af2d63727a497d1a9f13a |
refs/heads/main | <file_sep>using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ProxyChecker
{
internal class ProxyList
{
private List<Leaf.xNet.ProxyClient> proxyClients;
private object lockerProxy;
private int indexOfCurrentProxyFromPool;
public ProxyList()
{
proxyClients = new List<Leaf.xNet.ProxyClient>();
lockerProxy = new object();
indexOfCurrentProxyFromPool = 0;
}
public int ReadFromFile(string fileName, Leaf.xNet.ProxyType proxyType)
{
try
{
var fileLines = File.ReadAllLines(fileName).ToList();
fileLines.ForEach(line =>
{
Leaf.xNet.ProxyClient proxyClient;
if (Leaf.xNet.ProxyClient.TryParse(proxyType, line, out proxyClient))
{
proxyClients.Add(proxyClient);
}
});
return fileLines.Count;
}
catch { }
return 0;
}
public Leaf.xNet.ProxyClient GetProxyClient()
{
lock (lockerProxy)
{
if (indexOfCurrentProxyFromPool == proxyClients.Count)
{
indexOfCurrentProxyFromPool = 0;
}
return proxyClients[indexOfCurrentProxyFromPool++];
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Threading;
namespace ProxyChecker
{
internal class Program
{
const string proxyFileName = "proxy.txt";
const int maxThreadsNumber = 100;
const Leaf.xNet.ProxyType proxyType = Leaf.xNet.ProxyType.HTTP;
const int IterationsAmount = 10;
static void Main(string[] args)
{
Console.WriteLine($"Файл с прокси {proxyFileName}, тип {proxyType}");
ProxyList proxyList = new ProxyList();
int loadedProxyNumber = proxyList.ReadFromFile(proxyFileName, proxyType);
Console.WriteLine($"Загружено {loadedProxyNumber} проксей");
if(loadedProxyNumber == 0)
{
Console.ReadKey();
return;
}
int threadsAmount = Math.Min(maxThreadsNumber, loadedProxyNumber);
Console.WriteLine($"Запускаем {threadsAmount} потоков");
var listThreads = StartThreads(threadsAmount, proxyList);
while (listThreads.Exists(x => x.IsAlive))
{
Thread.Sleep(100);
}
Console.WriteLine("Итерации завершены");
Console.ReadKey();
}
static List<Thread> StartThreads(int amount, ProxyList proxyList)
{
var list = new List<Thread>();
for (int i = 0; i < amount; i++)
{
int index = i;
var thread = new Thread(() => { ThreadBody(index, proxyList.GetProxyClient()); });
list.Add(thread);
thread.Start();
}
return list;
}
static string RequestUrl = "http://icanhazip.com/";
static void ThreadBody(int index, Leaf.xNet.ProxyClient proxyClient)
{
Leaf.xNet.HttpRequest httpRequest = new Leaf.xNet.HttpRequest()
{
Proxy = proxyClient,
ConnectTimeout = 10000
};
string tempText = $"Поток {index}, прокси {proxyClient.Host}:{proxyClient.Port}";
for (int i = 0; i < IterationsAmount; i++)
{
try
{
var page = httpRequest.Get(RequestUrl).ToString();
Console.WriteLine($"{tempText} Ответ сайта: {page}");
}
catch (Exception e) { Console.WriteLine(tempText + " Error " + e.Message); }
}
}
}
}
| 6eecb20a50129ebfb8e93e1ebf2bc732ea7ca809 | [
"C#"
] | 2 | C# | AlexWanderer/ProxyChecker | 3b845be9c2cbb4578525df25d0335514ea3ad957 | c671c0ae4a733f228a887f88aedddc029851c8ad |
refs/heads/master | <repo_name>fuxuewei/learning_c-<file_sep>/hello.cpp
#include <iostream>
using namespace std;
void func()
{
//必须重新声明
using namespace std;
cout << "http://c.biancheng.net" << endl;
}
int sum(int n)
{
int total = 0;
for (int i = 1; i <= n; i++)
{
total += i;
}
return total;
}
//内联函数,交换两个数的值
inline void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
// *表示指针类型变量
void Swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// 类 首字母大写
// 一个类必须有构造函数
class Student
{
// 成员变量 public 公有的、protected 受保护的、private 私有的:只能修饰类的成员,不能修饰类;C++中的类没有共有私有之分
private: //私有的
char *m_name;
int m_age;
float m_score;
public: //共有的
//构造函数
Student();
Student(char *name, int age, float score);
char *name;
int age;
float score;
//const成员函数
int getage() const;
//成员函数 ,在类体中定义 自动成为内联函数(inline),不推荐
void say()
{
cout << name << "的年龄是" << age << ",成绩是" << score << endl;
};
void say1(); //内联函数声明,可以增加 inline 关键字,但编译器会忽略
public:
friend void show(Student *pstu); //将show()声明为友元函数
};
int Student::getage() const
{
return m_age;
}
Student::Student()
{
m_name = NULL;
m_age = 0;
m_score = 0.0;
}
Student::Student(char *name, int age, float score)
{
m_name = name;
m_age = age;
m_score = score;
}
//函数定义
inline void Student::say1()
{
cout << name << "的年龄是" << age << ",成绩是" << score << endl;
};
Student liLei; //创建单个对象
Student allStu[100]; //创建对象数组 拥有100个元素,每个元素都是 Student 类型的对象
//非成员函数
void show(Student *pstu)
{
cout << pstu->m_name << "的年龄是 " << pstu->m_age << ",成绩是 " << pstu->m_score << endl;
}
int main()
{
int a, b;
bool flag; //定义布尔变量
cin >> a >> b;
flag = a > b;
cout << "flag = " << flag << endl;
cout << "Input a interge: ";
int n;
cin >> n;
cout << "total:" << sum(n) << endl;
int m1, n1;
cin >> m1 >> n1;
cout << m1 << ", " << n1 << endl;
swap(&m1, &n1);
cout << m1 << ", " << n1 << endl;
//在栈上创建对象
Student stu;
stu.name = "小明";
stu.age = 15;
stu.score = 92.5f;
stu.say();
//在堆上创建对象,分配了内存,但没有名字, 需要使用 new 关键字,使用指针变量来接收指针
Student *pStu = new Student;
pStu->name = "可可宝贝";
pStu->age = 3;
pStu->score = 100;
pStu->say();
delete pStu; //删除对象
return 0;
}
/**
* 堆内存:必须手动释放 new
*
*
*
* **/
/** <iostream> 是 Input Output Stream 的缩写,意思是“输入输出流”
* cin 标准输入 >>
* cout 标准输出 <<
* cerr 标准错误
* endl 换行 end of line
* new 用来动态分配内存 int *p = new int[10]; //分配10个int型的内存空间
* delete 用来释放内存 delete[] p; //new[] 分配的内存需要用 delete[] 释放,它们是一一对应的
* 内联函数(Inline Function):使用内联函数的缺点也是非常明显的
* 编译后的程序会存在多份相同的函数拷贝
* 如果被声明为内联函数的函数体非常大,那么编译后的程序体积也将会变得很大
* 所以再次强调,一般只将那些短小的、频繁调用的函数声明为内联函数。
* 编译器会忽略函数声明处的 inline
* 函数的重载(Function Overloading)重载就是在一个作用范围内(同一个类、同一个命名空间等)有多个名称相同但参数不同的函数。重载的结果是让一个函数名拥有了多种用途
*
* 类:只是一个模板(Template)编译后不占用内存空间,故定义类时不能对成员变量进行初始化,创建对象后给成员变量分配内存后,才可以赋值
* 友元friend:友元函数不同于类的成员函数,在友元函数中不能直接访问类的成员,必须要借助对象
* 友元的关系是单向的,且关系不能传递
* 一般不建议吧整个类声明为友元类,而只将某些成员函数声明为友元函数,这样更安全一些
* 继承 & 派生 :基类,派生类 由于 private 和 protected 继承方式会改变基类成员在派生类中的访问权限,导致继承关系复杂,所以实际开发中我们一般使用 public。
*
* **/ | acb1e00274031a5cdda81efc08f51486586bae2c | [
"C++"
] | 1 | C++ | fuxuewei/learning_c- | 2b76fc2368acb876009d254da86859eceb0d228e | 13e65743060b37558a6395bef50a8e1305d41824 |
refs/heads/master | <repo_name>hwillson/Meteor-Griddle<file_sep>/README.md
# Meteor-Griddle
A smart Meteor wrapper for the [Griddle](http://griddlegriddle.github.io/Griddle/) React component
### Installation
`meteor add utilities:meteor-griddle`
### Usage
#### React Component
The `<MeteorGriddle/>` React component takes the same options as `<Griddle/>`, plus a couple extra ones:
##### Options
- `publication`: the publication that will provide the data
- `collection`: the collection to display
- `matchingResultsCount`: the name of the matching results counter
- `filteredFields`: an array of fields to search through when filtering
##### Example
```jsx
<MeteorGriddle
publication="adminUsers"
collection={Meteor.users}
matchingResultsCount="matching-users"
filteredFields={["email", "username", "emails.address", "services.meteor-developer.username"]}
/>
```
You'll usually want to pass along some of Griddle's [own options](http://griddlegriddle.github.io/Griddle/properties.html), too.
#### Publication
To use Griddle, you need to define a publication in your own codebase. That publication takes two `query` and `options` arguments from the client.
##### Example
```js
Meteor.publish('adminUsers', function (query, options) {
if(Users.isAdminById(this.userId)){
var users = Meteor.users.find(query, options);
// can't reuse "users" cursor
Counts.publish(this, 'matching-users', Meteor.users.find(query, options));
return users;
}
});
```
##### Notes
- The publication should publish a count of matching results using the [Publish Counts](https://github.com/percolatestudio/publish-counts) package.
- Note that [an issue with the Publish Counts package](https://github.com/percolatestudio/publish-counts/issues/58) prevents you from reusing the same cursor.
- You're trusted to make your own security checks on the `query` and `options` arguments.<file_sep>/package.js
Package.describe({
name: "utilities:meteor-griddle",
summary: "A smart Meteor wrapper for the Griddle React component",
version: "0.1.0",
git: "https://github.com/meteor-utilities/meteor-griddle.git"
});
Npm.depends({
"griddle-react": "0.3.1",
"externalify": "0.1.0"
});
Package.onUse(function(api) {
api.versionsFrom("METEOR@1.0");
api.use([
'react@0.14.3',
'cosmos:browserify@0.9.3',
'tmeasday:publish-counts@0.7.3'
]);
api.addFiles([
'package.browserify.js',
'package.browserify.options.json'
], ['client', 'server']);
api.addFiles([
'MeteorGriddle.jsx'
], 'client');
api.export([
'MeteorGriddle'
]);
});
| 0ca2ba6d3492e1543d88de73693c795aad5c2726 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | hwillson/Meteor-Griddle | 0f076b6ac5b777f87d5125058b9c4f8b13ac91e2 | 2ac798d9f7428bc3a52003c46e247f898a54b4c4 |
refs/heads/master | <repo_name>n1try/pyquadkey2<file_sep>/tests/__init__.py
import os
import sys
from unittest import TestLoader, TestSuite, TextTestRunner
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
def run():
from tests import test_quadkey, test_util
from tests.tilesystem import test_tilesystem
loader: TestLoader = TestLoader()
suite: TestSuite = TestSuite()
suite.addTests(loader.loadTestsFromModule(test_quadkey))
suite.addTests(loader.loadTestsFromModule(test_tilesystem))
suite.addTests(loader.loadTestsFromModule(test_util))
TextTestRunner().run(suite)
if __name__ == '__main__':
run()
<file_sep>/docs/installation.md
# Installation
## Requirements
This library requires **Python 3.6** or higher. To compile it by yourself, Cython is required in addition.
## Using Pip
* `pip3 install pyquadkey2`
Pip installation is only tested for Linux and Mac, yet. If you encounter problems with the installation on Windows, please report them as a new issue.
## From archive
* Download the latest [release](https://github.com/n1try/pyquadkey2/releases) as archive (`.tar.gz`) or wheel (`.whl`), e.g. `0.1.1.tar.gz`
* Install it with pip: `pip3 install 0.1.1.tar.gz`
## From source
* Clone repository: `git clone https://github.com/n1try/pyquadkey2`
* Make sure Cython is installed: `pip3 install cython`
* Compile Cython modules: `cd pyquadkey2/quadkey/tilesystem && python3 setup.py build_ext --inplace && ../../`
* Install the library with Pip: `pip3 install .`
## Troubleshooting
* `ImportError: cannot import name 'tilesystem'`: Simply try `pip3 install --upgrade pyquadkey2` once again. Second time usually works, as required build extensions are installed then. This is a known issue and will be fixed in the future.
<file_sep>/tests/test_util.py
import os
import sys
import unittest
from unittest import TestCase
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../src'))
from pyquadkey2.quadkey.util import *
class UtilTest(TestCase):
def testPrecondition(self):
self.assertTrue(self.pre(True))
with self.assertRaises(AssertionError):
self.pre(False)
def testPostcondition(self):
pass
@precondition(lambda c, x: x is True)
def pre(self, x):
return x
if __name__ == '__main__':
unittest.main()
<file_sep>/tests/tilesystem/test_tilesystem.py
import sys
import unittest
from unittest import TestCase
sys.path.append('../src')
from pyquadkey2.quadkey import TileAnchor
from pyquadkey2.quadkey.tilesystem import tilesystem
class TileSystemTest(TestCase):
def testGroundResolution(self):
self.assertAlmostEqual(936.87, tilesystem.ground_resolution(40., 7), 2)
def testGeoToPixel(self):
self.assertEqual((6827, 12405), tilesystem.geo_to_pixel((40., -105.), 7))
def testGeoToPixelClip(self):
self.assertEqual(tilesystem.geo_to_pixel((40., 180.), 7), tilesystem.geo_to_pixel((40., 181.), 7))
def testPixelToGeo(self):
self.assertEqual((40.002372, -104.996338), tilesystem.pixel_to_geo((6827, 12405), 7))
def testPixelToTile(self):
self.assertEqual((26, 48), tilesystem.pixel_to_tile((6827, 12405)))
def testTileToPixel(self):
self.assertEqual((6656, 12288), tilesystem.tile_to_pixel((26, 48), TileAnchor.ANCHOR_NW))
def testTileToQuadkey(self):
self.assertEqual('0231010', tilesystem.tile_to_quadkey((26, 48), 7))
def testQuadkeyToTile(self):
self.assertEqual(((26, 48), 7), tilesystem.quadkey_to_tile('0231010'))
def testQuadkeyToQuadint(self):
self.assertEqual(1953184653288407055, tilesystem.quadkey_to_quadint('012301230123012'))
self.assertEqual(1379860704579813385, tilesystem.quadkey_to_quadint('010302121'))
def testQuadintToQuadkey(self):
self.assertEqual('012301230123012', tilesystem.quadint_to_quadkey(1953184653288407055))
self.assertEqual('010302121', tilesystem.quadint_to_quadkey(1379860704579813385))
if __name__ == '__main__':
unittest.main()
<file_sep>/src/pyquadkey2/quadkey/tilesystem/setup.py
# python3 setup.py build_ext --inplace
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
name='tilesystem',
ext_modules=cythonize(
Extension(
'tilesystem',
sources=['tilesystem.pyx'],
include_dirs=[]
)
)
)
<file_sep>/README.md
# 🌍 pyquadkey2
[](https://docs.muetsch.io/pyquadkey2/)
This is a feature-rich Python implementation of [QuadKeys](https://docs.microsoft.com/en-us/bingmaps/articles/bing-maps-tile-system), an approach to **geographical tiling**, that was proposed by Microsoft to be used for Bing Maps.
In essence, the concept is to **recursively** divide the flat, two-dimensional world map into squares. Each square contains **four squares** as children, which again contain four squares and so on, up **centimeter-level precision**. Each of these squares is **uniquely identifiable with a string** like `021030032`.
For more details on the concept, please refer to the [original article](https://docs.microsoft.com/en-us/bingmaps/articles/bing-maps-tile-system).
[n1try/pyquadkey2](https://github.com/n1try/pyquadkey2) originates from a **fork** of [buckhx/QuadKey](https://github.com/buckhx/QuadKey), which is not maintained anymore. It build on top of that project and adds:
* ✅ Several (critical) [bug fixes](https://github.com/buckhx/QuadKey/pull/15)
* ✅ Python 3 support
* ✅ [Type hints](https://docs.python.org/3.6/library/typing.html) for all methods
* ✅ Higher test coverage
* ✅ Cython backend for improved performance
* ✅ 64-bit integer representation of QuadKeys
* ✅ Additional features and convenience methods
## Installation
### Requirements
This library requires **Python 3.6** or higher. To compile it by yourself, Cython is required in addition.
### Using Pip
* `pip3 install pyquadkey2`
Pip installation is only tested for Linux and Mac, yet. If you encounter problems with the installation on Windows, please report them as a new issue.
### From archive
* Download the latest [release](https://github.com/n1try/pyquadkey2/releases) as archive (`.tar.gz`) or wheel (`.whl`), e.g. `0.1.1.tar.gz`
* Install it with pip: `pip3 install 0.1.1.tar.gz`
### From source
* Clone repository: `git clone https://github.com/n1try/pyquadkey2`
* Make sure Cython is installed: `pip3 install cython`
* Compile Cython modules: `cd pyquadkey2/quadkey/tilesystem && python3 setup.py build_ext --inplace && ../../`
* Install the library with Pip: `pip3 install .`
### Troubleshooting
* `ImportError: cannot import name 'tilesystem'`: Simply try `pip3 install --upgrade pyquadkey2` once again. Second time usually works, as required build extensions are installed then. This is a known issue and will be fixed in the future.
## License
Apache 2.0
[](https://buymeacoff.ee/n1try)
<file_sep>/docs/index.md
# 🌍 Introduction
This is a feature-rich Python implementation of [QuadKeys](https://docs.microsoft.com/en-us/bingmaps/articles/bing-maps-tile-system), an approach to **geographical tiling**, that was proposed by Microsoft to be used for Bing Maps.
In essence, the concept is to **recursively** divide the flat, two-dimensional world map into squares. Each square contains **four squares** as children, which again contain four squares and so on, up **centimeter-level precision**. Each of these squares is **uniquely identifiable with a string** like `021030032`.
For more details on the concept, please refer to the [original article](https://docs.microsoft.com/en-us/bingmaps/articles/bing-maps-tile-system).
[n1try/pyquadkey2](https://github.com/n1try/pyquadkey2) originates from a **fork** of [buckhx/QuadKey](https://github.com/buckhx/QuadKey), which is not maintained anymore. It build on top of that project and adds:
* ✅ Several (critical) [bug fixes](https://github.com/buckhx/QuadKey/pull/15)
* ✅ Python 3 support
* ✅ [Type hints](https://docs.python.org/3.6/library/typing.html) for all methods
* ✅ Higher test coverage
* ✅ Cython backend for improved performance
* ✅ 64-bit integer representation of QuadKeys
* ✅ Additional features and convenience methods
[](https://buymeacoff.ee/n1try)<file_sep>/tests/test_quadkey.py
import os
import sys
import unittest
from operator import attrgetter
from unittest import TestCase
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../src'))
from pyquadkey2 import quadkey
class QuadKeyTest(TestCase):
def testInit(self):
key = '0321201120'
qk = quadkey.from_str(key)
self.assertIsInstance(qk, quadkey.QuadKey)
self.assertEqual(key, qk.key)
def testInitEmptyInput(self):
with self.assertRaises(AssertionError):
quadkey.from_str('')
def testInitInvalidKey(self):
with self.assertRaises(AssertionError):
quadkey.from_str('0156510012')
def testFromGeo(self):
self.assertEqual('1202032333311320', quadkey.from_geo((49.014205, 8.420025), 16).key)
def testFromGeoInvalidLevel(self):
with self.assertRaises(AssertionError):
quadkey.from_geo((49.014205, 8.420025), 32)
def testEquality(self):
one = quadkey.from_str('00')
two = quadkey.from_str('00')
three = quadkey.from_str('0')
self.assertEqual(one, two)
self.assertNotEqual(one, three)
def testSortability(self):
keys = [quadkey.from_str(s) for s in ['200', '100']]
keys_ordered = [quadkey.from_str(s) for s in ['100', '200']]
self.assertEqual(keys_ordered, sorted(keys))
def testChildren(self):
qk = quadkey.from_str('0')
self.assertEqual({'00', '01', '02', '03'}, set([c.key for c in qk.children()]))
def testChildrenMaxLevel(self):
qk = quadkey.from_str(''.join(['0'] * quadkey.LEVEL_RANGE[1]))
self.assertEqual(set(), set(qk.children()))
def testChildrenAtLevel(self):
qk = quadkey.from_str('0')
expected_children = set(map(quadkey.from_str, ['000', '001', '002', '003', '010', '011', '012', '013', '020', '021', '022', '023', '030', '031', '032', '033']))
self.assertEqual(expected_children, set(qk.children(at_level=3)))
def testChildrenAtInvalidLevel(self):
qk = quadkey.from_str('0')
self.assertEqual(set(), set(qk.children(at_level=32)))
def testParent(self):
self.assertEqual(quadkey.from_str('000'), quadkey.from_str('0001').parent())
def testParentMinLevel(self):
with self.assertRaises(AssertionError):
quadkey.from_str('0').parent()
def testAncestorDescendent(self):
one = quadkey.from_str('0')
two = quadkey.from_str('0101')
three = quadkey.from_str('1')
self.assertTrue(one.is_descendent(two))
self.assertFalse(two.is_descendent(one))
self.assertTrue(two.is_ancestor(one))
self.assertFalse(three.is_ancestor(one))
def testNearby(self):
self.assertEqual({'0', '1', '2', '3'}, set(quadkey.from_str('0').nearby()))
self.assertEqual({'00', '01', '10', '02', '03', '12'}, set(quadkey.from_str('01').nearby()))
def testNearbyWithRadius(self):
self.assertEqual(
{'023', '012', '103', '212', '021', '303', '033', '300', '203', '030', '211', '102', '003', '301', '031', '302', '201', '032', '120', '123', '213', '013', '122', '121', '210'},
set(quadkey.from_str('033').nearby(n=2))
)
def testDifference(self):
_from = quadkey.from_str('0320101102')
_to = quadkey.from_str('0320101110')
diff = {'0320101102', '0320101100', '0320101103', '0320101101', '0320101112', '0320101110'}
self.assertEqual(diff, set([qk.key for qk in _to.difference(_from)]))
self.assertEqual(diff, set([qk.key for qk in _from.difference(_to)]))
def testDifference2(self):
qk1 = quadkey.QuadKey('033')
qk2 = quadkey.QuadKey('003')
diff = [qk.key for qk in qk1.difference(qk2)]
self.assertEqual(set(diff), {'033', '031', '013', '032', '030', '012', '023', '021', '003'})
def testDifference3(self):
qk1 = quadkey.QuadKey('021')
qk2 = quadkey.QuadKey('011')
diff = [qk.key for qk in qk1.difference(qk2)]
self.assertEqual(set(diff), {'011', '013', '031', '010', '012', '030', '001', '003', '021'})
def testBbox(self):
qk1 = quadkey.QuadKey('033')
qk2 = quadkey.QuadKey('003')
bbox = quadkey.QuadKey.bbox([qk1, qk2])
self.assertEqual({'033', '031', '013', '032', '030', '012', '023', '021', '003'}, set(map(attrgetter('key'), bbox)))
def testSide(self):
qk = quadkey.QuadKey(''.join(['0'] * 10))
self.assertEqual(int(qk.side()), 39135)
def testArea(self):
qk = quadkey.QuadKey(''.join(['0'] * 10))
self.assertEqual(int(qk.area()), 1531607591)
if __name__ == '__main__':
unittest.main()
<file_sep>/docs/methods.md
# Methods
## children
`children(self, at_level: int = -1) -> List['QuadKey']`
Get all children of the specified level.
* `at_level` (default: 1): Level of the children keys to be returned. Has to be less than the current QuadKey's level.
**Example:**
```python
from pyquadkey2.quadkey import QuadKey
qk = QuadKey('0')
qk.children(at_level=2) # -> ['000', '001', '002', '003', '010', '011', '012', '013', '020', '021', '022', '023', '030', '031', '032', '033']
```
## parent
`parent(self) -> 'QuadKey'`
Get the immediate parent QuadKey.
## nearby
`nearby(self, n: int = 1) -> List[str]`
Get all QuadKeys at the same level that are in the current key's neighborhood of the specified radius `n`.
* `n` (default: 1): Rectangular "radius" to consider.
**Example:**
 
Left: `n=1`, right: `n=2`
```python
from pyquadkey2.quadkey import QuadKey
qk = QuadKey('032')
qk.nearby() # -> ['021', '031', '023', '033', '201', '032', '030', '211', '210']
qk.nearby(n=2) # -> ['023', '012', '022', '212', '210', '021', '033', '300', '203', '200', '030', '102', '003', '031', '302', '201', '032', '202', '120', '213', '002', '013', '122', '211', '020']
```
## is_ancestor
`is_ancestor(self, node: 'QuadKey')`
Whether or not the given key is an ancestor of the current one.
* `node`: The other QuadKey to check against
## is_descendent
`is_descendent(self, node: 'QuadKey')`
Whether or not the given key is a descendent of the current one.
* `node`: The other QuadKey to check against
## side
`side(self)`
Side length in meters of the current key's square projected onto a two-dimensional world map.
## area
`area(self)`
Area in m² of the current key's square projected onto a two-dimensional world map.
## difference
`difference(self, to: 'QuadKey') -> List['QuadKey']`
Returns all keys of the same level that are "between" (in two-dimensional space) the current key and a given one.
* `to`: The second QuadKey

```python
from pyquadkey2.quadkey import QuadKey
qk1 = QuadKey('032')
qk2 = QuadKey('011')
qk1.difference(qk1) # -> [011, 013, 031, 033, 010, 012, 030, 032]
```
## to_tile
`to_tile(self) -> Tuple[Tuple[int, int], int]`
Returns the current key as a tile-tuple and the corresponding level.
## to_pixel
`to_pixel(self, anchor: TileAnchor = TileAnchor.ANCHOR_NW) -> Tuple[int, int]`
Returns the current key as a pixel in a two-dimensional matrix.
* `anchor` (default: `TileAnchor.ANCHOR_NW`): "Corner" of the current QuadKey's square / tile to get the pixel value for. Choices are: `ANCHOR_NW`, `ANCHOR_SW`, `ANCHOR_NE`, `ANCHOR_SE`, `ANCHOR_CENTER`.
## to_geo
`to_geo(self, anchor: TileAnchor = TileAnchor.ANCHOR_NW) -> Tuple[float, float]`
Returns the current key as GPS coordinates.
* `anchor` (default: `TileAnchor.ANCHOR_NW`): "Corner" of the current QuadKey's square / tile to get the geo coordinate value for. Choices are: `ANCHOR_NW`, `ANCHOR_SW`, `ANCHOR_NE`, `ANCHOR_SE`, `ANCHOR_CENTER`.
## to_quadint
`to_quadint(self) -> int`
Returns the current key as 64-bit integer for better space efficiency.
* `anchor` (default: `TileAnchor.ANCHOR_NW`): "Corner" of the current QuadKey's square / tile to get the geo coordinate value for. Choices are: `ANCHOR_NW`, `ANCHOR_SW`, `ANCHOR_NE`, `ANCHOR_SE`, `ANCHOR_CENTER`.
## QuadKey.bbox (static)
`bbox(quadkeys: List['QuadKey']) -> List['QuadKey']`
Similar to [difference](#difference), but as a static method. In addition this method accepts multiple keys and returns all keys, that are contained in a bounding box spanned by the two outer-most `quadkeys`.
```python
from pyquadkey2.quadkey import QuadKey
qks = [QuadKey('032'), QuadKey('011')]
QuadKey.bbox(qks) # -> [011, 013, 031, 033, 010, 012, 030, 032]
```
## QuadKey.from_geo (static)
`from_geo(geo: Tuple[float, float], level: int) -> 'QuadKey'`
See [instantiation](/instantiation).
## QuadKey.from_str (static)
`from_str(qk_str: str) -> 'QuadKey'`
See [instantiation](/instantiation).
## QuadKey.from_int (static)
`from_int(qk_int: int) -> 'QuadKey'`
See [instantiation](/instantiation).<file_sep>/src/pyquadkey2/quadkey/__init__.py
import itertools
import re
from enum import IntEnum
from typing import Tuple, List, Iterable, Generator, Dict
try:
from pyquadkey2 import tilesystem
except (ModuleNotFoundError, ImportError):
from .tilesystem import tilesystem
from .util import precondition
LAT_STR: str = 'lat'
LON_STR: str = 'lon'
LATITUDE_RANGE: Tuple[float, float] = (-85.05112878, 85.05112878)
LONGITUDE_RANGE: Tuple[float, float] = (-180., 180.)
# Due to the way quadkeys are represented as 64-bit integers (https://github.com/joekarl/binary-quadkey/blob/64f76a15465169df9d0d5e9e653906fb00d8fa48/example/java/src/main/java/com/joekarl/binaryQuadkey/BinaryQuadkey.java#L67),
# we can not use 31 character quadkeys, but only 29, since five bits explicitly encode the zoom level
LEVEL_RANGE: Tuple[int, int] = (1, 29)
KEY_PATTERN: re = re.compile("^[0-3]+$")
class TileAnchor(IntEnum):
ANCHOR_NW = 0
ANCHOR_NE = 1
ANCHOR_SW = 2
ANCHOR_SE = 3
ANCHOR_CENTER = 4
def valid_level(level: int) -> bool:
return LEVEL_RANGE[0] <= level <= LEVEL_RANGE[1]
def valid_geo(lat: float, lon: float) -> bool:
return LATITUDE_RANGE[0] <= lat <= LATITUDE_RANGE[1] and LONGITUDE_RANGE[0] <= lon <= LONGITUDE_RANGE[1]
def valid_key(key: str) -> bool:
return KEY_PATTERN.match(key) is not None
class QuadKey:
@precondition(lambda c, key: valid_key(key))
def __init__(self, key: str):
self.key: str = key
tile_tuple: Tuple[Tuple[int, int], int] = tilesystem.quadkey_to_tile(self.key)
self.tile: Tuple[int, int] = tile_tuple[0]
self.level: int = tile_tuple[1]
def children(self, at_level: int = -1) -> List['QuadKey']:
if at_level <= 0:
at_level = self.level + 1
if self.level >= LEVEL_RANGE[1] or at_level > LEVEL_RANGE[1] or at_level <= self.level:
return []
return [QuadKey(self.key + ''.join(k)) for k in itertools.product('0123', repeat=at_level - self.level)]
def parent(self) -> 'QuadKey':
return QuadKey(self.key[:-1])
def nearby_custom(self, config: Tuple[Iterable[int], Iterable[int]]) -> List[str]:
perms = set(itertools.product(config[0], config[1]))
tiles = set(map(lambda perm: (abs(self.tile[0] + perm[0]), abs(self.tile[1] + perm[1])), perms))
return [tilesystem.tile_to_quadkey(tile, self.level) for tile in tiles]
def nearby(self, n: int = 1) -> List[str]:
return self.nearby_custom((range(-n, n + 1), range(-n, n + 1)))
def is_ancestor(self, node: 'QuadKey') -> bool:
return not (self.level <= node.level or self.key[:len(node.key)] != node.key)
def is_descendent(self, node) -> bool:
return node.is_ancestor(self)
def side(self) -> float:
return 256 * tilesystem.ground_resolution(0, self.level)
def area(self) -> float:
side = self.side()
return side * side
@staticmethod
def xdifference(first: 'QuadKey', second: 'QuadKey') -> Generator['QuadKey', None, None]:
x, y = 0, 1
assert first.level == second.level
self_tile = list(first.to_tile()[0])
to_tile = list(second.to_tile()[0])
se, sw, ne, nw = None, None, None, None
if self_tile[x] >= to_tile[x] and self_tile[y] <= to_tile[y]:
ne, sw = self_tile, to_tile
elif self_tile[x] <= to_tile[x] and self_tile[y] >= to_tile[y]:
sw, ne = self_tile, to_tile
elif self_tile[x] <= to_tile[x] and self_tile[y] <= to_tile[y]:
nw, se = self_tile, to_tile
elif self_tile[x] >= to_tile[x] and self_tile[y] >= to_tile[y]:
se, nw = self_tile, to_tile
cur = ne[:] if ne else se[:]
while cur[x] >= (sw[x] if sw else nw[x]):
while (sw and cur[y] <= sw[y]) or (nw and cur[y] >= nw[y]):
yield from_tile(tuple(cur), first.level)
cur[y] += 1 if sw else -1
cur[x] -= 1
cur[y] = ne[y] if ne else se[y]
def difference(self, to: 'QuadKey') -> List['QuadKey']:
return [qk for qk in self.xdifference(self, to)]
@staticmethod
def bbox(quadkeys: List['QuadKey']) -> List['QuadKey']:
assert len(quadkeys) > 0
level = quadkeys[0].level
tiles = [qk.to_tile()[0] for qk in quadkeys]
x, y = zip(*tiles)
ne = from_tile((max(x), min(y)), level)
sw = from_tile((min(x), max(y)), level)
return ne.difference(sw)
def to_tile(self) -> Tuple[Tuple[int, int], int]:
return self.tile, self.level
def to_pixel(self, anchor: TileAnchor = TileAnchor.ANCHOR_NW) -> Tuple[int, int]:
return tilesystem.tile_to_pixel(self.tile, anchor)
def to_geo(self, anchor: TileAnchor = TileAnchor.ANCHOR_NW) -> Tuple[float, float]:
pixel = tilesystem.tile_to_pixel(self.tile, anchor)
return tilesystem.pixel_to_geo(pixel, self.level)
def to_quadint(self) -> int:
return tilesystem.quadkey_to_quadint(self.key)
def set_level(self, level: int):
assert level < self.level
self.key = self.key[:level]
self.tile, self.level = tilesystem.quadkey_to_tile(self.key)
def __eq__(self, other):
return isinstance(other, QuadKey) and self.key == other.key
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.key.__lt__(other.key)
def __str__(self):
return self.key
def __repr__(self):
return self.key
def __hash__(self):
return hash(self.key)
@precondition(lambda geo, level: valid_geo(*geo) and valid_level(level))
def from_geo(geo: Tuple[float, float], level: int) -> 'QuadKey':
pixel = tilesystem.geo_to_pixel(geo, level)
tile = tilesystem.pixel_to_tile(pixel)
key = tilesystem.tile_to_quadkey(tile, level)
return QuadKey(key)
def from_tile(tile: Tuple[int, int], level: int) -> 'QuadKey':
return QuadKey(tilesystem.tile_to_quadkey(tile, level))
def from_str(qk_str: str) -> 'QuadKey':
return QuadKey(qk_str)
def from_int(qk_int: int) -> 'QuadKey':
return QuadKey(tilesystem.quadint_to_quadkey(qk_int))
@precondition(lambda geo: valid_geo(*geo))
def geo_to_dict(geo: Tuple[float, float]) -> Dict[str, float]:
return {LAT_STR: geo[0], LON_STR: geo[1]}
<file_sep>/requirements.txt
Cython==0.29.12<file_sep>/setup.py
#!/usr/bin/env python
# https://packaging.python.org/tutorials/packaging-projects/
# python3 setup.py sdist bdist_wheel
# python3 -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*.tar.gz
# mkdocs build
from setuptools import Extension
from setuptools import setup, find_packages
with open('README.md', 'r') as fh:
long_description = fh.read()
setup(
name='pyquadkey2',
version='0.2.0',
description='Python implementation of geographical tiling using QuadKeys as proposed by Microsoft',
long_description=long_description,
long_description_content_type='text/markdown',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/n1try/pyquadkey2',
packages=find_packages('src'),
package_dir={'': 'src'},
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 3',
'Programming Language :: Cython',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS',
'Operating System :: Unix',
'Operating System :: POSIX :: Linux',
'Natural Language :: English',
'Topic :: Scientific/Engineering :: GIS',
'Typing :: Typed'
],
project_urls={
'Bug Tracker': 'https://github.com/n1try/pyquadkey2/issues',
'Source Code': 'https://github.com/n1try/pyquadkey2',
'Documentation': 'https://docs.muetsch.io/pyquadkey2/'
},
keywords='tiling quadkey quadtile geospatial geohash',
python_requires='>=3.6',
ext_modules=[Extension('tilesystem', ['src/pyquadkey2/quadkey/tilesystem/tilesystem.c'])],
ext_package='pyquadkey2'
)
<file_sep>/docs/instantiation.md
# Instantiation
There are **three ways** of instantiating a QuadKey.
## From string representation
Creates a new `QuadKey` object from a tile's string representation.
`from_str(qk_str: str) -> 'QuadKey'`
**Example:**
```python
from pyquadkey2 import quadkey
qk = quadkey.from_str('010302121') # -> 010302121
```
## From integer representation
Creates a new `QuadKey` object from a tile's integer representation
`from_int(qk_int: int) -> 'QuadKey'`
**Example:**
```python
from pyquadkey2 import quadkey
qk = quadkey.from_int(1379860704579813385) # -> 010302121
```
## From coordinates
Creates a new `QuadKey` object from geo / GNSS coordinates
`from_geo(geo: Tuple[float, float], level: int) -> 'QuadKey'`
**Example:**
```python
from pyquadkey2 import quadkey
qk = quadkey.from_geo((49.011011, 8.414971), 9) # -> 120203233
```<file_sep>/src/pyquadkey2/quadkey/util.py
import functools
def condition(precondition=None, postcondition=None):
def decorator(func):
@functools.wraps(func) # preserve name, docstring, etc
def wrapper(*args, **kwargs): # NOTE: no self
if precondition is not None:
assert precondition(*args, **kwargs)
retval = func(*args, **kwargs) # call original function or method
if postcondition is not None:
assert postcondition(retval)
return retval
return wrapper
return decorator
def precondition(check):
return condition(precondition=check)
def postcondition(check):
return condition(postcondition=check)
<file_sep>/src/pyquadkey2/quadkey/tilesystem/tilesystem.pyx
#!python
#cython: boundscheck=False
#cython: wraparound=False
#cython: nonecheck=False
#cython: cdivision=True
#@formatter:off
from libc cimport math
cdef long EARTH_RADIUS = 6378137
cdef (double, double) LATITUDE_RANGE = (-85.05112878, 85.05112878)
cdef (double, double) LONGITUDE_RANGE = (-180., 180.)
ctypedef enum tile_anchor:
ANCHOR_NW
ANCHOR_NE
ANCHOR_SW
ANCHOR_SE
ANCHOR_CENTER
cdef double clip(const double n, const (double, double) min_max):
return min(max(n, min_max[0]), min_max[1])
cdef long map_size(const long level):
cdef unsigned long base = 256
return base << <unsigned long> level
# Alternative map size implementation, inspired by:
# – https://github.com/CartoDB/python-quadkey/blob/a7c53e8e8bd18eb9ba187b345bd2faf525b23ecc/quadkey.c#L194
# – https://github.com/ethlo/jquad/blob/3c0bed3b0433ef5f67e786a41c56af9cc103d7dd/src/main/java/com/ethlo/quadkey/QuadKey.java#L130
# cdef long map_size(const long level):
# cdef unsigned long base = 256
# return (1 << <unsigned long> level) & 0xFFFFFFFF
cpdef double ground_resolution(double lat, const long level):
lat = clip(lat, LATITUDE_RANGE)
return math.cos(lat * math.pi / 180) * 2 * math.pi * EARTH_RADIUS / map_size(level)
cpdef (long, long) geo_to_pixel((double, double) geo, const long level):
cdef double lat, lon, x, y, sin_lat
cdef long pixel_x, pixel_y, ms
lat, lon = geo[0], geo[1]
lat = clip(lat, LATITUDE_RANGE)
lon = clip(lon, LONGITUDE_RANGE)
x = (lon + 180) / 360
sin_lat = math.sin(lat * math.pi / 180)
y = 0.5 - math.log((1 + sin_lat) / (1 - sin_lat)) / (4 * math.pi)
ms = map_size(level)
pixel_x = <long>(clip(x * ms + 0.5, (0, ms - 1)))
pixel_y = <long>(clip(y * ms + 0.5, (0, ms - 1)))
return pixel_x, pixel_y
cpdef (double, double) pixel_to_geo((double, double) pixel, const long level):
cdef double x, y, lat, lon, pixel_x, pixel_y
cdef long ms
pixel_x = pixel[0]
pixel_y = pixel[1]
ms = map_size(level)
x = (clip(pixel_x, (0, ms - 1)) / ms) - 0.5
y = 0.5 - (clip(pixel_y, (0, ms - 1)) / ms)
lat = 90 - 360 * math.atan(math.exp(-y * 2 * math.pi)) / math.pi
lon = 360 * x
return math.round(lat * 1e6) / 1e6, math.round(lon * 1e6) / 1e6
cpdef (long, long) pixel_to_tile(const (long, long) pixel):
return pixel[0] // 256, pixel[1] // 256
cpdef (long, long) tile_to_pixel(const (long, long) tile, tile_anchor anchor):
cdef long pixel[2]
pixel = [tile[0] * 256, tile[1] * 256]
if anchor == ANCHOR_CENTER:
# TODO: should clip on max map size
pixel = [pixel[0] + 256, pixel[1] + 256]
elif anchor == ANCHOR_NE:
pixel = [pixel[0] + 256, pixel[1]]
elif anchor == ANCHOR_SW:
pixel = [pixel[0], pixel[1] + 256]
elif anchor == ANCHOR_SE:
pixel = [pixel[0] + 256, pixel[1] + 256]
return <long>pixel[0], <long>pixel[1]
cpdef str tile_to_quadkey(const (long, long) tile, const long level):
cdef int i
cdef long tile_x, tile_y, mask, bit
cdef char digit
cdef char qk[level]
tile_x = tile[0]
tile_y = tile[1]
quadkey = ''
for i in range(level):
bit = level - i
digit = 48 # ord('0')
mask = 1 << (bit - 1) # if (bit - 1) > 0 else 1 >> (bit - 1)
if (tile_x & mask) is not 0:
digit += 1
if (tile_y & mask) is not 0:
digit += 2
qk[i] = digit
return qk[:level].decode('UTF-8')
cpdef ((long, long), long) quadkey_to_tile(str quadkey):
cdef long tile_x, tile_y, mask, bit
cdef int level, i
tile_x, tile_y = (0, 0)
level = len(quadkey)
for i in range(level):
bit = level - i
mask = 1 << (bit - 1)
if quadkey[level - bit] == '1':
tile_x |= mask
if quadkey[level - bit] == '2':
tile_y |= mask
if quadkey[level - bit] == '3':
tile_x |= mask
tile_y |= mask
return (tile_x, tile_y), level
# Inspired by https://github.com/joekarl/binary-quadkey
cpdef str quadint_to_quadkey(const unsigned long quadint):
cdef int zoom = quadint & 0b11111
cdef int i
cdef unsigned long char_bits
cdef char qk[31]
for i in range(zoom):
bit_loc = (64 - ((i + 1) * 2))
char_bits = ((quadint & (0b11 << bit_loc)) >> bit_loc)
qk[i] = ord(str(char_bits))
return qk[:zoom].decode('UTF-8')
# Inspired by https://github.com/joekarl/binary-quadkey
cpdef unsigned long quadkey_to_quadint(str quadkey):
cdef int zoom = len(quadkey)
cdef int i
cdef unsigned long qi = 0
cdef unsigned long bit_loc
for i in range(zoom):
bit_loc = (64 - ((i + 1) * 2))
qi |= int(quadkey[i]) << bit_loc
qi |= zoom
return qi | 692b29e7fc261575c686955c089cb031c4f18ebd | [
"Markdown",
"Python",
"Text"
] | 15 | Python | n1try/pyquadkey2 | 24e68e48edbd96a357aa533943921e5fda1cc052 | 5f20a71e919078b4c36a14b0b267d20b02e5f458 |
refs/heads/main | <file_sep># 情感分析
from snownlp import SnowNLP
import codecs
import os
import pandas as pd
#将爬取弹幕得到的csv文件转化为txt文件并保存
data = pd.read_csv(r'C:\Users\86136\Desktop\ciyun2\bili_danmu2(1).csv', encoding='utf-8')
with open(r'C:\Users\86136\Desktop\ciyun2\bili.txt','a+', encoding='utf-8') as f:
for line in data.values:
f.write((str(line[0])+'\t'+str(line[1])+'\n'))
#情感波动分析以及可视化
source = open(r'C:\Users\86136\Desktop\ciyun2\bili.txt', "r", encoding='utf-8')
line = source.readlines()
sentimentslist = []
for i in line:
s = SnowNLP(i)
print(s.sentiments)
sentimentslist.append(s.sentiments)
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.arange(0, 39600, 1), sentimentslist, 'r-')
plt.xlabel('Number')
plt.ylabel('Sentiment')
plt.title('Analysis of Sentiments')
plt.show()
<file_sep>import glob
import random
import imageio
import wordcloud
import matplotlib.pyplot as plt
import pandas as pd
import os
data = pd.read_excel(r'D:\juexingniandai\#周恩来#.xlsx', encoding='utf-8')
bool=data.comment.notnull()
data2=data[bool]
#分词
import jieba
def cut_word(text):
return jieba.cut(text)
data2.comment=data2.comment.apply(cut_word)
#停用词处理
def get_stopword():
s = set()
with open(r'D:\juexingniandai\StopWords.txt',encoding = 'UTF-8') as f:
for line in f:
s.add(line.strip())
return s
def remove_stopword(words):
return [word for word in words if word not in stopword]
stopword = get_stopword()
data2.comment= data2.comment.apply(remove_stopword)
data2.comment
#将lisi里的list转化为str
d3= list ( filter ( None,data2.comment))
d4=[]
for i in d3:
x="".join(i)
d4.append(x)
#生成.txt文件,用于词云图
with open(r'D:\juexingniandai\周恩来.txt','w',encoding='utf-8') as f:
for li in d4:
f.write(li+"\n")
def toWordCloud():
with open(r'D:\juexingniandai\周恩来.txt', encoding='utf-8', errors='ignore') as f:
data = f.read()
f.close()
fonts = glob.glob(r'D:\juexingniandai\字体\*.ttf')
font = random.choice(fonts)
color_masks = glob.glob(r'D:\juexingniandai\树.JPG')
color_mask = random.choice(color_masks)
color_mask = imageio.imread(color_mask)
wcd = wordcloud.WordCloud(
font_path=font, # 设置字体
background_color="white", # 背景颜色
max_words=200, # 词云显示的最大词数
mask=color_mask, # 设置背景图片
max_font_size=150, # 字体最大值
mode="RGBA",
width=500,
height=400,
collocations=False
)
wcd.generate(data)
plt.imshow(wcd)
wcd.to_file("ciyuntu_weibo.png")
plt.axis('off')
plt.show()
if __name__ == '__main__':
toWordCloud()<file_sep>import 'echarts/map/js/china'
import china from 'echarts/map/json/china.json'
echarts.registerMap('china', china)
Vue.prototype.$echarts = echarts
<file_sep># 觉醒年代
# 目录
* 项目介绍
* 项目进度
* 项目亮点
* 关于我们
* 鸣谢
# 项目介绍
本项目着眼于当前热门电视剧《`觉醒年代`》,从`B站`、`微博`、`豆瓣`、`百度指数`等处抓取相关数据,结合`新京报`等新闻网站中相关数据,综合进行数据清洗及可视化分析,最后制作网页。
# 项目进度
### 第一阶段:爬取数据
抓取豆瓣热评、微博广场、百度指数相关数据、B站等相关数据,整合新京报等新闻网站相关数据<br>
完成时间:2021年7月16日
### 第二阶段:数据清洗及可视化,网页制作
##### 数据清洗及可视化
将得到的数据在Jupyter NoteBook上进行数据清洗,利用echarts选择合适的形式可视化展示<br>
##### 网页制作
利用DW进行网页框架规整搭建,并同步结合可视化的成果进行制作<br>
完成时间:2021年7月20日
### 第三阶段:视频制作
小组成员依次进行视频录制及剪辑<br>
完成时间:2021年7月20日
#### 第四阶段:仓库整理
细节整理,README整理<br>
完成时间:2021年7月21日
## 项目亮点
* 数据来源全面多样<br>
* 可视化形式多元<br>
* 网页设计及可视化时有意围绕主色调,注重色彩搭配及展示效果<br>
## 关于我们
### 小组成员
秦兆阳 刘禹含 卢宇晨 王露婷 王艺萌 邢纪琛
## 鸣谢
**最后,大力感谢吴才聪老师以及助教老师的教导,感谢GitHub,感谢我们小组所有人的共同努力。**
<file_sep>import requests
import random
from bs4 import BeautifulSoup
def getComments(id,pageNum):
movieComments = ""
for i in range(pageNum):
start = i*20
url = "https://movie.douban.com/subject/"+str(id)+"/comments?start="+str(start)+"&limit=20&sort=new_score&status=P"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64'
}
print("正在爬取第%s页评论" % (i+1))
r = requests.get(url,headers=headers)
soup = BeautifulSoup(r.text,'lxml')
commentsList = soup.find_all('span',class_ ='short')
for comments in commentsList:
movieComments += comments.text
movieComments += '\n'
return movieComments
def saveComments(Comments):
try:
fileName = 'movieComments.txt'
with open(fileName,'w',encoding='utf-8') as f:
f.write(str(Comments))
print('保存成功!')
except:
print('保存失败!')
if __name__ == '__main__':
id = '30228394'
pageNum=random.randint(10,50)
Comments = getComments(id,pageNum)
saveComments(Comments)
from jieba.analyse import *
keyWord = []
def getData():
with open('movieComments.txt',encoding = 'utf-8') as f:
data = f.read()
for keyword in extract_tags(data, topK=100):
keyWord.append(keyword)
def saveData(keyWord):
with open('TF-IDFanalyse.txt','w') as f:
for i in range(len(keyWord)):
f.write(str(i+1)+'.'+str(keyWord[i]))
f.write('\n')
if __name__ == '__main__':
getData()
saveData(keyWord)
print('保存成功!')
<file_sep>import glob
import random
import imageio
import wordcloud
import matplotlib.pyplot as plt
def toWordCloud():
with open( 'TF-IDFanalyse.txt','r') as f:
data=f.read()
f.close()
fonts = glob.glob(r'\Users\Administrator\PycharmProjects\juexingniandai\lycc\ziti\*.ttf')
font = random.choice(fonts)
color_masks = glob.glob(r'\Users\Administrator\PycharmProjects\juexingniandai\main-1\ciyun\*.jpg')
color_mask = random.choice(color_masks)
color_mask = imageio.imread(color_mask)
wcd = wordcloud.WordCloud(
font_path=font, # 设置字体
background_color="white", # 背景颜色
max_words=200, # 词云显示的最大词数
mask=color_mask, # 设置背景图片
max_font_size=150, # 字体最大值
mode="RGBA",
width=500,
height=400,
collocations=False
)
wcd.generate(data)
plt.imshow(wcd)
wcd.to_file("ciyuntu.png")
plt.axis('off')
plt.show()
if __name__ == '__main__':
toWordCloud()<file_sep>import matplotlib.pyplot as plt
import wordcloud
import jieba
import random
import glob
import imageio
import requests
from bs4 import BeautifulSoup
global_text = ""
def getDetail(data):
global global_text
data = BeautifulSoup(data,"html.parser")
spans = data.find_all(class_="short")
for i in spans:
global_text += ",".join(jieba.cut(str(i.text).strip())) # 对获取到的热评分词
def toWordCloud():
global global_text
fonts = glob.glob(r'\Users\Administrator\PycharmProjects\juexingniandai\lycc\ziti\*.ttf')
font = random.choice(fonts)
color_masks = glob.glob(r'\Users\Administrator\PycharmProjects\juexingniandai\main-1\ciyun\*.jpg')
color_mask = random.choice(color_masks)
color_mask = imageio.imread(color_mask)
wcd = wordcloud.WordCloud(
font_path=font, # 设置字体
background_color="white", # 背景颜色
max_words=200, # 词云显示的最大词数
mask=color_mask, # 设置背景图片
max_font_size=150, # 字体最大值
mode="RGBA",
width=500,
height=400,
collocations=False
)
wcd.generate(global_text)
plt.imshow(wcd)
wcd.to_file("ciyuntu.png")
plt.axis('off')
plt.show()
if __name__ == '__main__':
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64"
}
url = 'https://movie.douban.com/subject/30228394/comments?percent_type=h&start={}&limit=20&status=P&sort=new_score'
for i in range(random.randint(1,50)):
new_url = url.format(i * 20)
print( "正在爬取第%s页评论" % (i + 1) )
response = requests.get(url=url,headers=headers)
response.encoding = 'utf-8'
getDetail(response.text)
toWordCloud()<file_sep>from bs4 import BeautifulSoup
import pandas as pd
import requests
#爬取对应视频的弹幕
url = 'http://comment.bilibili.com/322683493.xml' # url链接
html = requests.get(url) # 用于解析
html.encoding = 'utf8' # 编码格式为utf8
soup = BeautifulSoup(html.text, 'lxml') # 使用bs进行xml的解析
results = soup.find_all('d') # 进行标签《d》的筛选
comments = [comment.text for comment in results]
print(comments)
comments_dict = {'comments': comments} # 定义一个字典
df = pd.DataFrame(comments_dict)
df.to_csv('bili_danmu2.csv', encoding='utf-8-sig') # 保存为csv格式的文件
#原文链接:https://blog.csdn.net/qq_44870829/article/details/111149808<file_sep>from pyecharts.charts import Bar, Line
from pyecharts import options as opts
x_data =['0-19','20-29','30-39','40-49','50+']
bar = (
Bar(init_opts=opts.InitOpts(width="1200px", height="600px"))
.add_xaxis(xaxis_data=x_data)
.add_yaxis(
series_name="觉醒年代",
yaxis_data=[
19.21,
46.67,
20.31,
12.14,
1.67,
],
label_opts=opts.LabelOpts(is_show=False),
)
.add_yaxis(
series_name="全网分布",
yaxis_data=[
11.03,
32.75,
33.05,
17.1,
6.06,
],
label_opts=opts.LabelOpts(is_show=False),
)
.extend_axis(
yaxis=opts.AxisOpts(
name="TGI",
type_="value",
min_=0,
max_=200,
interval=40,
axislabel_opts=opts.LabelOpts(formatter="{value}"),
)
)
.set_global_opts(
tooltip_opts=opts.TooltipOpts(
is_show=True, trigger="axis", axis_pointer_type="cross"
),
xaxis_opts=opts.AxisOpts(
type_="category",
axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow"),
),
yaxis_opts=opts.AxisOpts(
type_="value",
min_=0,
max_=50,
interval=10,
axislabel_opts=opts.LabelOpts(formatter="{value} %"),
axistick_opts=opts.AxisTickOpts(is_show=True),
splitline_opts=opts.SplitLineOpts(is_show=True),
),
)
)
line = (
Line()
.add_xaxis(xaxis_data=x_data)
.add_yaxis(
series_name="TGI",
yaxis_index=1,
y_axis=[174.22,142.57,61.49,71.02,27.56],
label_opts=opts.LabelOpts(is_show=False),
)
)
bar.overlap( line ).render( "age.html" )<file_sep>import glob
import random
import imageio
import wordcloud
import matplotlib.pyplot as plt
import pandas as pd
import os
data = pd.read_csv(r'C:\Users\86136\Desktop\ciyun2\bili_danmu2(1).csv', encoding='utf-8')
with open(r'C:\Users\86136\Desktop\ciyun2\bili.txt', 'a+', encoding='utf-8') as f:
for line in data.values:
f.write((str(line[0]) + '\t' + str(line[1]) + '\n'))
def toWordCloud():
with open(r'C:\Users\86136\Desktop\ciyun2\bili.txt', encoding='utf-8', errors='ignore') as f:
data = f.read()
f.close()
fonts = glob.glob(r'C:\Users\86136\Desktop\ciyun2\ziti\*.ttf')
font = random.choice(fonts)
color_masks = glob.glob(r'C:\Users\86136\Desktop\ciyun2\*.JPG')
color_mask = random.choice(color_masks)
color_mask = imageio.imread(color_mask)
wcd = wordcloud.WordCloud(
font_path=font, # 设置字体
background_color="white", # 背景颜色
max_words=200, # 词云显示的最大词数
mask=color_mask, # 设置背景图片
max_font_size=150, # 字体最大值
mode="RGBA",
width=500,
height=400,
collocations=False
)
wcd.generate(data)
plt.imshow(wcd)
wcd.to_file("ciyuntu.png")
plt.axis('off')
plt.show()
if __name__ == '__main__':
toWordCloud()<file_sep>#微博预登录;识别“展开全文”并爬取完整数据;翻页设置
#使用Selenium库,模拟真实用户对浏览器进行操作。
#导入selenium包
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import time
import pandas as pd
#打开页面
'''打开网址,预登陆'''
driver = webdriver.Edge() #使用Edge浏览器
print('准备登陆Weibo.cn网站...')
# 发送请求
driver.get("https://login.sina.com.cn/signup/signin.php")
wait = WebDriverWait(driver, 5)
# 重要:暂停1分钟进行预登陆,此处填写账号密码及验证
time.sleep(60)
'''输入关键词到搜索框,完成搜索'''
# 使用selector去定位关键词搜索框
s_input = driver.find_element_by_css_selector('#search_input')
# 向搜索框中传入字段
s_input.send_keys("#觉醒年代#")
# 定位搜索键
confirm_btn = driver.find_element_by_css_selector('#search_submit')
# 点击
confirm_btn.click()
# 人为移动driver
driver.switch_to.window(driver.window_handles[1])
'''爬取第一页数据'''
comment = []
username = []
# 抓取节点:每个评论为一个节点(包括用户信息、评论、日期等信息),如果一页有20条评论,那么nodes的长度就为20
nodes = driver.find_elements_by_css_selector('div.card > div.card-feed > div.content')
# 对每个节点进行循环操作
for i in range(0, len(nodes), 1):
# 判断每个节点是否有“展开全文”的链接
flag = False
try:
nodes[i].find_element_by_css_selector("p>a[action-type='fl_unfold']").is_displayed()
flag = True
except:
flag = False
# 如果该节点具有“展开全文”的链接,且该链接中的文字是“展开全文c”,那么点击这个要素,并获取指定位置的文本;否则直接获取文本
# (两个条件需要同时满足,因为该selector不仅标识了展开全文,还标识了其他元素,没有做到唯一定位)
if (flag and nodes[i].find_element_by_css_selector("p>a[action-type='fl_unfold']").text.startswith('展开全文c')):
nodes[i].find_element_by_css_selector("p>a[action-type='fl_unfold']").click()
comment.append(nodes[i].find_element_by_css_selector('p[node-type="feed_list_content_full"]').text)
else:
comment.append(nodes[i].find_element_by_css_selector('p[node-type="feed_list_content"]').text)
username.append(nodes[i].find_element_by_css_selector("div.info>div:nth-child(2)>a").text)
'''循环操作,获取剩余页数的数据,共爬取50页'''
for page in range(49):
print(page)
# 定位下一页按钮
nextpage_button = driver.find_element_by_link_text('下一页')
# 点击按键
driver.execute_script("arguments[0].click();", nextpage_button)
wait = WebDriverWait(driver, 5)
# 与前面类似
nodes1 = driver.find_elements_by_css_selector('div.card > div.card-feed > div.content')
for i in range(0, len(nodes1), 1):
flag = False
try:
nodes1[i].find_element_by_css_selector("p>a[action-type='fl_unfold']").is_displayed()
flag = True
except:
flag = False
if (flag and nodes1[i].find_element_by_css_selector("p>a[action-type='fl_unfold']").text.startswith('展开全文c')):
nodes1[i].find_element_by_css_selector("p>a[action-type='fl_unfold']").click()
comment.append(nodes1[i].find_element_by_css_selector('p[node-type="feed_list_content_full"]').text)
else:
comment.append(nodes1[i].find_element_by_css_selector('p[node-type="feed_list_content"]').text)
username.append(nodes1[i].find_element_by_css_selector("div.info>div:nth-child(2)>a").text)
'''保存数据'''
data = pd.DataFrame({'username': username, 'comment': comment})
data.to_excel("#觉醒年代#.xlsx")<file_sep>#!/usr/bin/env python
# coding: utf-8
# In[24]:
import glob
import random
import imageio
import wordcloud
import matplotlib.pyplot as plt
import pandas as pd
import os
# In[25]:
data = pd.read_csv(r'C:\Users\86136\Desktop\ciyun2\bili_danmu2(1).csv', encoding='utf-8')
# In[26]:
data.isnull().sum()
# In[27]:
data.dtypes
# In[28]:
#文本内容清洗,去除表达符号、特殊字符等等
import re
pattern = r"[!\"#$%&'()*+,-./:;<=>?@[\\\]^_^{|}~—!,。?、¥…():【】《》‘’“”\s]+"
re_obj = re.compile(pattern)
def clear(text):
return re_obj.sub("",text)
data.comments = data.comments.apply(clear)
# In[29]:
bool=data.comments!=''
bool.sum()
data2=data[bool]
data2
# In[30]:
with open(r'C:\Users\86136\Desktop\ciyun2\bilibili.txt','a+', encoding='utf-8') as f:
for line in data2.values:
f.write((str(line[0])+'\t'+str(line[1])+'\n'))
# In[32]:
#分词
import jieba
def cut_word(text):
return jieba.cut(text)
data2.comments=data2.comments.apply(cut_word)
# In[39]:
#停用词处理
def get_stopword():
s = set()
with open(r'C:\Users\86136\Desktop\ciyun2\StopWords.txt',encoding = 'UTF-8') as f:
for line in f:
s.add(line.strip())
return s
def remove_stopword(words):
return [word for word in words if word not in stopword]
stopword = get_stopword()
data2.comments= data2.comments.apply(remove_stopword)
#data2.comments[134]
# In[92]:
d3= list ( filter ( None,data2.comments))
d4=[]
for i in d3:
x="".join(i)
d4.append(x)
d4
# In[81]:
with open(r'C:\Users\86136\Desktop\ciyun2\bilibilibili.txt','w',encoding='utf-8') as f:
for li in d4:
f.write(li+"\n")
# In[83]:
def toWordCloud():
with open(r'C:\Users\86136\Desktop\ciyun2\bilibili.txt', encoding='utf-8', errors='ignore') as f:
data = f.read()
f.close()
fonts = glob.glob(r'C:\Users\86136\Desktop\ciyun2\ziti\*.ttf')
font = random.choice(fonts)
color_masks = glob.glob(r'C:\Users\86136\Desktop\ciyun2\*.JPG')
color_mask = random.choice(color_masks)
color_mask = imageio.imread(color_mask)
wcd = wordcloud.WordCloud(
font_path=font, # 设置字体
background_color="white", # 背景颜色
max_words=200, # 词云显示的最大词数
mask=color_mask, # 设置背景图片
max_font_size=150, # 字体最大值
mode="RGBA",
width=500,
height=400,
collocations=False
)
wcd.generate(data)
plt.imshow(wcd)
wcd.to_file("ciyuntu_bili.png")
plt.axis('off')
plt.show()
if __name__ == '__main__':
toWordCloud()
# In[86]:
def toWordCloud():
with open(r'C:\Users\86136\Desktop\ciyun2\bilibilibili.txt', encoding='utf-8', errors='ignore') as f:
data = f.read()
f.close()
fonts = glob.glob(r'C:\Users\86136\Desktop\ciyun2\ziti\*.ttf')
font = random.choice(fonts)
color_masks = glob.glob(r'C:\Users\86136\Desktop\ciyun2\*.JPG')
color_mask = random.choice(color_masks)
color_mask = imageio.imread(color_mask)
wcd = wordcloud.WordCloud(
font_path=font, # 设置字体
background_color="white", # 背景颜色
max_words=200, # 词云显示的最大词数
mask=color_mask, # 设置背景图片
max_font_size=150, # 字体最大值
mode="RGBA",
width=500,
height=400,
collocations=False
)
wcd.generate(data)
plt.imshow(wcd)
wcd.to_file("ciyuntu.png")
plt.axis('off')
plt.show()
if __name__ == '__main__':
toWordCloud()
# In[23]:
from snownlp import SnowNLP
import codecs
import os
import pandas as pd
# In[87]:
#情感各分数段出现频率以及可视化
source = open(r'C:\Users\86136\Desktop\ciyun2\bilibilibili.txt', "r", encoding='utf-8')
line = source.readlines()
sentimentslist = []
for i in line:
s = SnowNLP(i)
print(s.sentiments)
sentimentslist.append(s.sentiments)
import matplotlib.pyplot as plt
import numpy as np
plt.hist(sentimentslist, bins = np.arange(0, 1, 0.01), facecolor = 'r')
plt.xlabel('Sentiments Probability')
plt.ylabel('Quantity')
plt.title('Analysis of Sentiments')
plt.show()
# In[90]:
#情感变化及可视化
from snownlp import SnowNLP
import codecs
import os
source = open(r'C:\Users\86136\Desktop\ciyun2\bilibilibili.txt',"r", encoding='utf-8')
line = source.readlines()
sentimentslist = []
for i in line:
s = SnowNLP(i)
print(s.sentiments)
sentimentslist.append(s.sentiments)
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.arange(0, 3426, 1), sentimentslist, 'r-')
plt.xlabel('Number')
plt.ylabel('Sentiment')
plt.title('Analysis of Sentiments')
plt.show()
# In[ ]:
<file_sep>import requests
from lxml import etree
import time
import random
import csv
import pandas as pd
def get_target(keyword, page,saveName):
result = pd.DataFrame()
for i in range(1, page + 1):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67'}
url = 'https://search.bilibili.com/all?keyword={}&from_source=nav_suggest_new0&page={}'.format(keyword, i)
html = requests.get(url.format(i), headers=headers)
bs = etree.HTML(html.text)
items = bs.xpath('//li[@class = "video-item matrix"]')
for item in items:
video_url = item.xpath('div[@class = "info"]/div/a/@href')[0].replace("//","") #每个视频的来源地址
title = item.xpath('div[@class = "info"]/div/a/@title')[0] #每个视频的标题
region = item.xpath('div[@class = "info"]/div[1]/span[1]/text()')[0].strip('\n ') #每个视频的分类版块如动画
view_num = item.xpath('div[@class = "info"]/div[3]/span[1]/text()')[0].strip('\n ') #每个视频的播放量
danmu = item.xpath('div[@class = "info"]/div[3]/span[2]/text()')[0].strip('\n ') #弹幕
upload_time = item.xpath('div[@class = "info"]/div[3]/span[3]/text()')[0].strip('\n ') # 上传日期
up_author = item.xpath('div[@class = "info"]/div[3]/span[4]/a/text()')[0].strip('\n ') #up主
df = pd.DataFrame({'region': [region],'title': [title], 'view_num': [view_num], 'danmu': [danmu], 'upload_time': [upload_time], 'up_author': [up_author], 'video_url': [video_url]})
result = pd.concat([result, df])
time.sleep(random.random() + 1)
print('已经完成b站第 {} 页爬取'.format(i))
saveName = saveName + ".csv"
result.to_csv(saveName, encoding='utf-8-sig',index=False) # 保存为csv格式的文件
return result
if __name__ == "__main__":
keyword = input("请输入要搜索的关键词:")
page = int(input("请输入要爬取的页数:"))
saveName = input("请输入要保存的文件名:")
get_target(keyword, page,saveName)
#原文链接:https://blog.csdn.net/qq_44870829/article/details/111149808<file_sep><!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>李大钊</title>
<link href="C:\Users\Lenovo\PycharmProjects\juexing\try\AboutPageAssets\styles\aboutPageStyle.css" rel="stylesheet" type="text/css">
<!--The following script tag downloads a font from the Adobe Edge Web Fonts server for use within the web page. We recommend that you do not modify it.-->
<script>var __adobewebfontsappname__="dreamweaver"</script><script src="http://use.edgefonts.net/montserrat:n4:default;source-sans-pro:n2:default.js" type="text/javascript"></script>
</head>
<body>
<!-- Header content -->
<header>
<div class="profileLogo">
<!-- Profile logo. Add a img tag in place of <span>. -->
<p class="logoPlaceholder" data_temp_dwid="1"><strong data_temp_dwid="2">
<!-- <img src="logoImage.png" alt="sample logo"> -->
人物简介 </strong></p>
</div>
<!-- Identity details -->
<div class="profilePhoto">
<!-- Profile photo -->
<img src="characters/李大钊.jpg" alt="sample" width="173" height="250"></div>
<section class="profileHeader">
<h1>李大钊</h1>
<h3>1889年10月29日-1927年4月28日<br>
</h3>
<hr>
<p>李大钊,字守常,河北乐亭人。1907年考入天津北洋法政专门学校,1913年毕业后东渡日本,入东京早稻田大学政治本科学习,是中国共产主义运动的先驱,伟大的马克思主义者,杰出的无产阶级革命家,中国共产党的主要创始人之一。李大钊同志一生的奋斗历程,同马克思主义在中国传播的历史紧密相连,同中国共产党创建的历史紧密相连,同中国共产党领导的为中国人民谋幸福的历史紧密相连。</p>
<p>2019年10月27日,纪念李大钊同志诞辰130周年座谈会在京举行。会议纪念李大钊同志诞辰130周年,回顾神州大地发生的历史性变化,怀念李大钊同志等老一辈革命家为民族独立和人民解放、国家富强和人民幸福建立的不朽功勋。</p>
<p>2021年4月28日,俄罗斯保存的李大钊生前唯一影像公布。</p>
<blockquote> </blockquote>
</section>
<p class="section1" style="color:rgba(216,216,216,1.00)">相关人物</p>
<aside class="socialNetworkNavBar">
<div class="socialNetworkNav">
<!-- Add a Anchor tag with nested img tag here -->
<img src="characters/圆形 陈独秀.png" alt="sample" width="74" class="img">
<a href="file:///C:/Users/Lenovo/PycharmProjects/juexing/chenduxiu.html" title="Link" style="color:rgba(216,216,216,1.00)">陈独秀</a><p class="section1" style="color:rgba(216,216,216,1.00)">好友</p></div>
</aside>
<!-- Links to Social network accounts --></header>
<!-- content -->
<section class="mainContent">
<!-- Contact details -->
<!-- Previous experience details -->
<section class="section2">
<h2 class="sectionTitle">人物词云图</h2>
<hr class="sectionTitleRule">
<hr class="sectionTitleRule2">
<!-- First Title & company details -->
<article class="section2Content">
<p><br>
</p>
<img src="pictures/ldz.png" width="500" height="" alt=""/> </article>
<section class="section2">
<h2 class="sectionTitle">人物生平</h2>
<hr class="sectionTitleRule">
<hr class="sectionTitleRule2">
<!-- First Title & company details -->
<article class="section2Content">
<p class="sectionContent"> 李大钊同志1889年10月出生于河北省乐亭县。那时,中国正处在帝国主义列强加紧侵略和封建统治愈益腐朽而造成的深重灾难之中,国家和民族濒于危亡的边缘。进入二十世纪,辛亥革命爆发、新文化运动涌起,特别是五四运动的发生,使中国社会出现了曙光初现的变化。李大钊同志是在这样的历史背景下走上探索救国救民道路的。1913年,他东渡日本,就读于东京早稻田大学,开始接触社会主义思想和马克思主义学说。1916年回国后,他积极投身新文化运动,宣传民主、科学精神,抨击旧礼教、旧道德,向封建顽固势力展开猛烈斗争。他和他的战友们改造旧中国的决心和激情,有力激发了当时中国青年的蓬勃朝气和进取精神</p>
<p class="sectionContent"> 李大钊同志是中国最早的马克思主义传播者。1917年俄国十月革命胜利后,李大钊同志备受鼓舞,连续发表《法俄革命之比较观》《庶民的胜利》《布尔什维主义的胜利》《新纪元》等文章和演讲,热情讴歌十月革命。他敏锐认识到这场革命将对20世纪世界历史进程产生划时代的影响,从中看到民族独立和人民解放的希望,满怀信心地预言:“试看将来的环球,必是赤旗的世界!”</p>
<p class="sectionContent"> 在宣传十月革命过程中,他的思想认识迅速提高,从一个爱国的民主主义者转变为一个马克思主义者,进而成为我国最早的马克思主义传播者。1919年五四运动后,他更加致力于马克思主义的宣传,在《新青年》上发表《我的马克思主义观》,系统介绍马克思主义理论,在当时思想界产生重大影响,标志着马克思主义在中国进入比较系统的传播阶段。李大钊同志发表《再论问题与主义》等文章,通过批驳反马克思主义思潮,论证马克思主义符合中国需要的深刻道理。在北洋军阀反动统治的艰难环境中,李大钊同志推动了马克思主义在中国广泛传播,为中国共产党创建准备了思想条件。 </p>
<p class="sectionContent"> 李大钊同志是中国共产党的主要创始人之一。从1920年初开始,李大钊同志等革命家就商议在中国建立无产阶级政党的问题。1920年3月,李大钊同志在北京大学发起组织马克思学说研究会。同年秋,他领导建立北京的共产党早期组织和北京社会主义青年团,并积极推动建立全国范围的共产党组织。1921年3月,李大钊同志撰文号召全国的共产主义者“急急组织一个团体”,这个团体是“平民的劳动家的政党”,要担负起“中国彻底的大改革”的责任。1921年,中国共产党宣告成立,这是中国近现代史上开天辟地的大事件。李大钊同志为建党所作的重大贡献,使他成为中国共产党的主要创始人之一。 </p>
</article>
<!-- Second Title & company details -->
<article class="section2Content">
<p class="sectionContent"> 李大钊同志是党成立后革命运动的重要领导者。中国共产党成立后,李大钊同志代表党中央指导北方地区党的工作,并担任中国劳动组合书记部北方区分部主任,在党的三大、四大上当选为中央委员。他领导宣传马克思主义,开展工人运动,建立党的组织,掀起北方地区轰轰烈烈的革命运动。他认识到农民是中国革命的依靠力量,明确提出“中国的浩大的农民群众,如果能够组织起来,参加国民革命,中国国民革命的成功就不远了”。他认识到武装斗争的重要性,亲自出面做冯玉祥等国民军将领的工作,推动他们参加国民革命。他认识到欲要完成中国革命,必须建立统一战线。1922年至1924年,他受党的委托,奔走于北京、上海、广州之间,帮助孙中山改组国民党,为建立第一次国共合作的统一战线作出重大贡献。他领导北方党组织配合五卅运动,配合北伐胜利进军,开展反帝反军阀斗争,为大革命胜利推进作出卓越贡献。</p>
</article>
<article class="section2Content">
<p class="sectionContent"> 李大钊同志不仅是一位伟大的革命者和战士,而且是20世纪初我国思想文化界的一位杰出人物。他留下大量著作、文稿和译著,内容涉及哲学、经济学、法学、历史学、伦理学、美学、新闻学、图书管理学等诸多领域,为20世纪中国的思想文化建设作出重要贡献。正如鲁迅先生所说:“他的遗文却将永住,因为这是先驱者的遗产,革命史上的丰碑。”</p>
</article>
<article class="section2Content">
<p class="sectionContent"> 1927年4月6日,李大钊同志在北京被捕入狱。他受尽各种严刑拷问,始终坚守信仰、初心不改,坚贞不屈、大义凛然。4月28日,李大钊同志惨遭反动军阀绞杀,牺牲时年仅38岁。 </p>
</article>
<!-- Replicate the above Div block to add more title and company details -->
</section>
<!-- Links to expore your past projects and download your CV -->
<section class="section2">
<h2 class="sectionTitle">剧中片段</h2>
<hr class="sectionTitleRule">
<hr class="sectionTitleRule2">
<aside class="externalResourcesNav">
<div class="externalResources"><img src="shipin/ldz1.jpg" width="200" height="100" alt=""/> <a href="file:///C:/Users/Lenovo/PycharmProjects/juexing/shipin/videoldz1.html" title="Link">李大钊号召工人阶级</a> </div>
<span class="stretch"></span>
<div class="externalResources"><img src="shipin/ldzhs.jpg" width="200" height="100" alt=""/> <a href="file:///C:/Users/Lenovo/PycharmProjects/juexing/shipin/videoldz-hs.html" title="Link">李大钊胡适红楼辩论</a> </div>
<span class="stretch"></span>
<div class="externalResources"><img src="shipin/ncbl.jpg" width="200" height="100" alt=""/> <a href="file:///C:/Users/Lenovo/PycharmProjects/juexing/shipin/videocdx-ldz.html" title="Link">南陈北李相约建党</a> </div>
</aside>
</section>
</section>
<footer>
<hr>
<p class="footerDisclaimer">资料来源:<span>百度百科</span></p>
<p class="footerDisclaimer">视频来源:<span>哔哩哔哩</span></p>
<p class="footerNote"><NAME> - <span>Email me</span></p>
</footer>
</body>
</html>
<file_sep># -*- coding: utf-8 -*-
from snownlp import SnowNLP
import codecs
import os
import pandas as pd
#将爬取弹幕得到的csv文件转化为txt文件并保存
data = pd.read_csv(r'C:\Users\86136\Desktop\ciyun2\bili_danmu2(1).csv', encoding='utf-8')
with open(r'C:\Users\86136\Desktop\ciyun2\bili.txt','a+', encoding='utf-8') as f:
for line in data.values:
f.write((str(line[0])+'\t'+str(line[1])+'\n'))
#情感各分数段出现频率以及可视化
source = open(r'C:\Users\86136\Desktop\ciyun2\bili.txt', "r", encoding='utf-8')
line = source.readlines()
sentimentslist = []
for i in line:
s = SnowNLP(i)
print(s.sentiments)
sentimentslist.append(s.sentiments)
import matplotlib.pyplot as plt
import numpy as np
plt.hist(sentimentslist, bins = np.arange(0, 1, 0.01), facecolor = 'r')
plt.xlabel('Sentiments Probability')
plt.ylabel('Quantity')
plt.title('Analysis of Sentiments')
plt.show()
| 8884d30317dfe9743c23e7349c7bc88493e40005 | [
"JavaScript",
"Python",
"HTML",
"Markdown"
] | 15 | Python | Alymdeer/juexingniandai | b2b6d19e6570e6501a10a16da0c5efee96fc7af7 | 88da9292033840e236f4a8b901de40add0d7e420 |
refs/heads/master | <file_sep>package formasGeometricas;
public class CalculoQuadrado implements FormaGeometrica {
public void CalcularArea(int lado) {
// lado = (lado * lado);
System.out.println("A área do quadrado é: " + lado * lado);
}
public void CalcularPerimetro(int lado) {
// lado = (lado * 4);
System.out.println("O perímetro do quadrado é: " + lado * 4);
}
}
| e0ce0ffa8dbc3003528534890760fb5ee361ebe0 | [
"Java"
] | 1 | Java | Ronei1301719/Interfaces | b3ad6e811d8ed8659da1563266e2a31de6dc4481 | cdeb53273dd85aceaa0acc32d738b0a87494b167 |
refs/heads/master | <repo_name>pomeo/insalespartner<file_sep>/config/deploy.rb
#========================
#CONFIG
#========================
set :application, "partner.salesapps.ru"
#========================
#CONFIG
#========================
require "capistrano-offroad"
offroad_modules "defaults", "supervisord"
set :repository, "<EMAIL>:pomeo/insalespartner.git"
set :supervisord_start_group, "app"
set :supervisord_stop_group, "app"
#========================
#ROLES
#========================
role :app, "ubuntu@#{application}"
after "deploy:create_symlink", "deploy:npm_install", "deploy:restart"
<file_sep>/gulpfile.js
var gulp = require('gulp'),
imagemin = require('gulp-imagemin'),
pngcrush = require('imagemin-pngcrush'),
uglify = require('gulp-uglify'),
stylus = require('gulp-stylus'),
prefix = require('gulp-autoprefixer'),
minifyCSS = require('gulp-minify-css'),
grep = require('gulp-grep-stream'),
mocha = require('gulp-mocha'),
plumber = require('gulp-plumber'),
nib = require('nib'),
karma = require('karma').server,
watch = require('gulp-watch'),
browserSync = require('browser-sync'),
reload = browserSync.reload;
gulp.task('images', function () {
watch({glob: 'src/img/**/*'},
function(files) {
files
.pipe(plumber())
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngcrush()]
}))
.pipe(gulp.dest('public/img'))
.pipe(reload({stream:true}));
});
});
gulp.task('compress', function() {
watch({glob: 'src/js/**/*.js'},
function(files) {
files
.pipe(plumber())
.pipe(uglify())
.pipe(gulp.dest('public/js'))
.pipe(reload({stream:true}));
});
});
gulp.task('copy-json', function() {
watch({glob: 'src/js/**/*.json'},
function(files) {
files
.pipe(plumber())
.pipe(gulp.dest('public/js'))
.pipe(reload({stream:true}));
});
});
gulp.task('minify-css', function() {
watch({glob: 'src/css/**/*.css'},
function(files) {
files
.pipe(plumber())
.pipe(minifyCSS())
.pipe(gulp.dest('public/css'))
.pipe(reload({stream:true}));
});
});
gulp.task('stylus', function () {
watch({glob: 'src/css/**/*.styl'},
function(files) {
files
.pipe(plumber())
.pipe(stylus({compress: true, use: nib()}))
.pipe(prefix())
.pipe(gulp.dest('public/css'))
.pipe(reload({stream:true}));
});
});
gulp.task('mocha', function() {
gulp.src(['test/*.js'], {read: false})
.pipe(watch({ emit: 'all' }, function(files) {
files
.pipe(mocha({ reporter: 'spec' }))
.on('error', function() {
if (!/tests? failed/.test(err.stack)) {
console.log(err.stack);
}
})
}));
});
gulp.task('browser-sync', function() {
browserSync.init(null, {
proxy: 'localhost:3000',
open: false,
port: 8080,
notify: false
});
});
gulp.task('default', ['minify-css', 'stylus', 'images', 'compress', 'copy-json', 'browser-sync'], function () {
gulp.watch(['views/**/*.jade'], reload);
});
<file_sep>/routes/index.js
var express = require('express'),
router = express.Router(),
winston = require('winston'),
Logentries = require('winston-logentries');
if (process.env.NODE_ENV === 'development') {
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)()
]
});
} else {
var logger = new (winston.Logger)({
transports: [
new winston.transports.Logentries({token: process.env.logentries})
]
});
}
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
function log(logMsg, logType) {
if (logMsg instanceof Error) logger.error(logMsg.stack);
if (logType !== undefined) {
logger.log(logType, logMsg);
} else {
logger.info(logMsg);
}
}; | 5b108f5afe0f8ce71222d3936446d639628c80b2 | [
"JavaScript",
"Ruby"
] | 3 | Ruby | pomeo/insalespartner | d5c38652d4984ae1a0e7efeca7e6b7afbf8fb8ae | 7722f8e30c622c87da702308b8535b74fd6d89ce |
refs/heads/master | <repo_name>emacsway/go-api-boilerplate<file_sep>/cmd/user/internal/interfaces/http/router.go
package http
import (
"database/sql"
"net/http"
httpcors "github.com/rs/cors"
"github.com/vardius/gorouter/v4"
"golang.org/x/oauth2"
"google.golang.org/grpc"
httpformmiddleware "github.com/mar1n3r0/gorouter-middleware-formjson"
authproto "github.com/vardius/go-api-boilerplate/cmd/auth/proto"
usersecurity "github.com/vardius/go-api-boilerplate/cmd/user/internal/application/security"
"github.com/vardius/go-api-boilerplate/cmd/user/internal/domain/user"
userpersistence "github.com/vardius/go-api-boilerplate/cmd/user/internal/infrastructure/persistence"
"github.com/vardius/go-api-boilerplate/cmd/user/internal/interfaces/http/handlers"
"github.com/vardius/go-api-boilerplate/pkg/commandbus"
httpmiddleware "github.com/vardius/go-api-boilerplate/pkg/http/middleware"
httpauthenticator "github.com/vardius/go-api-boilerplate/pkg/http/middleware/authenticator"
"github.com/vardius/go-api-boilerplate/pkg/http/middleware/firewall"
"github.com/vardius/go-api-boilerplate/pkg/log"
)
const googleAPIURL = "https://www.googleapis.com/oauth2/v2/userinfo"
const facebookAPIURL = "https://graph.facebook.com/me"
// NewRouter provides new router
func NewRouter(logger *log.Logger, repository userpersistence.UserRepository, commandBus commandbus.CommandBus, mysqlConnection *sql.DB, grpAuthClient authproto.AuthenticationServiceClient, grpcConnectionMap map[string]*grpc.ClientConn, oauth2Config oauth2.Config, secretKey string) gorouter.Router {
auth := httpauthenticator.NewToken(usersecurity.TokenAuthHandler(grpAuthClient, repository))
// Global middleware
router := gorouter.New(
httpmiddleware.Recover(logger),
httpmiddleware.WithMetadata(),
httpmiddleware.Logger(logger),
httpmiddleware.WithContainer(),
httpcors.Default().Handler,
httpmiddleware.XSS(),
httpmiddleware.HSTS(),
httpmiddleware.Metrics(),
httpmiddleware.LimitRequestBody(int64(10<<20)), // 10 MB is a lot of text.
httpformmiddleware.FormJson(),
auth.FromHeader("USER"),
auth.FromQuery("authToken"),
)
// Liveness probes are to indicate that your application is running
router.GET("/v1/health", handlers.BuildLivenessHandler())
// Readiness is meant to check if your application is ready to serve traffic
router.GET("/v1/readiness", handlers.BuildReadinessHandler(mysqlConnection, grpcConnectionMap))
// Auth routes
router.POST("/v1/google/callback", handlers.BuildSocialAuthHandler(googleAPIURL, commandBus, user.RegisterUserWithGoogle, secretKey, oauth2Config))
router.POST("/v1/facebook/callback", handlers.BuildSocialAuthHandler(facebookAPIURL, commandBus, user.RegisterUserWithFacebook, secretKey, oauth2Config))
commandDispatchHandler := handlers.BuildCommandDispatchHandler(commandBus)
// Public User routes
router.POST("/v1/dispatch/{command}", commandDispatchHandler)
// Protected User routes
router.USE(http.MethodPost, "/v1/dispatch/"+user.ChangeUserEmailAddress, firewall.GrantAccessFor("USER"))
router.GET("/v1/me", handlers.BuildMeHandler(repository))
router.USE(http.MethodGet, "/v1/me", firewall.GrantAccessFor("USER"))
router.GET("/v1/", handlers.BuildListUserHandler(repository))
router.GET("/v1/{id}", handlers.BuildGetUserHandler(repository))
return router
}
<file_sep>/cmd/auth/internal/application/eventhandler/logger.go
package eventhandler
import (
"context"
"github.com/vardius/go-api-boilerplate/cmd/auth/internal/application/config"
"github.com/vardius/go-api-boilerplate/pkg/container"
"github.com/vardius/go-api-boilerplate/pkg/log"
)
func GetLogger(ctx context.Context) *log.Logger {
if requestContainer, ok := container.FromContext(ctx); ok {
if v, ok := requestContainer.Get("logger"); ok {
if logger, ok := v.(*log.Logger); ok {
return logger
}
}
}
return log.New(config.Env.App.Environment)
}
<file_sep>/go.mod
module github.com/vardius/go-api-boilerplate
go 1.13
require (
github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496
github.com/aws/aws-sdk-go v1.28.9
github.com/caarlos0/env/v6 v6.2.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-sql-driver/mysql v1.5.0
github.com/golang/protobuf v1.3.5
github.com/google/uuid v1.1.1
github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.2.0
github.com/klauspost/compress v1.10.3 // indirect
github.com/mar1n3r0/gorouter-middleware-formjson v1.1.0
github.com/rs/cors v1.7.0
github.com/valyala/fasthttp v1.9.0 // indirect
github.com/vardius/gocontainer v1.0.3
github.com/vardius/gollback v1.0.6
github.com/vardius/golog v1.1.1
github.com/vardius/gorouter/v4 v4.4.3
github.com/vardius/message-bus v1.1.4
github.com/vardius/pubsub/v2 v2.0.0
github.com/vardius/pushpull v1.0.0
github.com/vardius/shutdown v1.0.0
github.com/vardius/trace v1.0.1
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
google.golang.org/grpc v1.28.0
gopkg.in/oauth2.v3 v3.12.0
)
<file_sep>/cmd/user/internal/application/security/security.go
package application
import (
"context"
"fmt"
"github.com/google/uuid"
authproto "github.com/vardius/go-api-boilerplate/cmd/auth/proto"
userpersistence "github.com/vardius/go-api-boilerplate/cmd/user/internal/infrastructure/persistence"
"github.com/vardius/go-api-boilerplate/pkg/application"
"github.com/vardius/go-api-boilerplate/pkg/errors"
httpauthenticator "github.com/vardius/go-api-boilerplate/pkg/http/middleware/authenticator"
"github.com/vardius/go-api-boilerplate/pkg/identity"
)
// TokenAuthHandler provides token auth function
func TokenAuthHandler(grpAuthClient authproto.AuthenticationServiceClient, repository userpersistence.UserRepository) httpauthenticator.TokenAuthFunc {
fn := func(token string) (identity.Identity, error) {
tokenInfo, err := grpAuthClient.VerifyToken(context.Background(), &authproto.VerifyTokenRequest{
Token: token,
})
if err != nil {
return identity.NullIdentity, errors.Wrap(fmt.Errorf("%w: Could not verify token: %s", application.ErrUnauthorized, err))
}
user, err := repository.Get(context.Background(), tokenInfo.GetUserId())
if err != nil {
return identity.NullIdentity, errors.Wrap(err)
}
i := identity.Identity{
ID: uuid.MustParse(user.GetID()),
Token: token,
Email: user.GetEmail(),
Roles: []string{"USER"},
}
return i, nil
}
return fn
}
| acef12220747f79115c1e633396b6920f8cfde30 | [
"Go Module",
"Go"
] | 4 | Go | emacsway/go-api-boilerplate | a0476d556fc59f42ac219931d6d8f1772597e4f9 | 3f805ce0581c09a712b5c52ad76db7206e35298a |
refs/heads/master | <repo_name>Getabalew-F/CBE-Birr-App-Updated<file_sep>/github.properties
gpr.usr=79740874
gpr.key=<KEY><file_sep>/app/src/main/java/com/example/navdrawerdemo/SignUp.java
package com.example.navdrawerdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
public class SignUp extends AppCompatActivity {
Button callForRegistor;
Button callforBack;
AutoCompleteTextView autoCompleteTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
autoCompleteTextView = findViewById(R.id.gender);
String[] option = {"please select","Male", "Female"};
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.option_item, option);
autoCompleteTextView.setText(arrayAdapter.getItem(0).toString(), false);
autoCompleteTextView.setAdapter(arrayAdapter);
// Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
// ArrayAdapter<String> myAdapter = new ArrayAdapter<>(SignUp.this,
// android.R.layout.simple_list_item_1,
// getResources().getStringArray(R.array.names));
// myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// mySpinner.setAdapter(myAdapter);
callForRegistor = findViewById(R.id.register);
callForRegistor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SignUp.this, OTP.class);
startActivity(intent);
}
});
callforBack = findViewById(R.id.backk);
callforBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SignUp.this, Login.class);
startActivity(intent);
}
});
}
}<file_sep>/settings.gradle
include ':app'
rootProject.name = "CBE Birr" | 9c5764b8dc57256d69a4d4d9f89047d11f3317ac | [
"Java",
"INI",
"Gradle"
] | 3 | INI | Getabalew-F/CBE-Birr-App-Updated | c6e24ff4f07f0752d6a45a38c0d4cbd6bd0c2930 | 5ec35b4bb87ca5f923760fb713a9ec99978888ca |
refs/heads/master | <repo_name>iliy/LeoBase<file_sep>/AppPresentators/Components/IAdminViolationTableControl.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public delegate void ViolationEvent(int id);
public interface IAdminViolationTableControl: UIComponent
{
event Action AddNewAction;
event ViolationEvent RemoveViolation;
event ViolationEvent ShowDetails;
event ViolationEvent EditViolation;
}
}
<file_sep>/AppPresentators/Views/IMainView.cs
using AppPresentators.Components;
using AppPresentators.Components.MainMenu;
using AppPresentators.Infrastructure;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppPresentators.Views
{
public interface IMainView:IView
{
#region Models
VManager Manager { get; set; }
bool Enabled { get; set; }
bool ShowFastSearch { get; set; }
string SearchQuery { get; set; }
#endregion
#region Methods
void ShowError(string errorMessage);
bool RemoveComponent(Control control);
void SetComponent(Control control);
void SetTopControls(List<Control> controls);
void SetMenu(IMainMenu control);
void ClearCenter();
void StartTask();
void EndTask(bool setOldState);
void MakeOrder(IOrderPage orderPage);
#endregion
#region Actions
event Action Login;
event Action FastSearchGO;
event Action GoNextPage;
event Action GoBackPage;
#endregion
}
}
<file_sep>/AppCore/Repositrys/Violations/Protocols/ProtocolTypeRepository.cs
using AppData.Abstract.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations.Protocols
{
public class ProtocolTypeRepository : IProtocolTypeRepository
{
public IQueryable<ProtocolType> ProtocolTypes
{
get
{
var db = new LeoBaseContext();
return db.ProtocolTypes;
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/EmployerTableControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.VModels;
using AppPresentators.VModels.Persons;
using LeoBase.Components.CustomControls.SearchPanels;
using LeoBase.Forms;
using AppPresentators;
namespace LeoBase.Components.CustomControls
{
public partial class EmployerTableControl : UserControl, IEmployersTableControl
{
public bool ShowForResult { get; set; } = false;
private bool _nowTableUpdate = false;
private CustomTable _customTable;
private AllPersonesSearchPanel _searchPanel;
private bool _searchAnimate = false;
public event Action AddNewEmployer;
public event EditPersone EditPersone;
public event DeletePersone DeletePersone;
public event ShowPersoneDetails ShowPersoneDetails;
private List<Control> _topControls;
private Button _btnEditEmployer;
private Button _btnEmployerDelete;
private Button _btnShowEmployerDetails;
private int _selectedIndex;
public List<Control> TopControls { get {
return _topControls;
} set { } }
private void MakeTopControls()
{
if (ConfigApp.CurrentManager.Role.Equals("admin"))
{
AdminControls();
}
else
{
UserControls();
}
}
private void AdminControls()
{
Button btnCreateNewEmplyer = new Button();
Button btnReportButton = new Button();
_btnEditEmployer = new Button();
_btnEmployerDelete = new Button();
_btnShowEmployerDetails = new Button();
_btnEditEmployer.Text = "Редактировать";
_btnEmployerDelete.Text = "Удалить";
_btnShowEmployerDetails.Text = "Подробнее";
btnCreateNewEmplyer.Text = "Добавить нового сотрудника";
btnReportButton.Text = "Отчет";
_btnShowEmployerDetails.Click += (s, e) =>
{
var item = _data[_selectedIndex];
if (ShowPersoneDetails != null) ShowPersoneDetails(item);
};
_btnEditEmployer.Click += (s, e) =>
{
var item = _data[_selectedIndex];
if (EditPersone != null) EditPersone(item);
};
_btnEmployerDelete.Click += (s, e) =>
{
var item = _data[_selectedIndex];
if (MessageBox.Show("Вы уверены что хотите удалить сотрудника?", "Предупреждение", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.OK)
{
if (DeletePersone != null) DeletePersone(item);
}
};
btnCreateNewEmplyer.Click += (s, e) => {
if (AddNewEmployer != null)
AddNewEmployer();
};
_btnEditEmployer.Enabled = false;
_btnEmployerDelete.Enabled = false;
_btnEditEmployer.Enabled = false;
btnReportButton.Margin = new Padding(3, 3, 20, 3);
_topControls = new List<Control> { btnReportButton, _btnShowEmployerDetails, btnCreateNewEmplyer, _btnEditEmployer, _btnEmployerDelete };
}
private void UserControls()
{
_btnShowEmployerDetails = new Button();
Button btnReportButton = new Button();
_btnShowEmployerDetails.Text = "Подробнее";
btnReportButton.Text = "Отчет";
_btnShowEmployerDetails.Click += (s, e) =>
{
var item = _data[_selectedIndex];
if (ShowPersoneDetails != null) ShowPersoneDetails(item);
};
_btnShowEmployerDetails.Enabled = false;
btnReportButton.Margin = new Padding(3, 3, 20, 3);
_topControls = new List<Control> { btnReportButton, _btnShowEmployerDetails };
}
public EmployerTableControl()
{
InitializeComponent();
MakeTopControls();
_orderProperties = new Dictionary<string, int>();
_orderTypes = new Dictionary<string, OrderType>();
_orderProperties.Add("Фамилия", (int)PersonsOrderProperties.FIRST_NAME);
_orderProperties.Add("Имя", (int)PersonsOrderProperties.SECOND_NAME);
_orderProperties.Add("Отчество", (int)PersonsOrderProperties.MIDDLE_NAME);
_orderProperties.Add("Дата рождения", (int)PersonsOrderProperties.DATE_BERTHDAY);
_orderProperties.Add("Возвраст", (int)PersonsOrderProperties.AGE);
_orderProperties.Add("Дата создания", (int)PersonsOrderProperties.WAS_BE_CREATED);
_orderProperties.Add("Дата последнего обновления", (int)PersonsOrderProperties.WAS_BE_UPDATED);
_orderTypes.Add("Убывание", OrderType.ASC);
_orderTypes.Add("Возростание", OrderType.DESC);
_customTable = new CustomTable();
_customTable.Width = mainPanel.Width;
_customTable.Height = mainPanel.Height - 30;
_customTable.Location = new Point(0, 30);
_customTable.Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
_customTable.OrderProperties = (Dictionary<string, int>)_orderProperties;
_customTable.UpdateTable += () => UpdateTable();
_customTable.SelectedItemChange += (index) =>
{
if(index != -1)
{
_btnEditEmployer.Enabled = true;
_btnEmployerDelete.Enabled = true;
_btnShowEmployerDetails.Enabled = true;
_selectedIndex = index;
}
};
mainPanel.Controls.Add(_customTable);
_searchPanel = new AllPersonesSearchPanel(true);
_searchPanel.Search += () => UpdateTable();
_searchPanel.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
searchPanel.Controls.Add(_searchPanel);
animateSearchPanel.Tick += AnimateSearchPanel_Tick;
_searchPanel.HideSearchPanel += () =>
{
if (!_searchAnimate)
{
WidthAnimate animator = new WidthAnimate(searchPanel, searchPanel.Width, 0, 10, 20);
animator.OnAnimationComplete += () => button1.Visible = true;
animator.Start();
}
};
}
int animateTo = 300;
int animateSpeed = 30;
private void AnimateSearchPanel_Tick(object sender, EventArgs e)
{
if (searchPanel.Width != animateTo)
{
searchPanel.Width += animateSpeed;
}
else
{
if (animateTo == 0)
{
button1.Visible = true;
}
animateSearchPanel.Stop();
_searchAnimate = false;
}
}
private List<EmploeyrViewModel> _data;
public List<EmploeyrViewModel> Data
{
get
{
return _data;
}
set
{
_data = value;
_customTable.SetData<EmploeyrViewModel>(value);
}
}
public DocumentSearchModel DocumentSearchModel
{
get
{
return _searchPanel.DocumentSearchModel;
}
}
public PersonsSearchModel PersoneSearchModel
{
get
{
return _searchPanel.PersonSearchModel;
}
}
public SearchAddressModel AddressSearchModel
{
get
{
return _searchPanel.AddressSearchModel;
}
}
private PersonsOrderModel _orderModel;
private Dictionary<string, int> _orderProperties;
private Dictionary<string, OrderType> _orderTypes;
public PersonsOrderModel OrderModel
{
get
{
_orderModel = new PersonsOrderModel
{
OrderProperties = (PersonsOrderProperties)_customTable.SelectedOrderBy,
OrderType = _customTable.OrderType
};
return _orderModel;
}
set
{
_orderModel = value;
}
}
private PageModel _pageModel;
public PageModel PageModel
{
get
{
if (_pageModel == null) _pageModel = new PageModel();
_pageModel.ItemsOnPage = 10;
_pageModel = _customTable.PageModel;
return _pageModel;
}
set
{
if(animateTo == 0)
{
button1.Visible = true;
}
_pageModel = value;
_customTable.PageModel = value;
}
}
public event Action UpdateTable;
public event Action StartTask;
public event Action EndTask;
public event Action<EmploeyrViewModel> SelectedItemForResult;
public Control GetControl()
{
return this;
}
void UIComponent.Resize(int width, int height)
{
this.Width = width;
this.Height = height;
}
private void EmployerTableControl_Load(object sender, EventArgs e)
{
}
public void Update()
{
_customTable.SetData(_data);
}
private void metroTile1_Click(object sender, EventArgs e)
{
UpdateTable();
}
private void cmbItemsOnPage_SelectedIndexChanged(object sender, EventArgs e)
{
if(UpdateTable != null)
UpdateTable();
}
private void btnSearch_Click_1(object sender, EventArgs e)
{
UpdateTable();
}
private void btnClearAll_Click(object sender, EventArgs e)
{
_searchPanel.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
WidthAnimate animator = new WidthAnimate(searchPanel, searchPanel.Width, 450, 10, 20);
animator.Start();
}
public void LoadStart()
{
throw new NotImplementedException();
}
public void LoadEnd()
{
throw new NotImplementedException();
}
}
}
<file_sep>/FormControls/Controls/Models/HeadTitle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FormControls.Controls.Events;
using FormControls.Controls.Enums;
namespace FormControls.Controls.Models
{
public partial class HeadTitle : UserControl
{
public LeoDataViewHeadMetaData MetaData { get; set; }
public event TableOrderEvent OnTableOrder;
public event LeoTableResizeEvent OnResizeStart;
public event HeaderMouseMove OnHeaderMouseMove;
private bool _isLast = false;
public bool IsLast
{
get
{
return _isLast;
}
set
{
_isLast = value;
pbSeparator.Visible = !value;
}
}
public bool IsFirst
{
get;set;
}
public override Cursor Cursor
{
get
{
return base.Cursor;
}
set
{
base.Cursor = value;
lbTitle.Cursor = value;
}
}
private OrderTypes _orderType = OrderTypes.NONE;
public OrderTypes OrderType
{
get
{
return _orderType;
}
set
{
_orderType = value;
switch (value)
{
case OrderTypes.ASC:
lbTitle.Image = Properties.Resources.OrderAsc;
break;
case OrderTypes.DESC:
lbTitle.Image = Properties.Resources.OrderDesc;
break;
default:
lbTitle.Image = null;
break;
}
}
}
public HeadTitle(LeoDataViewHeadMetaData metaData)
{
InitializeComponent();
MetaData = metaData;
if (!metaData.Show) return;
if (metaData.CanOrder)
{
Cursor = Cursors.Hand;
Click += (s,e) => Order();
lbTitle.Click += (s, e) => Order();
lbTitle.MouseMove += (s, e) =>
{
if (OnHeaderMouseMove != null) OnHeaderMouseMove(this, e);
};
lbTitle.MouseUp += (s, e) =>
{
if (OnResizeStart != null) OnResizeStart(this, false);
};
}
pbSeparator.MouseDown += (s, e) =>
{
if (OnResizeStart != null) OnResizeStart(this, true);
};
pbSeparator.MouseUp += (s, e) =>
{
if (OnResizeStart != null) OnResizeStart(this, false);
};
pbSeparator.MouseMove += (s, e) =>
{
if (OnHeaderMouseMove != null) OnHeaderMouseMove(this, e);
};
lbTitle.Text = metaData.DisplayName ?? metaData.FieldName;
this.Dock = DockStyle.Fill;
}
private void Order()
{
if (OrderType == OrderTypes.NONE) OrderType = OrderTypes.ASC;
else if (OrderType == OrderTypes.ASC) OrderType = OrderTypes.DESC;
else if (OrderType == OrderTypes.DESC) OrderType = OrderTypes.ASC;
if (OnTableOrder != null) OnTableOrder(this, OrderType);
}
}
}
<file_sep>/WPFPresentators/Views/Controls/IControlView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFPresentators.Views.Windows;
namespace WPFPresentators.Views.Controls
{
public interface IControlView
{
void Render(IMainView main);
}
}
<file_sep>/AppPresentators/Infrastructure/IOrderBuilder.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Infrastructure
{
public interface IOrderBuilder
{
event Action<string> ErrorBuild;
bool WasError { get; set; }
void StartTable(string name, string[] headers);
void EndTable(string name);
void StartPharagraph(Align al);
void EndPharagraph();
void WriteText(string text, Color color, TextStyle style = TextStyle.NORMAL, float size = 12);
void DrawImage(Image img, Align al);
void WriteRow(string[] cells, RowColor color = RowColor.DEFAULT);
string Save();
void SetOrderPath(DirectoryInfo dirInfo, string orderName);
}
public enum TextStyle
{
BOLD,
ITALIC,
NORMAL
}
public enum RowColor
{
RED,
GREEN,
YELLOW,
DEFAULT
}
public enum Align
{
LEFT,
RIGHT,
CENTER
}
}
<file_sep>/AppCore/Abstract/IOrganisationRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract
{
public interface IOrganisationRepository
{
IQueryable<Organisation> Organisations { get; }
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/ISavePassControl.cs
namespace LeoBase.Components.CustomControls.NewControls
{
internal interface ISavePassControl
{
}
}<file_sep>/WPFPresentators/Views/Windows/IWindowView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFPresentators.Views.Windows
{
public interface IWindowView
{
void Show();
void ShowError(string message);
void Close();
}
}
<file_sep>/LeoBase/Components/CustomControls/LeoTextBox.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace LeoBase.Components.CustomControls
{
public class LeoTextBox:Panel
{
private TextBox _textBox;
public event EventHandler TextChanged;
public event KeyPressEventHandler KeyPress;
private LeoTextBoxStyle _style = LeoTextBoxStyle.Gray;
public LeoTextBoxStyle Style
{
get
{
return _style;
}
set
{
_style = value;
if (_style == LeoTextBoxStyle.White) this.BackColor = Color.White;
Update();
}
}
public override string Text {
get
{
return _textBox.Text;
}
set
{
_textBox.Text = value;
}
}
private LeoTextBoxDataType _dataType = LeoTextBoxDataType.TEXT;
public LeoTextBoxDataType DataType
{
get
{
return _dataType;
}
set
{
_dataType = value;
}
}
public LeoTextBox()
{
_textBox = new TextBox();
_textBox.Dock = DockStyle.Fill;
_textBox.BackColor = Color.FromArgb(248, 247, 245);
_textBox.BorderStyle = BorderStyle.None;
this.Padding = new Padding(7, 6, 7, 6);
this.Controls.Add(_textBox);
_textBox.TextChanged += _textBox_TextChanged;
_textBox.KeyPress += _textBox_KeyPress;
}
private void _textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (KeyPress != null) KeyPress(sender, e);
}
private void _textBox_TextChanged(object sender, EventArgs e)
{
if (TextChanged != null) TextChanged(sender, e);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
Image bg = _style == LeoTextBoxStyle.Gray ? Properties.Resources.tbBackground : Properties.Resources.tbBackgroundWhite;
Image imageBg = ResizeImage(bg, this.Width - 14 , 26);
Image imageLeft = _style == LeoTextBoxStyle.Gray ? Properties.Resources.tbLeft : Properties.Resources.tbLeftWhite;
Image imageRight = _style == LeoTextBoxStyle.Gray ? Properties.Resources.tbRight : Properties.Resources.tbRightWhite;
e.Graphics.DrawImage(imageBg, new Point(7, 0));
e.Graphics.DrawImage(imageLeft, new Point(0, 0));
e.Graphics.DrawImage(imageRight, new Point(this.Width - 7, 0));
}
public static Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
}
public enum LeoTextBoxDataType
{
REAL,
NUMBER,
TEXT
}
public enum LeoTextBoxStyle
{
Gray,
White
}
}
<file_sep>/LeoBase/Components/CustomControls/LeoComboBox.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace LeoBase.Components.CustomControls
{
public class LeoComboBox:Panel
{
private ComboBox _comboBox;
}
}
<file_sep>/FormControls/Controls/Enums/OrderTypes.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FormControls.Controls.Enums
{
public enum OrderTypes
{
ASC,
DESC,
NONE
}
}
<file_sep>/AppCore/Entities/DefinitionAboutViolation.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
/// <summary>
/// Определение о возбуждение дела об административном правонарушение
/// и проведение административного расследования
/// </summary>
public class DefinitionAboutViolation: IProtocol
{
[Key]
public int DefinitionAboutViolationID { get; set; }
[Required(AllowEmptyStrings = false)]
public Protocol Protocol { get; set; }
public int ViolatorDocumentID { get; set; }
public int OrganisationID { get; set; }
/// <summary>
/// Найденное оружие
/// </summary>
public string FindedWeapons { get; set; }
/// <summary>
/// Найденные боеприпасы
/// </summary>
public string FindedAmmunitions { get; set; }
/// <summary>
/// Найденые орудия для охоты и рыболовства
/// </summary>
public string FindedGunsHuntingAndFishing { get; set; }
/// <summary>
/// Найденная продукция природопользования
/// </summary>
public string FindedNatureManagementProducts { get; set; }
/// <summary>
/// Найденные документы
/// </summary>
public string FindedDocuments { get; set; }
/// <summary>
/// Статья КОАП
/// </summary>
public string KOAP { get; set; }
/// <summary>
/// Методы фиксации правонарушения
/// </summary>
public string FixingMethods { get; set; }
}
}
<file_sep>/AppPresentators/VModels/PageModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public class PageModel
{
public int CurentPage { get; set; }
public int ItemsOnPage { get; set; }
public int TotalItems { get; set; }
public int TotalPages { get
{
int ost = TotalItems % ItemsOnPage;
if (ost == 0) return TotalItems / ItemsOnPage;
return 1 + (TotalItems - TotalItems % ItemsOnPage) / ItemsOnPage;
}}
}
}
<file_sep>/AppCore/FakesRepositoryes/FakeDocumentTypeRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
namespace AppData.FakesRepositoryes
{
public class FakeDocumentTypeRepository : IDocumentTypeRepository
{
private List<DocumentType> _docTypes = new List<DocumentType>
{
new DocumentType
{
DocumentTypeID = 1,
Name = "Паспорт"
},
new DocumentType
{
DocumentTypeID = 2,
Name = "Водительские права"
}
};
public IQueryable<DocumentType> DocumentTypes
{
get
{
return _docTypes.AsQueryable();
}
}
}
}
<file_sep>/AppCore/Repositrys/DocumentsRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys
{
public class DocumentsRepository : IDocumentRepository
{
public IQueryable<Document> Documents
{
get
{
var db = new LeoBaseContext();
return db.Documents.Include("Persone");
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/CustomTable.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels;
using System.Collections;
namespace LeoBase.Components.CustomControls
{
public delegate void SelectedIndex(int index);
public delegate void RowCreated(DataGridViewRow row);
public delegate void GenerateControl(Control control);
public delegate void CellDataChanged(string columnName, object newValue, DataGridViewRow row);
public partial class CustomTable : UserControl
{
public bool CanEdit { get; set; }
public bool CanDelete { get; set; }
public event SelectedIndex SelectedItemChange;
public event RowCreated OnRowWasCreted;
public event CellDataChanged OnCellDataChanged;
public event Action DoubleClick;
private int _selectedOrderBy;
public int SelectedItemIndex
{
get
{
if (dataTable.SelectedRows.Count == 0) return -1;
return dataTable.SelectedRows[0].Index;
}
}
public bool VisibleOrderBy { get
{
return orderPanel.Visible;
}
set
{
orderPanel.Visible = value;
}
}
public int SelectedOrderBy
{
get
{
//if(cmbOrderBy.Items != null && cmbOrderBy.Items.Count != 0)
//{
// string value = cmbOrderBy.Items[cmbOrderBy.SelectedIndex].ToString();
// if (_orderProperties.ContainsKey(value))
// {
// return _orderProperties[value];
// }
//}
//return cmbOrderBy.SelectedIndex;
return _selectedOrderBy;
}
set
{
cmbOrderBy.SelectedIndex = value;
}
}
private string GetOrderText()
{
return cmbOrderBy.Items[cmbOrderBy.SelectedIndex].ToString();
}
public string SelectedOrderByValue
{
get
{
return cmbOrderBy.Items.Count != 0 ? cmbOrderBy.Items[cmbOrderBy.SelectedIndex].ToString(): "";
}
set
{
for(int i = 0; i < cmbOrderBy.Items.Count; i++)
{
if(value.Equals(cmbOrderBy.Items[i]))
{
cmbOrderBy.SelectedIndex = i;
return;
}
}
}
}
private Dictionary<string, int> _orderProperties;
public Dictionary<string, int> OrderProperties
{
get
{
return _orderProperties;
}
set
{
_orderProperties = value;
cmbOrderBy.Items.Clear();
foreach(var item in _orderProperties)
{
cmbOrderBy.Items.Add(item.Key);
}
cmbOrderBy.SelectedIndex = 0;
}
}
private Dictionary<string, OrderType> _orderTypes;
private OrderType _selectedOrderType = OrderType.NONE;
public OrderType OrderType
{
get
{
//if(cmbOrderType.Items != null && cmbOrderType.Items.Count != 0)
//{
// string value = cmbOrderType.Items[cmbOrderType.SelectedIndex].ToString();
// if(!string.IsNullOrEmpty(value) && _orderTypes.ContainsKey(value))
// {
// return _orderTypes[value];
// }
//}
return _selectedOrderType;
}
set
{
foreach(var orderType in _orderTypes)
{
if(orderType.Value == value)
{
for(int i = 0; i < cmbOrderType.Items.Count; i++)
{
if (orderType.Key.Equals(cmbOrderType.Items[i].ToString()))
{
cmbOrderType.SelectedIndex = i;
return;
}
}
return;
}
}
}
}
private PageModel _pageModel = new PageModel();
public PageModel PageModel {
get
{
if (_pageModel == null) _pageModel = new PageModel();
if (cmbBoxItemsOnPage.Items != null && cmbBoxItemsOnPage.Items.Count != 0)
{
string value = cmbBoxItemsOnPage.Items[cmbBoxItemsOnPage.SelectedIndex].ToString();
if (!string.IsNullOrEmpty(value))
{
try
{
_pageModel.ItemsOnPage = Convert.ToInt32(value);
}
catch
{
_pageModel.ItemsOnPage = 10;
}
}
}
if (paginationSource.Count != 0)
_pageModel.CurentPage = 1 + (int)paginationSource.Current;
else
_pageModel.CurentPage = 1;
if (_pageModel.ItemsOnPage == 0)
_pageModel.ItemsOnPage = 10;
return _pageModel;
}
set
{
//if (_pageModel == value) return;
if (_pageModel.TotalPages != value.TotalPages
|| paginationSource.Count == 0
|| paginationSource.Count != value.TotalPages)
{
List<int> pages = new List<int>();
for (int i = 0; i < value.TotalPages; i++)
{
pages.Add(i);
}
paginationSource = new BindingSource();
paginationSource.DataSource = new BindingList<int>(pages);
paginatior.BindingSource = paginationSource;
paginationSource.CurrentChanged += PaginationSource_CurrentChanged;
}
_pageModel = value;
}
}
public void SetData<T>(List<T> list)
{
dataTable.DataSource = new BindingList<T>(list);
dataTable.Update();
dataTable.Refresh();
foreach(DataGridViewColumn column in dataTable.Columns)
{
column.SortMode = DataGridViewColumnSortMode.NotSortable;
}
}
public event Action UpdateTable;
public CustomTable()
{
InitializeComponent();
_orderTypes = new Dictionary<string, OrderType>();
_orderTypes.Add("Возростание", OrderType.ASC);
_orderTypes.Add("Убывание", OrderType.DESC);
cmbOrderType.SelectedIndex = 0;
cmbBoxItemsOnPage.SelectedIndex = 0;
paginatior.BindingSource = paginationSource;
cmbBoxItemsOnPage.SelectedIndexChanged += (s, e) =>
{
paginationSource = new BindingSource();
_pageModel.CurentPage = 1;
UpdateTable();
};
cmbOrderType.SelectedIndexChanged += (s, e) =>
{
if (cmbOrderType.Items != null && cmbOrderType.Items.Count != 0)
{
string value = cmbOrderType.Items[cmbOrderType.SelectedIndex].ToString();
if (!string.IsNullOrEmpty(value) && _orderTypes.ContainsKey(value))
{
_selectedOrderType = _orderTypes[value];
return;
}
}
_selectedOrderType = OrderType.NONE;
};
cmbOrderBy.SelectedIndexChanged += (s, e) =>
{
if (cmbOrderBy.Items != null && cmbOrderBy.Items.Count != 0)
{
string value = cmbOrderBy.Items[cmbOrderBy.SelectedIndex].ToString();
if (_orderProperties.ContainsKey(value))
{
_selectedOrderBy = _orderProperties[value];
return;
}
}
_selectedOrderBy = cmbOrderBy.SelectedIndex;
};
dataTable.MultiSelect = false;
dataTable.EditingControlShowing += DataTable_EditingControlShowing;
dataTable.DataBindingComplete += DataTable_DataBindingComplete;
dataTable.CellValueChanged += DataTable_CellValueChanged;
paginationSource.CurrentChanged += PaginationSource_CurrentChanged;
dataTable.SelectionChanged += DataTable_SelectionChanged;
dataTable.DoubleClick += (s,e) => {
if (DoubleClick != null) DoubleClick();
};
}
private void DataTable_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (OnCellDataChanged != null) OnCellDataChanged(dataTable.Columns[e.ColumnIndex].HeaderText, dataTable.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, dataTable.Rows[e.RowIndex]);
}
private void DataTable_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
for(int i = 0; i < dataTable.RowCount; i++)
{
if (OnRowWasCreted != null) OnRowWasCreted(dataTable.Rows[i]);
}
}
private void DataTable_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if((e.Control) is ComboBox)
{
ComboBox combo = (ComboBox)(e.Control);
combo.DropDownStyle = ComboBoxStyle.DropDownList;
combo.SelectedIndexChanged += Combo_SelectedIndexChanged;
}
}
public event EventHandler SelectedIndexChanged;
private void Combo_SelectedIndexChanged(object sender, EventArgs e)
{
if (SelectedIndexChanged != null) SelectedIndexChanged(sender, e);
}
private void DataTable_SelectionChanged(object sender, EventArgs e)
{
if(dataTable.SelectedCells.Count != 0) {
int row = dataTable.SelectedCells[0].RowIndex;
dataTable.Rows[row].Selected = true;
if (SelectedItemChange != null) SelectedItemChange(row);
}
}
public void AddComboBox(List<string> values,string headName = null, string valueMember = null)
{
DataGridViewComboBoxColumn comboBox = new DataGridViewComboBoxColumn();
comboBox.DataSource = values;
if (headName != null) comboBox.HeaderText = headName;
comboBox.Name = valueMember;
dataTable.Columns.Add(comboBox);
}
private bool _wasUpdated = false;
private void PaginationSource_CurrentChanged(object sender, EventArgs e)
{
_pageModel.CurentPage = 1 + (int)paginationSource.Current;
if (UpdateTable != null)
UpdateTable();
}
private void metroTile1_Click(object sender, EventArgs e)
{
}
private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)
{
//if (_pageModel.CurentPage < _pageModel.TotalPages)
//{
// _pageModel.CurentPage = (int)paginationSource.Current;
// UpdateTable();
//}
}
private void bindingNavigatorMoveLastItem_Click(object sender, EventArgs e)
{
//if (_pageModel.CurentPage != _pageModel.TotalPages)
//{
// _pageModel.CurentPage = (int)paginationSource.Current;
// UpdateTable();
//}
}
private void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e)
{
//if(_pageModel.CurentPage - 1 > 1)
//{
// _pageModel.CurentPage = (int)paginationSource.Current;
// UpdateTable();
//}
}
private void bindingNavigatorMoveFirstItem_Click(object sender, EventArgs e)
{
//if (_pageModel.CurentPage != 1)
//{
// _pageModel.CurentPage = (int)paginationSource.Current;
// UpdateTable();
//}
}
private void cmbOrderBy_SelectedIndexChanged(object sender, EventArgs e)
{
if (UpdateTable != null)
UpdateTable();
}
private void cmbOrderType_SelectedIndexChanged(object sender, EventArgs e)
{
if (UpdateTable != null)
UpdateTable();
}
private void button1_Click(object sender, EventArgs e)
{
foreach(var a in dataTable.SelectedCells)
{
MessageBox.Show(a.ToString());
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/SaveComponent/SaveDocument/DocumentItem.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels.Persons;
using AppPresentators;
namespace LeoBase.Components.CustomControls.SaveComponent.SaveDocument
{
public partial class DocumentItem : UserControl
{
public event Action RemoveThis;
public bool ShowRemoveButton
{
get
{
return button1.Visible;
}
set
{
button1.Visible = value;
}
}
private int _docId = -1;
public PersoneDocumentModelView Document
{
get
{
PersoneDocumentModelView doc = new PersoneDocumentModelView
{
DocumentID = _docId,
CodeDevision = tbCode.Text.Trim(),
IssuedBy = tbWhoIssued.Text.Trim(),
DocumentTypeName = cmbDocumentType.Items[cmbDocumentType.SelectedIndex].ToString(),
Number = tbNumber.Text.Trim(),
Serial = tbSerial.Text.Trim(),
WhenIssued = dtpWhenIssued.Value
};
if(string.IsNullOrEmpty(doc.Number) || string.IsNullOrEmpty(doc.IssuedBy) || string.IsNullOrEmpty(doc.Serial))
{
return null;
}
return doc;
}
set
{
_docId = value.DocumentID;
for (int i = 0; i < cmbDocumentType.Items.Count; i++)
{
if (cmbDocumentType.Items[i].ToString().Equals(value.DocumentTypeName))
{
cmbDocumentType.SelectedIndex = i;
break;
}
}
tbSerial.Text = value.Serial;
tbNumber.Text = value.Number;
tbWhoIssued.Text = value.IssuedBy;
tbCode.Text = value.CodeDevision;
dtpWhenIssued.Value = value.WhenIssued;
}
}
public DocumentItem()
{
InitializeComponent();
foreach(var dt in ConfigApp.DocumentsType)
{
cmbDocumentType.Items.Add(dt.Value);
}
cmbDocumentType.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
if (RemoveThis != null) RemoveThis();
}
}
}
<file_sep>/AppPresentators/VModels/OrganisationViewModel.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public class OrganisationViewModel
{
public int OrganisationID { get; set; }
public string Name { get; set; }
public string Format { get; set; }
public string Info { get; set; }
public PersoneViewModel Representative { get; set; }
}
}
<file_sep>/AppCore/Repositrys/PhonesRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys
{
public class PhonesRepository : IPhonesRepository
{
public IQueryable<Phone> Phones
{
get
{
var db = new LeoBaseContext();
return db.Phones;
}
}
public int AddPhone(Phone phone)
{
using(var db = new LeoBaseContext())
{
var p = db.Phones.Add(phone);
db.SaveChanges();
return p.PhoneID;
}
}
public bool Remove(int id)
{
using(var db = new LeoBaseContext())
{
var phone = db.Phones.FirstOrDefault(p => p.PhoneID == id);
if(phone != null)
{
db.Phones.Remove(phone);
db.SaveChanges();
return true;
}
}
return false;
}
public int RemoveAllUserPhones(int userid)
{
using(var db = new LeoBaseContext())
{
var phones = db.Phones.Where(p => p.Persone.UserID == userid);
var count = phones.Count();
db.Phones.RemoveRange(phones);
db.SaveChanges();
return count;
}
}
}
}
<file_sep>/AppPresentators/VModels/Protocols/ProtocolAboutViolationPersoneViewModel.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Protocols
{
/// <summary>
/// Протокол об административном правонарушение для физического лица
/// </summary>
public class ProtocolAboutViolationPersoneViewModel:ProtocolViewModel
{
public int ProtocolAboutViolationPersoneID { get; set; }
public PersoneViewModel Violator { get; set; }
/// <summary>
/// Дата и время правонарушения
/// </summary>
public DateTime ViolationDate { get; set; }
/// <summary>
/// Описание правонарушения
/// </summary>
public string ViolationDescription { get; set; }
/// <summary>
/// Статья КОАП за данное нарушение
/// </summary>
public string KOAP { get; set; }
/// <summary>
/// Найденная продукция природопользования
/// </summary>
public string FindedNatureManagementProducts { get; set; }
/// <summary>
/// Найденное оружие
/// </summary>
public string FindedWeapons { get; set; }
/// <summary>
/// Найденые орудия для охоты и рыболовства
/// </summary>
public string FindedGunsHuntingAndFishing { get; set; }
}
}
<file_sep>/AppPresentators/Infrastructure/IApplicationFactory.cs
using AppPresentators.Components;
using AppPresentators.Presentators.Interfaces;
using AppPresentators.Views;
using AppPresentators.VModels.MainMenu;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Infrastructure
{
public interface IApplicationFactory
{
T GetPresentator<T, V, S>(IMainView main);
T GetPresentator<T>(IMainView main);
T GetPresentator<T>();
IMainPresentator GetMainPresentator(IApplicationFactory appFactory);
IMainPresentator GetMainPresentator();
IMainView GetMainView();
T GetView<T>();
T GetService<T>();
T GetComponent<T>();
UIComponent GetComponent(MenuCommand command);
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/ProtocolsPresentators/IProtocolAboutViolationPresentator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces.ProtocolsPresentators
{
public interface IProtocolAboutViolationPresentator:IProtocolPresentator
{
IRulingForViolationPresentator Ruling { get; set; }
}
}
<file_sep>/AppCore/Repositrys/PersonesRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys
{
public class PersonesRepository : IPersoneRepository
{
public int Count
{
get
{
return Persons.Count();
}
}
public IQueryable<Persone> Persons
{
get
{
var dbContext = new LeoBaseContext();
return dbContext.Persones;
}
}
public int AddPersone(Persone persone)
{
using (var dbContext = new LeoBaseContext()) {
dbContext.Persones.Add(persone);
dbContext.SaveChanges();
}
return persone.UserID;
}
public bool SimpleRemove(int id)
{
using(var db = new LeoBaseContext())
{
var persone = db.Persones.FirstOrDefault(p => p.UserID == id);
if (persone == null) return false;
persone.Deleted = true;
db.SaveChanges();
return true;
}
}
public bool Remove(int id)
{
using(var db = new LeoBaseContext())
{
var persone = db.Persones
.Include("Address")
.Include("Phones")
.Include("Documents")
.FirstOrDefault(p => p.UserID == id);
if (persone != null)
{
var addresses = db.Addresses.Where(p => p.Persone.UserID == persone.UserID);
var documents = db.Documents.Where(p => p.Persone.UserID == persone.UserID);
var phones = db.Phones.Where(p => p.Persone.UserID == persone.UserID);
if (addresses != null)
db.Addresses.RemoveRange(addresses);
if (documents != null)
db.Documents.RemoveRange(documents);
if (phones != null)
db.Phones.RemoveRange(phones);
db.Persones.Remove(persone);
db.SaveChanges();
return true;
}
}
return false;
}
public bool Update(Persone persone)
{
using(var db = new LeoBaseContext())
{
var uPersone = db.Persones.FirstOrDefault(p => p.UserID == persone.UserID);
//var uDocuments = db.Documents.Where(p => p.Persone.UserID == persone.UserID);
//var uPhones = db.Documents.Where(p => p.Persone.UserID == persone.UserID);
//var uAddresses = db.Addresses.Where(p => p.Persone.UserID == persone.UserID);
if(persone.Address != null) {
List<int> adrIds = new List<int>();
foreach (var address in persone.Address)
{
var adrSearch = db.Addresses.FirstOrDefault(a => a.AddressID == address.AddressID);
if (adrSearch != null)
{
adrSearch.Country = address.Country;
adrSearch.Subject = address.Subject;
adrSearch.Area = address.Area;
adrSearch.City = address.City;
adrSearch.Street = address.Street;
adrSearch.HomeNumber = address.HomeNumber;
adrSearch.Flat = address.Flat;
adrSearch.Note = address.Note;
}
else
{
address.Persone = uPersone;
db.Addresses.Add(address);
}
adrIds.Add(address.AddressID);
}
var addressesForRemove = db.Addresses.Where(a => a.Persone.UserID == persone.UserID && !adrIds.Contains(a.AddressID));
db.Addresses.RemoveRange(addressesForRemove);
}
if(persone.Documents != null)
{
List<int> docIds = new List<int>();
foreach(var document in persone.Documents)
{
var docSearch = db.Documents.FirstOrDefault(d => d.DocumentID == document.DocumentID);
if(docSearch != null)
{
docSearch.Document_DocumentTypeID = document.Document_DocumentTypeID;
docSearch.Serial = document.Serial;
docSearch.Number = document.Number;
docSearch.IssuedBy = document.IssuedBy;
docSearch.WhenIssued = document.WhenIssued;
docSearch.CodeDevision = document.CodeDevision;
}else
{
document.Persone = uPersone;
db.Documents.Add(document);
}
docIds.Add(document.DocumentID);
}
var documentsForDelete = db.Documents.Where(d => d.Persone.UserID == persone.UserID && !docIds.Contains(d.DocumentID));
db.Documents.RemoveRange(documentsForDelete);
}
if(persone.Phones != null)
{
List<int> phoneIds = new List<int>();
foreach(var phone in persone.Phones)
{
var phoneSearch = db.Phones.FirstOrDefault(p => p.PhoneID == phone.PhoneID);
if(phoneSearch != null)
{
phoneSearch.PhoneNumber = phone.PhoneNumber;
}else
{
phone.Persone = uPersone;
db.Phones.Add(phone);
}
phoneIds.Add(phone.PhoneID);
}
var phonesForDelete = db.Phones.Where(p => p.Persone.UserID == uPersone.UserID && !phoneIds.Contains(p.PhoneID));
db.Phones.RemoveRange(phonesForDelete);
}
uPersone.FirstName = persone.FirstName;
uPersone.SecondName = persone.SecondName;
uPersone.MiddleName = persone.MiddleName;
uPersone.PlaceOfBirth = persone.PlaceOfBirth;
uPersone.DateBirthday = persone.DateBirthday;
uPersone.PlaceWork = persone.PlaceWork;
uPersone.Image = persone.Image;
uPersone.IsEmploeyr = persone.IsEmploeyr;
uPersone.Position_PositionID = persone.Position_PositionID;
uPersone.WasBeUpdated = DateTime.Now;
db.SaveChanges();
}
return true;
}
}
}
<file_sep>/AppCore/Abstract/Protocols/IProtocolAboutInspectionRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract.Protocols
{
public interface IProtocolAboutInspectionRepository
{
IQueryable<ProtocolAboutInspection> ProtocolsAboutInspection { get; }
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/ComponentPresentators/IViolationTablePresentator.cs
using AppPresentators.Services;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces.ComponentPresentators
{
public interface IViolationTablePresentator:IComponentPresentator
{
void Update(ViolationSearchModel search, ViolationOrderModel order, PageModel page);
}
}
<file_sep>/LeoBase/Components/CustomControls/SaveComponent/SavePhone/PhoneItem.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels.Persons;
namespace LeoBase.Components.CustomControls.SaveComponent.SavePhone
{
public partial class PhoneItem : UserControl
{
public event Action RemoveThis;
private int _phoneID = -1;
public PhoneViewModel Phone { get
{
return new PhoneViewModel
{
PhoneID = _phoneID,
PhoneNumber = tbPhoneNumber.Text
};
}
set
{
_phoneID = value.PhoneID;
tbPhoneNumber.Text = value.PhoneNumber;
}
}
public bool ShowRemoveButton
{
get
{
return btnRemove.Visible;
}
set
{
btnRemove.Visible = value;
}
}
public PhoneItem()
{
InitializeComponent();
btnRemove.Click += (s, e)=>
{
if (RemoveThis != null) RemoveThis();
};
}
}
}
<file_sep>/LeoBase/Components/CustomControls/SearchPanels/AutoBinderPanel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using AppData.CustomAttributes;
using System.ComponentModel;
using AppPresentators.VModels;
using System.Collections;
using System.Drawing;
using LeoBase.Components.CustomControls.Interfaces;
using LeoBase.Components.CustomControls.NewControls;
using System.IO;
namespace LeoBase.Components.CustomControls.SearchPanels
{
public partial class AutoBinderPanel:Panel, IClearable
{
private object _dataSource = null;
private TableLayoutPanel _container;
private Dictionary<string, PropertyControlModel> _controls;
public event EventHandler DataSourceChanged;
public object DataSource { get
{
return _dataSource;
}
set
{
_dataSource = value;
BuildModel();
}
}
private void BuildModel()
{
_controls = new Dictionary<string, PropertyControlModel>();
int rowCount = 2;
foreach(var prop in _dataSource.GetType().GetProperties())
{
bool showInHead = true;
var propertyModel = new PropertyControlModel();
foreach (var attribute in prop.GetCustomAttributesData())
{
try {
switch (attribute.AttributeType.Name)
{
case "BrowsableAttribute":
if(PanelType != AutoBinderPanelType.DETAILS && PanelType != AutoBinderPanelType.EDIT)
showInHead = prop.GetCustomAttribute<BrowsableAttribute>().Browsable;
break;
case "BrowsableForEditAndDetailsAttribute":
propertyModel.ShowForDetails = prop.GetCustomAttribute<BrowsableForEditAndDetailsAttribute>().BrowsableForDetails;
propertyModel.ShowForEdit = prop.GetCustomAttribute<BrowsableForEditAndDetailsAttribute>().BrowsableForEdit;
break;
case "DisplayNameAttribute":
propertyModel.Title = prop.GetCustomAttribute<DisplayNameAttribute>().DisplayName;
break;
case "ControlTypeAttribute":
var attributeControlType = prop.GetCustomAttribute<ControlTypeAttribute>();
propertyModel.ControlType = attributeControlType.ControlType;
if(propertyModel.ControlType == ControlType.ComboBox)
{
propertyModel.DisplayMember = attributeControlType.DisplayMember;
propertyModel.ValueMember = attributeControlType.ValueMember;
var attributeData = prop.GetCustomAttribute<DataPropertiesNameAttribute>();
if(attributeData != null)
{
var type = _dataSource.GetType();
var data = (IList)type.GetProperty(attributeData.PropertyDataName).GetValue(_dataSource);
propertyModel.ComboBoxData = data;
}
}
break;
case "ChildrenPropertyAttribute":
propertyModel.CompareProperty = prop.GetCustomAttribute<ChildrenPropertyAttribute>().ChildrenPropertyName;
break;
case "DinamicBrowsableAttribute":
string propertyName = prop.GetCustomAttribute<DinamicBrowsableAttribute>().PropertyName;
bool findedValue = prop.GetCustomAttribute<DinamicBrowsableAttribute>().PropertyValue;
bool value = (bool)_dataSource.GetType().GetProperty(propertyName).GetValue(_dataSource);
showInHead = value == findedValue;
break;
case "PropertyNameSelectedTextAttribute":
string selectedTextPropertyName = prop.GetCustomAttribute<PropertyNameSelectedTextAttribute>().PropertyName;
propertyModel.SelectedText = (string)_dataSource.GetType().GetProperty(selectedTextPropertyName).GetValue(_dataSource);
break;
case "GenerateEmptyModelPropertyNameAttribute":
string funcGenerListItem = prop.GetCustomAttribute<GenerateEmptyModelPropertyNameAttribute>().PropertyName;
propertyModel.GetListObject = (Func<object>)_dataSource.GetType().GetProperty(funcGenerListItem).GetValue(_dataSource);
break;
}
}catch(Exception e)
{
int a = 10;
}
}
switch (PanelType)
{
case AutoBinderPanelType.SEARCH:
if (!showInHead) continue;
break;
case AutoBinderPanelType.DETAILS:
if (!propertyModel.ShowForDetails) continue;
break;
case AutoBinderPanelType.EDIT:
if (!propertyModel.ShowForEdit) continue;
break;
}
rowCount++;
try {
propertyModel.Value = prop.GetValue(_dataSource);
}catch(Exception e)
{
int a = 10;
}
Control control = null;
if (propertyModel.ControlType == ControlType.Text)
{
control = GetTextBox(propertyModel);
if(propertyModel.Value != null && propertyModel.Value != "0")
control.Text = propertyModel.Value.ToString();
((LeoTextBox)control).TextChanged += (s, e) =>
{
_dataSource.GetType().GetProperty(prop.Name).SetValue(_dataSource, control.Text);
if(DataSourceChanged != null)
{
DataSourceChanged(control, new EventArgs());
}
};
}
else if (propertyModel.ControlType == ControlType.Int)
{
control = GetTextBox(propertyModel);
if(propertyModel.Value != null)
control.Text = propertyModel.Value.ToString();
((LeoTextBox)control).TextChanged += (s, e) =>
{
try
{
_dataSource.GetType().GetProperty(prop.Name).SetValue(_dataSource, Convert.ToInt32(control.Text));
if (DataSourceChanged != null) DataSourceChanged(control, new EventArgs());
}
catch { }
};
control.KeyPress += (s, e) =>
{
if (!Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
};
}
else if (propertyModel.ControlType == ControlType.Real)
{
control = GetTextBox(propertyModel);// new LeoTextBox();
if(propertyModel.Value != null && (decimal)propertyModel.Value != 0)
control.Text = propertyModel.Value.ToString();
((LeoTextBox)control).TextChanged += (s, e) =>
{
try
{
decimal val = Convert.ToDecimal(control.Text.Replace('.', ','));
_dataSource.GetType().GetProperty(prop.Name).SetValue(_dataSource, val);
if (DataSourceChanged != null) DataSourceChanged(control, new EventArgs());
}
catch { }
};
control.KeyPress += (s, e) =>
{
if (e.KeyChar == 46 && (((TextBox)s).Text.Contains(".")))
{
e.Handled = true;
}
else if (!Char.IsDigit(e.KeyChar) && !e.KeyChar.ToString().Equals("."))
{
e.Handled = true;
}
};
}
else if (propertyModel.ControlType == ControlType.DateTime)
{
#region Set DatePiker
control = new DateTimePicker();
((DateTimePicker)control).Value = propertyModel.Value != null && ((DateTime)propertyModel.Value).Year != 1 ? (DateTime)propertyModel.Value : DateTime.Now;
((DateTimePicker)control).ValueChanged += (s, e) =>
{
_dataSource.GetType().GetProperty(prop.Name).SetValue(_dataSource, ((DateTimePicker)control).Value);
if (DataSourceChanged != null) DataSourceChanged(control, new EventArgs());
};
#endregion
}
else if (propertyModel.ControlType == ControlType.ComboBox)
{
control = GetComboBox(propertyModel);
((ComboBox)control).SelectedIndexChanged += (s, e) =>
{
_dataSource.GetType().GetProperty(prop.Name).SetValue(_dataSource, ((ComboBox)control).SelectedValue);
if (DataSourceChanged != null) DataSourceChanged(control, new EventArgs());
};
//propertyModel.Control = control;
}else if(propertyModel.ControlType == ControlType.Image )
{
PictureViewer viewer = new PictureViewer();
FlowLayoutPanel flow = new FlowLayoutPanel();
Button openFileDialogButton = new Button();
openFileDialogButton.Text = "Выбрать файл";
if(propertyModel.Value != null && ((byte[])propertyModel.Value).Length != 0)
try {
viewer.Image = (byte[])propertyModel.Value;
}
catch(Exception e) {
int a = 10;
}
viewer.Dock = DockStyle.Top;
openFileDialogButton.Dock = DockStyle.Bottom;
flow.Width = 180;
flow.Controls.Add(viewer);
flow.Controls.Add(openFileDialogButton);
flow.Height = viewer.Height + openFileDialogButton.Height + 6;
control = flow;
openFileDialogButton.Click += (s, e) =>
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG;*.JPEG)|*.BMP;*.JPG;*.GIF;*.PNG;*.JPEG";
fileDialog.Multiselect = false;
if(fileDialog.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(fileDialog.FileName, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
viewer.Image = data;
_dataSource.GetType().GetProperty(prop.Name).SetValue(_dataSource, data);
}
};
viewer.OnDeleteClick += (pv) =>
{
if (pv.Image == null || pv.Image.Length == 0) return;
if(MessageBox.Show("Вы уверены, что хотите удалить изображение?", "Предупреждение", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
viewer.Image = null;
_dataSource.GetType().GetProperty(prop.Name).SetValue(_dataSource, new byte[0]);
}
};
}
else if(propertyModel.ControlType == ControlType.List)
{
TableLayoutPanel panel = new TableLayoutPanel();
var value = (IList)propertyModel.Value;
panel.ColumnCount = 1;
//int childrenIndexRow = -1;
if (PanelType == AutoBinderPanelType.EDIT)
{
Button btn = new Button();
Panel panelButton = new Panel();
panelButton.Dock = DockStyle.Top;
panelButton.AutoSize = true;
btn.Text = "Добавить";
panelButton.Controls.Add(btn);
panel.Controls.Add(panelButton);
btn.Click += (s, e) =>
{
if (propertyModel.GetListObject != null)
{
var item = propertyModel.GetListObject();
value.Add(item);
var autoBinderPanel = new AutoBinderPanel(PanelType);
autoBinderPanel.DataSource = item;
autoBinderPanel.Dock = DockStyle.Left;
autoBinderPanel.Width = 400;
Button deleteBtn = new Button();
deleteBtn.Text = "Удалить";
deleteBtn.Click += (s2, e2) =>
{
if (MessageBox.Show("Вы уверены, что хотите удалить эту запись?", "Предупреждение", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
if (_container != null)
{
panel.Controls.Remove(deleteBtn);
panel.Controls.Remove(autoBinderPanel);
}
value.Remove(item);
}
};
panel.Controls.Add(deleteBtn);
panel.Controls.Add(autoBinderPanel);
}
};
}
panel.Dock = DockStyle.Top;
panel.AutoSize = true;
if(value != null)
foreach(var item in value)
{
var autoBinderPanel = new AutoBinderPanel(PanelType);
autoBinderPanel.DataSource = item;
autoBinderPanel.Dock = DockStyle.Left;
autoBinderPanel.Width = 400;
Button deleteBtn = new Button();
deleteBtn.Text = "Удалить";
deleteBtn.Click += (s, e) =>
{
if(MessageBox.Show("Вы уверены, что хотите удалить эту запись?", "Предупреждение", MessageBoxButtons.OKCancel) == DialogResult.OK) {
if(_container != null)
{
panel.Controls.Remove(deleteBtn);
panel.Controls.Remove(autoBinderPanel);
}
value.Remove(item);
}
};
panel.Controls.Add(deleteBtn);
panel.Controls.Add(autoBinderPanel);
}
control = panel;
}
#region CompareRegion
if(propertyModel.CompareProperty != null)
{
ComboBox compareCombo = new ComboBox();
compareCombo.DropDownStyle = ComboBoxStyle.DropDownList;
List<OrderComboBoxModel> data = new List<OrderComboBoxModel>
{
new OrderComboBoxModel
{
CompareType = CompareValue.NONE,
Value = "Не учитывать"
},
new OrderComboBoxModel
{
CompareType = CompareValue.MORE,
Value = "Больше"
},
new OrderComboBoxModel
{
CompareType = CompareValue.LESS,
Value = "Меньше"
},
new OrderComboBoxModel
{
CompareType = CompareValue.EQUAL,
Value = "Равно"
}
};
compareCombo.DisplayMember = "Value";
compareCombo.ValueMember = "CompareType";
compareCombo.DataSource = data;
if (propertyModel.CompareProperty != null)
{
compareCombo.SelectedIndexChanged += (s, e) =>
{
_dataSource.GetType().GetProperty(propertyModel.CompareProperty).SetValue(_dataSource, compareCombo.SelectedValue);
if (DataSourceChanged != null) DataSourceChanged(s, e);
};
}
TableLayoutPanel layoutPanel = new TableLayoutPanel();
layoutPanel.RowCount = 1;
layoutPanel.ColumnCount = 2;
for (int i = 0; i < layoutPanel.ColumnCount; i++)
{
layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
}
layoutPanel.Controls.Add(control, 0, 0);
layoutPanel.Controls.Add(compareCombo, 1, 0);
propertyModel.Control = layoutPanel;
}
else
{
propertyModel.Control = control;
}
#endregion
_controls.Add(prop.Name, propertyModel);
}
this.Controls.Clear();
switch (PanelType)
{
case AutoBinderPanelType.SEARCH:
SearchDesineRenderControls();
break;
case AutoBinderPanelType.EDIT:
EditDesineRenderControls();
break;
case AutoBinderPanelType.DETAILS:
DetailsDesineRenderControls();
break;
}
_container.AutoScroll = true;
_container.Padding = new Padding(0, 0, 20, 0);
}
private ComboBox GetComboBox(PropertyControlModel propertyModel)
{
ComboBox result = null;
switch (PanelType)
{
case AutoBinderPanelType.SEARCH:
result = GetComboBoxForSearch(propertyModel);
break;
case AutoBinderPanelType.EDIT:
result = GetComboBoxForEdit(propertyModel);
break;
case AutoBinderPanelType.DETAILS:
result = GetComboBoxForDetails(propertyModel);
break;
}
return result;
}
private LeoTextBox GetTextBox(PropertyControlModel propertyModel)
{
LeoTextBox textBox = null;
switch (PanelType)
{
case AutoBinderPanelType.SEARCH:
textBox = GetTextBoxForSearch(propertyModel);
break;
case AutoBinderPanelType.EDIT:
textBox = GetTextBoxForEdit(propertyModel);
break;
case AutoBinderPanelType.DETAILS:
textBox = GetTextBoxForDetails(propertyModel);
break;
}
return textBox;
}
public AutoBinderPanelType PanelType { get; private set; }
private Label _title;
private PictureBox _titleImage;
public string Title { get
{
if (_title == null) _title = new Label();
return _title.Text;
}
set
{
if (_title == null) _title = new Label();
}
}
public Image TitleImage { get; set; }
public AutoBinderPanel(AutoBinderPanelType panelType = AutoBinderPanelType.SEARCH, string title = null, Image titleImage = null)
{
PanelType = panelType;
}
public void UpdatePropertyValue(string propertyName, object data)
{
if (!_controls.ContainsKey(propertyName)) return;
var control = _controls[propertyName];
switch (control.ControlType)
{
case ControlType.Text:
case ControlType.Real:
case ControlType.Int:
((LeoTextBox)control.Control).Text = data.ToString();
break;
case ControlType.DateTime:
((DateTimePicker)control.Control).Value = (DateTime)data;
break;
case ControlType.ComboBox:
((ComboBox)control.Control).SelectedIndex = ((ComboBox)control.Control).FindString(data.ToString());// data;
break;
}
}
public void Clear()
{
foreach(var control in _controls)
{
Control ctr = control.Value.Control;
if (ctr.GetType().Name.Equals("TableLayoutPanel"))
{
foreach(var c in ctr.Controls)
{
if (c.GetType().Name.Equals("LeoTextBox")) ((LeoTextBox)c).Text = "";
else if (c.GetType().Name.Equals("DateTimePicker")) ((DateTimePicker)c).Value = DateTime.Now;
else if (c.GetType().Name.Equals("ComboBox")) ((ComboBox)c).SelectedIndex = 0;
}
}else {
switch (control.Value.ControlType)
{
case ControlType.ComboBox:
((ComboBox)(control.Value.Control)).SelectedIndex = 0;
break;
case ControlType.Real:
case ControlType.Int:
case ControlType.Text:
((LeoTextBox)control.Value.Control).Text = "";
break;
case ControlType.DateTime:
((DateTimePicker)control.Value.Control).Value = DateTime.Now;
break;
}
}
}
}
public Control GetControl()
{
return this;
}
}
public enum AutoBinderPanelType
{
SEARCH,
EDIT,
DETAILS
}
public class OrderComboBoxModel
{
public CompareValue CompareType { get; set; }
public string Value { get; set; }
}
public class PropertyControlModel
{
public string Title { get; set; }
public ControlType ControlType { get; set; } = ControlType.Text;
public Control Control { get; set; }
public Control ChildrenControl { get; set; }
public ControlType ChildrenControlType { get; set; } = ControlType.Text;
public string CompareProperty { get; set; }
public IList ComboBoxData { get; set; }
public string DisplayMember { get; set; }
public string ValueMember { get; set; }
public object Value { get; set; }
public bool ShowForEdit { get; set; }
public bool ShowForDetails { get; set; }
public string SelectedText { get; set; }
public Func<object> GetListObject { get; set; }
}
}
<file_sep>/AppCore/Abstract/Protocols/IProtocolRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract.Protocols
{
public interface IProtocolRepository
{
IQueryable<Protocol> Protocols { get; }
int SaveProtocol(Protocol protocol);
}
}
<file_sep>/AppCore/Contexts/PassedContext.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Contexts
{
public class PassedContext:DbContext
{
public PassedContext():base("DataSource='PassedDataBase.sdf';Password='<PASSWORD>'") { }
/// <summary>
/// Пропуска
/// </summary>
public DbSet<Pass> Passes { get; set; }
}
}
<file_sep>/LeoBase/Forms/MainView.cs
using AppPresentators.Views;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels;
using AppPresentators.Components;
using AppPresentators.Components.MainMenu;
using MetroFramework.Forms;
using System.Threading;
using LeoBase.Properties;
using LeoBase.Components.CustomControls;
using LeoBase.Components.CustomControls.SearchPanels;
using AppPresentators.Services;
using AppPresentators;
using AppPresentators.Infrastructure;
namespace LeoBase.Forms
{
public partial class MainView : Form, IMainView
{
public event Action Login;
public event Action FastSearchGO;
private VManager _currentManager;
private IMainMenu _mainMenu;
Size _oldSize = new Size(640, 480);
private PreloadPanel _preloadPanel;
private static MainView _instance = null;
private BackgroundWorker _pageLoader;
public bool ShowFastSearch { get
{
return panelFastSearch.Visible;
}
set
{
panelFastSearch.Visible = value;
}
}
public string SearchQuery
{
get
{
return tbFastSearch.Text.Trim();
}
set
{
string oldValue = tbFastSearch.Text.Trim();
tbFastSearch.Text = value;
}
}
public static MainView GetInstance()
{
if (_instance == null) _instance = new MainView();
return _instance;
}
public MainView()
{
InitializeComponent();
this.Resize += (s, e) => MainResize();
this.Text = string.Empty;
tbFastSearch.TextChanged += (s, e) => FastSearch();
_oldSize = this.Size;
_instance = this;
_pageLoader = new BackgroundWorker();
_pageLoader.DoWork += PageLoading;
_pageLoader.RunWorkerCompleted += PageLoaded;
_preloadPanel = new PreloadPanel();
_preloadPanel.Visible = false;
centerPanel.Controls.Add(_preloadPanel);
}
public void MakeOrder(IOrderPage orderPage)
{
OrderDialog dialog = new OrderDialog();
dialog.OrderPage = orderPage;
dialog.StartPosition = FormStartPosition.CenterParent;
dialog.ShowDialog();
}
AdminViolationSearchModel aa = new AdminViolationSearchModel();
public void SetTopControls(List<Control> controls)
{
contentButtons.Controls.Clear();
if (controls == null || controls.Count == 0) return;
contentButtons.ColumnCount = controls.Count;
contentButtons.Refresh();
foreach (var c in controls)
{
contentButtons.Controls.Add(c);
}
}
private void BtnFastSearch_Click(object sender, EventArgs e)
{
}
private void FastSearch()
{
string query = tbFastSearch.Text.Trim();
if(query.Length > 3 || query.Length == 0)
{
if(FastSearchGO != null)
{
FastSearchGO();
}
}
}
private void MainView_ResizeEnd(object sender, EventArgs e)
{
_oldSize = this.Size;
}
private void MainResize()
{
}
public VManager Manager
{
get
{
return _currentManager;
}
set
{
_currentManager = value;
if (_currentManager != null)
{
lbAccauntInfo.Text = _currentManager.Login.Equals("admin") ? "Администратор" : "Пользователь";
btnLogout.Enabled = true;
managerPanel.Visible = true;
}
else
{
managerPanel.Visible = false;
}
}
}
public void ShowError(string errorMessage)
{
MessageBox.Show(errorMessage);
}
private static bool _pageLoading = false;
Control saveControl = null;
private void PageLoaded(object sender, RunWorkerCompletedEventArgs e)
{
}
private void OnFrameChanged(object o, EventArgs e)
{
}
private void PageLoading(object sender, DoWorkEventArgs e)
{
centerPanel.Invoke(new MethodInvoker(() =>
{
var preloader = new Label();
preloader.AutoSize = true;
preloader.BackColor = Color.Transparent;
preloader.Text = "Загрузка...";
preloader.Top = centerPanel.Height / 2 - preloader.Height / 2;
preloader.Left = centerPanel.Width / 2 - preloader.Width / 2;
preloader.Font = new Font("Arial", 18, FontStyle.Italic);
Bitmap bmp = new Bitmap(preloader.Width, preloader.Height);
Graphics g = Graphics.FromImage(bmp);
preloader.Image = bmp;
centerPanel.Controls.Add(preloader);
}));
}
private Action<Control> setPictureBox = (Control control) =>
{
//control.Controls.Add(preloader);
};
public void StartTask()
{
Bitmap saveState = new Bitmap(centerPanel.Width, centerPanel.Height);
centerPanel.DrawToBitmap(saveState, new Rectangle(0, 0, centerPanel.Width, centerPanel.Height));
Graphics g = Graphics.FromImage(saveState);
var brash = new SolidBrush(Color.FromArgb(140, 255, 255, 255));
g.FillRectangle(brash, new Rectangle(0, 0, centerPanel.Width, centerPanel.Height));
if (centerPanel.Controls.Count != 0) saveControl = centerPanel.Controls[0];
centerPanel.Controls.Clear();
centerPanel.BackgroundImage = saveState;
_pageLoading = true;
_pageLoader.RunWorkerAsync();
//Thread.Sleep(3000);
}
public void EndTask(bool setOldState)
{
_pageLoading = false;
centerPanel.BackgroundImage = null;
if (setOldState && saveControl != null) {
centerPanel.Controls.Add(saveControl);
}
}
public void Show()
{
try {
Application.Run(this);
}catch(Exception e)
{
return;
}
}
public bool RemoveComponent(Control component)
{
if (centerPanel.Controls.IndexOf(component) != -1)
{
centerPanel.Controls.Remove(component);
return true;
}
return false;
}
private Control childrenControl;
public void SetComponent(Control component)
{
if(component == null)
{
centerPanel.Controls.Clear();
this.Refresh();
return;
}
component.Anchor = AnchorStyles.None;
component.Dock = DockStyle.Fill;
centerPanel.Controls.Clear();
centerPanel.Controls.Add(component);
childrenControl = component;
this.Refresh();
}
public void MainView_Load(object sender, EventArgs ev)
{
MainResize();
if (_currentManager == null) Login();
btnLogout.Click += (s, e) =>
{
SetComponent(null);
SetTopControls(null);
LogoutClick();
};
}
private void LogoutClick()
{
managerPanel.Visible = false;
if (Login != null) {
Login();
tbFastSearch.Visible = false;
}
}
public void SetMenu(IMainMenu control)
{
_mainMenu = control;
_mainMenu.Resize(menuPanel.Width, menuPanel.Height);
menuPanel.Controls.Clear();
menuPanel.Controls.Add(_mainMenu.GetControl());
}
public void ClearCenter()
{
centerPanel.Controls.Clear();
centerPanel.Refresh();
}
public event Action GoNextPage;
public event Action GoBackPage;
private void btnNext_Click(object sender, EventArgs e)
{
if (GoNextPage != null) GoNextPage();
}
private void btnBack_Click(object sender, EventArgs e)
{
if (GoBackPage != null) GoBackPage();
}
private void btnLogout_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>/LeoMapV2/Form1.cs
using LeoMapV2.Data;
using LeoMapV2.Map;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoMapV2
{
public partial class Form1 : Form
{
TitleDBRepository repo;
LeoMap map;
List<Models.DPoint> _points = new List<Models.DPoint>();
public Form1()
{
InitializeComponent();
repo = new TitleDBRepository("D:\\Maps\\test.lmap");
repo.ClearCache();
map = new LeoMap(repo);
var point = new Models.DPoint
{
N = 42.74501533,
E = 131.20658056,
Zoom = 14
};
var point2 = new Models.DPoint
{
N = 43.47892223,
E = 131.162419444,
Zoom = 14,
ToolTip = "Test 123"
};
map.SetPoint(point);
map.SetPoint(point2);
map.LookAt(point);
map.LookAt(point2);
for(double x = 131; x < 132; x+= 0.01)
{
for(double y = 42; y<44; y+= 0.01)
{
_points.Add(new Models.DPoint
{
N = y,
E = x
});
}
}
map.Dock = DockStyle.Fill;
map.MouseMoving += Map_MouseMoving;
map.RegionSelected += (s, e) =>
{
string message = e.ToString();
map.ClearPoints();
var points = _points.Where(p => p.E >= e.W && p.E <= e.E && p.N <= e.N && p.N >= e.S);
if(points != null)
{
map.SetPoints(points.ToList());
}
map.Redraw();
};
map.PointClicked += (s, e) =>
{
var a = e;
MessageBox.Show(a.ToolTip);
};
panel2.Controls.Add(map);
}
private void Map_MouseMoving(object arg1, Models.MapEventArgs arg2)
{
lbCoords.Text = string.Format("N:{0:0.00000000}; E:{1:0.00000000}", arg2.N, arg2.E);
}
private async void button1_Click(object sender, EventArgs e)
{
try
{
var point = TextBoxsToPoint();
map.SetPoint(point);
map.RedrawAsync();
}
catch(Exception e1)
{
var a = e1;
}
}
private Models.DPoint TextBoxsToPoint()
{
double n = Convert.ToDouble(textBox1.Text.Replace(".", ","));
double e = Convert.ToDouble(textBox2.Text.Replace(".", ","));
return new Models.DPoint
{
N = n,
E = e
};
}
private void button2_Click(object sender, EventArgs e)
{
try
{
var point = TextBoxsToPoint();
map.LookAt(point);
}
catch (Exception e1)
{
var a = e1;
}
}
}
}
<file_sep>/AppPresentators/Components/IViolatorDetailsControl.cs
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public interface IViolatorDetailsControl: UIComponent
{
event Action MakeReport;
event Action<int> ShowDetailsViolation;
event Action EditViolator;
ViolatorDetailsModel Violator { get; set; }
}
}
<file_sep>/AppPresentators/VModels/ViolatorDetailsModel.cs
using AppData.Entities;
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public class ViolatorDetailsModel
{
public int ViolatorID { get; set; }
public string FIO { get; set; }
public string PlaceWork { get; set; }
public DateTime DateBerth { get; set; }
public string PlaceBerth { get; set; }
public byte[] Image { get; set; }
public List<PersoneDocumentModelView> Documents { get; set; }
public List<PersonAddressModelView> Addresses { get; set; }
public List<PhoneViewModel> Phones { get; set; }
public List<AdminViolationRowModel> Violations { get; set; }
}
}
<file_sep>/AppPresentators/Components/ISaveAdminViolationControl.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public interface ISaveAdminViolationControl: UIComponent
{
event Action Save;
event Action FindEmployer;
event Action FindViolator;
event Action CreateEmployer;
event Action CreateViolator;
AdminViolation Violation { get; set; }
void Update();
void UpdateEmployer();
void UpdateViolator();
void ShowMessage(string message);
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/SavePassControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppData.Entities;
using AppPresentators;
namespace LeoBase.Components.CustomControls.NewControls
{
public partial class SavePassControl : UserControl, IEditPassControl
{
public SavePassControl()
{
InitializeComponent();
}
private Pass _pass;
public Pass Pass
{
get
{
MakePass();
return _pass;
}
set
{
_pass = value;
lbTitle.Text = value.PassID <= 0 ? "Добавление нового пропуска" : "Редактирование пропуска";
RenderPass();
}
}
public bool ShowForResult { get; set; }
public List<Control> TopControls
{
get
{
var btnSave = new Button();
btnSave.Text = "Сохранить";
btnSave.Click += (s, e) =>
{
if (Save != null) Save();
};
return new List<Control> { btnSave };
}
set { }
}
public event Action Save;
public Control GetControl()
{
return this;
}
public void ShowError(string message)
{
MessageBox.Show(message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public void ShowMessage(string message)
{
MessageBox.Show(message, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
void UIComponent.Resize(int width, int height)
{
}
private void MakePass()
{
_pass.FirstName = tbFirstName.Text;
_pass.SecondName = tbSecondName.Text;
_pass.MiddleName = tbMiddleName.Text;
_pass.Number = tbNumber.Text;
_pass.Serial = tbSerial.Text;
_pass.WhoIssued = tbWhoIssued.Text;
_pass.DocumentType = cmpDocumentType.Items[cmpDocumentType.SelectedIndex].ToString();
_pass.PassClosed = dtpPassClosed.Value;
_pass.PassGiven = dtpPassGiven.Value;
_pass.WhenIssued = dtpWhenIssued.Value;
}
private void RenderPass()
{
tbFirstName.Text = _pass.FirstName;
tbSecondName.Text = _pass.SecondName;
tbMiddleName.Text = _pass.MiddleName;
dtpPassGiven.Value = _pass.PassGiven;
dtpPassClosed.Value = _pass.PassClosed;
dtpWhenIssued.Value = _pass.WhenIssued;
tbSerial.Text = _pass.Serial;
tbNumber.Text = _pass.Number;
tbWhoIssued.Text = _pass.WhoIssued;
int i = 0;
foreach(var doc in ConfigApp.DocumentTypesList)
{
cmpDocumentType.Items.Add(doc.Name);
if (doc.Name.Equals(_pass.DocumentType)) cmpDocumentType.SelectedIndex = i;
i++;
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/SearchPanels/ViolationSearchPanel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Services;
using AppPresentators.VModels;
namespace LeoBase.Components.CustomControls.SearchPanels
{
public partial class ViolationSearchPanel : UserControl
{
public event Action HidePanel;
public event Action Search;
public ViolationSearchModel SearchModel { get
{
var dateViolation = dtpViolation.Value;
var dateWasCreated = dtpWasCreated.Value;
var dateWasUpdated = dtpWasUpdate.Value;
var description = tbDescription.Text;
List<CompareValue> compareDate = new List<CompareValue>
{
CompareValue.EQUAL,
CompareValue.MORE,
CompareValue.LESS
};
return new ViolationSearchModel
{
DateFixed = dateViolation.Year != 1990 ?
dateViolation : new DateTime(1, 1, 1),
DateSave = dateWasCreated.Year != 1990 ?
dateWasCreated : new DateTime(1, 1, 1),
DateUpdate = dateWasUpdated.Year != 1990 ?
dateWasUpdated : new DateTime(1, 1, 1),
CompareDateFixed = compareDate[cmbCompareViolation.SelectedIndex],
CompareDateUpdate = compareDate[cmdCompareWasUpdate.SelectedIndex],
CompareDateSave = compareDate[cmbCompareWasCreated.SelectedIndex],
Description = tbDescription.Text.Trim(),
CompareDescription = chbCompareDescription.Checked ? CompareString.EQUAL : CompareString.CONTAINS
};
} set
{
}
}
public ViolationSearchPanel()
{
InitializeComponent();
Clear();
}
private void button1_Click(object sender, EventArgs e)
{
if (HidePanel != null)
HidePanel();
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (Search != null)
Search();
}
public void Clear()
{
dtpViolation.Value = new DateTime(1990, 1, 1);
dtpWasCreated.Value = new DateTime(1990, 1, 1);
dtpWasUpdate.Value = new DateTime(1990, 1, 1);
tbDescription.Text = "";
cmbCompareViolation.SelectedIndex = 0;
cmbCompareWasCreated.SelectedIndex = 0;
cmdCompareWasUpdate.SelectedIndex = 0;
chbCompareDescription.Checked = true;
}
private void btnClearAll_Click(object sender, EventArgs e)
{
Clear();
if (Search != null) Search();
}
}
}
<file_sep>/AppCore/Entities/Protocol.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
public interface IProtocol
{
Protocol Protocol { get; set; }
}
public class Protocol
{
[Key]
public int ProtocolID { get; set; }
[Required(AllowEmptyStrings = false)]
public int ProtocolTypeID { get; set; }
[Required(AllowEmptyStrings = false)]
public DateTime DateCreatedProtocol { get; set; }
public string PlaceCreatedProtocol { get; set; }
public double PlaceCreatedProtocolN { get; set; }
public double PlaceCreatedProtocolE { get; set; }
public string WitnessFIO_1 { get; set; }
public string WitnessLive_1 { get; set; }
public string WitnessFIO_2 { get; set; }
public string WitnessLive_2 { get; set; }
public DateTime DateSave { get; set; }
public DateTime DateUpdate { get; set; }
public int ViolationID { get; set; }
public int EmployerID { get; set; }
}
}
<file_sep>/AppCore/Entities/ViolationImage.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
public class ViolationImage
{
[Key]
public int ViolationImageID { get; set; }
public virtual Violation Violation { get; set; }
public string Name { get; set; }
[Column(TypeName = "image")]
[MaxLength]
public byte[] Image { get; set; }
public virtual AdminViolation AdminViolation { get; set; }
}
}
<file_sep>/AppPresentators/VModels/Protocols/ProtocolViewModel.cs
using AppData.Entities;
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Protocols
{
public class ProtocolViewModel: Protocol
{
public int ProtocolID { get; set; }
/// <summary>
/// Тип протокол
/// </summary>
public int ProtocolTypeID { get; set; }
/// <summary>
/// Название протокола
/// </summary>
public string ProtocolTypeName { get; set; }
/// <summary>
/// Сотрудник, составивший протокол
/// </summary>
public EmploeyrViewModel Employer { get; set; }
public DateTime DateCreatedProtocol { get; set; }
public string PlaceCreatedProtocol { get; set; }
public double PlaceCreatedProtocolN { get; set; }
public double PlaceCreatedProtocolE { get; set; }
public string WitnessFIO_1 { get; set; }
public string WitnessLive_1 { get; set; }
public string WitnessFIO_2 { get; set; }
public string WitnessLive_2 { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/SearchPanels/DocumentSearchPanel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels.Persons;
using AppPresentators.VModels;
namespace LeoBase.Components.CustomControls.SearchPanels
{
public partial class DocumentSearchPanel : UserControl
{
public DocumentSearchModel DocumentSearchModel
{
get
{
return new DocumentSearchModel
{
//DocumentTypeName = cmbDocumentType.Items[cmbDocumentType.SelectedIndex].ToString() != null ?
// cmbDocumentType.Items[cmbDocumentType.SelectedIndex].ToString() :
// "",
Serial = tbDocumentSerial.Text.Trim(),
Number = tbDocumentNumber.Text.Trim(),
CompareWhenIssued = cmbWhenIssuedBy.Items[cmbWhenIssuedBy.SelectedIndex] == null ? CompareValue.EQUAL :
cmbWhenIssuedBy.Items[cmbWhenIssuedBy.SelectedIndex].ToString().Equals("Больше") ? CompareValue.MORE :
cmbWhenIssuedBy.Items[cmbWhenIssuedBy.SelectedIndex].ToString().Equals("Меньше") ? CompareValue.LESS :
CompareValue.EQUAL,
WhenIssued = dtpWhenIssued.Value.Year == 1900 ? new DateTime(1, 1, 1, 0, 0, 0) :
dtpWhenIssued.Value,
IssuedBy = tbIssuedBy.Text.Trim(),
CompareIssuedBy = chbIssuedBy.Checked ? CompareString.EQUAL : CompareString.CONTAINS,
CodeDevision = tbCodeDevision.Text.Trim()
};
}
}
public DocumentSearchPanel()
{
InitializeComponent();
cmbWhenIssuedBy.SelectedIndex = 0;
cmbDocumentType.SelectedIndex = 0;
}
public void Clear()
{
cmbDocumentType.SelectedIndex = 0;
tbDocumentSerial.Text = "";
tbDocumentNumber.Text = "";
tbIssuedBy.Text = "";
dtpWhenIssued.Value = new DateTime(1900, 1, 1);
cmbWhenIssuedBy.SelectedIndex = 0;
tbCodeDevision.Text = "";
}
private void btnClearDocument_Click(object sender, EventArgs e)
{
Clear();
}
}
}
<file_sep>/LeoBase/Components/CustomControls/Interfaces/ISearchPanel.cs
using LeoBase.Components.CustomControls.SearchPanels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls.Interfaces
{
public interface ISearchPanel
{
event Action OnSearchClick;
event Action OnHideClick;
void SetCustomSearchPanel(IClearable control);
Control Control { get; }
bool SearchButtonVisible { get; set; }
}
}
<file_sep>/AppPresentators/Components/IPassDetailsControl.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public interface IPassDetailsControl:UIComponent
{
Pass Pass { get; set; }
event Action MakeReport;
}
}
<file_sep>/AppPresentators/VModels/MSquare.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public class MSquare
{
public MPoint Point1 { get; set; }
public MPoint Point2 { get; set; }
}
}
<file_sep>/AppPresentators/Presentators/EmploerDetailsPresentator.cs
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using System.Windows.Forms;
using AppPresentators.Components;
using AppData.Contexts;
using AppPresentators.Services;
using AppPresentators.VModels.Persons;
namespace AppPresentators.Presentators
{
public interface IEmployerDetailsPresentator : IComponentPresentator
{
EmployerDetailsModel Employer { get; set; }
}
public class EmploerDetailsPresentator : IEmployerDetailsPresentator
{
private IEmployerDetailsControl _control;
private IApplicationFactory _appFactory;
public EmployerDetailsModel Employer
{
get
{
return _control.Employer;
}
set
{
_control.Employer = value;
}
}
public ResultTypes ResultType { get; set; }
public bool ShowFastSearch
{
get
{
return false;
}
}
public bool ShowForResult { get; set; }
public bool ShowSearch
{
get
{
return false;
}
}
public List<Control> TopControls
{
get
{
return _control.TopControls;
}
}
public event SendResult SendResult;
public void FastSearch(string message)
{
}
public Control RenderControl()
{
return _control.GetControl();
}
public void SetResult(ResultTypes resultType, object data)
{
//if (resultType != ResultTypes.UPDATE_PERSONE)
//{
// return;
//}
var service = _appFactory.GetService<IPersonesService>();
var personeModel = service.GetPerson(Employer.EmployerID, true);
var ee = personeModel as EmploeyrViewModel;
if (ee == null) return;
EmployerDetailsModel employer = new EmployerDetailsModel
{
FIO = personeModel.FirstName + " " + personeModel.SecondName + " " + personeModel.MiddleName,
DateBerth = personeModel.DateBirthday.ToShortDateString(),
Position = ee.Position,
PlaceBerth = personeModel.PlaceOfBirth,
EmployerID = personeModel.UserID
};
using (var db = new LeoBaseContext())
{
var searchForImage = db.Persones.FirstOrDefault(p => p.UserID == personeModel.UserID);
if (searchForImage != null)
{
employer.Image = searchForImage.Image;
}
employer.Addresses = new List<PersonAddressModelView>();
var addresses = db.Addresses.Where(a => a.Persone.UserID == ee.UserID);
if (addresses != null)
{
foreach (var a in addresses)
{
employer.Addresses.Add(new PersonAddressModelView
{
AddressID = a.AddressID,
Area = a.Area,
City = a.City,
Country = a.Country,
Flat = a.Flat,
HomeNumber = a.HomeNumber,
Note = a.Note,
Street = a.Street,
Subject = a.Subject
});
}
}
employer.Phones = new List<PhoneViewModel>();
var phones = db.Phones.Where(p => p.Persone.UserID == personeModel.UserID);
if (phones != null)
{
foreach (var p in phones)
{
employer.Phones.Add(new PhoneViewModel
{
PhoneID = p.PhoneID,
PhoneNumber = p.PhoneNumber
});
}
}
employer.Violations = new List<AdminViolationRowModel>();
var violations = db.AdminViolations.Include("Employer").Include("ViolatorPersone").Where(v => v.Employer.UserID == ee.UserID);
foreach (var v in violations)
{
var row = new AdminViolationRowModel();
if (v.ViolatorOrganisation != null)
{
row.ViolatorInfo = string.Format("Юридическое лицо: {0}", v.ViolatorOrganisation.Name);
}
else
{
row.ViolatorInfo = string.Format("{0} {1} {2}", v.ViolatorPersone.FirstName, v.ViolatorPersone.SecondName, v.ViolatorPersone.MiddleName);
}
row.EmployerInfo = string.Format("{0} {1} {2}", v.Employer.FirstName, v.Employer.SecondName, v.Employer.MiddleName);
row.Coordinates = string.Format("{0}; {1}", Math.Round(v.ViolationN, 8), Math.Round(v.ViolationE, 8));
row.Consideration = v.Consideration;
row.DatePaymant = v.WasPaymant ? v.DatePaymant.ToShortDateString() : "";
row.DateSentBailiff = v.WasSentBailiff ? v.DateSentBailiff.ToShortDateString() : "";
row.InformationAbout2025 = v.WasAgenda2025 ? v.DateAgenda2025.ToShortDateString() : "";
row.InformationAboutNotice = v.WasNotice ? v.DateNotice.ToShortDateString() : "";
row.InformationAboutSending = v.GotPersonaly ? "Получил лично"
: v.WasSent
? v.DateSent.ToShortDateString()
: "";
row.SumRecovery = v.SumRecovery;
row.SumViolation = v.SumViolation;
row.Violation = v.Violation;
row.ViolationID = v.ViolationID;
employer.Violations.Add(row);
}
}
Employer = employer;
}
public EmploerDetailsPresentator(IApplicationFactory appFactory)
{
_appFactory = appFactory;
_control = _appFactory.GetComponent<IEmployerDetailsControl>();
_control.ShowViolationDetails += ShowViolationDetails;
_control.EditEmployer += EditEmployer;
}
private void EditEmployer()
{
var service = _appFactory.GetService<IPersonesService>();
var persone = service.GetPerson(Employer.EmployerID, true);
var mainPresentator = _appFactory.GetMainPresentator();
var saveEmployerPresentator = _appFactory.GetPresentator<ISaveEmployerPresentator>();
saveEmployerPresentator.Persone = persone;
mainPresentator.ShowComponentForResult(this, saveEmployerPresentator, ResultTypes.UPDATE_PERSONE);
}
private void ShowViolationDetails(int id)
{
var mainPresentator = _appFactory.GetMainPresentator();
var detailsViolatorPresentator = _appFactory.GetPresentator<IViolationDetailsPresentator>();
using (var db = new LeoBaseContext())
{
detailsViolatorPresentator.Violation = db.AdminViolations.Include("Employer")
.Include("ViolatorOrganisation")
.Include("ViolatorPersone")
.Include("ViolatorDocument")
.Include("Images")
.FirstOrDefault(v => v.ViolationID == id);
}
mainPresentator.ShowComponentForResult(this, detailsViolatorPresentator, ResultTypes.DETAILS_VIOLATION);
}
}
}
<file_sep>/AppCore/Abstract/Protocols/IRulingForViolationRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract.Protocols
{
public interface IRulingForViolationRepository
{
IQueryable<RulingForViolation> RulingsForViolation { get; }
}
}
<file_sep>/AppPresentators/VModels/EmployerDetailsModel.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public class EmployerDetailsModel
{
public int EmployerID { get; set; }
public string FIO { get; set; }
public string Position { get; set; }
public string DateBerth { get; set; }
public string PlaceBerth { get; set; }
public byte[] Image { get; set; }
public List<PersonAddressModelView> Addresses { get; set; }
public List<PhoneViewModel> Phones { get; set; }
public List<AdminViolationRowModel> Violations { get; set; }
}
}
<file_sep>/AppPresentators/Components/ISaveOrUpdateViolationControl.cs
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppPresentators.Components
{
public delegate void AddNewProtocol(int id);
public interface ISaveOrUpdateViolationControl:UIComponent
{
event Action Save;
event Action FindEmplyer;
event Action FindViolator;
event Action FindRulingCreator;
ViolationViewModel Violation { get; set; }
void AddProtocol(Control control);
void RemoveProtocol(Control control);
DialogResult ShowDialog(string title, string message);
}
}
<file_sep>/FormControls/Form1.cs
using FormControls.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormControls
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
LeoDataGridView table = new LeoDataGridView();
table.Dock = DockStyle.Fill;
List<TestDataModel> testData = new List<TestDataModel>();
for (int i = 0; i < 30; i++)
testData.Add(new TestDataModel
{
Key = i,
Name = "Имя " + i,
DateBerthday = new DateTime(1980 + i, 1, i + 1),
SelectedSex = i % 2 == 0 ? "Муж" : "Жен"
});
table.SetData<TestDataModel>(testData);
this.Controls.Add(table);
}
}
}
<file_sep>/AppCore/Repositrys/Violations/EmployersRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations
{
public class EmployersRepository : IEmployerRepository
{
public IQueryable<Employer> Employers
{
get
{
var db = new LeoBaseContext();
return db.Employers;
}
}
public int SaveEmployer(Employer employer)
{
using(var db = new LeoBaseContext())
{
db.Employers.Add(employer);
db.SaveChanges();
return employer.EmployerID;
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/CustomDataTable.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using AppPresentators.VModels;
namespace LeoBase.Components.CustomControls
{
public partial class CustomDataTable: UserControl
{
private TableLayoutPanel _tableLayoutPanel;
public event OnSelecteItemChanged OnSeleceItemChanged;
private object _dataContext;
public event HeadItemClick Order;
public event GenerateRow OnRowGenerated;
public void SetData<T>(List<T> data)
{
if (data == null) throw new ArgumentNullException();
MakeTable<T>(data.Count);
_dataContext = data;
foreach(var item in data)
{
var row = new CustomDataTableRow(item, _headTitles);
// Добавление контролов
row.MouseMove += Row_MouseMove;
row.MouseLeave += Row_MouseLeave;
row.OnComboChanged += Row_OnComboChanged;
row.MouseClick += Row_MouseClick;
row.OnRowGenerated += Row_OnRowGenerated;
row.MakeControls();
foreach (var control in row.Controls)
{
_tableLayoutPanel.Controls.Add(control);
}
}
}
private void Row_OnRowGenerated(CustomDataTableRow item)
{
if (OnRowGenerated != null) OnRowGenerated(item);
}
private CustomDataTableRow _selectedItem;
private void Row_MouseClick(CustomDataTableRow sender)
{
if(_selectedItem == sender)
{
_selectedItem = null;
sender.BackgroundColor = sender.DefaultBackgroundColor;
if (OnSeleceItemChanged != null) OnSeleceItemChanged(null);
}
if (_selectedItem != null) _selectedItem.BackgroundColor = sender.OnActiveColor;
_selectedItem = sender;
sender.BackgroundColor = sender.OnActiveColor;
if (OnSeleceItemChanged != null) OnSeleceItemChanged(sender);
}
private void Row_OnComboChanged(CustomDataTableRow parent, ComboBox sender, string columnName)
{
MessageBox.Show(string.Format("Значение для поля {0} было изменено на {1}", columnName, sender.SelectedValue));
}
private void Row_MouseLeave(CustomDataTableRow sender)
{
if(sender != _selectedItem)
sender.BackgroundColor = sender.DefaultBackgroundColor;
}
private void Row_MouseMove(CustomDataTableRow sender)
{
if (sender != _selectedItem)
sender.BackgroundColor = sender.OnMouseMoveColor;
}
private List<HeadPanel> _headers;
private void MakeTable<T>(int rows)
{
SetDataType<T>();
var browsebleHead = _headTitles.Where(h => h.Show);
int columns = browsebleHead != null ? browsebleHead.Count() : 0;
//_tableLayoutPanel = new TableLayoutPanel();
_tableLayoutPanel.Controls.Clear();
_tableLayoutPanel.ColumnCount = columns;
_tableLayoutPanel.RowCount = rows + 1;
_tableLayoutPanel.SuspendLayout();
_tableLayoutPanel.Controls.Clear();
_tableLayoutPanel.GrowStyle = TableLayoutPanelGrowStyle.FixedSize;
_tableLayoutPanel.ColumnStyles.Clear();
for (int i = 0; i < _tableLayoutPanel.ColumnCount; i++)
{
ColumnStyle cs = new ColumnStyle(SizeType.Percent, 100 / _tableLayoutPanel.ColumnCount);
_tableLayoutPanel.ColumnStyles.Add(cs);
}
for (int i = 0; i < _tableLayoutPanel.RowCount; i++)
{
RowStyle rs = null;
if (i == 0)
rs = new RowStyle(SizeType.Absolute, 22);
else
rs = new RowStyle(SizeType.Absolute, 30);
_tableLayoutPanel.RowStyles.Add(rs);
}
_tableLayoutPanel.ResumeLayout();
_headers = new List<HeadPanel>();
foreach (var title in _headTitles)
{
if (title.Show) {
HeadPanel head = new HeadPanel(title);
//Label headButton = new Label();
//headButton.Padding = new Padding(3, 3, 3, 3);
//headButton.Margin = new Padding(0, 0, 0, 0);
//headButton.BorderStyle = BorderStyle.FixedSingle;
//headButton.TextAlign = ContentAlignment.MiddleCenter;
//headButton.Text = !string.IsNullOrEmpty(title.DisplayText) ? title.DisplayText : title.HeadName;
//headButton.Dock = DockStyle.Fill;
//headButton.Text = title.DisplayText;
head.Order += Head_Order;
_tableLayoutPanel.Controls.Add(head);
_headers.Add(head);
}
}
}
private void Head_Order(TableHeaderItem item, TableOrderType orderType)
{
foreach(var i in _headers)
{
if(i.HeadItem != item)
{
i.OrderType = TableOrderType.NONE;
}
}
if (Order != null) Order(item, orderType);
}
private List<TableHeaderItem> _headTitles;
public void SetDataType(Type type) {
_headTitles = new List<TableHeaderItem>();
foreach (var title in type.GetProperties()) {
bool showInHead = true;
TableHeaderItem item = new TableHeaderItem();
foreach (var attribute in title.GetCustomAttributesData()) {
if (attribute.AttributeType.Name.Equals("BrowsableAttribute")) {
showInHead = title.GetCustomAttribute<BrowsableAttribute>().Browsable;
}
else if(attribute.AttributeType.Name.Equals("DisplayNameAttribute"))
{
item.DisplayText = title.GetCustomAttribute<DisplayNameAttribute>().DisplayName;
}
}
item.HeadName = title.Name;
item.CellType = title.PropertyType.Name;
item.Show = showInHead;
_headTitles.Add(item);
}
}
public void SetDataType<T>()
{
SetDataType(typeof(T));
}
public CustomDataTable()
{
InitializeComponent();
this.Dock = DockStyle.Fill;
_tableLayoutPanel = new TableLayoutPanel();
_tableLayoutPanel.Dock = DockStyle.Top;
_tableLayoutPanel.AutoSize = true;
Label padgination = new Label();
padgination.Text = "Test";
padgination.Dock = DockStyle.Top;
this.Controls.Add(padgination);
Controls.Add(_tableLayoutPanel);
}
}
public enum CustomDataTableRowMouseEventType
{
MouseLeave,
MouseMove,
MouseHover,
MouseClick,
MouseDoubleClick
}
public delegate void CustomDataTableRowMouseEvent(CustomDataTableRow sender);
public delegate void CustomDataTableRowComboBoxEvent(CustomDataTableRow parent, ComboBox sender, string columnName);
public delegate void GenerateRow(CustomDataTableRow item);
public delegate void OnSelecteItemChanged(CustomDataTableRow item);
public class CustomDataTableRow
{
private List<Control> _controls;
public object Item { get; set; }
public List<TableHeaderItem> Metadata { get; private set; }
public event CustomDataTableRowMouseEvent MouseLeave;
public event CustomDataTableRowMouseEvent MouseMove;
public event CustomDataTableRowMouseEvent MouseHover;
public event CustomDataTableRowMouseEvent MouseClick;
public event CustomDataTableRowMouseEvent MouseDoubleClick;
public event CustomDataTableRowComboBoxEvent OnComboChanged;
public event GenerateRow OnRowGenerated;
public Color OnMouseMoveColor { get; set; } = Color.DarkGray;
public Color OnActiveColor { get; set; } = Color.LightGray;
public Color DefaultBackgroundColor { get; set; } = Color.White;
public Color _backgroundColor { get; set; } = Color.White;
public Color BackgroundColor
{
get
{
return _backgroundColor;
}
set
{
_backgroundColor = value;
foreach(var control in _controls)
{
control.BackColor = _backgroundColor;
}
}
}
public List<Control> Controls
{
get
{
return _controls;
}
set
{
_controls = value;
}
}
public CustomDataTableRow(object item, List<TableHeaderItem> metaData) {
Metadata = metaData;
Item = item;
}
public void MakeControls()
{
_controls = new List<Control>();
foreach (var metaData in Metadata)
{
if (!metaData.Show) continue;
var info = Item.GetType().GetProperty(metaData.HeadName);
if (info == null) continue;
if (metaData.CellType.ToLower() == "decimal" || metaData.CellType.ToLower() == "string")
{
string title = info.GetValue(Item).ToString();
Label label = new Label();
label.Text = title;
AddEvents(label);
_controls.Add(label);
}
else if(metaData.CellType.ToLower() == "cellcomboboxvalues")
{
var data = (CellComboBoxValues)info.GetValue(Item);
ComboBox combo = new ComboBox();
combo.DropDownStyle = ComboBoxStyle.DropDownList;
combo.DataSource = data;
combo.SelectedText = data.SelectedText;
combo.MouseMove += (s, e) =>
{
if (MouseMove != null) MouseMove(this);
};
combo.MouseHover += (s, e) =>
{
if (MouseHover != null) MouseHover(this);
};
combo.MouseLeave += (s, e) =>
{
if (MouseLeave != null) MouseLeave(this);
};
combo.SelectedValueChanged += (s, e) =>
{
if (OnComboChanged != null) OnComboChanged(this, combo, metaData.HeadName);
};
_controls.Add(combo);
}
}
foreach (var control in _controls) {
control.Cursor = Cursors.Hand;
control.Dock = DockStyle.Fill;
control.Padding = new Padding(0, 0, 0, 0);
control.Margin = new Padding(0, 0, 0, 0);
}
if (OnRowGenerated != null) OnRowGenerated(this);
}
private void AddEvents(Control control)
{
control.MouseClick += (s, e) =>
{
if (MouseClick != null) MouseClick(this);
};
control.MouseMove += (s, e) =>
{
if (MouseMove != null) MouseMove(this);
};
control.DoubleClick += (s, e) =>
{
if (MouseDoubleClick != null) MouseDoubleClick(this);
};
control.MouseHover += (s, e) =>
{
if (MouseHover != null) MouseHover(this);
};
control.MouseLeave += (s, e) =>
{
if (MouseLeave != null) MouseLeave(this);
};
}
}
public delegate void HeadItemClick(TableHeaderItem item, TableOrderType orderType);
public class HeadPanel:Panel
{
public event HeadItemClick Order;
private TableOrderType _orderType = TableOrderType.NONE;
public TableOrderType OrderType
{
get
{
return _orderType;
}
set
{
switch (value)
{
case TableOrderType.ASC:
_orderImage.Image = Properties.Resources.OrderAsc;
break;
case TableOrderType.DESC:
_orderImage.Image = Properties.Resources.OrderDesc;
break;
case TableOrderType.NONE:
_orderImage.Image = null;
break;
}
_orderType = value;
/// Изменяем изображение
}
}
public string Title
{
get
{
return _title.Text;
}
set
{
_title.Text = value;
}
}
private Label _title;
public TableHeaderItem HeadItem;
private PictureBox _orderImage;
public HeadPanel(TableHeaderItem item)
{
HeadItem = item;
this.AutoSize = true;
this.Margin = new Padding(0, 0, 0, 0);
this.Padding = new Padding(10, 3, 10, 3);
this.Cursor = Cursors.Hand;
this.BorderStyle = BorderStyle.FixedSingle;
_title = new Label();
_title.Text = item.DisplayText ?? item.HeadName;
_title.AutoSize = true;
this.Controls.Add(_title);
this.Dock = DockStyle.Fill;
_orderImage = new PictureBox();
_orderImage.Dock = DockStyle.Right;
_title.Dock = DockStyle.Left;
this.Controls.Add(_orderImage);
_title.Click += HeadPanel_Click;
this.Click += HeadPanel_Click;
_orderImage.Click += HeadPanel_Click;
// Добавить изображение сортировки
}
private void HeadPanel_Click(object sender, EventArgs e)
{
if (OrderType == TableOrderType.NONE) OrderType = TableOrderType.ASC;
else if (OrderType == TableOrderType.ASC) OrderType = TableOrderType.DESC;
else if (OrderType == TableOrderType.DESC) OrderType = TableOrderType.ASC;
if (Order != null) Order(HeadItem, _orderType);
}
}
public enum TableOrderType
{
DESC,
ASC,
NONE
}
public class TableHeaderItem
{
public string DisplayText { get; set; }
public string HeadName { get; set; }
public string CellType { get; set; }
public bool Show { get; set; }
}
}
<file_sep>/LeoMapV2/Models/ZoomInformation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoMapV2.Models
{
public class ZoomInformation
{
public int MaxX { get; set; }
public int MaxY { get; set; }
public int Zoom { get; set; }
public double E { get; set; }
public double W { get; set; }
public double N { get; set; }
public double S { get; set; }
public int TitleWidth { get; set; }
public int TitleHeight { get; set; }
}
}
<file_sep>/LeoMapV3/Data/TitleDBRepository.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LeoMapV3.Models;
using System.Runtime.Caching;
using System.Data.SQLite;
using System.Data.Common;
using System.IO;
namespace LeoMapV3.Data
{
public class TitleDBRepository : ITitlesRepository
{
private string _mapPath;
private MemoryCache _cache;
private List<string> _cacheKeys;
private static Dictionary<int, List<TitleCacheModel>> _titles = null;
private static Dictionary<int, ZoomInformation> _zoomInformation = null;
public TitleDBRepository(string dbFilePath)
{
_mapPath = dbFilePath;
_cacheKeys = new List<string>();
if(_titles == null)
{
LoadTitles();
}
// Загрузка начальных данных, скорей всего потребуется загрузить все тайтлы без изображений, для более быстрого доступа к ним по ID
// для этого имеет смысл создать статичное приватное поле в этом классе, в которое будем записывать все тайтлы
// чтобы при последующем обращение к карте не тянуть лишнюю информацию из базы.
}
private void LoadTitles()
{
_titles = new Dictionary<int, List<TitleCacheModel>>();
string query = "select id, x, y, z, n, e, w, s from 'titles'";
SQLiteFactory factory = (SQLiteFactory)DbProviderFactories.GetFactory("System.Data.SQLite");
using (SQLiteConnection connection = (SQLiteConnection)factory.CreateConnection())
{
connection.ConnectionString = "Data Source=" + _mapPath;
connection.Open();
using (var cmd = new SQLiteCommand(query, connection))
{
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
var title = new TitleCacheModel();
title.ID = rdr.GetInt32(0);
title.X = rdr.GetInt32(1);
title.Y = rdr.GetInt32(2);
title.Z = rdr.GetInt32(3);
title.N = rdr.GetDouble(4);
title.E = rdr.GetDouble(5);
title.W = rdr.GetDouble(6);
title.S = rdr.GetDouble(7);
if (!_titles.ContainsKey(title.Z)) _titles.Add(title.Z, new List<TitleCacheModel>());
_titles[title.Z].Add(title);
}
}
}
connection.Close();
}
}
public Point ConvertMapCoordsToPixels(DPoint point)
{
if (_titles == null) LoadTitles();
if (!_titles.ContainsKey(point.Zoom)) throw new ArgumentException("Зум указан неверно!");
var title = _titles[point.Zoom].FirstOrDefault(t => t.E >= point.E && t.W <= point.E && t.N >= point.N && t.S <= point.N);
if (title == null) return new Point(-1, -1);
int x = title.X * GetZoomInformation(point.Zoom).TitleWidth;
int y = title.Y * GetZoomInformation(point.Zoom).TitleHeight;
x += (int)Math.Round(GetZoomInformation(point.Zoom).TitleWidth * (point.E- title.W) / (title.E - title.W));
y += GetZoomInformation(point.Zoom).TitleHeight - (int)Math.Round(GetZoomInformation(point.Zoom).TitleHeight * (point.N - title.S) / (title.N - title.S));
return new Point(x, y);
}
public DPoint ConvertPixelsToMapCoords(int x, int y, int z)
{
var zInf = GetZoomInformation(z);
if (zInf == null) throw new ArgumentException("Указанный зум не найден!");
if (_titles == null) LoadTitles();
if (!_titles.ContainsKey(z)) throw new ArgumentException("Указанный зум не найден!");
int titleX = (x - x % zInf.TitleWidth) / zInf.TitleWidth;
int titleY = (y - y % zInf.TitleHeight) / zInf.TitleHeight;
var title = _titles[z].FirstOrDefault(t => t.X == titleX && t.Y == titleY);
if (title == null) return null;
DPoint result = new DPoint();
double dE = title.E - title.W;
double dN = title.N - title.S;
double dX = (double)(x % zInf.TitleWidth) / (double)zInf.TitleWidth;
double dY = 1 - (double)(y % zInf.TitleHeight) / (double)zInf.TitleHeight;
result.N = title.S + dN * dY;
result.E = title.W + dE * dX;
result.Zoom = z;
return result;
}
public TitleMapModel GetTitle(int x, int y, int z)
{
if (_cache == null) _cache = MemoryCache.Default;
string cacheKey = "img_" + x + "_" + y + "_" + z;
if (_cache.Contains(cacheKey)) return (TitleMapModel)_cache[cacheKey];
if (_titles == null) LoadTitles();
if (!_titles.ContainsKey(z)) return null;
var title = _titles[z].FirstOrDefault(t => t.X == x && t.Y == y);
if (title == null) return null;
TitleMapModel result = new TitleMapModel();
string query = "select n, s, e, w, i from 'titles' where id=" + title.ID;
SQLiteFactory factory = (SQLiteFactory)DbProviderFactories.GetFactory("System.Data.SQLite");
using (SQLiteConnection connection = (SQLiteConnection)factory.CreateConnection())
{
connection.ConnectionString = "Data Source=" + _mapPath;
connection.Open();
using (var cmd = new SQLiteCommand(query, connection))
{
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
result.N = rdr.GetDouble(0);
result.S = rdr.GetDouble(1);
result.E = rdr.GetDouble(2);
result.W = rdr.GetDouble(3);
result.Image = CellToImage(rdr["i"]);
}
}
}
connection.Close();
}
_cache.Add(cacheKey, result, DateTime.Now.AddMinutes(5));
_cacheKeys.Add(cacheKey);
return result;
}
public ZoomInformation GetZoomInformation(int z)
{
if (_zoomInformation != null && _zoomInformation.ContainsKey(z)) return _zoomInformation[z];
if (_cache == null) _cache = MemoryCache.Default;
if (_cache.Contains("zInf_" + z)) return (ZoomInformation)_cache["zInf_" + z];
if (_titles == null) LoadTitles();
ZoomInformation result = new ZoomInformation();
result.MaxX = _titles[z].Max(t => t.X);
result.MaxY = _titles[z].Max(t => t.Y);
result.Zoom = z;
SQLiteFactory factory = (SQLiteFactory)DbProviderFactories.GetFactory("System.Data.SQLite");
using (SQLiteConnection connection = (SQLiteConnection)factory.CreateConnection())
{
connection.ConnectionString = "Data Source=" + _mapPath;
connection.Open();
var ft = _titles[z].First();
int id = ft != null ? ft.ID : 0;
string query = "select i from 'titles' where id = " + id;
using (var cmd = new SQLiteCommand(query, connection))
{
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
var img = CellToImage(rdr["i"]);
result.TitleWidth = img.Width;
result.TitleHeight = img.Height;
}
}
}
query = "select max(n) from 'titles' where z=" + result.Zoom;
using (var cmd = new SQLiteCommand(query, connection))
{
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
result.N = rdr.GetDouble(0);
}
}
}
query = "select max(e) from 'titles' where z=" + result.Zoom;
using (var cmd = new SQLiteCommand(query, connection))
{
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
result.E = rdr.GetDouble(0);
}
}
}
query = "select min(s) from 'titles' where z=" + result.Zoom;
using (var cmd = new SQLiteCommand(query, connection))
{
using(var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
result.S = rdr.GetDouble(0);
}
}
}
query = "select min(w) from 'titles' where z=" + result.Zoom;
using(var cmd = new SQLiteCommand(query, connection))
{
using(var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
result.W = rdr.GetDouble(0);
}
}
}
connection.Close();
}
_cache.Add("zInf_" + z, result, DateTime.Now.AddMinutes(10));
_cacheKeys.Add("zIng_" + z);
return result;
}
public Dictionary<int, ZoomInformation> GetZoomsInformation()
{
if (_zoomInformation != null) return _zoomInformation;
_zoomInformation = new Dictionary<int, ZoomInformation>();
var zooms = GetZooms();
foreach(var zoom in zooms)
{
_zoomInformation.Add(zoom, GetZoomInformation(zoom));
}
return _zoomInformation;
}
public List<int> GetZooms()
{
if (_cache == null) _cache = MemoryCache.Default;
if (_cache.Contains("zooms")) return (List<int>)_cache["zooms"];
string query = "select distinct z from 'titles'";
List<int> result = new List<int>();
SQLiteFactory factory = (SQLiteFactory)DbProviderFactories.GetFactory("System.Data.SQLite");
using (SQLiteConnection connection = (SQLiteConnection)factory.CreateConnection())
{
connection.ConnectionString = "Data Source=" + _mapPath;
connection.Open();
using (var cmd = new SQLiteCommand(query, connection))
{
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
result.Add(rdr.GetInt32(0));
}
}
}
connection.Close();
}
_cache.Add("zooms", result, new DateTimeOffset(DateTime.Now.AddMinutes(10)));
_cacheKeys.Add("zooms");
return result;
}
public void ClearCache()
{
if (_cache == null) _cache = MemoryCache.Default;
if (_cacheKeys == null || _cacheKeys.Count == 0)
{
_cacheKeys = new List<string>();
foreach (var key in _cache)
{
_cacheKeys.Add(key.Key);
}
}
foreach (var key in _cacheKeys) _cache.Remove(key);
_cacheKeys.Clear();
}
private Image CellToImage(object data)
{
return ByteArrayToImage((byte[])data);
}
private Image ByteArrayToImage(byte[] byteArrayIn)
{
using (var ms = new MemoryStream(byteArrayIn))
{
return Image.FromStream(ms);
}
}
}
}
<file_sep>/AppPresentators/Presentators/AdminViolationTablePresentator.cs
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.Services;
using AppPresentators.Views;
using System.ComponentModel;
using AppPresentators.VModels;
using System.Threading;
using AppData.Contexts;
using AppPresentators.Infrastructure.Orders;
namespace AppPresentators.Presentators
{
public class AdminViolationTablePresentator : IAdminViolationTablePresentator, IOrderPage
{
public ResultTypes ResultType { get; set; }
public bool ShowFastSearch
{
get
{
return false;
}
}
public bool ShowForResult { get; set; }
public bool ShowSearch
{
get
{
return true;
}
}
public List<Control> TopControls
{
get
{
return _view.TopControls;
}
}
public Infrastructure.Orders.OrderType OrderType
{
get
{
return Infrastructure.Orders.OrderType.TABLE;
}
}
private string _orderDirPath;
public string OrderDirPath
{
get
{
return _orderDirPath;
}
}
public event SendResult SendResult;
private IApplicationFactory _appFactory;
private IAdminViolationControl _view;
private IAdminViolationService _service;
private IMainView _mainView;
private BackgroundWorker _pageLoader;
public AdminViolationTablePresentator(IMainView mainView, IApplicationFactory appFactory)
{
_appFactory = appFactory;
_view = _appFactory.GetComponent<IAdminViolationControl>();
_service = _appFactory.GetService<IAdminViolationService>();
_pageLoader = new BackgroundWorker();
_pageLoader.DoWork += PageLoading;
_pageLoader.RunWorkerCompleted += PageLoaded;
_mainView = mainView;
_view.AddViolation += AddViolation;
_view.EditViolation += EditViolation;
_view.ShowDetailsViolation += ShowDetaiolsForViolation;
_view.RemoveViolation += RemoveViolation;
_view.BuildReport += BuildReport;
_view.UpdateTable += () => UpdateData(_view.OrederModel, _view.SearchModel, _view.PageModel);
}
private static PageModel _page;
private static AdminViolationSearchModel _search;
private static AdminViolationOrderModel _order;
private void BuildReport()
{
var mainView = _appFactory.GetMainView();
_page = _view.PageModel;
_search = _view.SearchModel;
_order = _view.OrederModel;
mainView.MakeOrder(this);
}
private void PageLoaded(object sender, RunWorkerCompletedEventArgs e)
{
var response = (LoadDataViolationResponseModel)e.Result;
_view.DataContext = response.Data;
_view.PageModel = response.PageModel;
_view.LoadEnd();
}
private void PageLoading(object sender, DoWorkEventArgs e)
{
var requst = (LoadDataViolationRequestModel)e.Argument;
var order = requst.OrderModel;
var search = requst.SearchModel;
var page = requst.PageModel;
var data = _service.GetTableData(page, order, search);
var response = new LoadDataViolationResponseModel();
response.Data = data;
response.PageModel = _service.PageModel;
e.Result = response;
}
private void RemoveViolation(int id)
{
_service.RemoveViolation(id);
Update();
}
private void ShowDetaiolsForViolation(int id)
{
var mainPresentator = _appFactory.GetMainPresentator();
var detailsViolatorPresentator = _appFactory.GetPresentator<IViolationDetailsPresentator>();
//var violation = _service.GetViolation(id);
using (var db = new LeoBaseContext())
{
detailsViolatorPresentator.Violation = db.AdminViolations.Include("Employer")
.Include("ViolatorOrganisation")
.Include("ViolatorPersone")
.Include("ViolatorDocument")
.Include("Images")
.FirstOrDefault(v => v.ViolationID == id);
}
mainPresentator.ShowComponentForResult(this, detailsViolatorPresentator, ResultTypes.UPDATE_VIOLATION);
}
private void EditViolation(int id)
{
var mainPresentator = _appFactory.GetMainPresentator();
var saveViolatorPresentator = _appFactory.GetPresentator<ISaveAdminViolationPresentatar>();
//var violation = _service.GetViolation(id);
using(var db = new LeoBaseContext())
{
saveViolatorPresentator.Violation = db.AdminViolations.Include("Employer")
.Include("ViolatorOrganisation")
.Include("ViolatorPersone")
.Include("ViolatorDocument")
.Include("Images")
.FirstOrDefault(v => v.ViolationID == id);
}
mainPresentator.ShowComponentForResult(this, saveViolatorPresentator, ResultTypes.UPDATE_VIOLATION);
}
private void AddViolation()
{
var mainPresentator = _appFactory.GetMainPresentator();
var saveViolatorPresentator = _appFactory.GetPresentator<ISaveAdminViolationPresentatar>();
mainPresentator.ShowComponentForResult(this, saveViolatorPresentator, ResultTypes.ADD_VIOLATION);
}
private void UpdateData()
{
var tableData = _service.GetTableData(_view.PageModel, _view.OrederModel, _view.SearchModel);
_view.DataContext = tableData;
}
private void UpdateData(AdminViolationOrderModel order, AdminViolationSearchModel search, PageModel page)
{
if (_pageLoader.IsBusy) return;
if (page == null)
page = new PageModel
{
ItemsOnPage = 10,
CurentPage = 1
};
var request = new LoadDataViolationRequestModel
{
PageModel = page,
OrderModel = order,
SearchModel = search
};
_view.LoadStart();
_pageLoader.RunWorkerAsync(request);
}
public void FastSearch(string message)
{
var service = new AdminViolationService();
UpdateData(_view.OrederModel, new AdminViolationSearchModel
{
FastSearchString = message
}, _view.PageModel);
}
public Control RenderControl()
{
UpdateData(_view.OrederModel, _view.SearchModel, _view.PageModel);
return _view.GetControl();
}
public void SetResult(ResultTypes resultType, object data)
{
//throw new NotImplementedException();
}
public void Update()
{
UpdateData();
}
public void BuildOrder(IOrderBuilder orderBuilder, OrderConfigs configs)
{
//_view.PageModel, _view.OrederModel, _view.SearchModel
List<AdminViolationRowModel> data = null;// _service.GetTableData(page, order, search);
if (!configs.TableConfig.ConsiderFilter) _search = null;
if (!configs.TableConfig.CurrentPageOnly)
_page = new PageModel()
{
CurentPage = 1,
ItemsOnPage = 1000000
};
data = _service.GetTableData(_page, _order, _search);
string[] headers = new[]
{
"Нарушитель",
"ФИО сотрудника",
"Координаты",
"Рассмотрение",
"Нарушение",
"Дата оплаты",
"Сумма наложения",
"Сумма взыскания",
"Отправление",
"Отправлено судебным приставам",
"Извещение",
"Повестка по статье 20.25"
};
orderBuilder.StartTable("violations table", headers);
foreach (var row in data)
{
string[] cells = new string[headers.Length];
cells[0] = row.ViolatorInfo;
cells[1] = row.EmployerInfo;
cells[2] = row.Coordinates;
cells[3] = row.Consideration.ToShortDateString();
cells[4] = row.Violation;
cells[5] = row.DatePaymant;
cells[6] = row.SumViolation.ToString();
cells[7] = row.SumRecovery.ToString();
cells[8] = row.InformationAboutSending;
cells[9] = row.DateSentBailiff;
cells[10] = row.InformationAboutNotice;
cells[11] = row.InformationAbout2025;
RowColor color = RowColor.DEFAULT;
if (row.SumRecovery == row.SumViolation)
{
color = RowColor.GREEN;
}
else if (row.SumRecovery < row.SumViolation && (DateTime.Now - row.Consideration).Days > 70)
{
color = RowColor.RED;
}
else if ((DateTime.Now - row.Consideration).Days < 70)
{
color = RowColor.YELLOW;
}
orderBuilder.WriteRow(cells, color);
}
orderBuilder.EndTable("violations table");
_orderDirPath = orderBuilder.Save();
}
}
public class LoadDataViolationRequestModel
{
public AdminViolationOrderModel OrderModel { get; set; }
public AdminViolationSearchModel SearchModel { get; set; }
public PageModel PageModel { get; set; }
}
public class LoadDataViolationResponseModel
{
public List<AdminViolationRowModel> Data { get; set; }
public PageModel PageModel { get; set; }
}
}
<file_sep>/FormControls/Controls/Models/LeoDataViewRow.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormControls.Controls.Models
{
public class LeoDataViewRow
{
public List<LeoDataViewCell> Cells { get; set; }
public int RowIndex { get; private set; }
public List<LeoDataViewHeadMetaData> MetaData { get; private set; }
public LeoDataViewRow(object data, List<LeoDataViewHeadMetaData> meta, int index)
{
RowIndex = index;
Cells = new List<LeoDataViewCell>();
MetaData = meta;
foreach(var metaData in MetaData)
{
if (!metaData.Show) continue;
var info = data.GetType().GetProperty(metaData.FieldName);
if (info == null) continue;
Control control = null;
if (metaData.Type != "LeoDataComboBox")
{
string title = info.GetValue(data).ToString();
control = new Label();
control.Text = title;
}else
{
LeoDataComboBox cbData = (LeoDataComboBox)(info.GetValue(data));
control = new ComboBox();
((ComboBox)control).DropDownStyle = ComboBoxStyle.DropDownList;
((ComboBox)control).DataSource = cbData;
((ComboBox)control).SelectedValue = cbData.SelectedValue;
}
AddCell(control);
}
}
public void AddCell(Control control)
{
LeoDataViewCell cell = new LeoDataViewCell();
cell.SetControl(control);
Cells.Add(cell);
}
}
}
<file_sep>/AppCore/Abstract/Protocols/IProtocolAboutBringingRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract.Protocols
{
public interface IProtocolAboutBringingRepository
{
IQueryable<ProtocolAboutBringing> ProtocolsAboutBringing { get; }
int SaveProtocolAboutBringing(ProtocolAboutBringing protocol);
}
}
<file_sep>/AppCore/Entities/Pass.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
public class Pass
{
[Browsable(false)]
[Key]
public int PassID { get; set; }
[DisplayName("Фамилия")]
[ReadOnly(true)]
public string FirstName { get; set; }
[ReadOnly(true)]
[DisplayName("Имя")]
public string SecondName { get; set; }
[ReadOnly(true)]
[DisplayName("Отчество")]
public string MiddleName { get; set; }
[ReadOnly(true)]
[DisplayName("Тип предоставленного документа")]
public string DocumentType { get; set; }
[ReadOnly(true)]
[DisplayName("Серия документа")]
public string Serial { get; set; }
[ReadOnly(true)]
[DisplayName("Номер документа")]
public string Number { get; set; }
[DisplayName("Когда выдан документ")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM.dd.yyyy}")]
[ReadOnly(true)]
public DateTime WhenIssued { get; set; }
[DisplayName("Кем выдан документ")]
[ReadOnly(true)]
public string WhoIssued { get; set; }
[DisplayName("Выдан пропуск")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM.dd.yyyy}")]
[ReadOnly(true)]
public DateTime PassGiven { get; set; }
[DisplayName("Дата закрытия пропуска")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
[DataType(DataType.Date)]
[ReadOnly(true)]
public DateTime PassClosed { get; set; }
}
}
<file_sep>/AppPresentators/Components/Protocols/IProtocolView.cs
using AppPresentators.Infrastructure;
using AppPresentators.VModels.MainMenu;
using AppPresentators.VModels.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppPresentators.Components.Protocols
{
public interface IProtocolView
{
event Action Remove;
ProtocolViewModel Protocol { get; set;}
void SetResult(ResultTypes resultType, object data);
Control GetControl();
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/ComponentPresentators/ISaveEmployerPresentator.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces.ComponentPresentators
{
public interface ISaveEmployerPresentator:IComponentPresentator
{
void SavePersone(IPersoneViewModel employer);
IPersoneViewModel Persone { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/EmployerDetailsControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.VModels;
using LeoBase.Components.TopMenu;
namespace LeoBase.Components.CustomControls.NewControls
{
public partial class EmployerDetailsControl : UserControl, IEmployerDetailsControl
{
public event Action MakeReport;
public event Action EditEmployer;
public EmployerDetailsControl()
{
InitializeComponent();
this.Load += EmployerDetailsControl_Load;
}
private void EmployerDetailsControl_Load(object sender, EventArgs e)
{
tableAddresses.ClearSelection();
tableViolations.ClearSelection();
}
private EmployerDetailsModel _employer;
private int _selectedViolationID = -1;
public EmployerDetailsModel Employer
{
get
{
return _employer;
}
set
{
_employer = value;
if(value != null)
{
UpdateControlData();
}
}
}
public bool ShowForResult { get; set; }
public List<Control> TopControls
{
get
{
var reportButton = new PictureButton(Properties.Resources.reportEnabled, Properties.Resources.reportDisabled, Properties.Resources.reportPress);
var editButton = new PictureButton(Properties.Resources.editEnabled, Properties.Resources.editDisabled, Properties.Resources.editPress);
reportButton.Enabled = true;
editButton.Enabled = true;
reportButton.Click += (s, e) =>
{
if (MakeReport != null) MakeReport();
};
editButton.Click += (s, e) =>
{
if (EditEmployer != null) EditEmployer();
};
return new List<Control> { reportButton, editButton };
}
set
{
}
}
public event Action<int> ShowViolationDetails;
public Control GetControl()
{
return this;
}
void UIComponent.Resize(int width, int height)
{
}
private void UpdateControlData()
{
lbFIO.Text = Employer.FIO;
lbDateBerth.Text = Employer.DateBerth;
if (Employer.Phones != null)
foreach (var p in Employer.Phones)
lbPhones.Text += p.PhoneNumber + "; ";
lbPlaceBerth.Text = Employer.PlaceBerth;
lbPosition.Text = Employer.Position;
if(Employer.Image != null) {
PictureViewer picture = new PictureViewer();
picture.Image = Employer.Image;
picture.Margin = new Padding(10, 10, 10, 10);
picture.Dock = DockStyle.Left;
picture.ShowDeleteButton = false;
picture.ShowZoomButton = false;
picture.CanSelected = false;
avatarPanel.Controls.Clear();
avatarPanel.Controls.Add(picture);
}
tableAddresses.DataSource = Employer.Addresses;
tableViolations.DataSource = Employer.Violations;
tableAddresses.ClearSelection();
tableViolations.ClearSelection();
}
private void tableAddresses_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.RowIndex >= tableAddresses.Rows.Count) return;
tableAddresses.Rows[e.RowIndex].Selected = true;
}
private void tableViolations_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.RowIndex >= tableViolations.Rows.Count) return;
tableViolations.Rows[e.RowIndex].Selected = true;
_selectedViolationID = Employer.Violations[e.RowIndex].ViolationID;
btnViolationDetails.Enabled = true;
}
private void btnViolationDetails_Click(object sender, EventArgs e)
{
if (_selectedViolationID <= 0 || ShowViolationDetails == null) return;
ShowViolationDetails(_selectedViolationID);
}
}
}
<file_sep>/LeoMapV3/Models/TitleMapModel.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoMapV3.Models
{
public class TitleMapModel
{
public Image Image { get; set; }
public double E { get; set; }
public double W { get; set; }
public double S { get; set; }
public double N { get; set; }
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/ComponentPresentators/IEmployersPresentator.cs
using AppPresentators.VModels;
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces.ComponentPresentators
{
public interface IEmployersPresentator:IComponentPresentator
{
void GetPersones(PageModel pageModel,
PersonsSearchModel searchModel,
SearchAddressModel addressSearchModel,
PersonsOrderModel orderModel,
DocumentSearchModel documentSearchModel);
}
}
<file_sep>/FormControls/Controls/Events/LeoDataViewEvents.cs
using FormControls.Controls.Enums;
using FormControls.Controls.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormControls.Controls.Events
{
public delegate void TableOrderEvent(HeadTitle sender, OrderTypes type);
public delegate void LeoTableResizeEvent(HeadTitle sender, bool resized);
public delegate void HeaderMouseMove(HeadTitle sender, MouseEventArgs e);
}
<file_sep>/AppPresentators/Components/IEmployerDetailsControl.cs
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public interface IEmployerDetailsControl : UIComponent
{
event Action MakeReport;
event Action EditEmployer;
EmployerDetailsModel Employer { get; set; }
event Action<int> ShowViolationDetails;
}
}
<file_sep>/AppPresentators/Presentators/SavePersonPresentator.cs
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.VModels.Persons;
using System.Windows.Forms;
using AppPresentators.Infrastructure;
using AppPresentators.Components;
using AppPresentators.Services;
using AppData.Infrastructure;
using AppData.Abstract;
using AppData.Entities;
namespace AppPresentators.Presentators
{
public class SavePersonPresentator : ISaveEmployerPresentator
{
private IApplicationFactory _appFactory;
private ISavePersonControl _control;
public bool ShowForResult { get; set; }
public ResultTypes ResultType { get; set; }
public void SetResult(ResultTypes resultType, object data)
{
// Может быть гдето понадобиться вызывать окно для возврата значений
}
public List<Control> TopControls
{
get
{
return _control.TopControls;
}
}
public event SendResult SendResult;
public IPersoneViewModel Persone {
get {
if (_control != null) return _control.Persone;
return null;
}
set
{
if (_control != null)
{
if(value.UserID <= 0)
{
_control.Persone = value;
}else
{
var persone = _service.GetPerson(value.UserID, true);
_control.Persone = persone;
}
}
}
}
public bool ShowFastSearch
{
get
{
return false;
}
}
public bool ShowSearch
{
get
{
return false;
}
}
private IPersonesService _service;
public SavePersonPresentator(IApplicationFactory appFactory)
{
_appFactory = appFactory;
_control = appFactory.GetComponent<ISavePersonControl>();
_service = _appFactory.GetService<IPersonesService>();
_control.SavePersone += () =>
{
var persone = _control.Persone;
if (persone != null)
{
SavePersone(persone);
}
};
}
public void FastSearch(string message){}
public Control RenderControl()
{
return _control.GetControl();
}
public void SavePersone(IPersoneViewModel persone)
{
bool result = false;
try {
if(persone.UserID <= 0)
{
int userId = _service.AddNewPersone(persone);
if (userId > 0) result = true;
}else
{
result = _service.UpdatePersone(persone);
}
}catch(ArgumentException e)
{
_control.ShowMessage(e.Message);
return;
}
if (result)
{
string message = persone.IsEmploeyr ? "Сотрудник успешно сохранен!" : "Нарушитель успешно сохранен!";
_control.ShowMessage(message);
if (ShowForResult)
{
if(SendResult != null)
{
SendResult(ResultType, result);
}
}
}else
{
string message = persone.IsEmploeyr ? "Возникли ошибки при сохранение сотрудника!" : "Возникли ошибки при сохранение нарушителя!";
_control.ShowMessage(message);
}
}
}
}
<file_sep>/AppCore/Repositrys/Violations/ViolatorsRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations
{
public class ViolatorsRepository : IViolatorRepository
{
public IQueryable<Violator> Violators
{
get
{
var db = new LeoBaseContext();
return db.Violators;
}
}
public int SaveViolator(Violator violator)
{
using(var db = new LeoBaseContext())
{
db.Violators.Add(violator);
db.SaveChanges();
return violator.ViolatorID;
}
}
}
}
<file_sep>/WPFPresentators/AppConfig.cs
using BFData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFPresentators
{
public static class AppConfig
{
public static Manager CurrentManager { get; set; }
}
}
<file_sep>/AppCore/Contexts/LeoBaseContext.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Contexts
{
public class LeoBaseContext : DbContext
{
public LeoBaseContext():base("DataSource='LeoDataBase.sdf';Password='<PASSWORD>'") {
}
public static void InitDefaultValue()
{
using (var context = new LeoBaseContext())
{
if (context.Managers.Count() == 0)
{
context.Managers.AddRange(new List<Manager> {
new Manager { Login = "admin", Password = "<PASSWORD>", Role = "admin" },
new Manager { Login = "user", Password = "<PASSWORD>", Role = "user" }
}
);
}
if (context.ProtocolTypes.Count() == 0)
{
context.ProtocolTypes.AddRange(new List<ProtocolType> {
new ProtocolType { Name = "Протоклы об аресте" },
new ProtocolType { Name = "Протоколы о доставление" },
new ProtocolType { Name = "Протоколы о личном досмотре и досмотре вещей, находящихся при физическом лице" },
new ProtocolType { Name = "Протокол о досмотре транспортного средства" },
new ProtocolType { Name = "Протокол об осмотре принадлежащих юридическому лицу или индивидуальному предпринимателю помещений, территорий и находящихся там вещей и документов" },
new ProtocolType { Name = "Протокол об административном правонарушение для юридического лица" },
new ProtocolType { Name = "Протокол об административном правонарушение для физического лица" },
new ProtocolType { Name = "Протокол об изъятие" },
new ProtocolType { Name = "Предписание об устранение нарушений законодательства в сфере природопользования и охраны окружающей среды" },
new ProtocolType { Name = "Постановление по делу об административном правонарушение" },
new ProtocolType { Name = "Определение о возбуждение дела об административном правонарушение и проведение административного расследования" }}
);
}
if (context.Positions.Count() == 0)
{
context.Positions.AddRange(new List<EmploeyrPosition> {
new EmploeyrPosition { Name = "Государственный инспектор" },
new EmploeyrPosition { Name = "Участковый государственный инспектор" },
new EmploeyrPosition { Name = "Старший государственный инспектор" }
}
);
}
if (context.DocumentsType.Count() == 0)
{
context.DocumentsType.AddRange(new List<DocumentType> {
new DocumentType { Name = "Водительское удостоверение" },
new DocumentType { Name = "Паспорт" }
}
);
}
context.SaveChanges();
}
}
public DbSet<Persone> Persones { get; set; }
public DbSet<PersoneAddress> Addresses { get; set; }
public DbSet<Document> Documents { get; set; }
public DbSet<DocumentType> DocumentsType { get; set; }
public DbSet<Phone> Phones { get; set; }
public DbSet<EmploeyrPosition> Positions { get; set; }
public DbSet<Manager> Managers { get; set; }
public DbSet<Violation> Violations { get; set; }
public DbSet<ViolationType> ViolationsType { get; set; }
public DbSet<Violator> Violators { get; set; }
public DbSet<Employer> Employers { get; set; }
public DbSet<ViolationImage> ViolationImages { get; set; }
public DbSet<AdminViolation> AdminViolations { get; set; }
///Протоколы
public DbSet<Protocol> Protocols { get; set; }
public DbSet<DefinitionAboutViolation> DefinitionsAboutViolation { get; set; }
/// <summary>
/// Протоклы об аресте
/// </summary>
public DbSet<ProtocolAboutArrest> ProtocolsAboutArrest { get; set; }
/// <summary>
/// Протоколы о доставление
/// </summary>
public DbSet<ProtocolAboutBringing> ProtocolsAboutBringing { get; set; }
/// <summary>
/// Протоколы о личном досмотре и досмотре вещей, находящихся при физическом лице
/// </summary>
public DbSet<ProtocolAboutInspection> ProtocolsAboutInspection { get; set; }
/// <summary>
/// Протокол о досмотре транспортного средства
/// </summary>
public DbSet<ProtocolAboutInspectionAuto> ProtocolsAboutInspectionAuto { get; set; }
/// <summary>
/// Протокол об осмотре принадлежащих юридическому лицу или индивидуальному предпринимателю помещений, территорий
/// и находящихся там вещей и документов
/// </summary>
public DbSet<ProtocolAboutInspectionOrganisation> ProtocolsAboutInspectionOrganisation { get; set; }
/// <summary>
/// Протокол об административном правонарушение для юридического лица
/// </summary>
public DbSet<ProtocolAboutViolationOrganisation> ProtocolsAboutViolationOrganisation { get; set; }
/// <summary>
/// Протокол об административном правонарушение для физического лица
/// </summary>
public DbSet<ProtocolAboutViolationPersone> ProtocolsAboutViolationPersone { get; set; }
/// <summary>
/// Протокол об изъятие
/// </summary>
public DbSet<ProtocolAboutWithdraw> ProtocolsAboutWithdraw { get; set; }
/// <summary>
/// Предписание об устранение нарушений законодательства в сфере
/// природопользования и охраны окружающей среды
/// </summary>
public DbSet<Injunction> Injunctions { get; set; }
/// <summary>
/// Пункт предписания
/// </summary>
public DbSet<InjunctionItem> InjunctionItems { get; set; }
/// <summary>
/// Юридические лица
/// </summary>
public DbSet<Organisation> Organisations { get; set; }
/// <summary>
/// Постановление по делу об административном правонарушение
/// </summary>
public DbSet<RulingForViolation> RulingsForViolation { get; set; }
/// <summary>
/// Типы протоколов
/// </summary>
public DbSet<ProtocolType> ProtocolTypes { get; set; }
}
}
<file_sep>/FormControls/TestDataModel.cs
using FormControls.Controls.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FormControls
{
public class TestDataModel
{
private LeoDataComboBox _sex = new LeoDataComboBox("Муж") { "Муж", "Жен" };
[DisplayName("Код")]
public int Key { get; set; }
public string Name { get; set; }
[DisplayName("Дата рождения")]
public DateTime DateBerthday { get; set; }
[DisplayName("Пол")]
public LeoDataComboBox Sex { get
{
return _sex;
}
}
[Browsable(false)]
public string SelectedSex
{
get
{
return Sex.SelectedValue;
}
set
{
Sex.SelectedValue = value;
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/SearchPanels/AdminViolationSearchPanel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Services;
namespace LeoBase.Components.CustomControls.SearchPanels
{
public partial class AdminViolationSearchPanel : UserControl
{
public AdminViolationSearchModel SearchModel {get;set;}
public AdminViolationSearchPanel()
{
InitializeComponent();
var leoTextBox = new LeoTextBox();
leoTextBox.Dock = DockStyle.Fill;
tableLayoutPanel1.Controls.Add(leoTextBox);
}
}
}
<file_sep>/LeoBase/Components/CustomControls/WidthAnimate.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls
{
public class WidthAnimate:BackgroundWorker
{
private Control _control;
private static bool _stop = false;
private AnimationInfo _animationInfo;
public event Action OnAnimationComplete;
public WidthAnimate(Control control, int from, int to, int speed = 100, int step = 10)
{
_animationInfo = new AnimationInfo
{
From = from,
To = to,
Speed = speed,
Step = step
};
_control = control;
this.DoWork += Animate;
this.RunWorkerCompleted += WidthAnimate_RunWorkerCompleted;
this.ProgressChanged += AnimationStep;
}
private void AnimationStep(object sender, ProgressChangedEventArgs e)
{
MethodInvoker methodInvokerDelegate = delegate ()
{ _control.Width = e.ProgressPercentage; };
if (_control.InvokeRequired)
_control.Invoke(methodInvokerDelegate);
else
methodInvokerDelegate();
}
public void Start()
{
this.RunWorkerAsync(_animationInfo);
}
public void AnimationStop()
{
if (this.IsBusy)
{
_stop = true;
}
}
private void WidthAnimate_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (OnAnimationComplete != null) OnAnimationComplete();
}
private void Animate(object sender, DoWorkEventArgs e)
{
if (!(e.Argument is AnimationInfo)) return;
var info = (AnimationInfo)e.Argument;
int from = info.From;
int to = info.To;
int width = info.From;
int step = info.Step;
int speed = info.Speed;
while (width != to)
{
if(to > from)
{
if (width + step > to) width = to;
else width += step;
}else if(to < from)
{
if (width - step < to) width = to;
else width -= step;
}
this.OnProgressChanged(new ProgressChangedEventArgs(width, 1));
Thread.Sleep(speed);
}
}
}
public class AnimationInfo
{
public int From { get; set; }
public int To { get; set; }
public int Speed { get; set; }
public int Step { get; set; }
}
}
<file_sep>/LeoBase/Program.cs
using AppData.Contexts;
using AppPresentators.Infrastructure;
using AppPresentators.Presentators.Interfaces;
using LeoBase.Forms;
using LeoBase.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Infrastructure.Orders;
using System.Threading;
using System.Drawing;
namespace LeoBase
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Настройка ninject для создания абстрактных репозиториев
ApplicationFactory appFactory = new ApplicationFactory();
var mainView = new MainView();
IMainPresentator mainPresentator = appFactory.GetMainPresentator(appFactory);
LeoBaseContext.InitDefaultValue();
mainPresentator.Run();
//Application.Run(new OrderDialog() { OrderPage = new TestOrderPage() });
}
}
public class TestOrderPage : IOrderPage
{
private string _orderDirPath;
public string OrderDirPath
{
get
{
return _orderDirPath;
}
}
public OrderType OrderType
{
get
{
return OrderType.SINGLE_PAGE;
}
}
public void BuildOrder(IOrderBuilder orderBuilder, OrderConfigs configs)
{
if (configs.SinglePageConfig.DrawImages)
{
Image img = Image.FromFile("D:/Images/testimg.jpg");
orderBuilder.DrawImage(img, Align.LEFT);
}
if (configs.SinglePageConfig.DrawImages)
{
Image img = Image.FromFile("D:/Images/testimg.jpg");
orderBuilder.DrawImage(img, Align.LEFT);
}
orderBuilder.StartTable("Test table", new[] { "h1", "h2", "h3" });
for (int i = 0; i < 10; i++)
{
orderBuilder.WriteRow(new[] { "фывфыв1", "c2", "c3" }, i % 3 == 0 ? RowColor.GREEN : i % 3 == 1 ? RowColor.RED : RowColor.YELLOW);
}
orderBuilder.EndTable("Test table");
orderBuilder.StartPharagraph(Align.LEFT);
orderBuilder.WriteText("Проверочный текст 1 ", Color.Black, TextStyle.BOLD, 15);
orderBuilder.WriteText("Проверочный текст 2 ", Color.Red, TextStyle.ITALIC, 12);
orderBuilder.WriteText("Проверочный текст 3 ", Color.Green, TextStyle.NORMAL, 22);
orderBuilder.EndPharagraph();
orderBuilder.StartPharagraph(Align.CENTER);
orderBuilder.WriteText("Снова проверочный текст", Color.Black, TextStyle.ITALIC, 15);
orderBuilder.EndPharagraph();
if (configs.SinglePageConfig.DrawImages)
{
Image img = Image.FromFile("D:/Images/testimg.jpg");
orderBuilder.DrawImage(img, Align.LEFT);
}
_orderDirPath = orderBuilder.Save();
//Thread.Sleep(3000);
}
}
}
<file_sep>/Map/Map/DefaultMapRenderer.cs
using Map.Map.interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using LeoMapV2.Data;
using LeoMapV2.Models;
namespace Map.Map
{
public class DefaultMapRenderer : IMapRenderer
{
public event Action<string> OnError;
private ITitlesRepository _repo;
public int Width { get; set; }
public int Height { get; set; }
private Point CenterMap { get; set; }
public bool WasRender { get; private set; } = false;
public List<DPoint> Points { get; set; }
private int _currentZoom = MapConfig.DefaultZoom;
private List<PlaceMark> _visiblePlaceMarks;
public DefaultMapRenderer(ITitlesRepository repo)
{
_repo = repo;
_visiblePlaceMarks = new List<PlaceMark>();
}
public DPoint MouseAtPoint(int x, int y)
{
if (_visiblePlaceMarks == null) return null;
var placeMark = _visiblePlaceMarks.FirstOrDefault(p => p.Rect.X <= x && p.Rect.Y <= y && p.Rect.X + p.Rect.Width >= x && p.Rect.Y + p.Rect.Height >= y);
return placeMark != null ? placeMark.Point : null;
}
public Image GetImage()
{
_visiblePlaceMarks.Clear();
int l = CenterMap.X - Width / 2;
int t = CenterMap.Y - Height / 2;
int r = CenterMap.X + Width / 2;
int b = CenterMap.Y + Height / 2;
int titleWidth = _repo.GetZoomInformation(_currentZoom).TitleWidth;
int titleHeight = _repo.GetZoomInformation(_currentZoom).TitleHeight;
int xStart = CoordsToIndexH(l, titleWidth);
int xEnd = CoordsToIndexH(r, titleWidth);
int yStart = CoordsToIndexV(t, titleHeight);
int yEnd = CoordsToIndexV(b, titleHeight);
Bitmap result = new Bitmap((xEnd - xStart + 1) * titleWidth, (yEnd - yStart + 1) * titleHeight);
Graphics g = Graphics.FromImage(result);
for (int x = xStart; x <= xEnd; x++)
{
for (int y = yStart; y <= yEnd; y++)
{
var title = _repo.GetTitle(x, y, _currentZoom);
if (title == null) continue;
var img = title.Image;
Rectangle from = new Rectangle();
Rectangle to = new Rectangle();
from.X = 0;
from.Y = 0;
from.Width = img.Width;
from.Height = img.Height;
to.X = (x - xStart) * titleWidth - l % titleWidth;
to.Y = (y - yStart) * titleHeight - t % titleHeight;
to.Width = titleWidth;
to.Height = titleHeight;
if(Points != null)
{
var titlePoints = Points.Where(p => title.E >= p.E && title.W <= p.E && title.N >= p.N && title.S <= p.N);
double dE = title.E - title.W;
double dN = title.N - title.S;
if (titlePoints != null)
{
Graphics titleImage = Graphics.FromImage(img);
var placeMarkImage = Properties.Resources.placeMark;
foreach (var p in titlePoints)
{
int xPoint = (int)Math.Round((double)img.Width * (p.E - title.W) / dE );
int yPoint = img.Height - (int)Math.Round((double)img.Height * (p.N - title.S) / dN );
if (xPoint - placeMarkImage.Width / 2 < 0) xPoint = placeMarkImage.Width / 2;
else if (xPoint + placeMarkImage.Width / 2 > img.Width) xPoint = img.Width - placeMarkImage.Width / 2;
if (yPoint < 0) yPoint = 0;
else if (yPoint + placeMarkImage.Height > img.Height) yPoint = img.Height - placeMarkImage.Height;
Rectangle drawTo = new Rectangle();
drawTo.X = xPoint - placeMarkImage.Width / 2;
drawTo.Y = yPoint - placeMarkImage.Height;
drawTo.Width = placeMarkImage.Width;
drawTo.Height = placeMarkImage.Height;
titleImage.DrawImage(placeMarkImage, drawTo, new Rectangle(0, 0, placeMarkImage.Width, placeMarkImage.Height), GraphicsUnit.Pixel);
_visiblePlaceMarks.Add(new PlaceMark
{
Rect = new Rectangle
{
X = drawTo.X + to.X,
Y = drawTo.Y + to.Y,
Width = placeMarkImage.Width,
Height = placeMarkImage.Height
},
Point = p
});
}
}
}
g.DrawImage(img, to, from, GraphicsUnit.Pixel);
}
}
return (Image)result;
}
public Task<Image> GetImageAsync()
{
_visiblePlaceMarks.Clear();
return Task.Run(() =>
{
int l = CenterMap.X - Width / 2;
int t = CenterMap.Y - Height / 2;
int r = CenterMap.X + Width / 2;
int b = CenterMap.Y + Height / 2;
int titleWidth = _repo.GetZoomInformation(_currentZoom).TitleWidth;
int titleHeight = _repo.GetZoomInformation(_currentZoom).TitleHeight;
int xStart = CoordsToIndexH(l, titleWidth);
int xEnd = CoordsToIndexH(r, titleWidth);
int yStart = CoordsToIndexV(t, titleHeight);
int yEnd = CoordsToIndexV(b, titleHeight);
Bitmap result = new Bitmap((xEnd - xStart + 1) * titleWidth, (yEnd - yStart + 1) * titleHeight);
Graphics g = Graphics.FromImage(result);
for(int x = xStart; x<=xEnd; x++)
{
for(int y = yStart; y <= yEnd; y++)
{
var title = _repo.GetTitle(x, y, _currentZoom);
if (title == null) continue;
var img = title.Image;
Rectangle from = new Rectangle();
Rectangle to = new Rectangle();
from.X = 0;
from.Y = 0;
from.Width = img.Width;
from.Height = img.Height;
to.X = (x - xStart) * titleWidth - l % titleWidth;
to.Y = (y - yStart) * titleHeight - t % titleHeight;
to.Width = titleWidth;
to.Height = titleHeight;
if (Points != null)
{
var titlePoints = Points.Where(p => title.E >= p.E && title.W <= p.E && title.N >= p.N && title.S <= p.N);
double dE = title.E - title.W;
double dN = title.N - title.S;
if (titlePoints != null)
{
Graphics titleImage = Graphics.FromImage(img);
var placeMarkImage = Properties.Resources.placeMark;
foreach (var p in titlePoints)
{
int xPoint = (int)Math.Round((double)img.Width * (p.E - title.W) / dE);
int yPoint = img.Height - (int)Math.Round((double)img.Height * (p.N - title.S) / dN);
if (xPoint - placeMarkImage.Width / 2 < 0) xPoint = placeMarkImage.Width / 2;
else if (xPoint + placeMarkImage.Width / 2 > img.Width) xPoint = img.Width - placeMarkImage.Width / 2;
if (yPoint < 0) yPoint = 0;
else if (yPoint + placeMarkImage.Height > img.Height) yPoint = img.Height - placeMarkImage.Height;
Rectangle drawTo = new Rectangle();
drawTo.X = xPoint - placeMarkImage.Width / 2;
drawTo.Y = yPoint - placeMarkImage.Height;
drawTo.Width = placeMarkImage.Width;
drawTo.Height = placeMarkImage.Height;
titleImage.DrawImage(placeMarkImage, drawTo, new Rectangle(0, 0, placeMarkImage.Width, placeMarkImage.Height), GraphicsUnit.Pixel);
_visiblePlaceMarks.Add(new PlaceMark
{
Rect = new Rectangle
{
X = drawTo.X + to.X,
Y = drawTo.Y + to.Y,
Width = placeMarkImage.Width,
Height = placeMarkImage.Height
},
Point = p
});
}
}
}
g.DrawImage(img, to, from, GraphicsUnit.Pixel);
}
}
return (Image)result;
});
}
private static int CoordsToIndexH(int x, int titleWidth)
{
return (x - x % titleWidth) / titleWidth;
}
private static int CoordsToIndexV(int y, int titleHeight)
{
return (y - y % titleHeight) / titleHeight;
}
public void LookAt(int x, int y)
{
var zInf = _repo.GetZoomInformation(_currentZoom);
int titleWidth = zInf.TitleWidth;
int titleHeight = zInf.TitleHeight;
int totalWidth = titleWidth * zInf.MaxX;
int totalHeight = titleHeight * zInf.MaxY;
if (x - Width / 2 < 0 && x + Width / 2 > totalWidth) x = totalWidth / 2;
else if (x - Width / 2 < 0) x = Width / 2;
else if (x + Width / 2 > totalWidth) x = totalWidth - Width / 2;
if (y - Height / 2 < 0 && y + Height / 2 > totalHeight) y = totalHeight / 2;
else if (y - Height / 2 < 0) y = Height / 2;
else if (y + Height / 2 > totalHeight) y = totalHeight - Height / 2;
CenterMap = new Point(x, y);
WasRender = true;
}
public void MoveCenter(int dx, int dy)
{
int nX = CenterMap.X - dx;
int nY = CenterMap.Y - dy;
var zInf = _repo.GetZoomInformation(_currentZoom);
int titleWidth = zInf.TitleWidth;
int titleHeight = zInf.TitleHeight;
int totalWidth = titleWidth * zInf.MaxX;
int totalHeight = titleHeight * zInf.MaxY;
if (nX - Width / 2 < 0) nX = Width / 2;
if (nY - Height / 2 < 0) nY = Height / 2;
if (nX + Width / 2 > totalWidth) nX = totalWidth - Width / 2;
if (nY + Height / 2 > totalHeight) nY = totalHeight - Height / 2;
CenterMap = new Point(nX, nY);
}
public void LookAt(DPoint point)
{
if (_repo.GetZooms().Contains(point.Zoom)) _currentZoom = point.Zoom;
else point.Zoom = _currentZoom;
var center = _repo.ConvertMapCoordsToPixels(point);
LookAt(center.X, center.Y);
}
public MapEventArgs GetMapEventArgs(int x, int y)
{
int mx = x - Width / 2 + CenterMap.X;
int my = y - Height / 2 + CenterMap.Y;
var dPoint = _repo.ConvertPixelsToMapCoords(mx, my, _currentZoom);
if (dPoint == null) return null;
MapEventArgs eventArgs = new MapEventArgs(x, y, dPoint.N, dPoint.E, mx, my);
return eventArgs;
}
public bool ZoomMinus(int dx, int dy)
{
if (_repo.GetZooms().Contains(_currentZoom - 1))
{
int nX = (CenterMap.X + dx) / 2;
int nY = (CenterMap.Y + dy) / 2;
CenterMap = new Point(nX, nY);
_currentZoom--;
return true;
}
return false;
}
public bool ZoomPlus(int dx, int dy)
{
if (_repo.GetZooms().Contains(_currentZoom + 1)) {
int nx = (CenterMap.X + dx) * 2;
int ny = (CenterMap.Y + dy) * 2;
CenterMap = new Point(nx, ny);
_currentZoom++;
return true;
}
return false;
}
}
}
<file_sep>/FormControls/Controls/Models/LeoDataComboBox.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FormControls.Controls.Models
{
public class LeoDataComboBox:List<string>
{
public string SelectedValue { get; set; }
public LeoDataComboBox(string selectedValue)
{
SelectedValue = selectedValue;
}
}
}
<file_sep>/AppPresentators/Components/IPersoneDetailsControl.cs
using AppPresentators.VModels;
using AppPresentators.VModels.Persons;
using AppPresentators.VModels.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public interface IPersoneDetailsControl: UIComponent
{
IPersoneViewModel Persone { get; set; }
List<ViolationViewModel> Violations { get; set; }
List<ProtocolViewModel> Protocols { get; set; }
Dictionary<int, string> Positions { get; set; }
}
}
<file_sep>/AppCore/Abstract/IPhonesRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract
{
public interface IPhonesRepository
{
IQueryable<Phone> Phones { get; }
int AddPhone(Phone phone);
bool Remove(int id);
int RemoveAllUserPhones(int userid);
}
}
<file_sep>/FormControls/Controls/LeoDataGridView.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FormControls.Controls.Models;
using System.Reflection;
using FormControls.Controls.Attributes;
using FormControls.Controls.Enums;
using FormControls.Controls.Events;
namespace FormControls.Controls
{
public partial class LeoDataGridView : UserControl
{
private TableLayoutPanel _dataPanel;
private TableLayoutPanel _headPanel;
private bool _resizeStart = false;
private HeadTitle _resizedColumn;
private int _oldXPositionForResize;
private TransparentPanel _resizedPanel;
private PictureBox _resizeSeparator;
#region Events
public event TableOrderEvent OnTableOrder;
#endregion
public int ColumnCount { get; private set; } = 0;
public int RowCount { get; private set; } = 0;
public PageModel PageModel { get; set; }
public object Data { get; private set; }
private List<HeadTitle> _headers;
private List<LeoDataViewRow> _rows;
public void SetData<T>(List<T> data)
{
Data = data;
_dataPanel.Controls.Clear();
_headPanel.Controls.Clear();
MakeHeaders(typeof(T));
_headPanel.SendToBack();
_dataPanel.ColumnCount = ColumnCount;
if (data == null) return;
_dataPanel.RowCount = data.Count;
var metaList = _headers.Select(h => h.MetaData).ToList();
_rows = new List<LeoDataViewRow>();
int index = 0;
foreach (var item in data)
{
var row = new LeoDataViewRow(item, metaList, index);
_rows.Add(row);
foreach(var control in row.Cells)
{
_dataPanel.Controls.Add(control);
}
index++;
}
UpdateTableSize();
}
public LeoDataGridView()
{
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
SetStyle(ControlStyles.Opaque, true);
InitializeComponent();
_dataPanel = new TableLayoutPanel();
_headPanel = new TableLayoutPanel();
_headPanel.Dock = DockStyle.Fill;
_dataPanel.Dock = DockStyle.Top;
_dataPanel.AutoSize = true;
headersPanel.Controls.Add(_headPanel);
dataPanel.Controls.Add(_dataPanel);
this.MouseMove += TableMouseMove;
_resizedPanel = new TransparentPanel();
_resizeSeparator = new PictureBox();
_resizeSeparator.Height = _resizedPanel.Height;
_resizeSeparator.Width = 20;
_resizeSeparator.BackColor = Color.Black;
_resizedPanel.Dock = DockStyle.Fill;
_resizedPanel.BackColor = Color.Transparent;
headersPanel.Controls.Add(_resizedPanel);
_resizedPanel.Controls.Add(_resizeSeparator);
_resizedPanel.Visible = false;
this.Load += LeoDataGridView_Load;
this.Resize += TableResize;
}
private void TableResize(object sender, EventArgs e)
{
if (_dataPanel == null || _headPanel == null) return;
//UpdateTableSize();
}
private void UpdateTableSize()
{
_headPanel.ColumnStyles.Clear();
_dataPanel.ColumnStyles.Clear();
for (int i = 0; i < ColumnCount; i++)
{
ColumnStyle cs = new ColumnStyle(SizeType.Absolute, this.Width / ColumnCount);
_headPanel.ColumnStyles.Add(cs);
if (_dataPanel.Height > dataPanel.Height && i == ColumnCount - 1)
cs = new ColumnStyle(SizeType.Absolute, (this.Width / ColumnCount) - 100);
else
cs = new ColumnStyle(SizeType.Absolute, this.Width / ColumnCount);
_dataPanel.ColumnStyles.Add(cs);
}
}
private void LeoDataGridView_Load(object sender, EventArgs e)
{
this.Refresh();
_resizeSeparator.Left = 100;
}
private void TableMouseMove(object sender, MouseEventArgs e)
{
if (_resizeStart)
{
MessageBox.Show("It`s work!");
_resizeStart = false;
}
}
private void MakeHeaders(Type t)
{
_headers = new List<HeadTitle>();
foreach (var propertie in t.GetProperties())
{
LeoDataViewHeadMetaData metadata = new LeoDataViewHeadMetaData();
metadata.Show = true;
metadata.CanOrder = true;
metadata.Type = propertie.PropertyType.Name;
metadata.FieldName = propertie.Name;
foreach(var attr in propertie.GetCustomAttributesData())
{
if (attr.AttributeType.Name.Equals("BrowsableAttribute"))
{
metadata.Show = propertie.GetCustomAttribute<BrowsableAttribute>().Browsable;
}else if (attr.AttributeType.Name.Equals("OrderAttribute"))
{
metadata.CanOrder = propertie.GetCustomAttribute<OrderAttribute>().Order;
}else if (attr.AttributeType.Name.Equals("DisplayNameAttribute"))
{
metadata.DisplayName = propertie.GetCustomAttribute<DisplayNameAttribute>().DisplayName;
}
}
ColumnCount += metadata.Show ? 1 : 0;
var header = new HeadTitle(metadata);
header.OnTableOrder += TableOrder;
_headers.Add(header);
}
_headPanel.ColumnCount = ColumnCount;
_headPanel.RowCount = 1;
int index = 0;
foreach (var head in _headers)
{
if (head.MetaData.Show)
{
ColumnStyle cs = new ColumnStyle(SizeType.Percent, 100 / ColumnCount);
head.MetaData.ColumnIndex = index;
_headPanel.Controls.Add(head);
_headPanel.ColumnStyles.Add(cs);
head.OnResizeStart += CustomResizeColumns;
head.OnHeaderMouseMove += HeadMouseMove;
index++;
}
}
var firstHeader = _headers.FirstOrDefault(h => h.MetaData.Show);
if (firstHeader != null) firstHeader.IsFirst = true;
var lastHeader = _headers.FindLast(h => h.MetaData.Show);
if (lastHeader != null) lastHeader.IsLast = true;
}
private void HeadMouseMove(HeadTitle sender, MouseEventArgs e)
{
_resizeStart = false;
return;
if (_resizedColumn == null)
{
_resizeStart = false;
}
if (_resizeStart)
{
_resizedPanel.Visible = true;
int newPosition = Cursor.Position.X;
_resizeSeparator.Left = newPosition;
return;
int delta = _oldXPositionForResize - newPosition;
if (_headPanel.ColumnStyles[_resizedColumn.MetaData.ColumnIndex].Width + delta < 50) return;
_headPanel.ColumnStyles[_resizedColumn.MetaData.ColumnIndex].Width += delta;
_oldXPositionForResize = newPosition;
}else
{
_oldXPositionForResize = Cursor.Position.X;
}
}
private void CustomResizeColumns(HeadTitle sender, bool resized)
{
_resizeStart = resized;
_resizedColumn = sender;
}
private void TableOrder(HeadTitle sender, OrderTypes type)
{
foreach(var header in _headers)
{
if (header != sender && header.MetaData.CanOrder) header.OrderType = OrderTypes.NONE;
}
if (OnTableOrder != null) OnTableOrder(sender, type);
}
}
}
<file_sep>/AppCore/Entities/PersoneAddress.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
public class PersoneAddress
{
[Key]
public int AddressID { get; set; }
[Required(AllowEmptyStrings = false)]
public string Country { get; set; } = "Российская Федерация";
[Required(AllowEmptyStrings = false)]
public virtual Persone Persone { get; set; }
public string Subject { get; set; } = "Приморский край";
public string Area { get; set; } = "Хасанский район";
public string City { get; set; }
public string Street { get; set; }
public string HomeNumber { get; set; }
public string Flat { get; set; }
[DefaultValue("Проживает и прописка")]
public string Note { get; set; } = "Проживает и прописка";
public override string ToString()
{
return Country + " " + Subject + " " + Area + " " + City + " " + Street + " " + HomeNumber + " " +Flat;
}
}
}
<file_sep>/AppCore/Abstract/Protocols/IProtocolAboutWithdrawRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract.Protocols
{
public interface IProtocolAboutWithdrawRepository
{
IQueryable<ProtocolAboutWithdraw> ProtocolsAboutWithdraw { get; }
}
}
<file_sep>/LeoMapV3/Models/MapDragAndDropStates.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoMapV3.Models
{
public enum MapDragAndDropStates
{
DRAG_AND_DROP,
SELECT_AREA,
NONE
}
}
<file_sep>/WPFPresentators/Views/Windows/ILoginView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFPresentators.Views.Windows
{
public interface ILoginView:IWindowView
{
#region Actions
event Action OnLogin;
#endregion
#region Properties
string Login { get; }
string Password { get; }
#endregion
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/ComponentPresentators/IPersoneDetailsPresentator.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces.ComponentPresentators
{
public interface IPersoneDetailsPresentator:IComponentPresentator
{
IPersoneViewModel Persone { get; set; }
void UpdatePersone();
}
}
<file_sep>/LeoBase/Components/CustomControls/PreloadPanel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls
{
public partial class PreloadPanel : UserControl
{
public Bitmap Image
{
set
{
this.BackgroundImage = value;
}
}
public PreloadPanel()
{
InitializeComponent();
}
}
}
<file_sep>/AppCore/Repositrys/Violations/ViolationImageRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations
{
public class ViolationImageRepository : IViolationImagesRepository
{
public IQueryable<ViolationImage> ViolationImages
{
get
{
var db = new LeoBaseContext();
return db.ViolationImages;
}
}
}
}
<file_sep>/AppPresentators/VModels/ViolationViewModel.cs
using AppPresentators.VModels.Protocols;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public class ViolationViewModel
{
[Browsable(false)]
public int ViolationID { get; set; }
[DisplayName("Дата")]
public DateTime Date { get; set; }
[DisplayName("Описание")]
public string Description { get; set; }
[DisplayName("Северная широта(N)")]
public double N { get; set; }
[DisplayName("Восточная долгота(E)")]
public double E { get; set; }
[DisplayName("Возбуждено дело")]
[Browsable(false)]
public string ViolationType { get; set; } = "Административное";
public List<ProtocolViewModel> Protocols { get; set; }
public List<byte[]> Images { get; set; }
}
}
<file_sep>/AppPresentators/Factorys/ProtocolFactory.cs
using AppData.Abstract;
using AppData.Abstract.Protocols;
using AppData.Contexts;
using AppData.Entities;
using AppData.Infrastructure;
using AppPresentators.VModels.Persons;
using AppPresentators.VModels.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Factorys
{
public enum ProtocolsType
{
/// <summary>
/// Протокол о доставление
/// </summary>
PROTOCOL_ABOUT_BRINGING = 1,
/// <summary>
/// Протокол о личном досмотре
/// </summary>
PROTOCOL_ABOUT_INSPECTION = 2,
/// <summary>
/// Протокол о досмотре транспортного средства
/// </summary>
PROTOCOL_ABOUT_INSPECTION_AUTO = 3,
/// <summary>
/// Протокол об изъятии
/// </summary>
PROTOCOL_ABOUT_WITHDRAW = 4,
/// <summary>
/// Протокол об осмотре территорий и зданий принадлежащих организации
/// </summary>
PROTOCOL_ABOUT_INSPECTION_ORGANISATION = 5,
/// <summary>
/// Протокол об аресте
/// </summary>
PROTOCOL_ABOUT_ARREST = 6,
/// <summary>
/// Определение
/// </summary>
DEFINITION = 7,
/// <summary>
/// Протокол об административном правонарушение для физического лица
/// </summary>
PROTOCOL_ABOUT_VIOLATION_PERSONE = 8,
/// <summary>
/// Протокол об административном правонарушение для юридического лица
/// </summary>
PROTOCOL_ABOUT_VIOLATION_ORGANISATION = 9,
/// <summary>
/// Постановление
/// </summary>
RULING_FOR_VIOLATION = 10,
/// <summary>
/// Предписание
/// </summary>
INJUCTION = 11
}
public class ProtocolFactory
{
private static ProtocolFactory _instance;
public static Dictionary<int, string> ProtocolTypes = new Dictionary<int, string> {
{1, "Протокол о доставление" },
{2, "Протокол о личном досмотре" },
{3, "Протокол о досмотре транспортного средства" },
{4, "Протокол об изъятии" },
{5, "Протокол об осмотре территорий и зданий принадлежащих организации"},
{6, "Протокол об аресте" },
{7, "Определение" },
{8, "Протокол об административном правонарушение для физического лица" },
{9, "Протокол об административном правонарушение для юридического лица" },
{10, "Постановление" },
{11, "Предписание"}
};
public static ProtocolFactory GetInstance()
{
if (_instance == null) _instance = new ProtocolFactory();
return _instance;
}
private ProtocolFactory() { }
#region Сохранение протоколов
public static bool SaveProtocolAboutBringing(IProtocol protocol)
{
if (!(protocol is ProtocolAboutBringing))
throw new ArgumentException("Протокол не является протоколом о доставление.");
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction()) {
try
{
db.Database.CommandTimeout = 3000;
var protocolAboutBringing = (ProtocolAboutBringing)protocol;
var violatorDocument = db.Documents
.FirstOrDefault(d => d.DocumentID == protocolAboutBringing.ViolatorDocumentID);
if (violatorDocument == null) return false;
var violatorEntity = db.Persones
.FirstOrDefault(p => p.UserID == violatorDocument.Persone.UserID);
if (violatorEntity == null) return false;
Violator violator = new Violator
{
PersoneID = violatorEntity.UserID,
ViolationID = protocol.Protocol.ViolationID,
Protocol = protocol.Protocol
};
db.ProtocolsAboutBringing.Add(protocolAboutBringing);
db.Violators.Add(violator);
db.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool SaveProtocolAboutInspection(IProtocol protocol)
{
if (!(protocol is ProtocolAboutInspection))
throw new ArgumentException("Протокол не является протоколом о досмотре.");
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
var protocolAboutInspection = (ProtocolAboutInspection)protocol;
var violatorDocument = db.Documents
.FirstOrDefault(d => d.DocumentID == protocolAboutInspection.ViolatorDocumentID);
if (violatorDocument == null) return false;
var violatorEntity = db.Persones
.FirstOrDefault(p => p.UserID == violatorDocument.Persone.UserID);
if (violatorEntity == null) return false;
Violator violator = new Violator
{
PersoneID = violatorEntity.UserID,
ViolationID = protocol.Protocol.ViolationID,
Protocol = protocol.Protocol
};
db.ProtocolsAboutInspection.Add(protocolAboutInspection);
db.Violators.Add(violator);
db.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool SaveProtocolAboutInspectAuto(IProtocol protocol)
{
if (!(protocol is ProtocolAboutInspectionAuto))
throw new ArgumentException("Протокол не является протоколом досмотра машины");
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
var protocolAboutInspectionAuto = (ProtocolAboutInspectionAuto)protocol;
var violatorDocument = db.Documents
.FirstOrDefault(d => d.DocumentID == protocolAboutInspectionAuto.ViolatorDocumentID);
if (violatorDocument == null) return false;
var violatorEntity = db.Persones
.FirstOrDefault(p => p.UserID == violatorDocument.Persone.UserID);
if (violatorEntity == null) return false;
Violator violator = new Violator
{
PersoneID = violatorEntity.UserID,
ViolationID = protocol.Protocol.ViolationID,
Protocol = protocol.Protocol
};
db.ProtocolsAboutInspectionAuto.Add(protocolAboutInspectionAuto);
db.Violators.Add(violator);
db.SaveChanges();
transaction.Commit();
return true;
} catch (Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool SaveProtocolAboutWithdraw(IProtocol protocol)
{
if (!(protocol is ProtocolAboutWithdraw))
throw new ArgumentException("Протокол не является протоколом о изъятии.");
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
var protocolAboutWithdraw = (ProtocolAboutWithdraw)protocol;
var violatorDocument = db.Documents
.FirstOrDefault(d => d.DocumentID == protocolAboutWithdraw.ViolatorDocumentID);
if (violatorDocument == null) return false;
var violatorEntity = db.Persones
.FirstOrDefault(p => p.UserID == violatorDocument.Persone.UserID);
if (violatorEntity == null) return false;
Violator violator = new Violator
{
PersoneID = violatorEntity.UserID,
ViolationID = protocol.Protocol.ViolationID,
Protocol = protocol.Protocol
};
db.ProtocolsAboutWithdraw.Add(protocolAboutWithdraw);
db.Violators.Add(violator);
db.SaveChanges();
transaction.Commit();
return true;
} catch (Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool SaveProtocolAboutInspectionOrganisation(IProtocol protocol)
{
if (!(protocol is ProtocolAboutInspectionOrganisation))
throw new ArgumentException("Протокол не является протоколом осмотра организации");
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
ProtocolAboutInspectionOrganisation protocolAboutInspectionOrganisation = (ProtocolAboutInspectionOrganisation)protocol;
Organisation organisation = db.Organisations.FirstOrDefault(o => o.OrganisationID == protocolAboutInspectionOrganisation.OrganisationID);
if (organisation == null) return false;
Violator violator = new Violator
{
ViolatorType = "Организация",
ViolationID = protocol.Protocol.ViolationID,
PersoneID = organisation.OrganisationID,
Protocol = protocol.Protocol
};
db.Violators.Add(violator);
db.ProtocolsAboutInspectionOrganisation.Add(protocolAboutInspectionOrganisation);
db.SaveChanges();
transaction.Commit();
return true;
} catch (Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool SaveProtocolAboutArrest(IProtocol protocol)
{
if (!(protocol is ProtocolAboutArrest))
throw new ArgumentException("Протокол не является протоколом об аресте");
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
var protocolAboutArrest = (ProtocolAboutArrest)protocol;
var violatorDocument = db.Documents
.Include("Persone")
.FirstOrDefault(d => d.DocumentID == protocolAboutArrest.ViolatorDocumentID);
if (violatorDocument == null) return false;
var violatorEntity = db.Persones
.FirstOrDefault(p => p.UserID == violatorDocument.Persone.UserID);
if (violatorEntity == null) return false;
Violator violator = new Violator
{
PersoneID = violatorEntity.UserID,
ViolationID = protocol.Protocol.ViolationID,
Protocol = protocol.Protocol
};
db.ProtocolsAboutArrest.Add(protocolAboutArrest);
db.Violators.Add(violator);
db.SaveChanges();
transaction.Commit();
return true;
} catch (Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool SaveDefinition(IProtocol protocol)
{
if (!(protocol is DefinitionAboutViolation))
throw new ArgumentException("Документ не является определением о возбуждение административного расследования.");
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
var definition = (DefinitionAboutViolation)protocol;
Violator violator;
if (definition.OrganisationID != 0)
{
var organisation = db.Organisations.FirstOrDefault(o => o.OrganisationID == definition.OrganisationID);
if (organisation == null) return false;
violator = new Violator
{
ViolationID = protocol.Protocol.ViolationID,
PersoneID = organisation.OrganisationID,
ViolatorType = "Организация",
Protocol = protocol.Protocol
};
} else if (definition.ViolatorDocumentID != 0)
{
var violatorDocument = db.Documents
.FirstOrDefault(d => d.DocumentID == definition.ViolatorDocumentID);
if (violatorDocument == null) return false;
var violatorEntity = db.Persones
.FirstOrDefault(p => p.UserID == violatorDocument.Persone.UserID);
if (violatorEntity == null) return false;
violator = new Violator
{
PersoneID = violatorEntity.UserID,
ViolationID = protocol.Protocol.ViolationID,
Protocol = protocol.Protocol
};
}
else
{
return false;
}
db.Violators.Add(violator);
db.DefinitionsAboutViolation.Add(definition);
db.SaveChanges();
transaction.Commit();
return true;
} catch (Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool SaveProtocolAboutViolationPersone(IProtocol protocol)
{
if (!(protocol is ProtocolAboutViolationPersone))
throw new ArgumentException("Протокол не является протоколом об административном правонарушение гражданина");
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
var protocolAboutViolation = (ProtocolAboutViolationPersone)protocol;
var violatorDocument = db.Documents
.FirstOrDefault(d => d.DocumentID == protocolAboutViolation.ViolatorDocumentID);
if (violatorDocument == null) return false;
var violatorEntity = db.Persones
.FirstOrDefault(p => p.UserID == violatorDocument.Persone.UserID);
if (violatorEntity == null) return false;
Violator violator = new Violator
{
PersoneID = violatorEntity.UserID,
ViolationID = protocol.Protocol.ViolationID,
Protocol = protocol.Protocol
};
db.ProtocolsAboutViolationPersone.Add(protocolAboutViolation);
db.Violators.Add(violator);
db.SaveChanges();
transaction.Commit();
return true;
} catch (Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool SaveProtocolAboutViolationOrganisation(IProtocol protocol)
{
if (!(protocol is ProtocolAboutViolationOrganisation))
throw new ArgumentException("Протокол не является протоколом об административном правонарушение организации");
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
var protocolAboutViolationOrganisation = (ProtocolAboutViolationOrganisation)protocol;
var organisation = db.Organisations.FirstOrDefault(o => o.OrganisationID == protocolAboutViolationOrganisation.OrganisationID);
if (organisation == null) return false;
Violator violator = new Violator
{
ViolationID = protocol.Protocol.ViolationID,
PersoneID = organisation.OrganisationID,
ViolatorType = "Организация",
Protocol = protocol.Protocol
};
db.Violators.Add(violator);
db.ProtocolsAboutViolationOrganisation.Add(protocolAboutViolationOrganisation);
db.SaveChanges();
transaction.Commit();
return true;
} catch (Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool SaveRulingForViolation(IProtocol protocol)
{
if (!(protocol is RulingForViolation))
throw new AccessViolationException("Документ не является постановлением");
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
var ruling = (RulingForViolation)protocol;
Violator violator;
if (ruling.OrganisationID != 0)
{
var organisation = db.Organisations.FirstOrDefault(o => o.OrganisationID == ruling.OrganisationID);
if (organisation == null) return false;
violator = new Violator
{
ViolationID = protocol.Protocol.ViolationID,
PersoneID = organisation.OrganisationID,
ViolatorType = "Организация",
Protocol = protocol.Protocol
};
}
else if (ruling.ViolatorDocumentID != 0)
{
var violatorDocument = db.Documents
.FirstOrDefault(d => d.DocumentID == ruling.ViolatorDocumentID);
if (violatorDocument == null) return false;
var violatorEntity = db.Persones
.FirstOrDefault(p => p.UserID == violatorDocument.Persone.UserID);
if (violatorEntity == null) return false;
violator = new Violator
{
PersoneID = violatorEntity.UserID,
ViolationID = protocol.Protocol.ViolationID
};
}
else
{
return false;
}
db.RulingsForViolation.Add(ruling);
db.Violators.Add(violator);
db.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool SaveInjunction(IProtocol protocol)
{
if (!(protocol is Injunction))
throw new ArgumentException("Документ не является предписанием");
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
var injuction = (Injunction)protocol;
var violatorDocument = db.Documents
.FirstOrDefault(d => d.DocumentID == injuction.ViolatorDocumentID);
if (violatorDocument == null) return false;
var violatorEntity = db.Persones
.FirstOrDefault(p => p.UserID == violatorDocument.Persone.UserID);
if (violatorEntity == null) return false;
Violator violator = new Violator
{
PersoneID = violatorEntity.UserID,
ViolationID = protocol.Protocol.ViolationID,
Protocol = protocol.Protocol
};
db.Injunctions.Add(injuction);
db.Violators.Add(violator);
db.SaveChanges();
transaction.Commit();
return true;
} catch (Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
/// <summary>
/// Сохранение протокола
/// </summary>
/// <param name="protocol">Протокол</param>
/// <returns></returns>
public static bool SaveProtocol(IProtocol protocol)
{
switch (protocol.Protocol.ProtocolTypeID)
{
case (int)ProtocolsType.PROTOCOL_ABOUT_BRINGING:
return SaveProtocolAboutBringing(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION:
return SaveProtocolAboutInspection(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION_AUTO:
return SaveProtocolAboutInspectAuto(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_WITHDRAW:
return SaveProtocolAboutWithdraw(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION_ORGANISATION:
return SaveProtocolAboutInspectionOrganisation(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_ARREST:
return SaveProtocolAboutArrest(protocol);
case (int)ProtocolsType.DEFINITION:
return SaveDefinition(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_VIOLATION_PERSONE:
return SaveProtocolAboutViolationPersone(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_VIOLATION_ORGANISATION:
return SaveProtocolAboutViolationOrganisation(protocol);
case (int)ProtocolsType.RULING_FOR_VIOLATION:
return SaveRulingForViolation(protocol);
case (int)ProtocolsType.INJUCTION:
return SaveInjunction(protocol);
}
return false;
}
#endregion
#region Получение протоколов и их детализации
/// <summary>
/// Получение протокола по ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static Protocol GetProtocol(int id)
{
using (var db = new LeoBaseContext())
{
var protocol = db.Protocols.FirstOrDefault(p => p.ProtocolID == id);
return protocol;
}
}
/// <summary>
/// Получение всех протоколов по правонарушению
/// </summary>
/// <param name="id">Идентификатор правонарушения</param>
/// <returns></returns>
public static List<Protocol> GetViolationProtocols(int id)
{
List<Protocol> result = new List<Protocol>();
using (var db = new LeoBaseContext())
{
var protocols = db.Protocols.Where(p => p.ViolationID == id);
foreach (var protocol in protocols)
{
result.Add(protocol);
}
}
return result;
}
public static DefinitionAboutViolation GetDefinition(Protocol protocol)
{
using (var db = new LeoBaseContext())
{
var definition = db.DefinitionsAboutViolation.Include("Protocol")
.FirstOrDefault(d => d.Protocol.ProtocolID == protocol.ProtocolID);
return definition;
}
}
public static Injunction GetInjuctuion(Protocol protocol)
{
using (var db = new LeoBaseContext())
{
var injunctuion = db.Injunctions.Include("Protocol")
.Include("InjuctionsItem")
.FirstOrDefault(i => i.Protocol.ProtocolID == protocol.ProtocolID);
return injunctuion;
}
}
public static ProtocolAboutArrest GetProtocolAboutArrest(Protocol protocol)
{
using (var db = new LeoBaseContext())
{
var protocolAboutArrest = db.ProtocolsAboutArrest.Include("Protocol").FirstOrDefault(p => p.Protocol.ProtocolID == protocol.ProtocolID);
return protocolAboutArrest;
}
}
public static ProtocolAboutBringing GetProtocolAboutBringing(Protocol protocol)
{
using (var db = new LeoBaseContext())
{
var protocolAboutBringing = db.ProtocolsAboutBringing.Include("Protocol").FirstOrDefault(p => p.Protocol.ProtocolID == protocol.ProtocolID);
return protocolAboutBringing;
}
}
public static ProtocolAboutInspection GetProtocolAboutInspection(Protocol protocol)
{
using (var db = new LeoBaseContext())
{
var protocolAboutInspection = db.ProtocolsAboutInspection
.Include("Protocol")
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.ProtocolID);
return protocolAboutInspection;
}
}
public static ProtocolAboutInspectionAuto GetProtocolAboutInspectionAuto(Protocol protocol)
{
using(var db = new LeoBaseContext())
{
var protocolAboutInspectionAuto = db.ProtocolsAboutInspectionAuto
.Include("Protocol")
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.ProtocolID);
return protocolAboutInspectionAuto;
}
}
public static ProtocolAboutInspectionOrganisation GetProtocolAboutInspectionOrganisation(Protocol protocol)
{
using(var db = new LeoBaseContext())
{
var protocolAboutInspectionOrganisation = db.ProtocolsAboutInspectionOrganisation
.Include("Protocol")
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.ProtocolID);
return protocolAboutInspectionOrganisation;
}
}
public static ProtocolAboutViolationOrganisation GetProtocolAboutViolationOrganisation(Protocol protocol)
{
using(var db = new LeoBaseContext())
{
var protocolAboutViolationOrganisation = db.ProtocolsAboutViolationOrganisation
.Include("Protocol")
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.ProtocolID);
return protocolAboutViolationOrganisation;
}
}
public static ProtocolAboutViolationPersone GetProtocolAboutViolationPersone(Protocol protocol)
{
using(var db = new LeoBaseContext())
{
var protocolAboutViolationPersone = db.ProtocolsAboutViolationPersone
.Include("Protocol")
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.ProtocolID);
return protocolAboutViolationPersone;
}
}
public static ProtocolAboutWithdraw GetProtocolAboutWithdraw(Protocol protocol)
{
using(var db = new LeoBaseContext())
{
var protocolAboutWithdraw = db.ProtocolsAboutWithdraw
.Include("Protocol")
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.ProtocolID);
return protocolAboutWithdraw;
}
}
public static RulingForViolation GetRulingForViolation(Protocol protocol)
{
using(var db = new LeoBaseContext())
{
var rulingForViolation = db.RulingsForViolation
.Include("Protocol")
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.ProtocolID);
return rulingForViolation;
}
}
public static IProtocol GetProtocolDetails(Protocol protocol)
{
switch (protocol.ProtocolTypeID)
{
case (int)ProtocolsType.DEFINITION:
return GetDefinition(protocol);
case (int)ProtocolsType.INJUCTION:
return GetInjuctuion(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_ARREST:
return GetProtocolAboutArrest(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_BRINGING:
return GetProtocolAboutBringing(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION:
return GetProtocolAboutInspection(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION_AUTO:
return GetProtocolAboutInspectionAuto(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION_ORGANISATION:
return GetProtocolAboutInspectionOrganisation(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_VIOLATION_ORGANISATION:
return GetProtocolAboutViolationOrganisation(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_VIOLATION_PERSONE:
return GetProtocolAboutViolationPersone(protocol);
case (int)ProtocolsType.PROTOCOL_ABOUT_WITHDRAW:
return GetProtocolAboutWithdraw(protocol);
case (int)ProtocolsType.RULING_FOR_VIOLATION:
return GetRulingForViolation(protocol);
}
return null;
}
public static IProtocol GetProtocolDetails(int id)
{
Protocol protocol = GetProtocol(id);
if (protocol == null) return null;
return GetProtocolDetails(protocol);
}
#endregion
#region Удаление протоколов и нарушений
private static bool RemoveProtocol(int id, LeoBaseContext db)
{
var violators = db.Violators.Where(v => v.Protocol.ProtocolID == id);
var protocol = db.Protocols.FirstOrDefault(p => p.ProtocolID == id);
if (protocol == null) return false;
switch (protocol.ProtocolTypeID)
{
case (int)ProtocolsType.INJUCTION:
var injenction = db.Injunctions.Include("InjuctionsItem")
.FirstOrDefault(i => i.Protocol.ProtocolID == id);
if (injenction != null) {
db.InjunctionItems.RemoveRange(injenction.InjuctionsItem);
db.Injunctions.Remove(injenction);
}
break;
case (int)ProtocolsType.DEFINITION:
var definition = db.DefinitionsAboutViolation
.FirstOrDefault(d => d.Protocol.ProtocolID == id);
if (definition != null)
db.DefinitionsAboutViolation.Remove(definition);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_ARREST:
var protocolAboutArrest = db.ProtocolsAboutArrest
.FirstOrDefault(p => p.Protocol.ProtocolID == id);
if (protocolAboutArrest != null)
db.ProtocolsAboutArrest.Remove(protocolAboutArrest);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_BRINGING:
var protocolAboutBringing = db.ProtocolsAboutBringing
.FirstOrDefault(p => p.Protocol.ProtocolID == id);
if (protocolAboutBringing != null)
db.ProtocolsAboutBringing.Remove(protocolAboutBringing);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION:
var protocolAboutInspection = db.ProtocolsAboutInspection
.FirstOrDefault(p => p.Protocol.ProtocolID == id);
if (protocolAboutInspection != null)
db.ProtocolsAboutInspection.Remove(protocolAboutInspection);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION_AUTO:
var protocolAboutInspectionAuto = db.ProtocolsAboutInspectionAuto
.FirstOrDefault(p => p.Protocol.ProtocolID == id);
if (protocolAboutInspectionAuto != null)
db.ProtocolsAboutInspectionAuto.Remove(protocolAboutInspectionAuto);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION_ORGANISATION:
var protocolAboutInspectionOrganisation = db.ProtocolsAboutInspectionOrganisation
.FirstOrDefault(p => p.Protocol.ProtocolID == id);
if (protocolAboutInspectionOrganisation != null)
db.ProtocolsAboutInspectionOrganisation.Remove(protocolAboutInspectionOrganisation);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_VIOLATION_ORGANISATION:
var protocolAboutViolationOrganisation = db.ProtocolsAboutViolationOrganisation
.FirstOrDefault(p => p.Protocol.ProtocolID == id);
if (protocolAboutViolationOrganisation != null)
db.ProtocolsAboutViolationOrganisation.Remove(protocolAboutViolationOrganisation);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_VIOLATION_PERSONE:
var protocolAboutViolationPersone = db.ProtocolsAboutViolationPersone
.FirstOrDefault(p => p.Protocol.ProtocolID == id);
if (protocolAboutViolationPersone != null)
db.ProtocolsAboutViolationPersone.Remove(protocolAboutViolationPersone);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_WITHDRAW:
var protocolAboutWithdraw = db.ProtocolsAboutWithdraw
.FirstOrDefault(p => p.Protocol.ProtocolID == id);
if (protocolAboutWithdraw != null)
db.ProtocolsAboutWithdraw.Remove(protocolAboutWithdraw);
break;
case (int)ProtocolsType.RULING_FOR_VIOLATION:
var ruling = db.RulingsForViolation
.FirstOrDefault(r => r.Protocol.ProtocolID == id);
if (ruling != null)
db.RulingsForViolation.Remove(ruling);
break;
default:
return false;
}
db.Violators.RemoveRange(violators);
db.Protocols.Remove(protocol);
return true;
}
public static bool RemoveProtocol(int id)
{
using (var db = new LeoBaseContext())
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
if (!RemoveProtocol(id, db)) return false;
db.SaveChanges();
transaction.Commit();
return true;
}catch(Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool RemoveViolation(int violationID, LeoBaseContext db)
{
var violation = db.Violations
.FirstOrDefault(v => v.ViolationID == violationID);
if (violation == null) return false;
bool result = RemoveViolationProtocols(violationID, db);
if (!result) return false;
db.Violations.Remove(violation);
return true;
}
public static bool RemoveViolation(int violationID)
{
using(var db = new LeoBaseContext())
{
using(var transaction = db.Database.BeginTransaction())
{
try
{
if (!RemoveViolation(violationID, db)) return false;
db.SaveChanges();
transaction.Commit();
return true;
}catch(Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
public static bool RemoveViolationProtocols(int violationID, LeoBaseContext db)
{
List<int> protocolsIds = db.Protocols.Where(p => p.ViolationID == violationID)
.Select(p => p.ProtocolID)
.ToList();
if (protocolsIds == null) return false;
foreach (var idP in protocolsIds)
if (!RemoveProtocol(idP, db)) return false;
return true;
}
public static bool RemoveViolationProtocols(int violationID)
{
List<int> protocolsIds = new List<int>();
using(var db = new LeoBaseContext())
{
using(var transaction = db.Database.BeginTransaction()) {
try {
return RemoveViolationProtocols(violationID, db);
}catch(Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
#endregion
#region Обновление протоколов и нарушений
public static bool UpdateDefinition(IProtocol protocol, LeoBaseContext db)
{
if (!(protocol is DefinitionAboutViolation))
throw new ArgumentException("Документ не является определением о возбуждение административного расследования");
var definition = (DefinitionAboutViolation)protocol;
var definitionUpdate = db.DefinitionsAboutViolation.FirstOrDefault(d => d.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (definitionUpdate == null) return false;
var violator = db.Violators.FirstOrDefault(v => v.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (violator != null)
{
violator.ViolationID = definition.Protocol.ViolationID;
if (definition.OrganisationID != 0)
{
var organisation = db.Organisations.FirstOrDefault(o => o.OrganisationID == definition.OrganisationID);
if (organisation == null) return false;
violator.PersoneID = organisation.OrganisationID;
violator.ViolatorType = "Организация";
violator.ViolationID = definition.Protocol.ViolationID;
}
else if (definition.ViolatorDocumentID != 0)
{
var document = db.Documents.Include("Persone").FirstOrDefault(d => d.DocumentID == definition.ViolatorDocumentID);
if (document == null) return false;
violator.PersoneID = document.Persone.UserID;
violator.ViolatorType = "Гражданин";
violator.ViolationID = definition.Protocol.ViolationID;
}
}
definitionUpdate.FindedAmmunitions = definition.FindedAmmunitions;
definitionUpdate.FindedDocuments = definition.FindedDocuments;
definitionUpdate.FindedGunsHuntingAndFishing = definition.FindedGunsHuntingAndFishing;
definitionUpdate.FindedNatureManagementProducts = definition.FindedNatureManagementProducts;
definitionUpdate.FindedWeapons = definition.FindedWeapons;
definitionUpdate.FixingMethods = definition.FixingMethods;
definitionUpdate.KOAP = definition.FixingMethods;
definitionUpdate.OrganisationID = definition.OrganisationID;
definitionUpdate.ViolatorDocumentID = definition.ViolatorDocumentID;
return true;
}
public static bool UpdateInjunction(IProtocol protocol, LeoBaseContext db)
{
if (!(protocol is Injunction))
throw new ArgumentException("Документ не является предписанием");
var injunction = (Injunction)protocol;
var injunctionUpdate = db.Injunctions.Include("InjuctionsItem")
.FirstOrDefault(i => i.InjunctionID == injunction.InjunctionID);
if (injunctionUpdate == null)
return false;
if(injunction.InjuctionsItem != null)
{
var injunctionItemsForRemove = injunctionUpdate.InjuctionsItem;
if(injunctionItemsForRemove != null)
db.InjunctionItems.RemoveRange(injunctionItemsForRemove);
injunctionUpdate.InjuctionsItem = injunction.InjuctionsItem;
}
var document = db.Documents.Include("Persone").FirstOrDefault(d => d.DocumentID == injunction.ViolatorDocumentID);
var violator = db.Violators.FirstOrDefault(v => v.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if(document != null && violator != null)
{
violator.PersoneID = document.Persone.UserID;
violator.ViolationID = injunction.Protocol.ViolationID;
}
injunctionUpdate.ActInspectionDate = injunction.ActInspectionDate;
injunctionUpdate.ActInspectionNumber = injunction.ActInspectionNumber;
injunctionUpdate.InjunctionInfo = injunction.InjunctionInfo;
injunctionUpdate.ViolatorDocumentID = injunction.ViolatorDocumentID;
return true;
}
public static bool UpdateProtocolAboutArrest(IProtocol protocol, LeoBaseContext db)
{
if (!(protocol is ProtocolAboutArrest))
throw new ArgumentException("Протокол не является протоколом об аресте");
var protocolAboutArrest = (ProtocolAboutArrest)protocol;
var protocolAboutArrestUpdate = db.ProtocolsAboutArrest.FirstOrDefault(p => p.ProtocolAboutArrestID == protocolAboutArrest.ProtocolAboutArrestID);
if (protocolAboutArrestUpdate == null) return false;
var document = db.Documents.Include("Persone").FirstOrDefault(d => d.DocumentID == protocolAboutArrest.ViolatorDocumentID);
if (document == null) return false;
var violator = db.Violators.FirstOrDefault(v => v.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (violator == null) return false;
violator.PersoneID = document.Persone.UserID;
violator.ViolationID = protocol.Protocol.ViolationID;
protocolAboutArrestUpdate.AboutCar = protocolAboutArrest.AboutCar;
protocolAboutArrestUpdate.AboutOtherThings = protocolAboutArrest.AboutOtherThings;
protocolAboutArrestUpdate.AboutViolator = protocolAboutArrest.AboutViolator;
protocolAboutArrestUpdate.FixingMethods = protocolAboutArrest.FixingMethods;
protocolAboutArrestUpdate.ThingsWasTransfer = protocolAboutArrest.ThingsWasTransfer;
protocolAboutArrestUpdate.ViolatorDocumentID = protocolAboutArrest.ViolatorDocumentID;
return true;
}
public static bool UpdateProtocolAboutBringing(IProtocol protocol, LeoBaseContext db)
{
if (!(protocol is ProtocolAboutBringing))
throw new ArgumentException("Протокол не является протоколом о доставление.");
var protocolAboutBringing = (ProtocolAboutBringing)protocol;
var protocolAboutBringingUpdate = db.ProtocolsAboutBringing.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (protocolAboutBringingUpdate == null) return false;
var document = db.Documents.Include("Persone").FirstOrDefault(d => d.DocumentID == protocolAboutBringing.ViolatorDocumentID);
if (document == null) return false;
var violator = db.Violators.FirstOrDefault(v => v.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (violator == null) return false;
violator.ViolationID = protocol.Protocol.ViolationID;
violator.PersoneID = document.Persone.UserID;
protocolAboutBringingUpdate.FindedAmmunitions = protocolAboutBringing.FindedAmmunitions;
protocolAboutBringingUpdate.FindedDocuments = protocolAboutBringing.FindedDocuments;
protocolAboutBringingUpdate.FindedGunsHuntingAndFishing = protocolAboutBringing.FindedGunsHuntingAndFishing;
protocolAboutBringingUpdate.FindedNatureManagementProducts = protocolAboutBringing.FindedNatureManagementProducts;
protocolAboutBringingUpdate.FindedWeapons = protocolAboutBringing.FindedWeapons;
protocolAboutBringingUpdate.FixingMethods = protocolAboutBringing.FixingMethods;
protocolAboutBringingUpdate.ViolatorDocumentID = protocolAboutBringing.ViolatorDocumentID;
protocolAboutBringingUpdate.WithdrawAmmunitions = protocolAboutBringing.WithdrawAmmunitions;
protocolAboutBringingUpdate.WithdrawDocuments = protocolAboutBringing.WithdrawDocuments;
protocolAboutBringingUpdate.WithdrawGunsHuntingAndFishing = protocolAboutBringing.WithdrawGunsHuntingAndFishing;
protocolAboutBringingUpdate.WithdrawNatureManagementProducts = protocolAboutBringing.WithdrawNatureManagementProducts;
protocolAboutBringingUpdate.WithdrawWeapons = protocolAboutBringing.WithdrawWeapons;
return true;
}
public static bool UpdateProtocolAboutInspection(IProtocol protocol, LeoBaseContext db)
{
if (!(protocol is ProtocolAboutInspection))
throw new ArgumentException("Протокол не является протоколом о личном досмотре");
var protocolAboutInspection = (ProtocolAboutInspection)protocol;
var protocolAboutInspectionUpdate = db.ProtocolsAboutInspection.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
var document = db.Documents
.Include("Persone")
.FirstOrDefault(d => d.DocumentID == protocolAboutInspection.ViolatorDocumentID);
if (document == null) return false;
var violator = db.Violators.FirstOrDefault(v => v.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (violator == null) return false;
violator.ViolationID = protocol.Protocol.ViolationID;
violator.PersoneID = document.Persone.UserID;
protocolAboutInspectionUpdate.FindedAmmunitions = protocolAboutInspection.FindedAmmunitions;
protocolAboutInspectionUpdate.FindedDocuments = protocolAboutInspection.FindedDocuments;
protocolAboutInspectionUpdate.FindedGunsHuntingAndFishing = protocolAboutInspection.FindedGunsHuntingAndFishing;
protocolAboutInspectionUpdate.FindedNatureManagementProducts = protocolAboutInspection.FindedNatureManagementProducts;
protocolAboutInspectionUpdate.FindedWeapons = protocolAboutInspection.FindedWeapons;
protocolAboutInspectionUpdate.FixingMethods = protocolAboutInspection.FixingMethods;
protocolAboutInspectionUpdate.ViolatorDocumentID = protocolAboutInspection.ViolatorDocumentID;
return true;
}
public static bool UpdateProtocolAboutInspectionAuto(IProtocol protocol, LeoBaseContext db)
{
if (!(protocol is ProtocolAboutInspectionAuto))
throw new ArgumentException("Протокол не ялвяется протоколом о досмотре транспортного средства");
var protocolAboutInspectionAuto = (ProtocolAboutInspectionAuto)protocol;
var protocolAboutInspectionAutoUpdate = db.ProtocolsAboutInspectionAuto
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
var document = db.Documents.Include("Persone")
.FirstOrDefault(d => d.DocumentID == protocolAboutInspectionAuto.ViolatorDocumentID);
if (document == null) return false;
var violator = db.Violators.FirstOrDefault(v => v.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (violator == null) return false;
violator.ViolationID = protocol.Protocol.ViolationID;
violator.PersoneID = document.Persone.UserID;
protocolAboutInspectionAutoUpdate.FindedAmmunitions = protocolAboutInspectionAuto.FindedAmmunitions;
protocolAboutInspectionAutoUpdate.FindedDocuments = protocolAboutInspectionAuto.FindedDocuments;
protocolAboutInspectionAutoUpdate.FindedGunsHuntingAndFishing = protocolAboutInspectionAuto.FindedGunsHuntingAndFishing;
protocolAboutInspectionAutoUpdate.FindedNatureManagementProducts = protocolAboutInspectionAuto.FindedNatureManagementProducts;
protocolAboutInspectionAutoUpdate.FindedWeapons = protocolAboutInspectionAuto.FindedWeapons;
protocolAboutInspectionAutoUpdate.FixingMethods = protocolAboutInspectionAuto.FixingMethods;
protocolAboutInspectionAutoUpdate.InformationAbouCar = protocolAboutInspectionAuto.InformationAbouCar;
protocolAboutInspectionAutoUpdate.ViolatorDocumentID = protocolAboutInspectionAuto.ViolatorDocumentID;
return true;
}
public static bool UpdateProtocolAboutInspectionOrganisation(IProtocol protocol, LeoBaseContext db)
{
if (!(protocol is ProtocolAboutInspectionOrganisation))
throw new ArgumentException("Протокол не является протоколом осмтра оргнизации");
var protocolAboutInspectionOrganisation = (ProtocolAboutInspectionOrganisation)protocol;
var protocolAboutInspectionOrganisationUpdate = db.ProtocolsAboutInspectionOrganisation
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
var violator = db.Violators.FirstOrDefault(v => v.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (violator == null) return false;
violator.PersoneID = protocolAboutInspectionOrganisation.OrganisationID;
violator.ViolationID = protocolAboutInspectionOrganisation.Protocol.ViolationID;
protocolAboutInspectionOrganisationUpdate.FindedAmmunitions = protocolAboutInspectionOrganisation.FindedAmmunitions;
protocolAboutInspectionOrganisationUpdate.FindedDocuments = protocolAboutInspectionOrganisation.FindedDocuments;
protocolAboutInspectionOrganisationUpdate.FindedGunsHuntingAndFishing = protocolAboutInspectionOrganisation.FindedGunsHuntingAndFishing;
protocolAboutInspectionOrganisationUpdate.FindedNatureManagementProducts = protocolAboutInspectionOrganisation.FindedNatureManagementProducts;
protocolAboutInspectionOrganisationUpdate.FindedWeapons = protocolAboutInspectionOrganisation.FindedWeapons;
protocolAboutInspectionOrganisationUpdate.FixingMethods = protocolAboutInspectionOrganisation.FixingMethods;
protocolAboutInspectionOrganisationUpdate.InspectionTerritoryes = protocolAboutInspectionOrganisation.InspectionTerritoryes;
protocolAboutInspectionOrganisationUpdate.OrganisationID = protocolAboutInspectionOrganisation.OrganisationID;
return true;
}
public static bool UpdateProtocolAboutViolationOrganisation(IProtocol protocol, LeoBaseContext db)
{
if (!(protocol is ProtocolAboutViolationOrganisation))
throw new ArgumentException("Протокол не является протоколом за административное правонарушение организацией");
var protocolAboutViolationOrganisation = (ProtocolAboutViolationOrganisation)protocol;
var protocolAboutViolationOrganisationUpdate = db.ProtocolsAboutViolationOrganisation
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
var violator = db.Violators.FirstOrDefault(v => v.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (violator == null) return false;
violator.ViolationID = protocol.Protocol.ViolationID;
violator.PersoneID = protocolAboutViolationOrganisation.OrganisationID;
protocolAboutViolationOrganisationUpdate.Description = protocolAboutViolationOrganisation.Description;
protocolAboutViolationOrganisationUpdate.KOAP = protocolAboutViolationOrganisation.KOAP;
protocolAboutViolationOrganisationUpdate.OrganisationID = protocolAboutViolationOrganisation.OrganisationID;
protocolAboutViolationOrganisationUpdate.ViolationTime = protocolAboutViolationOrganisation.ViolationTime;
return true;
}
public static bool UpdateProtocolAboutViolationPersone(IProtocol protocol, LeoBaseContext db)
{
if (!(protocol is ProtocolAboutViolationPersone))
throw new ArgumentException("Документ не является протоколом о административном правонарушение");
var protocolAboutViolation = (ProtocolAboutViolationPersone)protocol;
var protocolAboutViolationUpdate = db.ProtocolsAboutViolationPersone
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
var document = db.Documents.Include("Persone")
.FirstOrDefault(d => d.DocumentID == protocolAboutViolation.ViolatorDocumentID);
if (document == null) return false;
var violator = db.Violators.FirstOrDefault(v => v.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (violator == null) return false;
violator.PersoneID = document.Persone.UserID;
violator.ViolationID = protocol.Protocol.ViolationID;
protocolAboutViolationUpdate.FindedGunsHuntingAndFishing = protocolAboutViolation.FindedGunsHuntingAndFishing;
protocolAboutViolationUpdate.FindedNatureManagementProducts = protocolAboutViolation.FindedNatureManagementProducts;
protocolAboutViolationUpdate.FindedWeapons = protocolAboutViolation.FindedWeapons;
protocolAboutViolationUpdate.KOAP = protocolAboutViolation.KOAP;
protocolAboutViolationUpdate.ViolationDate = protocolAboutViolation.ViolationDate;
protocolAboutViolationUpdate.ViolationDescription = protocolAboutViolation.ViolationDescription;
protocolAboutViolationUpdate.ViolatorDocumentID = protocolAboutViolation.ViolatorDocumentID;
return true;
}
public static bool UpdateProtocolAboutWithdraw(IProtocol protocol, LeoBaseContext db)
{
if (!(protocol is ProtocolAboutWithdraw))
throw new ArgumentException("Документ не является протоколом об изъятии");
var protocolAboutWithdraw = (ProtocolAboutWithdraw)protocol;
var protocolAboutWithdrawUpdate = db.ProtocolsAboutWithdraw
.FirstOrDefault(p => p.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
var document = db.Documents.Include("Persone")
.FirstOrDefault(d => d.DocumentID == protocolAboutWithdraw.ViolatorDocumentID);
if (document == null) return false;
var violator = db.Violators.FirstOrDefault(v => v.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (violator == null) return false;
violator.PersoneID = document.Persone.UserID;
violator.ViolationID = protocol.Protocol.ViolationID;
protocolAboutWithdrawUpdate.FixingMethods = protocolAboutWithdraw.FixingMethods;
protocolAboutWithdrawUpdate.ViolatorDocumentID = protocolAboutWithdraw.ViolatorDocumentID;
protocolAboutWithdrawUpdate.WithdrawAmmunitions = protocolAboutWithdraw.WithdrawAmmunitions;
protocolAboutWithdrawUpdate.WithdrawDocuments = protocolAboutWithdraw.WithdrawDocuments;
protocolAboutWithdrawUpdate.WithdrawGunsHuntingAndFishing = protocolAboutWithdraw.WithdrawGunsHuntingAndFishing;
protocolAboutWithdrawUpdate.WithdrawNatureManagementProducts = protocolAboutWithdraw.WithdrawNatureManagementProducts;
protocolAboutWithdrawUpdate.WithdrawWeapons = protocolAboutWithdraw.WithdrawWeapons;
return true;
}
public static bool UpdateRuling(IProtocol protocol, LeoBaseContext db)
{
if (!(protocol is RulingForViolation))
throw new ArgumentException("Документ не является постановлением по делу об административном правонарушение");
var ruling = (RulingForViolation)protocol;
var rulingUpdate = db.RulingsForViolation.FirstOrDefault(r => r.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
var violator = db.Violators.FirstOrDefault(v => v.Protocol.ProtocolID == protocol.Protocol.ProtocolID);
if (violator == null) return false;
if (ruling.OrganisationID != 0)
{
violator.PersoneID = ruling.OrganisationID;
violator.ViolatorType = "Организация";
violator.ViolationID = protocol.Protocol.ViolationID;
}
else if (ruling.ViolatorDocumentID != 0)
{
var document = db.Documents.Include("Persone")
.FirstOrDefault(p => p.DocumentID == ruling.ViolatorDocumentID);
if (document == null) return false;
violator.PersoneID = document.Persone.UserID;
violator.ViolatorType = "Гражданин";
violator.ViolationID = protocol.Protocol.ViolationID;
}
else
{
return false;
}
rulingUpdate.AboutArrest = ruling.AboutArrest;
rulingUpdate.BankDetails = ruling.BankDetails;
rulingUpdate.Damage = ruling.Damage;
rulingUpdate.Fine = ruling.Fine;
rulingUpdate.FixingDate = ruling.FixingDate;
rulingUpdate.FixingInfo = ruling.FixingInfo;
rulingUpdate.KOAP = ruling.KOAP;
rulingUpdate.Number = ruling.Number;
rulingUpdate.OrganisationID = ruling.OrganisationID;
rulingUpdate.Products = ruling.Products;
rulingUpdate.ProductsPrice = ruling.ProductsPrice;
rulingUpdate.ViolatorDocumentID = ruling.ViolatorDocumentID;
return true;
}
public static bool UpdateProtocol(IProtocol protocol)
{
using(var db = new LeoBaseContext())
{
using(var transaction = db.Database.BeginTransaction())
{
try
{
// 1. Обновление общей информации по протоколу
var updatedProtocol = db.Protocols.FirstOrDefault(p => p.ProtocolID == protocol.Protocol.ProtocolID);
if (updatedProtocol == null) return false;
// Обновление общей информации по протоколу
updatedProtocol.PlaceCreatedProtocol = protocol.Protocol.PlaceCreatedProtocol;
updatedProtocol.EmployerID = protocol.Protocol.EmployerID;
updatedProtocol.DateUpdate = DateTime.Now;
updatedProtocol.DateSave = protocol.Protocol.DateSave;
updatedProtocol.DateCreatedProtocol = protocol.Protocol.DateCreatedProtocol;
updatedProtocol.PlaceCreatedProtocolE = protocol.Protocol.PlaceCreatedProtocolE;
updatedProtocol.PlaceCreatedProtocolN = protocol.Protocol.PlaceCreatedProtocolN;
updatedProtocol.ViolationID = protocol.Protocol.ViolationID;
updatedProtocol.WitnessFIO_1 = protocol.Protocol.WitnessFIO_1;
updatedProtocol.WitnessFIO_2 = protocol.Protocol.WitnessFIO_2;
updatedProtocol.WitnessLive_1 = protocol.Protocol.WitnessLive_1;
updatedProtocol.WitnessLive_2 = protocol.Protocol.WitnessLive_2;
bool result = true;
switch (updatedProtocol.ProtocolTypeID)
{
case (int)ProtocolsType.DEFINITION:
result = UpdateDefinition(protocol, db);
break;
case (int)ProtocolsType.INJUCTION:
result = UpdateInjunction(protocol, db);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_ARREST:
result = UpdateProtocolAboutArrest(protocol, db);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_BRINGING:
result = UpdateProtocolAboutBringing(protocol, db);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION:
result = UpdateProtocolAboutInspection(protocol, db);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION_AUTO:
result = UpdateProtocolAboutInspectionAuto(protocol, db);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_INSPECTION_ORGANISATION:
result = UpdateProtocolAboutInspectionOrganisation(protocol, db);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_VIOLATION_ORGANISATION:
result = UpdateProtocolAboutViolationOrganisation(protocol, db);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_VIOLATION_PERSONE:
result = UpdateProtocolAboutViolationPersone(protocol, db);
break;
case (int)ProtocolsType.PROTOCOL_ABOUT_WITHDRAW:
result = UpdateProtocolAboutWithdraw(protocol, db);
break;
case (int)ProtocolsType.RULING_FOR_VIOLATION:
result = UpdateRuling(protocol, db);
break;
default:
return false;
}
if (!result) return false;
db.SaveChanges();
transaction.Commit();
return true;
}catch(Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
#endregion
}
}
<file_sep>/LeoBase/Components/CustomControls/LoadedControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
namespace LeoBase.Components.CustomControls
{
public partial class LoadedControl : UserControl, ILoadedControl
{
public LoadedControl()
{
InitializeComponent();
}
public bool ShowForResult
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public List<Control> TopControls
{
get
{
return new List<Control> { };
}
set
{
}
}
public Control GetControl()
{
return this;
}
void UIComponent.Resize(int width, int height)
{
}
}
}
<file_sep>/AppGUI/App.xaml.cs
using AppGUI.Infrastructure;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using WPFPresentators.Presentators;
using WPFPresentators.Views.Windows;
namespace AppGUI
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
ComponentsFactory factory = new ComponentsFactory();
MainPresentator mainPresentator = new MainPresentator(factory);
}
}
}
<file_sep>/AppCore/FakesRepositoryes/FakeDocumentRespository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
namespace AppData.FakesRepositoryes
{
public class FakeDocumentRespository : IDocumentRepository
{
private List<Document> _documents = new List<Document>
{
new Document
{
DocumentID = 1,
//DocumentTypeID = 1,
//UserID = 1,
Serial = "111",
Number = "123",
IssuedBy = "Выдан 1",
WhenIssued = new DateTime(2016, 11, 11, 0, 0, 0),//"11.11.2016",
CodeDevision = "234"
},
new Document
{
DocumentID = 2,
//DocumentTypeID = 1,
//UserID = 2,
Serial = "212",
Number = "126",
IssuedBy = "<NAME>",
WhenIssued = new DateTime(2015, 11, 11, 0, 0, 0)//"11.11.2015"
},
new Document
{
DocumentID = 3,
//DocumentTypeID = 2,
//UserID = 2,
Serial = "322",
Number = "125",
IssuedBy = "<NAME>",
WhenIssued = new DateTime(2015, 11, 12, 0, 0, 0)//"11.12.2015"
},
new Document
{
DocumentID = 4,
//DocumentTypeID = 1,
//UserID = 3,
Serial = "413",
Number = "127",
IssuedBy = "<NAME>",
WhenIssued = new DateTime(2016, 11, 5, 0, 0, 0),//"5.11.2016",
CodeDevision = "2341"
},
new Document
{
DocumentID = 5,
//DocumentTypeID = 2,
//UserID = 4,
Serial = "524",
Number = "223",
IssuedBy = "<NAME>",
WhenIssued = new DateTime(2012, 11, 11, 0, 0, 0)//"11.11.2012"
},
new Document
{
DocumentID = 6,
//DocumentTypeID = 1,
//UserID = 5,
Serial = "524",
Number = "12312",
IssuedBy = "<NAME>",
WhenIssued = new DateTime(2011, 7, 9, 0, 0, 0)//"09.7.2011"
}
};
public IQueryable<Document> Documents
{
get
{
return _documents.AsQueryable();
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/AdminintrationViolationTableControl.cs
using AppPresentators.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Services;
using AppPresentators.VModels;
using System.Windows.Forms;
using AppPresentators;
using System.Drawing;
using LeoBase.Components.CustomControls.SearchPanels;
using LeoBase.Components.TopMenu;
namespace LeoBase.Components.CustomControls
{
public class AdminintrationViolationTableControl : CustomTablePage, IAdminViolationControl
{
private List<AdminViolationRowModel> _dataContext;
public int SelectedID { get; private set; }
private CustomTable _customTable;
public List<AdminViolationRowModel> DataContext
{
get
{
return _dataContext;
}
set
{
_dataContext = value;
_customTable.SetData<AdminViolationRowModel>(value);
if (_tpControls != null)
{
if (value == null || value.Count == 0)
{
_tpControls.EnabledDelete = false;
_tpControls.EnabledDetails = false;
_tpControls.EnabledEdit = false;
}
}
//_customTable.AddComboBox(new List<string> { "Оплачен", "Не оплачен" }, "Оплата", "SelectedPaymentText");
}
}
AdminViolationOrderModel _orderModel;
public AdminViolationOrderModel OrederModel
{
get
{
_orderModel = new AdminViolationOrderModel
{
OrderBy = (AdminViolationOrderTypes)_customTable.SelectedOrderBy,
OrderType = _customTable.OrderType
};
return _orderModel;
}
}
private PageModel _pageModel;
public PageModel PageModel
{
get
{
if (_pageModel == null) _pageModel = new PageModel();
_pageModel.ItemsOnPage = 10;
_pageModel = _customTable.PageModel;
return _pageModel;
}
set
{
_pageModel = value;
_customTable.PageModel = value;
}
}
public AdminViolationSearchModel SearchModel
{
get
{
return (AdminViolationSearchModel)_searhcPanel.DataSource;
}
}
public bool ShowForResult { get; set; }
public event Action AddViolation;
public event ViolationEvent EditViolation;
public event ViolationEvent RemoveViolation;
public event ViolationEvent ShowDetailsViolation;
public event Action UpdateTable;
public event Action BuildReport;
private AutoBinderPanel _searhcPanel;
private Dictionary<string, int> _orderProperties;
private Dictionary<string, OrderType> _orderTypes;
private int _selectedIndex = -1;
public AdminintrationViolationTableControl() : base()
{
MakeTopControls();
_orderProperties = new Dictionary<string, int>();
_orderTypes = new Dictionary<string, OrderType>();
_orderProperties.Add("Нарушитель", (int)AdminViolationOrderTypes.VIOLATOR);
_orderProperties.Add("Инспектор", (int)AdminViolationOrderTypes.EMPLOYER);
_orderProperties.Add("Дата рассмотрения", (int)AdminViolationOrderTypes.DATE_CONSIDERATION);
_orderProperties.Add("Нарешение", (int)AdminViolationOrderTypes.VIOLATION);
_orderProperties.Add("Сумма наложения", (int)AdminViolationOrderTypes.SUM_VIOLATION);
_orderProperties.Add("Сумма взыскания", (int)AdminViolationOrderTypes.SUM_RECOVERY);
Title = "Нарушения";
_orderTypes.Add("Убывание", OrderType.ASC);
_orderTypes.Add("Возростание", OrderType.DESC);
_customTable = new CustomTable();
_customTable.OrderProperties = (Dictionary<string, int>)_orderProperties;
_customTable.SelectedItemChange += _customTable_SelectedItemChange;
_customTable.OnRowWasCreted += RowWasCreated;
_customTable.UpdateTable += () => UpdateTable();
_customTable.SelectedItemChange += (index) =>
{
if (index != -1)
{
_tpControls.EnabledDelete = true;
_tpControls.EnabledDetails = true;
_tpControls.EnabledEdit = true;
}
else
{
_tpControls.EnabledDelete = false;
_tpControls.EnabledDetails = false;
_tpControls.EnabledEdit = false;
}
_selectedIndex = index;
};
_customTable.DoubleClick += () =>
{
if (!ShowForResult && ShowDetailsViolation != null) ShowDetailsViolation(SelectedID);
};
this.AutoSize = true;
_searhcPanel = new AutoBinderPanel();
_searhcPanel.DataSource = new AdminViolationSearchModel();
var searchPanel = new SearchPanelContainer();
searchPanel.SetCustomSearchPanel(_searhcPanel);
AddSearchPanel(searchPanel);
_searhcPanel.DataSourceChanged += (s, e) =>
{
if (UpdateTable != null) UpdateTable();
};
searchPanel.OnSearchClick += () =>
{
if (UpdateTable != null) UpdateTable();
};
SetContent(_customTable);
}
private void RowWasCreated(DataGridViewRow row)
{
var v = (AdminViolationRowModel)(row.DataBoundItem);
if(v.SumRecovery == v.SumViolation)
{
row.DefaultCellStyle.BackColor = Color.FromArgb(223, 240, 216);
}else if(v.SumRecovery < v.SumViolation && (DateTime.Now - v.Consideration).Days > 70)
{
row.DefaultCellStyle.BackColor = Color.FromArgb(242, 222, 222);
}else if((DateTime.Now - v.Consideration).Days < 70)
{
row.DefaultCellStyle.BackColor = Color.FromArgb(252, 248, 227);
}
}
private void _customTable_SelectedItemChange(int index)
{
if (index != -1)
{
_btnUpdate.Enabled = true;
_btnRemove.Enabled = true;
_btnDetails.Enabled = true;
}
else
{
_btnUpdate.Enabled = false;
_btnRemove.Enabled = false;
_btnDetails.Enabled = false;
}
if (index >= 0 && index < DataContext.Count) SelectedID = DataContext[index].ViolationID;
}
public Control GetControl()
{
return this;
}
public DialogResult ShowConfitmDialog(string message, string title = null)
{
return MessageBox.Show(message, title, MessageBoxButtons.OKCancel);
}
void UIComponent.Resize(int width, int height)
{
}
private Button _btnReport = new Button();
private Button _btnAddNew = new Button();
private Button _btnRemove = new Button();
private Button _btnDetails = new Button();
private Button _btnUpdate = new Button();
private TopControls _tpControls;
private void MakeTopControls()
{
_tpControls = new TopControls(ConfigApp.CurrentManager.Role);
_tpControls.DetailsItem += () =>
{
if (_selectedIndex < 0 || _selectedIndex >= _dataContext.Count || _dataContext.Count == 0) return;
if (ShowDetailsViolation != null) ShowDetailsViolation(SelectedID);
};
_tpControls.EditItem += () =>
{
if (_selectedIndex < 0 || _selectedIndex >= _dataContext.Count || _dataContext.Count == 0) return;
if (EditViolation != null) EditViolation(SelectedID);
};
_tpControls.DeleteItem += () =>
{
if (_selectedIndex < 0 || _selectedIndex >= _dataContext.Count || _dataContext.Count == 0) return;
if (MessageBox.Show("Вы уверены что хотите удалить правонарушение?", "Предупреждение", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.OK)
{
if (RemoveViolation != null)
{
RemoveViolation(SelectedID);
if (_dataContext.Count == 0)
{
_selectedIndex = -1;
_tpControls.EnabledDelete = false;
_tpControls.EnabledDetails = false;
_tpControls.EnabledEdit = false;
}
}
}
};
_tpControls.AddItem += () => {
if (AddViolation != null)
AddViolation();
};
_tpControls.ReportItem += () =>
{
if(BuildReport != null)
{
BuildReport();
}
};
_tpControls.EnabledDelete = false;
_tpControls.EnabledDetails = false;
_tpControls.EnabledEdit = false;
_tpControls.EnabledAdd = true;
_tpControls.EnabledReport = true;
_topControls = _tpControls;
}
private List<Control> _topControls;
public List<Control> TopControls
{
get
{
return _topControls;
}
set
{
_topControls = value;
}
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// AdminintrationViolationTableControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Name = "AdminintrationViolationTableControl";
this.Size = new System.Drawing.Size(1250, 701);
this.VisibleLoadPanel = true;
this.ResumeLayout(false);
}
public void LoadStart()
{
_customTable.Visible = false;
VisibleLoadPanel = true;
}
public void LoadEnd()
{
try {
VisibleLoadPanel = false;
_customTable.Visible = true;
}catch(Exception e)
{
}
}
}
}
<file_sep>/LeoMapV3/Models/MapRegion.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoMapV3.Models
{
public class MapRegion
{
public double N { get; set; }
public double E { get; set; }
public double W { get; set; }
public double S { get; set; }
public override string ToString()
{
return string.Format("E:{0:0.0000000}; N:{1:0.0000000}; W:{2:0.0000000}; S:{3:0.0000000}", E, N, W, S);
}
}
}
<file_sep>/AppCore/Abstract/IEmployerRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract
{
public interface IEmployerRepository
{
IQueryable<Employer> Employers { get; }
int SaveEmployer(Employer employer);
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/ProtocolsPresentators/IRulingForViolationPresentator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces.ProtocolsPresentators
{
public interface IRulingForViolationPresentator:IProtocolPresentator
{
}
}
<file_sep>/AppCore/Repositrys/Violations/ViolationRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations
{
public class ViolationRepository : IViolationRepository
{
public IQueryable<Violation> Violations
{
get
{
var context = new LeoBaseContext();
return context.Violations;
}
}
public bool AddViolation(Violation violation)
{
using(var db = new LeoBaseContext())
{
db.Violations.Add(violation);
db.SaveChanges();
return true;
}
}
public bool UpdateViolation(Violation violation)
{
using(var db = new LeoBaseContext())
{
using(var transaction = db.Database.BeginTransaction())
{
try
{
var violationForSave = db.Violations
.Include("Images")
.FirstOrDefault(v => v.ViolationID == violation.ViolationID);
if (violationForSave == null) return false;
if (violation.Images != null)
{
// Если изображения не пустые, то удаляем старые из базы, и сохраняем новые
var imagesForRemove = violationForSave.Images;
db.ViolationImages.RemoveRange(imagesForRemove);
violationForSave.Images = violation.Images;
}
violationForSave.Date = violation.Date;
violationForSave.DateUpdate = DateTime.Now;
violationForSave.Description = violation.Description;
violationForSave.E = violation.E;
violationForSave.N = violation.N;
violationForSave.ViolationType = violation.ViolationType;
db.SaveChanges();
transaction.Commit();
return true;
}catch(Exception e)
{
transaction.Rollback();
}
}
}
return false;
}
}
}
<file_sep>/AppPresentators/Components/IEditPassControl.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public interface IEditPassControl:UIComponent
{
Pass Pass { get; set; }
event Action Save;
void ShowMessage(string message);
void ShowError(string message);
}
}
<file_sep>/TestConsoleApp/TestDB/TestContext.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestConsoleApp.TestDB
{
public class TestContext: DbContext
{
public TestContext():base("DataSource='TestDataBase';Password='<PASSWORD>'") { }
public DbSet<Persone> Persons { get; set; }
}
public class Persone
{
[Key]
public int PersoneID { get; set; }
public string Name { get; set; }
}
}
<file_sep>/AppPresentators/Presentators/MainPresentator.cs
using AppPresentators.Presentators.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Views;
using AppPresentators.VModels;
using AppPresentators.Infrastructure;
using AppPresentators.Services;
using AppPresentators.Components.MainMenu;
using AppPresentators.VModels.MainMenu;
using AppPresentators.Components;
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System.Threading;
using System.ComponentModel;
using AppData.Contexts;
namespace AppPresentators.Presentators
{
public class MainPresentator:IMainPresentator
{
public object DialogResult { get; set; }
public IVManager CurrentManager { get; set; }
private IMainView _mainView;
private IApplicationFactory _appFactory;
private static MainPresentator _instance;
public static MainPresentator GetInstance(IApplicationFactory appFactory)
{
if (_instance == null) _instance = new MainPresentator(appFactory);
return _instance;
}
public MainPresentator(IApplicationFactory appFactory)
{
_mainView = appFactory.GetMainView();
_appFactory = appFactory;
_mainView.Login += () => Login();
_mainView.FastSearchGO += () => FastSearch(_mainView.SearchQuery);
_instance = this;
_mainView.GoBackPage += () => GetBackPage();
_mainView.GoNextPage += () => GetNextPage();
}
public void ShowComponentForResult(IComponentPresentator sender, IComponentPresentator executor, ResultTypes resultType)
{
executor.ResultType = resultType;
executor.ShowForResult = true;
executor.SendResult += (t, d) =>
{
sender.SetResult(t, d);
GetBackPage();
};
SetNextPage(executor);
}
public void SendResult(IComponentPresentator recipient, ResultTypes resultType, object data)
{
}
public IMainView MainView
{
get
{
return _mainView;
}
}
public void AddMenu()
{
var user = _mainView.Manager;
if (user == null)
{
Login();
return;
}
var perService = _appFactory.GetService<IPermissonsService>();
var menuItems = perService.GetMenuItems("admin");
var mainMenu = _appFactory.GetComponent<IMainMenu>();
mainMenu.MenuItemSelected += MainMenu_MenuItemSelected;
mainMenu.AddMenuItems(menuItems);
_mainView.SetMenu(mainMenu);
mainMenu.SelecteItem(MenuCommand.Infringement);
}
private void FastSearch(string message)
{
if(_currentPresentator != null)
{
_currentPresentator.FastSearch(message);
}
}
private IComponentPresentator _currentPresentator;
private List<IComponentPresentator> _pages;
private int _currentPage;
public void SetNextPage(IComponentPresentator presentator)
{
while (_currentPage + 1 < _pages.Count)
{
_pages.RemoveAt(_currentPage + 1);
}
if(_currentPage + 1 == _pages.Count)
{
_mainView.StartTask();
_pages.Add(presentator);
_mainView.ShowFastSearch = presentator.ShowFastSearch;
_currentPage++;
_currentPresentator = presentator;
_mainView.SetTopControls(_currentPresentator.TopControls);
_mainView.SetComponent(presentator.RenderControl());
_mainView.EndTask(false);
}
}
public void GetBackPage()
{
if(_currentPage >= 1)
{
_mainView.StartTask();
_currentPage--;
_currentPresentator = _pages[_currentPage];
_mainView.ShowFastSearch = _currentPresentator.ShowFastSearch;
_mainView.SetTopControls(_currentPresentator.TopControls);
_mainView.SetComponent(_currentPresentator.RenderControl());
_mainView.EndTask(false);
}
}
public void GetNextPage()
{
if(_currentPage + 1 < _pages.Count)
{
_mainView.StartTask();
_currentPage++;
_currentPresentator = _pages[_currentPage];
_mainView.ShowFastSearch = _currentPresentator.ShowFastSearch;
_mainView.SetTopControls(_currentPresentator.TopControls);
_mainView.SetComponent(_currentPresentator.RenderControl());
_mainView.EndTask(false);
}
}
private static bool _taskWork = false;
private async void MainMenu_MenuItemSelected(MenuCommand command)
{
_mainView.StartTask();
#region Comment
if (command == MenuCommand.Employees)
{
_mainView.ClearCenter();
_currentPage = 0;
_pages = new List<IComponentPresentator>();
var presentator = _appFactory.GetPresentator<IEmployersPresentator>(_mainView);
_mainView.ShowFastSearch = presentator.ShowFastSearch;
_currentPresentator = presentator;
_mainView.SetTopControls(_currentPresentator.TopControls);
_mainView.SetComponent(_currentPresentator.RenderControl());
}
else if (command == MenuCommand.Violators)
{
_mainView.ClearCenter();
_currentPage = 0;
_pages = new List<IComponentPresentator>();
var presentator = _appFactory.GetPresentator<IViolatorTablePresentator>(_mainView);
_mainView.ShowFastSearch = presentator.ShowFastSearch;
_currentPresentator = presentator;
_mainView.SetTopControls(_currentPresentator.TopControls);
_mainView.SetComponent(_currentPresentator.RenderControl());
}
else if (command == MenuCommand.Infringement)
{
_mainView.ClearCenter();
_currentPage = 0;
_pages = new List<IComponentPresentator>();
var presentator = _appFactory.GetPresentator<IAdminViolationTablePresentator>(_mainView);
_mainView.ShowFastSearch = presentator.ShowFastSearch;
_currentPresentator = presentator;
_mainView.SetTopControls(_currentPresentator.TopControls);
_mainView.SetComponent(_currentPresentator.RenderControl());
}
else if (command == MenuCommand.Options)
{
_mainView.ClearCenter();
_currentPage = 0;
_pages = new List<IComponentPresentator>();
var presentator = _appFactory.GetPresentator<IOptionsPresentator>(_mainView);
_mainView.ShowFastSearch = presentator.ShowFastSearch;
_currentPresentator = presentator;
_mainView.SetTopControls(_currentPresentator.TopControls);
_mainView.SetComponent(_currentPresentator.RenderControl());
}
else if (command == MenuCommand.Map)
{
_mainView.ClearCenter();
_currentPage = 0;
_pages = new List<IComponentPresentator>();
var presentator = _appFactory.GetPresentator<IMapPresentator>(_mainView);
_mainView.ShowFastSearch = presentator.ShowFastSearch;
_currentPresentator = presentator;
_mainView.SetTopControls(_currentPresentator.TopControls);
_mainView.SetComponent(_currentPresentator.RenderControl());
}
else if (command == MenuCommand.Omissions)
{
_mainView.ClearCenter();
_currentPage = 0;
_pages = new List<IComponentPresentator>();
var presentator = _appFactory.GetPresentator<IPassesPresentator>(_mainView);
_mainView.ShowFastSearch = presentator.ShowFastSearch;
_currentPresentator = presentator;
_mainView.SetTopControls(_currentPresentator.TopControls);
_mainView.SetComponent(_currentPresentator.RenderControl());
}
else
{
_mainView.ShowError("Эта функция будет реализована в следующей версии программы");
return;
//_mainView.SetComponent(_appFactory.GetComponent(command).GetControl());
}
if (_currentPresentator != null)
{
_currentPage = 0;
_pages.Add(_currentPresentator);
}
_mainView.EndTask(false);
#endregion
}
public void Login()
{
_mainView.Manager = null;
var loginPresentator = _appFactory.GetPresentator<ILoginPresentator, ILoginView, ILoginService>(_mainView);
loginPresentator.LoginComplete += (m) => LoginComplete(m);
loginPresentator.Run();
}
public void LoginComplete(VManager manager)
{
_mainView.Manager = manager;
AddMenu();
}
public void Run()
{
_mainView.Show();
}
}
}
<file_sep>/AppPresentators/Services/PersonesService.cs
using AppData.Abstract;
using AppData.Entities;
using AppData.Infrastructure;
using AppPresentators.VModels;
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Services
{
public interface IPersonesService
{
PageModel PageModel { get; set; }
PersonsSearchModel SearchModel { get; set; }
SearchAddressModel AddressSearchModel { get; set; }
DocumentSearchModel DocumentSearchModel { get; set; }
PersonsOrderModel OrderModel { get; set; }
List<IPersoneViewModel> GetPersons(bool loadDeleted = false);
int AddNewPersone(IPersoneViewModel personeModel);
bool Remove(int id);
bool Remove(IPersoneViewModel model);
IPersoneViewModel GetPerson(int id, bool loadFullModel = false);
bool UpdatePersone(IPersoneViewModel persone);
bool SimpleRemove(int id);
bool SimpleRemove(IPersoneViewModel model);
Persone ConverToEnity(IPersoneViewModel model);
}
public class PersonesService : IPersonesService
{
private IPersoneRepository _personRepository;
private IPersonePositionRepository _personPositionRepository;
private IPersoneAddressRepository _personAddressRepository;
private IPhonesRepository _phonesRepository;
private IDocumentRepository _documentsRepository;
private IDocumentTypeRepository _documentsTypeRepository;
private Dictionary<int, string> _documentTypes;
private Dictionary<int, string> _positionNames;
public SearchAddressModel AddressSearchModel { get; set; }
public PersonsSearchModel SearchModel { get; set; }
public DocumentSearchModel DocumentSearchModel { get; set; }
public PersonsOrderModel OrderModel { get; set; } = new PersonsOrderModel
{
OrderType = OrderType.NONE
};
public PageModel PageModel { get; set; } = new PageModel
{
ItemsOnPage = 30,
CurentPage = 1
};
public PersonesService() : this(RepositoryesFactory.GetInstance().Get<IPersoneRepository>(),
RepositoryesFactory.GetInstance().Get<IPersonePositionRepository>(),
RepositoryesFactory.GetInstance().Get<IPersoneAddressRepository>(),
RepositoryesFactory.GetInstance().Get<IPhonesRepository>(),
RepositoryesFactory.GetInstance().Get<IDocumentRepository>(),
RepositoryesFactory.GetInstance().Get<IDocumentTypeRepository>()) { }
public PersonesService(IPersoneRepository personRepository,
IPersonePositionRepository personPositionRepository,
IPersoneAddressRepository personAddressRepository,
IPhonesRepository phoneRepository,
IDocumentRepository documentRepository,
IDocumentTypeRepository documentTypeRepository)
{
_personRepository = personRepository;
_personPositionRepository = personPositionRepository;
_personAddressRepository = personAddressRepository;
_phonesRepository = phoneRepository;
_documentsRepository = documentRepository;
_documentsTypeRepository = documentTypeRepository;
_documentTypes = new Dictionary<int, string>();
_positionNames = new Dictionary<int, string>();
foreach (var dT in _documentsTypeRepository.DocumentTypes.ToList())
{
_documentTypes.Add(dT.DocumentTypeID, dT.Name);
}
foreach(var pN in _personPositionRepository.Positions.ToList())
{
_positionNames.Add(pN.PositionID, pN.Name);
}
}
/// <summary>
/// Возвращает список представлений для граждан на основе моделей:
/// SearchModel - общая модель поиска (фамилия, имя и т.д.)
/// DocumentSearchModel - модель поиска по документу
/// AddressSearchModel - модель поиска по адресу
/// Сперва ищеться по документу, потом по адресу и в последнюю очередь по общей модели поиска
/// </summary>
/// <returns>Список представлений граждан, без подробной информации</returns>
public List<IPersoneViewModel> GetPersons(bool loadDeleted = false)
{
List<int> usersIds = new List<int>();
IQueryable<Persone> persones = _personRepository.Persons.Where(p => p.Deleted == loadDeleted);
var aa = persones.ToList();
#region Search by ID and Return
if (SearchModel != null && SearchModel.PersoneID != 0)
{
var persone = persones.FirstOrDefault(p => p.UserID == SearchModel.PersoneID);
if(persone != null)
{
bool isEmployer = persone.IsEmploeyr;
EmploeyrPosition position = null;
if (isEmployer)
{
var p = _personPositionRepository.Positions.FirstOrDefault(pos => pos.PositionID == persone.Position_PositionID);
if(p != null)
{
position = p;
}
}
if (isEmployer)
{
return new List<IPersoneViewModel>
{
new EmploeyrViewModel
{
UserID = persone.UserID,
FirstName = persone.FirstName,
SecondName = persone.SecondName,
MiddleName = persone.MiddleName,
IsEmploeyr = persone.IsEmploeyr,
DateBirthday = persone.DateBirthday,
Position = position != null ? position.Name : null,
PositionID = position != null ? position.PositionID.ToString() : "-1"
}
};
}else
{
}
}
}
#endregion
bool wasSearched = false;
#region SearchByDocument
if (DocumentSearchModel != null && !DocumentSearchModel.IsEmptySearchModel)
{
var documents = _documentsRepository.Documents;
var documentsType = _documentsTypeRepository.DocumentTypes;
if(!string.IsNullOrEmpty(DocumentSearchModel.DocumentTypeID))
{
int docTypeId = Convert.ToInt32(DocumentSearchModel.DocumentTypeID);
if(docTypeId != 0)
documents = documents.Where(d => d.Document_DocumentTypeID == docTypeId);
}
if (!string.IsNullOrEmpty(DocumentSearchModel.Serial))
{
documents = documents.Where(d => d.Serial.Equals(DocumentSearchModel.Serial));
}
if (!string.IsNullOrEmpty(DocumentSearchModel.Number))
{
documents = documents.Where(d => d.Number.Equals(DocumentSearchModel.Number));
}
if (!string.IsNullOrEmpty(DocumentSearchModel.IssuedBy))
{
if(DocumentSearchModel.CompareIssuedBy == CompareString.EQUAL)
{
documents = documents.Where(d => d.IssuedBy.Equals(DocumentSearchModel.IssuedBy));
}else
{
documents = documents.Where(d => d.IssuedBy.Contains(DocumentSearchModel.IssuedBy));
}
}
if (!string.IsNullOrEmpty(DocumentSearchModel.CodeDevision))
{
if (DocumentSearchModel.CompareCodeDevision == CompareString.EQUAL)
{
documents = documents.Where(d => d.CodeDevision.Equals(DocumentSearchModel.CodeDevision));
}
else
{
documents = documents.Where(d => d.CodeDevision.Contains(DocumentSearchModel.CodeDevision));
}
}
if(DocumentSearchModel.WhenIssued.Year != 1 && (DocumentSearchModel.WhenIssued.Year != DateTime.Now.Year || DocumentSearchModel.WhenIssued.Month != DateTime.Now.Month || DocumentSearchModel.WhenIssued.Day != DateTime.Now.Day))
{
if(DocumentSearchModel.CompareWhenIssued == CompareValue.MORE)
{
documents = documents.Where(d => d.WhenIssued >= DocumentSearchModel.WhenIssued);
}else if(DocumentSearchModel.CompareWhenIssued == CompareValue.LESS) {
documents = documents.Where(d => d.WhenIssued <= DocumentSearchModel.WhenIssued);
}else if(DocumentSearchModel.CompareWhenIssued == CompareValue.EQUAL)
{
documents = documents.Where(d => d.WhenIssued == DocumentSearchModel.WhenIssued);
}
}
//string q = documents.ToString();
wasSearched = true;
usersIds.AddRange(documents.Select(d => d.Persone.UserID).ToList());
}
#endregion
#region Search By Address
if (AddressSearchModel != null && !AddressSearchModel.IsEmptyAddress)
{
var addresses = _personAddressRepository.Addresses;
if (!string.IsNullOrEmpty(AddressSearchModel.Country))
{
if (AddressSearchModel.CompareCountry == CompareString.EQUAL)
{
addresses = addresses.Where(a => a.Country.Equals(AddressSearchModel.Country));
}
else
{
addresses = addresses.Where(a => a.Country.Contains(AddressSearchModel.Country));
}
}
if (!string.IsNullOrEmpty(AddressSearchModel.Subject))
{
if(AddressSearchModel.CompareSubject == CompareString.EQUAL)
{
addresses = addresses.Where(a => a.Subject.Equals(AddressSearchModel.Subject));
}else
{
addresses = addresses.Where(a => a.Subject.Contains(AddressSearchModel.Subject));
}
}
if (!string.IsNullOrEmpty(AddressSearchModel.Area))
{
if(AddressSearchModel.CompareArea == CompareString.EQUAL)
{
addresses = addresses.Where(a => a.Area.Equals(AddressSearchModel.Area));
}else
{
addresses = addresses.Where(a => a.Area.Contains(AddressSearchModel.Area));
}
}
if (!string.IsNullOrEmpty(AddressSearchModel.City))
{
if(AddressSearchModel.CompareCity == CompareString.EQUAL)
{
addresses = addresses.Where(a => a.City.Equals(AddressSearchModel.City));
}else
{
addresses = addresses.Where(a => a.City.Contains(AddressSearchModel.City));
}
}
if (!string.IsNullOrEmpty(AddressSearchModel.Street))
{
if(AddressSearchModel.CompareStreet == CompareString.EQUAL)
{
addresses = addresses.Where(a => a.Street.Equals(AddressSearchModel.Street));
}else
{
addresses = addresses.Where(a => a.Street.Contains(AddressSearchModel.Street));
}
}
if (!string.IsNullOrEmpty(AddressSearchModel.HomeNumber))
{
addresses = addresses.Where(a => a.HomeNumber.Equals(AddressSearchModel.HomeNumber));
}
if (!string.IsNullOrEmpty(AddressSearchModel.Flat))
{
addresses = addresses.Where(a => a.Flat.Equals(AddressSearchModel.Flat));
}
if (!string.IsNullOrEmpty(AddressSearchModel.Note))
{
if(AddressSearchModel.CompareNote == CompareString.EQUAL)
{
addresses = addresses.Where(a => a.Note.Equals(AddressSearchModel.Note));
}else
{
addresses = addresses.Where(a => a.Note.Contains(AddressSearchModel.Note));
}
}
wasSearched = true;
if (usersIds.Count == 0)
{
// Если список с ID пуст то просто добавляем новые ID
usersIds.AddRange(addresses.Select(a => a.Persone.UserID).ToList());
}
else
{
// Иначе делаем пересечение
var aaddd = addresses.Select(a => a.Persone.UserID).ToList();
usersIds = usersIds.Where(id => aaddd.Contains(id)).Select(id => id).ToList();
}
}
#endregion
#region Search by Ids
if (wasSearched)
{
persones = persones.Where(p => usersIds.Contains(p.UserID));
}
#endregion
#region Search By Name and Others
if (SearchModel != null && !SearchModel.IsEmptySearch)
{
if(persones == null) persones = _personRepository.Persons;
if (SearchModel.IsEmployer != null)
{
bool isEmployer = (bool)SearchModel.IsEmployer;
persones = persones.Where(p => p.IsEmploeyr == isEmployer);
if (isEmployer)
{
if (!string.IsNullOrEmpty(SearchModel.Position))
{
var position = _personPositionRepository.Positions.FirstOrDefault(p => p.Name.Equals(SearchModel.Position));
if(position != null)
{
persones = persones.Where(p => p.Position_PositionID == position.PositionID);
}
}
}
}
if (!string.IsNullOrEmpty(SearchModel.FirstName))
{
if(SearchModel.CompareFirstName == CompareString.EQUAL)
{
persones = persones.Where(p => p.FirstName.Equals(SearchModel.FirstName));
}else
{
persones = persones.Where(p => p.FirstName.Contains(SearchModel.FirstName));
}
}
if (!string.IsNullOrEmpty(SearchModel.SecondName))
{
if(SearchModel.CompareSecondName == CompareString.EQUAL)
{
persones = persones.Where(p => p.SecondName.Equals(SearchModel.SecondName));
}else
{
persones = persones.Where(p => p.SecondName.Contains(SearchModel.SecondName));
}
}
if (!string.IsNullOrEmpty(SearchModel.MiddleName))
{
if (SearchModel.CompareMiddleName == CompareString.EQUAL)
{
persones = persones.Where(p => p.MiddleName.Equals(SearchModel.MiddleName));
}
else
{
persones = persones.Where(p => p.MiddleName.Contains(SearchModel.MiddleName));
}
}
if (!string.IsNullOrEmpty(SearchModel.PlaceOfBirth))
{
if(SearchModel.ComparePlaceOfBirth == CompareString.EQUAL)
{
persones = persones.Where(p => p.PlaceOfBirth.Equals(SearchModel.PlaceOfBirth));
}else
{
persones = persones.Where(p => p.PlaceOfBirth.Contains(SearchModel.PlaceOfBirth));
}
}
if (SearchModel.DateBirthday.Year != 1
//&& (SearchModel.DateBirthday.Year != DateTime.Now.Year || SearchModel.DateBirthday.Month != DateTime.Now.Month || SearchModel.DateBirthday.Day != DateTime.Now.Day)
)
{
if(SearchModel.CompareDate == CompareValue.MORE)
{
persones = persones.Where(p => p.DateBirthday >= SearchModel.DateBirthday);
}else if(SearchModel.CompareDate == CompareValue.LESS){
persones = persones.Where(p => p.DateBirthday <= SearchModel.DateBirthday);
}
else if(SearchModel.CompareDate == CompareValue.EQUAL)
{
persones = persones.Where(p => p.DateBirthday == SearchModel.DateBirthday);
}
}
if(SearchModel.Age > 0 && (
SearchModel.DateBirthday.Year == 1 ||
SearchModel.DateBirthday.Year == DateTime.Now.Year && SearchModel.DateBirthday.Month == DateTime.Now.Month && SearchModel.DateBirthday.Day == DateTime.Now.Day
))
{
int year = DateTime.Now.Year - SearchModel.Age;
int mounth = DateTime.Now.Month;
int day = DateTime.Now.Month;
var dateBirth = new DateTime(year, mounth, day);
if (SearchModel.CompareAge == CompareValue.MORE)
{
persones = persones.Where(p => p.DateBirthday <= dateBirth);
}else if(SearchModel.CompareAge == CompareValue.LESS)
{
persones = persones.Where(p => p.DateBirthday >= dateBirth);
}
else if(SearchModel.CompareAge == CompareValue.EQUAL)
{
persones = persones.Where(p => p.DateBirthday.Year == dateBirth.Year
&& (p.DateBirthday.Month < dateBirth.Month
|| p.DateBirthday.Month == dateBirth.Month
&& p.DateBirthday.Day <= dateBirth.Day));
}
}
if(SearchModel.WasBeCreated.Year != 1)
{
if(SearchModel.CompareWasBeCreated == CompareValue.MORE)
{
persones = persones.Where(p => p.WasBeCreated >= SearchModel.WasBeCreated);
}
else if(SearchModel.CompareWasBeCreated == CompareValue.LESS)
{
persones = persones.Where(p => p.WasBeCreated <= SearchModel.WasBeCreated);
}
else
{
persones = persones.Where(p => p.WasBeCreated == SearchModel.WasBeCreated);
}
}
if(SearchModel.WasBeUpdated.Year != 1)
{
if (SearchModel.CompareWasBeUpdated == CompareValue.MORE)
{
persones = persones.Where(p => p.WasBeUpdated >= SearchModel.WasBeUpdated);
}
else if (SearchModel.CompareWasBeUpdated == CompareValue.LESS)
{
persones = persones.Where(p => p.WasBeUpdated <= SearchModel.WasBeUpdated);
}
else
{
persones = persones.Where(p => p.WasBeUpdated == SearchModel.WasBeUpdated);
}
}
if (!string.IsNullOrEmpty(SearchModel.PlaceWork))
{
if(SearchModel.ComparePlaceWork == CompareString.EQUAL)
{
persones = persones.Where(p => p.PlaceWork.Equals(SearchModel.PlaceWork));
}else
{
persones = persones.Where(p => p.PlaceWork.Contains(SearchModel.PlaceWork));
}
}
}
#endregion
#region Orders
if (OrderModel.OrderType == OrderType.NONE) OrderModel.OrderType = OrderType.DESC;
if (OrderModel.OrderType != OrderType.NONE)
{
if (persones == null) persones = _personRepository.Persons;
if (OrderModel.OrderType == OrderType.ASC)
{
switch (OrderModel.OrderProperties)
{
case PersonsOrderProperties.AGE:
persones = persones.OrderBy(p => p.DateBirthday);
break;
case PersonsOrderProperties.DATE_BERTHDAY:
persones = persones.OrderByDescending(p => p.DateBirthday);
break;
case PersonsOrderProperties.FIRST_NAME:
persones = persones.OrderByDescending(p => p.FirstName);
break;
case PersonsOrderProperties.MIDDLE_NAME:
persones = persones.OrderByDescending(p => p.MiddleName);
break;
case PersonsOrderProperties.SECOND_NAME:
persones = persones.OrderByDescending(p => p.SecondName);
break;
case PersonsOrderProperties.WAS_BE_CREATED:
persones = persones.OrderByDescending(p => p.WasBeCreated);
break;
case PersonsOrderProperties.WAS_BE_UPDATED:
persones = persones.OrderByDescending(p => p.WasBeUpdated);
break;
}
}
else
{
switch (OrderModel.OrderProperties)
{
case PersonsOrderProperties.AGE:
persones = persones.OrderByDescending(p => p.DateBirthday);
break;
case PersonsOrderProperties.DATE_BERTHDAY:
persones = persones.OrderBy(p => p.DateBirthday);
break;
case PersonsOrderProperties.FIRST_NAME:
persones = persones.OrderBy(p => p.FirstName);
break;
case PersonsOrderProperties.MIDDLE_NAME:
persones = persones.OrderBy(p => p.MiddleName);
break;
case PersonsOrderProperties.SECOND_NAME:
persones = persones.OrderBy(p => p.SecondName);
break;
case PersonsOrderProperties.WAS_BE_CREATED:
persones = persones.OrderBy(p => p.WasBeCreated);
break;
case PersonsOrderProperties.WAS_BE_UPDATED:
persones = persones.OrderBy(p => p.WasBeUpdated);
break;
}
}
}
else
{
if (persones == null) persones = _personRepository.Persons;
persones = persones.OrderBy(p => p.UserID);
}
#endregion
#region Make total items into PageModel
if (persones == null) persones = _personRepository.Persons;
PageModel.TotalItems = persones.Count();
#endregion
#region Paginations
if (PageModel.ItemsOnPage != -1)
{
persones = persones.Skip(PageModel.ItemsOnPage * (PageModel.CurentPage - 1)).Take(PageModel.ItemsOnPage);
}
#endregion
List<Persone> result = persones.ToList();
if (SearchModel.IsEmployer!= null && SearchModel.IsEmployer == true)
{
return result
.Select(p =>
(IPersoneViewModel)
new EmploeyrViewModel
{
WasBeCreated = p.WasBeCreated,
WasBeUpdated = p.WasBeUpdated,
UserID = p.UserID,
FirstName = p.FirstName,
SecondName = p.SecondName,
MiddleName = p.MiddleName,
IsEmploeyr = p.IsEmploeyr,
DateBirthday = p.DateBirthday,
PlaceOfBirth = p.PlaceOfBirth,
PositionID = p.Position_PositionID.ToString(),
Position = _positionNames.ContainsKey(p.Position_PositionID) ?
_positionNames[p.Position_PositionID] : ""
}
).ToList();
}
else
{
return result
.Select(p =>
(IPersoneViewModel)
new ViolatorViewModel
{
WasBeCreated = p.WasBeCreated,
WasBeUpdated = p.WasBeUpdated,
UserID = p.UserID,
FirstName = p.FirstName,
SecondName = p.SecondName,
MiddleName = p.MiddleName,
IsEmploeyr = p.IsEmploeyr,
DateBirthday = p.DateBirthday,
PlaceOfBirth = p.PlaceOfBirth,
PlaceOfWork = p.PlaceWork
}
).ToList(); ;
}
}
public int AddNewPersone(IPersoneViewModel personeModel)
{
var dt = _documentsTypeRepository.DocumentTypes;
Dictionary<string, int> documentTypes = new Dictionary<string, int>();
EmploeyrPosition position = null;
if(!personeModel.IsEmploeyr)
{
if(personeModel.Addresses.Count == 0 || personeModel.Addresses.First().IsEmptyModel)
{
throw new ArgumentException("Невозможно создать нарушителя.\r\nХотя бы один адрес должен быть заполнен.");
}
var document = personeModel.Documents.First();
if (string.IsNullOrEmpty(document.DocumentTypeName))
{
string docTN = "";
if(ConfigApp.DocumentTypesList.Count == 0)
{
throw new ArgumentException("Невозможно создать нарушителя, отсутствуют типы документов. \r\nЧтобы воспользоваться этой функцией, создайте тип документа");
}
else
{
docTN = ConfigApp.DocumentTypesList.First().Name;
}
document.DocumentTypeName = docTN;
}
if(string.IsNullOrEmpty(document.IssuedBy) || string.IsNullOrEmpty(document.Number)
|| string.IsNullOrEmpty(document.Serial) || document.WhenIssued.Year == 1)
throw new ArgumentException("У нарушителя должен быть хотя бы один документ!");
}
if(personeModel.DateBirthday.Year < 1700)
{
throw new ArgumentException("Укажите дату рождения!");
}
if (string.IsNullOrEmpty(personeModel.FirstName))
{
throw new ArgumentException("Укажите фамилию!");
}
if (string.IsNullOrEmpty(personeModel.SecondName))
{
throw new ArgumentException("Укажите имя!");
}
if (string.IsNullOrEmpty(personeModel.MiddleName))
{
throw new ArgumentException("Укажите отчество!");
}
if (personeModel.IsEmploeyr && personeModel is EmploeyrViewModel)
{
var employer = (EmploeyrViewModel)personeModel;
try
{
int positionID = Convert.ToInt32(employer.PositionID);
position = _personPositionRepository.Positions.FirstOrDefault(p => p.PositionID == positionID);
}
catch
{
position = _personPositionRepository.Positions.FirstOrDefault(p => p.Name.Equals(employer.Position));
}
finally
{
if (position == null) throw new ArgumentException("Неизвестная должность!");
}
}
foreach (var d in dt)
{
documentTypes.Add(d.Name, d.DocumentTypeID);
}
#region make persone model
Persone persone = new Persone
{
IsEmploeyr = personeModel.IsEmploeyr,
Position_PositionID = personeModel.IsEmploeyr ? position.PositionID : -1,
FirstName = personeModel.FirstName,
SecondName = personeModel.SecondName,
MiddleName = personeModel.MiddleName,
DateBirthday = personeModel.DateBirthday,
WasBeUpdated = DateTime.Now,
WasBeCreated = DateTime.Now,
PlaceOfBirth = personeModel.PlaceOfBirth,
Image = personeModel.Image,
PlaceWork = !personeModel.IsEmploeyr ? ((ViolatorViewModel)personeModel).PlaceOfWork : ""
};
persone.Documents = new List<Document>();
if (!personeModel.IsEmploeyr && personeModel.Documents != null)
{
foreach (var doc in personeModel.Documents)
{
if (string.IsNullOrEmpty(doc.DocumentTypeName))
{
doc.DocumentTypeName = ConfigApp.DocumentTypesList.First().Name;
}
if (string.IsNullOrEmpty(doc.IssuedBy)
|| string.IsNullOrEmpty(doc.Number)
|| string.IsNullOrEmpty(doc.Serial)
|| doc.WhenIssued.Year == 1) continue;
persone.Documents.Add(new Document
{
DocumentID = doc.DocumentID,
Document_DocumentTypeID = ConfigApp.DocumentTypesList.FirstOrDefault(d => d.Name.Equals(doc.DocumentTypeName)).DocumentTypeID,
CodeDevision = doc.CodeDevision,
IssuedBy = doc.IssuedBy,
Number = doc.Number,
Serial = doc.Serial,
WhenIssued = doc.WhenIssued
});
}
}
persone.Address = new List<PersoneAddress>();
if (personeModel.Addresses != null)
{
foreach (var address in personeModel.Addresses)
{
if (!address.IsEmptyModel) {
string note = address.Note;
if (string.IsNullOrWhiteSpace(note)) note = "Проживает и прописан";
persone.Address.Add(new PersoneAddress
{
Country = address.Country,
Subject = address.Subject,
Area = address.Area,
City = address.City,
Street = address.Street,
HomeNumber = address.HomeNumber,
Flat = address.Flat,
Note = address.Note
});
}
}
}
persone.Phones = new List<Phone>();
if(personeModel.Phones != null)
{
foreach(var phone in personeModel.Phones)
{
if (!string.IsNullOrEmpty(phone.PhoneNumber))
{
persone.Phones.Add(new Phone
{
PhoneNumber = phone.PhoneNumber
});
}
}
}
_personRepository.AddPersone(persone);
#endregion
return persone.UserID;
}
public bool Remove(int id)
{
return _personRepository.Remove(id);
}
public bool SimpleRemove(int id)
{
return _personRepository.SimpleRemove(id);
}
public bool SimpleRemove(IPersoneViewModel model)
{
return SimpleRemove(model.UserID);
}
public bool Remove(IPersoneViewModel model)
{
return Remove(model.UserID);
}
public IPersoneViewModel GetPerson(int id, bool loadFullModel = false)
{
var person = _personRepository.Persons.FirstOrDefault(p => p.UserID == id);
List<PersonAddressModelView> addresses = null;
List<PersoneDocumentModelView> documents = null;
List<PhoneViewModel> phones = null;
string positionName = null;
if (person == null) return null;
if (person.IsEmploeyr)
{
var position = _personPositionRepository.Positions
.FirstOrDefault(p => p.PositionID == person.Position_PositionID);
positionName = position != null ? position.Name : "";
}
if (loadFullModel)
{
Dictionary<int, string> documentsType = new Dictionary<int, string>();
foreach(var dt in _documentsTypeRepository.DocumentTypes)
{
documentsType.Add(dt.DocumentTypeID, dt.Name);
}
addresses = _personAddressRepository.Addresses
.Where(a => a.Persone.UserID == id)
.Select(a => new PersonAddressModelView
{
Country = a.Country,
Subject = a.Subject,
Area = a.Area,
City = a.City,
Street = a.Street,
HomeNumber = a.HomeNumber,
AddressID = a.AddressID,
Flat = a.Flat,
Note = a.Note
}).ToList();
documents = _documentsRepository.Documents
.Where(d => d.Persone.UserID == id)
.Select(d => new PersoneDocumentModelView
{
DocumentTypeID = d.Document_DocumentTypeID
//DocumentTypeName = //documentsType.ContainsKey(d.Document_DocumentTypeID)?
// documentsType[d.Document_DocumentTypeID]//:
// //"",
,
DocumentID = d.DocumentID,
IssuedBy = d.IssuedBy,
CodeDevision = d.CodeDevision,
Number = d.Number,
Serial = d.Serial,
WhenIssued = d.WhenIssued
}).ToList();
phones = _phonesRepository.Phones
.Where(p => p.Persone.UserID == id)
.Select(p => new PhoneViewModel
{
PhoneID = p.PhoneID,
PhoneNumber = p.PhoneNumber
}).ToList();
foreach(var doc in documents)
{
doc.DocumentTypeName = documentsType.ContainsKey(doc.DocumentTypeID) ?
documentsType[doc.DocumentTypeID] : "";
}
}
if (addresses == null) addresses = new List<PersonAddressModelView>();
if (documents == null) documents = new List<PersoneDocumentModelView>();
if (phones == null) phones = new List<PhoneViewModel>();
if(person.IsEmploeyr != null && person.IsEmploeyr == true)
{
return new EmploeyrViewModel
{
UserID = person.UserID,
FirstName = person.FirstName,
SecondName = person.SecondName,
MiddleName = person.MiddleName,
IsEmploeyr = person.IsEmploeyr,
PositionID = person.Position_PositionID.ToString(),
PlaceOfBirth = person.PlaceOfBirth,
DateBirthday = person.DateBirthday,
Image = person.Image,
Position = person.IsEmploeyr ? positionName : "",
Documents = documents,
Addresses = addresses,
Phones = phones,
WasBeCreated = person.WasBeCreated,
WasBeUpdated = person.WasBeUpdated
};
}else
{
return new ViolatorViewModel
{
UserID = person.UserID,
FirstName = person.FirstName,
SecondName = person.SecondName,
MiddleName = person.MiddleName,
IsEmploeyr = person.IsEmploeyr,
PlaceOfBirth = person.PlaceOfBirth,
DateBirthday = person.DateBirthday,
Image = person.Image,
Documents = documents,
Addresses = addresses,
Phones = phones,
PlaceOfWork = person.PlaceWork,
WasBeCreated = person.WasBeCreated,
WasBeUpdated = person.WasBeUpdated
};
}
}
public Persone ConverToEnity(IPersoneViewModel model)
{
Persone persone = new Persone
{
FirstName = model.FirstName,
SecondName = model.SecondName,
MiddleName = model.MiddleName,
IsEmploeyr = model.IsEmploeyr,
PlaceOfBirth = model.PlaceOfBirth,
PlaceWork = (!model.IsEmploeyr) ? ((ViolatorViewModel)model).PlaceOfWork : "",
Image = model.Image,
Phones = model.Phones.Select(p => new Phone {PhoneNumber = p.PhoneNumber }).ToList(),
UserID = model.UserID,
Position_PositionID = model.IsEmploeyr ? Convert.ToInt32(((EmploeyrViewModel)model).PositionID) : 0,
WasBeCreated = model.WasBeCreated,
WasBeUpdated = model.WasBeUpdated,
Address = model.Addresses.Select(a => new PersoneAddress
{
AddressID = a.AddressID,
Area = a.Area,
City = a.City,
Country = a.Country,
Flat = a.Flat,
HomeNumber = a.HomeNumber,
Note = a.Note,
Street = a.Street,
Subject = a.Subject
}).ToList(),
Documents = model.Documents.Select(d => new Document
{
CodeDevision = d.CodeDevision,
DocumentID = d.DocumentID,
Document_DocumentTypeID = d.DocumentTypeID,
IssuedBy = d.IssuedBy,
Number = d.Number,
Serial = d.Serial,
WhenIssued = d.WhenIssued
}).ToList(),
DateBirthday = model.DateBirthday,
};
return persone;
}
public bool UpdatePersone(IPersoneViewModel personeModel)
{
var dt = _documentsTypeRepository.DocumentTypes;
Dictionary<string, int> documentTypes = new Dictionary<string, int>();
EmploeyrPosition position = null;
if (personeModel.DateBirthday.Year < 1700)
{
throw new ArgumentException("Укажите дату рождения!");
}
if (string.IsNullOrEmpty(personeModel.FirstName))
{
throw new ArgumentException("Укажите фамилию!");
}
if (string.IsNullOrEmpty(personeModel.SecondName))
{
throw new ArgumentException("Укажите имя!");
}
if (string.IsNullOrEmpty(personeModel.MiddleName))
{
throw new ArgumentException("Укажите отчество!");
}
if (personeModel.IsEmploeyr && personeModel is EmploeyrViewModel)
{
var employer = (EmploeyrViewModel)personeModel;
try
{
int positionID = Convert.ToInt32(employer.PositionID);
position = _personPositionRepository.Positions.FirstOrDefault(p => p.PositionID == positionID);
}
catch
{
position = _personPositionRepository.Positions.FirstOrDefault(p => p.Name.Equals(employer.Position));
}
finally {
if (position == null) throw new ArgumentException("Неизвестная должность!");
}
}
foreach (var d in dt)
{
documentTypes.Add(d.Name, d.DocumentTypeID);
}
#region make persone model
Persone persone = new Persone
{
UserID = personeModel.UserID,
IsEmploeyr = personeModel.IsEmploeyr,
Position_PositionID = personeModel.IsEmploeyr ? position.PositionID : -1,
FirstName = personeModel.FirstName,
SecondName = personeModel.SecondName,
MiddleName = personeModel.MiddleName,
DateBirthday = personeModel.DateBirthday,
WasBeUpdated = DateTime.Now,
PlaceOfBirth = personeModel.PlaceOfBirth,
Image = personeModel.Image,
PlaceWork = !personeModel.IsEmploeyr ? ((ViolatorViewModel)personeModel).PlaceOfWork : "",
};
persone.Documents = new List<Document>();
if (!personeModel.IsEmploeyr && personeModel.Documents != null)
{
foreach (var doc in personeModel.Documents)
{
if (doc.WhenIssued.Year == 1) doc.WhenIssued = DateTime.Now;
persone.Documents.Add(new Document
{
DocumentID = doc.DocumentID,
Document_DocumentTypeID = ConfigApp.DocumentTypesList.FirstOrDefault(d => d.Name.Equals(doc.DocumentTypeName)).DocumentTypeID,
CodeDevision = doc.CodeDevision,
IssuedBy = doc.IssuedBy,
Number = doc.Number,
Serial = doc.Serial,
WhenIssued = doc.WhenIssued
});
}
}
persone.Address = new List<PersoneAddress>();
if (personeModel.Addresses != null)
{
foreach (var address in personeModel.Addresses)
{
if (!address.IsEmptyModel)
persone.Address.Add(new PersoneAddress
{
AddressID = address.AddressID,
Country = address.Country,
Subject = address.Subject,
Area = address.Area,
City = address.City,
Street = address.Street,
HomeNumber = address.HomeNumber,
Flat = address.Flat,
Note = address.Note
});
}
}
persone.Phones = new List<Phone>();
if (personeModel.Phones != null)
{
foreach (var phone in personeModel.Phones)
{
if (!string.IsNullOrEmpty(phone.PhoneNumber))
{
persone.Phones.Add(new Phone
{
PhoneID = phone.PhoneID,
PhoneNumber = phone.PhoneNumber
});
}
}
}
#endregion
return _personRepository.Update(persone);
}
}
}
<file_sep>/AppGUI/Windows/LoginWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WPFPresentators.Views.Windows;
namespace AppGUI.Windows
{
/// <summary>
/// Interaction logic for LoginWindow.xaml
/// </summary>
public partial class LoginWindow : Window, ILoginView
{
public LoginWindow()
{
InitializeComponent();
}
public string Login { get
{
return txtLogin.Text;
}
}
public string Password { get
{
return txtPassword.Text;
}
}
public event Action OnLogin;
public void ShowError(string message)
{
lbError.Content = message;
}
public void Show()
{
base.ShowDialog();
}
private void BtnLogin_Click(object sender, RoutedEventArgs e)
{
if (OnLogin != null) OnLogin();
}
}
}
<file_sep>/AppCore/Abstract/IPersoneAddressRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract
{
public interface IPersoneAddressRepository
{
IQueryable<PersoneAddress> Addresses { get; }
bool Remove(int id);
int RemoveUserAddresses(int userid);
int AddAdress(PersoneAddress address);
}
}
<file_sep>/AppCore/Infrastructure/RepositoryesFactory.cs
using AppData.Abstract;
using AppData.Abstract.Protocols;
using AppData.Entities;
using AppData.FakesRepositoryes;
using AppData.Repositrys;
using AppData.Repositrys.Violations;
using AppData.Repositrys.Violations.Protocols;
using Moq;
using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Infrastructure
{
public class RepositoryesFactory
{
private static IKernel ninjectKernel = null;
private static RepositoryesFactory _instance;
public static RepositoryesFactory GetInstance()
{
if(_instance == null)
{
//AppDomain.CurrentDomain.SetData("DataDirecotry", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase));
_instance = new RepositoryesFactory();
_instance.Init();
}
return _instance;
}
private void Init()
{
ninjectKernel = new StandardKernel();
AddBinds();
}
public T Get<T>()
{
if (!ninjectKernel.CanResolve<T>())
throw new ArgumentException("Has`t type!");
return (T)ninjectKernel.Get<T>();
}
public object GetProtocol(int protocolType)
{
return null;
}
private void AddBinds()
{
ninjectKernel.Bind<IManagersRepository>().To<ManagersRepository>();
/// Общая информация по гражданам
ninjectKernel.Bind<IPersoneRepository>().To<PersonesRepository>();
ninjectKernel.Bind<IPersonePositionRepository>().To<PositionsRepository>();
ninjectKernel.Bind<IPersoneAddressRepository>().To<AddressRepository>();
ninjectKernel.Bind<IPhonesRepository>().To<PhonesRepository>();
/// Репозитории с документами
ninjectKernel.Bind<IDocumentRepository>().To<DocumentsRepository>();
ninjectKernel.Bind<IDocumentTypeRepository>().To<DocumentTypesRepository>();
/// Репозитории с общей информацией о нарушениях
ninjectKernel.Bind<IViolationRepository>().To<ViolationRepository>();
ninjectKernel.Bind<IViolationTypeRepository>().To<ViolationTypesRepository>();
ninjectKernel.Bind<IViolatorRepository>().To<ViolatorsRepository>();
ninjectKernel.Bind<IEmployerRepository>().To<EmployersRepository>();
/// Протоколы
ninjectKernel.Bind<IProtocolRepository>().To<ProtocolRepository>();
ninjectKernel.Bind<IProtocolTypeRepository>().To<ProtocolTypeRepository>();
ninjectKernel.Bind<IProtocolAboutArrestRepository>().To<ProtocolAboutArrestRepository>();
ninjectKernel.Bind<IProtocolAboutBringingRepository>().To<ProtocolAboutBringingRepository>();
ninjectKernel.Bind<IProtocolAboutInspectionAutoRepository>().To<ProtocolAboutInspectionAutoRepository>();
ninjectKernel.Bind<IProtocolAboutInspectionOrganisationRepository>().To<ProtocolAboutInspectionOrganisationRepository>();
ninjectKernel.Bind<IProtocolAboutInspectionRepository>().To<ProtocolAboutInspectionRepository>();
ninjectKernel.Bind<IProtocolAboutViolationOrganisationRepository>().To<ProtocolAboutViolationOrganisationRepository>();
ninjectKernel.Bind<IProtocolAboutViolationPersoneRepository>().To<ProtocolAboutViolationPersoneRepository>();
ninjectKernel.Bind<IProtocolAboutWithdrawRepository>().To<ProtocolAboutWithdrawRepository>();
ninjectKernel.Bind<IRulingForViolationRepository>().To<RulingForViolationRepository>();
ninjectKernel.Bind<IInjunctionRepository>().To<InjunctionRepository>();
ninjectKernel.Bind<IInjunctionItemRepository>().To<IInjunctionItemRepository>();
}
}
}
<file_sep>/LeoBase/Components/CustomControls/DetailsComponent/PersoneDetailsControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.VModels.Persons;
using AppPresentators.VModels;
using AppPresentators.VModels.Protocols;
namespace LeoBase.Components.CustomControls.DetailsComponent
{
public partial class PersoneDetailsControl : UserControl, IPersoneDetailsControl
{
public PersoneDetailsControl()
{
InitializeComponent();
}
public List<ViolationViewModel> Violations { get; set; }
public List<ProtocolViewModel> Protocols { get; set; }
public IPersoneViewModel Persone { get; set; }
public Dictionary<int, string> Positions { get; set; }
public bool ShowForResult { get; set; }
public List<Control> TopControls { get { return new List<Control>(); } set { } }
public Control GetControl()
{
return this;
}
void UIComponent.Resize(int width, int height)
{
}
}
}
<file_sep>/AppCore/Repositrys/Violations/Protocols/ProtocolAboutViolationPersoneRepository.cs
using AppData.Abstract.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations.Protocols
{
public class ProtocolAboutViolationPersoneRepository : IProtocolAboutViolationPersoneRepository
{
public IQueryable<ProtocolAboutViolationPersone> ProtocolsAboutViolationPersone
{
get
{
var db = new LeoBaseContext();
return db.ProtocolsAboutViolationPersone;
}
}
}
}
<file_sep>/AppCore/Entities/ProtocolAboutInspectionAuto.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
/// <summary>
/// Протокол о досмотре транспортного средства
/// </summary>
public class ProtocolAboutInspectionAuto:IProtocol
{
[Key]
public int ProtocolAboutInspectionAutoID { get; set; }
[Required(AllowEmptyStrings = false)]
public Protocol Protocol { get; set; }
public int ViolatorDocumentID { get; set; }
/// <summary>
/// Информация о транспортном средстве
/// </summary>
public string InformationAbouCar { get; set; }
/// <summary>
/// Найденное оружие
/// </summary>
public string FindedWeapons { get; set; }
/// <summary>
/// Найденные боеприпасы
/// </summary>
public string FindedAmmunitions { get; set; }
/// <summary>
/// Найденые орудия для охоты и рыболовства
/// </summary>
public string FindedGunsHuntingAndFishing { get; set; }
/// <summary>
/// Найденная продукция природопользования
/// </summary>
public string FindedNatureManagementProducts { get; set; }
/// <summary>
/// Найденные документы
/// </summary>
public string FindedDocuments { get; set; }
/// <summary>
/// Методы фиксации правонарушения
/// </summary>
public string FixingMethods { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/ViolationTableControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.Services;
using AppPresentators.VModels;
using LeoBase.Components.CustomControls.SearchPanels;
using AppPresentators;
namespace LeoBase.Components.CustomControls
{
public partial class ViolationTableControl : UserControl, IViolationTableControl
{
private Dictionary<string, int> _orderProperties;
private Dictionary<string, OrderType> _orderTypes;
public ViolationTableControl()
{
InitializeComponent();
SearchPanel = new ViolationSearchPanel();
SearchPanel.Search += () => UpdateData();
SearchPanel.HidePanel += () =>
{
WidthAnimate animator = new WidthAnimate(searchPanel, searchPanel.Width, 0, 5, 20);
animator.OnAnimationComplete += () => btnShowSearch.Visible = true;
animator.Start();
};
searchPanel.Controls.Add(SearchPanel);
_table = new CustomTable();
_orderProperties = new Dictionary<string, int>();
_orderTypes = new Dictionary<string, OrderType>();
_orderProperties.Add("Дата создания", (int)ViolationOrderProperties.WAS_BE_CREATED);
_orderProperties.Add("Дата последнего обновления", (int)ViolationOrderProperties.WAS_BE_UPDATED);
_orderTypes.Add("Убывание", OrderType.ASC);
_orderTypes.Add("Возростание", OrderType.DESC);
_table = new CustomTable();
_table.Width = mainPanel.Width - 5;
_table.Height = mainPanel.Height - 35;
_table.Location = new Point(0, 30);
_table.Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
_table.Margin = new Padding(0, 0, 0, 0);
_table.OrderProperties = (Dictionary<string, int>)_orderProperties;
_table.UpdateTable += () => Update();
mainPanel.Controls.Add(_table);
animateSearchPanel.Tick += AnimateSearchPanel_Tick;
MakeTopControls();
_table.SelectedItemChange += (index) =>
{
if (index != -1)
{
_btnUpdate.Enabled = true;
_btnRemove.Enabled = true;
_btnDetails.Enabled = true;
}
else
{
_btnUpdate.Enabled = false;
_btnRemove.Enabled = false;
_btnDetails.Enabled = false;
}
};
}
private Button _btnReport = new Button();
private Button _btnAddNew = new Button();
private Button _btnRemove = new Button();
private Button _btnDetails = new Button();
private Button _btnUpdate = new Button();
private void MakeTopControls()
{
if (!ConfigApp.CurrentManager.Role.Equals("admin"))
{
_btnAddNew.Visible = false;
_btnRemove.Visible = false;
_btnUpdate.Visible = false;
}
_btnUpdate.Enabled = false;
_btnRemove.Enabled = false;
_btnDetails.Enabled = false;
_btnAddNew.Text = "Добавить";
_btnRemove.Text = "Удалить";
_btnUpdate.Text = "Редактировать";
_btnDetails.Text = "Подробнее";
_btnReport.Text = "Отчет";
_btnAddNew.Click += (s, e) =>
{
if (AddNewViolation != null) AddNewViolation();
};
_topControls = new List<Control>();
_topControls.Add(_btnReport);
_topControls.Add(_btnDetails);
_topControls.Add(_btnAddNew);
_topControls.Add(_btnUpdate);
_topControls.Add(_btnRemove);
}
private void MakeAdminControls()
{
}
private void MakeUserControls()
{
}
public ViolationOrderModel OrderModel
{
get
{
return new ViolationOrderModel
{
OrderProperties = (ViolationOrderProperties)_orderProperties[_table.SelectedOrderByValue],
OrderType = _table.OrderType
};
}
}
public PageModel PageModel
{
get
{
return _table.PageModel;
}
set
{
}
}
private ViolationSearchPanel SearchPanel;
public ViolationSearchModel SearchModel
{
get
{
return SearchPanel.SearchModel;
}
}
public bool ShowForResult { get; set; }
private List<Control> _topControls;
public List<Control> TopControls { get { return _topControls; } set { } }
private List<ViolationViewModel> _data;
public List<ViolationViewModel> Violations
{
get
{
return _data;
}
set
{
_data = value;
_table.SetData<ViolationViewModel>(_data);
}
}
public event Action AddNewViolation;
public event ViolationAction RemoveViolation;
public event ViolationAction ShowDetailsViolation;
public event Action UpdateData;
public event ViolationAction UpdateViolation;
private CustomTable _table;
public Control GetControl()
{
return this;
}
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
void UIComponent.Resize(int width, int height){}
private int animateTo = 0;
private int animateSpeed = 0;
bool _searchAnimate = false;
private void AnimateSearchPanel_Tick(object sender, EventArgs e)
{
if (searchPanel.Width != animateTo)
{
searchPanel.Width += animateSpeed;
}
else
{
if (animateTo == 0)
{
btnShowSearch.Visible = true;
}
animateSearchPanel.Stop();
_searchAnimate = false;
}
}
private void btnShowSearch_Click(object sender, EventArgs e)
{
btnShowSearch.Visible = false;
WidthAnimate animator = new WidthAnimate(searchPanel, searchPanel.Width, 450, 10, 20);
animator.Start();
}
public void LoadStart()
{
//_customTable.Visible = false;
//VisibleLoadPanel = true;
}
public void LoadEnd()
{
//VisibleLoadPanel = false;
//_customTable.Visible = true;
}
}
}
<file_sep>/AppCore/Entities/Injunction.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
/// <summary>
/// Предписание об устранение нарушений законодательства в сфере
/// природопользования и охраны окружающей среды
/// </summary>
public class Injunction:IProtocol
{
[Key]
public int InjunctionID { get; set; }
public Protocol Protocol { get; set; }
public int ViolatorDocumentID { get; set; }
/// <summary>
/// Дата акта проверки
/// </summary>
public DateTime ActInspectionDate { get; set; }
/// <summary>
/// Номер акта проверки
/// </summary>
public string ActInspectionNumber { get; set; }
/// <summary>
/// Что предписывает
/// </summary>
public string InjunctionInfo { get; set; }
/// <summary>
/// Пункты предписания
/// </summary>
public virtual List<InjunctionItem> InjuctionsItem { get; set; }
}
/// <summary>
/// Пункт предписания
/// </summary>
public class InjunctionItem
{
[Key]
public int InjunctionItemID { get; set; }
/// <summary>
/// Содержание пункта предписания
/// </summary>
public string Description { get; set; }
/// <summary>
/// Срок выполнения предписания
/// </summary>
public string Deedline { get; set; }
/// <summary>
/// Основание предписания
/// </summary>
public string BaseOrders { get; set; }
}
}
<file_sep>/LeoMapV2/Models/MapEventArgs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoMapV2.Models
{
public class MapEventArgs
{
public int CanvasX { get; private set; }
public int CanvasY { get; private set; }
public double N { get; private set; }
public double E { get; private set; }
public int MapX { get; private set; }
public int MapY { get; private set; }
public MapEventArgs(int x, int y, double n, double e, int mx, int my)
{
CanvasX = x;
CanvasY = y;
N = n;
E = e;
MapX = mx;
MapY = my;
}
}
}
<file_sep>/WPFPresentators/Presentators/IPresentator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFPresentators.Presentators
{
public interface IPresentator
{
}
}
<file_sep>/AppGUI/Windows/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WPFPresentators;
using WPFPresentators.Views.Controls;
using WPFPresentators.Views.Windows;
namespace AppGUI.Windows
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, IMainView
{
public MainWindow()
{
InitializeComponent();
if (Login != null) Login();
}
public event Action BackPage;
public event Action Login;
public event Action NextPage;
public void Show()
{
base.Show();
if(AppConfig.CurrentManager == null && Login != null)
{
Login();
}
}
public void LoadEnd()
{
throw new NotImplementedException();
}
public void LoadStart()
{
throw new NotImplementedException();
}
public void SetCenterPanel(IControlView view)
{
throw new NotImplementedException();
}
public void SetMainMenu(IControlView view)
{
throw new NotImplementedException();
}
public void SetTopMenu(IControlView view)
{
throw new NotImplementedException();
}
public void ShowError(string message)
{
throw new NotImplementedException();
}
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/SaveViolationControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppData.Entities;
using System.IO;
using AppPresentators;
namespace LeoBase.Components.CustomControls.NewControls
{
public partial class SaveViolationControl : UserControl, ISaveAdminViolationControl
{
private Button _saveButton;
public SaveViolationControl()
{
InitializeComponent();
_saveButton = new Button();
_saveButton.Text = "Сохранить";
cmbDocument.SelectedIndexChanged += (s, e) => SelectedNewDocument();
_saveButton.Click += (s, e) =>
{
if (Save != null && ValidateData()) {
try {
CreateViolation();
Save();
}catch(Exception ex)
{
ShowError(ex.Message);
}
}
};
btnFindEmployer.Click += (s, e) =>
{
if (FindEmployer != null) FindEmployer();
};
btnCreateEmployer.Click += (s, e) =>
{
if (CreateEmployer != null) CreateEmployer();
};
btnCreateViolator.Click += (s, e) =>
{
if (CreateViolator != null) CreateViolator();
};
btnFindViolator.Click += (s, e) =>
{
if (FindViolator != null) FindViolator();
};
tbCoordsCreatedProtocolE.KeyPress += RealListener;
tbCoordsCreatedProtocolN.KeyPress += RealListener;
tbCoordsViolationE.KeyPress += RealListener;
tbCoordsViolationN.KeyPress += RealListener;
tbSumRecovery.KeyPress += RealListener;
tbSumViolation.KeyPress += RealListener;
chbWasPaymant.CheckedChanged += chbWasPaymant_CheckedChanged;
chbGotPersonaly.CheckedChanged += chbGotPersonaly_CheckedChanged;
chbWasSent.CheckedChanged += chbWasSent_CheckedChanged;
chbWasReceiving.CheckedChanged += chbWasReceiving_CheckedChanged;
chbWasSentBailiff.CheckedChanged += chbWasSentBailiff_CheckedChanged;
chbWasNotice.CheckedChanged += chbWasNotice_CheckedChanged;
chbWasAgenda2025.CheckedChanged += chbWasAgenda2025_CheckedChanged;
}
private void RealListener(object s, KeyPressEventArgs e)
{
if (e.KeyChar == 46 && (((TextBox)s).Text.Contains(".")))
{
e.Handled = true;
}
else if (!Char.IsDigit(e.KeyChar) && !e.KeyChar.ToString().Equals(".") && e.KeyChar != 8)
{
e.Handled = true;
}
}
private bool ValidateData()
{
if(Violation == null)
{
MessageBox.Show("Информация заполнена не верно");
return false;
}
if (Violation.Employer == null) {
MessageBox.Show("Не выбран сотрудник");
return false;
}
if(Violation.ViolatorPersone == null)
{
MessageBox.Show("Не выбран нарушитель");
return false;
}
if(Violation.ViolatorDocument == null)
{
MessageBox.Show("Не выбран документ правонарушителя");
return false;
}
return true;
}
public bool ShowForResult { get; set; }
public List<Control> TopControls { get
{
return new List<Control>
{
_saveButton
};
}
set
{
}
}
private AdminViolation _violation;
public AdminViolation Violation {
get
{
if(_violation == null)
{
_violation = new AdminViolation
{
Images = new List<ViolationImage>()
};
}
return _violation;
}
set
{
_violation = value;
lbTitle.Text = value == null || value.Employer == null ? "Создание правонарушения" : "Редактирование правонарушения";
if(_violation != null)
UpdateDataSource();
}
}
public event Action CreateEmployer;
public event Action CreateViolator;
public event Action FindEmployer;
public event Action FindViolator;
public event Action Save;
public Control GetControl()
{
return this;
}
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
void UIComponent.Resize(int width, int height)
{
}
public void UpdateDataSource()
{
UpdateEmployer();
UpdateViolator();
UpdateImages();
tbPlaceCreatedProtocol.Text = Violation.PlaceCreatedProtocol;
tbCoordsCreatedProtocolN.Text = Violation.CreatedProtocolN.ToString().Replace(',', '.');
tbCoordsCreatedProtocolE.Text = Violation.CreatedProtocolE.ToString().Replace(',', '.');
tbCoordsViolationN.Text = Violation.ViolationN.ToString().Replace(',', '.');
tbCoordsViolationE.Text = Violation.ViolationE.ToString().Replace(',', '.');
dpCreatedProtocol.Value = Violation.DateCreatedProtocol;
dpTimeCreatedProtocol.Value = Violation.DateCreatedProtocol;
dpViolationDate.Value = Violation.DateViolation;
dpTimeViolation.Value = Violation.DateViolation;
tbDescriptionViolation.Text = Violation.ViolationDescription;
tbKOAP.Text = Violation.KOAP;
tbFindedNatureManagementProducts.Text = Violation.FindedNatureManagementProducts;
tbFindedGunsHuntingAndFishing.Text = Violation.FindedGunsHuntingAndFishing;
tbFindedWeapons.Text = Violation.FindedWeapons;
tbWitnessFIO_1.Text = Violation.WitnessFIO_1;
tbWitnessFIO_2.Text = Violation.WitnessFIO_2;
tbWitnessLive_1.Text = Violation.WitnessLive_1;
tbWitnessLive_2.Text = Violation.WitnessLive_2;
// Информация по постановлению
tbRulingNumber.Text = Violation.RulingNumber;
dpConsideration.Value = Violation.Consideration;
dpTimeConsideration.Value = Violation.Consideration;
tbViolation.Text = Violation.Violation;
chbWasPaymant.Checked = Violation.WasPaymant;
if (Violation.WasPaymant) {
dpDatePaymant.Value = Violation.DatePaymant;
tbSumRecovery.Text = Math.Round(Violation.SumRecovery, 2).ToString().Replace(',', '.');
dpDatePaymant.Enabled = true;
tbSumRecovery.Enabled = true;
}else
{
dpDatePaymant.Enabled = false;
tbSumRecovery.Enabled = false;
}
tbSumViolation.Text = Math.Round(Violation.SumViolation, 2).ToString().Replace(',', '.');
if (Violation.GotPersonaly)
{
chbGotPersonaly.Checked = true;
chbWasSent.Enabled = false;
dpDateSent.Enabled = false;
tbNumberSent.Enabled = false;
}else
{
chbGotPersonaly.Checked = false;
chbWasSent.Checked = Violation.WasSent;
dpDateSent.Enabled = false;
tbNumberSent.Enabled = false;
if (Violation.WasSent) {
dpDateSent.Enabled = true;
tbNumberSent.Enabled = true;
dpDateSent.Value = Violation.DateSent;
tbNumberSent.Text = Violation.NumberSent;
}
}
chbWasReceiving.Checked = Violation.WasReceiving;
if (Violation.WasReceiving) {
dpDateReceiving.Enabled = true;
dpDateReceiving.Value = Violation.DateReceiving;
}else
{
dpDateReceiving.Enabled = false;
}
chbWasSentBailiff.Checked = Violation.WasSentBailiff;
if (Violation.WasSentBailiff)
{
dpDateSentBailiff.Value = Violation.DateSentBailiff;
tbNumberSentBailigg.Text = Violation.NumberSentBailigg;
dpDateSentBailiff.Enabled = true;
tbNumberSentBailigg.Enabled = true;
}else
{
dpDateSentBailiff.Enabled = false;
tbNumberSentBailigg.Enabled = false;
}
chbWasNotice.Checked = Violation.WasNotice;
if (Violation.WasNotice) {
dpDateNotice.Value = Violation.DateNotice;
tbNumberNotice.Text = Violation.NumberNotice;
dpDateNotice.Enabled = true;
tbNumberNotice.Enabled = true;
}
else
{
dpDateNotice.Enabled = false;
tbNumberNotice.Enabled = false;
}
chbWasAgenda2025.Checked = Violation.WasAgenda2025;
if (Violation.WasAgenda2025) {
dpDateAgenda2025.Value = Violation.DateAgenda2025;
dpDateAgenda2025.Enabled = true;
}
else
{
dpDateAgenda2025.Enabled = false;
}
}
private void ShowError(string message)
{
MessageBox.Show(message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void CreateViolation()
{
if (string.IsNullOrWhiteSpace(tbPlaceCreatedProtocol.Text)) throw new Exception("Не указано место составления протокола");
Violation.PlaceCreatedProtocol = tbPlaceCreatedProtocol.Text;
if (string.IsNullOrWhiteSpace(tbCoordsCreatedProtocolN.Text) || string.IsNullOrEmpty(tbCoordsCreatedProtocolE.Text))
throw new Exception("Не указаны координаты составления протокола");
Violation.CreatedProtocolN = Convert.ToDouble(tbCoordsCreatedProtocolN.Text.Replace('.', ','));
Violation.CreatedProtocolE = Convert.ToDouble(tbCoordsCreatedProtocolE.Text.Replace('.', ','));
if (string.IsNullOrWhiteSpace(tbCoordsViolationE.Text) || string.IsNullOrWhiteSpace(tbCoordsViolationN.Text))
throw new Exception("Не указаны координаты правонарушения");
Violation.ViolationN = Convert.ToDouble(tbCoordsViolationN.Text.Replace('.', ','));
Violation.ViolationE = Convert.ToDouble(tbCoordsViolationE.Text.Replace('.', ','));
Violation.DateCreatedProtocol = dpCreatedProtocol.Value.Date + dpTimeCreatedProtocol.Value.TimeOfDay;
Violation.DateViolation = dpViolationDate.Value.Date + dpTimeViolation.Value.TimeOfDay;
Violation.ViolationDescription = tbDescriptionViolation.Text;
Violation.KOAP = tbKOAP.Text;
Violation.FindedNatureManagementProducts = tbFindedNatureManagementProducts.Text;
Violation.FindedGunsHuntingAndFishing = tbFindedGunsHuntingAndFishing.Text;
Violation.FindedWeapons = tbFindedWeapons.Text;
Violation.WitnessFIO_1 = tbWitnessFIO_1.Text;
Violation.WitnessFIO_2 = tbWitnessFIO_2.Text;
Violation.WitnessLive_1 = tbWitnessLive_1.Text;
Violation.WitnessLive_2 = tbWitnessLive_2.Text;
Violation.RulingNumber = tbRulingNumber.Text;
Violation.Consideration = dpConsideration.Value.Date + dpTimeConsideration.Value.TimeOfDay;
Violation.Violation = tbViolation.Text;
Violation.DatePaymant = dpDatePaymant.Value;
try {
Violation.SumViolation = Convert.ToDecimal(tbSumViolation.Text.Replace('.', ','));
}catch(Exception e)
{
Violation.SumViolation = 0;
}
if (tbSumRecovery.Text == "") tbSumRecovery.Text = "0";
Violation.SumRecovery = Convert.ToDecimal(tbSumRecovery.Text.Replace('.', ','));
Violation.GotPersonaly = chbGotPersonaly.Checked;
if (Violation.GotPersonaly)
{
Violation.DateSent = Violation.Consideration;
Violation.NumberSent = "";
}else
{
Violation.DateSent = dpDateSent.Value;
Violation.NumberSent = tbNumberSent.Text;
}
Violation.DateReceiving = dpDateReceiving.Value;
Violation.DateSentBailiff = dpDateSentBailiff.Value;
Violation.NumberSentBailigg = tbNumberSentBailigg.Text;
Violation.DateNotice = dpDateNotice.Value;
Violation.NumberNotice = tbNumberNotice.Text;
Violation.DateAgenda2025 = dpDateAgenda2025.Value;
}
public void UpdateEmployer()
{
if (Violation.Employer == null) return;
string fio = Violation.Employer.FirstName + " " + Violation.Employer.SecondName + " " + Violation.Employer.MiddleName;
string position = "";
if (ConfigApp.EmploerPositions.ContainsKey(Violation.Employer.Position_PositionID))
{
position = ConfigApp.EmploerPositions[Violation.Employer.Position_PositionID];
}
lbEmployerFIO.Text = fio;
lbEmployerPosition.Text = position;
}
public void UpdateViolator()
{
if (Violation.ViolatorPersone == null) return;
string fio = Violation.ViolatorPersone.FirstName + " " + Violation.ViolatorPersone.SecondName + " " + Violation.ViolatorPersone.MiddleName;
lbViolatorFIO.Text = fio;
List<string> documents = new List<string>();
cmbDocument.Items.Clear();
foreach (var doc in Violation.ViolatorPersone.Documents)
{
string doc_str = "";
if (ConfigApp.DocumentsType.ContainsKey(doc.Document_DocumentTypeID)) doc_str = ConfigApp.DocumentsType[doc.Document_DocumentTypeID] + " ";
doc_str += doc.Serial + " " + doc.Number + " " + doc.IssuedBy + " " + doc.WhenIssued.ToShortDateString();
cmbDocument.Items.Add(doc_str);
}
cmbDocument.Enabled = true;
cmbDocument.SelectedIndex = 0;
foreach(var address in Violation.ViolatorPersone.Address)
{
if (address.Note == null || address.Note.Equals("Проживает и прописан"))
{
lbViolatorLive.Text = address.ToString();
lbViolatorRegistration.Text = address.ToString();
break;
}
else if (address.Note != null && address.Note.Equals("Проживает"))
{
lbViolatorLive.Text = address.ToString();
}
else
{
lbViolatorRegistration.Text = address.ToString();
}
}
if(string.IsNullOrWhiteSpace(lbViolatorLive.Text) && !string.IsNullOrWhiteSpace(lbViolatorRegistration.Text))
{
lbViolatorLive.Text = lbViolatorRegistration.Text;
}else if(string.IsNullOrWhiteSpace(lbViolatorRegistration.Text) && !string.IsNullOrWhiteSpace(lbViolatorLive.Text))
{
lbViolatorRegistration.Text = lbViolatorLive.Text;
}
lbViolatorWork.Text = Violation.ViolatorPersone.PlaceWork;
if (string.IsNullOrWhiteSpace(lbViolatorWork.Text)) lbViolatorWork.Text = "Временно безработный";
lbViolatorDateB.Text = Violation.ViolatorPersone.DateBirthday.ToShortDateString();
lbViolatorPlaceB.Text = Violation.ViolatorPersone.PlaceOfBirth;
if (Violation.ViolatorPersone.Phones != null && Violation.ViolatorPersone.Phones.Count != 0)
lbViolatorPhone.Text = Violation.ViolatorPersone.Phones.First().PhoneNumber;
}
private void SelectedNewDocument()
{
if (Violation.ViolatorPersone == null || Violation.ViolatorPersone.Documents == null) return;
Violation.ViolatorDocument = Violation.ViolatorPersone.Documents[cmbDocument.SelectedIndex];
}
private void UpdateImages()
{
photosList.Controls.Clear();
foreach (var image in Violation.Images)
{
PictureViewer pv = new PictureViewer();
pv.OnDeleteClick += (p) =>
{
if (MessageBox.Show("Вы уверены, что хотите удалить это избражение?", "Предупреждение", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
this.photosList.Controls.Remove(pv);
_violation.Images.Remove(image);
}
};
pv.Image = image.Image;
photosList.Controls.Add(pv);
}
}
private void chbGotPersonaly_CheckedChanged(object sender, EventArgs e)
{
Violation.GotPersonaly = chbGotPersonaly.Checked;
chbWasSent.Enabled = !Violation.GotPersonaly;
if (Violation.GotPersonaly)
{
dpDateSent.Enabled = false;
tbNumberSent.Enabled = false;
}
else
{
dpDateSent.Value = Violation.DateSent;
tbNumberSent.Text = Violation.NumberSent;
dpDateSent.Enabled = chbWasSent.Checked;
tbNumberSent.Enabled = chbWasSent.Checked;
}
}
private void chbWasPaymant_CheckedChanged(object sender, EventArgs e)
{
Violation.WasPaymant = chbWasPaymant.Checked;
if (Violation.WasPaymant)
{
dpDatePaymant.Enabled = true;
tbSumRecovery.Enabled = true;
}else
{
dpDatePaymant.Enabled = false;
tbSumRecovery.Enabled = false;
}
}
private void chbWasSent_CheckedChanged(object sender, EventArgs e)
{
Violation.WasSent = chbWasSent.Checked;
if (Violation.WasSent)
{
dpDateSent.Enabled = true;
tbNumberSent.Enabled = true;
}else
{
dpDateSent.Enabled = false;
tbNumberSent.Enabled = false;
}
}
private void chbWasReceiving_CheckedChanged(object sender, EventArgs e)
{
Violation.WasReceiving = chbWasReceiving.Checked;
if (Violation.WasReceiving)
{
dpDateReceiving.Enabled = true;
}else
{
dpDateReceiving.Enabled = false;
}
}
private void chbWasSentBailiff_CheckedChanged(object sender, EventArgs e)
{
Violation.WasSentBailiff = chbWasSentBailiff.Checked;
if (Violation.WasSentBailiff)
{
dpDateSentBailiff.Enabled = true;
tbNumberSentBailigg.Enabled = true;
}else
{
dpDateSentBailiff.Enabled = false;
tbNumberSentBailigg.Enabled = false;
}
}
private void chbWasNotice_CheckedChanged(object sender, EventArgs e)
{
Violation.WasNotice = chbWasNotice.Checked;
if (Violation.WasNotice)
{
dpDateNotice.Enabled = true;
tbNumberNotice.Enabled = true;
}else
{
dpDateNotice.Enabled = false;
tbNumberNotice.Enabled = false;
}
}
private void chbWasAgenda2025_CheckedChanged(object sender, EventArgs e)
{
Violation.WasAgenda2025 = chbWasAgenda2025.Checked;
if (Violation.WasAgenda2025)
{
dpDateAgenda2025.Enabled = true;
}else
{
dpDateAgenda2025.Enabled = false;
}
}
private void btnAddPhoto_Click_1(object sender, EventArgs e)
{
imageDialog.Filter = "Images (*.jpeg,*.png,*.jpg,*.gif) |*.jpeg;*.png;*.jpg;*.gif";
if (imageDialog.ShowDialog() == DialogResult.OK)
{
for (int i = 0; i < imageDialog.FileNames.Length; i++)
{
FileStream fs = new FileStream(imageDialog.FileNames[i], FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
string name = imageDialog.SafeFileNames[i].Split(new[] { '.' })[0];
var violationImage = new ViolationImage
{
Image = data,
Name = name
};
Violation.Images.Add(violationImage);
PictureViewer pv = new PictureViewer();
pv.OnDeleteClick += (p) =>
{
if (MessageBox.Show("Вы уверены, что хотите удалить это избражение?", "Предупреждение", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
this.photosList.Controls.Remove(pv);
_violation.Images.Remove(violationImage);
}
};
pv.Image = data;
photosList.Controls.Add(pv);
}
}
}
}
}
<file_sep>/Tests/Services/TestPersonesService.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AppData.Abstract;
using Moq;
using AppPresentators.Services;
using AppData.Entities;
using AppData.FakesRepositoryes;
using System.Collections.Generic;
using System.Linq;
using AppPresentators.VModels.Persons;
namespace Tests.Services
{
//[TestClass]
public class TestPersonesService
{
private IPersoneRepository _userRepository;
private IPersonePositionRepository _positionRepository;
private IPersoneAddressRepository _userAdddresRepository;
private IPhonesRepository _phoneRepository;
private IDocumentRepository _documentsRepository;
private IDocumentTypeRepository _documentsTypeRepository;
private PersonesService _target;
[TestInitialize]
public void Initialize()
{
_userRepository = new FakePersonesRepository();
_positionRepository = new FakePersonsPositionRepository();
_userAdddresRepository = new FakePersonesAddressRepository();
_phoneRepository = new FakePhonesRepository();
_documentsRepository = new FakeDocumentRespository();
_documentsTypeRepository = new FakeDocumentTypeRepository();
_target = new PersonesService(_userRepository, _positionRepository, _userAdddresRepository, _phoneRepository, _documentsRepository, _documentsTypeRepository);
}
[TestMethod]
public void TestGetAllUsers()
{
int count = _userRepository.Count;
_target.PageModel = new AppPresentators.VModels.PageModel
{
ItemsOnPage = -1
};
var users = _target.GetPersons();
Assert.AreEqual(users.Count(), count);
}
[TestMethod]
public void TestGetFirstPageItemsOnPage2()
{
int id1 = _userRepository.Persons.ToList()[0].UserID;
int id2 = _userRepository.Persons.ToList()[1].UserID;
_target.PageModel = new AppPresentators.VModels.PageModel
{
ItemsOnPage = 2
};
var persons = _target.GetPersons();
Assert.AreEqual(persons.Count, 2);
Assert.AreEqual(persons[0].UserID, id1);
Assert.AreEqual(persons[1].UserID, id2);
}
[TestMethod]
public void TestDeleteByIDPersone()
{
var personeForDelete = _userRepository.Persons.ToList()[0];
int secondUserID = _userRepository.Persons.ToList()[1].UserID;
int count = _userRepository.Count;
Assert.AreEqual(_target.GetPersons().Count(), count);
_target.Remove(_userRepository.Persons.ToList()[0].UserID);
Assert.AreEqual(_target.GetPersons().Count(), count - 1);
Assert.AreEqual(_target.GetPersons()[0].UserID, secondUserID);
}
[TestMethod]
public void TestDeleteByModel()
{
PersoneViewModel pModel = new PersoneViewModel
{
UserID = 1
};
int count = _target.GetPersons().Count - 1;
//_target.Remove(pModel);
Assert.AreEqual(_target.GetPersons().Count, count);
}
[TestMethod]
public void TestGetPersoneByID()
{
var persone = _target.GetPerson(1);
Assert.AreEqual(persone.FirstName, _userRepository.Persons.ToList()[0].FirstName);
Assert.AreEqual(persone.SecondName, _userRepository.Persons.ToList()[0].SecondName);
Assert.AreEqual(persone.MiddleName, _userRepository.Persons.ToList()[0].MiddleName);
}
[TestMethod]
public void TestAddNewPerson()
{
PersoneViewModel person = new PersoneViewModel
{
FirstName = "Test first name 1",
SecondName = "Test second name 1",
MiddleName = "Test middle name 1",
DateBirthday = new DateTime(1990, 12, 2, 0, 0, 0, DateTimeKind.Utc),
Addresses = new List<PersonAddressModelView>
{
new PersonAddressModelView
{
City = "пгт. Славянка",
Street = "Героев-Хасана",
HomeNumber = "2",
Flat = "3",
Note = "Проживает"
}
},
Phones = new List<PhoneViewModel>
{
new PhoneViewModel
{
PhoneID = 1,
PhoneNumber = "2434"
}
},
PositionID = 1,
IsEmploeyr = true
};
int maxId = _userRepository.Persons.Max(x => x.UserID);
int personsCount = _userRepository.Count;
int addressCount = _userAdddresRepository.Addresses.Count();
int phoneCount = _phoneRepository.Phones.Count();
int id = 1;// _target.AddNewPersone(person);
var lastAddress = _userAdddresRepository.Addresses.Last();
Assert.AreEqual(id, maxId + 1);
Assert.AreEqual(personsCount + 1, _userRepository.Count);
Assert.AreEqual(addressCount + 1, _userAdddresRepository.Addresses.Count());
Assert.AreEqual(phoneCount + 2, _phoneRepository.Phones.Count());
Assert.AreEqual(lastAddress.City, person.Addresses[0].City);
Assert.AreEqual(lastAddress.Street, person.Addresses[0].Street);
Assert.AreEqual(lastAddress.HomeNumber, person.Addresses[0].HomeNumber);
Assert.AreEqual(lastAddress.Flat, person.Addresses[0].Flat);
}
#region Тестирование поиска
[TestMethod]
public void TestSearchUserByFirstNameContain()
{
_target.SearchModel = new PersonsSearchModel
{
FirstName = "Сид",
CompareFirstName = AppPresentators.VModels.CompareString.CONTAINS
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
}
[TestMethod]
public void TestSearchUserByFirstNameEqual()
{
_target.SearchModel = new PersonsSearchModel
{
FirstName = "Иванов",
CompareFirstName = AppPresentators.VModels.CompareString.EQUAL
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
}
[TestMethod]
public void TestSearchUserByFirstNameNotSearch()
{
_target.SearchModel = new PersonsSearchModel
{
FirstName = "Ге",
CompareFirstName = AppPresentators.VModels.CompareString.EQUAL
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 0);
}
[TestMethod]
public void TestSearchUserBySecondName()
{
_target.SearchModel = new PersonsSearchModel
{
SecondName = "Илья",
CompareSecondName = AppPresentators.VModels.CompareString.EQUAL
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
_target.SearchModel = new PersonsSearchModel
{
SecondName = "Евг",
CompareSecondName = AppPresentators.VModels.CompareString.CONTAINS
};
result = _target.GetPersons();
Assert.AreEqual(result.Count, 1);
Assert.AreEqual(result[0].MiddleName, "Эдуардович");
_target.SearchModel = new PersonsSearchModel
{
MiddleName = "Петро",
CompareMiddleName = AppPresentators.VModels.CompareString.CONTAINS
};
result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
}
[TestMethod]
public void TestSearchUserByDateBirthdayMore()
{
_target.SearchModel = new PersonsSearchModel
{
DateBirthday = new DateTime(1991, 5, 10, 0, 0, 0),
CompareDate = AppPresentators.VModels.CompareValue.MORE
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 2) != null);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 5) != null);
}
[TestMethod]
public void TestSearchUserByDateBirthdayLess()
{
_target.SearchModel = new PersonsSearchModel
{
DateBirthday = new DateTime(1991, 5, 10, 0, 0, 0),
CompareDate = AppPresentators.VModels.CompareValue.LESS
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 3);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 1) != null);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 3) != null);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 4) != null);
}
[TestMethod]
public void TestSearchUserByAgeLess()
{
_target.SearchModel = new PersonsSearchModel
{
Age = 24,
CompareAge = AppPresentators.VModels.CompareValue.LESS
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 2) != null);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 5) != null);
}
[TestMethod]
public void TestSearchUserByAgeMore()
{
_target.SearchModel = new PersonsSearchModel
{
Age = 24,
CompareAge = AppPresentators.VModels.CompareValue.MORE
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 4);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 1) != null);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 2) != null);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 3) != null);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 4) != null);
}
[TestMethod]
public void TestSearchByEmployersFlag()
{
_target.SearchModel = new PersonsSearchModel
{
IsEmployer = true
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
}
[TestMethod]
public void TestSearchByEmployersFlagAndPositionName()
{
_target.SearchModel = new PersonsSearchModel
{
IsEmployer = true,
Position = "Госинспектор"
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 1);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 4) != null);
}
[TestMethod]
public void SearchByAddressCountry()
{
_target.SearchModel = new PersonsSearchModel
{
Address = new SearchAddressModel
{
Country = "Российская Федерация"
}
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 5);
}
[TestMethod]
public void SearchByAddressCityEquals()
{
_target.SearchModel = new PersonsSearchModel
{
Address = new SearchAddressModel
{
City = "с.Барабаш"
}
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
}
[TestMethod]
public void SearchByAddressCityContains()
{
_target.SearchModel = new PersonsSearchModel
{
Address = new SearchAddressModel
{
City = "Барабаш",
CompareCity = AppPresentators.VModels.CompareString.CONTAINS
}
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
}
[TestMethod]
public void SearchByAddressStreetEquals()
{
_target.SearchModel = new PersonsSearchModel
{
Address = new SearchAddressModel
{
Street = "Гагарина"
}
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 1);
}
[TestMethod]
public void SearchByAddressStreetContains()
{
_target.SearchModel = new PersonsSearchModel
{
Address = new SearchAddressModel
{
Street = "Моло",
CompareStreet = AppPresentators.VModels.CompareString.CONTAINS
}
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
}
[TestMethod]
public void SearchByAddressHomeNumberEquals()
{
_target.SearchModel = new PersonsSearchModel
{
Address = new SearchAddressModel
{
HomeNumber = "7"
}
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 3);
}
[TestMethod]
public void SearchByAddressFlatEquals()
{
_target.SearchModel = new PersonsSearchModel
{
Address = new SearchAddressModel
{
Flat = "15"
}
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 1);
}
[TestMethod]
public void SearchByAddressNote()
{
_target.SearchModel = new PersonsSearchModel
{
Address = new SearchAddressModel
{
Note = "Прописка"
}
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 5);
}
[TestMethod]
public void SearchAndPageModel()
{
_target.SearchModel = new PersonsSearchModel
{
Address = new SearchAddressModel
{
Note = "Прописка"
}
};
_target.PageModel = new AppPresentators.VModels.PageModel
{
ItemsOnPage = 2,
CurentPage = 1
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
Assert.AreEqual(_target.PageModel.TotalItems, 5);
Assert.AreEqual(_target.PageModel.TotalPages, 3);
}
[TestMethod]
public void TestSearchByDocumentType()
{
_target.DocumentSearchModel = new DocumentSearchModel
{
//DocumentTypeName = "Водительские права"
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
}
[TestMethod]
public void TestSearchByDocumentSerial()
{
_target.DocumentSearchModel = new DocumentSearchModel
{
Serial = "524"
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
}
[TestMethod]
public void TestSearchByDocumentNumber()
{
_target.DocumentSearchModel = new DocumentSearchModel
{
Number = "223"
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 1);
}
[TestMethod]
public void TestSearchByDocumentIssuedBy()
{
_target.DocumentSearchModel = new DocumentSearchModel
{
IssuedBy = "Выдан 3",
CompareIssuedBy = AppPresentators.VModels.CompareString.EQUAL
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
}
[TestMethod]
public void TestSearchByDocumentWhenIssuedEquals()
{
_target.DocumentSearchModel = new DocumentSearchModel
{
WhenIssued = new DateTime(2011, 7, 9, 0, 0, 0),
CompareWhenIssued = AppPresentators.VModels.CompareValue.EQUAL
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 1);
}
[TestMethod]
public void TestSearchByDocumentWhenIssuedMore()
{
_target.DocumentSearchModel = new DocumentSearchModel
{
WhenIssued = new DateTime(2011, 7, 10, 0, 0, 0),
CompareWhenIssued = AppPresentators.VModels.CompareValue.MORE
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 4);
}
[TestMethod]
public void TestSearchByDocumentWhenIssuedLess()
{
_target.DocumentSearchModel = new DocumentSearchModel
{
WhenIssued = new DateTime(2011, 7, 10, 0, 0, 0),
CompareWhenIssued = AppPresentators.VModels.CompareValue.LESS
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 1);
}
[TestMethod]
public void TestSearchByDocumentCodeDevissionEquals()
{
_target.DocumentSearchModel = new DocumentSearchModel
{
CodeDevision = "234",
CompareCodeDevision = AppPresentators.VModels.CompareString.EQUAL
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 1);
}
[TestMethod]
public void TestSearchByDocumentCodeDevissionCotains()
{
_target.DocumentSearchModel = new DocumentSearchModel
{
CodeDevision = "234",
CompareCodeDevision = AppPresentators.VModels.CompareString.CONTAINS
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 2);
}
[TestMethod]
public void TestSearchByDocumentAndFirstName()
{
_target.DocumentSearchModel = new DocumentSearchModel
{
CodeDevision = "234",
CompareCodeDevision = AppPresentators.VModels.CompareString.CONTAINS
};
_target.SearchModel = new PersonsSearchModel
{
FirstName = "Кирилов",
CompareFirstName = AppPresentators.VModels.CompareString.EQUAL
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 1);
}
[TestMethod]
public void TestSearchByDocumentSerialAndPersonAge()
{
_target.DocumentSearchModel = new DocumentSearchModel
{
Serial = "524"
};
_target.SearchModel = new PersonsSearchModel
{
Age = 23,
CompareAge = AppPresentators.VModels.CompareValue.LESS
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 1);
Assert.IsTrue(result.FirstOrDefault(p => p.UserID == 5) != null);
}
#endregion
#region Тестирование сортировки
[TestMethod]
public void OrderByFirstName()
{
_target.OrderModel = new PersonsOrderModel
{
OrderType = AppPresentators.VModels.OrderType.ASC,
OrderProperties = PersonsOrderProperties.FIRST_NAME
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 5);
Assert.AreEqual(result[0].UserID, 1);
Assert.AreEqual(result[1].UserID, 5);
}
[TestMethod]
public void OrderBySecondNameDesc()
{
_target.OrderModel = new PersonsOrderModel
{
OrderType = AppPresentators.VModels.OrderType.DESC,
OrderProperties = PersonsOrderProperties.SECOND_NAME
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 5);
Assert.AreEqual(result[0].UserID, 5);
Assert.AreEqual(result[1].UserID, 3);
}
[TestMethod]
public void OrderByAgeDesc()
{
_target.OrderModel = new PersonsOrderModel
{
OrderType = AppPresentators.VModels.OrderType.DESC,
OrderProperties = PersonsOrderProperties.AGE
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 5);
Assert.AreEqual(result[0].UserID, 4);
Assert.AreEqual(result[1].UserID, 3);
}
[TestMethod]
public void OrderByDateBerthdayDesc()
{
_target.OrderModel = new PersonsOrderModel
{
OrderType = AppPresentators.VModels.OrderType.DESC,
OrderProperties = PersonsOrderProperties.DATE_BERTHDAY
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 5);
Assert.AreEqual(result[0].UserID, 5);
Assert.AreEqual(result[1].UserID, 2);
}
[TestMethod]
public void OrderByMiddleName()
{
_target.OrderModel = new PersonsOrderModel
{
OrderType = AppPresentators.VModels.OrderType.ASC,
OrderProperties = PersonsOrderProperties.MIDDLE_NAME
};
var result = _target.GetPersons();
Assert.AreEqual(result.Count, 5);
Assert.AreEqual(result[0].UserID, 1);
Assert.AreEqual(result[1].UserID, 4);
}
[TestMethod]
public void TestSearchAndPginationsAndOrder()
{
_target.SearchModel = new PersonsSearchModel
{
Address = new SearchAddressModel
{
Note = "Прописка"
}
};
_target.PageModel = new AppPresentators.VModels.PageModel
{
ItemsOnPage = 2,
CurentPage = 1
};
_target.OrderModel = new PersonsOrderModel
{
OrderType = AppPresentators.VModels.OrderType.DESC,
OrderProperties = PersonsOrderProperties.AGE
};
var result = _target.GetPersons();
Assert.AreEqual(_target.PageModel.TotalItems, 5);
Assert.AreEqual(_target.PageModel.TotalPages, 3);
Assert.AreEqual(result.Count, 2);
Assert.AreEqual(result[0].UserID, 4);
Assert.AreEqual(result[1].UserID, 3);
}
#endregion
// Добавить тесты на выборку только сотрудников, добавить тесты на фильтрацию и сортировку, и последнее - добавить тесты на паджинацию.
}
}
<file_sep>/AppCore/Entities/ProtocolAboutWithdraw.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
/// <summary>
/// Протокол об изъятие
/// </summary>
public class ProtocolAboutWithdraw:IProtocol
{
[Key]
public int ProtocolAboutWithdrawID { get; set; }
[Required(AllowEmptyStrings = false)]
public Protocol Protocol { get; set; }
[Required(AllowEmptyStrings = false)]
public int ViolatorDocumentID { get; set; }
/// <summary>
/// Изъятое оружие
/// </summary>
public string WithdrawWeapons { get; set; }
/// <summary>
/// Изъятые боеприпасы
/// </summary>
public string WithdrawAmmunitions { get; set; }
/// <summary>
/// Изъятые орудия охоты и рыболовства
/// </summary>
public string WithdrawGunsHuntingAndFishing { get; set; }
/// <summary>
/// Изъятая продукция природопользования
/// </summary>
public string WithdrawNatureManagementProducts { get; set; }
/// <summary>
/// Изъятые документы
/// </summary>
public string WithdrawDocuments { get; set; }
/// <summary>
/// Методы фиксации правонарушения
/// </summary>
public string FixingMethods { get; set; }
}
}
<file_sep>/LeoBase/Components/TopMenu/PictureButton.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.TopMenu
{
public class PictureButton:PictureBox
{
public event EventHandler OnClick;
private bool _enabled = false;
private Image _defaultImage;
private Image _disabledImage;
private Image _pressImage;
public bool Enabled
{
get
{
return _enabled;
}
set
{
_enabled = true;
if (true)
{
this.BackgroundImage = _defaultImage;
}
else
{
this.BackgroundImage = _disabledImage;
}
}
}
public PictureButton(Image defaultImage, Image disabledImage, Image pressImage) : base()
{
_defaultImage = defaultImage;
_disabledImage = disabledImage;
_pressImage = pressImage;
this.BackgroundImage = _disabledImage;
this.Click += PictureButton_Click;
this.Width = _disabledImage.Width + 10;
this.Height = _disabledImage.Height + 6;
this.BackColor = Color.Transparent;
this.Cursor = Cursors.Hand;
this.MouseDown += PictureButton_MouseDown;
this.MouseLeave += PictureButtonDefaultImage;
this.MouseUp += PictureButtonDefaultImage;
this.BackgroundImageLayout = ImageLayout.Center;
}
private void PictureButtonDefaultImage(object sender, EventArgs e)
{
if (Enabled)
{
this.BackgroundImage = _defaultImage;
}
else
{
this.BackgroundImage = _disabledImage;
}
}
private void PictureButton_MouseDown(object sender, MouseEventArgs e)
{
if (Enabled)
{
this.BackgroundImage = _pressImage;
}
}
private void PictureButton_Click(object sender, EventArgs e)
{
if(Enabled && OnClick != null)
{
OnClick(sender, e);
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/MapControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppData.Entities;
using AppPresentators.VModels.Map;
using LeoMapV3.Map;
using LeoMapV3.Data;
using LeoMapV3.Models;
using AppPresentators;
using System.IO;
using LeoBase.Components.TopMenu;
namespace LeoBase.Components.CustomControls.NewControls
{
public partial class MapControl : UserControl, IMapControl
{
private LeoMap _map;
private TitleDBRepository _repo;
private MapSearchModel SearchModel;
public MapControl()
{
InitializeComponent();
this.Load += MapControl_Load;
SearchModel = new MapSearchModel();
dtpFrom.Value = DateTime.Now.AddYears(-1);
dtpTo.Value = DateTime.Now;
SearchModel.DateFrom = dtpFrom.Value;
SearchModel.DateTo = dtpTo.Value;
SearchModel.MapRegion = new AppPresentators.VModels.Map.MapRegion
{
E = 133,
N = 50,
W = 120,
S = 40
};
if (!File.Exists(ConfigApp.DefaultMapPath))
{
MessageBox.Show("Не удается найти карту по указанному пути: " + ConfigApp.DefaultMapPath, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try {
_repo = new TitleDBRepository(ConfigApp.DefaultMapPath); //"D:\\Maps\\test.lmap");
}catch(Exception e)
{
MessageBox.Show("Не удается прочитать файл с картой: " + ConfigApp.DefaultMapPath, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_map = new LeoMap(_repo);
_map.Dock = DockStyle.Fill;
panelMap.Controls.Add(_map);
_map.MouseMoving += (s, p) =>
{
lbCoords.Text = string.Format("N:{0:0.000000}; E:{1:0.000000}", p.N, p.E);
};
_map.RegionSelected += SelectedRegion;
_map.PointClicked += ClickedToPoint;
dtpFrom.ValueChanged += DtpFrom_ValueChanged;
dtpTo.ValueChanged += DtpTo_ValueChanged;
}
private void DtpTo_ValueChanged(object sender, EventArgs e)
{
if (dtpFrom.Value > dtpTo.Value)
{
return;
}
SearchModel.DateFrom = dtpFrom.Value;
SearchModel.DateTo = dtpTo.Value;
if (FilterViolations != null) FilterViolations(SearchModel);
}
private void DtpFrom_ValueChanged(object sender, EventArgs e)
{
if (dtpFrom.Value > dtpTo.Value)
{
return;
}
SearchModel.DateFrom = dtpFrom.Value;
SearchModel.DateTo = dtpTo.Value;
if (FilterViolations != null) FilterViolations(SearchModel);
}
private void MapControl_Load(object sender, EventArgs e)
{
if (_map != null) _map.ClearPoints();
if (FilterViolations != null) FilterViolations(SearchModel);
}
private void ClickedToPoint(object arg1, LeoMapV3.Models.DPoint arg2)
{
var map = arg1 as LeoMap;
if (map == null) return;
if (OpenViolation != null) OpenViolation(((AdminViolation)(arg2.DataSource)).ViolationID);
//if (!string.IsNullOrEmpty(arg2.ToolTip)) MessageBox.Show(string.Format("Tool tip:{0}\r\nX:{1}; Y:{2}", arg2.ToolTip, map.ClientMouseX, map.ClientMouseY));
}
private void SelectedRegion(object arg1, LeoMapV3.Models.MapRegion arg2)
{
if(dtpFrom.Value > dtpTo.Value)
{
MessageBox.Show("Даты для поиска указаны не верно.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
SearchModel.MapRegion = new AppPresentators.VModels.Map.MapRegion
{
E = arg2.E,
N = arg2.N,
W = arg2.W,
S = arg2.S
};
SearchModel.DateFrom = dtpFrom.Value;
SearchModel.DateTo = dtpTo.Value;
btnClearSelected.Enabled = true;
if (FilterViolations != null) FilterViolations(SearchModel);
}
private List<AdminViolation> _violations;
public List<AdminViolation> DataSource
{
get
{
return _violations;
}
set
{
if (_map != null) _map.ClearPoints();
_violations = value;
if (value != null && _map != null)
{
foreach (var v in _violations) SetPoint(v);
}
if(_map != null) _map.Redraw();
}
}
public bool ShowForResult { get; set; }
public List<Control> TopControls { get
{
var _btnReport = new PictureButton(Properties.Resources.reportEnabled, Properties.Resources.reportDisabled, Properties.Resources.reportPress);
_btnReport.Click += ReportClick;
_btnReport.Enabled = true;
return new List<Control> { _btnReport };
}
set { }
}
private void ReportClick(object sender, EventArgs e)
{
///TODO:Сделать отчет
}
public event Action<MapSearchModel> FilterViolations;
public event Action<int> OpenViolation;
public void ClearPoints()
{
if (_map == null) return;
_map.ClearPoints();
_map.Redraw();
}
public Control GetControl()
{
return this;
}
public void SetPoint(AdminViolation violation)
{
if (_map == null) return;
DPoint point = new DPoint
{
E = violation.ViolationE,
N = violation.ViolationN,
DataSource = violation,
ToolTip = violation.Violation
};
_map.SetPoint(point);
}
public void SetPoint(MapPoint point)
{
if (_map == null) return;
_map.SetPoint(new DPoint
{
E = point.E,
N = point.N,
ToolTip = point.ToolTip
});
}
void UIComponent.Resize(int width, int height)
{
}
private void btnClearSelected_Click(object sender, EventArgs e)
{
if (_map == null) return;
SearchModel.MapRegion = new AppPresentators.VModels.Map.MapRegion
{
E = 135,
N = 45,
W = 129,
S = 39
};
btnClearSelected.Enabled = false;
if (FilterViolations != null) FilterViolations(SearchModel);
}
}
}
<file_sep>/AppPresentators/VModels/VManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public interface IVManager
{
string Login { get; set; }
string Password { get; set; }
string Role { get; set; }
int ManagerID { get; set; }
}
public class VManager:IVManager
{
public string Login { get; set; }
public string Password { get; set; }
public string Role { get; set; }
public int ManagerID { get; set; }
}
}
<file_sep>/WPFPresentators/Presentators/LoginPresentator.cs
using BFData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFPresentators.Services;
using WPFPresentators.Views.Windows;
namespace WPFPresentators.Presentators
{
public delegate void LoginComplete(Manager manager);
public class LoginPresentator:IPresentator
{
private ILoginView _view;
private ILoginService _service;
public event LoginComplete OnLoginComplete;
public LoginPresentator(ILoginView view, ILoginService service)
{
_view = view;
_service = service;
_view.OnLogin += () => Login(_view.Login, _view.Password);
}
private void Login(string login, string password)
{
var manager = _service.Login(login, password);
if (manager == null) {
ShowError("Неверно указан логин или пароль.");
return;
}
if (OnLoginComplete != null)
{
OnLoginComplete(manager);
_view.Close();
}
}
public void Show()
{
_view.Show();
}
public void ShowError(string message)
{
_view.ShowError(message);
}
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/ProtocolsPresentators/IProtocolPresentator.cs
using AppPresentators.Infrastructure;
using AppPresentators.VModels.MainMenu;
using AppPresentators.VModels.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppPresentators.Presentators.Interfaces.ProtocolsPresentators
{
public delegate void RemoveProtocolEvent(int key);
public interface IProtocolPresentator
{
event RemoveProtocolEvent OnRemove;
ProtocolViewModel Protocol { get; set; }
int Key { get; set; }
Control GetControl();
void Save();
void Remove();
void SetResult(ResultTypes command, object data);
}
}
<file_sep>/AppPresentators/VModels/Persons/PersonsSearchModel.cs
using AppData.CustomAttributes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace AppPresentators.VModels.Persons
{
public class PersonsSearchModel
{
[Browsable(false)]
public int PersoneID { get; set; } = 0;
[DisplayName("Фамилия")]
public string FirstName { get; set; }
[DisplayName("Имя")]
public string SecondName { get; set; }
[DisplayName("Отчество")]
public string MiddleName { get; set; }
[DisplayName("Дата рождения")]
[ControlType(ControlType.DateTime)]
[ChildrenProperty("CompareDate")]
public DateTime DateBirthday { get; set; }
[Browsable(false)]
public CompareValue CompareDate { get; set; } = CompareValue.NONE;
[DisplayName("Возраст")]
[ControlType(ControlType.Int)]
[ChildrenProperty("CompareAge")]
[Browsable(false)]
public int Age { get; set; } = 0;
[Browsable(false)]
public CompareValue CompareAge { get; set; } = CompareValue.NONE;
[DisplayName("Адрес")]
public SearchAddressModel Address { get; set; }
[ControlType(ControlType.ComboBox, "Display", "Value")]
[DataPropertiesName("PositionData")]
[DisplayName("Должность")]
[DinamicBrowsable("IsEmployer", true)]
public string Position { get; set; }
[Browsable(false)]
public bool IsEmployer { get; set; }
[DisplayName("Место рождения")]
[DinamicBrowsable("IsEmployer", false)]
public string PlaceOfBirth { get; set; }
[DisplayName("Место работы")]
[DinamicBrowsable("IsEmployer", false)]
public string PlaceWork { get; set; }
[Browsable(false)]
public DateTime WasBeCreated { get; set; }
[Browsable(false)]
public CompareValue CompareWasBeCreated { get; set; } = CompareValue.EQUAL;
[Browsable(false)]
public DateTime WasBeUpdated { get; set; }
[Browsable(false)]
public CompareValue CompareWasBeUpdated { get; set; } = CompareValue.EQUAL;
[Browsable(false)]
public CompareString CompareSecondName { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public CompareString CompareMiddleName { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public CompareString ComparePlaceWork { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public CompareString ComparePlaceOfBirth { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public CompareString CompareFirstName { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public List<ComboBoxDefaultItem> PositionData
{
get
{
List<ComboBoxDefaultItem> data = new List<ComboBoxDefaultItem>();
data.Add(new ComboBoxDefaultItem { Display = "Не использовать", Value = "Не использовать" });
data.AddRange(ConfigApp.EmployerPositionsList.Select(p => new ComboBoxDefaultItem { Display = p.Name, Value = p.Name }).ToList());
return data;
}
}
[Browsable(false)]
public bool IsEmptySearch { get
{
return
string.IsNullOrEmpty(FirstName)
&& string.IsNullOrEmpty(SecondName)
&& string.IsNullOrEmpty(MiddleName)
&& (WasBeCreated.Year == 1)
&& (WasBeUpdated.Year == 1)
&& (DateBirthday.Year == 1)
&& string.IsNullOrEmpty(Position)
&& Age == 0
&& (Address == null || Address.IsEmptyAddress)
&& string.IsNullOrEmpty(PlaceOfBirth)
&& (IsEmployer == null)
&& string.IsNullOrEmpty(PlaceWork);
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/ViolatorDetailsControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.VModels;
using LeoBase.Components.TopMenu;
namespace LeoBase.Components.CustomControls.NewControls
{
public partial class ViolatorDetailsControl : UserControl, IViolatorDetailsControl
{
public event Action MakeReport;
public event Action EditViolator;
public ViolatorDetailsControl()
{
InitializeComponent();
var reportButton = new PictureButton(Properties.Resources.reportEnabled, Properties.Resources.reportDisabled, Properties.Resources.reportPress);
var editButton = new PictureButton(Properties.Resources.editEnabled, Properties.Resources.editDisabled, Properties.Resources.editPress); ;
reportButton.Enabled = true;
editButton.Enabled = true;
reportButton.Click += (s, e) =>
{
if (MakeReport != null) MakeReport();
};
editButton.Click += (s, e) =>
{
if (EditViolator != null) EditViolator();
};
TopControls = new List<Control>();
TopControls.Add(reportButton);
TopControls.Add(editButton);
this.Load += ViolatorDetailsControl_Load;
}
private void ViolatorDetailsControl_Load(object sender, EventArgs e)
{
tableAddresses.ClearSelection();
tableDocuments.ClearSelection();
tableViolations.ClearSelection();
}
public bool ShowForResult { get; set; }
public List<Control> TopControls { get; set; }
private ViolatorDetailsModel _violator;
public ViolatorDetailsModel Violator
{
get
{
return _violator;
}
set
{
_violator = value;
if (value != null) RenderDataSource();
}
}
private void RenderDataSource()
{
lbFIO.Text = Violator.FIO;
lbPlaceBerth.Text = Violator.PlaceBerth;
lbPlaceWork.Text = Violator.PlaceBerth;
lbDateBerth.Text = Violator.DateBerth.ToShortDateString();
string phones = "";
if (Violator.Phones != null)
foreach (var phone in Violator.Phones)
phones += phone.PhoneNumber + "; ";
lbPhones.Text = phones;
tableDocuments.DataSource = Violator.Documents;
tableAddresses.DataSource = Violator.Addresses;
tableViolations.DataSource = Violator.Violations;
avatarPanel.Controls.Clear();
if(Violator.Image != null) {
PictureViewer picture = new PictureViewer();
picture.Image = Violator.Image;
picture.Margin = new Padding(10, 10, 10, 10);
picture.Dock = DockStyle.Left;
picture.ShowDeleteButton = false;
picture.ShowZoomButton = false;
picture.CanSelected = false;
avatarPanel.Controls.Clear();
avatarPanel.Controls.Add(picture);
}
tableAddresses.ClearSelection();
tableDocuments.ClearSelection();
tableViolations.ClearSelection();
}
public event Action<int> ShowDetailsViolation;
public Control GetControl()
{
return this;
}
void UIComponent.Resize(int width, int height)
{
}
private void tableAddresses_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.RowIndex >= tableAddresses.Rows.Count) return;
tableAddresses.Rows[e.RowIndex].Selected = true;
}
private void tableDocuments_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.RowIndex >= tableDocuments.Rows.Count) return;
tableDocuments.Rows[e.RowIndex].Selected = true;
}
private int selectedViolationID = -1;
private void tableViolations_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.RowIndex >= tableViolations.Rows.Count) return;
tableViolations.Rows[e.RowIndex].Selected = true;
btnViolationDetails.Enabled = true;
selectedViolationID = Violator.Violations[e.RowIndex].ViolationID;
}
private void btnViolationDetails_Click(object sender, EventArgs e)
{
if (selectedViolationID == -1) return;
ShowDetailsViolation(selectedViolationID);
}
}
}
<file_sep>/AppPresentators/Infrastructure/OrderBuilders/OrderFactory.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Infrastructure.OrderBuilders
{
public class OrderFactory
{
public static IOrderBuilder GetOrderBuilder(OrdersTypes type, string dirName, string orderName, Action<string> ErrorAction = null)
{
IOrderBuilder builder = null;
DirectoryInfo dirInfo = new DirectoryInfo(dirName);
switch (type)
{
case OrdersTypes.EXCEL:
builder = new ExcelOrderBuilder();
break;
case OrdersTypes.PDF:
builder = new PDFOrderBuilder();
break;
case OrdersTypes.WORD:
builder = new WordOrderBuilder();
break;
}
builder.ErrorBuild += ErrorAction;
builder.SetOrderPath(dirInfo, orderName);
return builder;
}
}
public enum OrdersTypes
{
EXCEL,
WORD,
PDF
}
}
<file_sep>/AppPresentators/VModels/MainMenu/MenuItemModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.MainMenu
{
public class MenuItemModel
{
public string Title { get; set; }
public MenuCommand MenuCommand { get; set; }
public byte[] Icon { get; set; }
}
}
<file_sep>/AppCore/Entities/Violation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
public class Violation
{
public int ViolationID { get; set; }
public virtual List<ViolationImage> Images { get; set; }
public virtual ViolationType ViolationType { get; set; }
public virtual List<Protocol> Protocols { get; set; }
public DateTime DateSave { get; set; }
public DateTime DateUpdate { get; set; }
public DateTime Date { get; set; }
public double N { get; set; }
public double E { get; set; }
public string Description { get; set; }
}
}
<file_sep>/LeoBase/Forms/OrderDialog.cs
using AppPresentators.Infrastructure;
using AppPresentators.Infrastructure.OrderBuilders;
using AppPresentators.Infrastructure.Orders;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Spire.Pdf;
namespace LeoBase.Forms
{
public partial class OrderDialog : Form
{
public IOrderPage OrderPage { get; set; }
public event Action<string> Error;
public BackgroundWorker _backgroundWorker;
private bool _wasError = false;
public OrderDialog()
{
InitializeComponent();
_backgroundWorker = new BackgroundWorker();
_backgroundWorker.DoWork += MakeOrderAsync;
_backgroundWorker.RunWorkerCompleted += MakeOrderComplete;
}
private void MakeOrderComplete(object sender, RunWorkerCompletedEventArgs e)
{
if (_wasError)
{
this.Close();
}
if (cmbOrderType.SelectedIndex == 0)
{
panelLoad.Visible = false;
panelComplete.Visible = true;
}
else
{
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(OrderPage.OrderDirPath);
//Use the default printer to print all the pages
//doc.PrintDocument.Print();
//Set the printer and select the pages you want to print
printDialog.AllowPrintToFile = true;
printDialog.AllowSomePages = true;
printDialog.PrinterSettings.MinimumPage = 1;
printDialog.PrinterSettings.MaximumPage = doc.Pages.Count;
printDialog.PrinterSettings.FromPage = 1;
printDialog.PrinterSettings.ToPage = doc.Pages.Count;
if (printDialog.ShowDialog() == DialogResult.OK)
{
//Set the pagenumber which you choose as the start page to print
doc.PrintFromPage = printDialog.PrinterSettings.FromPage;
//Set the pagenumber which you choose as the final page to print
doc.PrintToPage = printDialog.PrinterSettings.ToPage;
//Set the name of the printer which is to print the PDF
doc.PrinterName = printDialog.PrinterSettings.PrinterName;
PrintDocument printDoc = doc.PrintDocument;
printDialog.Document = printDoc;
printDoc.Print();
}
this.Close();
}
}
private void MakeOrderAsync(object sender, DoWorkEventArgs e)
{
var arg = (OrderConfigsArgument)e.Argument;
OrderPage.BuildOrder(arg.OrderBuilder, arg.OrderConfigs);
}
private void OrderDialog_Load(object sender, EventArgs e)
{
cmbOrderFormat.SelectedIndex = 0;
cmbOrderType.SelectedIndex = 0;
if(OrderPage == null)
{
if (Error != null) Error("Не указана страница для отчета.");
this.Close();
}
if(OrderPage.OrderType == AppPresentators.Infrastructure.Orders.OrderType.SINGLE_PAGE)
{
panelTableConfig.Visible = false;
panelSingleWithImages.Visible = true;
}else
{
panelTableConfig.Visible = true;
panelSingleWithImages.Visible = false;
}
}
private void cmbOrderType_SelectedIndexChanged(object sender, EventArgs e)
{
if(cmbOrderType.SelectedIndex == 0)
{
btnOrderComplete.Text = "Сформировать отчет";
formatPanel.Visible = true;
}
else
{
btnOrderComplete.Text = "Печать";
formatPanel.Visible = false;
}
}
private void btnOrderCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnOrderComplete_Click(object sender, EventArgs e)
{
OrderConfigs configs = new OrderConfigs();
IOrderBuilder builder = null;
configs.OrderType = OrderPage.OrderType;
if(cmbOrderType.SelectedIndex == 0)
{
if (string.IsNullOrWhiteSpace(lbPath.Text))
{
Builder_ErrorBuild("Не указан путь для отчета.");
return;
}
if (string.IsNullOrWhiteSpace(tbOrderName.Text))
{
Builder_ErrorBuild("Не указано имя отчета.");
return;
}
configs.OrderDirPath = lbPath.Text;
configs.OrderName = tbOrderName.Text;
switch (cmbOrderFormat.SelectedIndex)
{
case 0:
builder = OrderFactory.GetOrderBuilder(OrdersTypes.PDF, lbPath.Text, tbOrderName.Text, Builder_ErrorBuild);
break;
case 1:
builder = OrderFactory.GetOrderBuilder(OrdersTypes.EXCEL, lbPath.Text, tbOrderName.Text, Builder_ErrorBuild);
break;
case 2:
builder = OrderFactory.GetOrderBuilder(OrdersTypes.WORD, lbPath.Text, tbOrderName.Text, Builder_ErrorBuild);
break;
}
}
else
{
configs.OrderDirPath = Directory.GetCurrentDirectory();
configs.OrderName = "OrderForPrint";
builder = OrderFactory.GetOrderBuilder(OrdersTypes.PDF, configs.OrderDirPath, configs.OrderName, Builder_ErrorBuild);
}
if (builder.WasError)
{
_wasError = false;
return;
}
if (OrderPage.OrderType == OrderType.TABLE)
{
configs.TableConfig = new OrderTableConfig
{
ConsiderFilter = chbSearchResult.Checked,
CurrentPageOnly = chbCurrentPage.Checked
};
}else
{
configs.SinglePageConfig = new OrderSinglePageConfig
{
DrawImages = chbOutputImages.Checked
};
}
OrderConfigsArgument arg = new OrderConfigsArgument
{
OrderBuilder = builder,
OrderConfigs = configs
};
penelOrderType.Visible = false;
formatPanel.Visible = false;
panelTableConfig.Visible = false;
panelSingleWithImages.Visible = false;
btnsPunel.Visible = false;
panelComplete.Visible = false;
panelLoad.Visible = true;
_backgroundWorker.RunWorkerAsync(arg);
}
private void Builder_ErrorBuild(string obj)
{
if (Error != null) Error(obj);
else MessageBox.Show(obj, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_wasError = true;
}
private void button1_Click(object sender, EventArgs e)
{
Process.Start(OrderPage.OrderDirPath);
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSelectPathForOrder_Click(object sender, EventArgs e)
{
if(orderSaveFolderDialog.ShowDialog() == DialogResult.OK)
{
lbPath.Text = orderSaveFolderDialog.SelectedPath;
}
}
}
public class OrderConfigsArgument
{
public IOrderBuilder OrderBuilder { get; set; }
public OrderConfigs OrderConfigs { get; set; }
}
}
<file_sep>/AppPresentators/Presentators/MapPresentator.cs
using AppPresentators.Presentators.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.Views;
using AppPresentators.VModels.Map;
using AppData.Contexts;
using AppData.Entities;
namespace AppPresentators.Presentators
{
public class MapPresentator : IMapPresentator
{
public ResultTypes ResultType { get; set; }
public bool ShowFastSearch
{
get
{
return false;
}
}
public bool ShowSearch
{
get
{
return false;
}
}
public bool ShowForResult { get; set; }
public List<Control> TopControls
{
get
{
return _control.TopControls;
}
}
public event SendResult SendResult;
public void FastSearch(string message)
{
}
private IMapControl _control;
private IMainView _parent;
private IApplicationFactory _appFactory;
public Control RenderControl()
{
return _control.GetControl();
}
public void SetResult(ResultTypes resultType, object data)
{
}
public MapPresentator(IMainView main, IApplicationFactory appFactory)
{
_parent = main;
_appFactory = appFactory;
_control = _appFactory.GetComponent<IMapControl>();
_control.FilterViolations += FilteringViolation;
_control.OpenViolation += OpenDetailsViolation;
}
private void OpenDetailsViolation(int id)
{
var mainPresentator = _appFactory.GetMainPresentator();
var detailsViolatorPresentator = _appFactory.GetPresentator<IViolationDetailsPresentator>();
using (var db = new LeoBaseContext())
{
detailsViolatorPresentator.Violation = db.AdminViolations.Include("Employer")
.Include("ViolatorOrganisation")
.Include("ViolatorPersone")
.Include("ViolatorDocument")
.Include("Images")
.FirstOrDefault(v => v.ViolationID == id);
}
mainPresentator.ShowComponentForResult(this, detailsViolatorPresentator, ResultTypes.UPDATE_VIOLATION);
}
private void FilteringViolation(MapSearchModel searchModel)
{
using(var db = new LeoBaseContext())
{
var violations = db.AdminViolations.Where(v => v.DateViolation >= searchModel.DateFrom && v.DateViolation <= searchModel.DateTo
&& v.ViolationE <= searchModel.MapRegion.E
&& v.ViolationN <= searchModel.MapRegion.N
&& v.ViolationE >= searchModel.MapRegion.W
&& v.ViolationN >= searchModel.MapRegion.S);
var listViolations = violations == null ? new List<AdminViolation>() : violations.ToList();
_control.DataSource = listViolations;
}
//throw new NotImplementedException();
}
}
}
<file_sep>/AppCore/Abstract/IDocumentTypeRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract
{
public interface IDocumentTypeRepository
{
IQueryable<DocumentType> DocumentTypes { get; }
}
}
<file_sep>/AppPresentators/VModels/Protocols/ProtocolAboutViolationOrganisationViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Protocols
{
/// <summary>
/// Протокол об административном правонарушение для юридического лица
/// </summary>
public class ProtocolAboutViolationOrganisationViewModel:ProtocolViewModel
{
public int ProtocolAboutViolationOrganisationID { get; set; }
public OrganisationViewModel Organisation { get; set; }
public DateTime ViolationTime { get; set; }
public string KOAP { get; set; }
}
}
<file_sep>/LeoMapV2/Data/ITitlesRepository.cs
using LeoMapV2.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoMapV2.Data
{
public interface ITitlesRepository
{
TitleMapModel GetTitle(int x, int y, int z);
Dictionary<int, ZoomInformation> GetZoomsInformation();
ZoomInformation GetZoomInformation(int z);
List<int> GetZooms();
void ClearCache();
Point ConvertMapCoordsToPixels(DPoint point);
DPoint ConvertPixelsToMapCoords(int x, int y, int z);
}
}
<file_sep>/LeoBase/Components/CustomControls/PaginationControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls
{
public partial class PaginationControl : UserControl
{
public PaginationControl()
{
InitializeComponent();
}
}
}
<file_sep>/AppCore/Abstract/Protocols/IProtocolAboutInspectionOrganisationRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract.Protocols
{
public interface IProtocolAboutInspectionOrganisationRepository
{
IQueryable<ProtocolAboutInspectionOrganisation> ProtocolsAboutInspectionOrganisation { get; }
}
}
<file_sep>/AppCore/Entities/Employer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
public class Employer
{
[Key]
public int EmployerID { get; set; }
public int PersoneID { get; set; }
public int ViolationID { get; set; }
}
}
<file_sep>/FormControls/Controls/Attributes/OrderAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FormControls.Controls.Attributes
{
public class OrderAttribute:Attribute
{
public bool Order { get; set; } = true;
public OrderAttribute() { }
public OrderAttribute(bool order)
{
Order = order;
}
}
}
<file_sep>/LeoBase/Components/CustomControls/SearchPanels/GallaryViwer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls.SearchPanels
{
public partial class GallaryViwer : Form
{
public event Action BackImage;
public event Action NextImage;
private byte[] _image;
public byte[] Image
{
get
{
return _image;
}
set
{
_image = value;
}
}
public GallaryViwer()
{
InitializeComponent();
this.Text = null;
}
private Image ImageFromByteArray(byte[] byteArrayIn)
{
using (var ms = new MemoryStream(byteArrayIn))
{
return System.Drawing.Image.FromStream(ms);
}
}
}
}
<file_sep>/AppPresentators/Infrastructure/OrderBuilders/WordOrderBuilder.cs
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppPresentators.Infrastructure.OrderBuilders
{
public class WordOrderBuilder : IOrderBuilder
{
public event Action<string> ErrorBuild;
private DirectoryInfo _dirInfo;
private string _orderName;
private bool _wasCreated;
private Microsoft.Office.Interop.Word.Application _winword;
private Microsoft.Office.Interop.Word.Document _document;
Microsoft.Office.Interop.Word.Paragraph _currentParagr;
private List<string> _tableHeaders = null;
private string _tableName = null;
private List<TableRow> _rows = null;
private object _missing;
public bool WasError { get; set; } = false;
public void DrawImage(Image img, Align al)
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
WasError = true;
return;
}
string dir = Directory.GetCurrentDirectory() + @"/cache/";
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
string imagePath = dir + "cahce_" + DateTime.Now.Millisecond.ToString() + ".jpg";
img.Save(imagePath);
_currentParagr = _document.Content.Paragraphs.Add(ref _missing);
_currentParagr.Range.InlineShapes.AddPicture(imagePath);
switch (al)
{
case Align.CENTER:
_currentParagr.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
break;
case Align.LEFT:
_currentParagr.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
break;
case Align.RIGHT:
_currentParagr.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
break;
}
_currentParagr = null;
}
public void EndPharagraph()
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
WasError = true;
return;
}
_currentParagr.Range.InsertParagraphAfter();
_currentParagr = null;
}
public void EndTable(string name)
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
WasError = true;
return;
}
_currentParagr = _document.Content.Paragraphs.Add(ref _missing);
Table table = _document.Tables.Add(_currentParagr.Range, _rows.Count + 1, _tableHeaders.Count, ref _missing, ref _missing);
table.Borders.Enable = 1;
for(int i = 0; i < _tableHeaders.Count; i++)
{
table.Rows[1].Cells[i + 1].Range.Text = _tableHeaders[i];
table.Rows[1].Cells[i + 1].Shading.BackgroundPatternColor = WdColor.wdColorGray25;
}
for(int i = 0; i < _rows.Count; i++)
{
for(int j = 0; j < _rows[i].Cells.Length; j++)
{
table.Rows[i + 2].Cells[j + 1].Range.Text = _rows[i].Cells[j];
switch (_rows[i].RowColor)
{
case RowColor.GREEN:
var green = (Microsoft.Office.Interop.Word.WdColor)(223 + 0x100 * 240 + 0x10000 * 216);
table.Rows[i + 2].Cells[j + 1].Shading.BackgroundPatternColor = green;// WdColor.wdColorLightGreen;
break;
case RowColor.RED:
var red = (Microsoft.Office.Interop.Word.WdColor)(242 + 0x100 * 222 + 0x10000 * 222);
table.Rows[i + 2].Cells[j + 1].Shading.BackgroundPatternColor = red;// WdColor.wdColorRed;
break;
case RowColor.YELLOW:
var yellow = (Microsoft.Office.Interop.Word.WdColor)(252 + 0x100 * 248 + 0x10000 * 227);
table.Rows[i + 2].Cells[j + 1].Shading.BackgroundPatternColor = yellow;// WdColor.wdColorLightYellow;
break;
}
}
}
_currentParagr = null;
}
public string Save()
{
//_winword.Visible = true;
object filename = _dirInfo.FullName + @"/" + _orderName + ".docx";
try {
//Сохранение документа
_document.SaveAs(ref filename);
//Закрытие текущего документа
_document.Close(ref _missing, ref _missing, ref _missing);
_document = null;
//Закрытие приложения Word
_winword.Quit(ref _missing, ref _missing, ref _missing);
_winword = null;
string dir = Directory.GetCurrentDirectory() + @"/cache/";
DirectoryInfo info = new DirectoryInfo(dir);
if (info.Exists)
{
info.Delete(true);
}
}catch(Exception e)
{
if (ErrorBuild != null) ErrorBuild("Невозможно сохранить отчет. Возможно файл используется другим процессом.");
WasError = true;
return null;
}
return filename.ToString();
}
public void SetOrderPath(DirectoryInfo dirInfo, string orderName)
{
if (!dirInfo.Exists)
{
if (ErrorBuild != null) ErrorBuild("Папка " + dirInfo.FullName + " не найдена.");
WasError = true;
return;
}
_winword = new Microsoft.Office.Interop.Word.Application();
_winword.Visible = false;
_winword.Documents.Application.Caption = "Отчет";
_missing = System.Reflection.Missing.Value;
_document = _winword.Documents.Add(ref _missing, ref _missing, ref _missing, ref _missing);
//добавление новой страницы
//winword.Selection.InsertNewPage();
_dirInfo = dirInfo;
_orderName = orderName;
_wasCreated = true;
}
public void StartPharagraph(Align al)
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
WasError = true;
return;
}
_currentParagr = _document.Content.Paragraphs.Add(ref _missing);
switch (al)
{
case Align.CENTER:
_currentParagr.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
break;
case Align.LEFT:
_currentParagr.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
break;
case Align.RIGHT:
_currentParagr.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
break;
}
}
public void StartTable(string name, string[] headers)
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
WasError = true;
return;
}
_tableName = name;
_tableHeaders = new List<string>();
foreach (var h in headers) _tableHeaders.Add(h);
_rows = new List<TableRow>();
}
public void WriteRow(string[] cells, RowColor color = RowColor.DEFAULT)
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
WasError = true;
return;
}
_rows.Add(new TableRow
{
Cells = cells,
RowColor = color
});
}
public void WriteText(string text, Color color, TextStyle style = TextStyle.NORMAL, float size = 12)
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
WasError = true;
return;
}
//Добавление текста в документ
if (_currentParagr == null)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Невозможно добавить текст в документ.");
WasError = true;
return;
}
string oldText = _currentParagr.Range.Text;
_currentParagr.Range.Text = oldText + text;
var wdc = (Microsoft.Office.Interop.Word.WdColor)(color.R + 0x100 * color.G + 0x10000 * color.B);
_currentParagr.Range.Font.Color = wdc;
_currentParagr.Range.Font.Size = size;
switch (style)
{
case TextStyle.BOLD:
_currentParagr.Range.Font.Bold = 1;
break;
case TextStyle.ITALIC:
_currentParagr.Range.Font.Italic = 1;
break;
case TextStyle.NORMAL:
_currentParagr.Range.Font.Italic = 0;
_currentParagr.Range.Font.Bold = 0;
break;
}
}
}
public class TableRow
{
public string[] Cells { get; set; }
public RowColor RowColor { get; set; }
}
}
<file_sep>/LeoBase/Components/TopMenu/TopControls.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.TopMenu
{
public class TopControls:List<Control>
{
public event Action AddItem;
public event Action DeleteItem;
public event Action DetailsItem;
public event Action ReportItem;
public event Action EditItem;
private PictureButton _btnAdd;
private PictureButton _btnEdit;
private PictureButton _btnDelete;
private PictureButton _btnDetails;
private PictureButton _btnReport;
public bool EnabledAdd
{
get
{
return _btnAdd != null ? _btnAdd.Enabled : false;
}
set
{
if (_btnAdd != null) _btnAdd.Enabled = value;
}
}
public bool EnabledEdit
{
get
{
return _btnEdit != null ? _btnEdit.Enabled : false;
}
set
{
if (_btnEdit != null) _btnEdit.Enabled = value;
}
}
public bool EnabledDelete
{
get
{
return _btnDelete != null ? _btnDelete.Enabled : false;
}
set
{
if (_btnDelete != null) _btnDelete.Enabled = value;
}
}
public bool EnabledDetails
{
get
{
return _btnDetails != null ? _btnDetails.Enabled : false;
}
set
{
if (_btnDetails != null) _btnDetails.Enabled = value;
}
}
public bool EnabledReport
{
get
{
return _btnReport != null ? _btnReport.Enabled : false;
}
set
{
if (_btnReport != null) _btnReport.Enabled = value;
}
}
public TopControls(string role, bool isOmissions = false):base()
{
if (role.Equals("admin") || isOmissions && role.Equals("passesManager"))
{
_btnAdd = new PictureButton(Properties.Resources.addEnabled, Properties.Resources.addDisabled, Properties.Resources.addPress);
_btnEdit = new PictureButton(Properties.Resources.editEnabled, Properties.Resources.editDisabled, Properties.Resources.editPress);
_btnDelete = new PictureButton(Properties.Resources.deleteEnabled, Properties.Resources.deleteDisabled, Properties.Resources.deletePress);
_btnDetails = new PictureButton(Properties.Resources.detailsEnabled, Properties.Resources.detailsDisabled, Properties.Resources.detailsPress);
_btnReport = new PictureButton(Properties.Resources.reportEnabled, Properties.Resources.reportDisabled, Properties.Resources.reportPress);
_btnAdd.OnClick += (s, e) =>
{
if (AddItem != null) AddItem();
};
_btnEdit.OnClick += (s, e) =>
{
if (EditItem != null) EditItem();
};
_btnDetails.OnClick += (s, e) =>
{
if (DetailsItem != null) DetailsItem();
};
_btnReport.OnClick += (s, e) =>
{
if (ReportItem != null) ReportItem();
};
_btnDelete.OnClick += (s, e) =>
{
if (DeleteItem != null) DeleteItem();
};
this.Add(_btnReport);
this.Add(_btnAdd);
this.Add(_btnEdit);
this.Add(_btnDelete);
this.Add(_btnDetails);
}else
{
_btnDetails = new PictureButton(Properties.Resources.detailsEnabled, Properties.Resources.detailsDisabled, Properties.Resources.detailsPress);
_btnReport = new PictureButton(Properties.Resources.reportEnabled, Properties.Resources.reportDisabled, Properties.Resources.reportPress);
_btnDetails.OnClick += (s, e) =>
{
if (DetailsItem != null) DetailsItem();
};
_btnReport.OnClick += (s, e) =>
{
if (ReportItem != null) ReportItem();
};
this.Add(_btnReport);
this.Add(_btnDetails);
}
}
}
}
<file_sep>/FormControls/Controls/Models/LeoDataViewCell.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormControls.Controls.Models
{
public class LeoDataViewCell:Panel
{
public Control Control { get; private set; }
public LeoDataViewCell()
{
this.Dock = DockStyle.Top;
this.BorderStyle = BorderStyle.FixedSingle;
this.Margin = new Padding(0, 0, 0, 0);
this.Height = 50;
}
public void SetControl(Control control)
{
this.Controls.Clear();
this.Controls.Add(control);
}
}
}
<file_sep>/LeoBase/Components/CustomControls/Delegates/Delegates.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoBase.Components.CustomControls.Delegates
{
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/SavePageTemplate.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls.NewControls
{
public partial class SavePageTemplate : UserControl
{
public event Action SaveClick;
public List<Control> TopControls
{
get
{
Button saveBtn = new Button();
saveBtn.Text = "Сохранить";
saveBtn.Click += (s, e) =>
{
if (SaveClick != null) SaveClick();
};
return new List<Control>
{
saveBtn
};
}
set
{
throw new NotImplementedException();
}
}
public string Title
{
get
{
return lbTitle.Text;
}
set
{
lbTitle.Text = value;
}
}
public SavePageTemplate()
{
InitializeComponent();
}
public void SetContent(Control control)
{
centerPlace.Controls.Clear();
centerPlace.Controls.Add(control);
}
}
}
<file_sep>/AppPresentators/VModels/CompareValue.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public enum CompareValue
{
NONE,
LESS,
MORE,
EQUAL
}
}
<file_sep>/Tests/Services/TestTestLoginService.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AppData.Abstract;
using Moq;
using System.Collections.Generic;
using AppData.Entities;
using System.Linq;
using AppPresentators.Services;
using AppPresentators.VModels;
namespace Tests.Services
{
[TestClass]
public class TestTestLoginService
{
private TestLoginService _testLoginService;
[TestInitialize]
public void Initialize()
{
Mock<IManagersRepository> mockRepository = new Mock<IManagersRepository>();
mockRepository.Setup(r => r.Managers).Returns(new List<Manager>
{
new Manager
{
ManagerID = 1,
Login = "admin",
Password = "<PASSWORD>",
Role = "admin"
},
new Manager
{
ManagerID = 2,
Login = "manager",
Password = "<PASSWORD>",
Role = "manager"
},
new Manager
{
ManagerID = 3,
Login = "user",
Password = "<PASSWORD>",
Role = "user"
}
}.AsQueryable());
_testLoginService = new TestLoginService(mockRepository.Object);
}
[TestMethod]
public void TestTrueAdminLogin()
{
IVManager admin = _testLoginService.Login("admin", "admin");
Assert.IsNotNull(admin);
Assert.AreEqual(admin.ManagerID, 1);
Assert.AreEqual(admin.Role, "admin");
}
[TestMethod]
public void TestTrueMangerLogin()
{
IVManager admin = _testLoginService.Login("manager", "manager");
Assert.IsNotNull(admin);
Assert.AreEqual(admin.ManagerID, 2);
Assert.AreEqual(admin.Role, "manager");
}
[TestMethod]
public void TestTrueUserLogin()
{
IVManager admin = _testLoginService.Login("user", "user");
Assert.IsNotNull(admin);
Assert.AreEqual(admin.ManagerID, 3);
Assert.AreEqual(admin.Role, "user");
}
[TestMethod]
public void TestFalseLogin()
{
IVManager nullUser = _testLoginService.Login("noname", "nopassword");
Assert.IsNull(nullUser);
}
}
}
<file_sep>/AppPresentators/Infrastructure/OrderBuilders/ExcelOrderBuilder.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
using System.IO;
using System.Diagnostics;
using OfficeOpenXml.Style;
using iTextSharp.text;
namespace AppPresentators.Infrastructure.OrderBuilders
{
public class ExcelOrderBuilder : IOrderBuilder
{
public event Action<string> ErrorBuild;
private FileInfo _docInfo;
private ExcelPackage _package;
private ExcelWorksheet _worksheet;
private bool _wasCreated = false;
private int _currentRow = 1;
private int _imageCount = 1;
private int _currentCol = 1;
private bool _wasError = false;
public bool WasError { get { return _wasError; } set { _wasError = value; } }
public ExcelOrderBuilder(){ }
public void SetOrderPath(DirectoryInfo dirInfo, string orderName)
{
if (!Directory.Exists(dirInfo.FullName))
{
if (ErrorBuild != null) ErrorBuild("Папка " + dirInfo.FullName + " не найдена.");
return;
}
_docInfo = new FileInfo(dirInfo.FullName + @"/" + orderName + ".xlsx");
try {
if (_docInfo.Exists)
{
_docInfo.Delete();
_docInfo = new FileInfo(dirInfo.FullName + @"/" + orderName + ".xlsx");
}
_package = new ExcelPackage(_docInfo);
_worksheet = _package.Workbook.Worksheets.Add("Order");
_wasCreated = true;
}catch(Exception e)
{
if (ErrorBuild != null) ErrorBuild("Невозможно создать отчет. Возможно файл занят другим процессом.");
_wasError = true;
}
}
public void DrawImage(System.Drawing.Image img, Align al)
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
return;
}
try
{
Bitmap image = new Bitmap(img);
ExcelPicture excelImage = null;
if (image != null)
{
excelImage = _worksheet.Drawings.AddPicture("image_" + _imageCount, image);
_imageCount++;
excelImage.From.Column = 0;
excelImage.From.Row = _currentRow;
excelImage.SetSize(540, img.Height * 540 / img.Width);
excelImage.From.ColumnOff = Pixel2MTU(0);
excelImage.From.RowOff = Pixel2MTU(_currentRow);
_currentRow += (img.Height * 27 / img.Width) + 3;
}
}
catch (Exception e)
{
if (ErrorBuild != null) ErrorBuild("Невозможно создать отчет. Возможно файл занят другим процессом.");
_wasError = true;
}
}
public int Pixel2MTU(int pixels)
{
int mtus = pixels * 9525;
return mtus;
}
public void EndPharagraph()
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
_wasError = true;
return;
}
_currentCol = 1;
_currentRow++;
}
public void EndTable(string name)
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
_wasError = true;
return;
}
_currentRow++;
}
public string Save()
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
_wasError = true;
return null;
}
try
{
_worksheet.Cells.AutoFitColumns(0);
_package.Save();
}
catch (Exception e)
{
if (ErrorBuild != null) ErrorBuild("Невозможно создать отчет. Возможно файл занят другим процессом.");
_wasError = true;
return null;
}
return _docInfo.FullName;
}
public void StartPharagraph(Align al)
{
try
{
switch (al)
{
case Align.CENTER:
_worksheet.Cells[_currentRow, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
break;
case Align.LEFT:
_worksheet.Cells[_currentRow, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
break;
case Align.RIGHT:
_worksheet.Cells[_currentRow, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
break;
}
_currentCol = 1;
}
catch (Exception e)
{
if (ErrorBuild != null) ErrorBuild("Невозможно создать отчет. Возможно файл занят другим процессом.");
_wasError = true;
}
}
public void StartTable(string name, string[] headers)
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
_wasError = true;
return;
}
try
{
for (int i = 0; i < headers.Length; i++)
{
_worksheet.Cells[_currentRow, i + 1].Value = headers[i];
_worksheet.Cells[_currentRow, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
_worksheet.Cells[_currentRow, i + 1].Style.Fill.BackgroundColor.SetColor(Color.LightGray);
_worksheet.Cells[_currentRow, i + 1].Style.Border.Top.Style = ExcelBorderStyle.Thin;
_worksheet.Cells[_currentRow, i + 1].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
_worksheet.Cells[_currentRow, i + 1].Style.Border.Left.Style = ExcelBorderStyle.Thin;
_worksheet.Cells[_currentRow, i + 1].Style.Border.Right.Style = ExcelBorderStyle.Thin;
}
_currentRow++;
}
catch (Exception e)
{
if (ErrorBuild != null) ErrorBuild("Невозможно создать отчет. Возможно файл занят другим процессом.");
_wasError = true;
}
}
public void WriteRow(string[] cells, RowColor color = RowColor.DEFAULT)
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
_wasError = true;
return;
}
try
{
for (int i = 0; i < cells.Length; i++)
{
_worksheet.Cells[_currentRow, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
_worksheet.Cells[_currentRow, i + 1].Value = cells[i];
_worksheet.Cells[_currentRow, i + 1].Style.Border.Top.Style = ExcelBorderStyle.Thin;
_worksheet.Cells[_currentRow, i + 1].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
_worksheet.Cells[_currentRow, i + 1].Style.Border.Left.Style = ExcelBorderStyle.Thin;
_worksheet.Cells[_currentRow, i + 1].Style.Border.Right.Style = ExcelBorderStyle.Thin;
switch (color)
{
case RowColor.GREEN:
_worksheet.Cells[_currentRow, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(223, 240, 216));
break;
case RowColor.RED:
_worksheet.Cells[_currentRow, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(242, 222, 222));
break;
case RowColor.YELLOW:
_worksheet.Cells[_currentRow, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(252, 248, 227));
break;
case RowColor.DEFAULT:
_worksheet.Cells[_currentRow, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(255, 255, 255));
break;
}
}
_currentRow++;
}
catch (Exception e)
{
if (ErrorBuild != null) ErrorBuild("Невозможно создать отчет. Возможно файл занят другим процессом.");
}
}
public void WriteText(string text, Color color, TextStyle style = TextStyle.NORMAL, float size = 12)
{
if (!_wasCreated)
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Документ не был создан.");
_wasError = true;
return;
}
try
{
_worksheet.Cells[_currentRow, _currentCol].Value = text;
_worksheet.Cells[_currentRow, _currentCol].Style.Font.Color.SetColor(color);
_worksheet.Cells[_currentRow, _currentCol].Style.Font.Size = size;
switch (style)
{
case TextStyle.BOLD:
_worksheet.Cells[_currentRow, _currentCol].Style.Font.Bold = true;
break;
case TextStyle.ITALIC:
_worksheet.Cells[_currentRow, _currentCol].Style.Font.Italic = true;
break;
case TextStyle.NORMAL:
_worksheet.Cells[_currentRow, _currentCol].Style.Font.Bold = false;
_worksheet.Cells[_currentRow, _currentCol].Style.Font.Italic = false;
break;
}
_currentCol++;
}
catch (Exception e)
{
if (ErrorBuild != null) ErrorBuild("Невозможно создать отчет. Возможно файл занят другим процессом.");
_wasError = true;
}
}
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/Component/IComponenPresentator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppPresentators.Presentators.Interfaces.Component
{
public interface IComponenPresentator
{
Control GetControl();
}
}
<file_sep>/AppPresentators/Services/LoginService.cs
using AppData.Abstract;
using AppData.Entities;
using AppData.Infrastructure;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Services
{
public interface ILoginService
{
VManager Login(string login, string password);
}
public class TestLoginService : ILoginService
{
private IManagersRepository _managersRepository;
public TestLoginService()
{
_managersRepository = RepositoryesFactory.GetInstance().Get<IManagersRepository>();
}
public TestLoginService(IManagersRepository managerRepository)
{
_managersRepository = managerRepository;
}
public VManager Login(string login, string password)
{
var mmm = _managersRepository.Managers.ToList();
var manager = _managersRepository.Managers.FirstOrDefault(u => u.Login.Equals(login) && u.Password.Equals(<PASSWORD>));
if (manager == null)
return null;
return new VManager
{
ManagerID = manager.ManagerID,
Login = manager.Login,
Password = <PASSWORD>.Password,
Role = manager.Role
};
}
}
}
<file_sep>/FormControls/Controls/Models/PageModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FormControls.Controls.Models
{
public class PageModel
{
public int CurrentPage { get; set; }
public int TotalItems { get; set; }
public int ItemsOnPage { get; set; }
public int TotalPages
{
get
{
return (int)Math.Round( (TotalItems + (ItemsOnPage - TotalItems % ItemsOnPage)) / (double)ItemsOnPage);
}
}
}
}
<file_sep>/AppPresentators/Infrastructure/Orders/OrderConfigs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Infrastructure.Orders
{
public class OrderConfigs
{
public OrderType OrderType {get; set;}
public OrderTableConfig TableConfig { get; set; }
public OrderSinglePageConfig SinglePageConfig { get; set; }
public string OrderDirPath { get; set; }
public string OrderName { get; set; }
}
public class OrderTableConfig
{
public bool CurrentPageOnly { get; set; }
public bool ConsiderFilter { get; set; }
}
public class OrderSinglePageConfig
{
public bool DrawImages { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/SaveComponent/SavePhone/PhonesList.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels.Persons;
namespace LeoBase.Components.CustomControls.SaveComponent.SavePhone
{
public partial class PhonesList : UserControl
{
public List<PhoneViewModel> Phones
{
get
{
List<PhoneViewModel> result = new List<PhoneViewModel>();
foreach(var item in flPhoneList.Controls)
{
var phoneItem = (PhoneItem)item;
var phoneNumber = phoneItem.Phone;
if (phoneNumber != null)
result.Add(phoneNumber);
}
return result;
}
set
{
flPhoneList.Controls.Clear();
flPhoneList.Refresh();
foreach (var phoneNumber in value)
{
var phoneItem = new PhoneItem
{
Phone = phoneNumber
};
phoneItem.RemoveThis += () => RemoveItem(phoneItem);
flPhoneList.Controls.Add(phoneItem);
if(flPhoneList.Controls.Count == 1)
{
phoneItem.ShowRemoveButton = false;
}
}
}
}
private void RemoveItem(PhoneItem item)
{
flPhoneList.Controls.Remove(item);
}
public PhonesList()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
var phoneItem = new PhoneItem();
phoneItem.RemoveThis += () => RemoveItem(phoneItem);
flPhoneList.Controls.Add(phoneItem);
}
}
}
<file_sep>/LeoMapV2/MapConfig.cs
using LeoMapV2.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoMapV2
{
public static class MapConfig
{
public const int DefaultZoom = 13;
public static MapDragAndDropStates DefaultMouseState = MapDragAndDropStates.DRAG_AND_DROP;
}
}
<file_sep>/AppCore/FakesRepositoryes/FakePhonesRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
namespace AppData.FakesRepositoryes
{
public class FakePhonesRepository : IPhonesRepository
{
private List<Phone> _phones = new List<Phone>
{
//new Phone
//{
// PhoneID = 1,
// UserID = 1,
// PhoneNumber = "1100000"
//},
//new Phone
//{
// PhoneID = 2,
// UserID = 2,
// PhoneNumber = "2200000"
//},
//new Phone
//{
// PhoneID = 3,
// UserID = 2,
// PhoneNumber = "3200000"
//},
//new Phone
//{
// PhoneID = 4,
// UserID = 3,
// PhoneNumber = "4300000"
//},
//new Phone
//{
// PhoneID = 5,
// UserID = 4,
// PhoneNumber = "5400000"
//},
//new Phone
//{
// PhoneID = 6,
// UserID = 5,
// PhoneNumber = "6500000"
//},
//new Phone
//{
// PhoneID = 7,
// UserID = 5,
// PhoneNumber = "7500000"
//}
};
public IQueryable<Phone> Phones
{
get
{
return _phones.AsQueryable();
}
}
public int AddPhone(Phone phone)
{
int id = Phones.Max(p => p.PhoneID) + 1;
phone.PhoneID = id;
_phones.Add(phone);
return id;
}
public bool Remove(int id)
{
var phone = Phones.FirstOrDefault(p => p.PhoneID == id);
if (phone == null)
return false;
return _phones.Remove(phone);
}
public int RemoveAllUserPhones(int userid)
{
return 0;
//return _phones.RemoveAll(p => p.UserID == userid);
}
}
}
<file_sep>/AppCore/Entities/Persone.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
public class Persone
{
[Key]
public int UserID { get; set; }
[DefaultValue(false)]
public bool IsEmploeyr { get; set; }
[Required(AllowEmptyStrings = false)]
public string FirstName { get; set; }
[Required(AllowEmptyStrings = false)]
public string SecondName { get; set; }
[Required(AllowEmptyStrings = false)]
public string MiddleName { get; set; }
public string PlaceWork { get; set; }
public DateTime DateBirthday { get; set; }
public DateTime WasBeCreated { get; set; } = DateTime.Now;
public DateTime WasBeUpdated { get; set; } = DateTime.Now;
public string PlaceOfBirth { get; set; }
[Column(TypeName = "image")]
[MaxLength]
public byte[] Image { get; set; }
public virtual List<Document> Documents { get; set; }
public virtual List<PersoneAddress> Address { get; set; }
public virtual List<Phone> Phones { get; set; }
public int Position_PositionID { get; set; }
public bool Deleted { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/Interfaces/IClearable.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls.Interfaces
{
public interface IClearable
{
void Clear();
Control GetControl();
DockStyle Dock { get; set; }
}
}
<file_sep>/AppPresentators/Components/ISavePersonControl.cs
using AppData.Entities;
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public interface ISavePersonControl:UIComponent
{
event Action SavePersone;
IPersoneViewModel Persone { get; set; }
void ShowMessage(string message);
}
}
<file_sep>/AppPresentators/Presentators/Protocols/ProtocolAboutViolationPresentator.cs
using AppPresentators.Presentators.Interfaces.ProtocolsPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.VModels.MainMenu;
using AppPresentators.VModels.Protocols;
using System.Windows.Forms;
using AppPresentators.Infrastructure;
using AppPresentators.Components.Protocols;
using AppPresentators.Services;
using AppPresentators.VModels.Persons;
namespace AppPresentators.Presentators.Protocols
{
public class ProtocolAboutViolationPresentator : IProtocolAboutViolationPresentator
{
public int Key { get; set; }
public event RemoveProtocolEvent OnRemove;
public ProtocolViewModel Protocol { get
{
return _view.Protocol;
}
set
{
_view.Protocol = value;
}
}
public IRulingForViolationPresentator Ruling { get; set; }
private IApplicationFactory _appFactory;
private IProtocolAboutViolationView _view;
private IPersonesService _personeService;
public ProtocolAboutViolationPresentator(IApplicationFactory appFactory)
{
_appFactory = appFactory;
_view = appFactory.GetComponent<IProtocolAboutViolationView>();
_personeService = appFactory.GetService<IPersonesService>();
_view.SearchEmployer += SearchEmployer;
_view.SearchViolator += SearchViolator;
_view.ChangeEmployerData += AutocompliteEmployer;
_view.ChangeViolatorData += AutocompliteViolator;
_view.Protocol = new ProtocolAboutViolationPersoneViewModel
{
ProtocolID = -1,
ProtocolTypeID = 7,
Employer = new EmploeyrViewModel
{
UserID = -1
},
Violator = new PersoneViewModel
{
UserID = -1
}
};
}
private void AutocompliteViolator()
{
var protocol = (ProtocolAboutViolationPersoneViewModel)_view.Protocol;
var searchModel = new VModels.Persons.PersonsSearchModel();
var violator = protocol.Violator;
if (!string.IsNullOrEmpty(violator.FirstName)) searchModel.FirstName = violator.FirstName;
if (!string.IsNullOrEmpty(violator.SecondName)) searchModel.SecondName = violator.SecondName;
if (!string.IsNullOrEmpty(violator.MiddleName)) searchModel.MiddleName = violator.MiddleName;
if (violator.DateBirthday.Year != 1) searchModel.DateBirthday = violator.DateBirthday;
if (!string.IsNullOrEmpty(violator.PlaceOfBirth)) searchModel.PlaceOfBirth = violator.PlaceOfBirth;
if (!string.IsNullOrEmpty(violator.PlaceWork)) searchModel.PlaceWork = violator.PlaceWork;
searchModel.IsEmployer = false;
_personeService.SearchModel = searchModel;
var persones = _personeService.GetPersons();
if (persones != null && persones.Count == 1) _view.SetViolator(persones.First());
}
private void AutocompliteEmployer()
{
var protocol = (ProtocolAboutViolationPersoneViewModel)_view.Protocol;
var searchModel = new VModels.Persons.PersonsSearchModel();
var employer = protocol.Employer;
if (!string.IsNullOrEmpty(employer.FirstName)) searchModel.FirstName = employer.FirstName;
if (!string.IsNullOrEmpty(employer.SecondName)) searchModel.SecondName = employer.SecondName;
if (!string.IsNullOrEmpty(employer.MiddleName)) searchModel.MiddleName = employer.MiddleName;
searchModel.IsEmployer = true;
_personeService.SearchModel = searchModel;
var persones = _personeService.GetPersons();
if (persones != null && persones.Count == 1) _view.SetEmployer(persones.First());
}
private void SearchViolator()
{
throw new NotImplementedException();
}
private void SearchEmployer()
{
throw new NotImplementedException();
}
public Control GetControl()
{
return _view.GetControl();
}
public void Remove()
{
if (OnRemove != null) OnRemove(Key);
}
public void Save()
{
throw new NotImplementedException();
}
public void SetResult(ResultTypes command, object data)
{
if(command == ResultTypes.SEARCH_VIOLATOR)
{
if(data is IPersoneViewModel)
{
_view.SetViolator((IPersoneViewModel)data);
}
}
// TODO: Добавить обработку других возможных позвращенных результатов
}
}
}
<file_sep>/AppPresentators/VModels/Protocols/ProtocolAboutInspectionAutoViewModel.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Protocols
{
/// <summary>
/// Протокол о досмотре транспортного средства
/// </summary>
public class ProtocolAboutInspectionAutoViewModel:ProtocolViewModel
{
public int ProtocolAboutInspectionAutoID { get; set; }
public PersoneViewModel Violator { get; set; }
/// <summary>
/// Информация о транспортном средстве
/// </summary>
public string InformationAbouCar { get; set; }
/// <summary>
/// Найденное оружие
/// </summary>
public string FindedWeapons { get; set; }
/// <summary>
/// Найденные боеприпасы
/// </summary>
public string FindedAmmunitions { get; set; }
/// <summary>
/// Найденые орудия для охоты и рыболовства
/// </summary>
public string FindedGunsHuntingAndFishing { get; set; }
/// <summary>
/// Найденная продукция природопользования
/// </summary>
public string FindedNatureManagementProducts { get; set; }
/// <summary>
/// Найденные документы
/// </summary>
public string FindedDocuments { get; set; }
/// <summary>
/// Методы фиксации правонарушения
/// </summary>
public string FixingMethods { get; set; }
}
}
<file_sep>/AppPresentators/Components/IEmployersTableControl.cs
using AppPresentators.VModels;
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public delegate void EditPersone(IPersoneViewModel persone);
public delegate void DeletePersone(IPersoneViewModel persone);
public delegate void ShowPersoneDetails(IPersoneViewModel persone);
public interface IEmployersTableControl:UIComponent
{
event Action UpdateTable;
event Action AddNewEmployer;
event Action<EmploeyrViewModel> SelectedItemForResult;
event ShowPersoneDetails ShowPersoneDetails;
event EditPersone EditPersone;
event DeletePersone DeletePersone;
PageModel PageModel { get; set; }
PersonsSearchModel PersoneSearchModel { get; }
DocumentSearchModel DocumentSearchModel { get; }
SearchAddressModel AddressSearchModel { get; }
PersonsOrderModel OrderModel { get; set; }
List<EmploeyrViewModel> Data { get; set; }
void Update();
void LoadStart();
void LoadEnd();
}
}
<file_sep>/AppCore/FakesRepositoryes/FakePersonsPositionRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
namespace AppData.FakesRepositoryes
{
public class FakePersonsPositionRepository : IPersonePositionRepository
{
private List<EmploeyrPosition> _positions = new List<EmploeyrPosition>
{
new EmploeyrPosition
{
PositionID = 4,
Name = "Госинспектор"
},
new EmploeyrPosition
{
PositionID = 5,
Name = "Участковый госинспектор"
},
new EmploeyrPosition
{
PositionID = 6,
Name = "Старший госинпектор"
}
};
public IQueryable<EmploeyrPosition> Positions
{
get
{
return _positions.AsQueryable();
}
}
public int AddPosition(EmploeyrPosition position)
{
int id = Positions.Max(p => p.PositionID) + 1;
position.PositionID = id;
_positions.Add(position);
return id;
}
public bool Remove(int id)
{
var position = Positions.FirstOrDefault(p => p.PositionID == id);
if (position == null) return false;
return _positions.Remove(position);
}
}
}
<file_sep>/AppCore/Abstract/IPersonePositionRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract
{
public interface IPersonePositionRepository
{
IQueryable<EmploeyrPosition> Positions { get; }
bool Remove(int id);
int AddPosition(EmploeyrPosition position);
}
}
<file_sep>/AppPresentators/VModels/Persons/PhoneViewModel.cs
using AppData.CustomAttributes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Persons
{
public class PhoneViewModel
{
[Browsable(false)]
[BrowsableForEditAndDetails(false, false)]
public int PhoneID { get; set; }
[Browsable(true)]
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Номер телефона")]
public string PhoneNumber { get; set; }
}
}
<file_sep>/LeoMapV3/Models/PlaceMark.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoMapV3.Models
{
public class PlaceMark
{
public Rectangle Rect { get; set; }
public DPoint Point { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/SaveComponent/SaveAddress/AddressItem.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels.Persons;
namespace LeoBase.Components.CustomControls.SaveComponent.SaveAddress
{
public partial class AddressItem : UserControl
{
public event Action RemoveThis;
private int _addressID = -1;
public bool ShowRemoveButton
{
get
{
return button1.Visible;
}
set
{
button1.Visible = value;
}
}
public PersonAddressModelView Address
{
get
{
if (string.IsNullOrWhiteSpace(tbCity.Text) ||
string.IsNullOrWhiteSpace(tbRegion.Text) ||
string.IsNullOrWhiteSpace(tbRayon.Text) ||
string.IsNullOrWhiteSpace(tbCity.Text) ||
string.IsNullOrWhiteSpace(tbStreet.Text) ||
string.IsNullOrWhiteSpace(tbHome.Text)) return null;
return new PersonAddressModelView
{
Country = tbCountry.Text,
Subject = tbRegion.Text,
Area = tbRayon.Text,
City = tbCity.Text,
Street = tbStreet.Text,
HomeNumber = tbHome.Text,
Flat = tbFlat.Text,
Note = cmbNote.Items[cmbNote.SelectedIndex].ToString()
};
}
set
{
tbCountry.Text = value.Country;
tbRegion.Text = value.Subject;
tbRayon.Text = value.Area;
tbCity.Text = value.City;
tbStreet.Text = value.Street;
tbHome.Text = value.HomeNumber;
tbFlat.Text = value.Flat;
_addressID = value.AddressID;
for(int i = 0; i < cmbNote.Items.Count; i++)
{
if (cmbNote.Items[i].ToString().Equals(value.Note))
{
cmbNote.SelectedIndex = i;
break;
}
}
}
}
public AddressItem()
{
InitializeComponent();
cmbNote.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
if (RemoveThis != null) RemoveThis();
}
}
}
<file_sep>/AppCore/Repositrys/Violations/Protocols/ProtocolRepository.cs
using AppData.Abstract.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations.Protocols
{
public class ProtocolRepository : IProtocolRepository
{
public IQueryable<Protocol> Protocols
{
get
{
var db = new LeoBaseContext();
return db.Protocols;
}
}
public int SaveProtocol(Protocol protocol)
{
using(var db = new LeoBaseContext())
{
db.Protocols.Add(protocol);
db.SaveChanges();
return protocol.ProtocolID;
}
}
}
}
<file_sep>/AppCore/Repositrys/Violations/Protocols/ProtocolAboutViolationOrganisationRepository.cs
using AppData.Abstract.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations.Protocols
{
public class ProtocolAboutViolationOrganisationRepository : IProtocolAboutViolationOrganisationRepository
{
public IQueryable<ProtocolAboutViolationOrganisation> ProtocolAboutViolationOrganisation
{
get
{
var db = new LeoBaseContext();
return db.ProtocolsAboutViolationOrganisation;
}
}
}
}
<file_sep>/AppPresentators/VModels/Persons/PersoneViewModel.cs
using AppData.Abstract;
using AppData.CustomAttributes;
using AppData.Entities;
using AppData.Infrastructure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppPresentators.VModels.Persons
{
public class PersonAddressModelView
{
[BrowsableForEditAndDetails(false, false)]
[Browsable(false)]
public int AddressID { get; set; }
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Страна")]
public string Country { get; set; } = "Российская Федерация";
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Область")]
public string Subject { get; set; } = "Приморский край";
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Район")]
public string Area { get; set; } = "Хасанский район";
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Город")]
public string City { get; set; }
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Улица")]
public string Street { get; set; }
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Номер дома")]
public string HomeNumber { get; set; }
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Номер квартиры")]
public string Flat { get; set; }
[BrowsableForEditAndDetails(true, true)]
[ControlType(ControlType.ComboBox, "Value", "Display")]
[DataPropertiesName("NoteTypes")]
[DisplayName("Проживает/прописан")]
[PropertyNameSelectedText("Note")]
public string Note { get; set; }
[Browsable(false)]
[BrowsableForEditAndDetails(false, false)]
public List<ComboBoxDefaultItem> NoteTypes
{
get
{
return new List<ComboBoxDefaultItem>
{
new ComboBoxDefaultItem { Display ="Проживает и прописан", Value = "Проживает и прописан" },
new ComboBoxDefaultItem { Display ="Проживает", Value = "Проживает" },
new ComboBoxDefaultItem { Display ="Прописан", Value = "Прописан" }
};
}
}
[BrowsableForEditAndDetails(false, false)]
[Browsable(false)]
public bool IsEmptyModel
{
get
{
bool defaultValue = Country == "Российская Федерация" && Subject == "Приморский край" && Area == "Хасанский район" &&
string.IsNullOrEmpty(City) && string.IsNullOrEmpty(Street) && string.IsNullOrEmpty(Flat) && string.IsNullOrEmpty(HomeNumber);
bool emptyValue = string.IsNullOrEmpty(Country) && string.IsNullOrEmpty(Subject) && string.IsNullOrEmpty(Area) &&
string.IsNullOrEmpty(City) && string.IsNullOrEmpty(Street) && string.IsNullOrEmpty(Flat) && string.IsNullOrEmpty(HomeNumber);
return defaultValue || emptyValue;
}
}
}
public class PersoneDocumentModelView
{
[Browsable(false)]
public int DocumentID { get; set; }
[Browsable(false)]
public int DocumentTypeID { get; set; }
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Тип документа")]
[ControlType(ControlType.ComboBox, "Value", "Display")]
[DataPropertiesName("DocumentTypes")]
public string DocumentTypeName { get; set; }
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Серия")]
public string Serial { get; set; }
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Номер")]
public string Number { get; set; }
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Кем выдан")]
public string IssuedBy { get; set; }
[BrowsableForEditAndDetails(true, true)]
[ControlType(ControlType.DateTime)]
[DisplayName("Когда выдан")]
public DateTime WhenIssued { get; set; }
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Код подразделения")]
public string CodeDevision { get; set; }
[Browsable(false)]
[BrowsableForEditAndDetails(false, false)]
public List<ComboBoxDefaultItem> DocumentTypes
{
get
{
return ConfigApp.DocumentsType.Select(x => new ComboBoxDefaultItem { Display = x.Value, Value = x.Value }).ToList();
}
}
[Browsable(false)]
public PersoneViewModel Persone { get; set; }
public PersoneDocumentModelView() { }
public PersoneDocumentModelView(Document document, string documentType, Persone persone)
{
DocumentTypeName = documentType;
Persone = new PersoneViewModel(persone);
DocumentID = document.DocumentID;
DocumentTypeID = document.Document_DocumentTypeID;
Serial = document.Serial;
Number = document.Number;
IssuedBy = document.IssuedBy;
WhenIssued = document.WhenIssued;
CodeDevision = document.CodeDevision;
}
}
public interface IPersoneViewModel
{
[Browsable(false)]
int UserID { get; set; }
[Browsable(false)]
bool IsEmploeyr { get; set; }
[DisplayName("Фамилия")]
string FirstName { get; set; }
[DisplayName("Имя")]
string SecondName { get; set; }
[DisplayName("Отчество")]
string MiddleName { get; set; }
[DisplayName("Дата рождения")]
DateTime DateBirthday { get; set; }
[DisplayName("Дата создания")]
DateTime WasBeCreated { get; set; }
[DisplayName("Дата обновления")]
DateTime WasBeUpdated { get; set; }
[DisplayName("Место рождения")]
string PlaceOfBirth { get; set; }
byte[] Image { get; set; }
List<PersonAddressModelView> Addresses { get; set; }
List<PersoneDocumentModelView> Documents { get; set; }
List<PhoneViewModel> Phones { get; set; }
}
public class PersoneViewModel
{
[Browsable(false)]
public int UserID { get; set; }
[Browsable(false)]
public int PositionID { get; set; }
[Browsable(false)]
public bool IsEmploeyr { get; set; }
[DisplayName("Фамилия")]
public string FirstName { get; set; }
[DisplayName("Имя")]
public string SecondName { get; set; }
[DisplayName("Отчество")]
public string MiddleName { get; set; }
[DisplayName("Дата рождения")]
public DateTime DateBirthday { get; set; }
[DisplayName("Место рождения")]
public string PlaceOfBirth { get; set; }
[DisplayName("Дата создания")]
public DateTime WasBeCreated { get; set; }
[DisplayName("Дата обновления")]
public DateTime WasBeUpdated { get; set; }
[DisplayName("Место работы")]
public string PlaceWork { get; set; }
public List<PersoneDocumentModelView> Documents { get; set; }
public List<PhoneViewModel> Phones { get; set; }
public List<PersonAddressModelView> Addresses { get; set; }
public byte[] Image { get; set; } = new byte[0];
private IPersonePositionRepository _personPositionRepository;
private IPersoneAddressRepository _personAddressRepository;
private IPhonesRepository _phonesRepository;
private IDocumentRepository _documentsRepository;
private IDocumentTypeRepository _documentsTypeRepository;
public PersoneViewModel(Persone persone) : this(RepositoryesFactory.GetInstance().Get<IPersoneAddressRepository>(),
RepositoryesFactory.GetInstance().Get<IPhonesRepository>(),
RepositoryesFactory.GetInstance().Get<IPersonePositionRepository>(),
RepositoryesFactory.GetInstance().Get<IDocumentRepository>(),
RepositoryesFactory.GetInstance().Get<IDocumentTypeRepository>()
)
{
FirstName = persone.FirstName;
SecondName = persone.SecondName;
MiddleName = persone.MiddleName;
DateBirthday = persone.DateBirthday;
PlaceOfBirth = persone.PlaceOfBirth;
WasBeCreated = persone.WasBeCreated;
WasBeUpdated = persone.WasBeUpdated;
PlaceWork = persone.PlaceWork;
Image = persone.Image;
Phones = new List<PhoneViewModel>();
Documents = new List<PersoneDocumentModelView>();
Addresses = new List<PersonAddressModelView>();
if(persone.Phones != null)
foreach(var phone in persone.Phones)
{
Phones.Add(new PhoneViewModel
{
PhoneID = phone.PhoneID,
PhoneNumber = phone.PhoneNumber
});
}
if(persone.Documents != null)
{
foreach(var document in persone.Documents)
{
Documents.Add(new PersoneDocumentModelView
{
});
}
}
if(persone.Address != null)
{
foreach(var address in persone.Address)
{
Addresses.Add(new PersonAddressModelView
{
Country = address.Country,
Subject = address.Subject,
Area = address.Area,
City = address.City,
HomeNumber = address.HomeNumber,
Flat = address.Flat,
Street = address.Street,
Note = address.Note
});
}
}
}
public PersoneViewModel():this(RepositoryesFactory.GetInstance().Get<IPersoneAddressRepository>(),
RepositoryesFactory.GetInstance().Get<IPhonesRepository>(),
RepositoryesFactory.GetInstance().Get<IPersonePositionRepository>(),
RepositoryesFactory.GetInstance().Get<IDocumentRepository>(),
RepositoryesFactory.GetInstance().Get<IDocumentTypeRepository>()
)
{ }
public PersoneViewModel(IPersoneAddressRepository addressRepository,
IPhonesRepository phoneRepository,
IPersonePositionRepository positionRepository,
IDocumentRepository documentRepository,
IDocumentTypeRepository documentTypeRepository)
{
_personAddressRepository = addressRepository;
_phonesRepository = phoneRepository;
_personPositionRepository = positionRepository;
_documentsRepository = documentRepository;
_documentsTypeRepository = documentTypeRepository;
}
}
}
<file_sep>/AppPresentators/Presentators/ViolationTablePresentator.cs
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.Services;
using AppPresentators.VModels;
using System.ComponentModel;
using System.Threading;
namespace AppPresentators.Presentators
{
public class ViolationTablePresentator : IViolationTablePresentator
{
public ResultTypes ResultType { get; set; }
public bool ShowFastSearch
{
get { return true; }
}
public bool ShowForResult { get; set; }
public bool ShowSearch { get
{
return true;
}
}
public List<Control> TopControls
{
get
{
return _control.TopControls;
}
}
public event SendResult SendResult;
private IApplicationFactory _appFactory;
private IViolationTableControl _control;
private IViolationService _service;
private BackgroundWorker _pageLoader;
public ViolationTablePresentator(IApplicationFactory appFactory)
{
_appFactory = appFactory;
_service = _appFactory.GetService<IViolationService>();
_control = _appFactory.GetComponent<IViolationTableControl>();
_control.RemoveViolation += ViolationAction;
_control.UpdateViolation += ViolationAction;
_control.ShowDetailsViolation += ViolationAction;
_control.AddNewViolation += () => ViolationAction(ViolationActionType.ADD_NEW_VIOLATION, null);
_control.UpdateData += () => Update(_control.SearchModel, _control.OrderModel, _control.PageModel);
_pageLoader = new BackgroundWorker();
_pageLoader.DoWork += PageLoading;
_pageLoader.RunWorkerCompleted += PageLoaded;
}
private void PageLoaded(object sender, RunWorkerCompletedEventArgs e)
{
//var result = (LoadDataViolationResponseModel)e.Result;
//if (result == null) return;
//_control.Violations = result.Data;
//_control.PageModel = result.PageModel;
//_control.LoadEnd();
}
private void PageLoading(object sender, DoWorkEventArgs e)
{
//Thread.Sleep(2000);
//var request = (LoadDataViolationRequestModel)e.Argument;
//var order = request.OrderModel;
//var page = request.PageModel;
//var search = request.SearchModel;
//_service.OrderModel = order;
//_service.PageModel = page;
//_service.SearchModel = search;
//var data = _service.GetViolations();
//if (data == null)
// data = new List<ViolationViewModel>();
//var result = new LoadDataViolationResponseModel();
//result.Data = data;
//result.PageModel = _service.PageModel;
//e.Result = result;
}
private void ViolationAction(ViolationActionType type, ViolationViewModel violation)
{
var mainPresentator = _appFactory.GetMainPresentator();
IComponentPresentator presentator = null;
ResultTypes rt = ResultTypes.NONE;
switch (type)
{
case ViolationActionType.DETAILS:
rt = ResultTypes.UPDATE_VIOLATION;
break;
case ViolationActionType.UPDATE:
rt = ResultTypes.UPDATE_VIOLATION;
break;
case ViolationActionType.SHOW_ON_MAP:
rt = ResultTypes.SHOW_ON_MAP;
break;
case ViolationActionType.ADD_NEW_VIOLATION:
presentator = _appFactory.GetPresentator<IAddOrUpdateViolation>();
rt = ResultTypes.ADD_VIOLATION;
break;
case ViolationActionType.REMOVE:
return;
}
mainPresentator.ShowComponentForResult(this, presentator, rt);
}
public void FastSearch(string message)
{
Update(new ViolationSearchModel(), _control.OrderModel, _control.PageModel);
}
public Control RenderControl()
{
Update(_control.SearchModel, _control.OrderModel, _control.PageModel);
return _control.GetControl();
}
public void SetResult(ResultTypes resultType, object data)
{
Update(_control.SearchModel, _control.OrderModel, _control.PageModel);
}
public void Update(ViolationSearchModel search, ViolationOrderModel order, PageModel page)
{
//var request = new LoadDataViolationRequestModel
////{
//// SearchModel = search,
//// OrderModel = order,
//// PageModel = page
//};
//_control.LoadStart();
//_pageLoader.RunWorkerAsync(request);
}
}
//public class LoadDataViolationRequestModel
//{
// public PageModel PageModel { get; set; }
// public ViolationOrderModel OrderModel { get; set; }
// public ViolationSearchModel SearchModel { get; set; }
//}
//public class LoadDataViolationResponseModel
//{
// public List<ViolationViewModel> Data { get; set; }
// public PageModel PageModel { get; set; }
//}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/PassesTableControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppData.Entities;
using AppPresentators.VModels;
using LeoBase.Components.TopMenu;
using AppPresentators;
using LeoBase.Components.CustomControls.SearchPanels;
namespace LeoBase.Components.CustomControls.NewControls
{
public partial class PassesTableControl : CustomTablePage, IPassesTableControl
{
public int SelectedID { get; private set; }
private int _selectedIndex = -1;
private CustomTable _customTable;
private TopControls _tpControls;
private AutoBinderPanel _searchPanel;
private Dictionary<string, int> _orderProperties;
private Dictionary<string, OrderType> _orderTypes;
public PassesTableControl():base()
{
InitializeComponent();
MakeTopControls();
_orderProperties = new Dictionary<string, int>();
_orderTypes = new Dictionary<string, OrderType>();
_orderProperties.Add("По дате завершения действия пропуска", (int)PassesOrderProperties.BY_DATE_CLOSED);
_orderProperties.Add("По дате выдачи пропуска", (int)PassesOrderProperties.BY_DATE_GIVED);
_orderProperties.Add("По фамилии", (int)PassesOrderProperties.BY_FIO);
Title = "Пропуски";
_orderTypes.Add("Убывание", OrderType.ASC);
_orderTypes.Add("Возростание", OrderType.DESC);
_customTable = new CustomTable();
_customTable.OrderProperties = (Dictionary<string, int>)_orderProperties;
_customTable.SelectedItemChange += _customTable_SelectedItemChange;
//_customTable.OnRowWasCreted += RowWasCreated;
_customTable.UpdateTable += () => UpdateTable();
_customTable.SelectedItemChange += (index) =>
{
if (index != -1)
{
_tpControls.EnabledDelete = true;
_tpControls.EnabledDetails = true;
_tpControls.EnabledEdit = true;
}
else
{
_tpControls.EnabledDelete = false;
_tpControls.EnabledDetails = false;
_tpControls.EnabledEdit = false;
}
_selectedIndex = index;
};
_customTable.DoubleClick += () =>
{
if (!ShowForResult && ShowDetailsPass != null)
{
if(_selectedIndex > 0 && _selectedIndex < _passes.Count) ShowDetailsPass(_passes[_selectedIndex].PassID);
}
};
this.AutoSize = true;
_searchPanel = new AutoBinderPanel();
_searchPanel.DataSource = new PassesSearchModel();
var searchPanel = new SearchPanelContainer();
searchPanel.SetCustomSearchPanel(_searchPanel);
AddSearchPanel(searchPanel);
_searchPanel.DataSourceChanged += (s, e) =>
{
if (UpdateTable != null) UpdateTable();
};
searchPanel.OnSearchClick += () =>
{
if (UpdateTable != null) UpdateTable();
};
SetContent(_customTable);
}
private void _customTable_SelectedItemChange(int index)
{
if (index > 0 && index <= _passes.Count) _selectedIndex = index;
}
private List<Pass> _passes;
public List<Pass> DataSource
{
get
{
return _passes;
}
set
{
_passes = value;
if(_passes == null)
{
_customTable.SetData<PassTableModel>(new List<PassTableModel>());
return;
}
_customTable.SetData<PassTableModel>(value.Select(p => new PassTableModel
{
FIO = p.FirstName + " " + p.SecondName + " " + p.MiddleName,
Document = p.DocumentType,
Number = p.Number,
PassClosen = p.PassClosed.ToShortDateString(),
PassGiven = p.PassGiven.ToShortDateString(),
Serial = p.Serial,
WhenIssued = p.WhenIssued.ToShortDateString(),
WhoIssued = p.WhoIssued
}).ToList());
if (_tpControls != null)
{
if (value == null || value.Count == 0)
{
_tpControls.EnabledDelete = false;
_tpControls.EnabledDetails = false;
_tpControls.EnabledEdit = false;
SelectedID = 0;
}
}
}
}
private void MakeTopControls()
{
_tpControls = new TopControls(ConfigApp.CurrentManager.Role, true);
_tpControls.DetailsItem += () =>
{
if (_selectedIndex >= 0 && _selectedIndex < _passes.Count && ShowDetailsPass != null) ShowDetailsPass(_passes[_selectedIndex].PassID);
};
_tpControls.DeleteItem += () =>
{
if (_selectedIndex >= 0 && _selectedIndex < _passes.Count && RemovePass != null) RemovePass(_passes[_selectedIndex].PassID);
};
_tpControls.EditItem += () =>
{
if (_selectedIndex >= 0 && _selectedIndex < _passes.Count && EditPass != null) EditPass(_passes[_selectedIndex].PassID);
};
_tpControls.AddItem += () =>
{
if (AddPass != null) AddPass();
};
_tpControls.ReportItem += () =>
{
if (MakeReport != null) MakeReport(_passes);
};
_tpControls.EnabledDelete = false;
_tpControls.EnabledDetails = false;
_tpControls.EnabledEdit = false;
_tpControls.EnabledAdd = true;
_tpControls.EnabledReport = true;
}
public PassesOrderModel OrderModel
{
get
{
var orderModel = new PassesOrderModel
{
OrderProperties = (PassesOrderProperties)_customTable.SelectedOrderBy,
OrderType = _customTable.OrderType
};
return orderModel;
}
set { }
}
private PageModel _pageModel;
public PageModel PageModel
{
get
{
if (_pageModel == null) _pageModel = new PageModel();
_pageModel.ItemsOnPage = 10;
_pageModel = _customTable.PageModel;
return _pageModel;
}
set
{
_pageModel = value;
_customTable.PageModel = value;
}
}
public PassesSearchModel SearchModel
{
get
{
return (PassesSearchModel)_searchPanel.DataSource;
}
set
{
}
}
public bool ShowForResult { get; set; }
public List<Control> TopControls
{
get
{
return _tpControls;
}
set { }
}
public event Action AddPass;
public event Action<int> EditPass;
public event Action<object> MakeReport;
public event Action<int> RemovePass;
public event Action<int> ShowDetailsPass;
public event Action UpdateTable;
public Control GetControl()
{
return this;
}
public bool ShowDialog(string text)
{
return MessageBox.Show(text, "", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK;
}
public void ShowError(string text)
{
MessageBox.Show(text, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public void ShowMessage(string text, string title)
{
MessageBox.Show(text, title, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
void UIComponent.Resize(int width, int height)
{
}
public void LoadStart()
{
_customTable.Visible = false;
VisibleLoadPanel = true;
}
public void LoadEnd()
{
try
{
VisibleLoadPanel = false;
_customTable.Visible = true;
}
catch (Exception e)
{
}
}
}
public class PassTableModel
{
[DisplayName("ФИО")]
[ReadOnly(true)]
public string FIO { get; set; }
[ReadOnly(true)]
[DisplayName("Пропуск выдан")]
public string PassGiven { get; set; }
[ReadOnly(true)]
[DisplayName("Пропуск заканчивается")]
public string PassClosen { get; set; }
[ReadOnly(true)]
[DisplayName("Предоставлен документ")]
public string Document { get; set; }
[ReadOnly(true)]
[DisplayName("Серия")]
public string Serial { get; set; }
[ReadOnly(true)]
[DisplayName("Номер")]
public string Number { get; set; }
[ReadOnly(true)]
[DisplayName("Кем выдан")]
public string WhoIssued { get; set; }
[ReadOnly(true)]
[DisplayName("Когда выдан")]
public string WhenIssued { get; set; }
}
}
<file_sep>/AppPresentators/Presentators/EmployersPresentator.cs
using AppData.Contexts;
using AppPresentators.Components;
using AppPresentators.Infrastructure;
using AppPresentators.Presentators.Interfaces;
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using AppPresentators.Services;
using AppPresentators.Views;
using AppPresentators.VModels;
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppPresentators.Presentators
{
public class EmployersPresentator : IEmployersPresentator
{
private IApplicationFactory _appFactory;
private IEmployersTableControl _control;
private IPersonesService _service;
private IMainView _mainView;
public event SendResult SendResult;
private BackgroundWorker _pageLoader;
public bool ShowFastSearch { get { return true; } }
public bool ShowSearch { get { return true; } }
private bool _showForResult = false;
public bool ShowForResult
{
get
{
return _showForResult;
}
set
{
_showForResult = value;
_control.ShowForResult = value;
}
}
public ResultTypes ResultType { get; set; }
public List<Control> TopControls {
get
{
return _control.TopControls;
}
}
public void SetResult(ResultTypes resultType, object data)
{
switch (resultType)
{
case ResultTypes.ADD_PERSONE:
bool result = (bool)data;
if (result)
{
GetPersones(_control.PageModel, _control.PersoneSearchModel, _control.AddressSearchModel, _control.OrderModel, _control.DocumentSearchModel);
}
break;
}
}
public EmployersPresentator(IMainView main, IApplicationFactory appFactory)
{
_appFactory = appFactory;
_mainView = main;
_service = _appFactory.GetService<IPersonesService>();
_control = _appFactory.GetComponent<IEmployersTableControl>();
_control.UpdateTable += () => GetPersones(_control.PageModel, _control.PersoneSearchModel, _control.AddressSearchModel, _control.OrderModel, _control.DocumentSearchModel);
_control.AddNewEmployer += AddNewEmployer;
_control.EditPersone += UpdatePersone;
_control.DeletePersone += DeletePersone;
_control.ShowPersoneDetails += ShowEmployerDetails;
_pageLoader = new BackgroundWorker();
_pageLoader.DoWork += PageLoading;
_pageLoader.RunWorkerCompleted += PageLoaded;
_control.SelectedItemForResult += SelectedItemForResult;
}
private void SelectedItemForResult(EmploeyrViewModel obj)
{
if (ShowForResult)
{
if (SendResult != null) SendResult(ResultType, _service.ConverToEnity(_service.GetPerson(obj.UserID, true)));
}
}
private void PageLoaded(object sender, RunWorkerCompletedEventArgs e)
{
var answer = (LoadEmplyerDataResultModel)e.Result;
_control.Data = answer.Data;
_control.PageModel = answer.PageModel;
_control.Update();
_control.LoadEnd();
}
private void PageLoading(object sender, DoWorkEventArgs e)
{
var request = (LoadEmployerDataRequestModel)e.Argument;
var pageModel = request.PageModel;
var searchModel = request.SearchModel;
var addressSearchModel = request.AddressSearchModel;
var documentSearchModel = new DocumentSearchModel();
var orderModel = request.OrderModel;
if (pageModel == null)
pageModel = new PageModel
{
ItemsOnPage = 10,
CurentPage = 1
};
if (searchModel == null)
searchModel = new PersonsSearchModel();
if (addressSearchModel == null)
addressSearchModel = new SearchAddressModel();
if (orderModel == null)
orderModel = new PersonsOrderModel();
searchModel.IsEmployer = true;
_service.PageModel = pageModel;
_service.DocumentSearchModel = documentSearchModel;
_service.SearchModel = searchModel;
_service.AddressSearchModel = addressSearchModel;
_service.OrderModel = orderModel;
var result = _service.GetPersons();
var answer = new LoadEmplyerDataResultModel();
if (result == null)
answer.Data = new List<EmploeyrViewModel>();
else
answer.Data = result.Select(v => (EmploeyrViewModel)v).ToList();
answer.PageModel = _service.PageModel;
e.Result = answer;
}
public void ShowEmployerDetails(IPersoneViewModel personeModel)
{
var ee = personeModel as EmploeyrViewModel;
if (ee == null) return;
var mainPresentator = _appFactory.GetMainPresentator();
var detailsEmployerPresentator = _appFactory.GetPresentator<IEmployerDetailsPresentator>();
EmployerDetailsModel employer = new EmployerDetailsModel
{
FIO = personeModel.FirstName + " " + personeModel.SecondName + " " + personeModel.MiddleName,
DateBerth = personeModel.DateBirthday.ToShortDateString(),
Position = ee.Position,
PlaceBerth = personeModel.PlaceOfBirth,
EmployerID = personeModel.UserID
};
using(var db = new LeoBaseContext())
{
var searchForImage = db.Persones.FirstOrDefault(p => p.UserID == personeModel.UserID);
if(searchForImage != null)
{
employer.Image = searchForImage.Image;
}
employer.Addresses = new List<PersonAddressModelView>();
var addresses = db.Addresses.Where(a => a.Persone.UserID == ee.UserID);
if(addresses != null)
{
foreach (var a in addresses)
{
employer.Addresses.Add(new PersonAddressModelView
{
AddressID = a.AddressID,
Area = a.Area,
City = a.City,
Country = a.Country,
Flat = a.Flat,
HomeNumber = a.HomeNumber,
Note = a.Note,
Street = a.Street,
Subject = a.Subject
});
}
}
employer.Phones = new List<PhoneViewModel>();
var phones = db.Phones.Where(p => p.Persone.UserID == personeModel.UserID);
if (phones != null)
{
foreach (var p in phones)
{
employer.Phones.Add(new PhoneViewModel
{
PhoneID = p.PhoneID,
PhoneNumber = p.PhoneNumber
});
}
}
employer.Violations = new List<AdminViolationRowModel>();
var violations = db.AdminViolations.Include("Employer").Include("ViolatorPersone").Where(v => v.Employer.UserID == ee.UserID);
foreach (var v in violations)
{
var row = new AdminViolationRowModel();
if (v.ViolatorOrganisation != null)
{
row.ViolatorInfo = string.Format("Юридическое лицо: {0}", v.ViolatorOrganisation.Name);
}
else
{
row.ViolatorInfo = string.Format("{0} {1} {2}", v.ViolatorPersone.FirstName, v.ViolatorPersone.SecondName, v.ViolatorPersone.MiddleName);
}
row.EmployerInfo = string.Format("{0} {1} {2}", v.Employer.FirstName, v.Employer.SecondName, v.Employer.MiddleName);
row.Coordinates = string.Format("{0}; {1}", Math.Round(v.ViolationN, 8), Math.Round(v.ViolationE, 8));
row.Consideration = v.Consideration;
row.DatePaymant = v.WasPaymant ? v.DatePaymant.ToShortDateString() : "";
row.DateSentBailiff = v.WasSentBailiff ? v.DateSentBailiff.ToShortDateString() : "";
row.InformationAbout2025 = v.WasAgenda2025 ? v.DateAgenda2025.ToShortDateString() : "";
row.InformationAboutNotice = v.WasNotice ? v.DateNotice.ToShortDateString() : "";
row.InformationAboutSending = v.GotPersonaly ? "Получил лично"
: v.WasSent
? v.DateSent.ToShortDateString()
: "";
row.SumRecovery = v.SumRecovery;
row.SumViolation = v.SumViolation;
row.Violation = v.Violation;
row.ViolationID = v.ViolationID;
employer.Violations.Add(row);
}
}
detailsEmployerPresentator.Employer = employer;
mainPresentator.ShowComponentForResult(this, detailsEmployerPresentator, ResultTypes.UPDATE_PERSONE);
}
public void DeletePersone(IPersoneViewModel personeModel)
{
_service.SimpleRemove(personeModel);
GetPersones(_control.PageModel, _control.PersoneSearchModel, _control.AddressSearchModel, _control.OrderModel, _control.DocumentSearchModel);
}
public void UpdatePersone(IPersoneViewModel personeModel)
{
var mainPresentator = _appFactory.GetMainPresentator();
var saveEmployerPresentator = _appFactory.GetPresentator<ISaveEmployerPresentator>();
saveEmployerPresentator.Persone = personeModel;
mainPresentator.ShowComponentForResult(this, saveEmployerPresentator, ResultTypes.UPDATE_PERSONE);
}
public void AddNewEmployer()
{
var mainPresentator = _appFactory.GetMainPresentator();
var saveEmployerPresentator = _appFactory.GetPresentator<ISaveEmployerPresentator>();
var persone = new EmploeyrViewModel();
persone.IsEmploeyr = true;
persone.UserID = -1;
persone.PositionID = ConfigApp.EmployerPositionsList.First() != null ? ConfigApp.EmployerPositionsList.First().PositionID.ToString() : "";
persone.Position = ConfigApp.EmployerPositionsList.First() != null ? ConfigApp.EmployerPositionsList.First().Name.ToString() : "";
var addresses = new List<PersonAddressModelView>();
var documents = new List<PersoneDocumentModelView>();
var phones = new List<PhoneViewModel>();
addresses.Add(new PersonAddressModelView
{
Country = "Российская Федерация",
Subject = "Приморский край",
Area = "Хасанский район"
});
documents.Add(new PersoneDocumentModelView
{
DocumentID = -1
});
phones.Add(new PhoneViewModel());
persone.Addresses = addresses;
persone.Phones = phones;
persone.Documents = documents;
saveEmployerPresentator.Persone = persone;
mainPresentator.ShowComponentForResult(this, saveEmployerPresentator, ResultTypes.ADD_PERSONE);
//mainPresentator.SetNextPage(saveEmployerPresentator);
}
public void FastSearch(string query)
{
string[] qs = query.Split(new char[] { ' ' });
PersonsSearchModel searchModel = new PersonsSearchModel();
if(qs.Length >= 1)
{
searchModel.FirstName = qs[0];
searchModel.CompareFirstName = CompareString.CONTAINS;
}
if(qs.Length >= 2)
{
searchModel.SecondName = qs[1];
searchModel.CompareSecondName = CompareString.CONTAINS;
}
if(qs.Length >= 3)
{
searchModel.MiddleName = qs[2];
searchModel.CompareMiddleName = CompareString.CONTAINS;
}
GetPersones(_control.PageModel, searchModel, new SearchAddressModel(), _control.OrderModel, new DocumentSearchModel());
}
public void GetPersones(PageModel pageModel, PersonsSearchModel searchModel, SearchAddressModel addressSearchModel, PersonsOrderModel orderModel, DocumentSearchModel documentSearchModel)
{
if (!_mainView.Enabled || _pageLoader.IsBusy) return;
LoadEmployerDataRequestModel request = new LoadEmployerDataRequestModel
{
AddressSearchModel = addressSearchModel,
OrderModel = orderModel,
SearchModel = searchModel,
PageModel = pageModel
};
_control.LoadStart();
_pageLoader.RunWorkerAsync(request);
}
public Control RenderControl()
{
GetPersones(_control.PageModel, _control.PersoneSearchModel, _control.AddressSearchModel, _control.OrderModel, _control.DocumentSearchModel);
return _control.GetControl();
}
}
public class LoadEmployerDataRequestModel
{
public PageModel PageModel { get; set; }
public PersonsSearchModel SearchModel { get; set; }
public SearchAddressModel AddressSearchModel { get; set; }
public PersonsOrderModel OrderModel { get; set; }
}
public class LoadEmplyerDataResultModel
{
public List<EmploeyrViewModel> Data { get; set; }
public PageModel PageModel { get; set; }
}
}
<file_sep>/AppPresentators/Infrastructure/OrderBuilders/TestOrderBuilder.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Infrastructure.OrderBuilders
{
public class TestOrderBuilder : IOrderBuilder
{
private string TextMessage = "";
public bool WasError
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public event Action<string> ErrorBuild;
public void DrawImage(Image img, Align al)
{
TextMessage += "Было нарисовано изображение\r\n";
}
public void EndPharagraph()
{
throw new NotImplementedException();
}
public void EndTable(string name)
{
TextMessage += "Таблица [" + name + "] закончена \r\n";
}
public string Save()
{
throw new NotImplementedException();
}
public string Save(string path, string orderName)
{
if (string.IsNullOrEmpty(path))
{
if (ErrorBuild != null) ErrorBuild("Ошибка! Не задан путь.");
return null;
}
if (!Directory.Exists(path))
{
if (ErrorBuild != null) ErrorBuild("Не найдена указанная дирректория.");
return null;
}
path = path.EndsWith("\\") || path.EndsWith("/") ? path : path + (path.Contains("\\") ? "\\" : "/");
path += orderName + ".txt";
File.WriteAllText(@path, TextMessage);
return path;
}
public void SetOrderPath(DirectoryInfo dirInfo, string orderName)
{
throw new NotImplementedException();
}
public void StartPharagraph(Align al)
{
throw new NotImplementedException();
}
public void StartTable(string name, string[] headers)
{
TextMessage += "Таблица [" + name + "] начата \r\n";
foreach(var head in headers)
{
TextMessage += head + "\t|\t";
}
TextMessage += "\r\n";
}
public void WriteP(string text, Align al)
{
TextMessage += "Записан параграф: " + text;
}
public void WriteRow(string[] cells, RowColor color = RowColor.DEFAULT)
{
TextMessage += "Запись строки цвета: " + color.ToString() + "\r\n";
foreach (var cell in cells)
{
TextMessage += cell + "\t|\t";
}
TextMessage += "\r\n";
}
public void WriteText(string text, Color color, TextStyle style = TextStyle.NORMAL, float size = 12)
{
throw new NotImplementedException();
}
}
}
<file_sep>/AppPresentators/Presentators/PassDetailsPresentator.cs
using AppData.Entities;
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.Views;
namespace AppPresentators.Presentators
{
public interface IPassDeatailsPresentator : IComponentPresentator
{
Pass Pass { get; set; }
}
public class PassDetailsPresentator : IPassDeatailsPresentator
{
private IPassDetailsControl _control;
private IMainView _parent;
private IApplicationFactory _appFactory;
public PassDetailsPresentator(IMainView main, IApplicationFactory appFactory)
{
_parent = main;
_appFactory = appFactory;
_control = _appFactory.GetComponent<IPassDetailsControl>();
_control.MakeReport += MakeReport;
}
private void MakeReport()
{
}
public Pass Pass
{
get
{
return _control.Pass;
}
set
{
_control.Pass = value;
}
}
public ResultTypes ResultType { get; set; }
public bool ShowFastSearch
{
get
{
return false;
}
}
public bool ShowForResult { get; set; }
public bool ShowSearch
{
get
{
return false;
}
}
public List<Control> TopControls
{
get
{
return _control.TopControls;
}
}
public event SendResult SendResult;
public void FastSearch(string message)
{
}
public Control RenderControl()
{
return _control.GetControl();
}
public void SetResult(ResultTypes resultType, object data)
{
}
}
}
<file_sep>/AppPresentators/Services/PermissonsService.cs
using AppPresentators.Components.MainMenu;
using AppPresentators.Infrastructure;
using AppPresentators.VModels.MainMenu;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Services
{
public interface IPermissonsService
{
List<MenuItemModel> GetMenuItems(string role);
}
public class PermissonsService: IPermissonsService
{
private Dictionary<string, List<MenuItemModel>> _menuPermissions;
public PermissonsService(Dictionary<string, List<MenuItemModel>> menuPermissions)
{
_menuPermissions = menuPermissions;
}
public PermissonsService()
{
_menuPermissions = new Dictionary<string, List<MenuItemModel>>();
_menuPermissions.Add("admin", new List<MenuItemModel>
{
new MenuItemModel
{
Title = "Нарушения",
MenuCommand = MenuCommand.Infringement
},
new MenuItemModel
{
Title = "Нарушители",
MenuCommand = MenuCommand.Violators
},
new MenuItemModel
{
Title = "Сотрудники",
MenuCommand = MenuCommand.Employees
},
new MenuItemModel
{
Title = "Пропуски",
MenuCommand = MenuCommand.Omissions
},
new MenuItemModel
{
Title = "Карта",
MenuCommand = MenuCommand.Map
},
new MenuItemModel
{
Title = "Настройки",
MenuCommand = MenuCommand.Options
}
});
_menuPermissions.Add("manager", new List<MenuItemModel>
{
new MenuItemModel
{
Title = "Нарушения",
MenuCommand = MenuCommand.Infringement
},
new MenuItemModel
{
Title = "Нарушители",
MenuCommand = MenuCommand.Violators
},
new MenuItemModel
{
Title = "Сотрудники",
MenuCommand = MenuCommand.Employees
},
new MenuItemModel
{
Title = "Пропуски",
MenuCommand = MenuCommand.Omissions
},
new MenuItemModel
{
Title = "Карта",
MenuCommand = MenuCommand.Map
}
});
}
public List<MenuItemModel> GetMenuItems(string role)
{
if (_menuPermissions.ContainsKey(role))
return _menuPermissions[role];
return null;
}
}
}
<file_sep>/AppPresentators/VModels/CellComboBoxValues.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public class CellComboBoxValues:List<string>
{
public string SelectedText { get; set; }
public CellComboBoxValues(string selectedtext)
{
SelectedText = selectedtext;
}
}
}
<file_sep>/AppPresentators/Infrastructure/IOrderPage.cs
using AppPresentators.Infrastructure.Orders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Infrastructure
{
public interface IOrderPage
{
OrderType OrderType { get; }
string OrderDirPath { get; }
void BuildOrder(IOrderBuilder orderBuilder, OrderConfigs configs);
}
}
<file_sep>/Tests/Presentators/TestEmployerPresentator.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests.Presentators
{
[TestClass]
public class TestEmployerPresentator
{
[TestMethod]
public void TestGetAllEmployers()
{
}
}
}
<file_sep>/AppCore/Entities/Document.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
public class Document
{
[Key]
public int DocumentID { get; set; }
public int Document_DocumentTypeID { get; set; }
public virtual Persone Persone { get; set; }
[Required(AllowEmptyStrings = false)]
public string Serial { get; set; }
[Required(AllowEmptyStrings = false)]
public string Number { get; set; }
[Required(AllowEmptyStrings = false)]
public string IssuedBy { get; set; }
[Required(AllowEmptyStrings = false)]
public DateTime WhenIssued { get; set; }
public string CodeDevision { get; set; }
}
}
<file_sep>/LeoMapV3/Form1.cs
using LeoMapV3.Data;
using LeoMapV3.Map;
using LeoMapV3.Map.interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoMapV3
{
public partial class Form1 : Form
{
private ITitlesRepository _repo;
private ILeoMap _map;
public Form1()
{
InitializeComponent();
_repo = new TitleDBRepository("D:\\Maps\\test.lmap");
_map = new LeoMap(_repo);
((Panel)_map).Dock = DockStyle.Fill;
mapPanel.Controls.Add((Panel)_map);
}
}
}
<file_sep>/AppPresentators/Infrastructure/Orders/OrderType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Infrastructure.Orders
{
public enum OrderType
{
SINGLE_PAGE,
TABLE
}
}
<file_sep>/AppPresentators/Presentators/SaveAdminViolationPresentator.cs
using AppData.Entities;
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.Services;
using AppPresentators.VModels.Persons;
using AppData.Contexts;
namespace AppPresentators.Presentators
{
public interface ISaveAdminViolationPresentatar: IComponentPresentator
{
AdminViolation Violation { get; set; }
void Save();
}
public class SaveAdminViolationPresentator : ISaveAdminViolationPresentatar
{
public ResultTypes ResultType { get; set; }
public bool ShowFastSearch
{
get
{
return false;
}
}
public bool ShowForResult { get; set; }
public bool ShowSearch
{
get
{
return false;
}
}
public List<Control> TopControls
{
get
{
return _view.TopControls;
}
}
public AdminViolation Violation { get
{
return _view.Violation;
}
set
{
_view.Violation = value;
}
}
public event SendResult SendResult;
private ISaveAdminViolationControl _view;
private IApplicationFactory _appFactory;
private IAdminViolationService _sevice;
public SaveAdminViolationPresentator(IApplicationFactory appFactory)
{
_appFactory = appFactory;
_view = _appFactory.GetComponent<ISaveAdminViolationControl>();
_sevice = _appFactory.GetService<IAdminViolationService>();
_view.Save += Save;
_view.CreateEmployer += CreateEmployer;
_view.CreateViolator += CreateViolator;
_view.FindEmployer += FindEmployer;
_view.FindViolator += FindViolator;
}
public void FastSearch(string message)
{
}
public void CreateViolator()
{
var mainPresentator = _appFactory.GetMainPresentator();
var saveEmployerPresentator = _appFactory.GetPresentator<ISaveEmployerPresentator>();
saveEmployerPresentator.Persone = new ViolatorViewModel
{
IsEmploeyr = false,
UserID = -1,
Addresses = new List<PersonAddressModelView>
{
new PersonAddressModelView {
Country = "Российская Федерация",
Subject = "Приморский край",
Area = "Хасанский район"
}
},
Phones = new List<PhoneViewModel>
{
new PhoneViewModel { }
},
Documents = new List<PersoneDocumentModelView>
{
new PersoneDocumentModelView
{
DocumentID = -1,
WhenIssued = new DateTime(1999, 1, 1)
}
}
};
mainPresentator.ShowComponentForResult(this, saveEmployerPresentator, ResultTypes.ADD_VIOLATOR);
}
public void FindEmployer()
{
var mainPresentator = _appFactory.GetMainPresentator();
var tableEmployerPresentator = _appFactory.GetPresentator<IEmployersPresentator>();
tableEmployerPresentator.ShowForResult = true;
mainPresentator.ShowComponentForResult(this, tableEmployerPresentator, ResultTypes.FIND_EMPLOYER);
}
public void FindViolator()
{
var mainPresentator = _appFactory.GetMainPresentator();
var tableViolatorPresentator = _appFactory.GetPresentator<IViolatorTablePresentator>();
tableViolatorPresentator.ShowForResult = true;
mainPresentator.ShowComponentForResult(this, tableViolatorPresentator, ResultTypes.FIND_VIOLATOR);
}
public void CreateEmployer()
{
var mainPresentator = _appFactory.GetMainPresentator();
var saveEmployerPresentator = _appFactory.GetPresentator<ISaveEmployerPresentator>();
var persone = new EmploeyrViewModel();
persone.IsEmploeyr = true;
persone.UserID = -1;
persone.PositionID = ConfigApp.EmployerPositionsList.First() != null ? ConfigApp.EmployerPositionsList.First().PositionID.ToString() : "";
persone.Position = ConfigApp.EmployerPositionsList.First() != null ? ConfigApp.EmployerPositionsList.First().Name.ToString() : "";
var addresses = new List<PersonAddressModelView>();
var documents = new List<PersoneDocumentModelView>();
var phones = new List<PhoneViewModel>();
addresses.Add(new PersonAddressModelView
{
Country = "Российская Федерация",
Subject = "Приморский край",
Area = "Хасанский район"
});
documents.Add(new PersoneDocumentModelView
{
DocumentID = -1
});
phones.Add(new PhoneViewModel());
persone.Addresses = addresses;
persone.Phones = phones;
persone.Documents = documents;
saveEmployerPresentator.Persone = persone;
mainPresentator.ShowComponentForResult(this, saveEmployerPresentator, ResultTypes.ADD_EMPLOYER);
}
public Control RenderControl()
{
return _view.GetControl();
}
public void Save()
{
if (_sevice.SaveViolation(_view.Violation))
{
_view.ShowMessage("Правонарушение успешно сохранено");
if (ShowForResult)
{
if (SendResult != null)
{
SendResult(ResultType, _view.Violation);
}
}
}
else
{
_view.ShowMessage("При сохранение правонарушения возеникла ошибка!\r\nВозможно не все поля заполнены верно.");
}
}
public void SetResult(ResultTypes resultType, object data)
{
using (var db = new LeoBaseContext())
{
switch (resultType)
{
case ResultTypes.ADD_EMPLOYER:
{
var employerID = db.Persones.Max(p => p.UserID);
var employer = db.Persones.FirstOrDefault(p => p.UserID == employerID);
if(employer != null) {
_view.Violation.Employer = employer;
_view.UpdateEmployer();
}
}
break;
case ResultTypes.ADD_VIOLATOR:
{
var violatorID = db.Persones.Max(p => p.UserID);
var violator = db.Persones.Include("Documents").Include("Phones").Include("Address").FirstOrDefault(p => p.UserID == violatorID);
if(violator != null)
{
_view.Violation.ViolatorPersone = violator;
_view.UpdateViolator();
}
}
break;
case ResultTypes.FIND_EMPLOYER:
{
var employer = data as Persone;
_view.Violation.Employer = employer;
_view.UpdateEmployer();
}
break;
case ResultTypes.FIND_VIOLATOR:
{
var violator = data as Persone;
_view.Violation.ViolatorPersone = violator;
_view.UpdateViolator();
}
break;
}
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/PassDetailsControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppData.Entities;
using LeoBase.Components.TopMenu;
namespace LeoBase.Components.CustomControls.NewControls
{
public partial class PassDetailsControl : UserControl, IPassDetailsControl
{
public PassDetailsControl()
{
InitializeComponent();
}
private Pass _pass;
public Pass Pass
{
get
{
return _pass;
}
set
{
_pass = value;
if(value != null)
{
tbFIO.Text = _pass.FirstName + " " + _pass.SecondName + " " + _pass.MiddleName;
tbPassClosen.Text = _pass.PassClosed.ToShortDateString();
tbPassGiven.Text = _pass.PassGiven.ToShortDateString();
tbDocument.Text = _pass.DocumentType;
tbSerialNumber.Text = _pass.Serial + " " + _pass.Number;
tbWhenIssued.Text = _pass.WhenIssued.ToShortDateString();
tbWhoIssued.Text = _pass.WhoIssued;
}
}
}
public bool ShowForResult { get; set; }
public List<Control> TopControls
{
get
{
var btnDetails = new PictureButton(Properties.Resources.reportEnabled, Properties.Resources.reportDisabled, Properties.Resources.reportPress);
btnDetails.Enabled = true;
btnDetails.OnClick += (s, e) =>
{
if (MakeReport != null) MakeReport();
};
return new List<Control> { btnDetails };
}
set
{
}
}
public event Action MakeReport;
public Control GetControl()
{
return this;
}
void UIComponent.Resize(int width, int height)
{
}
}
}
<file_sep>/LeoMapV2/Data/TestTitleRepository.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LeoMapV2.Models;
using System.Runtime.Caching;
namespace LeoMapV2.Data
{
public class TestTitleRepository : ITitlesRepository
{
private string path = "D:\\Maps\\EmptyTitles\\";
private MemoryCache _cache;
#region ZoomInformation
private Dictionary<int, ZoomInformation> _zoomInformation = new Dictionary<int, ZoomInformation>
{
{10, new ZoomInformation
{
MaxX = 2,
MaxY = 3,
E = 10,
W = 2,
N = 14,
S = 1,
Zoom = 10,
TitleHeight = 400,
TitleWidth = 256
}},
{11, new ZoomInformation
{
MaxX = 4,
MaxY = 6,
E = 10,
W = 2,
N = 14,
S = 1,
Zoom = 11,
TitleHeight = 400,
TitleWidth = 256
}},
{ 12, new ZoomInformation
{
MaxX = 8,
MaxY = 12,
E = 10,
W = 2,
N = 14,
S = 1,
Zoom = 12,
TitleHeight = 400,
TitleWidth = 256
}},
{ 13, new ZoomInformation
{
MaxX = 16,
MaxY = 24,
E = 10,
W = 2,
N = 14,
S = 1,
Zoom = 13,
TitleHeight = 400,
TitleWidth = 256
}},{14, new ZoomInformation
{
MaxX = 32,
MaxY = 48,
E = 10,
W = 2,
N = 14,
S = 1,
Zoom = 14,
TitleHeight = 400,
TitleWidth = 256
}},
};
#endregion
public TitleMapModel GetTitle(int x, int y, int z)
{
if (x < 0 || y < 0 || x > _zoomInformation[z].MaxX || y > _zoomInformation[z].MaxY) return null;
if (_cache == null) _cache = MemoryCache.Default;
Image result;
if(_cache.Contains("img_" + z))
{
result = (Image)_cache["img_" + z];
}
else
{
result = Image.FromFile(path + "z" + z + ".jpg");
_cache.Add("img_" + z, result, DateTime.Now.AddMinutes(2));
}
Bitmap bmp = new Bitmap(result.Width, result.Height);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(result, new Rectangle(0, 0, result.Width, result.Height), new Rectangle(0, 0, result.Width, result.Height), GraphicsUnit.Pixel);
int xt = result.Width / 2 - 20;
int yt = result.Height / 2 - 10;
g.DrawString("X:" + x + "; Y:" + y, new Font("Arial", 18, FontStyle.Bold), Brushes.Red, new Point(xt, yt));
return new TitleMapModel { Image = bmp };
}
public ZoomInformation GetZoomInformation(int z)
{
if (_zoomInformation.ContainsKey(z)) return _zoomInformation[z];
return null;
}
public void ClearCache()
{
}
public Point ConvertMapCoordsToPixels(DPoint point)
{
return new Point();
}
public List<int> GetZooms()
{
return new List<int>
{
10, 11, 12, 13, 14
};
}
public Dictionary<int, ZoomInformation> GetZoomsInformation()
{
return _zoomInformation;
}
public DPoint ConvertPixelsToMapCoords(int x, int y, int z)
{
return null;
}
}
}
<file_sep>/AppCore/Entities/RulingForViolation.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
/// <summary>
/// Постановление по делу об административном правонарушение
/// </summary>
public class RulingForViolation:IProtocol
{
[Key]
public int RulingForViolationID { get; set; }
[Required(AllowEmptyStrings = false)]
public Protocol Protocol { get; set; }
public int ViolatorDocumentID { get; set; }
public int OrganisationID { get; set; }
/// <summary>
/// Номер постановления
/// </summary>
public int Number { get; set; }
/// <summary>
/// Когда установил
/// </summary>
public DateTime FixingDate { get; set; }
/// <summary>
/// Что установил
/// </summary>
public string FixingInfo { get; set; }
/// <summary>
/// Статья КОАП
/// </summary>
public string KOAP { get; set; }
/// <summary>
/// Штраф
/// </summary>
public decimal Fine { get; set; }
/// <summary>
/// Ущерб
/// </summary>
public decimal Damage { get; set; }
/// <summary>
/// Добытая продукция
/// </summary>
public string Products { get; set; }
/// <summary>
/// Стоимость добытой продукции
/// </summary>
public decimal ProductsPrice { get; set; }
/// <summary>
/// Решить вопрос об изъятых вещах
/// </summary>
public string AboutArrest { get; set; }
/// <summary>
/// Банковские реквизиты
/// </summary>
public string BankDetails { get; set; }
}
}
<file_sep>/AppPresentators/VModels/PassesSearchModel.cs
using AppData.CustomAttributes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public class PassesSearchModel
{
[DisplayName("ФИО")]
public string FIO { get; set; }
[DisplayName("Тип документа")]
public string DocumentType { get; set; }
[DisplayName("Серия документа")]
public string Serial { get; set; }
[DisplayName("Номер документа")]
public string Number { get; set; }
[DisplayName("Кем выдан")]
public string IssuedBy { get; set; }
[ControlType(ControlType.DateTime)]
[DisplayName("Когда выдан")]
[ChildrenProperty("CompareWhenIssued")]
public DateTime WhenIssued { get; set; } = DateTime.Now;
[Browsable(false)]
public CompareValue CompareWhenIssued { get; set; } = CompareValue.NONE;
[ControlType(ControlType.DateTime)]
[DisplayName("Когда выдан пропуск")]
[ChildrenProperty("CompareWhenGived")]
public DateTime WhenGived { get; set; } = DateTime.Now;
[Browsable(false)]
public CompareValue CompareWhenGived { get; set; } = CompareValue.NONE;
[ControlType(ControlType.DateTime)]
[DisplayName("Пропуск выдан до")]
[ChildrenProperty("CompareWhenClosed")]
public DateTime WhenClosed { get; set; } = DateTime.Now;
[Browsable(false)]
public CompareValue CompareWhenClosed { get; set; } = CompareValue.NONE;
public bool IsEmptySearchModel()
{
return string.IsNullOrWhiteSpace(FIO) && string.IsNullOrWhiteSpace(DocumentType) && string.IsNullOrWhiteSpace(Serial) && string.IsNullOrWhiteSpace(Number)
&& string.IsNullOrWhiteSpace(IssuedBy) && CompareWhenIssued == CompareValue.NONE && CompareWhenClosed == CompareValue.NONE && CompareWhenGived == CompareValue.NONE;
}
}
}
<file_sep>/AppCore/Repositrys/Violations/Protocols/ProtocolAboutBringingRepository.cs
using AppData.Abstract.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations.Protocols
{
public class ProtocolAboutBringingRepository : IProtocolAboutBringingRepository
{
public IQueryable<ProtocolAboutBringing> ProtocolsAboutBringing
{
get
{
var db = new LeoBaseContext();
return db.ProtocolsAboutBringing;
}
}
public int SaveProtocolAboutBringing(ProtocolAboutBringing protocol)
{
using(var db = new LeoBaseContext())
{
db.ProtocolsAboutBringing.Add(protocol);
db.SaveChanges();
return protocol.ProtocolAboutBringingID;
}
}
}
}
<file_sep>/AppPresentators/VModels/Persons/EmploeyrViewModel.cs
using AppData.Abstract;
using AppData.CustomAttributes;
using AppData.Infrastructure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Persons
{
public class EmploeyrViewModel: IPersoneViewModel
{
[BrowsableForEditAndDetails(true, true)]
[DisplayName("Фамилия")]
[ReadOnly(true)]
public string FirstName { get; set; }
[BrowsableForEditAndDetails(true, true)]
[ReadOnly(true)]
[DisplayName("Имя")]
public string SecondName { get; set; }
[BrowsableForEditAndDetails(true, true)]
[ReadOnly(true)]
[DisplayName("Отчество")]
public string MiddleName { get; set; }
[BrowsableForEditAndDetails(false, false)]
[ReadOnly(true)]
[DisplayName("Должность")]
public string Position { get; set; }
[BrowsableForEditAndDetails(true, true)]
[ReadOnly(true)]
[DisplayName("Дата рождения")]
[ControlType(ControlType.DateTime)]
public DateTime DateBirthday { get; set; }
[BrowsableForEditAndDetails(true, true)]
[ReadOnly(true)]
[DisplayName("Место рождения")]
public string PlaceOfBirth { get; set; }
[BrowsableForEditAndDetails(false, false)]
[ReadOnly(true)]
[DisplayName("Добавлено в базу")]
public DateTime WasBeCreated { get; set; }
[BrowsableForEditAndDetails(false, false)]
[ReadOnly(true)]
[DisplayName("Последнее обновление")]
public DateTime WasBeUpdated { get; set; }
[BrowsableForEditAndDetails(false, false)]
[Browsable(false)]
public bool IsEmploeyr { get; set; }
[BrowsableForEditAndDetails(true, true)]
[Browsable(false)]
[ControlType(ControlType.ComboBox, "Value", "Display")]
[DataPropertiesName("PositionsData")]
[DisplayName("Должность")]
[PropertyNameSelectedText("Position")]
public string PositionID { get; set; }
[BrowsableForEditAndDetails(false, false)]
[Browsable(false)]
public int UserID { get; set; }
[BrowsableForEditAndDetails(true, true)]
[ControlType(ControlType.Image)]
[DisplayName("Изображение")]
[Browsable(false)]
public byte[] Image { get; set; } = new byte[0];
[BrowsableForEditAndDetails(true, true)]
[Browsable(false)]
[DisplayName("Адреса")]
[ControlType(ControlType.List)]
[GenerateEmptyModelPropertyName("GenerateEmptyAddress")]
public List<PersonAddressModelView> Addresses { get; set; }
[Browsable(false)]
[BrowsableForEditAndDetails(false, false)]
public Func<object> GenerateEmptyAddress
{
get
{
return () =>
{
return new PersonAddressModelView
{
AddressID = -1
};
};
}
}
[BrowsableForEditAndDetails(false, false)]
[Browsable(false)]
public List<PersoneDocumentModelView> Documents { get; set; }
[BrowsableForEditAndDetails(true, true)]
[ControlType(ControlType.List)]
[GenerateEmptyModelPropertyName("GenerateEmptyPhone")]
[Browsable(false)]
public List<PhoneViewModel> Phones { get; set; }
[BrowsableForEditAndDetails(false, false)]
[Browsable(false)]
public Func<object> GenerateEmptyPhone
{
get
{
return () =>
{
return new PhoneViewModel
{
PhoneID = -1
};
};
}
}
[BrowsableForEditAndDetails(false, false)]
[Browsable(false)]
public BindingList<ComboBoxDefaultItem> PositionsData
{
get
{
return new BindingList<ComboBoxDefaultItem>(ConfigApp.EmployerPositionsList.Select(dt => new ComboBoxDefaultItem { Display = dt.Name, Value = dt.PositionID.ToString() }).ToList());
}
}
}
}
<file_sep>/AppPresentators/Infrastructure/ResultTypes.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Infrastructure
{
public enum ResultTypes
{
NONE,
ADD_PERSONE,
UPDATE_PERSONE,
SEARCH_PERSONE,
SEARCH_VIOLATOR,
SEARCH_EMPLOYER,
DETAILS_VIOLATOR,
DETAILS_EMPLOYER,
DETAILS_VIOLATION,
UPDATE_VIOLATION,
ADD_VIOLATION,
SHOW_ON_MAP,
ADD_VIOLATOR,
ADD_EMPLOYER,
FIND_EMPLOYER,
FIND_VIOLATOR,
EDIT_PASS,
SAVE_PASS,
DETAILS_PASS
}
}
<file_sep>/AppPresentators/VModels/MainMenu/MenuCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.MainMenu
{
public enum MenuCommand
{
/// <summary>
/// Нарушения
/// </summary>
Infringement,
/// <summary>
/// Нарушители
/// </summary>
Violators,
/// <summary>
/// Сотрудники
/// </summary>
Employees,
/// <summary>
/// Пропуски
/// </summary>
Omissions,
/// <summary>
/// Карта
/// </summary>
Map,
/// <summary>
/// Настройки
/// </summary>
Options
}
}
<file_sep>/LeoBase/Forms/LoginView.cs
using AppPresentators;
using AppPresentators.Components;
using AppPresentators.Views;
using LeoBase.Properties;
using MetroFramework.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Forms
{
public partial class LoginView : Form, ILoginView
{
public event Action Login;
public event Action Cancel;
public event Action CloseAndLogin;
private bool _wasLoginClicked = false;
public LoginView()
{
InitializeComponent();
this.MaximizeBox = false;
this.MinimizeBox = false;
Text = null;
}
public string Password
{
get
{
if (tbPassword == null) return "";
return tbPassword.Text;
}
set
{
tbPassword.Text = value;
}
}
public string UserName
{
get
{
if (tbLogin == null) return "";
return tbLogin.Text;
}
set
{
tbLogin.Text = value;
}
}
private static string _errorMessage = "";
public void ShowError(string errorMessage)
{
_errorMessage = errorMessage;
//pbLoader.Visible = false;
//tbLogin.Enabled = true;
//tbPassword.Enabled = true;
//_wasLoginClicked = false;
//lbError.Text = errorMessage;
//lbError.Visible = true;
}
private void LoginView_Load(object sender, EventArgs ev)
{
btnLogin.Click += (s, e) =>
{
_wasLoginClicked = true;
Login();
};
//tbLogin.BackColor = Color.FromArgb(66, 66, 66);
//tbPassword.BackColor = Color.FromArgb(66, 66, 66);
lbError.BackColor = Color.Transparent;
//tbLogin.ForeColor = Color.FromArgb(138, 138, 138);
//tbPassword.ForeColor = Color.FromArgb(138, 138, 138);
tbLogin.GotFocus += tb_GotFocus;
tbLogin.LostFocus += tb_LostFocus;
tbPassword.GotFocus += tb_GotFocus;
tbPassword.LostFocus += tb_LostFocus;
tbLogin.KeyDown += tb_KeyDown;
tbPassword.KeyDown += tb_KeyDown;
this.KeyDown += tb_KeyDown;
btnCancel.Click += (s, e) => Cancel();
this.FormClosed += (s, e) =>
{
pbLoader.Visible = false;
if (!_wasLoginClicked)
Cancel();
};
//tbLogin.Text = "admin";
//tbPassword.Text = "<PASSWORD>";
loaderWorker.RunWorkerCompleted += LoaderWorker_RunWorkerCompleted;
loaderWorker.DoWork += LoaderWorker_DoWork;
}
private void LoaderWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (Login != null)
{
Login();
}
}
private void LoaderWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(ConfigApp.CurrentManager == null)
{
ShowError("Неверные логин или пароль");
pbLoader.Visible = false;
tbLogin.Enabled = true;
tbPassword.Enabled = true;
_wasLoginClicked = false;
lbError.Text = _errorMessage;
lbError.Visible = true;
}
else
{
if(CloseAndLogin != null)
CloseAndLogin();
}
}
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
if (loaderWorker.IsBusy) return;
_wasLoginClicked = true;
pbLoader.Visible = true;
tbLogin.Enabled = false;
tbPassword.Enabled = false;
this.Refresh();
loaderWorker.RunWorkerAsync();
}else if(e.KeyCode == Keys.Escape)
{
if (Cancel != null) Cancel();
}
}
private void tb_LostFocus(object sender, EventArgs e)
{
if (sender == tbLogin)
{
pbLogin.Image = Resources.tbAutorizeNotFocuse;
}
else
{
pbPassword.Image = Resources.tbAutorizeNotFocuse;
}
}
private void tb_GotFocus(object sender, EventArgs e)
{
if(sender == tbLogin)
{
pbLogin.Image = Resources.tbAutorizeFocuse;
}else
{
pbPassword.Image = Resources.tbAutorizeFocuse;
}
}
public void Show()
{
//loaderWorker.RunWorkerAsync();
ShowDialog();
}
}
}
<file_sep>/Tests/Presentators/TestMainPresentator.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AppPresentators.Infrastructure;
using AppPresentators.Views;
using Moq;
using AppPresentators.Presentators.Interfaces;
using AppPresentators.Presentators;
using LeoBase.Infrastructure;
using Ninject;
using AppPresentators.Services;
using AppPresentators.VModels;
using AppPresentators.VModels.MainMenu;
using System.Collections.Generic;
using AppPresentators.Components.MainMenu;
namespace Tests.Presentators
{
[TestClass]
public class TestMainPresentator
{
private IApplicationFactory _appFactory;
private IMainPresentator _mainPresentator;
private Mock<IMainView> _mockMainView;
private Mock<IMainMenu> _mockMainMenu;
private Mock<ILoginView> _mockLoginView;
private Mock<ILoginPresentator> _mockLoginPresentator;
private Mock<ILoginService> _mockLoginService;
private Mock<IPermissonsService> _mockPermissionService;
private IKernel _ninjectKernel;
[TestInitialize]
public void Initialize()
{
InitMock();
InitMockMethodAndProperties();
InitNinjectKernel();
_appFactory = new ApplicationFactory(_ninjectKernel);
_mainPresentator = new MainPresentator(_appFactory);
}
private void InitNinjectKernel()
{
_ninjectKernel = new StandardKernel();
_ninjectKernel.Bind<IMainView>().ToConstant(_mockMainView.Object);
_ninjectKernel.Bind<ILoginView>().ToConstant(_mockLoginView.Object);
_ninjectKernel.Bind<ILoginPresentator>().ToConstant(_mockLoginPresentator.Object);
_ninjectKernel.Bind<ILoginService>().ToConstant(_mockLoginService.Object);
_ninjectKernel.Bind<IPermissonsService>().ToConstant(_mockPermissionService.Object);
}
private void InitMockMethodAndProperties()
{
_mockMainView.Setup(m => m.ShowError(It.IsAny<string>()));
_mockMainView.Setup(m => m.Show());
_mockMainView.Setup(m => m.Close());
_mockMainView.SetupAllProperties();
_mockLoginView.SetupAllProperties();
_mockLoginView.Setup(m => m.Show());
_mockLoginService.Setup(m => m.Login(It.Is<string>(s => s.Equals("admin")), It.Is<string>(s => s.Equals("admin"))))
.Returns(new VManager
{
ManagerID = 1,
Login = "admin",
Password = "<PASSWORD>",
Role = "admin"
});
_mockLoginPresentator.Setup(lp => lp.Login(It.IsAny<string>(), It.IsAny<string>()));
_mockLoginPresentator.Setup(lp => lp.Run());
_mockPermissionService.Setup(mps => mps.GetMenuItems(It.Is<string>(s => s.Equals("admin")))).Returns(
new List<MenuItemModel>
{
new MenuItemModel
{
Title = "admin1"
},
new MenuItemModel
{
Title = "admin2"
}
}
);
_mockPermissionService.Setup(mps => mps.GetMenuItems(It.Is<string>(s => s.Equals("manager")))).Returns(
new List<MenuItemModel>
{
new MenuItemModel
{
Title = "manager1"
},
new MenuItemModel
{
Title = "manager2"
},
new MenuItemModel
{
Title = "manager3"
}
}
);
_mockMainMenu.Setup(mm => mm.AddMenuItems(It.IsAny<List<MenuItemModel>>()));
}
private void InitMock()
{
_mockMainView = new Mock<IMainView>();
_mockLoginView = new Mock<ILoginView>();
_mockLoginPresentator = new Mock<ILoginPresentator>();
_mockLoginService = new Mock<ILoginService>();
_mockPermissionService = new Mock<IPermissonsService>();
_mockMainMenu = new Mock<IMainMenu>();
}
[TestMethod]
public void TestShowMainView()
{
_mainPresentator.Run();
_mockMainView.Verify(m => m.Show());
}
[TestMethod]
public void TestLoginOnFirstOpenMainView()
{
_mainPresentator.Run();
_mainPresentator.Login();
_mockMainView.Verify(m => m.Show());
_mockLoginPresentator.Verify(m => m.Run());
}
}
}
<file_sep>/AppPresentators/VModels/AdminViolationRowModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public class AdminViolationRowModel
{
[Browsable(false)]
public int ViolationID { get; set; }
[DisplayName("Нарушитель")]
[ReadOnly(true)]
public string ViolatorInfo { get; set; }
[DisplayName("ФИО сотрудника")]
[ReadOnly(true)]
public string EmployerInfo { get; set; }
[DisplayName("Координаты")]
[ReadOnly(true)]
public string Coordinates { get; set; }
[DisplayName("Рассмотрение")]
[ReadOnly(true)]
public DateTime Consideration { get; set; }
[ReadOnly(true)]
[DisplayName("Нарушение")]
public string Violation { get; set; }
[ReadOnly(true)]
[DisplayName("Дата оплаты")]
public string DatePaymant { get; set; }
[ReadOnly(true)]
[DisplayName("Сумма наложения")]
public decimal SumViolation { get; set; }
[ReadOnly(true)]
[DisplayName("Сумма взыскания")]
public decimal SumRecovery { get; set; }
[ReadOnly(true)]
[DisplayName("Отправление")]
public string InformationAboutSending { get; set; }
[ReadOnly(true)]
[DisplayName("Отправлено судебным приставам")]
public string DateSentBailiff { get; set; }
[ReadOnly(true)]
[DisplayName("Извещение")]
public string InformationAboutNotice { get; set; }
[ReadOnly(true)]
[DisplayName("Повестка по статье 20.25")]
public string InformationAbout2025 { get; set; }
}
}
<file_sep>/AppCore/Entities/ProtocolAboutViolationOrganisation.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
/// <summary>
/// Протокол об административном правонарушение для юридического лица
/// </summary>
public class ProtocolAboutViolationOrganisation:IProtocol
{
[Key]
public int ProtocolAboutViolationOrganisationID { get; set; }
[Required(AllowEmptyStrings = false)]
public int OrganisationID { get; set; }
[Required(AllowEmptyStrings = false)]
public Protocol Protocol { get; set; }
public DateTime ViolationTime { get; set; }
public string KOAP { get; set; }
public string Description { get; set; }
}
}
<file_sep>/AppPresentators/Components/IViolationTableControl.cs
using AppPresentators.Services;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public enum ViolationActionType
{
UPDATE = 1,
DETAILS = 2,
REMOVE = 3,
SHOW_ON_MAP = 4,
ADD_NEW_VIOLATION = 5
}
public delegate void ViolationAction(ViolationActionType type, ViolationViewModel violation);
public interface IViolationTableControl:UIComponent
{
event Action AddNewViolation;
event ViolationAction RemoveViolation;
event ViolationAction UpdateViolation;
event ViolationAction ShowDetailsViolation;
event Action UpdateData;
ViolationSearchModel SearchModel { get; }
ViolationOrderModel OrderModel { get; }
PageModel PageModel { get; set; }
List<ViolationViewModel> Violations { get; set; }
void ShowMessage(string message);
void LoadStart();
void LoadEnd();
}
}
<file_sep>/AppPresentators/VModels/VViolation.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public class VViolator
{
public int ID { get; set; }
}
public class VEmployer
{
public int ID { get; set; }
}
public class VViolationType
{
public int ID { get; set; }
public string Name { get; set; }
}
public class VViolation
{
private Violation _violation;
public int ViolationID { get; set; }
public string Date { get; set; }
public VViolationType ViolationType { get; set; }
public double N { get; set; }
public double E { get; set; }
public string Description { get; set; }
public List<VViolator> Violators { get; set; }
public List<VEmployer> Employers { get; set; }
}
}
<file_sep>/AppPresentators/Components/MainMenu/IMainMenuItem.cs
using AppPresentators.VModels.MainMenu;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components.MainMenu
{
public delegate void ItemClicked(MenuCommand command);
public interface IMainMenuItem : UIComponent
{
string Title { get; set; }
byte[] Icon { get; set; }
MenuCommand MenuCommand {get;set;}
event ItemClicked ItemClicked;
bool IsActive { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/OpenSearchPanelButton.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls
{
public class OpenSearchPanelButton:Panel
{
public event Action OnClickButton;
private Color _mouseHover = Color.FromArgb(255, 178, 178, 177);
private Color _defaultColor = Color.FromArgb(255, 89, 78, 60);
private Color _mouseDown = Color.FromArgb(255, 222, 221, 219);
private Label _btnText;
private PictureBox _lupa;
public OpenSearchPanelButton()
{
_btnText = new Label();
_lupa = new PictureBox();
_lupa.Width = 18;
_lupa.Height = 18;
_lupa.Image = Properties.Resources.lupa_small;
_btnText.ForeColor = _defaultColor;
_btnText.Text = "Открыть расширенный поиск";
_btnText.Font = new System.Drawing.Font("Arial", 11, FontStyle.Regular);
this.Cursor = Cursors.Hand;
_btnText.AutoSize = true;
_btnText.MouseDown += OnMouseDown;
this.MouseDown += OnMouseDown;
_btnText.MouseUp += OnMouseUp;
this.MouseUp += OnMouseUp;
_btnText.MouseLeave += OnMouseLeave;
this.MouseLeave += OnMouseLeave;
_btnText.MouseMove += OnMouseMove;
this.MouseMove += OnMouseMove;
this.Controls.Add(_lupa);
_btnText.Left = 20;
this.Controls.Add(_btnText);
this.Width = _btnText.Width + 22;
this.Height = _btnText.Height + 6;
this.Click += OnClick;
_btnText.Click += OnClick;
}
private void OnClick(object sender, EventArgs e)
{
if (OnClickButton != null) OnClickButton();
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
_btnText.ForeColor = _mouseHover;
}
private void OnMouseLeave(object sender, EventArgs e)
{
_btnText.ForeColor = _defaultColor;
}
private void OnMouseUp(object sender, MouseEventArgs e)
{
_btnText.ForeColor = _defaultColor;
}
private void OnMouseDown(object sender, MouseEventArgs e)
{
_btnText.ForeColor = _mouseDown;
}
}
}
<file_sep>/AppCore/FakesRepositoryes/FakePersonesRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
namespace AppData.FakesRepositoryes
{
public class FakePersonesRepository : IPersoneRepository
{
private List<Persone> _persones = new List<Persone> { new Persone()
{
UserID = 1,
FirstName = "Иванов",
SecondName = "Иван",
MiddleName = "Васильевич",
DateBirthday = new DateTime(1990, 5, 10, 0, 0, 0)
},
new Persone
{
UserID = 2,
FirstName = "Сидоров",
SecondName = "Евгений",
MiddleName = "Эдуардович",
DateBirthday = new DateTime(1992, 10, 5, 0, 0, 0)
},
new Persone
{
UserID = 3,
FirstName = "Кирилов",
SecondName = "Илья",
MiddleName = "Петрововия",
DateBirthday = new DateTime(1989, 6, 7, 0, 0, 0)
},
new Persone
{
UserID = 4,
IsEmploeyr = true,
FirstName = "Сидоренко",
SecondName = "Илья",
MiddleName = "Игоревич",
Position_PositionID = 1,
DateBirthday = new DateTime(1978, 2, 12, 0, 0, 0)
},
new Persone
{
UserID = 5,
IsEmploeyr = true,
FirstName = "Иванов",
SecondName = "Юрий",
MiddleName = "Петрововия",
Position_PositionID = 2,
DateBirthday = new DateTime(1995, 3, 15, 0, 0, 0)
},
//new Persone
//{
// UserID = 6,
// IsEmploeyr = true,
// FirstName = "Иванов2",
// SecondName = "Юрий",
// MiddleName = "Петрововия",
// PositionID = 2,
// DateBirthday = new DateTime(1995, 3, 15, 0, 0, 0)
//},
//new Persone
//{
// UserID = 7,
// IsEmploeyr = true,
// FirstName = "Иванов3",
// SecondName = "Юрий",
// MiddleName = "Петрововия",
// PositionID = 2,
// DateBirthday = new DateTime(1995, 3, 15, 0, 0, 0)
//},
//new Persone
//{
// UserID = 8,
// IsEmploeyr = true,
// FirstName = "Иванов4",
// SecondName = "Юрий",
// MiddleName = "Петрововия",
// PositionID = 2,
// DateBirthday = new DateTime(1995, 3, 15, 0, 0, 0)
//}
};
public IQueryable<Persone> Persons
{
get
{
return _persones.AsQueryable();
}
}
public int Count
{
get
{
return _persones.Count();
}
}
public int AddPersone(Persone persone)
{
int id = _persones.Max(p => p.UserID) + 1;
persone.UserID = id;
_persones.Add(persone);
return id;
}
public bool Remove(int id)
{
var persone = _persones.FirstOrDefault(p => p.UserID == id);
if (persone == null) return false;
return _persones.Remove(persone);
}
public bool Update(Persone persone)
{
throw new NotImplementedException();
}
public bool SimpleRemove(int id)
{
throw new NotImplementedException();
}
}
}
<file_sep>/LeoBase/Infrastructure/ApplicationFactory.cs
using AppPresentators.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Presentators.Interfaces;
using AppPresentators.Views;
using Ninject;
using AppPresentators.Presentators;
using AppPresentators.Services;
using Ninject.Parameters;
using LeoBase.Forms;
using LeoBase.Components.MainMenu;
using AppPresentators.Components.MainMenu;
using AppPresentators.Components;
using AppPresentators.VModels.MainMenu;
using LeoBase.Components;
using LeoBase.Components.CustomControls;
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using LeoBase.Components.CustomControls.SaveComponent;
using LeoBase.Components.CustomControls.DetailsComponent;
using AppPresentators.Components.Protocols;
using LeoBase.Components.CustomControls.Protocols;
using AppPresentators.Presentators.Protocols;
using AppPresentators.Presentators.Interfaces.ProtocolsPresentators;
namespace LeoBase.Infrastructure
{
public class ApplicationFactory : IApplicationFactory
{
private IKernel _ninjectKernel;
public ApplicationFactory()
{
_ninjectKernel = new StandardKernel();
Init();
}
public ApplicationFactory(IKernel kernel)
{
_ninjectKernel = kernel;
}
public T GetView<T>()
{
return _ninjectKernel.Get<T>();
}
public T GetService<T>()
{
return _ninjectKernel.Get<T>();
}
public T GetPresentator<T>()
{
ConstructorArgument[] args = new ConstructorArgument[]
{
new ConstructorArgument("appFactory", this)
};
return _ninjectKernel.Get<T>(args);
}
public T GetPresentator<T, V, S>(IMainView main)
{
V view = GetView<V>();
S service = GetService<S>();
ConstructorArgument[] args = new ConstructorArgument[]
{
new ConstructorArgument("main", main),
new ConstructorArgument("service", service),
new ConstructorArgument("view", view)
};
return _ninjectKernel.Get<T>(args);
}
public T GetPresentator<T>(IMainView main)
{
ConstructorArgument[] args = new ConstructorArgument[]
{
new ConstructorArgument("main", main),
new ConstructorArgument("appFactory", this)
};
return _ninjectKernel.Get<T>(args);
}
public IMainPresentator GetMainPresentator()
{
var mainPresentator = MainPresentator.GetInstance(null);
return mainPresentator;
}
public IMainPresentator GetMainPresentator(IApplicationFactory appFactory)
{
var mainPresentator = MainPresentator.GetInstance(appFactory);
return mainPresentator;
// ConstructorArgument[] args = new ConstructorArgument[]
//{
// //new ConstructorArgument("view", main),
// new ConstructorArgument("appFactory", appFactory)
//};
// return _ninjectKernel.Get<IMainPresentator>(args);
}
public IMainView GetMainView()
{
return MainView.GetInstance();
}
private void Init()
{
#region Presentators
_ninjectKernel.Bind<IMainPresentator>().To<MainPresentator>();
_ninjectKernel.Bind<ILoginPresentator>().To<LoginPresentator>();
_ninjectKernel.Bind<IEmployersPresentator>().To<EmployersPresentator>();
_ninjectKernel.Bind<ISaveEmployerPresentator>().To<SavePersonPresentator>();
_ninjectKernel.Bind<IPersoneDetailsPresentator>().To<PersoneDetailsPresentator>();
_ninjectKernel.Bind<IViolatorTablePresentator>().To<ViolatorTablePresentator>();
_ninjectKernel.Bind<IViolationTablePresentator>().To<ViolationTablePresentator>();
//_ninjectKernel.Bind<IAddOrUpdateViolation>().To<AddOrUpdateViolationPresentator>();
_ninjectKernel.Bind<ISaveAdminViolationPresentatar>().To<SaveAdminViolationPresentator>();
_ninjectKernel.Bind<IAdminViolationTablePresentator>().To<AdminViolationTablePresentator>();
_ninjectKernel.Bind<IViolationDetailsPresentator>().To<ViolationDetailsPresentator>();
_ninjectKernel.Bind<IViolatorDetailsPresentator>().To<ViolatorDetailsPresentator>();
_ninjectKernel.Bind<IEmployerDetailsPresentator>().To<EmploerDetailsPresentator>();
_ninjectKernel.Bind<IOptionsPresentator>().To<OptionsPresentator>();
_ninjectKernel.Bind<IMapPresentator>().To<MapPresentator>();
_ninjectKernel.Bind<IPassesPresentator>().To<PassesPresentator>();
_ninjectKernel.Bind<IEditPassPresentator>().To<EditPassPresentator>();
_ninjectKernel.Bind<IPassDeatailsPresentator>().To<PassDetailsPresentator>();
#endregion
#region Services
_ninjectKernel.Bind<ILoginService>().To<TestLoginService>();
_ninjectKernel.Bind<IPermissonsService>().To<PermissonsService>();
_ninjectKernel.Bind<IPersonesService>().To<PersonesService>();
_ninjectKernel.Bind<IViolationService>().To<ViolationService>();
_ninjectKernel.Bind<IAdminViolationService>().To<AdminViolationService>();
#endregion
#region Views
_ninjectKernel.Bind<IMainView>().To<MainView>();
_ninjectKernel.Bind<ILoginView>().To<LoginView>();
#endregion
#region Components
_ninjectKernel.Bind<IMainMenu>().To<MainMenu>();
_ninjectKernel.Bind<IEmployerDetailsControl>().To<LeoBase.Components.CustomControls.NewControls.EmployerDetailsControl>();
_ninjectKernel.Bind<IEmployersTableControl>().To<LeoBase.Components.CustomControls.NewControls.EmployerTableControl>();
_ninjectKernel.Bind<IOptionsControl>().To<LeoBase.Components.CustomControls.NewControls.OptionsPanel.OptionsControl>();
_ninjectKernel.Bind<ISavePersonControl>().To<Components.CustomControls.NewControls.PersoneSavePanel> ();
_ninjectKernel.Bind<IViolatorDetailsControl>().To<Components.CustomControls.NewControls.ViolatorDetailsControl>();
_ninjectKernel.Bind<IPersoneDetailsControl>().To<PersoneDetailsControl>();
_ninjectKernel.Bind<IViolatorTableControl>().To<Components.CustomControls.NewControls.ViolatorTableControl>();
_ninjectKernel.Bind<IViolationTableControl>().To<ViolationTableControl>();
_ninjectKernel.Bind<ILoadedControl>().To<LoadedControl>();
_ninjectKernel.Bind<ISaveOrUpdateViolationControl>().To<SaveViolationControl>();
_ninjectKernel.Bind<IAdminViolationControl>().To<AdminintrationViolationTableControl>();
_ninjectKernel.Bind<ISaveAdminViolationControl>().To<Components.CustomControls.NewControls.SaveViolationControl>();
_ninjectKernel.Bind<IViolationDetailsControl>().To<LeoBase.Components.CustomControls.NewControls.ViolationDetailsControl>();
_ninjectKernel.Bind<IMapControl>().To<LeoBase.Components.CustomControls.NewControls.MapControl>();
_ninjectKernel.Bind<IPassesTableControl>().To<Components.CustomControls.NewControls.PassesTableControl>();
_ninjectKernel.Bind<IEditPassControl>().To<Components.CustomControls.NewControls.SavePassControl>();
_ninjectKernel.Bind<IPassDetailsControl>().To<Components.CustomControls.NewControls.PassDetailsControl>();
#endregion
#region ProtocolsView
_ninjectKernel.Bind<IProtocolAboutViolationView>().To<ViolationAboutPersoneView>();
#endregion
#region ProtocolsPresentators
_ninjectKernel.Bind<IProtocolAboutViolationPresentator>().To<ProtocolAboutViolationPresentator>();
#endregion
}
public T GetComponent<T>()
{
return _ninjectKernel.Get<T>();
}
public UIComponent GetComponent(MenuCommand command)
{
return null;/* TestComponent
{
Title = command.ToString()
};*/
}
}
}
<file_sep>/AppCore/Entities/ProtocolAboutViolationPersone.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
/// <summary>
/// Протокол об административном правонарушение для физического лица
/// </summary>
public class ProtocolAboutViolationPersone:IProtocol
{
[Key]
public int ProtocolAboutViolationPersoneID { get; set; }
[Required(AllowEmptyStrings = false)]
public Protocol Protocol { get; set; }
[Required(AllowEmptyStrings = false)]
public int ViolatorDocumentID { get; set; }
/// <summary>
/// Дата и время правонарушения
/// </summary>
public DateTime ViolationDate { get; set; }
/// <summary>
/// Описание правонарушения
/// </summary>
public string ViolationDescription { get; set; }
/// <summary>
/// Статья КОАП за данное нарушение
/// </summary>
public string KOAP { get; set; }
/// <summary>
/// Найденная продукция природопользования
/// </summary>
public string FindedNatureManagementProducts { get; set; }
/// <summary>
/// Найденное оружие
/// </summary>
public string FindedWeapons { get; set; }
/// <summary>
/// Найденые орудия для охоты и рыболовства
/// </summary>
public string FindedGunsHuntingAndFishing { get; set; }
}
}
<file_sep>/AppCore/CustomAttributes/ControlTypeAttribute.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.CustomAttributes
{
public class ControlTypeAttribute:Attribute
{
public ControlType ControlType { get; set; }
public string ValueMember { get; set; }
public string DisplayMember { get; set; }
public ControlTypeAttribute(ControlType controlType, string valueMember = null, string displayMember = null)
{
ControlType = controlType;
ValueMember = valueMember;
DisplayMember = displayMember;
}
}
public class DinamicBrowsableAttribute : Attribute
{
public string PropertyName { get; set; }
public bool PropertyValue { get; set; }
public DinamicBrowsableAttribute(string propertyName, bool propertyValue)
{
PropertyName = propertyName;
PropertyValue = propertyValue;
}
}
public class PropertyNameSelectedTextAttribute:Attribute
{
public string PropertyName { get; set; }
public PropertyNameSelectedTextAttribute(string propertyName)
{
PropertyName = propertyName;
}
}
public class BrowsableForEditAndDetailsAttribute:Attribute
{
public bool BrowsableForEdit { get; set; }
public bool BrowsableForDetails { get; set; }
public BrowsableForEditAndDetailsAttribute(bool browsableForEdit, bool browsableForDetails)
{
BrowsableForDetails = browsableForDetails;
BrowsableForEdit = browsableForEdit;
}
}
public class DataPropertiesNameAttribute : Attribute
{
public string PropertyDataName { get; set; }
public DataPropertiesNameAttribute(string propertyDataName)
{
PropertyDataName = propertyDataName;
}
}
public class ControlDataAttribute : Attribute
{
public IList Source { get; set; }
public ControlDataAttribute(IList source)
{
Source = source;
}
}
public class ChildrenPropertyAttribute : Attribute
{
public string ChildrenPropertyName { get; set; }
public ChildrenPropertyAttribute(string childrenPropertyName)
{
ChildrenPropertyName = childrenPropertyName;
}
}
public class GenerateEmptyModelPropertyNameAttribute : Attribute
{
public string PropertyName { get; set; }
public GenerateEmptyModelPropertyNameAttribute(string propertyName)
{
PropertyName = propertyName;
}
}
public class ComboBoxDefaultItem
{
public string Value { get; set; }
public string Display { get; set; }
}
public enum ControlType
{
Text,
Int,
Real,
ComboBox,
DateTime,
Image,
ImageGallary,
List
}
}
<file_sep>/LeoBase/Components/CustomControls/SearchPanels/PersoneSearchPanel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels.Persons;
using AppPresentators.VModels;
namespace LeoBase.Components.CustomControls.SearchPanels
{
public partial class PersoneSearchPanel : UserControl
{
private PersonsSearchModel _searchModel;
private bool _isEmployerSearch;
public bool ItSearchForEmployer { get
{
return _isEmployerSearch;
}
set
{
_isEmployerSearch = value;
if (value)
{
lbPosition.Visible = true;
cmbPosition.Visible = true;
lbWorkPlace.Visible = false;
tbWorkPlace.Visible = false;
cbComapreWorkPlace.Visible = false;
}
else
{
lbPosition.Visible = false;
cmbPosition.Visible = false;
lbWorkPlace.Visible = true;
tbWorkPlace.Visible = true;
cbComapreWorkPlace.Visible = true;
}
}
}
public List<string> Positions
{
set
{
cmbPosition.Items.Clear();
foreach(var position in value)
{
cmbPosition.Items.Add(position);
}
}
}
public PersonsSearchModel SearchModel
{
get
{
_searchModel = new PersonsSearchModel
{
ComparePlaceOfBirth = cmbComparePlaceBerth.Checked ? CompareString.EQUAL : CompareString.CONTAINS,
PlaceOfBirth = tbPlaceBerth.Text.Trim(),
ComparePlaceWork = cbComapreWorkPlace.Checked ? CompareString.EQUAL : CompareString.CONTAINS,
PlaceWork = tbWorkPlace.Text.Trim(),
FirstName = tbFirstName.Text.Trim(),
CompareFirstName = chbFirstName.Checked ? CompareString.EQUAL : CompareString.CONTAINS,
SecondName = tbSecondName.Text.Trim(),
CompareSecondName = chbSecondName.Checked ? CompareString.EQUAL : CompareString.CONTAINS,
MiddleName = tbMiddleName.Text.Trim(),
CompareMiddleName = chbMiddleName.Checked ? CompareString.EQUAL : CompareString.CONTAINS,
DateBirthday = dtpDateBerthday.Value.Year != 1900 ?
dtpDateBerthday.Value :
new DateTime(1, 1, 1, 0, 0, 0),
CompareDate = chbDateBerthday.Items[chbDateBerthday.SelectedIndex] == null ? CompareValue.EQUAL :
chbDateBerthday.Items[chbDateBerthday.SelectedIndex].ToString().Equals("Больше") ? CompareValue.MORE :
chbDateBerthday.Items[chbDateBerthday.SelectedIndex].ToString().Equals("Меньше") ? CompareValue.LESS :
CompareValue.EQUAL,
Age = Convert.ToInt32((string.IsNullOrEmpty(tbAge.Text.Trim())
? "0" :
tbAge.Text.Trim())),
CompareAge = cmbAge.Items[cmbAge.SelectedIndex] == null ? CompareValue.EQUAL :
cmbAge.Items[cmbAge.SelectedIndex].ToString().Equals("Больше") ? CompareValue.MORE :
cmbAge.Items[cmbAge.SelectedIndex].ToString().Equals("Меньше") ? CompareValue.LESS :
CompareValue.EQUAL,
Position = cmbPosition.Items[cmbPosition.SelectedIndex].ToString() != null ?
cmbPosition.Items[cmbPosition.SelectedIndex].ToString() :
"",
};
return _searchModel;
}
set
{
}
}
public PersoneSearchPanel()
{
InitializeComponent();
cmbAge.SelectedIndex = 0;
chbDateBerthday.SelectedIndex = 0;
cmbPosition.SelectedIndex = 0;
}
public void Clear()
{
tbFirstName.Text = "";
tbSecondName.Text = "";
tbMiddleName.Text = "";
tbAge.Text = "";
tbWorkPlace.Text = "";
tbPlaceBerth.Text = "";
dtpDateBerthday.Value = new DateTime(1900, 1, 1);
cmbPosition.SelectedIndex = 0;
chbFirstName.Checked = true;
chbSecondName.Checked = true;
chbMiddleName.Checked = true;
cbComapreWorkPlace.Checked = true;
cmbComparePlaceBerth.Checked = true;
cmbAge.SelectedIndex = 0;
chbDateBerthday.SelectedIndex = 0;
}
private void btnClearSearchModel_Click(object sender, EventArgs e)
{
Clear();
}
}
}
<file_sep>/WPFPresentators/Services/LoginService.cs
using BFData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFPresentators.Services
{
public interface ILoginService:IService
{
Manager Login(string login, string password);
}
public class LoginService:ILoginService
{
public Manager Login(string login, string password)
{
using(var db = new DataBaseDataContext())
{
return db.Managers.FirstOrDefault(m => m.Login.Equals(login) && m.Password.Equals(password));
}
}
}
}
<file_sep>/AppCore/Repositrys/Violations/ViolationTypesRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations
{
public class ViolationTypesRepository : IViolationTypeRepository
{
public IQueryable<ViolationType> ViolationTypes
{
get
{
var db = new LeoBaseContext();
return db.ViolationsType;
}
}
}
}
<file_sep>/Tests/Presentators/TestLoginPresentator.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using AppPresentators.Services;
using AppPresentators.Views;
using AppPresentators.Presentators;
using AppPresentators.VModels;
namespace Tests.Presentators
{
[TestClass]
public class TestLoginPresentator
{
[TestMethod]
public void TestValidMangerLogin()
{
Mock<ILoginService> service = new Mock<ILoginService>();
Mock<IMainView> mainView = new Mock<IMainView>();
Mock<ILoginView> loginView = new Mock<ILoginView>();
LoginPresentator target = null;
VManager manager = new VManager
{
Login = "login",
Password = "<PASSWORD>",
ManagerID = 1,
Role = "admin"
};
service.Setup(s => s.Login(
It.Is<string>(login => login.Equals("login")),
It.Is<string>(password => password.Equals("<PASSWORD>"))
))
.Returns(manager);
loginView.Setup(s => s.Close());
target = new LoginPresentator(mainView.Object, service.Object, loginView.Object);
target.Login("login", "password");
service.Verify(s => s.Login(It.IsAny<string>(), It.IsAny<string>()));
loginView.Verify(lv => lv.Close(), Times.Once);
loginView.Verify(lv => lv.ShowError(It.IsAny<string>()), Times.Never);
}
[TestMethod]
public void TestInvalidMangerLogin()
{
Mock<ILoginService> service = new Mock<ILoginService>();
Mock<IMainView> mainView = new Mock<IMainView>();
Mock<ILoginView> loginView = new Mock<ILoginView>();
LoginPresentator target = null;
VManager manager = new VManager
{
Login = "login",
Password = "<PASSWORD>",
ManagerID = 1,
Role = "admin"
};
service.Setup(s => s.Login(
It.Is<string>(login => login.Equals("login2")),
It.Is<string>(password => password.Equals("<PASSWORD>"))
))
.Returns(manager);
loginView.Setup(s => s.Close());
target = new LoginPresentator(mainView.Object, service.Object, loginView.Object);
target.Login("login", "password");
service.Verify(s => s.Login(It.IsAny<string>(), It.IsAny<string>()));
loginView.Verify(lv => lv.Close(), Times.Never);
loginView.Verify(lv => lv.ShowError(It.IsAny<string>()), Times.Once);
}
[TestMethod]
public void TestSaveManagerToMainForm()
{
Mock<ILoginService> service = new Mock<ILoginService>();
Mock<IMainView> mainView = new Mock<IMainView>();
Mock<ILoginView> loginView = new Mock<ILoginView>();
LoginPresentator target = null;
VManager manager = new VManager
{
Login = "login",
Password = "<PASSWORD>",
ManagerID = 1,
Role = "admin"
};
mainView.SetupAllProperties();
service.Setup(s => s.Login(It.Is<string>(l => l.Equals(manager.Login)), It.Is<string>(p => p.Equals(manager.Password)))).Returns(manager);
loginView.Setup(s => s.Close());
target = new LoginPresentator(mainView.Object, service.Object, loginView.Object);
target.LoginComplete += (m) => mainView.Object.Manager = m;
target.Login("login", "password");
Assert.AreEqual(mainView.Object.Manager.Login, manager.Login);
Assert.AreEqual(mainView.Object.Manager.Password, manager.Password);
Assert.AreEqual(mainView.Object.Manager.Role, manager.Role);
Assert.AreEqual(mainView.Object.Manager.ManagerID, manager.ManagerID);
loginView.Verify(s => s.Close());
}
}
}
<file_sep>/AppCore/Entities/Violator.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
public class Violator
{
[Key]
public int ViolatorID { get; set; }
public int PersoneID { get; set; }
public int ViolationID { get; set; }
public string ViolatorType { get; set; } = "Гражданин"; // "Гражданин или организация"
public Protocol Protocol { get; set; }
}
}
<file_sep>/AppCore/Repositrys/Violations/Protocols/DefinitionsAboutViolationRepository.cs
using AppData.Abstract.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations.Protocols
{
public class DefinitionsAboutViolationRepository : IDefinitionsAboutViolationRepository
{
public IQueryable<DefinitionAboutViolation> DefinitionsAboutViolation
{
get
{
var db = new LeoBaseContext();
return db.DefinitionsAboutViolation;
}
}
}
}
<file_sep>/AppPresentators/VModels/ComboSelectedValueAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public class ComboSelectedValueAttribute:Attribute
{
}
}
<file_sep>/AppPresentators/Components/IAdminViolationControl.cs
using AppPresentators.Services;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppPresentators.Components
{
public delegate void ViolationEvent(int id);
public interface IAdminViolationControl:UIComponent
{
event Action AddViolation;
event ViolationEvent RemoveViolation;
event ViolationEvent ShowDetailsViolation;
event ViolationEvent EditViolation;
event Action UpdateTable;
event Action BuildReport;
AdminViolationSearchModel SearchModel { get; }
AdminViolationOrderModel OrederModel { get; }
PageModel PageModel { get; set; }
List<AdminViolationRowModel> DataContext { get; set; }
DialogResult ShowConfitmDialog(string message, string title = null);
void LoadStart();
void LoadEnd();
}
}
<file_sep>/AppCore/Repositrys/DocumentTypesRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys
{
public class DocumentTypesRepository : IDocumentTypeRepository
{
public IQueryable<DocumentType> DocumentTypes
{
get
{
var db = new LeoBaseContext();
return db.DocumentsType;
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/SaveComponent/SaveDocument/DocumentsList.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels.Persons;
namespace LeoBase.Components.CustomControls.SaveComponent.SaveDocument
{
public partial class DocumentsList : UserControl
{
public List<PersoneDocumentModelView> Documents
{
get
{
List<PersoneDocumentModelView> result = new List<PersoneDocumentModelView>();
foreach(var item in flowLayoutPanel1.Controls)
{
var doc = (DocumentItem)item;
if(doc.Document != null)
{
result.Add(doc.Document);
}
}
return result;
}
set
{
flowLayoutPanel1.Controls.Clear();
flowLayoutPanel1.Refresh();
foreach(var item in value)
{
DocumentItem doc = new DocumentItem();
doc.Document = item;
doc.RemoveThis += () => RemoveItem(doc);
if (value.Count == 1) doc.ShowRemoveButton = false;
flowLayoutPanel1.Controls.Add(doc);
}
}
}
private void RemoveItem(Control control)
{
flowLayoutPanel1.Controls.Remove(control);
}
public DocumentsList()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DocumentItem doc = new DocumentItem();
doc.Document = new PersoneDocumentModelView
{
DocumentID = -1,
WhenIssued = new DateTime(1999, 1, 1)
};
doc.RemoveThis += () => RemoveItem(doc);
flowLayoutPanel1.Controls.Add(doc);
}
}
}
<file_sep>/TestConsoleApp/Program.cs
using AppData.Abstract;
using AppData.Contexts;
using AppData.Entities;
using AppData.Infrastructure;
using AppData.Repositrys;
using AppPresentators.Factorys;
using AppPresentators.Presentators;
using AppPresentators.Services;
using AppPresentators.VModels;
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.SqlServerCe;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestConsoleApp
{
class Program
{
#region Vars
Image image;//= Image.FromFile("C:\\Dev\\Images\\LeoBase\\ImagesNew\\avatar.jpg");
string[] first_names = new string[] {
"Иванов", "Петров", "Сидоров", "Григорьев", "Кузнецов", "Лаврентов"
};
string[] second_names = new string[] {
"Иван", "Евгений", "Генадий", "Кирил", "Илья", "Семен"
};
string[] middle_names = new string[] {
"Иванов", "Николаевич", "Генадьевич", "Лаврентов", "Евгеньевич", "Олегович"
};
string[] citys = new string[] {
"Барабаш", "Славянка", "Безверхово", "Овчиниково", "Занадворовка", "Филиповка"
};
string[] streets = new string[] {
"<NAME>", "Хасанская", "Лазо", "Молодежная", "Овчиниковская", "Дружба"
};
string[] countys = new string[] {
"США", "Российская федерация"
};
string[] subject = new string[] {
"Приморский край", "Хабаровский край"
};
string[] area = new string[] {
"Хасанский район", "Надежденский район"
};
string[] issuedBy = new string[] {
"Хасанский РОВД", "Приморским РОВД", "Барабашский ОМ"
};
#endregion
static void Main(string[] args)
{
new Program();
}
public byte[] imageToByteArray(Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms, ImageFormat.Jpeg);
return ms.ToArray();
}
}
Random rand = new Random();
private int getIndex(int number = 6)
{
return (int)Math.Ceiling(rand.NextDouble() * number);
}
private DateTime getDateBerthday()
{
return new DateTime(getIndex(100) + 1900, getIndex(12), getIndex(29));
}
private DateTime getIssuedWhen()
{
return new DateTime(getIndex(20) + 1996, getIndex(12), getIndex(29));
}
Program()
{
using(var db = new PassedContext())
{
db.Passes.Add(new Pass
{
DocumentType = "Паспорт",
FirstName = "Иванов",
SecondName = "Иван",
MiddleName = "Иванович",
Number = "2123",
Serial = "3214",
WhenIssued = new DateTime(1999, 12, 1),
PassGiven = DateTime.Now,
PassClosed = DateTime.Now.AddYears(1)
});
db.SaveChanges();
}
Console.ReadKey();
}
private PersoneViewModel makePersone()
{
List<PersonAddressModelView> addresses = new List<PersonAddressModelView>();
List<PersoneDocumentModelView> documents = new List<PersoneDocumentModelView>();
List<PhoneViewModel> phones = new List<PhoneViewModel>();
PersoneViewModel persone = new PersoneViewModel();
addresses.Add(new PersonAddressModelView
{
Country = "Российская федерация",
Subject = "Приморский край",
Area = "Хасанский район",
City = "пгт.Славянка",
Street = "ул.Героев-Хасана",
HomeNumber = "23",
Flat = "22",
Note = "Фактический"
});
addresses.Add(new PersonAddressModelView
{
Country = "Российская федерация",
Subject = "Приморский край",
Area = "Хасанский район",
City = "пгт.Славянка",
Street = "ул.Героев-Хасана",
HomeNumber = "25",
Flat = "21",
Note = "Прописан"
});
documents.Add(new PersoneDocumentModelView
{
DocumentTypeName = "Паспорт",
Serial = "4405",
Number = "11233",
IssuedBy = "Славянским РОВД Хасанского муниципального района",
WhenIssued = new DateTime(2012, 1, 2),
CodeDevision = "4500"
});
phones.Add(new PhoneViewModel { PhoneNumber = "8912123132" });
phones.Add(new PhoneViewModel { PhoneNumber = "1231321233" });
persone = new PersoneViewModel
{
Addresses = addresses,
Documents = documents,
DateBirthday = new DateTime(1990, 1, 1),
FirstName = "Сидоров",
SecondName = "Николай",
MiddleName = "Петровович",
Phones = phones,
IsEmploeyr = true,
//Position = "Госинспектор",
//PlaceOfBirth = "Приморский край, г.Владивосток"
};
return persone;
}
private void AddPersone(int count, bool isEmployer = false)
{
var personeRepository = RepositoryesFactory.GetInstance().Get<IPersoneRepository>();
byte[] imageBytes = imageToByteArray(image);
for (int i = 0; i < count; i++)
{
Persone persone1;
persone1 = new Persone
{
WasBeCreated = DateTime.Now,
WasBeUpdated = DateTime.Now,
Address = new List<PersoneAddress>
{
new PersoneAddress
{
Country = countys[getIndex(countys.Length - 1)],
Subject = subject[getIndex(subject.Length - 1)],
Area = area[getIndex(area.Length - 1)],
City = citys[getIndex(citys.Length - 1)],
Street = streets[getIndex(streets.Length - 1)],
Flat = (getIndex(120) + 1).ToString(),
HomeNumber = (getIndex(20) + 1).ToString()
}
},
Documents = new List<Document>
{
new Document
{
Document_DocumentTypeID = getIndex(1) + 1,
IssuedBy = issuedBy[getIndex(issuedBy.Length - 1)],
WhenIssued = getIssuedWhen(),
Serial = (getIndex(2000) + 1).ToString(),
Number = (getIndex(6000) + 1).ToString()
}
},
Phones = new List<Phone>
{
new Phone
{
PhoneNumber = (getIndex(10000) + 10000).ToString()
}
},
DateBirthday = getDateBerthday(),
FirstName = first_names[getIndex(first_names.Length - 1)],
SecondName = second_names[getIndex(second_names.Length - 1)],
MiddleName = middle_names[getIndex(middle_names.Length - 1)],
IsEmploeyr = isEmployer,
Position_PositionID = isEmployer ? getIndex(3) + 1 : 0,
Image = imageBytes,
PlaceOfBirth = countys[getIndex(countys.Length - 1)]
+ "; " + subject[getIndex(subject.Length - 1)]
+ "; " + area[getIndex(area.Length - 1)]
+ "; " + citys[getIndex(citys.Length - 1)]
};
personeRepository.AddPersone(persone1);
}
}
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/ComponentPresentators/IAdminViolationTablePresentator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces.ComponentPresentators
{
public interface IAdminViolationTablePresentator: IComponentPresentator
{
void Update();
}
}
<file_sep>/AppPresentators/Presentators/EditPassPresentator.cs
using AppData.Entities;
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using System.Windows.Forms;
using AppPresentators.Views;
using AppPresentators.Components;
using AppData.Contexts;
namespace AppPresentators.Presentators
{
public interface IEditPassPresentator: IComponentPresentator
{
Pass Pass { get; set; }
}
public class EditPassPresentator : IEditPassPresentator
{
private IMainView _parent;
private IApplicationFactory _appFactory;
private IEditPassControl _control;
public EditPassPresentator(IMainView main, IApplicationFactory appFactory)
{
_parent = main;
_appFactory = appFactory;
_control = _appFactory.GetComponent<IEditPassControl>();
_control.Save += Save;
}
private void Save()
{
if (!ValidateData()) return;
using(var db = new PassedContext())
{
var pass = db.Passes.FirstOrDefault(p => p.PassID == _control.Pass.PassID);
if(pass == null)
{
db.Passes.Add(_control.Pass);
}else
{
pass.DocumentType = _control.Pass.DocumentType;
pass.FirstName = _control.Pass.FirstName;
pass.MiddleName = _control.Pass.MiddleName;
pass.Number = _control.Pass.Number;
pass.PassClosed = _control.Pass.PassClosed;
pass.PassGiven = _control.Pass.PassGiven;
pass.SecondName = _control.Pass.SecondName;
pass.Serial = _control.Pass.Serial;
pass.WhenIssued = _control.Pass.WhenIssued;
pass.WhoIssued = _control.Pass.WhoIssued;
}
try {
db.SaveChanges();
_control.ShowMessage("Пропуск успешно сохранен.");
if (ShowForResult)
{
if (SendResult != null)
{
SendResult(ResultType, pass);
}
}
} catch (Exception e)
{
_control.ShowError("При сохранение пропуска возникли ошибки. Обратитесь к разработчику.");
}
}
}
private bool ValidateData()
{
if (string.IsNullOrWhiteSpace(_control.Pass.FirstName))
{
_control.ShowMessage("Укажите фамилию");
return false;
}
if (string.IsNullOrWhiteSpace(_control.Pass.SecondName))
{
_control.ShowMessage("Укажите имя");
return false;
}
if (string.IsNullOrWhiteSpace(_control.Pass.MiddleName))
{
_control.ShowMessage("Укажите отчество");
return false;
}
if (string.IsNullOrWhiteSpace(_control.Pass.DocumentType) || ConfigApp.DocumentTypesList.FirstOrDefault(d => d.Name == _control.Pass.DocumentType) == null)
{
_control.ShowMessage("Выберите тип документа");
return false;
}
if (string.IsNullOrWhiteSpace(_control.Pass.Number))
{
_control.ShowMessage("Укажите номер документа");
return false;
}
if (string.IsNullOrWhiteSpace(_control.Pass.Serial))
{
_control.ShowMessage("Укажите серию документа");
return false;
}
if (string.IsNullOrWhiteSpace(_control.Pass.WhoIssued))
{
_control.ShowMessage("Укажите кем был выдан документ");
return false;
}
if(_control.Pass.PassGiven.Year <= 1900)
{
_control.ShowMessage("Неверно указана дата выдачи пропуска");
return false;
}
if(_control.Pass.PassGiven >= _control.Pass.PassClosed)
{
_control.ShowMessage("Дата выдачи пропуска должна быть раньше даты закрытия пропуска");
return false;
}
if(_control.Pass.WhenIssued.Year <= 1900)
{
_control.ShowMessage("Неверно указана дата выдачи документа");
return false;
}
return true;
}
public Pass Pass
{
get
{
return _control.Pass;
}
set
{
_control.Pass = value;
}
}
public ResultTypes ResultType { get; set; }
public bool ShowForResult { get; set; }
public bool ShowFastSearch
{
get
{
return false;
}
}
public bool ShowSearch
{
get
{
return false;
}
}
public List<Control> TopControls
{
get
{
return _control.TopControls;
}
}
public event SendResult SendResult;
public void FastSearch(string message)
{
}
public Control RenderControl()
{
return _control.GetControl();
}
public void SetResult(ResultTypes resultType, object data)
{
}
}
}
<file_sep>/AppGUI/Infrastructure/ComponentsFactory.cs
using AppGUI.Windows;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFPresentators.Factorys;
using WPFPresentators.Services;
using WPFPresentators.Views.Controls;
using WPFPresentators.Views.Windows;
namespace AppGUI.Infrastructure
{
public class ComponentsFactory : IComponentFactory
{
private IUnityContainer _container;
public ComponentsFactory()
{
_container = new UnityContainer();
Init();
}
public T GetControl<T>() where T : IControlView
{
throw new NotImplementedException();
}
public T GetPresentator<T>()
{
throw new NotImplementedException();
}
public T GetService<T>()
{
if (!_container.IsRegistered<T>()) throw new ArgumentException("Тип не найден");
return _container.Resolve<T>();
}
public T GetWindow<T>() where T : IWindowView
{
if (!_container.IsRegistered<T>()) throw new ArgumentException("Тип не найден");
return _container.Resolve<T>();
}
public void Init()
{
#region Windows
_container.RegisterType<IMainView, MainWindow>();
_container.RegisterType<ILoginView, LoginWindow>();
#endregion
#region Services
_container.RegisterType<ILoginService, LoginService>();
#endregion
}
}
}
<file_sep>/AppCore/Repositrys/ManagersRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys
{
public class ManagersRepository : IManagersRepository
{
public IQueryable<Manager> Managers
{
get
{
var db = new LeoBaseContext();
return db.Managers;
}
}
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/ComponentPresentators/IAddOrUpdateViolation.cs
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces.ComponentPresentators
{
public interface IAddOrUpdateViolation:IComponentPresentator
{
ViolationViewModel Violation { get; set; }
void SaveViolation(ViolationViewModel violation);
}
}
<file_sep>/AppCore/Repositrys/Violations/Protocols/RulingForViolationRepository.cs
using AppData.Abstract.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys.Violations.Protocols
{
public class RulingForViolationRepository : IRulingForViolationRepository
{
public IQueryable<RulingForViolation> RulingsForViolation
{
get
{
var db = new LeoBaseContext();
return db.RulingsForViolation;
}
}
}
}
<file_sep>/AppPresentators/VModels/Persons/PersonsOrderModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Persons
{
public class PersonsOrderModel
{
public OrderType OrderType { get; set; }
public PersonsOrderProperties OrderProperties { get; set; }
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/Component/IViolationPagePresentator.cs
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces.Component
{
public interface IViolationPagePresentator:IComponenPresentator
{
List<VViolation> GetViolations();
List<VViolation> GetViolations(Func<VViolation, bool> func);
List<VViolation> GetPage(int page, int pageLimit = 30);
bool SaveViolation(VViolation violation);
bool RemoveViolation(VViolation violation);
bool RemoceViolation(int id);
event Action ShowMap;
event Action AddViolator;
event Action AddEmployer;
event Action ShowViolationDetails;
event Action MakeOtchet;
}
}
<file_sep>/LeoBase/Components/CustomControls/CustomTablePage.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LeoBase.Components.CustomControls.Interfaces;
using System.Threading;
namespace LeoBase.Components.CustomControls
{
public partial class CustomTablePage : UserControl
{
private OpenSearchPanelButton openSearchPanelButton;
private ISearchPanel _searchPanel;
private System.Windows.Forms.Timer _timer;
private BackgroundWorker _animatorSP;
private bool _animateOpen;
public bool VisibleLoadPanel
{
get
{
return loadPanel.Visible;
}
set
{
loadPanel.Visible = value;
}
}
public string Title
{
get
{
return lbTitle.Text;
}
set
{
lbTitle.Text = value;
}
}
public CustomTablePage()
{
InitializeComponent();
this.DoubleBuffered = true;
this.Dock = DockStyle.Fill;
this.Margin = new Padding(0, 0, 0, 0);
openSearchPanelButton = new OpenSearchPanelButton();
mainTableContainer.Controls.Add(openSearchPanelButton, 0, 1);
SearchPanelContainer.Visible = false;
openSearchPanelButton.OnClickButton += () =>
{
//_animateOpen = true;
SearchPanelContainer.Visible = true;
//foreach (var control in SearchPanelContainer.Controls)
//{
// ((Control)control).Visible = false;
//}
//SearchPanelContainer.BackgroundImage = _saveState;
openSearchPanelButton.Visible = false;
//_animationStarted = true;
//_animatorSP.RunWorkerAsync();
//_timer.Start();
};
SearchPanelContainer.BackgroundImageLayout = ImageLayout.None;
_timer = new System.Windows.Forms.Timer();
_timer.Tick += AnimatePanel;
_timer.Interval = 1;
_animatorSP = new BackgroundWorker();
_animatorSP.WorkerReportsProgress = true;
_animatorSP.ProgressChanged += ProgressAnimationChange;
_animatorSP.DoWork += TimerTick;
_animatorSP.RunWorkerCompleted += AnimationComplete;
_animatorSP.WorkerSupportsCancellation = true;
}
private static bool _animationStarted = false;
private void AnimationComplete(object sender, RunWorkerCompletedEventArgs e)
{
}
private void TimerTick(object sender, DoWorkEventArgs e)
{
while (_animationStarted)
{
_animatorSP.ReportProgress(0);
Thread.Sleep(42);
}
}
private void ProgressAnimationChange(object sender, ProgressChangedEventArgs e)
{
if (_animateOpen)
{
int dw = 15;// (450 - SearchPanelContainer.Width) / 20;
if (dw < 5) dw = 5;
if (SearchPanelContainer.Width + dw >= 450)
{
SearchPanelContainer.Width = 450;
SearchPanelContainer.BackgroundImage = null;
foreach (var control in SearchPanelContainer.Controls)
{
((Control)control).Visible = true;
}
_searchPanel.Control.Refresh();
_searchPanel.Control.Update();
_animationStarted = false;
_animatorSP.CancelAsync();
//_timer.Stop();
}
else
{
SearchPanelContainer.Width += dw;
}
}
else
{
int dw = -15;// (SearchPanelContainer.Width) / 20;
if (dw > -5) dw = -5;
if (SearchPanelContainer.Width + dw <= 0)
{
SearchPanelContainer.Width = 0;
openSearchPanelButton.Visible = true;
_animationStarted = false;
_animatorSP.CancelAsync();
//_timer.Stop();
}
else
{
SearchPanelContainer.Width += dw;
}
}
}
private void AnimatePanel(object sender, EventArgs e)
{
// width 450px
if (_animateOpen)
{
int dw = (450 - SearchPanelContainer.Width) / 5;
if(SearchPanelContainer.Width + dw >= 450)
{
SearchPanelContainer.Width = 450;
SearchPanelContainer.BackgroundImage = null;
foreach (var control in SearchPanelContainer.Controls)
{
((Control)control).Visible = true;
}
_searchPanel.Control.Refresh();
_searchPanel.Control.Update();
_timer.Stop();
}else
{
SearchPanelContainer.Width += dw;
}
}else
{
int dw = (SearchPanelContainer.Width - 450)/ 5;
if(SearchPanelContainer.Width + dw <= 0)
{
SearchPanelContainer.Width = 0;
openSearchPanelButton.Visible = true;
_timer.Stop();
}else
{
SearchPanelContainer.Width += dw;
}
}
}
private Bitmap _saveState;
public void AddSearchPanel(ISearchPanel searchPanel)
{
_searchPanel = searchPanel;
SearchPanelContainer.Width = 450;
SearchPanelContainer.Controls.Add(searchPanel.Control);
searchPanel.OnHideClick += HideSearchPanel;
//searchPanel.Control.Refresh();
//searchPanel.Control.Update();
//SearchPanelContainer.Refresh();
//SearchPanelContainer.Update();
//_saveState = new Bitmap(SearchPanelContainer.Width, SearchPanelContainer.Height);
//SearchPanelContainer.DrawToBitmap(_saveState, new Rectangle(0, 0, SearchPanelContainer.Width, SearchPanelContainer.Height));
//SearchPanelContainer.Visible = true;
//SearchPanelContainer.Width = 0;
}
public void HideSearchPanel()
{
SearchPanelContainer.Visible = false;
openSearchPanelButton.Visible = true;
//_animateOpen = false;
//foreach(var control in SearchPanelContainer.Controls)
//{
// ((Control)control).Visible = false;
//}
//SearchPanelContainer.BackgroundImage = _saveState;
//SearchPanelContainer.Controls[0].Visible = false;
//_animationStarted = true;
//_animatorSP.RunWorkerAsync();
//_timer.Start();
//SearchPanelContainer.Visible = false;
//SearchPanelContainer.Visible = true;
//openSearchPanelButton.Visible = false;
}
public void SetContent(Control control)
{
control.Dock = DockStyle.Fill;
mainTableContainer.Controls.Add(control, 0, 2);
}
}
}
<file_sep>/AppPresentators/VModels/Protocols/ProtocolAboutWithdrawViewModel.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Protocols
{
/// <summary>
/// Протокол об изъятии
/// </summary>
public class ProtocolAboutWithdrawViewModel:ProtocolViewModel
{
public int ProtocolAboutWithdrawID { get; set; }
public PersoneViewModel Violator { get; set; }
/// <summary>
/// Изъятое оружие
/// </summary>
public string WithdrawWeapons { get; set; }
/// <summary>
/// Изъятые боеприпасы
/// </summary>
public string WithdrawAmmunitions { get; set; }
/// <summary>
/// Изъятые орудия охоты и рыболовства
/// </summary>
public string WithdrawGunsHuntingAndFishing { get; set; }
/// <summary>
/// Изъятая продукция природопользования
/// </summary>
public string WithdrawNatureManagementProducts { get; set; }
/// <summary>
/// Изъятые документы
/// </summary>
public string WithdrawDocuments { get; set; }
/// <summary>
/// Методы фиксации правонарушения
/// </summary>
public string FixingMethods { get; set; }
}
}
<file_sep>/AppPresentators/VModels/Protocols/RulingForViolationViewModel.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Protocols
{
/// <summary>
/// Постановление по делу об административном правонарушение
/// </summary>
public class RulingForViolationViewModel:ProtocolViewModel
{
public int RulingForViolationID { get; set; }
public PersoneViewModel Violator { get; set; }
public OrganisationViewModel Organisation { get; set; }
/// <summary>
/// Номер постановления
/// </summary>
public int Number { get; set; }
/// <summary>
/// Когда установил
/// </summary>
public DateTime FixingDate { get; set; }
/// <summary>
/// Что установил
/// </summary>
public string FixingInfo { get; set; }
/// <summary>
/// Статья КОАП
/// </summary>
public string KOAP { get; set; }
/// <summary>
/// Штраф
/// </summary>
public decimal Fine { get; set; }
/// <summary>
/// Ущерб
/// </summary>
public decimal Damage { get; set; }
/// <summary>
/// Добытая продукция
/// </summary>
public string Products { get; set; }
/// <summary>
/// Стоимость добытой продукции
/// </summary>
public decimal ProductsPrice { get; set; }
/// <summary>
/// Решить вопрос об изъятых вещах
/// </summary>
public string AboutArrest { get; set; }
/// <summary>
/// Банковские реквизиты
/// </summary>
public string BankDetails { get; set; }
}
}
<file_sep>/LeoBase/Components/MainMenu/MainMenuItem.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components.MainMenu;
using AppPresentators.VModels.MainMenu;
namespace LeoBase.Components.MainMenu
{
public partial class MainMenuItem : UserControl, IMainMenuItem
{
public event ItemClicked ItemClicked;
private bool _isActive = false;
public bool IsActive { get
{
return _isActive;
} set
{
_isActive = value;
if (_isActive)
{
this.BackColor = Color.FromArgb(69, 57, 33);
lbTitle.ForeColor = Color.FromArgb(201, 210, 145);
}else
{
this.BackColor = Color.FromArgb(102, 83, 53);
lbTitle.ForeColor = Color.FromArgb(208, 186, 149);
}
}
}
public MainMenuItem(string title, MenuCommand command):this(title, command, new byte[0])
{
}
public MainMenuItem(string title, MenuCommand command, byte[] icon)
{
InitializeComponent();
MouseMove += MainMenuItem_MouseMove;
MouseDown += MainMenuItem_MouseDown;
this.Click += (s, e) => _ItemClicked(command);
lbTitle.Click += (s, e) => _ItemClicked(command);
this.MouseMove += (s, e) => Hover();
this.MouseLeave += (s, e) => Leave();
lbTitle.MouseMove += (s, e) => Hover();
lbTitle.MouseLeave += (s, e) => Leave();
Title = title;
MenuCommand = command;
Icon = icon;
}
private void Leave()
{
if (!_isActive) {
this.BackColor = Color.FromArgb(102, 83, 53);
lbTitle.ForeColor = Color.FromArgb(208, 186, 149);
}
}
private void Hover()
{
this.BackColor = Color.FromArgb(69, 57, 33);
lbTitle.ForeColor = Color.FromArgb(201, 210, 145);
}
private void _ItemClicked(MenuCommand command)
{
ItemClicked(command);
}
private void MainMenuItem_MouseDown(object sender, MouseEventArgs e)
{
}
private void MainMenuItem_MouseMove(object sender, MouseEventArgs e)
{
}
public byte[] Icon
{
get
{
return new byte[0];
}
set
{
}
}
public List<Control> TopControls
{
get
{
return new List<Control>();
}
set
{
}
}
public MenuCommand MenuCommand { get; set; }
public string Title
{
get
{
return lbTitle.Text;
}
set
{
lbTitle.Text = value;
}
}
public bool ShowForResult
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public Control GetControl()
{
return this;
}
public void Resize(int width, int height)
{
this.Width = width;
this.Height = height;
}
}
}
<file_sep>/AppCore/Repositrys/AdminViolationsRepository.cs
using AppData.Contexts;
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Repositrys
{
public interface IAdminViolationRepository
{
AdminViolation SaveViolation(AdminViolation violation);
AdminViolation GetViolation(int violationID);
bool RemoveViolation(AdminViolation violation);
bool RemoveViolation(int violationID);
IQueryable<AdminViolation> Violations(LeoBaseContext context);
List<AdminViolation> Violations();
}
public class AdminViolationsRepository : IAdminViolationRepository
{
public AdminViolation GetViolation(int violationID)
{
using(var db = new LeoBaseContext())
{
var violations = db.AdminViolations.Include("Employer")
.Include("ViolatorOrganisation")
.Include("ViolatorPersone")
.Include("ViolatorDocument")
.Include("Images")
.Where(v => v.ViolationID == violationID).ToList();
return violations.Count != 0 ? violations[0] : null;
}
}
public bool RemoveViolation(int violationID)
{
using(var db = new LeoBaseContext())
{
var deletedViolation = db.AdminViolations.FirstOrDefault(v => v.ViolationID == violationID);
if (deletedViolation == null) return false;
var violationImages = db.ViolationImages.Where(i => i.AdminViolation.ViolationID == violationID);
if(violationImages != null)
db.ViolationImages.RemoveRange(violationImages);
db.AdminViolations.Remove(deletedViolation);
db.SaveChanges();
return true;
}
}
public bool RemoveViolation(AdminViolation violation)
{
return RemoveViolation(violation.ViolationID);
}
public AdminViolation SaveViolation(AdminViolation violation)
{
if (violation == null) throw new ArgumentNullException();
using (var db = new LeoBaseContext()) {
using(var transaction = db.Database.BeginTransaction()) {
if (violation.Employer != null && violation.Employer.UserID > 0)
{
violation.Employer = db.Persones.FirstOrDefault(p => p.UserID == violation.Employer.UserID);
}
if (violation.ViolatorPersone != null && violation.ViolatorPersone.UserID > 0)
{
violation.ViolatorPersone = db.Persones.FirstOrDefault(p => p.UserID == violation.ViolatorPersone.UserID);
}
if (violation.ViolatorDocument != null && violation.ViolatorDocument.DocumentID > 0)
{
violation.ViolatorDocument = db.Documents.FirstOrDefault(d => d.DocumentID == violation.ViolatorDocument.DocumentID);
}
if (violation.ViolatorOrganisation != null && violation.ViolatorOrganisation.OrganisationID > 0)
{
violation.ViolatorOrganisation = db.Organisations.FirstOrDefault(o => o.OrganisationID == violation.ViolatorOrganisation.OrganisationID);
}
if (violation.ViolationID <= 0)
{
violation.DateSave = DateTime.Now;
violation.DateUpdate = DateTime.Now;
db.AdminViolations.Add(violation);
}
else
{
var findedViolation = db.AdminViolations.FirstOrDefault(v => v.ViolationID == violation.ViolationID);
if (findedViolation == null) return null;
findedViolation.Employer = violation.Employer;
findedViolation.ViolatorDocument = violation.ViolatorDocument;
findedViolation.ViolatorOrganisation = violation.ViolatorOrganisation;
findedViolation.ViolatorPersone = violation.ViolatorPersone;
findedViolation.Consideration = violation.Consideration;
findedViolation.CreatedProtocolE = violation.CreatedProtocolE;
findedViolation.CreatedProtocolN = violation.CreatedProtocolN;
findedViolation.DateAgenda2025 = violation.DateAgenda2025;
findedViolation.DateCreatedProtocol = violation.DateCreatedProtocol;
findedViolation.DateNotice = violation.DateNotice;
findedViolation.DatePaymant = violation.DatePaymant;
findedViolation.DateReceiving = violation.DateReceiving;
findedViolation.DateSave = violation.DateSave;
findedViolation.DateSent = violation.DateSent;
findedViolation.DateSentBailiff = violation.DateSentBailiff;
findedViolation.DateUpdate = DateTime.Now;
findedViolation.DateViolation = violation.DateViolation;
findedViolation.FindedGunsHuntingAndFishing = violation.FindedGunsHuntingAndFishing;
findedViolation.FindedNatureManagementProducts = violation.FindedNatureManagementProducts;
findedViolation.FindedWeapons = violation.FindedWeapons;
findedViolation.GotPersonaly = violation.GotPersonaly;
findedViolation.KOAP = violation.KOAP;
findedViolation.NumberNotice = violation.NumberNotice;
findedViolation.NumberSent = violation.NumberSent;
findedViolation.NumberSentBailigg = violation.NumberSentBailigg;
findedViolation.PlaceCreatedProtocol = violation.PlaceCreatedProtocol;
findedViolation.PlaceViolation = violation.PlaceViolation;
findedViolation.RulingNumber = violation.RulingNumber;
findedViolation.SumRecovery = violation.SumRecovery;
findedViolation.SumViolation = violation.SumViolation;
findedViolation.Violation = violation.Violation;
findedViolation.ViolationDescription = violation.ViolationDescription;
findedViolation.ViolationE = violation.ViolationE;
findedViolation.ViolationN = violation.ViolationN;
findedViolation.WasAgenda2025 = violation.WasAgenda2025;
findedViolation.WasNotice = violation.WasNotice;
findedViolation.WasPaymant = violation.WasPaymant;
findedViolation.WasReceiving = violation.WasReceiving;
findedViolation.WasSent = violation.WasSent;
findedViolation.WasSentBailiff = violation.WasSentBailiff;
findedViolation.WitnessFIO_1 = violation.WitnessFIO_1;
findedViolation.WitnessFIO_2 = violation.WitnessFIO_2;
findedViolation.WitnessLive_1 = violation.WitnessLive_1;
findedViolation.WitnessLive_2 = violation.WitnessLive_2;
if (violation.Images != null) {
db.ViolationImages.RemoveRange(db.ViolationImages.Where(i => i.AdminViolation.ViolationID == violation.ViolationID));
foreach (var image in violation.Images)
{
image.AdminViolation = findedViolation;
db.ViolationImages.Add(image);
}
}
}
try
{
db.SaveChanges();
transaction.Commit();
}catch(Exception e)
{
transaction.Rollback();
return null;
}
}
}
return violation;
}
public List<AdminViolation> Violations()
{
using (var db = new LeoBaseContext()) return db.AdminViolations.ToList();
}
public IQueryable<AdminViolation> Violations(LeoBaseContext context = null)
{
if (context != null) return context.AdminViolations;
using (var db = new LeoBaseContext()) return db.AdminViolations;
}
}
}
<file_sep>/AppPresentators/Presentators/ViolatorTablePresentator.cs
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using AppPresentators.VModels;
using AppPresentators.VModels.Persons;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.Services;
using AppPresentators.Views;
using System.ComponentModel;
using System.Threading;
using AppData.Contexts;
using AppPresentators.Infrastructure.Orders;
namespace AppPresentators.Presentators
{
public class ViolatorTablePresentator : IViolatorTablePresentator, IOrderPage
{
private IApplicationFactory _appFactory;
private IViolatorTableControl _control;
private IPersonesService _service;
private IMainView _mainView;
public event SendResult SendResult;
private BackgroundWorker _pageLoader;
private static PageModel _pageModel;
private static PersonsOrderModel _orderModel;
private static PersonsSearchModel _personeSearchModel;
private static DocumentSearchModel _documentSearchModel;
private static SearchAddressModel _addressSearchModel;
public bool ShowFastSearch { get { return true; } }
public bool ShowSearch { get { return true; } }
private bool _showForResult = false;
public bool ShowForResult
{
get
{
return _showForResult;
}
set
{
_showForResult = value;
_control.ShowForResult = value;
}
}
public ResultTypes ResultType { get; set; }
public List<Control> TopControls
{
get
{
return _control.TopControls;
}
}
public Infrastructure.Orders.OrderType OrderType
{
get
{
return Infrastructure.Orders.OrderType.TABLE;
}
}
private string _orderPath;
public string OrderDirPath
{
get
{
return _orderPath;
}
}
public void SetResult(ResultTypes resultType, object data)
{
switch (resultType)
{
case ResultTypes.ADD_PERSONE:
bool result = (bool)data;
if (result)
{
GetPersones(_control.PageModel, _control.PersoneSearchModel, _control.AddressSearchModel, _control.OrderModel, _control.DocumentSearchModel);
}
break;
}
}
public ViolatorTablePresentator(IMainView main, IApplicationFactory appFactory)
{
_appFactory = appFactory;
_mainView = main;
_service = _appFactory.GetService<IPersonesService>();
_control = _appFactory.GetComponent<IViolatorTableControl>();
_control.UpdateTable += () => GetPersones(_control.PageModel, _control.PersoneSearchModel, _control.AddressSearchModel, _control.OrderModel, _control.DocumentSearchModel);
_control.AddNewEmployer += AddNewEmployer;
_control.EditPersone += UpdatePersone;
_control.DeletePersone += DeletePersone;
_control.ShowPersoneDetails += ShowEmployerDetails;
_control.MakeReport += MakeReport;
_pageLoader = new BackgroundWorker();
_pageLoader.DoWork += PageLoading;
_pageLoader.RunWorkerCompleted += PageLoadingComplete;
_control.SelectedItemForResult += SelectedItemForResult;
}
private void MakeReport()
{
var mainView = _appFactory.GetMainView();
_personeSearchModel = _control.PersoneSearchModel;
_addressSearchModel = _control.AddressSearchModel;
_documentSearchModel = _control.DocumentSearchModel;
_orderModel = _control.OrderModel;
_pageModel = _control.PageModel;
mainView.MakeOrder(this);
}
private void PageLoadingComplete(object sender, RunWorkerCompletedEventArgs e)
{
var answer = (LoadViolatorDataResultModel)e.Result;
_control.Data = answer.Data;
_control.PageModel = answer.PageModel;
_control.Update();
_control.LoadEnd();
}
private void PageLoading(object sender, DoWorkEventArgs e)
{
var request = (LoadViolatorDataRequestModel)e.Argument;
var pageModel = request.PageModel;
var searchModel = request.SearchModel;
var addressSearchModel = request.AddressSearchModel;
var documentSearchModel = request.DocumentSearchModel;
var orderModel = request.OrderModel;
if (pageModel == null)
pageModel = new PageModel
{
ItemsOnPage = 10,
CurentPage = 1
};
if (searchModel == null)
searchModel = new PersonsSearchModel();
if (addressSearchModel == null)
addressSearchModel = new SearchAddressModel();
if (documentSearchModel == null)
documentSearchModel = new DocumentSearchModel();
if (orderModel == null)
orderModel = new PersonsOrderModel();
searchModel.IsEmployer = false;
_service.PageModel = pageModel;
_service.DocumentSearchModel = documentSearchModel;
_service.SearchModel = searchModel;
_service.AddressSearchModel = addressSearchModel;
_service.OrderModel = orderModel;
var result = _service.GetPersons();
var answer = new LoadViolatorDataResultModel();
if (result == null)
answer.Data = new List<ViolatorViewModel>();
else
answer.Data = result.Select(v => (ViolatorViewModel)v).ToList();
answer.PageModel = _service.PageModel;
e.Result = answer;
}
private void SelectedItemForResult(ViolatorViewModel obj)
{
if (ShowForResult)
{
if (SendResult != null) SendResult(ResultType, _service.ConverToEnity(_service.GetPerson(obj.UserID, true)));
}
}
public void ShowEmployerDetails(IPersoneViewModel personeModel)
{
var mainPresentator = _appFactory.GetMainPresentator();
var violatorDetailsPresentator = _appFactory.GetPresentator<IViolatorDetailsPresentator>();
var vv = personeModel as ViolatorViewModel;
if (vv == null) return;
ViolatorDetailsModel violator = new ViolatorDetailsModel
{
ViolatorID = personeModel.UserID,
FIO = personeModel.FirstName + " " + personeModel.SecondName + " " + personeModel.MiddleName,
Addresses = personeModel.Addresses,
Documents = personeModel.Documents,
Phones = personeModel.Phones,
PlaceBerth = personeModel.PlaceOfBirth,
DateBerth = personeModel.DateBirthday,
PlaceWork = vv.PlaceOfWork,
Image = vv.Image,
Violations = new List<AdminViolationRowModel>()
};
using(var db = new LeoBaseContext())
{
var persone = db.Persones.FirstOrDefault(p => p.UserID == personeModel.UserID);
if (persone != null) violator.Image = persone.Image;
var documents = db.Documents.Where(d => d.Persone.UserID == personeModel.UserID);
if(documents != null) {
violator.Documents = new List<PersoneDocumentModelView>();
foreach (var d in documents)
{
violator.Documents.Add(new PersoneDocumentModelView
{
CodeDevision = d.CodeDevision,
DocumentID = d.DocumentID,
DocumentTypeID = d.Document_DocumentTypeID,
DocumentTypeName = ConfigApp.DocumentsType[d.Document_DocumentTypeID],
IssuedBy = d.IssuedBy,
Number = d.Number,
Serial = d.Serial,
WhenIssued = d.WhenIssued
});
}
}
var addresses = db.Addresses.Where(a => a.Persone.UserID == personeModel.UserID);
if(addresses != null)
{
violator.Addresses = new List<PersonAddressModelView>();
foreach(var a in addresses)
{
violator.Addresses.Add(new PersonAddressModelView
{
AddressID = a.AddressID,
Area = a.Area,
City = a.City,
Country = a.Country,
Flat = a.Flat,
HomeNumber = a.HomeNumber,
Note = a.Note,
Street = a.Street,
Subject = a.Subject
});
}
}
var phones = db.Phones.Where(p => p.Persone.UserID == personeModel.UserID);
if(phones != null)
{
violator.Phones = new List<PhoneViewModel>();
foreach(var p in phones)
{
violator.Phones.Add(new PhoneViewModel
{
PhoneID = p.PhoneID,
PhoneNumber = p.PhoneNumber
});
}
}
var violations = db.AdminViolations.Include("Employer").Include("ViolatorPersone").Where(v => v.ViolatorPersone.UserID == vv.UserID);
foreach(var v in violations)
{
var row = new AdminViolationRowModel();
if (v.ViolatorOrganisation != null)
{
row.ViolatorInfo = string.Format("Юридическое лицо: {0}", v.ViolatorOrganisation.Name);
}
else
{
row.ViolatorInfo = string.Format("{0} {1} {2}", v.ViolatorPersone.FirstName, v.ViolatorPersone.SecondName, v.ViolatorPersone.MiddleName);
}
row.EmployerInfo = string.Format("{0} {1} {2}", v.Employer.FirstName, v.Employer.SecondName, v.Employer.MiddleName);
row.Coordinates = string.Format("{0}; {1}", Math.Round(v.ViolationN, 8), Math.Round(v.ViolationE, 8));
row.Consideration = v.Consideration;
row.DatePaymant = v.WasPaymant ? v.DatePaymant.ToShortDateString() : "";
row.DateSentBailiff = v.WasSentBailiff ? v.DateSentBailiff.ToShortDateString() : "";
row.InformationAbout2025 = v.WasAgenda2025 ? v.DateAgenda2025.ToShortDateString() : "";
row.InformationAboutNotice = v.WasNotice ? v.DateNotice.ToShortDateString() : "";
row.InformationAboutSending = v.GotPersonaly ? "Получил лично"
: v.WasSent
? v.DateSent.ToShortDateString()
: "";
row.SumRecovery = v.SumRecovery;
row.SumViolation = v.SumViolation;
row.Violation = v.Violation;
row.ViolationID = v.ViolationID;
violator.Violations.Add(row);
}
}
violatorDetailsPresentator.Violator = violator;
mainPresentator.ShowComponentForResult(this, violatorDetailsPresentator, ResultTypes.UPDATE_PERSONE);
}
public void DeletePersone(IPersoneViewModel personeModel)
{
_service.SimpleRemove(personeModel);
GetPersones(_control.PageModel, _control.PersoneSearchModel, _control.AddressSearchModel, _control.OrderModel, _control.DocumentSearchModel);
}
public void UpdatePersone(IPersoneViewModel personeModel)
{
var mainPresentator = _appFactory.GetMainPresentator();
var saveEmployerPresentator = _appFactory.GetPresentator<ISaveEmployerPresentator>();
saveEmployerPresentator.Persone = personeModel;
mainPresentator.ShowComponentForResult(this, saveEmployerPresentator, ResultTypes.UPDATE_PERSONE);
}
public void AddNewEmployer()
{
var mainPresentator = _appFactory.GetMainPresentator();
var saveEmployerPresentator = _appFactory.GetPresentator<ISaveEmployerPresentator>();
saveEmployerPresentator.Persone = new ViolatorViewModel
{
IsEmploeyr = false,
UserID = -1,
Addresses = new List<PersonAddressModelView>
{
new PersonAddressModelView {
Country = "Российская Федерация",
Subject = "Приморский край",
Area = "Хасанский район"
}
},
Phones = new List<PhoneViewModel>
{
new PhoneViewModel { }
},
Documents = new List<PersoneDocumentModelView>
{
new PersoneDocumentModelView
{
DocumentID = -1,
WhenIssued = new DateTime(1999, 1, 1)
}
}
};
mainPresentator.ShowComponentForResult(this, saveEmployerPresentator, ResultTypes.ADD_PERSONE);
}
public void FastSearch(string query)
{
string[] qs = query.Split(new char[] { ' ' });
PersonsSearchModel searchModel = new PersonsSearchModel();
if (qs.Length >= 1)
{
searchModel.FirstName = qs[0];
searchModel.CompareFirstName = CompareString.CONTAINS;
}
if (qs.Length >= 2)
{
searchModel.SecondName = qs[1];
searchModel.CompareSecondName = CompareString.CONTAINS;
}
if (qs.Length >= 3)
{
searchModel.MiddleName = qs[2];
searchModel.CompareMiddleName = CompareString.CONTAINS;
}
GetPersones(_control.PageModel, searchModel, new SearchAddressModel(), _control.OrderModel, new DocumentSearchModel());
}
public void GetPersones(PageModel pageModel, PersonsSearchModel searchModel, SearchAddressModel addressSearchModel, PersonsOrderModel orderModel, DocumentSearchModel documentSearchModel)
{
if (!_mainView.Enabled || _pageLoader.IsBusy) return;
LoadViolatorDataRequestModel loadRequest = new LoadViolatorDataRequestModel
{
PageModel = pageModel,
SearchModel = searchModel,
AddressSearchModel = addressSearchModel,
OrderModel = orderModel,
DocumentSearchModel = documentSearchModel
};
_control.LoadStart();
_pageLoader.RunWorkerAsync(loadRequest);
}
public Control RenderControl()
{
GetPersones(_control.PageModel, _control.PersoneSearchModel, _control.AddressSearchModel, _control.OrderModel, _control.DocumentSearchModel);
return _control.GetControl();
}
public void BuildOrder(IOrderBuilder orderBuilder, OrderConfigs configs)
{
if (!configs.TableConfig.CurrentPageOnly)
{
_pageModel = new PageModel
{
CurentPage = 1,
ItemsOnPage = 100000
};
}
if (!configs.TableConfig.ConsiderFilter)
{
_personeSearchModel = new PersonsSearchModel
{
IsEmployer = false
};
_documentSearchModel = new DocumentSearchModel();
_addressSearchModel = new SearchAddressModel();
}
_service.PageModel = _pageModel;
_service.DocumentSearchModel = _documentSearchModel;
_service.SearchModel = _personeSearchModel;
_service.AddressSearchModel = _addressSearchModel;
_service.OrderModel = _orderModel;
var result = _service.GetPersons();
string[] headers = new string[]
{
"Фамилия",
"Имя",
"Отчество",
"Дата рождения",
"Место рождения",
"Место работы"
};
orderBuilder.StartTable("violators_table", headers);
foreach(var violator in result)
{
orderBuilder.WriteRow(new string[]
{
violator.FirstName,
violator.SecondName,
violator.MiddleName,
string.Format("{0}.{1}.{2}", violator.DateBirthday.Day, violator.DateBirthday.Month, violator.DateBirthday.Year),
violator.PlaceOfBirth,
((ViolatorViewModel)violator).PlaceOfWork
});
}
orderBuilder.EndTable("violators_table");
_orderPath = orderBuilder.Save();
}
}
public class LoadViolatorDataRequestModel
{
public PageModel PageModel { get; set; }
public PersonsSearchModel SearchModel { get; set; }
public SearchAddressModel AddressSearchModel { get; set; }
public PersonsOrderModel OrderModel { get; set; }
public DocumentSearchModel DocumentSearchModel { get; set; }
}
public class LoadViolatorDataResultModel
{
public List<ViolatorViewModel> Data { get; set; }
public PageModel PageModel { get; set; }
}
}
<file_sep>/AppPresentators/VModels/Map/MapSearchModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Map
{
public class MapSearchModel
{
[DefaultValue(-1)]
public int ViolationID { get; set; }
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public MapRegion MapRegion { get; set; }
}
public class MapRegion
{
[DefaultValue(0)]
public double E { get; set; }
[DefaultValue(0)]
public double W { get; set; }
[DefaultValue(0)]
public double N { get; set; }
[DefaultValue(0)]
public double S { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/FastSearchControl.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls
{
public class FastSearchControl : TextBox
{
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
}
}
}
<file_sep>/AppCore/Abstract/IViolationRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract
{
public interface IViolationRepository
{
IQueryable<Violation> Violations { get; }
bool AddViolation(Violation violation);
bool UpdateViolation(Violation violation);
}
}
<file_sep>/AppPresentators/Services/ViolationService.cs
using AppData.Abstract;
using AppData.Abstract.Protocols;
using AppData.Contexts;
using AppData.Entities;
using AppData.Infrastructure;
using AppPresentators.Factorys;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Services
{
public interface IViolationService
{
ViolationSearchModel SearchModel { get; set; }
ViolationOrderModel OrderModel { get; set; }
PageModel PageModel { get; set; }
List<ViolationViewModel> GetViolations(bool loadProtocols = false);
bool SaveViolation(ViolationViewModel violation);
bool AddProtocolForViolation(ViolationViewModel violation, IProtocol protocol);
}
public class ViolationSearchModel
{
public int ViolaotionID { get; set; }
public DateTime DateFixed { get; set; } = new DateTime(1, 1, 1);
public CompareValue CompareDateFixed { get; set; } = CompareValue.EQUAL;
public DateTime DateSave { get; set; } = new DateTime(1, 1, 1);
public CompareValue CompareDateSave { get; set; } = CompareValue.EQUAL;
public DateTime DateUpdate { get; set; } = new DateTime(1, 1, 1);
public CompareValue CompareDateUpdate { get; set; } = CompareValue.EQUAL;
public int EmplyerID { get; set; }
public int ViolatorID { get; set; }
public string Description { get; set; }
public CompareString CompareDescription { get; set; } = CompareString.EQUAL;
public MSquare SquareCoordinat { get; set; }
}
public enum ViolationOrderProperties
{
WAS_BE_CREATED = 1,
WAS_BE_UPDATED = 2
}
public class ViolationOrderModel
{
public ViolationOrderProperties OrderProperties { get; set; }
public OrderType OrderType { get; set; }
}
public class ViolationService : IViolationService
{
public ViolationSearchModel SearchModel { get; set; }
public ViolationOrderModel OrderModel { get; set; }
public PageModel PageModel { get; set; }
#region Добавление и обновление правонарушений
public ViolationService()
{
}
public bool AddViolation(ViolationViewModel violation)
{
if (violation == null)
throw new ArgumentNullException("Нарушение не определено");
Violation violationSave = new Violation
{
DateSave = DateTime.Now,
DateUpdate = DateTime.Now,
Date = violation.Date,
Description = violation.Description,
E = violation.E,
N = violation.N
};
if (violation.Images != null)
{
violationSave.Images = violation.Images.Select(v => new ViolationImage
{
Image = v
}).ToList();
}
//if (violation.ViolationType != null)
//{
// violationSave.ViolationType = new ViolationType
// {
// Name = violationSave.ViolationType.Name
// };
//}
var repo = RepositoryesFactory.GetInstance().Get<IViolationRepository>();
return repo.AddViolation(violationSave);
}
public bool UpdateViolation(ViolationViewModel violation)
{
if (violation == null)
throw new ArgumentNullException("Нарушение не определено");
Violation violationForUpdate = new Violation
{
Date = violation.Date,
DateUpdate = DateTime.Now,
Description = violation.Description,
E = violation.E,
N = violation.N,
ViolationID = violation.ViolationID
};
if (violation.Images != null)
{
violationForUpdate.Images = violation.Images.Select(v => new ViolationImage
{
Image = v
}).ToList();
}
if (violation.ViolationType != null)
{
violationForUpdate.ViolationType = new ViolationType {
Name = violation.ViolationType
};
}
var repo = RepositoryesFactory.GetInstance().Get<IViolationRepository>();
return repo.UpdateViolation(violationForUpdate);
}
public bool SaveViolation(ViolationViewModel violation)
{
return violation.ViolationID == 0 ? AddViolation(violation) : UpdateViolation(violation);
}
public bool AddProtocolForViolation(ViolationViewModel violation, IProtocol protocol)
{
if (violation == null || protocol == null)
throw new ArgumentNullException("Не все аргументы заданы");
protocol.Protocol.ViolationID = violation.ViolationID;
return ProtocolFactory.SaveProtocol(protocol);
}
#endregion
public List<ViolationViewModel> GetViolations(bool loadProtocols = false)
{
var repo = RepositoryesFactory.GetInstance().Get<IViolationRepository>();
var answer = repo.Violations.SearchByModel(SearchModel, OrderModel, PageModel);
List<ViolationViewModel> result = new List<ViolationViewModel>();
if (answer != null && answer.Count() != 0)
if (loadProtocols)
{
result = answer.Select(a => new ViolationViewModel
{
ViolationID = a.ViolationID,
Date = a.Date,
Description = a.Description,
E = a.E,
N = a.N,
ViolationType = "Административное"//a.ViolationType
}).ToList();
foreach (var violation in result)
{
var protocols = ProtocolFactory.GetViolationProtocols(violation.ViolationID);
if(protocols != null ) {
violation.Protocols = protocols.Select(p =>
new VModels.Protocols.ProtocolViewModel
{
DateCreatedProtocol = p.DateCreatedProtocol,
PlaceCreatedProtocol = p.PlaceCreatedProtocol,
PlaceCreatedProtocolE = p.PlaceCreatedProtocolE,
PlaceCreatedProtocolN = p.PlaceCreatedProtocolN,
ProtocolID = p.ProtocolID,
ProtocolTypeID = p.ProtocolTypeID,
WitnessFIO_1 = p.WitnessFIO_1,
WitnessFIO_2 = p.WitnessFIO_2,
WitnessLive_1 = p.WitnessLive_1,
WitnessLive_2 = p.WitnessLive_2,
ProtocolTypeName = ProtocolFactory.ProtocolTypes[p.ProtocolTypeID]
}).ToList();
}else
{
violation.Protocols = new List<VModels.Protocols.ProtocolViewModel>();
}
}
}
else {
result = answer.Select(a => new ViolationViewModel
{
ViolationID = a.ViolationID,
Date = a.Date,
Description = a.Description,
E = a.E,
N = a.N,
ViolationType = "Административное"//a.ViolationType
}).ToList();
}
return result;
}
}
public static class ViolationTools
{
public static IQueryable<Violation> SearchByModel(this IQueryable<Violation> vt, ViolationSearchModel search, ViolationOrderModel order, PageModel page)
{
if (search == null) throw new ArgumentNullException("Модель поиска должна быть задана");
if (search.ViolaotionID != 0)
return vt.Where(v => v.ViolationID == search.ViolaotionID);
vt = vt.SearchByDate(search.DateFixed, search.CompareDateFixed);
vt = vt.SearchByDate(search.DateSave, search.CompareDateSave);
vt = vt.SearchByDescription(search.Description, search.CompareDescription);
vt = vt.SearchByCoordinats(search.SquareCoordinat);
vt = vt.SearchByEmployer(search.EmplyerID);
return vt;
}
public static IQueryable<Violation> OrderByModel(this IQueryable<Violation> vt, ViolationOrderModel order)
{
return vt;
}
public static IQueryable<Violation> SearchByEmployer(this IQueryable<Violation> vt, int employerId)
{
if (employerId <= 0) return vt;
var pr = RepositoryesFactory.GetInstance().Get<IProtocolRepository>().Protocols;
var violationIds = pr.Where(p => p.EmployerID == employerId).Select(p => p.ViolationID).ToList();//.Distinct();
vt = vt.Where(v => violationIds.Contains(v.ViolationID));
return vt;
}
public static IQueryable<Violation> SearchByCoordinats(this IQueryable<Violation> vt, MSquare square)
{
if (square == null || square.Point1 == null || square.Point2 == null) return vt;
if (square.Point1.X > square.Point2.X)
{
double b = square.Point1.X;
square.Point1.X = square.Point2.X;
square.Point2.X = b;
}
if (square.Point1.Y > square.Point2.Y)
{
double b = square.Point1.Y;
square.Point1.Y = square.Point2.Y;
square.Point2.Y = b;
}
return vt.Where(v => v.E >= square.Point1.X &&
v.N >= square.Point1.Y &&
v.E <= square.Point2.X &&
v.N <= square.Point2.Y);
}
/// <summary>
/// Поиск по описанию
/// </summary>
/// <param name="vt"></param>
/// <param name="description"></param>
/// <param name="compare"></param>
/// <returns></returns>
public static IQueryable<Violation> SearchByDescription(this IQueryable<Violation> vt, string description, CompareString compare)
{
if (description == null || string.IsNullOrEmpty(description.Trim())) return vt;
if (compare == CompareString.CONTAINS)
return vt.Where(v => v.Description.Contains(description));
return vt.Where(v => v.Description.Equals(description));
}
/// <summary>
/// Поиск по дате
/// </summary>
/// <param name="vt"></param>
/// <param name="date"></param>
/// <param name="compare"></param>
/// <returns></returns>
public static IQueryable<Violation> SearchByDate(this IQueryable<Violation> vt, DateTime date, CompareValue compare)
{
if (date == null || date.Year == 1) return vt;
switch (compare)
{
case CompareValue.EQUAL:
return vt.Where(v => v.Date == date);
case CompareValue.LESS:
return vt.Where(v => v.Date <= date);
case CompareValue.MORE:
return vt.Where(v => v.Date >= date);
}
return vt;
}
}
}
<file_sep>/WPFPresentators/Tools/CustomMethods.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFPresentators.Tools
{
public static class CustomMethods
{
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/ComponentPresentators/IComponentPresentator.cs
using AppPresentators.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppPresentators.Presentators.Interfaces.ComponentPresentators
{
public delegate void SendResult(ResultTypes resultType, object data);
public interface IComponentPresentator
{
bool ShowForResult { get; set; }
ResultTypes ResultType { get; set; }
void SetResult(ResultTypes resultType, object data);
event SendResult SendResult;
Control RenderControl();
void FastSearch(string message);
bool ShowFastSearch { get; }
bool ShowSearch { get; }
List<Control> TopControls { get; }
}
}
<file_sep>/AppPresentators/VModels/Protocols/ProtocolsAboutArrestViewModel.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Protocols
{
/// <summary>
/// Протоклы об аресте
/// </summary>
public class ProtocolsAboutArrestViewModel:ProtocolViewModel
{
public int ProtocolAboutArrestID { get; set; }
/// <summary>
/// Нарушитель
/// </summary>
public PersoneViewModel Violator { get; set; }
/// <summary>
/// Сведения о лице, во владение которого находятся веши, на которые наложен арест
/// </summary>
public string AboutViolator { get; set; }
/// <summary>
/// Сведения о транспортном средстве
/// </summary>
public string AboutCar { get; set; }
/// <summary>
/// Сведения о других вещах
/// </summary>
public string AboutOtherThings { get; set; }
/// <summary>
/// Куда были переданы арестованые вещи
/// </summary>
public string ThingsWasTransfer { get; set; }
/// <summary>
/// Методы фиксации правонарушения
/// </summary>
public string FixingMethods { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/HideSearchPanelBtn.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls
{
public class HideSearchPanelBtn:Panel
{
public event Action OnClick;
private Color _mouseHover = Color.FromArgb(255, 95, 85, 61);
private Color _defaultColor = Color.FromArgb(255, 82, 66, 40);
private Color _mouseDown = Color.FromArgb(255, 215, 212, 205);
private Label _btnText;
public HideSearchPanelBtn()
{
_btnText = new Label();
_btnText.Text = "Закрыть расширенный поиск";
_btnText.Font = new System.Drawing.Font("Arial", 14, FontStyle.Bold);
_btnText.Padding = new Padding(3, 5, 3, 5);
this.Cursor = Cursors.Hand;
//_btnText.Dock = DockStyle.Fill;
_btnText.AutoSize = true;
this.Dock = DockStyle.Fill;
this.BackgroundImage = Properties.Resources.arrow_title_search;
this.BackgroundImageLayout = ImageLayout.Center;
this.Margin = new Padding(0);
this.Padding = new Padding(0);
this.MouseDown += OnMouseDown;
_btnText.MouseDown += OnMouseDown;
this.MouseUp += OnMouseUp;
_btnText.MouseUp += OnMouseUp;
this.MouseLeave += OnMouseLeave;
_btnText.MouseLeave += OnMouseLeave;
this.MouseMove += OnMouseMove;
_btnText.MouseMove += OnMouseMove;
this.Controls.Add(_btnText);
this.Click += (s, e) =>
{
if (OnClick != null) OnClick();
};
_btnText.Click += (s, e) =>
{
if (OnClick != null) OnClick();
};
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
_btnText.ForeColor = _mouseHover;
}
private void OnMouseLeave(object sender, EventArgs e)
{
_btnText.ForeColor = _defaultColor;
}
private void OnMouseUp(object sender, MouseEventArgs e)
{
_btnText.ForeColor = _defaultColor;
}
private void OnMouseDown(object sender, MouseEventArgs e)
{
_btnText.ForeColor = _mouseDown;
}
}
}
<file_sep>/LeoMapV3/Map/interfaces/IMapRenderer.cs
using LeoMapV3.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoMapV3.Map.interfaces
{
public interface IMapRenderer
{
event Action<string> OnError;
Image GetImage();
Task<Image> GetImageAsync();
int Width { get; set; }
int Height { get; set; }
List<DPoint> Points { get; set; }
void LookAt(int x, int y);
void LookAt(DPoint point);
bool ZoomPlus(int dx, int dy);
bool ZoomMinus(int dx, int dy);
void MoveCenter(int dx, int dy);
bool WasRender { get; }
MapEventArgs GetMapEventArgs(int x, int y);
DPoint MouseAtPoint(int x, int y);
}
}
<file_sep>/AppPresentators/Presentators/OptionsPresentator.cs
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using System.Windows.Forms;
using AppPresentators.Components;
using AppData.Contexts;
using AppPresentators.Views;
namespace AppPresentators.Presentators
{
public interface IOptionsPresentator: IComponentPresentator
{
}
public class OptionsPresentator : IOptionsPresentator
{
#region Interface Realisation
public ResultTypes ResultType { get; set; }
public bool ShowFastSearch
{
get
{
return false;
}
}
public bool ShowForResult { get; set; }
public bool ShowSearch
{
get
{
return false;
}
}
public List<Control> TopControls
{
get
{
return _control != null ? _control.TopControls : new List<Control>();
}
}
public event SendResult SendResult;
public void FastSearch(string message)
{
}
public Control RenderControl()
{
return _control != null ? _control.GetControl() : null;
}
public void SetResult(ResultTypes resultType, object data)
{
}
#endregion
private IOptionsControl _control;
private IApplicationFactory _appFactory;
private IMainView _main;
public OptionsPresentator(IMainView mainView, IApplicationFactory appFactory)
{
_main = mainView;
_appFactory = appFactory;
_control = _appFactory.GetComponent<IOptionsControl>();
_control.RemoveDocumentType += RemoveDocumentType;
_control.SaveDocumentType += SaveDocumentType;
_control.UpdateCurrentManager += UpdateCurrentManager;
_control.AddManager += AddNewManager;
_control.RemoveManager += RemoveManager;
_control.UpdateManager += UpdateManager;
_control.GetManagers += GetManagers;
if (ConfigApp.CurrentManager.Role.Equals("admin"))
{
_control.DocumentTypes = ConfigApp.DocumentTypesList;
_control.UpdateManagerTable();
}
}
private List<AppData.Entities.Manager> GetManagers()
{
using(var db = new LeoBaseContext())
{
var managers = db.Managers.Where(m => !m.Role.Equals("admin"));
return managers != null ? managers.ToList() : new List<AppData.Entities.Manager>();
}
}
private void UpdateManager(AppData.Entities.Manager obj)
{
using(var db = new LeoBaseContext())
{
var manager = db.Managers.FirstOrDefault(m => m.ManagerID == obj.ManagerID);
if(manager == null)
{
_control.ShowError("Пользователь не найден");
return;
}
manager.Password = <PASSWORD>;
db.SaveChanges();
}
}
private void RemoveManager(AppData.Entities.Manager obj)
{
using(var db = new LeoBaseContext())
{
var manager = db.Managers.FirstOrDefault(m => m.ManagerID == obj.ManagerID);
if(manager == null)
{
_control.ShowError("Пользователь не найден");
return;
}
db.Managers.Remove(manager);
db.SaveChanges();
}
}
private void AddNewManager(AppData.Entities.Manager obj)
{
using(var db = new LeoBaseContext())
{
db.Managers.Add(obj);
db.SaveChanges();
}
}
private void UpdateCurrentManager(string login, string oldPassword, string newPassword)
{
if (!ConfigApp.CurrentManager.Password.Equals(oldPassword))
{
_control.ShowError("Старый пароль указан не верно!");
return;
}
using(var db = new LeoBaseContext())
{
var findedManager = db.Managers.FirstOrDefault(m => m.Login.Equals(login) && m.ManagerID != ConfigApp.CurrentManager.ManagerID);
if(findedManager != null)
{
_control.ShowError("Логин уже используется");
return;
}
var manager = db.Managers.FirstOrDefault(m => m.ManagerID == ConfigApp.CurrentManager.ManagerID);
if(manager == null)
{
_control.ShowError("Пользователь не найден.");
return;
}
manager.Login = login;
manager.Password = <PASSWORD>;
db.SaveChanges();
_control.ShowMessage("Изменения успешно сохранены");
}
}
/// <summary>
/// Сохранение типа документов
/// </summary>
/// <param name="name">Имя типа документов</param>
/// <param name="id">Идентификатор типа документов</param>
private void SaveDocumentType(string name, int id = -1)
{
using(var db = new LeoBaseContext())
{
var docType = db.DocumentsType.FirstOrDefault(d => d.Name.Equals(name));
if (docType != null)
{
_control.ShowError("Тип документов с таким именем уже существует.");
return;
}
if (id == -1)
{
db.DocumentsType.Add(new AppData.Entities.DocumentType
{
Name = name
});
}else
{
var dt = db.DocumentsType.FirstOrDefault(d => d.DocumentTypeID == id);
dt.Name = name;
}
db.SaveChanges();
ConfigApp.DocumentTypesWasUpdated = true;
_control.DocumentTypes = db.DocumentsType.ToList();
_control.ShowMessage("Тип документа успешно сохранен");
}
}
/// <summary>
/// Удаление типа документов
/// </summary>
/// <param name="id"></param>
private void RemoveDocumentType(int id)
{
using(var db = new LeoBaseContext())
{
var documents = db.Documents.Where(d => d.Document_DocumentTypeID == id);
if (documents != null && documents.Count() != 0)
{
_control.ShowError("Удалить тип документов невозможно, имеются связанные с ним записи в базе данных.");
return;
}
var dt = db.DocumentsType.FirstOrDefault(d => d.DocumentTypeID == id);
if(dt != null)
{
try {
db.DocumentsType.Remove(dt);
db.SaveChanges();
_control.ShowMessage("Тип документов успешно удален");
}catch(Exception e)
{
_control.ShowMessage("Тип документов удалить не удалось. Если ошибка будет повторяться, обратитесь к разработчику.");
return;
}
}
ConfigApp.DocumentTypesWasUpdated = true;
_control.DocumentTypes = db.DocumentsType.ToList();
}
}
}
}
<file_sep>/AppPresentators/VModels/Persons/DocumentSearchModel.cs
using AppData.CustomAttributes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Persons
{
public class DocumentSearchModel
{
[DisplayName("Тип документа")]
[ControlType(ControlType.ComboBox, "Value", "Display")]
[DataPropertiesName("DocumentTypes")]
public string DocumentTypeID { get; set; }
private string s = "";
[DisplayName("Серия")]
public string Serial { get; set; }
[DisplayName("Номер")]
public string Number { get; set; }
[DisplayName("Кем выдан")]
public string IssuedBy { get; set; }
[Browsable(false)]
public CompareString CompareIssuedBy { get; set; } = CompareString.CONTAINS;
[ControlType(ControlType.DateTime)]
[DisplayName("Когда выдан")]
[ChildrenProperty("CompareWhenIssued")]
public DateTime WhenIssued { get; set; }
[Browsable(false)]
public CompareValue CompareWhenIssued { get; set; } = CompareValue.NONE;
[DisplayName("Код подразделения")]
public string CodeDevision { get; set; }
[Browsable(false)]
public CompareString CompareCodeDevision { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public bool IsEmptySearchModel
{
get
{
return
(DocumentTypeID == "0" || DocumentTypeID == null)
&& string.IsNullOrEmpty(Serial)
&& string.IsNullOrEmpty(Number)
&& string.IsNullOrEmpty(IssuedBy)
&& string.IsNullOrEmpty(CodeDevision)
&& WhenIssued.Year == 1;
}
}
[Browsable(false)]
public List<ComboBoxDefaultItem> DocumentTypes
{
get
{
var _dTypes = new List<ComboBoxDefaultItem>();
_dTypes.Add(new ComboBoxDefaultItem
{
Display = "Не учитывать",
Value = "0"
});
_dTypes.AddRange(ConfigApp.DocumentsType.Select(d => new ComboBoxDefaultItem { Display = d.Value, Value = d.Key.ToString() }).ToList());
return _dTypes;
}
}
}
}
<file_sep>/AppPresentators/VModels/Persons/SearchAddressModel.cs
using AppData.CustomAttributes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Persons
{
public class SearchAddressModel
{
[DisplayName("Страна")]
public string Country { get; set; }
[DisplayName("Регион")]
public string Subject { get; set; }
[DisplayName("Район")]
public string Area { get; set; }
[DisplayName("Город")]
public string City { get; set; }
[DisplayName("Улица")]
public string Street { get; set; }
[DisplayName("Номер дома")]
public string HomeNumber { get; set; }
[DisplayName("Номер квартиры")]
public string Flat { get; set; }
[DisplayName("Проживает/прописан")]
[ControlType(ControlType.ComboBox, "Value", "Display")]
[DataPropertiesName("NoteData")]
public string Note { get; set; }
[Browsable(false)]
public List<ComboBoxDefaultItem> NoteData
{
get
{
return new List<ComboBoxDefaultItem>
{
new ComboBoxDefaultItem { Display ="Не использовать", Value = "Не использовать" },
new ComboBoxDefaultItem {Display = "Проживает", Value = "Проживает" },
new ComboBoxDefaultItem {Display = "Прописан", Value = "Прописан" },
new ComboBoxDefaultItem {Display = "Проживает и прописан", Value = "Проживает и прописан" }
};
}
}
[Browsable(false)]
public CompareString CompareCountry { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public CompareString CompareSubject { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public CompareString CompareArea { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public CompareString CompareCity { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public CompareString CompareStreet { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public CompareString CompareNote { get; set; } = CompareString.CONTAINS;
[Browsable(false)]
public bool IsEmptyAddress { get
{
return string.IsNullOrEmpty(Country) && string.IsNullOrEmpty(Subject) && string.IsNullOrEmpty(Area)
&& string.IsNullOrEmpty(City) && string.IsNullOrEmpty(Street) && string.IsNullOrEmpty(HomeNumber)
&& string.IsNullOrEmpty(Flat);
}
}
}
}
<file_sep>/AppPresentators/ConfigApp.cs
using AppData.Abstract;
using AppData.Contexts;
using AppData.Entities;
using AppData.Infrastructure;
using AppData.Repositrys;
using AppPresentators.Services;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators
{
public static class ConfigApp
{
public static string DefaultMapPath = "map\\map.lmap";
public static int DefaultMapZoomForViolation = 14;
private static Random rnd = new Random();
public static void InitDefaultData()
{
List<Persone> employers = null;
List<Persone> violators = null;
using (var db = new LeoBaseContext())
{
employers = db.Persones.Where(p => p.IsEmploeyr).ToList();
violators = db.Persones.Include("Documents").Where(p => !p.IsEmploeyr).ToList();
}
var repo = new AdminViolationsRepository();
for (int i = 0; i < 10; i++)
{
try
{
AdminViolation violation = new AdminViolation();
var employer = employers[RndIndex(0, employers.Count - 1)];
var violator = violators[RndIndex(0, violators.Count - 1)];
var document = violator.Documents.First();
violation.Employer = employer;
violation.ViolatorPersone = violator;
violation.ViolatorDocument = document;
violation.Consideration = RndDate();
violation.CreatedProtocolE = RndDouble(130, 2);
violation.CreatedProtocolN = RndDouble(40, 42);
violation.DateAgenda2025 = RndDate();
violation.WasAgenda2025 = RndBool();
violation.DateCreatedProtocol = violation.Consideration.AddDays(-4);
violation.DateNotice = violation.Consideration.AddDays(30);
violation.DatePaymant = violation.Consideration.AddDays(10);
violation.DateReceiving = violation.Consideration.AddDays(15);
violation.DateSave = DateTime.Now;
violation.DateSent = violation.Consideration.AddDays(1);
violation.DateSentBailiff = violation.Consideration.AddDays(90);
violation.DateUpdate = DateTime.Now;
violation.DateViolation = violation.DateCreatedProtocol;
violation.FindedGunsHuntingAndFishing = "Найденные орудия охоты и рыболовства " + i;
violation.FindedNatureManagementProducts = "Найденная продукция природопользования" + i;
violation.FindedWeapons = "Найденные оружия " + i;
violation.GotPersonaly = RndBool();
violation.KOAP = "8.39" + RndIndex(1, 10);
violation.NumberNotice = i.ToString();
violation.NumberSent = i.ToString();
violation.NumberSentBailigg = i.ToString();
violation.PlaceCreatedProtocol = "Место составления протокола " + i;
violation.PlaceViolation = "Место правонарушения " + i;
violation.RulingNumber = i.ToString();
violation.SumViolation = (decimal)RndDouble(1500, 3000);
violation.WasPaymant = RndBool();
violation.SumRecovery = violation.WasPaymant ? violation.SumViolation : 0;
violation.Violation = "8.39" + RndIndex(1, 10);
violation.ViolationDescription = "Находился на территории ООПТ и т.д. " + i;
violation.ViolationE = RndDouble(130, 132);
violation.ViolationN = RndDouble(41, 43);
violation.WasAgenda2025 = RndBool();
violation.WasNotice = RndBool();
violation.WasPaymant = RndBool();
violation.WasReceiving = RndBool();
violation.WasSent = RndBool();
violation.WasSentBailiff = RndBool();
violation.WitnessFIO_1 = "Иванов " + i;
violation.WitnessFIO_2 = "Сидоров " + i;
violation.WitnessLive_1 = "Живет " + i;
violation.WitnessLive_2 = "Живет " + i;
repo.SaveViolation(violation);
}
catch (Exception e)
{
int a = 10;
}
}
}
private static bool RndBool()
{
return RndDouble(0, 1) > 0.5;
}
private static DateTime RndDate()
{
return new DateTime(1990 + RndIndex(0, 20), RndIndex(1, 12), RndIndex(1, 30));
}
private static double RndDouble(double start, double end)
{
return rnd.NextDouble() * end + start;
}
private static int RndIndex(int start, int end)
{
return (int)Math.Round(rnd.NextDouble() * (double)end + start);
}
public static VManager CurrentManager { get; set; }
private static Dictionary<int, string> _docTypes;
public static Dictionary<int, string> DocumentsType {
get
{
if(_docTypes == null) {
_docTypes = new Dictionary<int, string>();
var repoDocTypes = RepositoryesFactory.GetInstance().Get<IDocumentTypeRepository>();
foreach (var dt in repoDocTypes.DocumentTypes)
{
_docTypes.Add(dt.DocumentTypeID, dt.Name);
}
}
return _docTypes;
}
}
private static Dictionary<int, string> _employerPositions;
private static List<EmploeyrPosition> _employerPositionsList;
public static Dictionary<int, string> EmploerPositions
{
get
{
if(_employerPositions == null)
{
_employerPositions = new Dictionary<int, string>();
var repo = RepositoryesFactory.GetInstance().Get<IPersonePositionRepository>();
foreach(var p in repo.Positions)
{
_employerPositions.Add(p.PositionID, p.Name);
}
}
return _employerPositions;
}
}
public static List<EmploeyrPosition> EmployerPositionsList
{
get
{
if(_employerPositionsList == null)
{
using (var db = new LeoBaseContext()) {
_employerPositionsList = db.Positions.ToList();
}
}
return _employerPositionsList;
}
}
private static List<DocumentType> _documentTypesList;
public static bool DocumentTypesWasUpdated = false;
public static List<DocumentType> DocumentTypesList
{
get
{
if(_documentTypesList == null || DocumentTypesWasUpdated)
{
_documentTypesList = new List<DocumentType>();
using (var db = new LeoBaseContext()) {
_documentTypesList = db.DocumentsType.ToList();
}
DocumentTypesWasUpdated = false;
}
return _documentTypesList;
}
}
private static Dictionary<int, string> _protocolTypes;
private static List<ProtocolType> _protocolTypesList;
public static Dictionary<int, string> ProtocolTypes
{
get
{
if(_protocolTypes == null)
{
_protocolTypes = new Dictionary<int, string>();
using(var db = new LeoBaseContext())
{
var types = db.ProtocolTypes;
foreach(var type in types)
{
_protocolTypes.Add(type.ProtocolTypeID, type.Name);
}
}
}
return _protocolTypes;
}
}
public static List<ProtocolType> ProtocolTypesList
{
get
{
if(_protocolTypesList == null)
{
using(var db = new LeoBaseContext())
{
_protocolTypesList = db.ProtocolTypes.ToList();
}
}
return _protocolTypesList;
}
}
public static Dictionary<string, string> ManagerRoleTranslate
{
get
{
return new Dictionary<string, string>
{
{"admin", "Администратор" },
{"user", "Пользователь"},
{"passesManager","Добавляет пропуски" }
};
}
}
}
}
<file_sep>/AppPresentators/Components/IViolationDetailsControl.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public interface IViolationDetailsControl: UIComponent
{
AdminViolation Violation { get; set; }
event Action Report;
event Action<int> ShowViolatorDetails;
event Action<int> ShowEmployerDetails;
event Action EditViolation;
Image GetMap();
}
}
<file_sep>/WPFPresentators/Views/Windows/IMainView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFPresentators.Views.Controls;
namespace WPFPresentators.Views.Windows
{
public interface IMainView:IWindowView
{
#region Actions
event Action Login;
event Action BackPage;
event Action NextPage;
#endregion
#region Methods
void SetCenterPanel(IControlView view);
void SetTopMenu(IControlView view);
void SetMainMenu(IControlView view);
void LoadStart();
void LoadEnd();
#endregion
}
}
<file_sep>/WPFPresentators/Presentators/MainPresentator.cs
using BFData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFPresentators.Factorys;
using WPFPresentators.Services;
using WPFPresentators.Views.Windows;
namespace WPFPresentators.Presentators
{
public class MainPresentator:IPresentator
{
private IComponentFactory _appFactory;
private IMainView _mainView;
public MainPresentator(IComponentFactory appFactory)
{
_appFactory = appFactory;
_mainView = _appFactory.GetWindow<IMainView>();
_mainView.BackPage += BackPage;
_mainView.NextPage += NextPage;
_mainView.Login += Login;
_mainView.Show();
}
private void Login()
{
LoginPresentator loginPresentator = new LoginPresentator(_appFactory.GetWindow<ILoginView>(), _appFactory.GetService<ILoginService>());
loginPresentator.OnLoginComplete += LoginComplete;
loginPresentator.Show();
}
private void LoginComplete(Manager manager)
{
AppConfig.CurrentManager = manager;
}
private void BackPage()
{
}
private void NextPage()
{
}
}
}
<file_sep>/AppPresentators/Presentators/ViolatorDetailsPresentator.cs
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using System.Windows.Forms;
using AppPresentators.Components;
using AppData.Contexts;
using AppPresentators.Services;
using AppPresentators.VModels.Persons;
using AppPresentators.Infrastructure.Orders;
using System.Drawing;
using System.IO;
namespace AppPresentators.Presentators
{
public interface IViolatorDetailsPresentator: IComponentPresentator
{
ViolatorDetailsModel Violator { get; set; }
}
public class ViolatorDetailsPresentator : IViolatorDetailsPresentator, IOrderPage
{
public ResultTypes ResultType { get; set; }
public bool ShowFastSearch
{
get
{
return false;
}
}
public bool ShowForResult { get; set; }
public bool ShowSearch
{
get
{
return false;
}
}
public List<Control> TopControls
{
get
{
return _control.TopControls;
}
}
private static ViolatorDetailsModel _violator;
public ViolatorDetailsModel Violator
{
get
{
return _control.Violator;
}
set
{
_violator = value;
_control.Violator = value;
}
}
public Infrastructure.Orders.OrderType OrderType
{
get
{
return Infrastructure.Orders.OrderType.SINGLE_PAGE;
}
}
private string _orderPath;
public string OrderDirPath
{
get
{
return _orderPath;
}
}
public event SendResult SendResult;
private IViolatorDetailsControl _control;
private IApplicationFactory _appFactory;
public ViolatorDetailsPresentator(IApplicationFactory appFactory)
{
_appFactory = appFactory;
_control = _appFactory.GetComponent<IViolatorDetailsControl>();
_control.ShowDetailsViolation += ShowDetailsViolation;
_control.EditViolator += EditViolator;
_control.MakeReport += MakeReport;
}
private void MakeReport()
{
var mainView = _appFactory.GetMainView();
mainView.MakeOrder(this);
}
private void EditViolator()
{
var service = _appFactory.GetService<IPersonesService>();
var mainPresentator = _appFactory.GetMainPresentator();
var saveViolatorPresentator = _appFactory.GetPresentator<ISaveEmployerPresentator>();
var violator = service.GetPerson(Violator.ViolatorID, true);
saveViolatorPresentator.Persone = violator;
mainPresentator.ShowComponentForResult(this, saveViolatorPresentator, ResultTypes.UPDATE_PERSONE);
}
private void ShowDetailsViolation(int id)
{
var mainPresentator = _appFactory.GetMainPresentator();
var detailsViolatorPresentator = _appFactory.GetPresentator<IViolationDetailsPresentator>();
using (var db = new LeoBaseContext())
{
detailsViolatorPresentator.Violation = db.AdminViolations.Include("Employer")
.Include("ViolatorOrganisation")
.Include("ViolatorPersone")
.Include("ViolatorDocument")
.Include("Images")
.FirstOrDefault(v => v.ViolationID == id);
}
mainPresentator.ShowComponentForResult(this, detailsViolatorPresentator, ResultTypes.UPDATE_VIOLATION);
}
public void FastSearch(string message)
{
}
public Control RenderControl()
{
return _control.GetControl();
}
public void SetResult(ResultTypes resultType, object data)
{
var service = _appFactory.GetService<IPersonesService>();
var personeModel = service.GetPerson(Violator.ViolatorID, true);
var vv = personeModel as ViolatorViewModel;
if (vv == null) return;
ViolatorDetailsModel violator = new ViolatorDetailsModel
{
ViolatorID = personeModel.UserID,
FIO = personeModel.FirstName + " " + personeModel.SecondName + " " + personeModel.MiddleName,
Addresses = personeModel.Addresses,
Documents = personeModel.Documents,
Phones = personeModel.Phones,
PlaceBerth = personeModel.PlaceOfBirth,
DateBerth = personeModel.DateBirthday,
PlaceWork = vv.PlaceOfWork,
Image = vv.Image,
Violations = new List<AdminViolationRowModel>()
};
using (var db = new LeoBaseContext())
{
var persone = db.Persones.FirstOrDefault(p => p.UserID == personeModel.UserID);
if (persone != null) violator.Image = persone.Image;
var documents = db.Documents.Where(d => d.Persone.UserID == personeModel.UserID);
if (documents != null)
{
violator.Documents = new List<PersoneDocumentModelView>();
foreach (var d in documents)
{
violator.Documents.Add(new PersoneDocumentModelView
{
CodeDevision = d.CodeDevision,
DocumentID = d.DocumentID,
DocumentTypeID = d.Document_DocumentTypeID,
DocumentTypeName = ConfigApp.DocumentsType[d.Document_DocumentTypeID],
IssuedBy = d.IssuedBy,
Number = d.Number,
Serial = d.Serial,
WhenIssued = d.WhenIssued
});
}
}
var addresses = db.Addresses.Where(a => a.Persone.UserID == personeModel.UserID);
if (addresses != null)
{
violator.Addresses = new List<PersonAddressModelView>();
foreach (var a in addresses)
{
violator.Addresses.Add(new PersonAddressModelView
{
AddressID = a.AddressID,
Area = a.Area,
City = a.City,
Country = a.Country,
Flat = a.Flat,
HomeNumber = a.HomeNumber,
Note = a.Note,
Street = a.Street,
Subject = a.Subject
});
}
}
var phones = db.Phones.Where(p => p.Persone.UserID == personeModel.UserID);
if (phones != null)
{
violator.Phones = new List<PhoneViewModel>();
foreach (var p in phones)
{
violator.Phones.Add(new PhoneViewModel
{
PhoneID = p.PhoneID,
PhoneNumber = p.PhoneNumber
});
}
}
var violations = db.AdminViolations.Include("Employer").Include("ViolatorPersone").Where(v => v.ViolatorPersone.UserID == vv.UserID);
foreach (var v in violations)
{
var row = new AdminViolationRowModel();
if (v.ViolatorOrganisation != null)
{
row.ViolatorInfo = string.Format("Юридическое лицо: {0}", v.ViolatorOrganisation.Name);
}
else
{
row.ViolatorInfo = string.Format("{0} {1} {2}", v.ViolatorPersone.FirstName, v.ViolatorPersone.SecondName, v.ViolatorPersone.MiddleName);
}
row.EmployerInfo = string.Format("{0} {1} {2}", v.Employer.FirstName, v.Employer.SecondName, v.Employer.MiddleName);
row.Coordinates = string.Format("{0}; {1}", Math.Round(v.ViolationN, 8), Math.Round(v.ViolationE, 8));
row.Consideration = v.Consideration;
row.DatePaymant = v.WasPaymant ? v.DatePaymant.ToShortDateString() : "";
row.DateSentBailiff = v.WasSentBailiff ? v.DateSentBailiff.ToShortDateString() : "";
row.InformationAbout2025 = v.WasAgenda2025 ? v.DateAgenda2025.ToShortDateString() : "";
row.InformationAboutNotice = v.WasNotice ? v.DateNotice.ToShortDateString() : "";
row.InformationAboutSending = v.GotPersonaly ? "Получил лично"
: v.WasSent
? v.DateSent.ToShortDateString()
: "";
row.SumRecovery = v.SumRecovery;
row.SumViolation = v.SumViolation;
row.Violation = v.Violation;
row.ViolationID = v.ViolationID;
violator.Violations.Add(row);
}
}
Violator = violator;
}
public void BuildOrder(IOrderBuilder orderBuilder, OrderConfigs configs)
{
if (configs.SinglePageConfig.DrawImages)
{
using (var ms = new MemoryStream(_violator.Image))
{
var image = Image.FromStream(ms);
orderBuilder.DrawImage(image, Align.CENTER);
}
}
/// TODO: Доделать вывод информации о правонарушителе в отчет
_orderPath = orderBuilder.Save();
}
}
}
<file_sep>/AppCore/Abstract/Protocols/IProtocolAboutViolationOrganisationRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract.Protocols
{
public interface IProtocolAboutViolationOrganisationRepository
{
IQueryable<ProtocolAboutViolationOrganisation> ProtocolAboutViolationOrganisation { get; }
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/OptionsPanel/Dialogs/SetNewPasswordDialog.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls.NewControls.OptionsPanel.Dialogs
{
public partial class SetNewPasswordDialog : Form
{
public string NewPassword { get; set; }
public SetNewPasswordDialog()
{
InitializeComponent();
}
private void btnOk_Click(object sender, EventArgs e)
{
if (!tbPassword.Text.Equals(tbPasswordAgain.Text))
{
ShowError("Введенные вами пароли не совпадают");
return;
}
if (string.IsNullOrWhiteSpace(tbPassword.Text))
{
ShowError("Введите новый пароль");
return;
}
if(tbPassword.Text.Length < 5)
{
ShowError("Пароль должен быть длинее");
return;
}
NewPassword = tbPassword.Text;
DialogResult = DialogResult.OK;
this.Close();
}
private void ShowError(string message)
{
lbError.Text = message;
lbError.Visible = true;
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
this.Close();
}
}
}
<file_sep>/AppPresentators/Services/AdminViolationService.cs
using AppData.Contexts;
using AppData.CustomAttributes;
using AppData.Entities;
using AppData.Repositrys;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Services
{
public class AdminViolationSearchModel
{
[Browsable(false)]
public string FastSearchString { get; set; }
[Browsable(false)]
public int EmployerID { get; set; }
[DisplayName("ФИО сотрудника")]
public string EmployerFIO { get; set; } // 1
[Browsable(false)]
public int ViolatorID { get; set; }
[DisplayName("ФИО нарушителя")]
public string ViolatorFiO { get; set; } // 2
[Browsable(false)]
public int OrganisationID { get; set; }
[DisplayName("Оргнизация")]
public string Organisation { get; set; } // 3
[Browsable(false)]
public MSquare CordsCreatedProtocol { get; set; } // 4
[Browsable(false)]
public MSquare CordsViolation { get; set; } // 6
[DisplayName("Место составления протокола")]
public string PlaceCreatedProtocol { get; set; } // 5
[DisplayName("Место правонарушения")]
public string PlaceViolation { get; set; }
[ChildrenProperty("CompareDateCreatedProtocol")]
[DisplayName("Дата составления протокола")]
[ControlType(ControlType.DateTime)]
public DateTime DateCreatedProtocol { get; set; } // 7
[Browsable(false)]
public CompareValue CompareDateCreatedProtocol { get; set; }
[ChildrenProperty("CompareDateViolation")]
[DisplayName("Дата правонарушения")]
[ControlType(ControlType.DateTime)]
public DateTime DateViolation { get; set; } // 8
[Browsable(false)]
public CompareValue CompareDateViolation { get; set; }
[DisplayName("КОАП")]
public string KOAP { get; set; } // 11
[DisplayName("Найдена незаконная \r\nпродукция природопользования")]
public string FindedNatureManagmentProducts { get; set; } // 12
[DisplayName("Найденное оружие")]
public string FindedWayponts { get; set; } // 13
[DisplayName("Найденные орудия охоты\r\n и рыбной ловли")]
public string FindedGunsHunterAndFishing { get; set; } // 14
[DisplayName("ФИО свидетеля")]
public string WitnesFIO { get; set; } // 15
[DisplayName("Номер постановления")]
public string RulingNumber { get; set; } // 16
[DisplayName("Дата рассмотрения")]
[ChildrenPropertyAttribute("CompareRulingDate")]
[ControlType(ControlType.DateTime)]
public DateTime RulingDate { get; set; } // 17
[Browsable(false)]
public CompareValue CompareRulingDate { get; set; }
[DisplayName("Сумма наложения")]
[ChildrenPropertyAttribute("CompareSumViolation")]
[ControlType(ControlType.Real)]
public decimal SumViolation { get; set; } // 19
[Browsable(false)]
public CompareValue CompareSumViolation { get; set; }
[Browsable(false)]
public string Products { get; set; } // 21
[ControlType(ControlType.ComboBox, "Value", "Display")]
[DisplayName("Оплачен штраф")]
[DataPropertiesName("SearchByPaymantValues")]
public SearchByPaymantEnum WasPaymant { get; set; }
[Browsable(false)]
public List<SearchByPaymantComboModel> SearchByPaymantValues
{
get
{
return new List<SearchByPaymantComboModel>
{
new SearchByPaymantComboModel
{
Display = "Не учитывать",
Value = SearchByPaymantEnum.NONE
},
new SearchByPaymantComboModel
{
Display = "Оплачены",
Value = SearchByPaymantEnum.WAS_PAYMANT
},
new SearchByPaymantComboModel
{
Display = "Не оплачен",
Value = SearchByPaymantEnum.NOT_PAYMENT
}
};
}
}
[ControlType(ControlType.ComboBox, "Value", "Display")]
[DisplayName("Оплачен штраф")]
[DataPropertiesName("SearchWasSentBailiffValues")]
public SearchBySentBailiffEnum WasSentBailiff { get; set; }
[Browsable(false)]
public List<SearchBySentBailiffComboModel> SearchWasSentBailiffValues
{
get
{
return new List<SearchBySentBailiffComboModel>
{
new SearchBySentBailiffComboModel
{
Display = "Не учитывать",
Value = SearchBySentBailiffEnum.NONE
},
new SearchBySentBailiffComboModel
{
Display = "Не отправлен",
Value = SearchBySentBailiffEnum.NOT_SEND
},
new SearchBySentBailiffComboModel
{
Display = "Отправлен",
Value = SearchBySentBailiffEnum.WAS_SEND
}
};
}
}
[ControlType(ControlType.ComboBox, "Value", "Display")]
[DisplayName("Отправлено")]
[DataPropertiesName("SearchByTypeSendingValues")]
public SearchByTypeSendingEnum SearchByTypeSending { get; set; }
[Browsable(false)]
public List<SearchByTypeSendingComboModel> SearchByTypeSendingValues
{
get
{
return new List<SearchByTypeSendingComboModel>
{
new SearchByTypeSendingComboModel
{
Display = "Не учитывать",
Value = SearchByTypeSendingEnum.NONE
},
new SearchByTypeSendingComboModel
{
Display = "Получил лично",
Value = SearchByTypeSendingEnum.GOT_PERSONALY
},
new SearchByTypeSendingComboModel
{
Display = "Отправлено почтой",
Value = SearchByTypeSendingEnum.SENDING_BY_POST
}
};
}
}
}
public class SearchByPaymantComboModel
{
public string Display { get; set; }
public SearchByPaymantEnum Value { get; set; }
}
public enum SearchByPaymantEnum
{
NONE,
WAS_PAYMANT,
NOT_PAYMENT
}
public class SearchBySentBailiffComboModel
{
public string Display { get; set; }
public SearchBySentBailiffEnum Value { get; set; }
}
public enum SearchBySentBailiffEnum
{
NONE,
WAS_SEND,
NOT_SEND
}
public class SearchByTypeSendingComboModel
{
public string Display { get; set; }
public SearchByTypeSendingEnum Value { get; set; }
}
public enum SearchByTypeSendingEnum
{
NONE,
GOT_PERSONALY,
SENDING_BY_POST
}
public class AdminViolationOrderModel {
public OrderType OrderType { get; set; }
public AdminViolationOrderTypes OrderBy { get; set; }
}
public enum AdminViolationOrderTypes
{
/// <summary>
/// Нарушитель
/// </summary>
VIOLATOR = 0,
/// <summary>
/// Сотрудник
/// </summary>
EMPLOYER = 1,
/// <summary>
/// Дата рассмотрения
/// </summary>
DATE_CONSIDERATION = 3,
/// <summary>
/// Нарушение
/// </summary>
VIOLATION = 4,
/// <summary>
/// Сумма наложения
/// </summary>
SUM_VIOLATION = 5,
/// <summary>
/// Сумма взыскания
/// </summary>
SUM_RECOVERY = 6
}
public interface IAdminViolationService {
AdminViolation GetViolation(int id);
List<AdminViolationRowModel> GetTableData(PageModel pageModel = null, AdminViolationOrderModel orderModel = null, AdminViolationSearchModel searchModel = null);
bool RemoveViolation(int id);
bool SaveViolation(AdminViolation violation);
PageModel PageModel { get; set; }
}
public class AdminViolationService : IAdminViolationService
{
private IAdminViolationRepository _repo;
public string ErrorMessage { get; private set; }
public AdminViolationService()
{
_repo = new AdminViolationsRepository();
}
public PageModel PageModel { get; set; }
public List<AdminViolationRowModel> GetTableData(PageModel pageModel = null, AdminViolationOrderModel orderModel = null, AdminViolationSearchModel searchModel = null)
{
using (var context = new LeoBaseContext())
{
var violations = _repo.Violations(context);
if (searchModel != null)
{
// Доработать модель поиска нарушений
// Поиск по ФИО сотрудника
if (!string.IsNullOrEmpty(searchModel.EmployerFIO))
{
string[] splitter = searchModel.EmployerFIO.Split(new[] { ' ' });
if (splitter.Length == 1) {
string buf = splitter[0];
violations = violations.Where(v => v.Employer.FirstName.Contains(buf) || v.Employer.SecondName.Contains(buf) || v.Employer.MiddleName.Contains(buf));
} else if (splitter.Length == 2)
{
string fn = splitter[0];
string sn = splitter[1];
violations = violations.Where(v => v.Employer.FirstName.Equals(fn) && v.Employer.SecondName.Contains(sn));
} else if (splitter.Length == 3)
{
string fn = splitter[0];
string sn = splitter[1];
string mn = splitter[2];
violations = violations.Where(v => v.Employer.FirstName.Equals(fn) && v.Employer.SecondName.Equals(sn) && v.Employer.MiddleName.Contains(mn));
}
}
if (!string.IsNullOrEmpty(searchModel.Organisation)) { } // Поиск по организациям
if (!string.IsNullOrEmpty(searchModel.ViolatorFiO))
{
string[] splitter = searchModel.ViolatorFiO.Split(new[] { ' ' });
if (splitter.Length == 1)
{
string buf = splitter[0];
violations = violations.Where(v => v.ViolatorPersone.FirstName.Contains(buf) || v.ViolatorPersone.SecondName.Contains(buf) || v.ViolatorPersone.MiddleName.Contains(buf));
} else if (splitter.Length == 2)
{
string fn = splitter[0];
string sn = splitter[1];
violations = violations.Where(v => v.ViolatorPersone.FirstName.Equals(fn) && v.ViolatorPersone.SecondName.Contains(sn));
}
else if (splitter.Length == 3)
{
string fn = splitter[0];
string sn = splitter[1];
string mn = splitter[2];
violations = violations.Where(v => v.ViolatorPersone.FirstName.Equals(fn) && v.ViolatorPersone.SecondName.Equals(sn) && v.ViolatorPersone.MiddleName.Contains(mn));
}
}
if (searchModel.CompareDateCreatedProtocol != CompareValue.NONE)
{
if (searchModel.DateCreatedProtocol.Year == 1) searchModel.DateCreatedProtocol = DateTime.Now;
switch (searchModel.CompareDateCreatedProtocol)
{
case CompareValue.LESS:
violations = violations.Where(v => v.DateCreatedProtocol < searchModel.DateCreatedProtocol);
break;
case CompareValue.MORE:
violations = violations.Where(v => v.DateCreatedProtocol > searchModel.DateCreatedProtocol);
break;
case CompareValue.EQUAL:
violations = violations.Where(v => v.DateCreatedProtocol == searchModel.DateCreatedProtocol);
break;
}
}
if (searchModel.CompareRulingDate != CompareValue.NONE)
{
if (searchModel.RulingDate.Year == 1) searchModel.RulingDate = DateTime.Now;
switch (searchModel.CompareRulingDate)
{
case CompareValue.LESS:
violations = violations.Where(v => v.Consideration < searchModel.RulingDate);
break;
case CompareValue.MORE:
violations = violations.Where(v => v.Consideration > searchModel.RulingDate);
break;
case CompareValue.EQUAL:
violations = violations.Where(v => v.Consideration == searchModel.RulingDate);
break;
}
}
if (searchModel.CompareSumViolation != CompareValue.NONE)
{
switch (searchModel.CompareSumViolation)
{
case CompareValue.LESS:
violations = violations.Where(v => v.SumViolation < searchModel.SumViolation);
break;
case CompareValue.MORE:
violations = violations.Where(v => v.SumViolation > searchModel.SumViolation);
break;
case CompareValue.EQUAL:
violations = violations.Where(v => v.SumViolation == searchModel.SumViolation);
break;
}
}
if (searchModel.CordsCreatedProtocol != null) { } // Поиск по координатам составления протокола
if (searchModel.CordsViolation != null) { } // Поиск по координатам правонарушения
if (searchModel.CompareDateViolation != CompareValue.NONE)
{
if (searchModel.DateViolation.Year == 1) searchModel.DateViolation = DateTime.Now;
switch (searchModel.CompareDateViolation)
{
case CompareValue.LESS:
violations = violations.Where(v => v.DateViolation < searchModel.DateViolation);
break;
case CompareValue.MORE:
violations = violations.Where(v => v.DateViolation > searchModel.DateViolation);
break;
case CompareValue.EQUAL:
violations = violations.Where(v => v.DateViolation == searchModel.DateViolation);
break;
}
}
if (!string.IsNullOrWhiteSpace(searchModel.PlaceCreatedProtocol))
{
violations = violations.Where(v => v.PlaceCreatedProtocol.Contains(searchModel.PlaceCreatedProtocol));
}
if (!string.IsNullOrWhiteSpace(searchModel.PlaceViolation))
{
violations = violations.Where(v => v.PlaceViolation.Contains(searchModel.PlaceViolation));
}
if (!string.IsNullOrWhiteSpace(searchModel.KOAP))
{
violations = violations.Where(v => v.KOAP.Contains(searchModel.KOAP));
}
if (!string.IsNullOrWhiteSpace(searchModel.FindedNatureManagmentProducts))
{
violations = violations.Where(v => v.FindedNatureManagementProducts.Contains(searchModel.FindedNatureManagmentProducts));
}
if (!string.IsNullOrWhiteSpace(searchModel.FindedGunsHunterAndFishing))
{
violations = violations.Where(v => v.FindedGunsHuntingAndFishing.Contains(searchModel.FindedGunsHunterAndFishing));
}
if (!string.IsNullOrWhiteSpace(searchModel.FindedWayponts))
{
violations = violations.Where(v => v.FindedWeapons.Contains(searchModel.FindedWayponts));
}
if (!string.IsNullOrWhiteSpace(searchModel.WitnesFIO))
{
violations = violations.Where(v => v.WitnessFIO_1.Contains(searchModel.WitnesFIO) || v.WitnessFIO_2.Contains(searchModel.WitnesFIO));
}
if (!string.IsNullOrWhiteSpace(searchModel.RulingNumber))
{
violations = violations.Where(v => v.RulingNumber.Contains(searchModel.RulingNumber));
}
if(searchModel.WasPaymant != SearchByPaymantEnum.NONE)
{
switch (searchModel.WasPaymant)
{
case SearchByPaymantEnum.NOT_PAYMENT:
violations = violations.Where(v => v.SumRecovery < v.SumViolation);
break;
case SearchByPaymantEnum.WAS_PAYMANT:
violations = violations.Where(v => v.SumViolation == v.SumRecovery);
break;
}
}
if(searchModel.WasSentBailiff != SearchBySentBailiffEnum.NONE)
{
switch (searchModel.WasSentBailiff)
{
case SearchBySentBailiffEnum.NOT_SEND:
violations = violations.Where(v => !v.WasSentBailiff);
break;
case SearchBySentBailiffEnum.WAS_SEND:
violations = violations.Where(v => v.WasSentBailiff);
break;
}
}
if(searchModel.SearchByTypeSending != SearchByTypeSendingEnum.NONE)
{
switch (searchModel.SearchByTypeSending)
{
case SearchByTypeSendingEnum.GOT_PERSONALY:
violations = violations.Where(v => v.GotPersonaly);
break;
case SearchByTypeSendingEnum.SENDING_BY_POST:
violations = violations.Where(v => !v.GotPersonaly);
break;
}
}
}
if (orderModel != null)
{
switch (orderModel.OrderBy)
{
case AdminViolationOrderTypes.DATE_CONSIDERATION:
if (orderModel.OrderType == OrderType.ASC)
violations = violations.OrderBy(v => v.Consideration);
else
violations = violations.OrderByDescending(v => v.Consideration);
break;
case AdminViolationOrderTypes.EMPLOYER:
if (orderModel.OrderType == OrderType.ASC)
violations = violations.OrderBy(v => v.Employer.FirstName + v.Employer.SecondName + v.Employer.MiddleName);
else
violations = violations.OrderByDescending(v => v.Employer.FirstName + v.Employer.SecondName + v.Employer.MiddleName);
break;
case AdminViolationOrderTypes.SUM_RECOVERY:
if (orderModel.OrderType == OrderType.ASC)
violations = violations.OrderBy(v => v.SumRecovery);
else
violations = violations.OrderByDescending(v => v.SumRecovery);
break;
case AdminViolationOrderTypes.SUM_VIOLATION:
if (orderModel.OrderType == OrderType.ASC)
violations = violations.OrderBy(v => v.SumViolation);
else
violations = violations.OrderByDescending(v => v.SumViolation);
break;
case AdminViolationOrderTypes.VIOLATION:
if (orderModel.OrderType == OrderType.ASC)
violations = violations.OrderBy(v => v.Violation);
else
violations = violations.OrderByDescending(v => v.Violation);
break;
case AdminViolationOrderTypes.VIOLATOR:
if (orderModel.OrderType == OrderType.ASC)
violations = violations.OrderBy(v => v.ViolatorPersone.FirstName + v.ViolatorPersone.SecondName + v.ViolatorPersone.MiddleName);
else
violations = violations.OrderByDescending(v => v.ViolatorPersone.FirstName + v.ViolatorPersone.SecondName + v.ViolatorPersone.MiddleName);
break;
}
}
PageModel = pageModel;
PageModel.TotalItems = violations.Count();
violations = violations.Skip(PageModel.ItemsOnPage * (PageModel.CurentPage - 1)).Take(PageModel.ItemsOnPage);
List<AdminViolationRowModel> result = new List<AdminViolationRowModel>();
foreach (var v in violations) {
var row = new AdminViolationRowModel();
if(v.ViolatorOrganisation != null)
{
row.ViolatorInfo = string.Format("Юридическое лицо: {0}",v.ViolatorOrganisation.Name);
}else
{
row.ViolatorInfo = string.Format("{0} {1} {2}", v.ViolatorPersone.FirstName, v.ViolatorPersone.SecondName, v.ViolatorPersone.MiddleName);
}
row.EmployerInfo = string.Format("{0} {1} {2}", v.Employer.FirstName, v.Employer.SecondName, v.Employer.MiddleName);
row.Coordinates = string.Format("{0}; {1}", v.ViolationN, v.ViolationE);
row.Consideration = v.Consideration;
row.DatePaymant = v.WasPaymant ? v.DatePaymant.ToShortDateString() : "";
row.DateSentBailiff = v.WasSentBailiff ? v.DateSentBailiff.ToShortDateString() : "";
row.InformationAbout2025 = v.WasAgenda2025 ? v.DateAgenda2025.ToShortDateString() : "";
row.InformationAboutNotice = v.WasNotice ? v.DateNotice.ToShortDateString() : "";
row.InformationAboutSending = v.GotPersonaly ? "Получил лично"
: v.WasSent
? v.DateSent.ToShortDateString()
: "";
row.SumRecovery = v.SumRecovery;
row.SumViolation = v.SumViolation;
row.Violation = v.Violation;
row.ViolationID = v.ViolationID;
result.Add(row);
}
//PageModel = pageModel;
//PageModel.TotalItems = violations.Count();
return result;
}
}
public AdminViolation GetViolation(int id)
{
return _repo.GetViolation(id);
}
public bool RemoveViolation(int id)
{
return _repo.RemoveViolation(id);
}
public bool SaveViolation(AdminViolation violation)
{
try {
return _repo.SaveViolation(violation) != null;
}catch(Exception e)
{
return false;
}
}
}
}
<file_sep>/AppPresentators/Views/ILoginView.cs
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Views
{
public interface ILoginView:IView
{
string UserName { get; set; }
string Password { get; set; }
event Action Login;
event Action Cancel;
void ShowError(string errorMessage);
event Action CloseAndLogin;
}
}
<file_sep>/AppCore/Entities/AdminViolation.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
public class AdminViolation
{
[Key]
public int ViolationID { get; set; }
public virtual Persone Employer { get; set; }
public virtual Organisation ViolatorOrganisation { get; set; }
public virtual Persone ViolatorPersone { get; set; }
public virtual Document ViolatorDocument { get; set; }
public double CreatedProtocolN { get; set; }
public double CreatedProtocolE { get; set; }
public double ViolationN { get; set; }
public double ViolationE { get; set; }
public DateTime DateCreatedProtocol { get; set; }
public DateTime DateViolation { get; set; }
public string PlaceCreatedProtocol { get; set; }
public string PlaceViolation { get; set; }
/// <summary>
/// Описание правонарушения
/// </summary>
public string ViolationDescription { get; set; }
/// <summary>
/// Статья КОАП за данное нарушение
/// </summary>
public string KOAP { get; set; }
/// <summary>
/// Найденная продукция природопользования
/// </summary>
public string FindedNatureManagementProducts { get; set; }
/// <summary>
/// Найденное оружие
/// </summary>
public string FindedWeapons { get; set; }
/// <summary>
/// Найденые орудия для охоты и рыболовства
/// </summary>
public string FindedGunsHuntingAndFishing { get; set; }
public string WitnessFIO_1 { get; set; }
public string WitnessLive_1 { get; set; }
public string WitnessFIO_2 { get; set; }
public string WitnessLive_2 { get; set; }
public DateTime DateSave { get; set; }
public DateTime DateUpdate { get; set; }
#region Information Obout Ruling
/// <summary>
/// Номер постановления
/// </summary>
public string RulingNumber { get; set; }
/// <summary>
/// Дата рассмотрения
/// </summary>
public DateTime Consideration { get; set; }
/// <summary>
/// Нарушение
/// </summary>
public string Violation { get; set; }
/// <summary>
/// Дата оплаты
/// </summary>
public DateTime DatePaymant { get; set; }
/// <summary>
/// Было-ли оплачено
/// </summary>
public bool WasPaymant { get; set; }
/// <summary>
/// Сумма наложения
/// </summary>
public decimal SumViolation { get; set; }
/// <summary>
/// Сумма взыскания
/// </summary>
public decimal SumRecovery { get; set; }
/// <summary>
/// Дата отправления
/// </summary>
public DateTime DateSent { get; set; }
/// <summary>
/// Было-ли отправлено
/// </summary>
public bool WasSent { get; set; }
/// <summary>
/// Номер отправления
/// </summary>
public string NumberSent { get; set; }
/// <summary>
/// Получил лично
/// </summary>
public bool GotPersonaly { get; set; }
/// <summary>
/// Дата получения
/// </summary>
public DateTime DateReceiving { get; set; }
/// <summary>
/// Было-ли получено
/// </summary>
public bool WasReceiving { get; set; }
/// <summary>
/// Дата отправления судебным приставам
/// </summary>
public DateTime DateSentBailiff { get; set; }
/// <summary>
/// Было-ли отправлено судебным приставам
/// </summary>
public bool WasSentBailiff { get; set; }
/// <summary>
/// Номер отправления судебным приставам
/// </summary>
public string NumberSentBailigg { get; set; }
/// <summary>
/// Дата извещения
/// </summary>
public DateTime DateNotice { get; set; }
/// <summary>
/// Номер извещения
/// </summary>
public string NumberNotice { get; set; }
/// <summary>
/// Было-ли извещение
/// </summary>
public bool WasNotice { get; set; }
/// <summary>
/// Дата повестки по 20.25
/// </summary>
public DateTime DateAgenda2025 { get; set; }
/// <summary>
/// Была-ли повестка по статье 20.25
/// </summary>
public bool WasAgenda2025 { get; set; }
#endregion
/// <summary>
/// Изображения
/// </summary>
public List<ViolationImage> Images { get; set; }
public void Update(AdminViolation violation)
{
}
}
}
<file_sep>/AppPresentators/Presentators/ViolationDetailsPresentator.cs
using AppData.Entities;
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using System.Windows.Forms;
using AppPresentators.Services;
using AppPresentators.Components;
using AppData.Contexts;
using AppPresentators.VModels;
using AppPresentators.VModels.Persons;
using AppPresentators.Infrastructure.Orders;
using System.Drawing;
using System.IO;
namespace AppPresentators.Presentators
{
public interface IViolationDetailsPresentator: IComponentPresentator
{
AdminViolation Violation { get; set; }
}
public class ViolationDetailsPresentator : IViolationDetailsPresentator, IOrderPage
{
public ResultTypes ResultType { get; set; }
private static Image _map;
public bool ShowFastSearch
{
get
{
return false;
}
}
public bool ShowForResult { get; set; }
public bool ShowSearch
{
get
{
return false;
}
}
public List<Control> TopControls
{
get
{
return _view.TopControls;
}
}
private static AdminViolation _violation;
public AdminViolation Violation {
get
{
return _view.Violation;
}
set
{
_violation = value;
_view.Violation = value;
}
}
public Infrastructure.Orders.OrderType OrderType
{
get
{
return Infrastructure.Orders.OrderType.SINGLE_PAGE;
}
}
private string _orderPath;
public string OrderDirPath
{
get
{
return _orderPath;
}
}
public event SendResult SendResult;
private IApplicationFactory _appFactory;
private IViolationDetailsControl _view;
public ViolationDetailsPresentator(IApplicationFactory appFactory)
{
_appFactory = appFactory;
_view = _appFactory.GetComponent<IViolationDetailsControl>();
_view.Report += Report;
_view.ShowViolatorDetails += ShowViolatorDetails;
_view.ShowEmployerDetails += ShowEmployerDetails;
_view.EditViolation += EditViolation;
}
private void EditViolation()
{
var mainPresentator = _appFactory.GetMainPresentator();
var saveViolatorPresentator = _appFactory.GetPresentator<ISaveAdminViolationPresentatar>();
using (var db = new LeoBaseContext())
{
saveViolatorPresentator.Violation = db.AdminViolations.Include("Employer")
.Include("ViolatorOrganisation")
.Include("ViolatorPersone")
.Include("ViolatorDocument")
.Include("Images")
.FirstOrDefault(v => v.ViolationID == Violation.ViolationID);
}
mainPresentator.ShowComponentForResult(this, saveViolatorPresentator, ResultTypes.UPDATE_VIOLATION);
}
private void ShowEmployerDetails(int id)
{
var mainPresentator = _appFactory.GetMainPresentator();
var employerDetailsPresentator = _appFactory.GetPresentator<IEmployerDetailsPresentator>();
var personeServices = _appFactory.GetService<IPersonesService>();
var ee = personeServices.GetPerson(id, true) as EmploeyrViewModel;
EmployerDetailsModel employer = new EmployerDetailsModel
{
EmployerID = ee.UserID,
FIO = ee.FirstName + " " + ee.SecondName + " " + ee.MiddleName,
Addresses = ee.Addresses,
Phones = ee.Phones,
PlaceBerth = ee.PlaceOfBirth,
DateBerth = ee.DateBirthday.ToShortDateString(),
Position = ee.Position,
Image = ee.Image,
Violations = new List<AdminViolationRowModel>()
};
using (var db = new LeoBaseContext())
{
var violations = db.AdminViolations.Include("Employer").Include("ViolatorPersone").Where(v => v.Employer.UserID == id);
foreach (var v in violations)
{
var row = new AdminViolationRowModel();
if (v.ViolatorOrganisation != null)
{
row.ViolatorInfo = string.Format("Юридическое лицо: {0}", v.ViolatorOrganisation.Name);
}
else
{
row.ViolatorInfo = string.Format("{0} {1} {2}", v.ViolatorPersone.FirstName, v.ViolatorPersone.SecondName, v.ViolatorPersone.MiddleName);
}
row.EmployerInfo = string.Format("{0} {1} {2}", v.Employer.FirstName, v.Employer.SecondName, v.Employer.MiddleName);
row.Coordinates = string.Format("{0}; {1}", Math.Round(v.ViolationN, 8), Math.Round(v.ViolationE, 8));
row.Consideration = v.Consideration;
row.DatePaymant = v.WasPaymant ? v.DatePaymant.ToShortDateString() : "";
row.DateSentBailiff = v.WasSentBailiff ? v.DateSentBailiff.ToShortDateString() : "";
row.InformationAbout2025 = v.WasAgenda2025 ? v.DateAgenda2025.ToShortDateString() : "";
row.InformationAboutNotice = v.WasNotice ? v.DateNotice.ToShortDateString() : "";
row.InformationAboutSending = v.GotPersonaly ? "Получил лично"
: v.WasSent
? v.DateSent.ToShortDateString()
: "";
row.SumRecovery = v.SumRecovery;
row.SumViolation = v.SumViolation;
row.Violation = v.Violation;
row.ViolationID = v.ViolationID;
employer.Violations.Add(row);
}
}
employerDetailsPresentator.Employer = employer;
mainPresentator.ShowComponentForResult(this, employerDetailsPresentator, ResultTypes.DETAILS_EMPLOYER);
}
private void ShowViolatorDetails(int id)
{
var mainPresentator = _appFactory.GetMainPresentator();
var violatorDetailsPresentator = _appFactory.GetPresentator<IViolatorDetailsPresentator>();
var personeServices = _appFactory.GetService<IPersonesService>();
var vv = personeServices.GetPerson(id, true) as ViolatorViewModel;
ViolatorDetailsModel violator = new ViolatorDetailsModel
{
ViolatorID = vv.UserID,
FIO = vv.FirstName + " " + vv.SecondName + " " + vv.MiddleName,
Addresses = vv.Addresses,
Documents = vv.Documents,
Phones = vv.Phones,
PlaceBerth = vv.PlaceOfBirth,
DateBerth = vv.DateBirthday,
PlaceWork = vv.PlaceOfWork,
Image = vv.Image,
Violations = new List<AdminViolationRowModel>()
};
using (var db = new LeoBaseContext()) {
var violations = db.AdminViolations.Include("Employer").Include("ViolatorPersone").Where(v => v.ViolatorPersone.UserID == id);
foreach (var v in violations)
{
var row = new AdminViolationRowModel();
if (v.ViolatorOrganisation != null)
{
row.ViolatorInfo = string.Format("Юридическое лицо: {0}", v.ViolatorOrganisation.Name);
}
else
{
row.ViolatorInfo = string.Format("{0} {1} {2}", v.ViolatorPersone.FirstName, v.ViolatorPersone.SecondName, v.ViolatorPersone.MiddleName);
}
row.EmployerInfo = string.Format("{0} {1} {2}", v.Employer.FirstName, v.Employer.SecondName, v.Employer.MiddleName);
row.Coordinates = string.Format("{0}; {1}", Math.Round(v.ViolationN, 8), Math.Round(v.ViolationE, 8));
row.Consideration = v.Consideration;
row.DatePaymant = v.WasPaymant ? v.DatePaymant.ToShortDateString() : "";
row.DateSentBailiff = v.WasSentBailiff ? v.DateSentBailiff.ToShortDateString() : "";
row.InformationAbout2025 = v.WasAgenda2025 ? v.DateAgenda2025.ToShortDateString() : "";
row.InformationAboutNotice = v.WasNotice ? v.DateNotice.ToShortDateString() : "";
row.InformationAboutSending = v.GotPersonaly ? "Получил лично"
: v.WasSent
? v.DateSent.ToShortDateString()
: "";
row.SumRecovery = v.SumRecovery;
row.SumViolation = v.SumViolation;
row.Violation = v.Violation;
row.ViolationID = v.ViolationID;
violator.Violations.Add(row);
}
}
violatorDetailsPresentator.Violator = violator;
mainPresentator.ShowComponentForResult(this, violatorDetailsPresentator, ResultTypes.DETAILS_VIOLATOR);
}
private void Report()
{
var mainView = _appFactory.GetMainView();
_map = _view.GetMap();
mainView.MakeOrder(this);
}
public void FastSearch(string message)
{
}
public Control RenderControl()
{
return _view.GetControl();
}
public void SetResult(ResultTypes resultType, object data)
{
using (var db = new LeoBaseContext())
{
Violation = db.AdminViolations.Include("Employer")
.Include("ViolatorOrganisation")
.Include("ViolatorPersone")
.Include("ViolatorDocument")
.Include("Images")
.FirstOrDefault(v => v.ViolationID == Violation.ViolationID);
}
}
public void BuildOrder(IOrderBuilder orderBuilder, OrderConfigs configs)
{
orderBuilder.StartPharagraph(Align.LEFT);
orderBuilder.WriteText("Отчет по правонарушению ", System.Drawing.Color.Black, TextStyle.BOLD, 24);
orderBuilder.EndPharagraph();
orderBuilder.StartPharagraph(Align.LEFT);
orderBuilder.WriteText(" ", System.Drawing.Color.Black, TextStyle.BOLD, 24);
orderBuilder.EndPharagraph();
orderBuilder.StartPharagraph(Align.LEFT);
orderBuilder.WriteText("Информация по правонарушению", System.Drawing.Color.Black, TextStyle.BOLD, 14);
orderBuilder.EndPharagraph();
WriteOrderInformation(orderBuilder, "Место составления протокола: ", _violation.PlaceCreatedProtocol, System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "Координаты места составления протокола: ", string.Format("N: {0}; E: {1}", _violation.CreatedProtocolN, _violation.CreatedProtocolE), System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "Дата/время составления протокола: ", string.Format("{0}.{1}.{2} {3}:{4}", _violation.DateCreatedProtocol.Day, _violation.DateCreatedProtocol.Month, _violation.DateCreatedProtocol.Year, _violation.DateCreatedProtocol.Hour, _violation.DateCreatedProtocol.Minute), System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "Координаты места правонарушения: ", string.Format("N: {0}; E: {1}", _violation.ViolationN, _violation.ViolationE), System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "Дата/время правонарушения: ", string.Format("{0}.{1}.{2} {3}:{4}", _violation.DateViolation.Day, _violation.DateViolation.Month, _violation.DateViolation.Year, _violation.DateViolation.Hour, _violation.DateViolation.Minute), System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "КОАП: ", _violation.KOAP, System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "Найдена продукция природопользования: ", _violation.FindedNatureManagementProducts, System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "Найдено оружие: ", _violation.FindedWeapons, System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "Найдены орудия охоты и рыболовства: ", _violation.FindedGunsHuntingAndFishing, System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "ФИО свидетеля: ", _violation.WitnessFIO_1, System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "Свидетель проживает: ", _violation.WitnessLive_1, System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "ФИО свидетеля: ", _violation.WitnessFIO_2, System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "Свидетель проживает: ", _violation.WitnessLive_2, System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "Сотрудник, составивший протокол: ", string.Format("{0} ; {1} {2} {3}", ConfigApp.EmploerPositions[_violation.Employer.Position_PositionID], _violation.Employer.FirstName, _violation.Employer.SecondName, _violation.Employer.MiddleName), System.Drawing.Color.Black);
string violatorInformation = string.Format("{0} {1} {2}; ", _violation.ViolatorPersone.FirstName, _violation.ViolatorPersone.SecondName, _violation.ViolatorPersone.MiddleName);
violatorInformation += string.Format("Дата рождения: {0}; ", _violation.ViolatorPersone.DateBirthday.ToShortDateString());
violatorInformation += string.Format("Место работы: {0}; ", _violation.ViolatorPersone.PlaceWork);
violatorInformation += string.Format("Место рождения: {0}; ", _violation.ViolatorPersone.PlaceOfBirth);
violatorInformation += string.Format("Документ: {0} {1} {2} {3} {4}",
ConfigApp.DocumentsType[_violation.ViolatorDocument.Document_DocumentTypeID],
_violation.ViolatorDocument.Serial,
_violation.ViolatorDocument.Number,
_violation.ViolatorDocument.WhenIssued.ToShortDateString(),
_violation.ViolatorDocument.IssuedBy
);
WriteOrderInformation(orderBuilder, "Информация по правонарушителю: ", violatorInformation, System.Drawing.Color.Black);
if (_map != null) orderBuilder.DrawImage(_map, Align.CENTER);
orderBuilder.StartPharagraph(Align.LEFT);
orderBuilder.WriteText(" ", System.Drawing.Color.Black, TextStyle.BOLD, 24);
orderBuilder.EndPharagraph();
orderBuilder.StartPharagraph(Align.LEFT);
orderBuilder.WriteText("Информация по правонарушению", System.Drawing.Color.Black, TextStyle.BOLD, 14);
orderBuilder.EndPharagraph();
WriteOrderInformation(orderBuilder, "Номер постановления: ", _violation.RulingNumber, Color.Black);
WriteOrderInformation(orderBuilder, "Дата/время рассмотрения: ", string.Format("{0}.{1}.{2} {3}:{4}", _violation.Consideration.Day, _violation.Consideration.Month, _violation.Consideration.Year, _violation.Consideration.Hour, _violation.Consideration.Minute), System.Drawing.Color.Black);
WriteOrderInformation(orderBuilder, "Нарушение: ", _violation.Violation, Color.Black);
WriteOrderInformation(orderBuilder, "Сумма наложения: ", _violation.SumViolation.ToString(), Color.Black);
if (_violation.GotPersonaly)
{
WriteOrderInformation(orderBuilder, "Отправлено: ", "Получил лично", Color.Black);
}
else if (Violation.WasSent)
{
WriteOrderInformation(orderBuilder, "Отправлено: ",
string.Format("Отправлено: {0}; Номер отправления: {1}", _violation.DateSent.ToShortDateString(), _violation.NumberSent), Color.Black);
}
else
{
WriteOrderInformation(orderBuilder, "Отправлено: ", "Не отправлено", Color.Black);
}
if (_violation.WasSentBailiff)
{
WriteOrderInformation(orderBuilder, "Отправлено судебным приставам: ",
string.Format("Отправлено: {0}; Номер отправления: {1}", _violation.DateSentBailiff.ToShortDateString(), _violation.NumberSentBailigg), Color.Black);
}
else
{
WriteOrderInformation(orderBuilder, "Отправлено судебным приставам: ", "не отправлено", Color.Black);
}
if (_violation.WasNotice)
{
WriteOrderInformation(orderBuilder, "Извещение: ",
string.Format("Извещение получено: {0}; Номер извещения: {1} ", _violation.DateNotice.ToShortDateString(), _violation.NumberNotice), Color.Black);
}
else
{
WriteOrderInformation(orderBuilder, "Извещение: ", "Извещения не было", Color.Black);
}
if (_violation.WasAgenda2025)
{
WriteOrderInformation(orderBuilder, "Повестка по статье 20.25: ", _violation.DateAgenda2025.ToShortDateString(), Color.Black);;
}
else
{
WriteOrderInformation(orderBuilder, "Повестка по статье 20.25: ", "Повестки по статье 20.25 не было", Color.Black);
}
if (_violation.WasPaymant)
{
if (_violation.SumRecovery >= _violation.SumViolation)
{
WriteOrderInformation(orderBuilder, "Оплата: ", "Оплачено " + _violation.DatePaymant.ToShortDateString(), Color.Green);
}
else
{
WriteOrderInformation(orderBuilder, "Оплата: ", string.Format("Оплачено не полностью ({0} из {1}): {2}", _violation.SumRecovery, _violation.SumViolation, _violation.DatePaymant.ToShortDateString()), Color.Red);
}
}
else
{
WriteOrderInformation(orderBuilder, "Оплата: ", "Не оплачено", Color.Red);
}
orderBuilder.StartPharagraph(Align.LEFT);
orderBuilder.WriteText(" ", System.Drawing.Color.Black, TextStyle.BOLD, 14);
orderBuilder.EndPharagraph();
orderBuilder.StartPharagraph(Align.LEFT);
orderBuilder.WriteText(" ", System.Drawing.Color.Black, TextStyle.BOLD, 14);
orderBuilder.EndPharagraph();
orderBuilder.StartPharagraph(Align.LEFT);
orderBuilder.WriteText("Изображения", System.Drawing.Color.Black, TextStyle.BOLD, 14);
orderBuilder.EndPharagraph();
if (configs.SinglePageConfig.DrawImages)
{
foreach (var img in Violation.Images)
{
using (var ms = new MemoryStream(img.Image))
{
var image = Image.FromStream(ms);
orderBuilder.DrawImage(image, Align.CENTER);
}
}
}
_orderPath = orderBuilder.Save();
}
private Image ImageFromByteArray(byte[] byteArrayIn)
{
using (var ms = new MemoryStream(byteArrayIn))
{
return System.Drawing.Image.FromStream(ms);
}
}
private void WriteOrderInformation(IOrderBuilder builder, string lable, string text, System.Drawing.Color color)
{
builder.StartPharagraph(Align.LEFT);
builder.WriteText(lable, System.Drawing.Color.Black, TextStyle.BOLD);
builder.WriteText(text, color);
builder.EndPharagraph();
}
}
}
<file_sep>/LeoMapV3/Models/DPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoMapV3.Models
{
public class DPoint
{
public double X { get; set; }
public double Y { get; set; }
public double E { get; set; }
public double N { get; set; }
public int Zoom { get; set; } = MapConfig.DefaultZoom;
public string ToolTip { get; set; }
public object DataSource { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/SearchPanels/AllPersonesSearchPanel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels.Persons;
namespace LeoBase.Components.CustomControls.SearchPanels
{
public partial class AllPersonesSearchPanel : UserControl
{
private PersoneSearchPanel _personeSearchPanel;
private DocumentSearchPanel _documentSearchPanel;
private AddressSearchPanel _addressSearchPanel;
public event Action Search;
public SearchAddressModel AddressSearchModel
{
get
{
return _addressSearchPanel.SearchAddressModel;
}
}
public PersonsSearchModel PersonSearchModel
{
get
{
return _personeSearchPanel.SearchModel;
}
}
public DocumentSearchModel DocumentSearchModel
{
get
{
return _documentSearchPanel.DocumentSearchModel;
}
}
public AllPersonesSearchPanel():this(false)
{
}
public AllPersonesSearchPanel(bool isEmployer)
{
InitializeComponent();
_personeSearchPanel = new PersoneSearchPanel();
_personeSearchPanel.ItSearchForEmployer = isEmployer;
_addressSearchPanel = new AddressSearchPanel();
_documentSearchPanel = new DocumentSearchPanel();
_addressSearchPanel.Height = _personeSearchPanel.Height;
_documentSearchPanel.Height = _personeSearchPanel.Height;
_addressSearchPanel.Width = 420;
_documentSearchPanel.Width = 420;
tableLayoutPanel1.Width = 420;
_personeSearchPanel.Width = 420;
tableLayoutPanel1.Controls.Add(_personeSearchPanel, 0, 0);
tableLayoutPanel1.Controls.Add(_addressSearchPanel, 0, 1);
if (!isEmployer)
tableLayoutPanel1.Controls.Add(_documentSearchPanel, 0, 2);
this.Height = tableLayoutPanel1.Height + 90;
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (Search != null)
{
Search();
if (HideSearchPanel != null) HideSearchPanel();
}
}
private void btnClearAll_Click(object sender, EventArgs e)
{
Clear();
if (Search != null)
Search();
}
public void Clear()
{
_personeSearchPanel.Clear();
_addressSearchPanel.Clear();
_documentSearchPanel.Clear();
}
public event Action HideSearchPanel;
private void button1_Click(object sender, EventArgs e)
{
if (HideSearchPanel != null)
HideSearchPanel();
}
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/OptionsPanel/OptionsControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppData.Entities;
using AppPresentators;
using LeoBase.Components.CustomControls.NewControls.OptionsPanel.Dialogs;
namespace LeoBase.Components.CustomControls.NewControls.OptionsPanel
{
public partial class OptionsControl : UserControl, IOptionsControl
{
public event Func<List<Manager>> GetManagers;
public event Action<Manager> AddManager;
public event Action<Manager> UpdateManager;
public event Action<Manager> RemoveManager;
private List<Manager> _managers;
private Manager _selectedManager;
/*
*
{"user", "Пользователь"},
{"passesManager","Добавляет пропуски" }
* */
public OptionsControl()
{
InitializeComponent();
tbManagerLogin.Text = ConfigApp.CurrentManager.Login;
groupDocumentTypes.Visible = ConfigApp.CurrentManager.Role.Equals("admin");
cmbUserRole.Items.Add("Пользователь");
cmbUserRole.Items.Add("Добавляет пропуски");
cmbUserRole.SelectedIndex = 0;
if (ConfigApp.CurrentManager.Role.Equals("admin"))
{
usersGroupBox.Visible = true;
if(GetManagers != null)
{
_managers = GetManagers();
var tableSource = _managers.Select(m => new ManagerTableModel
{
Role = ConfigApp.ManagerRoleTranslate[m.Role],
Login = m.Login
}).ToList();
managersTable.DataSource = new BindingList<ManagerTableModel>(tableSource);
managersTable.Update();
managersTable.Refresh();
managersTable.CellClick += CellClicked;
}
}else
{
usersGroupBox.Visible = false;
}
}
private void CellClicked(object sender, DataGridViewCellEventArgs e)
{
}
private List<DocumentType> _docTypes;
private int _selectedDocumentTypeID = -1;
public List<DocumentType> DocumentTypes
{
get
{
return _docTypes;
}
set
{
_docTypes = value;
if(value != null)
{
UpdateDocumentTypesTable();
}
}
}
private List<EmploeyrPosition> _positions;
public List<EmploeyrPosition> Positions
{
get
{
return _positions;
}
set
{
_positions = value;
if(value != null)
{
UpdateEmployerPositionsTable();
}
}
}
private void UpdateDocumentTypesTable()
{
if (!ConfigApp.CurrentManager.Role.Equals("admin"))
{
groupDocumentTypes.Visible = false;
return;
}
cmbDocumentTypes.ValueMember = "DocumentTypeID";
cmbDocumentTypes.DisplayMember = "Name";
cmbDocumentTypes.DataSource = _docTypes;
}
private void UpdateEmployerPositionsTable()
{
if (!ConfigApp.CurrentManager.Role.Equals("admin"))
{
return;
}
}
private void cmbDocumentTypes_SelectedIndexChanged(object sender, EventArgs e)
{
}
#region Interface Realisation
public bool ShowForResult { get; set; }
public List<Control> TopControls
{
get
{
return new List<Control>();
}
set
{
}
}
public event Action<int> RemoveDocumentType;
public event Action<string, int> SaveDocumentType;
public event Action<string, string, string> UpdateCurrentManager;
public Control GetControl()
{
return this;
}
public void ShowError(string message)
{
MessageBox.Show(message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public void ShowMessage(string message)
{
MessageBox.Show(message, "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.None);
}
void UIComponent.Resize(int width, int height)
{
}
#endregion
private void btnSaveCurrentManager_Click(object sender, EventArgs e)
{
ConfirmPassword confirmDialog = new ConfirmPassword();
string newPassword = <PASSWORD>;
if (string.IsNullOrWhiteSpace(newPassword) || newPassword.Length < 5)
{
ShowError("Пароль должен быть не короче пяти символов.");
return;
}
if (!newPassword.Equals(tbManagerPassword2.Text))
{
ShowError("Пароль и подтверждение пароля не совпадают.");
return;
}
if (confirmDialog.ShowDialog() == DialogResult.OK)
{
if (!confirmDialog.Password.Equals(ConfigApp.CurrentManager.Password))
{
ShowError("Введен неверный пароль!");
return;
}
if(UpdateCurrentManager != null)
{
UpdateCurrentManager(tbManagerLogin.Text, confirmDialog.Password, tbManagerPassword1.Text);
}
}
}
private void btnRemoveDocumentType_Click(object sender, EventArgs e)
{
if (cmbDocumentTypes.SelectedValue == null)
{
ShowError("Выберите тип документа в выпадающем списке");
return;
}
int selectedID = (int)cmbDocumentTypes.SelectedValue;
if(RemoveDocumentType != null)
{
RemoveDocumentType(selectedID);
}
}
private void btnUpdateDocumentType_Click(object sender, EventArgs e)
{
if (cmbDocumentTypes.SelectedValue == null)
{
ShowError("Выберите тип документа в выпадающем списке");
return;
}
int selectedID = (int)cmbDocumentTypes.SelectedValue;
InputDialog dialog = new InputDialog();
dialog.Title = "Введите новое название для типа документа:";
if(dialog.ShowDialog() == DialogResult.OK)
{
if(string.IsNullOrWhiteSpace(dialog.Result) || dialog.Result.Length < 5)
{
ShowError("Длина названия для типа документов не может быть меньше пяти символов.");
return;
}
if(SaveDocumentType != null)
{
SaveDocumentType(dialog.Result, selectedID);
}
}
}
private void btnAddDocumentType_Click(object sender, EventArgs e)
{
string docTypeName = tbNewDocumentType.Text;
if (string.IsNullOrWhiteSpace(docTypeName) || docTypeName.Length < 5)
{
ShowError("Длина названия для типа документов не может быть меньше пяти символов.");
return;
}
if (SaveDocumentType != null)
{
SaveDocumentType(docTypeName, -1);
tbNewDocumentType.Text = "";
}
}
private void btnAddUser_Click(object sender, EventArgs e)
{
if (!tbUserPassword.Text.Equals(tbUserPasswordAgain.Text))
{
ShowError("Пароли не совпадают!");
return;
}
string role = cmbUserRole.Items[cmbUserRole.SelectedIndex].ToString();
if (string.IsNullOrEmpty(role))
{
ShowError("Не указаны права пользователя!");
return;
}
if (!ConfigApp.ManagerRoleTranslate.ContainsValue(role))
{
ShowError("Права для пользователя не определены!");
return;
}
if (string.IsNullOrWhiteSpace(tbUserPassword.Text))
{
ShowError("Укажите пароль для нового пользователя!");
return;
}
if (string.IsNullOrWhiteSpace(tbUserLogin.Text))
{
ShowError("Укажите логин для нового пользователя!");
return;
}
if (_managers.FirstOrDefault(m => m.Login.Equals(tbUserLogin.Text)) != null)
{
ShowError("Пользователь с таким логином уже существует!");
return;
}
string roleTranslate = ConfigApp.ManagerRoleTranslate.FirstOrDefault(p => p.Value.Equals(role)).Key;
Manager manager = new Manager
{
Role = roleTranslate,
Login = tbUserLogin.Text,
Password = <PASSWORD>
};
if (AddManager != null)
{
AddManager(manager);
}
UpdateManagerTable();
tbUserLogin.Text = "";
tbUserPassword.Text = "";
tbUserPasswordAgain.Text = "";
}
public void UpdateManagerTable()
{
_selectedManager = null;
btnDeleteUser.Enabled = false;
btnResetPassword.Enabled = false;
if (GetManagers != null)
{
_managers = GetManagers();
var tableSource = _managers.Select(m => new ManagerTableModel
{
Role = ConfigApp.ManagerRoleTranslate[m.Role],
Login = m.Login
}).ToList();
managersTable.DataSource = new BindingList<ManagerTableModel>(tableSource);
managersTable.Update();
managersTable.Refresh();
}
}
private void btnDeleteUser_Click(object sender, EventArgs e)
{
if (_selectedManager == null) return;
if(RemoveManager != null)
{
RemoveManager(_selectedManager);
UpdateManagerTable();
}
}
private void btnResetPassword_Click(object sender, EventArgs e)
{
if (_selectedManager == null) return;
SetNewPasswordDialog dialog = new SetNewPasswordDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
_selectedManager.Password = <PASSWORD>;
if (UpdateManager != null) UpdateManager(_selectedManager);
UpdateManagerTable();
}
}
private void managersTable_Click(object sender, EventArgs e)
{
}
private void managersTable_SelectionChanged(object sender, EventArgs e)
{
btnDeleteUser.Enabled = false;
btnResetPassword.Enabled = false;
if (managersTable.SelectedRows.Count == 0) return;
int row = managersTable.SelectedRows[0].Index;
if (_managers == null || row < 0 || row >= _managers.Count) return;
_selectedManager = _managers[row];
btnDeleteUser.Enabled = true;
btnResetPassword.Enabled = true;
}
}
public class ManagerTableModel
{
[DisplayName("Логин")]
[ReadOnly(true)]
public string Login { get; set; }
[DisplayName("Права")]
[ReadOnly(true)]
public string Role { get; set; }
}
}
<file_sep>/AppCore/Entities/ProtocolAboutArrest.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Entities
{
/// <summary>
/// Протокол об аресте товаров, транспортных средств и иных вещей,
/// явившихся орудиями совершения или предметами административного правонарушения
/// </summary>
public class ProtocolAboutArrest: IProtocol
{
[Key]
public int ProtocolAboutArrestID { get; set; }
[Required(AllowEmptyStrings = false)]
public int ViolatorDocumentID { get; set; }
[Required(AllowEmptyStrings = false)]
public Protocol Protocol { get; set; }
/// <summary>
/// Сведения о лице, во владение которого находятся веши, на которые наложен арест
/// </summary>
public string AboutViolator { get; set; }
/// <summary>
/// Сведения о транспортном средстве
/// </summary>
public string AboutCar { get; set; }
/// <summary>
/// Сведения о других вещах
/// </summary>
public string AboutOtherThings { get; set; }
/// <summary>
/// Куда были переданы арестованые вещи
/// </summary>
public string ThingsWasTransfer { get; set; }
/// <summary>
/// Методы фиксации правонарушения
/// </summary>
public string FixingMethods { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/ClearableFlowLayoutPanel.cs
using LeoBase.Components.CustomControls.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls.NewControls
{
public class ClearableFlowLayoutPanel : FlowLayoutPanel, IClearable
{
private List<IClearable> _controls = new List<IClearable>();
public ClearableFlowLayoutPanel()
{
}
public void AddControl(List<IClearable> controls)
{
foreach (var control in controls)
this.Controls.Add(control.GetControl());
_controls = controls;
}
public void Clear()
{
foreach (var control in _controls) control.Clear();
}
public Control GetControl()
{
return this;
}
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/PersoneSavePanel.cs
using AppPresentators.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels.Persons;
using AppData.Entities;
using LeoBase.Components.CustomControls.SearchPanels;
namespace LeoBase.Components.CustomControls.NewControls
{
public class PersoneSavePanel : SavePageTemplate, ISavePersonControl
{
private IPersoneViewModel _persone;
public IPersoneViewModel Persone
{
get
{
return _persone;
}
set
{
_persone = value;
_personePanel.DataSource = _persone;
if (_persone != null) Title = _persone.IsEmploeyr ? "Сохранить сотрудника" : "Сохранить правонарушителя";
}
}
public bool ShowForResult { get; set; }
private AutoBinderPanel _personePanel;
public event Action SavePersone;
public Control GetControl()
{
return this;
}
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
public PersoneSavePanel():base()
{
this.Dock = DockStyle.Fill;
this.AutoScroll = true;
_personePanel = new AutoBinderPanel(AutoBinderPanelType.EDIT);
this.SaveClick += () =>
{
if (SavePersone != null) SavePersone();
};
_personePanel.Dock = DockStyle.Fill;
_personePanel.AutoScroll = true;
SetContent(_personePanel);
}
void UIComponent.Resize(int width, int height)
{
}
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/ViolationDetailsControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppData.Entities;
using AppPresentators;
using System.IO;
using LeoMapV3.Map;
using LeoMapV3.Data;
using LeoBase.Components.TopMenu;
namespace LeoBase.Components.CustomControls.NewControls
{
public partial class ViolationDetailsControl : UserControl, IViolationDetailsControl
{
private Button _btnReport;
private List<Control> _topControls;
public event Action<int> ShowEmployerDetails;
public event Action<int> ShowViolatorDetails;
public event Action EditViolation;
private LeoMap _map;
private TitleDBRepository _titleRepo;
public ViolationDetailsControl()
{
InitializeComponent();
var reportButton = new PictureButton(Properties.Resources.reportEnabled, Properties.Resources.reportDisabled, Properties.Resources.reportPress);
var editButton = new PictureButton(Properties.Resources.editEnabled, Properties.Resources.editDisabled, Properties.Resources.editPress);
editButton.Enabled = true;
reportButton.Enabled = true;
editButton.Click += (s, e) =>
{
if (EditViolation != null) EditViolation();
};
reportButton.Click += (s, e) =>
{
if (Report != null) Report();
};
_topControls = new List<Control>();
_topControls.Add(reportButton);
_topControls.Add(editButton);
}
public bool ShowForResult { get; set; }
public List<Control> TopControls
{
get
{
return _topControls;
}
set { }
}
private AdminViolation _violation;
public AdminViolation Violation
{
get
{
return _violation;
}
set
{
_violation = value;
if (value != null) RenderDataSource();
}
}
public event Action Report;
public Control GetControl()
{
return this;
}
private void RenderDataSource()
{
RenderProtocolInformation();
RenderRulingInformation();
RenderImages();
}
private void RenderImages()
{
if (Violation.Images == null)
{
groupBox3.Visible = false;
return;
}
imagePanel.Controls.Clear();
int x = 5;
int y = 5;
int count = 0;
foreach(var image in Violation.Images)
{
PictureViewer pv = new PictureViewer();
pv.CanSelected = true;
pv.ShowDeleteButton = false;
pv.Image = image.Image;
pv.Left = x;
pv.Top = y;
count++;
if(count % 5 != 0)
{
x += pv.Width + 10;
}else
{
count = 0;
x = 5;
y += pv.Height + 10;
}
pv.ImageName = image.Name;
imagePanel.Controls.Add(pv);
}
}
private void RenderRulingInformation()
{
lbRulingNumber.Text = Violation.RulingNumber;
lbDateConsideration.Text = Violation.Consideration.ToString();
lbViolation.Text = Violation.Violation;
lbSumViolation.Text = Math.Round(Violation.SumViolation, 2).ToString();
if (Violation.GotPersonaly)
{
lbSent.Text = "Получил лично";
} else if (Violation.WasSent)
{
lbSent.Text = string.Format("Отправлено: {0}; Номер отправления: {1}", Violation.DateSent.ToShortDateString(), Violation.NumberSent);
}
else
{
lbSent.Text = "Не отправлено";
}
if (Violation.WasSentBailiff)
{
lbSentBailiff.Text = string.Format("Отправлено: {0}; Номер отправления: {1}", Violation.DateSentBailiff.ToShortDateString(), Violation.NumberSentBailigg);
}else
{
lbSentBailiff.Text = "Не отправлялось";
}
if (Violation.WasNotice)
{
lbNotice.Text = string.Format("Извещение получено: {0}; Номер извещения: {1} ", Violation.DateNotice.ToShortDateString(), Violation.NumberNotice);
}else
{
lbNotice.Text = "Извещения не было";
}
if (Violation.WasAgenda2025)
{
lbAgenda2025.Text = Violation.DateAgenda2025.ToShortDateString();
}
else
{
lbAgenda2025.Text = "Повестки по статье 20.25 не было";
}
if (Violation.WasPaymant)
{
if(Violation.SumRecovery >= Violation.SumViolation)
{
lbPaymant.Text = "Оплачено " + Violation.DatePaymant.ToShortDateString();
lbPaymant.ForeColor = Color.Green;
}else
{
lbPaymant.Text = string.Format("Оплачено не полностью ({0} из {1}): {2}", Violation.SumRecovery, Violation.SumViolation, Violation.DatePaymant.ToShortDateString());
lbPaymant.ForeColor = Color.Red;
}
}
else
{
lbPaymant.Text = "Не оплачено";
lbPaymant.ForeColor = Color.Red;
}
}
private void RenderProtocolInformation()
{
lbPlaceCreatedProtocol.Text = Violation.PlaceCreatedProtocol;
lbCoordsCreatedProtocol.Text = string.Format("N: {0}; E: {1}", Math.Round(Violation.CreatedProtocolN, 8), Math.Round(Violation.CreatedProtocolE, 8));
lbDateTimeCreatedProtocol.Text = Violation.DateCreatedProtocol.ToString();
lbCoordsViolation.Text = string.Format("N: {0}; E: {1}", Math.Round(Violation.ViolationN, 8), Math.Round(Violation.ViolationE, 8));
lbDateTimeViolation.Text = Violation.DateViolation.ToString();
lbKOAP.Text = Violation.KOAP;
lbFindedNatureManagementProducts.Text = Violation.FindedNatureManagementProducts;
lbFindedGunsHuntingAndFishing.Text = Violation.FindedGunsHuntingAndFishing;
lbFindedWiapons.Text = Violation.FindedWeapons;
lbWitnessFIO_1.Text = Violation.WitnessFIO_1;
lbWitnessFIO_2.Text = Violation.WitnessFIO_2;
lbWitnessLive_1.Text = Violation.WitnessLive_1;
lbWitnessLive_2.Text = Violation.WitnessLive_2;
lbViolationDetails.Text = Violation.ViolationDescription;
lbEmployerInformation.Text = string.Format("{0} ; {1} {2} {3}", ConfigApp.EmploerPositions[Violation.Employer.Position_PositionID], Violation.Employer.FirstName, Violation.Employer.SecondName, Violation.Employer.MiddleName);
string violatorInformation = string.Format("{0} {1} {2}; ", Violation.ViolatorPersone.FirstName, Violation.ViolatorPersone.SecondName, Violation.ViolatorPersone.MiddleName);
violatorInformation += string.Format("Дата рождения: {0}; " , Violation.ViolatorPersone.DateBirthday.ToShortDateString());
violatorInformation += string.Format("Место работы: {0}; ", Violation.ViolatorPersone.PlaceWork);
violatorInformation += string.Format("Место рождения: {0}; ", Violation.ViolatorPersone.PlaceOfBirth);
violatorInformation += string.Format("Документ: {0} {1} {2} {3} {4}",
ConfigApp.DocumentsType[Violation.ViolatorDocument.Document_DocumentTypeID],
Violation.ViolatorDocument.Serial,
Violation.ViolatorDocument.Number,
Violation.ViolatorDocument.WhenIssued.ToShortDateString(),
Violation.ViolatorDocument.IssuedBy
);
lbViolatorInformation.Text = violatorInformation;
if(Violation.ViolationE != 0 && Violation.ViolationN != 0)
{
if (!File.Exists(ConfigApp.DefaultMapPath))
{
MessageBox.Show("Не удается найти карту по указанному пути: " + ConfigApp.DefaultMapPath, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
_titleRepo = new TitleDBRepository(ConfigApp.DefaultMapPath);
}
catch (Exception e)
{
MessageBox.Show("Не удается прочитать файл с картой: " + ConfigApp.DefaultMapPath, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_map = new LeoMap(_titleRepo);
_map.ClearPoints();
mapPanel.Controls.Clear();
_map.Dock = DockStyle.Fill;
var point = new LeoMapV3.Models.DPoint
{
E = Violation.ViolationE,
N = Violation.ViolationN,
ToolTip = "Место правонарушения",
Zoom = ConfigApp.DefaultMapZoomForViolation
};
_map.SetPoint(point);
_map.LookAt(point);
//_map.MouseState = LeoMapV3.Models.MapDragAndDropStates.NONE;
mapPanel.Controls.Add(_map);
mapPanel.Visible = true;
}
}
void UIComponent.Resize(int width, int height)
{
}
private bool _wasSelectedAll = false;
private void button1_Click(object sender, EventArgs e)
{
_wasSelectedAll = !_wasSelectedAll;
button1.Text = _wasSelectedAll ? "Снять выделенное" : "Выделить все";
foreach(var control in imagePanel.Controls)
{
var pv = control as PictureViewer;
if (pv == null) continue;
pv.Checked = _wasSelectedAll;
}
}
private void btnSaveImages_Click(object sender, EventArgs e)
{
FolderBrowserDialog browserDialog = new FolderBrowserDialog();
browserDialog.Description = "Выберите папку, для сохранения выбранных изображений";
if(browserDialog.ShowDialog() == DialogResult.OK)
{
string path = browserDialog.SelectedPath;
if (!path.EndsWith("\\")) path += "\\";
foreach (var img in Violation.Images)
{
int index = 1;
string fileName = path + (img.Name ?? (index).ToString()) + ".jpg";
while (File.Exists(fileName))
{
fileName = path + (string.IsNullOrEmpty(img.Name) ? (index++).ToString() : img.Name + (index++)) + ".jpg";
}
using (var ms = new MemoryStream(img.Image))
{
var image = Image.FromStream(ms);
image.Save(fileName);
}
}
}
}
private void btnViolatorDetails_Click(object sender, EventArgs e)
{
if (ShowViolatorDetails != null)
{
ShowViolatorDetails(Violation.ViolatorPersone.UserID);
}
}
private void btnEmployerDetails_Click(object sender, EventArgs e)
{
if(ShowEmployerDetails != null)
{
ShowEmployerDetails(Violation.Employer.UserID);
}
}
public Image GetMap()
{
if (_map == null) return null;
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(_map.Width, _map.Height);
_map.DrawToBitmap(bitmap, _map.ClientRectangle);
return bitmap;
}
}
}
<file_sep>/LeoBase/Components/CustomControls/SearchPanels/AutoBinderPanelDetailsDesine.cs
using LeoBase.Components.CustomControls.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls.SearchPanels
{
public partial class AutoBinderPanel : Panel, IClearable
{
private ComboBox GetComboBoxForDetails(PropertyControlModel propertyModel)
{
var comboBox = new ComboBox();
comboBox.DisplayMember = propertyModel.DisplayMember;
comboBox.ValueMember = propertyModel.ValueMember;
comboBox.DataSource = propertyModel.ComboBoxData;
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
return comboBox;
}
private LeoTextBox GetTextBoxForDetails(PropertyControlModel propertyModel)
{
return new LeoTextBox();
}
private void DetailsDesineRenderControls()
{
_container = new TableLayoutPanel();
_container.RowCount = _controls.Count + 2;
int rowIndex = 0;
_container.ColumnCount = 2;
_container.Dock = DockStyle.Fill;
this.Controls.Add(_container);
foreach (var control in _controls)
{
Label label = new Label();
label.Text = control.Value.Title ?? control.Key;
label.Text += ":";
label.ForeColor = System.Drawing.Color.FromArgb(76, 66, 54);
label.Dock = DockStyle.Right;
label.AutoSize = true;
label.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
_container.Controls.Add(label, 0, rowIndex);
control.Value.Control.Dock = DockStyle.Fill;
_container.Controls.Add(control.Value.Control);
rowIndex++;
}
for (int i = 0; i < _container.RowCount; i++)
{
_container.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));
}
this.Controls.Add(_container);
this.Height = _container.RowCount * 30;
}
}
}
<file_sep>/AppCore/Repositrys/AddressRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys
{
public class AddressRepository : IPersoneAddressRepository
{
public IQueryable<PersoneAddress> Addresses
{
get
{
var context = new LeoBaseContext();
return context.Addresses;
}
}
public int AddAdress(PersoneAddress address)
{
using(var db = new LeoBaseContext())
{
db.Addresses.Add(address);
db.SaveChanges();
}
return 0;
}
public bool Remove(int id)
{
using(var db = new LeoBaseContext())
{
var address = db.Addresses.FirstOrDefault(a => a.AddressID == id);
if(address != null)
{
db.Addresses.Remove(address);
db.SaveChanges();
return true;
}
}
return false;
}
public int RemoveUserAddresses(int userid)
{
using(var db = new LeoBaseContext())
{
var addresses = db.Addresses.Where(a => a.Persone.UserID == userid);
int result = addresses.Count();
db.Addresses.RemoveRange(addresses);
db.SaveChanges();
return result;
}
}
}
}
<file_sep>/AppCore/Repositrys/PositionsRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
using AppData.Contexts;
namespace AppData.Repositrys
{
public class PositionsRepository : IPersonePositionRepository
{
public IQueryable<EmploeyrPosition> Positions
{
get
{
var db = new LeoBaseContext();
return db.Positions;
}
}
public int AddPosition(EmploeyrPosition position)
{
using (var db = new LeoBaseContext())
{
var pos = db.Positions.Add(position);
db.SaveChanges();
return pos.PositionID;
}
}
public bool Remove(int id)
{
using(var db = new LeoBaseContext())
{
var position = db.Positions.FirstOrDefault(p => p.PositionID == id);
if(position != null)
{
db.Positions.Remove(position);
db.SaveChanges();
return true;
}
}
return false;
}
}
}
<file_sep>/AppPresentators/Components/UIComponent.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppPresentators.Components
{
public interface UIComponent
{
Control GetControl();
void Resize(int width, int height);
bool ShowForResult { get; set; }
List<Control> TopControls { get; set; }
}
}
<file_sep>/AppPresentators/Components/MainMenu/IMainMenu.cs
using AppPresentators.VModels.MainMenu;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components.MainMenu
{
public delegate void MenuItemSelected(MenuCommand command);
public interface IMainMenu:UIComponent
{
void AddMenuItem(IMainMenuItem item);
void AddMenuItems(List<MenuItemModel> items);
void RemoveMenuItem(IMainMenuItem item);
void RemoveMenuItem(int index);
event MenuItemSelected MenuItemSelected;
void SelecteItem(MenuCommand command);
}
}
<file_sep>/AppPresentators/Presentators/PassesPresentator.cs
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.Views;
using AppData.Contexts;
using AppData.Entities;
using System.ComponentModel;
using AppPresentators.VModels;
namespace AppPresentators.Presentators
{
public interface IPassesPresentator: IComponentPresentator
{
}
public class PassesPresentator : IPassesPresentator
{
private IPassesTableControl _control;
private IApplicationFactory _appFactory;
private IMainView _parent;
private BackgroundWorker _pageLoader;
public PassesPresentator(IMainView main, IApplicationFactory appFactory)
{
_parent = main;
_appFactory = appFactory;
_control = appFactory.GetComponent<IPassesTableControl>();
_control.EditPass += EditPass;
_control.MakeReport += MakeReport;
_control.RemovePass += RemovePass;
_control.AddPass += AddPass;
_control.UpdateTable += UpdateTable;
_control.ShowDetailsPass += ShowDetails;
_pageLoader = new BackgroundWorker();
_pageLoader.DoWork += PageLoading;
_pageLoader.RunWorkerCompleted += LoadComplete;
UpdateTable();
}
private void ShowDetails(int id)
{
using(var db = new PassedContext())
{
var pass = db.Passes.FirstOrDefault(p => p.PassID == id);
if(pass == null)
{
_control.ShowError("Пропуск не найден");
return;
}
var mainPresentator = _appFactory.GetMainPresentator();
var detailsPresentator = _appFactory.GetPresentator<IPassDeatailsPresentator>();
detailsPresentator.Pass = pass;
mainPresentator.ShowComponentForResult(this, detailsPresentator, ResultTypes.DETAILS_PASS);
}
}
private void LoadComplete(object sender, RunWorkerCompletedEventArgs e)
{
var response = (LoadDataPassResponseModel)e.Result;
_control.DataSource = response.Data;
_control.PageModel = response.PageModel;
_control.LoadEnd();
}
private void PageLoading(object sender, DoWorkEventArgs e)
{
var loadModel = (LoadDataPassModel)e.Argument;
using (var db = new PassedContext())
{
var passes = db.Passes.AsQueryable();
if (loadModel.SearchModel != null && !loadModel.SearchModel.IsEmptySearchModel())
{
var sm = loadModel.SearchModel;
if (!string.IsNullOrWhiteSpace(sm.FIO))
{
string[] spliter = sm.FIO.Split(new[] { ' ' });
if (spliter.Length == 3)
{
string fn = spliter[0];
string sn = spliter[1];
string mn = spliter[2];
passes = passes.Where(p => p.FirstName == fn && p.SecondName == sn && p.MiddleName.Contains(mn));
}
else if (spliter.Length == 2)
{
string fn = spliter[0];
string sn = spliter[1];
passes = passes.Where(p => p.FirstName == fn && p.SecondName.Contains(sn));
}
else if (spliter.Length == 1)
{
string fn = spliter[0];
passes = passes.Where(p => p.FirstName.Contains(fn));
}
}
if (!string.IsNullOrWhiteSpace(sm.DocumentType))
{
passes = passes.Where(p => p.DocumentType.Contains(sm.DocumentType));
}
if (!string.IsNullOrWhiteSpace(sm.Serial))
{
passes = passes.Where(p => p.Serial == sm.Serial);
}
if (!string.IsNullOrWhiteSpace(sm.Number))
{
passes = passes.Where(p => p.Number == sm.Number);
}
if (!string.IsNullOrWhiteSpace(sm.IssuedBy))
{
passes = passes.Where(p => p.WhoIssued.Contains(sm.IssuedBy));
}
switch (sm.CompareWhenClosed)
{
case VModels.CompareValue.EQUAL:
passes = passes.Where(p => p.PassClosed == sm.WhenClosed);
break;
case VModels.CompareValue.LESS:
passes = passes.Where(p => p.PassClosed < sm.WhenClosed);
break;
case VModels.CompareValue.MORE:
passes = passes.Where(p => p.PassClosed > sm.WhenClosed);
break;
}
switch (sm.CompareWhenGived)
{
case VModels.CompareValue.EQUAL:
passes = passes.Where(p => p.PassGiven == sm.WhenGived);
break;
case VModels.CompareValue.LESS:
passes = passes.Where(p => p.PassGiven < sm.WhenGived);
break;
case VModels.CompareValue.MORE:
passes = passes.Where(p => p.PassGiven > sm.WhenGived);
break;
}
switch (sm.CompareWhenIssued)
{
case VModels.CompareValue.EQUAL:
passes = passes.Where(p => p.WhenIssued == sm.WhenIssued);
break;
case VModels.CompareValue.LESS:
passes = passes.Where(p => p.WhenIssued < sm.WhenIssued);
break;
case VModels.CompareValue.MORE:
passes = passes.Where(p => p.WhenIssued > sm.WhenIssued);
break;
}
}
switch (loadModel.OrderModel.OrderProperties)
{
case VModels.PassesOrderProperties.BY_DATE_CLOSED:
passes = loadModel.OrderModel.OrderType == VModels.OrderType.ASC
? passes.OrderBy(p => p.PassClosed)
: passes.OrderByDescending(p => p.PassClosed);
break;
case VModels.PassesOrderProperties.BY_DATE_GIVED:
passes = loadModel.OrderModel.OrderType == VModels.OrderType.ASC
? passes.OrderBy(p => p.PassGiven)
: passes.OrderByDescending(p => p.PassGiven);
break;
case VModels.PassesOrderProperties.BY_FIO:
passes = loadModel.OrderModel.OrderType == VModels.OrderType.ASC
? passes.OrderBy(p => p.FirstName)
: passes.OrderByDescending(p => p.FirstName);
break;
default:
passes = passes.OrderBy(p => p.PassClosed);
break;
}
List<Pass> result = null;
if (loadModel.PageModel != null && loadModel.PageModel.CurentPage != -1)
{
result = passes.Skip(loadModel.PageModel.ItemsOnPage * (loadModel.PageModel.CurentPage - 1)).Take(loadModel.PageModel.ItemsOnPage).ToList();
}
else
{
result = passes.ToList();
}
LoadDataPassResponseModel response = new LoadDataPassResponseModel();
response.Data = result;
response.PageModel = loadModel.PageModel;
e.Result = response;
}
}
private void UpdateTable()
{
if (_pageLoader.IsBusy) return;
var page = _control.PageModel;
var order = _control.OrderModel;
var search = _control.SearchModel;
if (_control == null)
page = new PageModel
{
ItemsOnPage = 10,
CurentPage = 1
};
var request = new LoadDataPassModel
{
PageModel = page,
OrderModel = order,
SearchModel = search
};
_control.LoadStart();
_pageLoader.RunWorkerAsync(request);
return;
}
private void AddPass()
{
var pass = new Pass
{
PassID = -1,
DocumentType = ConfigApp.DocumentTypesList.FirstOrDefault().Name,
PassGiven = DateTime.Now,
PassClosed = DateTime.Now.AddYears(1),
WhenIssued = DateTime.Now.AddYears(-2)
};
var mainPresentator = _appFactory.GetMainPresentator();
var savePassPresentator = _appFactory.GetPresentator<IEditPassPresentator>();
savePassPresentator.Pass = pass;
mainPresentator.ShowComponentForResult(this, savePassPresentator, ResultTypes.SAVE_PASS);
}
private void EditPass(int id)
{
using(var db = new PassedContext())
{
var pass = db.Passes.FirstOrDefault(p => p.PassID == id);
if (pass == null)
{
_control.ShowError("Пропуск не найден");
return;
}
var mainPresentator = _appFactory.GetMainPresentator();
var editPassPresentator = _appFactory.GetPresentator<IEditPassPresentator>();
editPassPresentator.Pass = pass;
mainPresentator.ShowComponentForResult(this, editPassPresentator, ResultTypes.EDIT_PASS);
}
}
private void RemovePass(int id)
{
if (_control.ShowDialog("Вы уверены что хотите удалить эту запись?"))
{
using(var db = new PassedContext())
{
var pass = db.Passes.FirstOrDefault(p => p.PassID == id);
if (pass != null)
{
db.Passes.Remove(pass);
db.SaveChanges();
}
}
UpdateTable();
}
}
private void MakeReport(object obj)
{
}
public ResultTypes ResultType { get; set; }
public bool ShowFastSearch
{
get
{
return true;
}
}
public bool ShowForResult { get; set; }
public bool ShowSearch
{
get
{
return true;
}
}
public List<Control> TopControls
{
get
{
return _control.TopControls;
}
}
public event SendResult SendResult;
public void FastSearch(string message)
{
if (_pageLoader.IsBusy) return;
var page = _control.PageModel;
var order = _control.OrderModel;
var search = new PassesSearchModel
{
FIO = message
};
if (_control == null)
page = new PageModel
{
ItemsOnPage = 10,
CurentPage = 1
};
var request = new LoadDataPassModel
{
PageModel = page,
OrderModel = order,
SearchModel = search
};
_control.LoadStart();
_pageLoader.RunWorkerAsync(request);
return;
}
public Control RenderControl()
{
return _control.GetControl();
}
public void SetResult(ResultTypes resultType, object data)
{
if(resultType == ResultTypes.SAVE_PASS || resultType == ResultTypes.EDIT_PASS)
{
UpdateTable();
}
}
}
public class LoadDataPassModel
{
public PageModel PageModel { get; set; }
public PassesOrderModel OrderModel { get; set; }
public PassesSearchModel SearchModel { get; set; }
}
public class LoadDataPassResponseModel
{
public List<Pass> Data { get; set; }
public PageModel PageModel { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/Protocols/ViolationAboutPersoneView.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components.Protocols;
using AppPresentators.VModels.MainMenu;
using AppPresentators.VModels.Persons;
using AppPresentators.VModels.Protocols;
using AppPresentators.Infrastructure;
using AppPresentators;
namespace LeoBase.Components.CustomControls.Protocols
{
public partial class ViolationAboutPersoneView : UserControl, IProtocolAboutViolationView
{
private bool _useAutocomplete = false;
public ViolationAboutPersoneView()
{
InitializeComponent();
tbFirstNameEmployer.TextChanged += (s, e) =>
{
_useAutocomplete = chbAutocompliteEmplyer.Checked;
AutoComopleteEmployer();
_useAutocomplete = false;
};
tbSecondNameEmployer.TextChanged += (s, e) =>
{
_useAutocomplete = chbAutocompliteEmplyer.Checked;
AutoComopleteEmployer();
_useAutocomplete = false;
};
tbMiddleNameEmployer.TextChanged += (s, e) =>
{
_useAutocomplete = chbAutocompliteEmplyer.Checked;
AutoComopleteEmployer();
_useAutocomplete = false;
};
cbPositionEmployer.ValueMember = "PositionID";
cbPositionEmployer.DisplayMember = "Name";
cbPositionEmployer.DataSource = ConfigApp.EmployerPositionsList;
}
private void AutoComopleteEmployer()
{
if (_useAutocomplete)
{
if(_protocol != null)
{
_protocol.Employer.FirstName = tbFirstNameEmployer.Text.Length > 1 ? tbFirstNameEmployer.Text : "";
_protocol.Employer.SecondName = tbSecondNameEmployer.Text.Length > 1 ? tbSecondNameEmployer.Text : "";
_protocol.Employer.MiddleName = tbMiddleNameEmployer.Text.Length > 1 ? tbMiddleNameEmployer.Text : "";
//_protocol.Employer.PositionID = cbPositionEmployer.SelectedIndex >= 0 ? Convert.ToInt32(cbPositionEmployer.SelectedValue) : -1;
if (ChangeEmployerData != null) ChangeEmployerData();
}
}
}
public EmploeyrViewModel Emploer
{
get
{
if (_protocol != null) return _protocol.Employer;
return null;
}
set
{
if (_protocol != null) _protocol.Employer = value;
}
}
private ProtocolAboutViolationPersoneViewModel _protocol;
public ProtocolViewModel Protocol
{
get
{
return _protocol;
}
set
{
if (value is ProtocolAboutViolationPersoneViewModel)
_protocol = (ProtocolAboutViolationPersoneViewModel)value;
else
throw new ArgumentException("Тип протокола передан не правильно");
}
}
public PersoneViewModel Violator
{
get
{
if (_protocol != null) return _protocol.Violator;
else return null;
}
set
{
if (_protocol != null) _protocol.Violator = value;
}
}
public event Action ChangeEmployerData;
public event Action ChangeViolatorData;
public event Action Remove;
public event Action SearchEmployer;
public event Action SearchViolator;
public Control GetControl()
{
return this;
}
public void SetResult(ResultTypes resultType, object data)
{
if(resultType == ResultTypes.SEARCH_EMPLOYER) // Поиск сотрудника
{
}else if(resultType == ResultTypes.SEARCH_VIOLATOR) // Поиск нарушителя
{
}
}
public void SetViolator(IPersoneViewModel violator)
{
//throw new NotImplementedException();
}
public void SetEmployer(IPersoneViewModel employer)
{
if (_protocol != null) _protocol.Employer = (EmploeyrViewModel)employer;
bool buf = chbAutocompliteEmplyer.Checked;
chbAutocompliteEmplyer.Checked = false;
tbFirstNameEmployer.Text = employer.FirstName;
tbSecondNameEmployer.Text = employer.SecondName;
tbMiddleNameEmployer.Text = employer.MiddleName;
cbPositionEmployer.SelectedValue = _protocol.Employer.PositionID;
chbAutocompliteEmplyer.Checked = buf;
}
}
}
<file_sep>/AppPresentators/Components/IOptionsControl.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public interface IOptionsControl: UIComponent
{
/// <summary>
/// Удаление типа документа (1 arg - id типа документа), если тип документов с заданным id используется, то запрет на удаление.
/// </summary>
event Action<int> RemoveDocumentType;
/// <summary>
/// Добавление/обновление типа документов (1 arg - название типа документа, 2 arg - id типа документа, если -1, то создание нового)
/// </summary>
event Action<string, int> SaveDocumentType;
/// <summary>
/// Обновить текущего пользователя (1 arg - новый логин, 2 arg - старый пароль, 3 arg - новый пароль)
/// </summary>
event Action<string, string, string> UpdateCurrentManager;
List<DocumentType> DocumentTypes { get; set; }
List<EmploeyrPosition> Positions { get; set; }
void ShowError(string message);
void ShowMessage(string message);
event Func<List<Manager>> GetManagers;
event Action<Manager> AddManager;
event Action<Manager> UpdateManager;
event Action<Manager> RemoveManager;
void UpdateManagerTable();
}
}
<file_sep>/LeoBase/Components/MainMenu/MainMenu.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components.MainMenu;
using AppPresentators.VModels.MainMenu;
namespace LeoBase.Components.MainMenu
{
public partial class MainMenu : UserControl, IMainMenu
{
public bool ShowForResult
{
get
{
return false;
}
set
{
}
}
public List<Control> TopControls
{
get
{
return new List<Control>();
}
set
{
}
}
public MainMenu()
{
InitializeComponent();
}
public event MenuItemSelected MenuItemSelected;
public void AddMenuItem(IMainMenuItem item)
{
MainMenuItem it = new MainMenuItem(item.Title, item.MenuCommand, item.Icon);
it.Width = menuList.Width;
it.Anchor = AnchorStyles.Left | AnchorStyles.Right;
menuList.Controls.Add(it);
}
public void AddMenuItems(List<MenuItemModel> items)
{
if (items == null) items = new List<MenuItemModel>();
foreach(var item in items)
{
var mainMenuItem = new MainMenuItem(
item.Title,
item.MenuCommand,
item.Icon
);
mainMenuItem.ItemClicked += (command) =>
{
SelectItem(mainMenuItem);
MenuItemSelected(command);
};
menuList.Controls.Add(mainMenuItem);
}
}
private void SelectItem(MainMenuItem item)
{
foreach(var i in this.Controls)
{
if(i is MainMenuItem)
{
((MainMenuItem)i).IsActive = false;
}
}
foreach(var i in menuList.Controls)
{
if(i is MainMenuItem)
{
((MainMenuItem)i).IsActive = false;
}
}
item.IsActive = true;
}
public void RemoveMenuItem(int index)
{
if (index < 0 || index >= menuList.Controls.Count) return;
menuList.Controls.RemoveAt(index);
menuList.Refresh();
}
public void RemoveMenuItem(IMainMenuItem item)
{
}
public Control GetControl()
{
return this;
}
public void Resize(int width, int height)
{
this.Width = width;
this.Height = height;
menuList.Width = width - 3;
menuList.Height = height - 2;
foreach(var item in menuList.Controls)
{
((Control)item).Width = menuList.Width;
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
Pen penLeft = new Pen(Color.FromArgb(86, 53, 36), 2);
Pen penTop = new Pen(Color.FromArgb(79, 85, 25), 2);
Pen penRight = new Pen(Color.FromArgb(88, 74, 47), 2);
e.Graphics.DrawLine(penLeft, new Point(1, 1), new Point(1, this.Height));
e.Graphics.DrawLine(penRight, new Point(this.Width - 1, 1), new Point(this.Width - 1, this.Height));
e.Graphics.DrawLine(penTop, new Point(1, 1), new Point(this.Width, 1));
e.Graphics.DrawLine(penLeft, new Point(1, this.Height - 1), new Point(this.Width, this.Height - 1));
}
public void SelecteItem(MenuCommand command)
{
foreach(var item in menuList.Controls)
{
if(item is MainMenuItem)
{
if(((MainMenuItem)item).MenuCommand == command) {
SelectItem(item as MainMenuItem);
MenuItemSelected(command);
break;
}
}
}
}
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/ViolatorTableControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.VModels;
using AppPresentators.VModels.Persons;
using AppPresentators;
using LeoBase.Components.CustomControls.SearchPanels;
using LeoBase.Components.CustomControls.Interfaces;
using LeoBase.Components.TopMenu;
namespace LeoBase.Components.CustomControls.NewControls
{
public partial class ViolatorTableControl : CustomTablePage, IViolatorTableControl
{
private CustomTable _customTable;
private AutoBinderPanel _documentsSearchPanel;
private AutoBinderPanel _personeSearchPanel;
private AutoBinderPanel _addressSerchPanel;
private int _selectedIndex;
public ViolatorTableControl():base()
{
InitializeComponent();
MakeTopControls();
_orderProperties = new Dictionary<string, int>();
_orderTypes = new Dictionary<string, OrderType>();
_orderProperties.Add("Фамилия", (int)PersonsOrderProperties.FIRST_NAME);
_orderProperties.Add("Имя", (int)PersonsOrderProperties.SECOND_NAME);
_orderProperties.Add("Отчество", (int)PersonsOrderProperties.MIDDLE_NAME);
_orderProperties.Add("Дата рождения", (int)PersonsOrderProperties.DATE_BERTHDAY);
_orderProperties.Add("Возвраст", (int)PersonsOrderProperties.AGE);
_orderProperties.Add("Дата создания", (int)PersonsOrderProperties.WAS_BE_CREATED);
_orderProperties.Add("Дата последнего обновления", (int)PersonsOrderProperties.WAS_BE_UPDATED);
Title = "Нарушители";
_orderTypes.Add("Убывание", OrderType.DESC);
_orderTypes.Add("Возростание", OrderType.ASC);
_customTable = new CustomTable();
_customTable.Location = new Point(0, 30);
_customTable.Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
_customTable.OrderProperties = (Dictionary<string, int>)_orderProperties;
_customTable.UpdateTable += () => UpdateTable();
_customTable.SelectedItemChange += (index) =>
{
if (index != -1)
{
_selectedIndex = index;
_tpControls.EnabledDetails = true;
if (ConfigApp.CurrentManager.Role == "user") return;
_tpControls.EnabledEdit = true;
_tpControls.EnabledDelete = true;
}
};
_customTable.DoubleClick += () =>
{
if (ShowForResult && SelectedItemForResult != null)
{
SelectedItemForResult(_data[_selectedIndex]);
} else if (ShowPersoneDetails != null)
{
ShowPersoneDetails(_data[_selectedIndex]);
}
};
SetContent(_customTable);
CreateSearchPanel();
}
private void CreateSearchPanel()
{
var searchPanel = new SearchPanelContainer();
var layout = new ClearableFlowLayoutPanel();
_documentsSearchPanel = new AutoBinderPanel();
_addressSerchPanel = new AutoBinderPanel();
_personeSearchPanel = new AutoBinderPanel();
_documentsSearchPanel.DataSource = new DocumentSearchModel();
_addressSerchPanel.DataSource = new SearchAddressModel();
_personeSearchPanel.DataSource = new PersonsSearchModel();
Action dataChanged = () =>
{
if (UpdateTable != null) UpdateTable();
};
_documentsSearchPanel.DataSourceChanged += (s, e) => dataChanged();
_addressSerchPanel.DataSourceChanged += (s, e) => dataChanged();
_personeSearchPanel.DataSourceChanged += (s, e) => dataChanged();
_documentsSearchPanel.Width = 444;
_personeSearchPanel.Width = 444;
_addressSerchPanel.Width = 444;
layout.AddControl(new List<IClearable> { _personeSearchPanel, _documentsSearchPanel, _addressSerchPanel });
layout.Width = _documentsSearchPanel.Width;
layout.Height = _documentsSearchPanel.Height + _personeSearchPanel.Height + _addressSerchPanel.Height;
searchPanel.SetCustomSearchPanel(layout);
AddSearchPanel(searchPanel);
searchPanel.OnSearchClick += () =>
{
if (UpdateTable != null) UpdateTable();
};
}
public SearchAddressModel AddressSearchModel
{
get
{
return (SearchAddressModel)_addressSerchPanel.DataSource;
}
}
private List<ViolatorViewModel> _data;
public List<ViolatorViewModel> Data
{
get
{
return _data;
}
set
{
_data = value;
_customTable.SetData<ViolatorViewModel>(value);
if (_tpControls != null)
{
if (_data == null || _data.Count == 0)
{
_tpControls.EnabledDelete = false;
_tpControls.EnabledDetails = false;
_tpControls.EnabledEdit = false;
}
}
}
}
public DocumentSearchModel DocumentSearchModel
{
get
{
return (DocumentSearchModel)_documentsSearchPanel.DataSource;
}
}
private PersonsOrderModel _orderModel;
private Dictionary<string, int> _orderProperties;
private Dictionary<string, OrderType> _orderTypes;
public PersonsOrderModel OrderModel
{
get
{
_orderModel = new PersonsOrderModel
{
OrderProperties = (PersonsOrderProperties)_customTable.SelectedOrderBy,
OrderType = _customTable.OrderType
};
return _orderModel;
}
set
{
_orderModel = value;
}
}
private PageModel _pageModel;
public PageModel PageModel
{
get
{
if (_pageModel == null) _pageModel = new PageModel();
_pageModel.ItemsOnPage = 10;
_pageModel = _customTable.PageModel;
return _pageModel;
}
set
{
_pageModel = value;
_customTable.PageModel = value;
}
}
public PersonsSearchModel PersoneSearchModel
{
get
{
return (PersonsSearchModel)_personeSearchPanel.DataSource;
}
}
private bool _showForResult = false;
public bool ShowForResult
{
get
{
return _showForResult;
}
set
{
_showForResult = value;
MakeTopControls();
}
}
public event Action AddNewEmployer;
public event DeletePersone DeletePersone;
public event EditPersone EditPersone;
public event Action EndTask;
public event ShowPersoneDetails ShowPersoneDetails;
public event Action StartTask;
public event Action UpdateTable;
public event Action<ViolatorViewModel> SelectedItemForResult;
public event Action MakeReport;
public Control GetControl()
{
return this;
}
void UIComponent.Resize(int width, int height)
{
}
private List<Control> _topControls;
public List<Control> TopControls
{
get
{
return _topControls;
}
set { }
}
private Button _btnEditEmployer;
private Button _btnEmployerDelete;
private Button _btnShowEmployerDetails;
private Button _btnReturnResult;
private TopControls _tpControls;
private void MakeTopControls()
{
if (ShowForResult)
{
_btnReturnResult = new Button();
_btnReturnResult.Text = "Принять";
_btnReturnResult.Click += (s, e) =>
{
if(_selectedIndex >= 0 && _selectedIndex < _data.Count)
if (SelectedItemForResult != null)
{
SelectedItemForResult(_data[_selectedIndex]);
}
};
_topControls = new List<Control> { _btnReturnResult };
return;
}
_tpControls = new TopControls(ConfigApp.CurrentManager.Role);
_tpControls.DetailsItem += () =>
{
if (_selectedIndex < 0 || _selectedIndex >= _data.Count || _data.Count == 0) return;
var item = _data[_selectedIndex];
if (ShowPersoneDetails != null) ShowPersoneDetails(item);
};
_tpControls.ReportItem += () =>
{
if (MakeReport != null) MakeReport();
};
_tpControls.EditItem += () =>
{
if (_selectedIndex < 0 || _selectedIndex >= _data.Count || _data.Count == 0) return;
var item = _data[_selectedIndex];
if (EditPersone != null) EditPersone(item);
};
_tpControls.DeleteItem += () =>
{
if (_selectedIndex < 0 || _selectedIndex >= _data.Count || _data.Count == 0) return;
var item = _data[_selectedIndex];
if (MessageBox.Show("Вы уверены что хотите удалить сотрудника?", "Предупреждение", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.OK)
{
if (DeletePersone != null)
{
DeletePersone(item);
if (_data.Count == 0)
{
_selectedIndex = -1;
_tpControls.EnabledDelete = false;
_tpControls.EnabledDetails = false;
_tpControls.EnabledEdit = false;
}
}
}
};
_tpControls.AddItem += () => {
if (AddNewEmployer != null)
AddNewEmployer();
};
_tpControls.EnabledDelete = false;
_tpControls.EnabledDetails = false;
_tpControls.EnabledEdit = false;
_tpControls.EnabledAdd = true;
_tpControls.EnabledReport = true;
_topControls = _tpControls;
//if (ConfigApp.CurrentManager.Role.Equals("admin"))
//{
// AdminControls();
//}
//else
//{
// UserControls();
//}
}
private void AdminControls()
{
Button btnCreateNewEmplyer = new Button();
Button btnReportButton = new Button();
_btnEditEmployer = new Button();
_btnEmployerDelete = new Button();
_btnShowEmployerDetails = new Button();
_btnEditEmployer.Text = "Редактировать";
_btnEmployerDelete.Text = "Удалить";
_btnShowEmployerDetails.Text = "Подробнее";
btnCreateNewEmplyer.Text = "Добавить нового сотрудника";
btnReportButton.Text = "Отчет";
_btnShowEmployerDetails.Click += (s, e) =>
{
var item = _data[_selectedIndex];
if (ShowPersoneDetails != null) ShowPersoneDetails(item);
};
_btnEditEmployer.Click += (s, e) =>
{
var item = _data[_selectedIndex];
if (EditPersone != null) EditPersone(item);
};
_btnEmployerDelete.Click += (s, e) =>
{
var item = _data[_selectedIndex];
if (MessageBox.Show("Вы уверены что хотите удалить сотрудника?", "Предупреждение", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.OK)
{
if (DeletePersone != null) DeletePersone(item);
}
};
btnCreateNewEmplyer.Click += (s, e) => {
if (AddNewEmployer != null)
AddNewEmployer();
};
_btnEditEmployer.Enabled = false;
_btnEmployerDelete.Enabled = false;
_btnEditEmployer.Enabled = false;
btnReportButton.Margin = new Padding(3, 3, 20, 3);
_topControls = new List<Control> { btnReportButton, _btnShowEmployerDetails, btnCreateNewEmplyer, _btnEditEmployer, _btnEmployerDelete };
}
private void UserControls()
{
_btnShowEmployerDetails = new Button();
Button btnReportButton = new Button();
_btnShowEmployerDetails.Text = "Подробнее";
btnReportButton.Text = "Отчет";
_btnShowEmployerDetails.Click += (s, e) =>
{
var item = _data[_selectedIndex];
if (ShowPersoneDetails != null) ShowPersoneDetails(item);
};
_btnShowEmployerDetails.Enabled = false;
btnReportButton.Margin = new Padding(3, 3, 20, 3);
_topControls = new List<Control> { btnReportButton, _btnShowEmployerDetails };
}
public void LoadStart()
{
_customTable.Visible = false;
VisibleLoadPanel = true;
}
public void LoadEnd()
{
try {
VisibleLoadPanel = false;
_customTable.Visible = true;
}catch(Exception e)
{
}
}
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/IMainPresentator.cs
using AppPresentators.Infrastructure;
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using AppPresentators.Views;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces
{
public interface IMainPresentator:IPresentator
{
IMainView MainView { get;}
IVManager CurrentManager { get; set; }
void Login();
void AddMenu();
void SetNextPage(IComponentPresentator presentator);
void ShowComponentForResult(IComponentPresentator sender, IComponentPresentator executor, ResultTypes resultType);
void SendResult(IComponentPresentator recipient, ResultTypes resultType, object data);
void GetBackPage();
void GetNextPage();
object DialogResult { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/PictureViewer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace LeoBase.Components.CustomControls.NewControls
{
public partial class PictureViewer : UserControl
{
public event Action<PictureViewer> OnZoomClick;
public event Action<PictureViewer> OnDeleteClick;
private bool _showDeleteButton = true;
public string ImageName { get; set; }
public bool CanSelected
{
get
{
return chbSelectedItem.Visible;
}
set
{
chbSelectedItem.Visible = value;
}
}
public bool Checked
{
get
{
return chbSelectedItem.Checked;
}
set
{
chbSelectedItem.Checked = value;
}
}
public bool ShowDeleteButton
{
get
{
return _showDeleteButton;
}
set
{
_showDeleteButton = value;
if (Image != null)
btnDelete.Visible = value;
}
}
private bool _showZoomButton = false;
public bool ShowZoomButton
{
get
{
return _showZoomButton;
}
set
{
_showZoomButton = value;
if (Image != null)
btnZoom.Visible = value;
}
}
private byte[] _image;
public byte[] Image
{
get
{
return _image;
}
set
{
if (value == null || value.Length == 0) {
this.BackgroundImage = null;
return;
}
_image = value;
btnZoom.Visible = _showZoomButton;
btnDelete.Visible = _showDeleteButton;
this.BackgroundImage = ImageFromByteArray(_image);
}
}
public Image GetImage()
{
return this.BackgroundImage;
}
public PictureViewer()
{
InitializeComponent();
btnZoom.MouseMove += (s, e) => btnZoom.BackgroundImage = Properties.Resources.zoomHover;
btnZoom.MouseLeave += (s,e)=> btnZoom.BackgroundImage = Properties.Resources.zoomLeave;
btnDelete.MouseMove += (s, e) => btnDelete.BackgroundImage = Properties.Resources.deleteHover;
btnDelete.MouseLeave += (s, e) => btnDelete.BackgroundImage = Properties.Resources.deleteLeave;
this.Cursor = Cursors.Hand;
btnDelete.Cursor = Cursors.Hand;
btnZoom.Cursor = Cursors.Hand;
btnZoom.Visible = false;
btnDelete.Visible = false;
this.Click += (s, e) =>
{
if (OnZoomClick != null) OnZoomClick(this);
};
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (OnDeleteClick != null) OnDeleteClick(this);
}
private void btnZoom_Click(object sender, EventArgs e)
{
if (OnZoomClick != null) OnZoomClick(this);
}
private void PictureViewer_Load(object sender, EventArgs e)
{
//if (OnZoomClick != null) OnZoomClick(this);
}
private Image ImageFromByteArray(byte[] byteArrayIn)
{
using (var ms = new MemoryStream(byteArrayIn))
{
return System.Drawing.Image.FromStream(ms);
}
}
}
}
<file_sep>/AppCore/Abstract/Protocols/IProtocolAboutViolationPersoneRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract.Protocols
{
public interface IProtocolAboutViolationPersoneRepository
{
IQueryable<ProtocolAboutViolationPersone> ProtocolsAboutViolationPersone { get; }
}
}
<file_sep>/AppPresentators/Components/Protocols/IProtocolAboutViolationView.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components.Protocols
{
public interface IProtocolAboutViolationView:IProtocolView
{
event Action SearchViolator;
event Action SearchEmployer;
event Action ChangeViolatorData;
event Action ChangeEmployerData;
EmploeyrViewModel Emploer { get; set; }
PersoneViewModel Violator { get; set; }
void SetEmployer(IPersoneViewModel employer);
void SetViolator(IPersoneViewModel violator);
}
}
<file_sep>/AppPresentators/VModels/Persons/PersonsOrderProperties.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Persons
{
public enum PersonsOrderProperties
{
FIRST_NAME = 0,
SECOND_NAME = 1,
MIDDLE_NAME = 2,
DATE_BERTHDAY = 3,
AGE = 4,
WAS_BE_CREATED = 5,
WAS_BE_UPDATED = 6
}
}
<file_sep>/AppCore/FakesRepositoryes/FakePersonesAddressRepository.cs
using AppData.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppData.Entities;
namespace AppData.FakesRepositoryes
{
public class FakePersonesAddressRepository : IPersoneAddressRepository
{
private List<PersoneAddress> _addresses = new List<PersoneAddress>
{
new PersoneAddress
{
AddressID = 1,
Persone = new Persone
{
UserID = 1
},
City = "пгт. Славянка",
Street = "Героев-Хасана",
HomeNumber = "25",
Flat = "27",
Note = "Проживает"
},
new PersoneAddress
{
AddressID = 2,
Persone = new Persone
{
UserID = 1
},
City = "пгт.Славянка",
Street = "Лазо",
HomeNumber = "26",
Flat = "53",
Note = "Прописка"
},
new PersoneAddress
{
AddressID = 3,
Persone = new Persone
{
UserID = 2
},
City = "с.Барабаш",
Street = "Хасанская",
HomeNumber = "2",
Note = "Прописка"
},
new PersoneAddress
{
AddressID = 4,
Persone = new Persone
{
UserID = 2
},
City = "с.Барабаш",
Street = "Космонавтов",
HomeNumber = "3",
Note = "Проживает"
},
new PersoneAddress
{
AddressID = 5,
Persone = new Persone
{
UserID = 3
},
City = "c.Филиповка",
Street = "Гагарина",
HomeNumber = "7",
Flat = "15"
},
new PersoneAddress
{
AddressID = 6,
Persone = new Persone
{
UserID = 4
},
City = "с.Барабаш",
Street = "Моложденая",
HomeNumber = "7"
},
new PersoneAddress
{
AddressID = 7,
Persone = new Persone
{
UserID = 5
},
City = "с.Безверхово",
Street = "Моложденая",
HomeNumber = "7",
Flat = "6"
}
};
public IQueryable<PersoneAddress> Addresses
{
get
{
return _addresses.AsQueryable();
}
}
public int AddAdress(PersoneAddress address)
{
int id = Addresses.Max(a => a.AddressID) + 1;
address.AddressID = id;
_addresses.Add(address);
return id;
}
public bool Remove(int id)
{
var address = Addresses.FirstOrDefault(a => a.AddressID == id);
if (address == null)
return false;
return _addresses.Remove(address);
}
public int RemoveUserAddresses(int userid)
{
return 0;
//return _addresses.RemoveAll(a => a.UserID == userid);
}
}
}
<file_sep>/AppPresentators/Infrastructure/OrderBuilders/PDFOrderBuilder.cs
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Infrastructure.OrderBuilders
{
public class PDFOrderBuilder : IOrderBuilder
{
public event Action<string> ErrorBuild;
private Document _doc;
private bool _wasBeCreated = false;
private string _path;
private PdfPTable _table;
private BaseFont _baseFont;
private iTextSharp.text.Font _fgFont;
private Paragraph _p;
private string _fontPath;
public bool WasError { get; set; } = false;
public PDFOrderBuilder()
{
_doc = new Document();
}
public void SetOrderPath(DirectoryInfo dirInfo, string orderName)
{
_fontPath = Directory.GetCurrentDirectory() + "\\Fonts\\8277.ttf";
if (!File.Exists(_fontPath))
{
if(ErrorBuild != null)
{
ErrorBuild("Шрифт не найден.");
}
return;
}
_baseFont = BaseFont.CreateFont(_fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
_fgFont = new iTextSharp.text.Font(_baseFont, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
if (!Directory.Exists(dirInfo.FullName))
{
if (ErrorBuild != null) ErrorBuild("Папка " + dirInfo.FullName + " не найдена.");
return;
}
string path = dirInfo.FullName + @"/" + orderName + ".pdf";
try
{
PdfWriter.GetInstance(_doc, new FileStream(path, FileMode.Create));
}catch(Exception e)
{
if (ErrorBuild != null) ErrorBuild("Невозможно записать отчет в файл: " + path +" \r\n" + "Файл занят другим процессом");
WasError = true;
return;
}
_doc.Open();
_wasBeCreated = true;
_path = path;
}
public void DrawImage(System.Drawing.Image img, Align al)
{
if (!_wasBeCreated)
{
if (ErrorBuild != null) ErrorBuild("Не указан путь для отчета.");
return;
}
iTextSharp.text.Image pdfImg = iTextSharp.text.Image.GetInstance(ConverterImageToByteArray(img));
float maxWidth = _doc.Right - 20f;
if(pdfImg.Width > maxWidth)
{
var scalePercent = 100 * maxWidth / pdfImg.Width;
pdfImg.ScalePercent(scalePercent);
}
pdfImg.Alignment = al == Align.LEFT ? Element.ALIGN_LEFT : al == Align.RIGHT ? Element.ALIGN_RIGHT : Element.ALIGN_CENTER;
var a = _doc.Right;
pdfImg.PaddingTop = 10;
_doc.Add(pdfImg);
SetClearLine();
}
private void SetClearLine()
{
_doc.Add(new Paragraph(" "));
}
private byte[] ConverterImageToByteArray(System.Drawing.Image x)
{
ImageConverter _imageConverter = new ImageConverter();
byte[] xByte = (byte[])_imageConverter.ConvertTo(x, typeof(byte[]));
return xByte;
}
public void EndTable(string name)
{
if (!_wasBeCreated)
{
if (ErrorBuild != null) ErrorBuild("Не указан путь для отчета.");
WasError = true;
return;
}
_doc.Add(_table);
SetClearLine();
}
public string Save()
{
if (!_wasBeCreated)
{
if (ErrorBuild != null) ErrorBuild("Не указан путь для отчета.");
WasError = true;
return null;
}
_doc.Close();
return _path;
}
public void StartTable(string name, string[] headers)
{
if (!_wasBeCreated)
{
if (ErrorBuild != null) ErrorBuild("Не указан путь для отчета.");
WasError = true;
return;
}
if(headers == null)
{
if (ErrorBuild != null) ErrorBuild("Не указаны заголовки.");
WasError = true;
return;
}
if(headers.Length == 0)
{
if (ErrorBuild != null) ErrorBuild("Ошибка при формирование отчета.");
WasError = true;
return;
}
_table = new PdfPTable(headers.Length);
foreach(var cellText in headers)
{
PdfPCell cell = new PdfPCell(new Phrase(cellText, _fgFont));
cell.BackgroundColor = new BaseColor(Color.LightGray);
_table.AddCell(cell);
}
}
public void StartPharagraph(Align al)
{
if (!_wasBeCreated)
{
if (ErrorBuild != null) ErrorBuild("Не указан путь для отчета.");
WasError = true;
return;
}
_p = new Paragraph();
_p.Alignment = al == Align.LEFT ? Element.ALIGN_LEFT : al == Align.RIGHT ? Element.ALIGN_RIGHT : Element.ALIGN_CENTER;
}
public void EndPharagraph()
{
_doc.Add(_p);
_p = null;
}
public void WriteText(string text, Color color, TextStyle style = TextStyle.NORMAL, float size = 12)
{
if(_p == null)
{
if (ErrorBuild != null) ErrorBuild("Ошибка записи текста.");
WasError = true;
return;
}
var baseFont = BaseFont.CreateFont(_fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
var fgFont = new iTextSharp.text.Font(baseFont,
size,
style == TextStyle.BOLD ? iTextSharp.text.Font.BOLD : style == TextStyle.ITALIC ? iTextSharp.text.Font.ITALIC : iTextSharp.text.Font.NORMAL,
new BaseColor(color));
Phrase ph = new Phrase(text, fgFont);
_p.Add(ph);
}
public void WriteRow(string[] cells, RowColor color = RowColor.DEFAULT)
{
if (!_wasBeCreated)
{
if (ErrorBuild != null) ErrorBuild("Не указан путь для отчета.");
WasError = true;
return;
}
foreach (var cellText in cells)
{
PdfPCell cell = new PdfPCell(new Phrase(cellText, _fgFont));
switch (color)
{
case RowColor.GREEN:
cell.BackgroundColor = new BaseColor(Color.FromArgb(223, 240, 216));
break;
case RowColor.RED:
cell.BackgroundColor = new BaseColor(Color.FromArgb(242, 222, 222));
break;
case RowColor.YELLOW:
cell.BackgroundColor = new BaseColor(Color.FromArgb(252, 248, 227));
break;
}
_table.AddCell(cell);
}
}
}
}
<file_sep>/AppPresentators/VModels/Protocols/InjunctionViewModel.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Protocols
{
/// <summary>
/// Предписание об устранение нарушений законодательства в сфере
/// природопользования и охраны окружающей среды
/// </summary>
public class InjunctionViewModel:ProtocolViewModel
{
public int InjunctionID { get; set; }
public PersoneViewModel Violator { get; set; }
/// <summary>
/// Дата акта проверки
/// </summary>
public DateTime ActInspectionDate { get; set; }
/// <summary>
/// Номер акта проверки
/// </summary>
public string ActInspectionNumber { get; set; }
/// <summary>
/// Что предписывает
/// </summary>
public string InjunctionInfo { get; set; }
/// <summary>
/// Пункты предписания
/// </summary>
public virtual List<InjunctionItemViewModel> InjuctionsItem { get; set; }
}
/// <summary>
/// Пункт предписания
/// </summary>
public class InjunctionItemViewModel
{
public int InjunctionItemID { get; set; }
/// <summary>
/// Содержание пункта предписания
/// </summary>
public string Description { get; set; }
/// <summary>
/// Срок выполнения предписания
/// </summary>
public string Deedline { get; set; }
/// <summary>
/// Основание предписания
/// </summary>
public string BaseOrders { get; set; }
}
}
<file_sep>/LeoMapV3/MapConfig.cs
using LeoMapV3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeoMapV3
{
public static class MapConfig
{
public const int DefaultZoom = 13;
public static MapDragAndDropStates DefaultMouseState = MapDragAndDropStates.DRAG_AND_DROP;
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/ILoginPresentator.cs
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces
{
public delegate void LoginComplete(VManager manager);
public interface ILoginPresentator:IPresentator
{
event LoginComplete LoginComplete;
void Login(string userName, string password);
}
}
<file_sep>/AppCore/Abstract/IDocumentRepository.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppData.Abstract
{
public interface IDocumentRepository
{
IQueryable<Document> Documents { get; }
}
}
<file_sep>/Tests/Classes/FakeDbContext.cs
using AppData.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tests.Classes
{
public class FakeDbContext:DbContext
{
public IQueryable<Persone> Persones { get; set; }
public IQueryable<PersoneAddress> Addresses { get; set; }
public IQueryable<Document> Documents { get; set; }
public IQueryable<DocumentType> DocumentsType { get; set; }
public IQueryable<Phone> Phones { get; set; }
public IQueryable<EmploeyrPosition> Positions { get; set; }
public IQueryable<Manager> Managers { get; set; }
public IQueryable<Violation> Violations { get; set; }
public IQueryable<ViolationType> ViolationsType { get; set; }
public IQueryable<Violator> Violators { get; set; }
public IQueryable<Employer> Employers { get; set; }
public IQueryable<ViolationImage> ViolationImages { get; set; }
///Протоколы
public IQueryable<Protocol> Protocols { get; set; }
public IQueryable<DefinitionAboutViolation> DefinitionsAboutViolation { get; set; }
/// <summary>
/// Протоклы об аресте
/// </summary>
public IQueryable<ProtocolAboutArrest> ProtocolsAboutArrest { get; set; }
/// <summary>
/// Протоколы о доставление
/// </summary>
public IQueryable<ProtocolAboutBringing> ProtocolsAboutBringing { get; set; }
/// <summary>
/// Протоколы о личном досмотре и досмотре вещей, находящихся при физическом лице
/// </summary>
public IQueryable<ProtocolAboutInspection> ProtocolsAboutInspection { get; set; }
/// <summary>
/// Протокол о досмотре транспортного средства
/// </summary>
public IQueryable<ProtocolAboutInspectionAuto> ProtocolsAboutInspectionAuto { get; set; }
/// <summary>
/// Протокол об осмотре принадлежащих юридическому лицу или индивидуальному предпринимателю помещений, территорий
/// и находящихся там вещей и документов
/// </summary>
public IQueryable<ProtocolAboutInspectionOrganisation> ProtocolsAboutInspectionOrganisation { get; set; }
/// <summary>
/// Протокол об административном правонарушение для юридического лица
/// </summary>
public IQueryable<ProtocolAboutViolationOrganisation> ProtocolsAboutViolationOrganisation { get; set; }
/// <summary>
/// Протокол об административном правонарушение для физического лица
/// </summary>
public IQueryable<ProtocolAboutViolationPersone> ProtocolsAboutViolationPersone { get; set; }
/// <summary>
/// Протокол об изъятие
/// </summary>
public IQueryable<ProtocolAboutWithdraw> ProtocolsAboutWithdraw { get; set; }
/// <summary>
/// Предписание об устранение нарушений законодательства в сфере
/// природопользования и охраны окружающей среды
/// </summary>
public IQueryable<Injunction> Injunctions { get; set; }
/// <summary>
/// Пункт предписания
/// </summary>
public IQueryable<InjunctionItem> InjunctionItems { get; set; }
/// <summary>
/// Юридические лица
/// </summary>
public IQueryable<Organisation> Organisations { get; set; }
/// <summary>
/// Постановление по делу об административном правонарушение
/// </summary>
public IQueryable<RulingForViolation> RulingsForViolation { get; set; }
/// <summary>
/// Типы протоколов
/// </summary>
public IQueryable<ProtocolType> ProtocolTypes { get; set; }
}
}
<file_sep>/AppPresentators/Components/IMapControl.cs
using AppData.Entities;
using AppPresentators.VModels.Map;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public interface IMapControl:UIComponent
{
event Action<MapSearchModel> FilterViolations;
event Action<int> OpenViolation;
List<AdminViolation> DataSource { get; set; }
void SetPoint(MapPoint point);
void SetPoint(AdminViolation violation);
void ClearPoints();
}
}
<file_sep>/WPFPresentators/Factorys/IComponentFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFPresentators.Presentators;
using WPFPresentators.Services;
using WPFPresentators.Views.Controls;
using WPFPresentators.Views.Windows;
namespace WPFPresentators.Factorys
{
public interface IComponentFactory
{
T GetWindow<T>() where T : IWindowView;
T GetControl<T>() where T : IControlView;
T GetPresentator<T>();
T GetService<T>();
}
}
<file_sep>/FormControls/Controls/Models/LeoDataViewHeadMetaData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FormControls.Controls.Models
{
public class LeoDataViewHeadMetaData
{
public int ColumnIndex { get; set; }
public string DisplayName { get; set; }
public string FieldName { get; set; }
public bool Show { get; set; }
public bool CanOrder { get; set; }
public string Type { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/SearchPanels/AutoBinderPanelEditDesine.cs
using LeoBase.Components.CustomControls.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls.SearchPanels
{
public partial class AutoBinderPanel : Panel, IClearable
{
private ComboBox GetComboBoxForEdit(PropertyControlModel propertyModel)
{
var comboBox = new ComboBox();
comboBox.DisplayMember = propertyModel.DisplayMember;
comboBox.ValueMember = propertyModel.ValueMember;
//var pp = propertyModel.ComboBoxData[0];
//BindingSource bs = new BindingSource();
//bs.DataSource = propertyModel.ComboBoxData;
//comboBox.DataBindings.Add(new Binding("SelectedValue", bs, propertyModel.ValueMember, true));
comboBox.DataSource = propertyModel.ComboBoxData;
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox.BindingContext = Forms.MainView.GetInstance().BindingContext;
if(propertyModel.Value != null)
comboBox.SelectedValue = propertyModel.Value;
return comboBox;
}
private LeoTextBox GetTextBoxForEdit(PropertyControlModel propertyModel)
{
return new LeoTextBox() { Style = LeoTextBoxStyle.White };
}
private void EditDesineRenderControls()
{
_container = new TableLayoutPanel();
_container.RowCount = _controls.Count + 2;
int rowIndex = 0;
_container.ColumnCount = 2;
_container.Dock = DockStyle.Fill;
this.Controls.Add(_container);
foreach (var control in _controls)
{
if(control.Value.ControlType == AppData.CustomAttributes.ControlType.List)
{
GroupBox group = new GroupBox();
group.Text = control.Value.Title ?? control.Key;
_container.RowStyles.Add(new RowStyle(SizeType.AutoSize));
_container.Controls.Add(group);
_container.SetColumnSpan(group, 2);
group.Dock = DockStyle.Fill;
group.Controls.Add(control.Value.Control);
group.AutoSize = true;
continue;
}
Label label = new Label();
label.Text = control.Value.Title ?? control.Key;
label.Text += ":";
label.ForeColor = System.Drawing.Color.FromArgb(76, 66, 54);
label.Dock = DockStyle.Right;
label.AutoSize = true;
label.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
_container.Controls.Add(label, 0, rowIndex);
control.Value.Control.Dock = DockStyle.Fill;
_container.Controls.Add(control.Value.Control);
//if(control.Value.ControlType == AppData.CustomAttributes.ControlType.ComboBox)
//{
// ((ComboBox)control.Value.Control).SelectedValue = control.Value.Value;
//}
rowIndex++;
if(control.Value.ControlType == AppData.CustomAttributes.ControlType.Image || control.Value.ControlType == AppData.CustomAttributes.ControlType.List)
{
_container.RowStyles.Add(new RowStyle(SizeType.AutoSize));
}
else
{
_container.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));
}
}
//for (int i = 0; i < _container.RowCount; i++)
//{
// if(_controls[i].ControlType == AppData.CustomAttributes.ControlType.Image)
// else
//}
this.Controls.Add(_container);
this.Height = _container.RowCount * 30;
}
}
}
<file_sep>/LeoBase/Components/CustomControls/SaveComponent/SaveViolationControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.VModels;
using LeoBase.Components.CustomControls.SaveComponent.SaveProtocol;
using AppPresentators;
namespace LeoBase.Components.CustomControls.SaveComponent
{
public partial class SaveViolationControl : UserControl, ISaveOrUpdateViolationControl
{
SaveProtocolPanel _saveProtocolsPanel;
public SaveViolationControl()
{
InitializeComponent();
_saveProtocolsPanel = new SaveProtocolPanel();
//this.documentsPanel.Controls.Add(_saveProtocolsPanel);
cbProtocolTypes.ValueMember = "ProtocolTypeID";
cbProtocolTypes.DisplayMember = "Name";
cbProtocolTypes.DataSource = ConfigApp.ProtocolTypesList;
}
public bool ShowForResult { get; set; }
public List<Control> TopControls
{
get
{
Button saveButton = new Button();
saveButton.Text = "Сохранить";
saveButton.Click += (s, e) =>
{
if (Save != null) Save();
};
return new List<Control>
{
saveButton
};
}
set
{
}
}
private ViolationViewModel _violation;
public ViolationViewModel Violation
{
get
{
if(_violation == null)
{
_violation = new ViolationViewModel
{
Date = dtDate.Value,
Description = tbDescription.Text,
E = Convert.ToDouble(tbE.Text.Replace('.', ',')),
N = Convert.ToDouble(tbN.Text.Replace('.', ','))
};
}
return _violation;
}
set
{
_violation = value;
if(value.ViolationID > 0)
{
}
}
}
public event Action Save;
public event AddNewProtocol AddNewProtocolEvent;
public event Action FindEmplyer;
public event Action FindViolator;
public event Action FindRulingCreator;
public Control GetControl()
{
return this;
}
void UIComponent.Resize(int width, int height)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (cbProtocolTypes.SelectedIndex < 0)
{
MessageBox.Show("Выберите тип документа");
return;
}
if (AddNewProtocolEvent != null) AddNewProtocolEvent(Convert.ToInt32(cbProtocolTypes.SelectedValue));
//MessageBox.Show(string.Format("ID: {0}; Name: {1}", cbProtocolTypes.SelectedValue, cbProtocolTypes.Text));
}
public void AddProtocol(Control control)
{
documentsPanel.Controls.Add(control);
}
public void RemoveProtocol(Control control)
{
documentsPanel.Controls.Remove(control);
}
public DialogResult ShowDialog(string title, string message)
{
return MessageBox.Show(message, title, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
}
}
}
<file_sep>/AppPresentators/VModels/PassesOrderModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels
{
public enum PassesOrderProperties
{
BY_DATE_GIVED = 0,
BY_DATE_CLOSED = 1,
BY_FIO = 2
}
public class PassesOrderModel
{
public OrderType OrderType { get; set; }
public PassesOrderProperties OrderProperties { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/SaveComponent/SaveAddress/AddressesList.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels.Persons;
namespace LeoBase.Components.CustomControls.SaveComponent.SaveAddress
{
public partial class AddressesList : UserControl
{
public List<PersonAddressModelView> Addresses
{
get
{
List<PersonAddressModelView> result = new List<PersonAddressModelView>();
foreach(var c in flowLayoutPanel1.Controls)
{
var addressItem = (AddressItem)c;
var address = addressItem.Address;
if(address != null)
result.Add(addressItem.Address);
}
return result;
}
set
{
foreach(var item in value)
{
var addressItem = new AddressItem();
addressItem.Address = item;
if(value.Count == 1)
{
addressItem.ShowRemoveButton = false;
}
addressItem.RemoveThis += () => RemoveItem(addressItem);
flowLayoutPanel1.Controls.Add(addressItem);
}
}
}
public AddressesList()
{
InitializeComponent();
}
private void RemoveItem(Control control)
{
flowLayoutPanel1.Controls.Remove(control);
}
private void button1_Click(object sender, EventArgs e)
{
AddressItem addressItem = new AddressItem();
addressItem.Address = new PersonAddressModelView
{
AddressID = -1,
Country = "Российская Федерация",
Subject = "Приморский край",
Area = "Хасанский район"
};
addressItem.RemoveThis += () => RemoveItem(addressItem);
flowLayoutPanel1.Controls.Add(addressItem);
}
}
}
<file_sep>/LeoBase/Components/CustomControls/SearchPanels/AddressSearchPanel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.VModels.Persons;
using AppPresentators.VModels;
namespace LeoBase.Components.CustomControls.SearchPanels
{
public partial class AddressSearchPanel : UserControl
{
public SearchAddressModel SearchAddressModel
{
get
{
return new SearchAddressModel
{
Country = tbCountry.Text.Trim(),
CompareCountry = chbCounty.Checked ? CompareString.EQUAL : CompareString.CONTAINS,
Subject = tbRegion.Text.Trim(),
CompareSubject = chbRegion.Checked ? CompareString.EQUAL : CompareString.CONTAINS,
Area = tbArea.Text.Trim(),
CompareArea = chbArea.Checked ? CompareString.EQUAL : CompareString.CONTAINS,
City = tbCity.Text.Trim(),
CompareCity = chbCity.Checked ? CompareString.EQUAL : CompareString.CONTAINS,
Street = tbStreet.Text.Trim(),
CompareStreet = chbStreet.Checked ? CompareString.EQUAL : CompareString.CONTAINS,
HomeNumber = tbHomeNumber.Text.Trim(),
Flat = tbFlat.Text.Trim(),
Note = ""
};
}
}
public AddressSearchPanel()
{
InitializeComponent();
}
public void Clear()
{
tbCountry.Text = "";
tbRegion.Text = "";
tbArea.Text = "";
tbStreet.Text = "";
tbCity.Text = "";
tbHomeNumber.Text = "";
tbFlat.Text = "";
chbCounty.Checked = true;
chbRegion.Checked = true;
chbCity.Checked = true;
chbArea.Checked = true;
chbStreet.Checked = true;
}
private void btnClearAddressSearchModel_Click(object sender, EventArgs e)
{
Clear();
}
}
}
<file_sep>/LeoBase/Components/CustomControls/NewControls/WhiteLeoTextBox.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeoBase.Components.CustomControls.NewControls
{
public class WhiteLeoTextBox:Panel
{
private TextBox _textBox;
public event EventHandler TextChanged;
public event KeyPressEventHandler KeyPress;
public override string Text
{
get
{
return _textBox.Text;
}
set
{
_textBox.Text = value;
}
}
private LeoTextBoxDataType _dataType = LeoTextBoxDataType.TEXT;
public LeoTextBoxDataType DataType
{
get
{
return _dataType;
}
set
{
_dataType = value;
}
}
public WhiteLeoTextBox()
{
_textBox = new TextBox();
_textBox.Dock = DockStyle.Fill;
_textBox.BackColor = Color.FromArgb(248, 247, 245);
_textBox.BorderStyle = BorderStyle.None;
this.Padding = new Padding(7, 6, 7, 6);
this.Controls.Add(_textBox);
_textBox.TextChanged += _textBox_TextChanged;
_textBox.KeyPress += _textBox_KeyPress;
}
private void _textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (KeyPress != null) KeyPress(sender, e);
}
private void _textBox_TextChanged(object sender, EventArgs e)
{
if (TextChanged != null) TextChanged(sender, e);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
Image imageBg = ResizeImage(Properties.Resources.tbBackground, this.Width - 14, 26);
Image imageLeft = Properties.Resources.tbLeft;
Image imageRight = Properties.Resources.tbRight;
e.Graphics.DrawImage(imageBg, new Point(7, 0));
e.Graphics.DrawImage(imageLeft, new Point(0, 0));
e.Graphics.DrawImage(imageRight, new Point(this.Width - 7, 0));
}
public static Bitmap ResizeImage(Image image, int width, int height)
{
//var destRect = new Rectangle(0, 0, width, height);
//var destImage = new Bitmap(width, height);
//destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
//using (var graphics = Graphics.FromImage(destImage))
//{
// graphics.CompositingMode = CompositingMode.SourceCopy;
// graphics.CompositingQuality = CompositingQuality.HighQuality;
// graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// graphics.SmoothingMode = SmoothingMode.HighQuality;
// graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
// using (var wrapMode = new ImageAttributes())
// {
// wrapMode.SetWrapMode(WrapMode.TileFlipXY);
// graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
// }
//}
return null;
}
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/IPresentator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces
{
public interface IPresentator
{
void Run();
}
}
<file_sep>/AppPresentators/Presentators/PersoneDetailsPresentator.cs
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppPresentators.Infrastructure;
using AppPresentators.VModels.Persons;
using System.Windows.Forms;
using AppPresentators.Services;
using AppPresentators.Components;
namespace AppPresentators.Presentators
{
public class PersoneDetailsPresentator : IPersoneDetailsPresentator
{
private IPersoneViewModel _persone;
public IPersoneViewModel Persone {
get {
return _persone;
}
set
{
_persone = value;
UpdatePersone();
}
}
public ResultTypes ResultType { get; set; }
public bool ShowFastSearch { get; set; }
public bool ShowForResult { get; set; }
public bool ShowSearch { get; set; }
public List<Control> TopControls
{
get
{
return _control.TopControls;
}
}
public event SendResult SendResult;
private IApplicationFactory _appFactory;
private IPersonesService _service;
private IPersoneDetailsControl _control;
public PersoneDetailsPresentator(IApplicationFactory appFactory)
{
_appFactory = appFactory;
_service = _appFactory.GetService<IPersonesService>();
_control = _appFactory.GetComponent<IPersoneDetailsControl>();
}
public void FastSearch(string message){}
public Control RenderControl()
{
return _control.GetControl();
}
public void SetResult(ResultTypes resultType, object data)
{
if(resultType == ResultTypes.UPDATE_PERSONE)
{
UpdatePersone();
}
}
public void UpdatePersone()
{
int userId = Persone.UserID;
_persone = _service.GetPerson(userId, true);
_control.Persone = Persone;
var violationsService = _appFactory.GetService<IViolationService>();
if (Persone.IsEmploeyr) {
violationsService.SearchModel = new ViolationSearchModel
{
EmplyerID = Persone.UserID
};
}
var violations = violationsService.GetViolations(true);
_control.Violations = violations;
}
}
}
<file_sep>/AppPresentators/Presentators/LoginPresentator.cs
using AppPresentators.Presentators.Interfaces;
using AppPresentators.Services;
using AppPresentators.Views;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators
{
public class LoginPresentator : ILoginPresentator
{
private IMainView _mainView;
private ILoginService _service;
private ILoginView _view;
public event LoginComplete LoginComplete;
public LoginPresentator(IMainView main, ILoginService service, ILoginView view)
{
_mainView = main;
_service = service;
_view = view;
_view.Login += () => Login(_view.UserName, _view.Password);
_view.Cancel += () => Cancel();
_view.CloseAndLogin += () => LoginAndCloseForm();
}
public void Cancel()
{
_view.Close();
_mainView.Close();
}
public void LoginAndCloseForm()
{
if (ConfigApp.CurrentManager == null)
{
_view.ShowError("Неверные логин или пароль");
}
else
{
_mainView.Manager = ConfigApp.CurrentManager;
if (LoginComplete != null) LoginComplete(ConfigApp.CurrentManager);
_view.Close();
}
}
public void Login(string userName, string password)
{
if (string.IsNullOrEmpty(userName))
{
_view.ShowError("Не указано имя пользователя");
}
if (string.IsNullOrEmpty(password))
{
_view.ShowError("Пароль не указан");
}
ConfigApp.CurrentManager = _service.Login(userName, password);
}
public void Run()
{
_view.Show();
}
}
}
<file_sep>/AppPresentators/Presentators/Interfaces/IMapPresentator.cs
using AppPresentators.Presentators.Interfaces.ComponentPresentators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Presentators.Interfaces
{
public interface IMapPresentator: IComponentPresentator
{
}
}
<file_sep>/Map/Map/interfaces/ILeoMap.cs
using Map.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Map.Map.interfaces
{
public interface ILeoMap
{
event Action<object, MapEventArgs> MouseMoving;
event Action<object, MapRegion> RegionSelected;
event Action<object, DPoint> PointClicked;
void Redraw();
void RedrawAsync();
void SetPoint(DPoint point);
void SetPoints(List<DPoint> points);
Image GetMapImage();
void LookAt(DPoint point);
void ClearPoints();
MapDragAndDropStates MouseState { get; set; }
}
}
<file_sep>/LeoBase/Components/CustomControls/SaveComponent/SavePersonControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AppPresentators.Components;
using AppPresentators.VModels.Persons;
using LeoBase.Forms;
using System.IO;
using LeoBase.Components.CustomControls.SaveComponent.SavePhone;
using LeoBase.Components.CustomControls.SaveComponent.SaveAddress;
using LeoBase.Components.CustomControls.SaveComponent.SaveDocument;
using AppData.Entities;
namespace LeoBase.Components.CustomControls.SaveComponent
{
public partial class SavePersonControl : UserControl, ISavePersonControl
{
public bool ShowForResult { get; set; } = false;
private string ErrorMessage { get; set; } = "";
private bool _wasCreated { get; set; } = true;
public event Action SavePersone;
private PhonesList Phones = new PhonesList();
private AddressesList Addresses = new AddressesList();
private DocumentsList Documents = new DocumentsList();
public List<Control> TopControls { get; set; }
private Button _saveButton;
public SavePersonControl()
{
InitializeComponent();
_saveButton = new Button();
_saveButton.Text = "Сохранить";
TopControls = new List<Control> { _saveButton };
_saveButton.Click += (s, e) =>
{
if (SavePersone != null) SavePersone();
};
tableLayoutPanel1.Controls.Add(Phones, 0, 2);
tableLayoutPanel1.Controls.Add(Addresses, 0, 3);
Phones.Phones = new List<PhoneViewModel>
{
new PhoneViewModel { }
};
Addresses.Addresses = new List<PersonAddressModelView>
{
new PersonAddressModelView {
Country = "Российская Федерация",
Subject = "Приморский край",
Area = "Хасанский район"
}
};
if (!IsEmployer) {
tableLayoutPanel1.Controls.Add(Documents, 0, 4);
Documents.Documents = new List<PersoneDocumentModelView>
{
new PersoneDocumentModelView
{
DocumentID = -1,
WhenIssued = new DateTime(1999, 1, 1)
}
};
}
}
private bool IsEmployer { get; set; } = false;
private DateTime _wasBeCreated { get; set; }
private int UserID { get; set; }
private Dictionary<int, string> _positions = new Dictionary<int, string>();
public Dictionary<int, string> Positions
{
get
{
return _positions;
}
set
{
_positions = value;
cmbPosition.Items.Clear();
cmbPosition.Refresh();
foreach(var p in value)
{
cmbPosition.Items.Add(p.Value);
}
}
}
public IPersoneViewModel Persone
{
get
{
var result = MakePersonViewModel();
if (result == null)
{
ShowMessage(ErrorMessage);
}
return result;
}
set
{
if (value == null) return;
IsEmployer = value.IsEmploeyr;
if (value.IsEmploeyr)
{
// Если это сотрудник то показываем дополнительные поля
//pageTitle.Text = "Добавление нового сотрудника";
cmbPosition.Visible = true;
lbPosition.Visible = true;
lbWorkPlace.Visible = false;
tbWorkPlace.Visible = false;
}else
{
//pageTitle.Text = "Добавление нового нарушителя";
tbWorkPlace.Visible = true;
lbWorkPlace.Visible = true;
lbPosition.Visible = false;
cmbPosition.Visible = false;
}
if(value.UserID > 0)
{
// Заполняем данные
UserID = value.UserID;
tbFirstName.Text = value.FirstName;
tbSecondName.Text = value.SecondName;
tbMiddleName.Text = value.MiddleName;
tbPlaceBerth.Text = value.PlaceOfBirth;
dtpDateBerth.Value = value.DateBirthday;
_wasBeCreated = value.WasBeCreated;
Phones.Phones = value.Phones;
Addresses.Addresses = value.Addresses;
Documents.Documents = value.Documents;
if (value.Image != null && value.Image.Length != 0)
{
pbAvatar.BackgroundImage = ImageFromByteArray(value.Image);
pbAvatar.BackgroundImageLayout = ImageLayout.Stretch;
}
if (IsEmployer)
{
var emploeyr = (EmploeyrViewModel)value;
for (int i = 0; i < cmbPosition.Items.Count; i++)
{
if (cmbPosition.Items[i].ToString().Equals(emploeyr.Position))
{
cmbPosition.SelectedIndex = i;
break;
}
}
}else
{
var violator = (ViolatorViewModel)value;
tbWorkPlace.Text = violator.PlaceOfWork;
}
_wasCreated = false;
}
else
{
_wasCreated = true;
}
PageTitle.Text = (_wasCreated ? "Добавление " : "Редактирование ") + (IsEmployer ? "сотрудника" : "нарушителя");
}
}
//Persone ISavePersonControl.Persone
//{
// get
// {
// throw new NotImplementedException();
// }
// set
// {
// throw new NotImplementedException();
// }
//}
private Image ImageFromByteArray(byte[] byteArrayIn)
{
using (var ms = new MemoryStream(byteArrayIn))
{
return Image.FromStream(ms);
}
}
public byte[] ImageToByteArray(Image imageIn)
{
if (imageIn == null) return new byte[0];
using (var ms = new MemoryStream())
{
var a = System.Drawing.Imaging.ImageFormat.Jpeg;
var format = new System.Drawing.Imaging.ImageFormat(imageIn.RawFormat.Guid);
imageIn.Save(ms, a);
return ms.ToArray();
}
}
public Control GetControl()
{
return this;
}
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
void UIComponent.Resize(int width, int height)
{
}
private IPersoneViewModel MakePersonViewModel()
{
IPersoneViewModel result = null;
if (IsEmployer)
{
if (cmbPosition.SelectedIndex < 0)
{
ErrorMessage = "Не выбрана должность для сотрудника";
return null;
}
string position = cmbPosition.Items[cmbPosition.SelectedIndex].ToString();
if (string.IsNullOrEmpty(position))
{
ErrorMessage = "Не выбрана должность для сотрудника";
return null;
}
if (!_positions.ContainsValue(position))
{
ErrorMessage = "Неизвестная должность для сотрудника";
return null;
}
int positionID = _positions.FirstOrDefault(p => p.Value.Equals(position)).Key;
EmploeyrViewModel employer = new EmploeyrViewModel
{
Position = position,
PositionID = positionID.ToString(),
IsEmploeyr = true
};
result = employer;
}else
{
if(string.IsNullOrWhiteSpace(tbWorkPlace.Text))
{
ErrorMessage = "Не указано место работы";
return null;
}
var violator = new ViolatorViewModel
{
PlaceOfWork = tbWorkPlace.Text,
IsEmploeyr = false
};
result = violator;
}
if (string.IsNullOrWhiteSpace(tbFirstName.Text))
{
ErrorMessage = "Не указана фамилия";
return null;
}
if (string.IsNullOrWhiteSpace(tbSecondName.Text))
{
ErrorMessage = "Не указано имя";
return null;
}
if (string.IsNullOrWhiteSpace(tbMiddleName.Text))
{
ErrorMessage = "Не указано отчество";
return null;
}
if (string.IsNullOrWhiteSpace(tbPlaceBerth.Text))
{
ErrorMessage = "Не указано место рождения";
return null;
}
result.Phones = Phones.Phones;
result.Addresses = Addresses.Addresses;
if (!IsEmployer)
result.Documents = Documents.Documents;
result.DateBirthday = dtpDateBerth.Value;
result.FirstName = tbFirstName.Text;
if (!string.IsNullOrEmpty(_fileName))
{
FileStream fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
string dd = data.ToString();
result.Image = data;
}else if (pbAvatar.BackgroundImage == null)
{
result.Image = new byte[0];
}
result.MiddleName = tbMiddleName.Text;
result.SecondName = tbSecondName.Text;
result.PlaceOfBirth = tbPlaceBerth.Text;
if (_wasCreated)
{
result.WasBeUpdated = DateTime.Now;
result.WasBeCreated = DateTime.Now;
}else
{
result.UserID = UserID;
result.WasBeUpdated = DateTime.Now;
result.WasBeCreated = _wasBeCreated;
}
return result;
}
private void button1_Click_1(object sender, EventArgs e)
{
if (SavePersone != null) SavePersone();
}
private string _fileName = null;
private void btnImageOpen_Click_1(object sender, EventArgs e)
{
openImageDialog.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.PNG;*.GIF;";
if (openImageDialog.ShowDialog() == DialogResult.OK)
{
Image image = Image.FromFile(openImageDialog.FileName);
pbAvatar.BackgroundImage = image;
pbAvatar.BackgroundImageLayout = ImageLayout.Stretch;
_fileName = openImageDialog.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
_fileName = null;
pbAvatar.BackgroundImage = null;
}
}
}
<file_sep>/AppPresentators/Components/IPassesTableControl.cs
using AppData.Entities;
using AppPresentators.VModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.Components
{
public interface IPassesTableControl:UIComponent
{
List<Pass> DataSource { get; set; }
PassesOrderModel OrderModel { get; set; }
PassesSearchModel SearchModel { get; set; }
PageModel PageModel { get; set; }
event Action<int> ShowDetailsPass;
event Action<int> RemovePass;
event Action<object> MakeReport;
event Action<int> EditPass;
event Action AddPass;
event Action UpdateTable;
void ShowMessage(string text, string title);
void ShowError(string text);
bool ShowDialog(string text);
void LoadStart();
void LoadEnd();
}
}
<file_sep>/AppPresentators/VModels/Protocols/DefinitionAboutViolationViewModel.cs
using AppPresentators.VModels.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppPresentators.VModels.Protocols
{
/// <summary>
/// Определение о возбуждение дела об административном правонарушение
/// и проведение административного расследования
/// </summary>
public class DefinitionAboutViolationViewModel:ProtocolViewModel
{
public int DefinitionAboutViolationID { get; set; }
public PersoneDocumentModelView ViolatorDocument { get; set; }
public OrganisationViewModel Organisation { get; set; }
/// <summary>
/// Найденное оружие
/// </summary>
public string FindedWeapons { get; set; }
/// <summary>
/// Найденные боеприпасы
/// </summary>
public string FindedAmmunitions { get; set; }
/// <summary>
/// Найденые орудия для охоты и рыболовства
/// </summary>
public string FindedGunsHuntingAndFishing { get; set; }
/// <summary>
/// Найденная продукция природопользования
/// </summary>
public string FindedNatureManagementProducts { get; set; }
/// <summary>
/// Найденные документы
/// </summary>
public string FindedDocuments { get; set; }
/// <summary>
/// Статья КОАП
/// </summary>
public string KOAP { get; set; }
/// <summary>
/// Методы фиксации правонарушения
/// </summary>
public string FixingMethods { get; set; }
}
}
<file_sep>/LeoMapV3/Map/LeoMap.cs
using LeoMapV3.Map.interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LeoMapV3.Models;
using System.Drawing;
using LeoMapV3.Data;
namespace LeoMapV3.Map
{
public class LeoMap : Panel, ILeoMap
{
private ITitlesRepository _repo;
private IMapRenderer _render;
private PictureBox _pictureBox;
private bool _dragAndDropStart;
private int _oldX;
private int _oldY;
private int _dX;
private int _dY;
private Timer _timerDragAndDrop;
private Label _lbToolTip;
public event Action<object, MapEventArgs> MouseMoving;
public event Action<object, MapRegion> RegionSelected;
public event Action<object, DPoint> PointClicked;
public int ClientMouseX { get; set; }
public int ClientMouseY { get; set; }
public MapDragAndDropStates MouseState { get; set; } = MapConfig.DefaultMouseState;
public LeoMap(ITitlesRepository repo)
{
_timerDragAndDrop = new Timer();
_lbToolTip = new Label();
_lbToolTip.AutoSize = true;
_lbToolTip.BackColor = Color.White;
_lbToolTip.Padding = new Padding(3);
_lbToolTip.Visible = false;
this.Controls.Add(_lbToolTip);
_timerDragAndDrop.Interval = 20;
_timerDragAndDrop.Tick += _timerDragAndDrop_Tick;
_pictureBox = new PictureBox();
_pictureBox.Size = new Size(256, 400);
_repo = repo;
_render = new DefaultMapRenderer(_repo);
this.Resize += OnResize;
this.Controls.Add(_pictureBox);
_pictureBox.MouseDown += OnMouseDown;
_pictureBox.MouseMove += OnMouseMove;
_pictureBox.MouseUp += OnMouseUp;
_pictureBox.MouseWheel += EditZoom;
_pictureBox.MouseClick += PictureBoxMouseClick;
DoubleBuffered = true;
this.BackgroundImage = Properties.Resources.map_bg;
}
private void PictureBoxMouseClick(object sender, MouseEventArgs e)
{
if (_dragAndDropStart)
{
if (Math.Abs(_oldX - e.X) <= 2 || Math.Abs(_oldY - e.Y) <= 2)
{
_dragAndDropStart = false;
_timerDragAndDrop.Stop();
_render.MoveCenter(_pictureBox.Left, _pictureBox.Top);
var img = _render.GetImage();
_pictureBox.Image = img;
_pictureBox.Left = 0;
_pictureBox.Top = 0;
}
else
{
return;
}
}
var point = _render.MouseAtPoint(e.X, e.Y);
if(point != null && PointClicked != null)
{
ClientMouseX = e.X;
ClientMouseY = e.Y;
PointClicked(this, point);
}
}
public async void RedrawAsync()
{
_pictureBox.Image = await _render.GetImageAsync();
}
public void Redraw()
{
_pictureBox.Image = _render.GetImage();
}
private void EditZoom(object sender, MouseEventArgs e)
{
int dx = e.X - this.Width / 2;
int dy = e.Y - this.Height / 2;
bool zoomEdited = false;
if(MouseState == MapDragAndDropStates.NONE)
{
dx = 0;
dy = 0;
}
if (e.Delta < 0)
{
zoomEdited = _render.ZoomMinus(dx, dy);
}
else
{
zoomEdited = _render.ZoomPlus(dx, dy);
}
if (zoomEdited)
{
_pictureBox.Image = _render.GetImage();
}
}
private void _timerDragAndDrop_Tick(object sender, EventArgs e)
{
int dx = 0;
int dy = 0;
if(_pictureBox.Left + _dX != _pictureBox.Left)
{
dx = _dX / 10;
_pictureBox.Left += dx;
}
if(_pictureBox.Top + _dY != _pictureBox.Top)
{
dy = _dY / 10;
_pictureBox.Top += dy;
}
}
private void OnMouseUp(object sender, MouseEventArgs e)
{
_pictureBox.Cursor = Cursors.Default;
if (MouseState == MapDragAndDropStates.NONE) return;
if (!_dragAndDropStart) {
if(e.Button == MouseButtons.Right)
{
_pictureBox.Image = _buffer;
var startPoint = _render.GetMapEventArgs(_oldX, _oldY);
var endPoint = _render.GetMapEventArgs(e.X, e.Y);
double no = Math.Max(startPoint.N, endPoint.N);
double so = Math.Min(startPoint.N, endPoint.N);
double es = Math.Max(startPoint.E, endPoint.E);
double ws = Math.Min(startPoint.E, endPoint.E);
if(RegionSelected != null)
{
var region = new MapRegion
{
N = no,
S = so,
E = es,
W = ws
};
RegionSelected(this, region);
}
}
return;
}
_dragAndDropStart = false;
_timerDragAndDrop.Stop();
_render.MoveCenter(_pictureBox.Left, _pictureBox.Top);
var img = _render.GetImage();
_pictureBox.Image = img;
_pictureBox.Left = 0;
_pictureBox.Top = 0;
}
private int _oldMovingX = 0;
private int _oldMovingY = 0;
private int _oldMovingWidth = 0;
private int _oldMovingHeight = 0;
private Rectangle _oldSelectedImage = new Rectangle();
private void OnMouseMove(object sender, MouseEventArgs e)
{
//if (MouseState == MapDragAndDropStates.NONE) return;
if (!_dragAndDropStart) {
if (e.Button == MouseButtons.Right && MouseState != MapDragAndDropStates.NONE)
{
int x = Math.Min(_oldX, e.X);
int y = Math.Min(_oldY, e.Y);
int width = Math.Max(_oldX, e.X) - x;
int height = Math.Max(_oldY, e.Y) - y;
Graphics g = Graphics.FromImage(_pictureBox.Image);
_selectedImage = Graphics.FromImage(_pictureBox.Image);
Brush brush = new SolidBrush(Color.FromArgb(120, 100, 100, 100));
g.DrawImage(_buffer, _oldSelectedImage, _oldSelectedImage, GraphicsUnit.Pixel);
g.FillRectangle(brush, new Rectangle(x, y, width, height));
_oldSelectedImage.X = x;
_oldSelectedImage.Y = y;
_oldSelectedImage.Width = width;
_oldSelectedImage.Height = height;
_pictureBox.Image = _pictureBox.Image;
} else if (_render.MouseAtPoint(e.X, e.Y) != null)
{
var point = _render.MouseAtPoint(e.X, e.Y);
_pictureBox.Cursor = Cursors.Hand;
if (!string.IsNullOrEmpty(point.ToolTip))
{
_lbToolTip.Left = e.X + 2;
_lbToolTip.Top = e.Y - _lbToolTip.Height - 3;
_lbToolTip.Text = point.ToolTip;
_lbToolTip.Visible = true;
}
}else
{
_pictureBox.Cursor = Cursors.Default;
_lbToolTip.Visible = false;
}
if (MouseMoving != null)
{
var arg = _render.GetMapEventArgs(e.X, e.Y);
if (arg != null) MouseMoving(this, arg);
}
return;
}
_lbToolTip.Visible = false;
if (e.Button == MouseButtons.None)
{
_dragAndDropStart = false;
_timerDragAndDrop.Stop();
_render.MoveCenter(_pictureBox.Left, _pictureBox.Top);
var img = _render.GetImage();
_pictureBox.Image = img;
_pictureBox.Left = 0;
_pictureBox.Top = 0;
return;
}
if (MouseState == MapDragAndDropStates.NONE) return;
_dX = e.X - _oldX;
_dY = e.Y - _oldY;
}
private Bitmap _buffer;
private Graphics _selectedImage;
private void OnMouseDown(object sender, MouseEventArgs e)
{
if (MouseState == MapDragAndDropStates.NONE) return;
if(e.Button == MouseButtons.Left) {
_pictureBox.Cursor = Cursors.NoMove2D;
_dragAndDropStart = true;
_oldX = e.X;
_oldY = e.Y;
_timerDragAndDrop.Start();
}else if(e.Button == MouseButtons.Right)
{
_pictureBox.Cursor = Cursors.Cross;
_oldX = e.X;
_oldY = e.Y;
_buffer = new Bitmap(_pictureBox.Image);
_oldSelectedImage.X = 0;
_oldSelectedImage.Y = 0;
_oldSelectedImage.Width = 0;
_oldSelectedImage.Height = 0;
//Graphics g = Graphics.FromImage(_buffer);
//g.DrawImage(_pictureBox.Image, new Rectangle(0, 0, _pictureBox.Width, _pictureBox.Height), new Rectangle(0, 0, _pictureBox.Width, _pictureBox.Height), GraphicsUnit.Pixel);
}
}
private async void OnResize(object sender, EventArgs e)
{
_pictureBox.Width = this.Width;
_pictureBox.Height = this.Height;
_render.Width = this.Width;
_render.Height = this.Height;
if (!_render.WasRender)
{
var defaultZoomInformation = _repo.GetZoomInformation(MapConfig.DefaultZoom);
int xC = defaultZoomInformation.MaxX * defaultZoomInformation.TitleWidth / 2;
int yC = defaultZoomInformation.MaxY * defaultZoomInformation.TitleHeight / 2;
_render.LookAt(xC, yC);
}
_pictureBox.Image = _render.GetImage();// await UpdateMapImage();
}
public Image GetMapImage()
{
return _pictureBox.Image;
}
public void LookAt(DPoint point)
{
_render.LookAt(point);
_pictureBox.Image = _render.GetImage();
}
public void SetPoint(DPoint point)
{
if (_render.Points == null) _render.Points = new List<DPoint>();
_render.Points.Add(point);
_repo.ClearCache();
}
public void SetPoints(List<DPoint> points)
{
if (_render.Points == null) _render.Points = new List<DPoint>();
_render.Points.AddRange(points);
_repo.ClearCache();
}
public async void ClearPoints()
{
_render.Points = new List<DPoint>();
_repo.ClearCache();
_pictureBox.Image = _render.GetImage();
}
private async Task<Image> UpdateMapImage()
{
if (!_render.WasRender)
{
var defaultZoomInformation = _repo.GetZoomInformation(MapConfig.DefaultZoom);
int xC = defaultZoomInformation.MaxX * defaultZoomInformation.TitleWidth / 2;
int yC = defaultZoomInformation.MaxY * defaultZoomInformation.TitleHeight / 2;
_render.LookAt(xC, yC);
}
return await _render.GetImageAsync();
//;
}
}
}
<file_sep>/LeoBase/Components/CustomControls/SearchPanels/SearchPanelContainer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LeoBase.Components.CustomControls.Interfaces;
namespace LeoBase.Components.CustomControls.SearchPanels
{
public partial class SearchPanelContainer : UserControl, ISearchPanel
{
private HideSearchPanelBtn hideBtn;
public bool SearchButtonVisible {
get
{
return hideBtn.Visible;
}
set
{
hideBtn.Visible = value;
}
}
public SearchPanelContainer()
{
InitializeComponent();
hideBtn = new HideSearchPanelBtn();
this.Dock = DockStyle.Fill;
hideBtn.OnClick += () =>
{
if (OnHideClick != null) OnHideClick();
};
tableLayoutPanel1.Controls.Add(hideBtn, 0, 0);
hideBtn.Margin = new Padding(2, 2, 2, 2);
tableLayoutPanel1.HorizontalScroll.Enabled = false;
tableLayoutPanel1.HorizontalScroll.Visible = false;
}
public Control Control
{
get
{
return this;
}
}
public event Action OnHideClick;
public event Action OnSearchClick;
protected object SearchData { get; set; }
private IClearable _control;
public void SetCustomSearchPanel(IClearable control)
{
control.Dock = DockStyle.Fill;
_control = control;
tableLayoutPanel1.Controls.Add(control.GetControl(), 0, 1);
control.GetControl().Margin = new Padding(2, 2, 2, 2);
var bmp = new Bitmap(tableLayoutPanel1.Width, tableLayoutPanel1.Height);
Graphics g = Graphics.FromImage(bmp);
Color borderColor = Color.FromArgb(0xcecbc6);
Color shadowBorderColor = Color.FromArgb(0xe6e5e1);
Pen borderPen = new Pen(borderColor, 2);
Pen shadowPen = new Pen(shadowBorderColor, 2);
g.DrawLine(borderPen, new Point(0, hideBtn.Height + 1), new Point(this.Width, hideBtn.Height + 1));
g.DrawLine(borderPen, new Point(0, 0), new Point(this.Width, this.Height));
tableLayoutPanel1.BackgroundImage = bmp;
control.GetControl().BackgroundImage = bmp;
}
private void btnSearchGO_Click(object sender, EventArgs e)
{
if(OnSearchClick != null)
{
OnSearchClick();
}
}
private void btnClearSearchPanel_Click(object sender, EventArgs e)
{
ClearPanel();
if (OnSearchClick != null) OnSearchClick();
}
protected void ClearPanel()
{
_control.Clear();
}
//protected override void OnPaintBackground(PaintEventArgs e)
//{
// base.OnPaintBackground(e);
// Color borderColor = Color.FromArgb(0xcecbc6);
// Color shadowBorderColor = Color.FromArgb(0xe6e5e1);
// Pen borderPen = new Pen(borderColor, 1);
// Pen shadowPen = new Pen(shadowBorderColor, 1);
// e.Graphics.DrawLine(borderPen, new Point(0, hideBtn.Height + 1), new Point(this.Width, hideBtn.Height + 1));
// e.Graphics.DrawLine(borderPen, new Point(this.Width - 2, 0), new Point(this.Width - 2, this.Height));
// e.Graphics.DrawLine(shadowPen, new Point(0, hideBtn.Height + 2), new Point(this.Width, hideBtn.Height + 2));
//}
}
}
| 5fe104fb5622cadca0fbf993e45d8a4809fb847c | [
"C#"
] | 291 | C# | iliy/LeoBase | 890f337f51a942db737812251323dc638886d55b | 8c6a094b5594e24fdd05838c79533a6cf714b857 |
refs/heads/master | <repo_name>spbsu-student-projects/permanent<file_sep>/readme_english.md
# permanent
## What is it?
permanent is a program for counting [the permanent](https://en.wikipedia.org/wiki/Permanent "Permanent") of a matrix using Ryser's formula with `O(2^n * n^2)` time complexity. Not only numbers but also polynomials in many variables can be the elements of the matrix.
### What do we mean by a polynomial?
By a polynomial we mean an arithmetical expression, which doesn't contain spaces written with the use of `+`,`-`,`*` and `^` signs
with operators which are polynomials made of variables and brackets (the second term in operator `^` must be a positive integer
and the first term mustn't be an integer). By a variable we mean any sequence of symbols which doesn't contain arithmetic signs
but contains at least one symbol different from `0..9` and `.`. Any variable as well as any number
is considered a polynomial. The multiplication sign can't be skipped: for example, `1.5x` is an incorrect construction because the program
will take it as a single variable. The right way to write it is `1.5*x`.
## How to use it?
The program reads from the standard input stream and returns the result into the output stream.
Firstly, you should write one number `n`, the size of the matrix the permanent of which is counted (if `n > 14`,
the program will work too much time). Then `n` strings containing `n` polynomials separated by spaces should follow.
The output consists of one polynomial - the permanent of the matrix. For example:
~~~
\\stdin
3
(semen+svyat)^2 x 1
(semen-svyat)^2 0 1
1*ivan_kazmenko 1 0
\\stdout
2*svyat^2+2*semen^2+x*ivan_kazmenko
~~~
## And what is it needed for?
I don't know :)
<file_sep>/Source.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <vector>
#include <map>
#include <algorithm>
#include <set>
#include <math.h>
#include "polynom.h"
#include <string>
#include <fstream>
#include <ctime>
#include <iomanip>
using namespace std;
string s;
vector<vector<polynom> > matr;
int n;
vector<int> perm;
polynom res;
int main(){
n = 0;
cin >> n;
matr.resize(n);
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
cin >> s;
matr[i].push_back(polynom_make_polynom(s));
}
}
int pow2 = 1 << n;
for (int i = 0; i < pow2; i++) {
vector<bool> take(n);
int x = i;
int s = 0;
for (int j = 0; j < n; j++) {
if (x == 0) break;
if (x % 2) {
take[j] = true;
s++;
}
x /= 2;
}
polynom summator;
if (s % 2 != 0) summator = polynom(-1);
else summator = polynom(1);
for (int j = 0; j < n; j++) {
polynom sum;
for (int k = 0; k < n; k++) {
if (take[k]) sum += matr[j][k];
}
summator *= sum;
}
res += summator;
}
if (n % 2 != 0) res = res * polynom(-1);
if (n == 0) res = polynom(0);
cout << res << endl;
return 0;
}
<file_sep>/polynom.h
#pragma once
#include <vector>
#include <string>
#include <map>
#include <sstream>
#include <iostream>
class monom {
private:
std::vector<int> powers;
public:
monom();
monom(int);
monom(int, int);
void resize();
int get_power(int);
int get_power();
monom& operator*=(monom);
monom& operator^=(int);
monom& operator%=(monom);
monom& operator/=(monom);
friend monom operator*(monom, monom);
friend monom operator^(monom, int);
friend monom operator%(monom, monom);
friend monom operator/(monom, monom);
friend bool operator<(monom, monom);
friend bool operator>(monom, monom);
friend bool operator==(monom, monom);
friend bool operator!=(monom, monom);
friend bool operator<=(monom, monom);
friend bool operator>=(monom, monom);
friend std::ostream& operator<<(std::ostream&, monom);
};
class polynom {
private:
std::map<monom, long double> monoms;
void clean();
public:
polynom();
polynom(long double);
polynom(monom, long double);
polynom& operator+=(polynom&);
polynom& operator-=(polynom&);
polynom& operator*=(polynom&);
polynom& operator^=(int);
//polynom& operator%=(monom);
//polynom& operator/=(monom);
//polynom& operator%=(polynom);
//polynom& operator/=(polynom);
friend polynom operator+(polynom, polynom);
friend polynom operator-(polynom, polynom);
friend polynom operator*(polynom, polynom);
friend polynom operator^(polynom, int);
//friend polynom operator%(polynom, monom);
//friend polynom operator/(polynom, monom);
//friend polynom operator%(polynom, polynom);
//friend polynom operator/(polynom, polynom);
friend std::ostream& operator<<(std::ostream&, polynom&);
};
extern polynom polynom_make_polynom(std::string&, int start = 0, int end = 1e9);
extern int polynom_make_int(std::string&, int start = 0, int end = 1e9);
extern long double string_to_real(std::string&);
<file_sep>/Makefile
compile: Source.cpp polynom.cpp polynom.h
g++ -O2 -std=c++11 Source.cpp polynom.cpp -o permanent.exe<file_sep>/README.md
# permanent
## Что это?
permanent - это программа для расчёта [перманента](https://ru.wikipedia.org/wiki/%D0%9F%D0%B5%D1%80%D0%BC%D0%B0%D0%BD%D0%B5%D0%BD%D1%82 "Перманент") матрицы с помощью формулы Райзера со сложностью **O(2^n*n^2)**. Однако элементами матрицы могут быть не только обычные числа, но и многочлены от произвольного числа переменных.
### Что мы понимаем под многочленом
Под многочленом мы понимаем арифметическое выражение, записанное с использованием знаков `+`, `-`, `*` и `^` с операторами-многочленами от переменных и скобок (второй член в операторе `^` должен быть целым положительным числом, при этом первый не должен быть числом), не содержащее пробелов. Переменной считается любая последовательность символов, не содержащая знаков арифметических выражений и содержащая хотя бы один символ, отличный от `0...9` и точки. Всякая переменная, как и всякое число, считается многочленом.
Знак умножения не может быть опущен: так, `1.5x` - неверная конструкция, программа воспримет это как единую переменную. Правильно: `1.5*x`.
## Как это использовать?
Программа читает из стандартного входного потока, и выдаёт результат в стандартный выходной поток. Во входной поток необходимо сначала передать число `n` - размер матрицы, у которой считается перманент (при `n > 14` программа работает слишком долго). Далее должны следовать `n` строк, содержащие `n` многочленов, разделённых пробелами. Вывод состоит из одного многочлена - перманента введённой матрицы.
Например:
~~~
\\stdin
3
(semen+svyat)^2 x 1
(semen-svyat)^2 0 1
1*ivan_kazmenko 1 0
\\stdout
2*svyat^2+2*semen^2+x*ivan_kazmenko
~~~
## И зачем это вообще нужно?
Я не знаю :)
<file_sep>/polynom.cpp
#include "polynom.h"
std::vector<std::string> variables;
//Monoms//
monom::monom() {
powers.resize(variables.size());
}
monom::monom(int variable) {
powers.resize(variables.size());
powers[variable] = 1;
}
monom::monom(int variable, int power) {
powers.resize(variables.size());
powers[variable] = power;
}
void monom::resize() {
powers.resize(variables.size());
}
int monom::get_power() {
int sum = 0;
for (int power : powers) sum += power;
return sum;
}
monom& monom::operator*=(monom right) {
resize();
right.resize();
for (int i = 0; i < (int)variables.size(); i++) {
powers[i] += right.powers[i];
}
return *this;
}
monom& monom::operator^=(int power) {
monom answer = (*this) ^ power;
powers = answer.powers;
return *this;
}
monom& monom::operator%=(monom right) {
resize();
right.resize();
int number_of_times = -1;
for (int i = 0; i < (int)variables.size(); i++) {
if (right.powers[i] > 0) {
if (number_of_times == -1 || number_of_times > powers[i] / right.powers[i]) {
number_of_times = powers[i] / right.powers[i];
}
}
}
for (int i = 0; i < (int)variables.size(); i++) {
powers[i] -= number_of_times * right.powers[i];
}
return *this;
}
monom& monom::operator/=(monom right) {
monom answer = (*this) / right;
powers = answer.powers;
return *this;
}
monom operator*(monom left, monom right) {
monom answer = left;
answer *= right;
return answer;
}
monom operator^(monom left, int power) {
if (power == 0) return monom();
monom answer = left ^ (power / 2);
answer *= answer;
if (power % 2 != 0) answer *= left;
return answer;
}
monom operator%(monom left, monom right) {
monom answer = left;
answer %= right;
return answer;
}
monom operator/(monom left, monom right) {
left.resize();
right.resize();
monom mod = left % right;
monom answer = left;
for (int i = 0; i < (int)variables.size(); i++) {
answer.powers[i] -= mod.powers[i];
answer.powers[i] /= right.powers[i];
}
return answer;
}
bool operator<(monom a, monom b) {
a.resize();
b.resize();
int delta = a.get_power() - b.get_power();
if (delta != 0) {
return delta > 0;
}
for (int i = 0; i < (int)variables.size(); i++) {
delta = a.powers[i] - b.powers[i];
if (delta != 0) {
return delta > 0;
}
}
return false;
}
bool operator>(monom a, monom b) {
return b < a;
}
bool operator==(monom a, monom b) {
return !((a < b) || (a > b));
}
bool operator!=(monom a, monom b) {
return !(a == b);
}
bool operator<=(monom a, monom b) {
return !(a > b);
}
bool operator>=(monom a, monom b) {
return !(a < b);
}
std::ostream& operator<<(std::ostream& os, monom a) {
a.resize();
int all_power = a.get_power();
for (int i = 0; i < (int)variables.size(); i++) {
all_power -= a.powers[i];
if (a.powers[i] > 0) os << variables[i];
if (a.powers[i] > 1) os << "^" << a.powers[i];
if (all_power > 0 && a.powers[i] > 0) os << "*";
}
return os;
}
//Polynoms//
void polynom::clean() {
std::map<monom, long double> new_monoms;
for (auto a : monoms) {
if (a.second != 0) {
new_monoms[a.first] = a.second;
}
}
monoms = new_monoms;
}
polynom::polynom() {
}
polynom::polynom(long double num) {
monoms[monom()] = num;
}
polynom::polynom(monom a, long double num) {
monoms[a] = num;
}
polynom& polynom::operator+=(polynom& right) {
for (auto a : right.monoms) {
monoms[a.first] += a.second;
}
clean();
return *this;
}
polynom& polynom::operator-=(polynom& right) {
for (auto a : right.monoms) {
monoms[a.first] -= a.second;
}
clean();
return *this;
}
polynom& polynom::operator*=(polynom& right) {
polynom answer = (*this) * right;
monoms = answer.monoms;
return *this;
}
polynom& polynom::operator^=(int power) {
polynom answer = (*this) ^ power;
monoms = answer.monoms;
return *this;
}
polynom operator+(polynom left, polynom right) {
polynom answer = left;
answer += right;
return answer;
}
polynom operator-(polynom left, polynom right) {
polynom answer = left;
answer -= right;
return answer;
}
polynom operator*(polynom left, polynom right) {
polynom answer;
for (auto a : left.monoms) {
for (auto b : right.monoms) {
answer.monoms[a.first * b.first] += a.second * b.second;
}
}
answer.clean();
return answer;
}
polynom operator^(polynom left, int power) {
if (power == 0) return polynom(1);
polynom answer = left ^ (power / 2);
answer *= answer;
if (power % 2 != 0) answer *= left;
return answer;
}
std::ostream& operator<<(std::ostream& os, polynom& poly) {
poly.clean();
int all_monoms = 0;
for (auto a : poly.monoms) {
if (all_monoms > 0 && a.second > 0) os << "+";
if (a.second == -1) os << "-";
else if (a.second != 1) {
os << a.second;
if (a.first != monom()) os << "*";
}
if (a.first == monom() && (a.second == -1 || a.second == 1)) os << 1;
os << a.first;
all_monoms++;
}
if (all_monoms == 0) os << 0;
return os;
}
//Miscellaneous//
polynom polynom_make_polynom(std::string& s, int start, int end) {
if (end > (int)s.size()) end = s.size();
if (start >= end) return polynom();
//+, -
int balance = 0;
for (int i = end - 1; i >= start; i--) {
if (s[i] == '(') balance++;
if (s[i] == ')') balance--;
if (balance == 0) {
if (s[i] == '+') return polynom_make_polynom(s, start, i) + polynom_make_polynom(s, i + 1, end);
if (s[i] == '-') return polynom_make_polynom(s, start, i) - polynom_make_polynom(s, i + 1, end);
}
}
//*
balance = 0;
for (int i = end - 1; i >= start; i--) {
if (s[i] == '(') balance++;
if (s[i] == ')') balance--;
if (balance == 0) {
if (s[i] == '*') return polynom_make_polynom(s, start, i) * polynom_make_polynom(s, i + 1, end);
}
}
//^ (left)
balance = 0;
for (int i = start; i < end; i++) {
if (s[i] == '(') balance++;
if (s[i] == ')') balance--;
if (balance == 0) {
if (s[i] == '^') return polynom_make_polynom(s, start, i) ^ polynom_make_int(s, i + 1, end);
}
}
//()
if (s[start] == '(' || s[end - 1] == ')') {
if (s[start] == '(') start++;
if (s[end - 1] == ')') end--;
return polynom_make_polynom(s, start, end);
}
//number or variable
bool not_a_number = false;
for (int i = start; i < end; i++) {
if (s[i] != '.' && (s[i] < '0' || s[i] > '9')) not_a_number = true;
}
if (not_a_number) {
std::string variable = s.substr(start, end - start);
for (int i = 0; i < (int)variables.size(); i++) {
if (variables[i] == variable) return polynom(monom(i), 1);
}
variables.push_back(variable);
return polynom(monom((int)variables.size() - 1), 1);
}
else {
std::string number = s.substr(start, end - start);
return polynom(string_to_real(number));
}
}
int polynom_make_int(std::string& s, int start, int end) {
if (end > (int)s.size()) end = s.size();
if (start >= end) return 0;
//+, -
int balance = 0;
for (int i = end - 1; i >= start; i--) {
if (s[i] == '(') balance++;
if (s[i] == ')') balance--;
if (balance == 0) {
if (s[i] == '+') return polynom_make_int(s, start, i) + polynom_make_int(s, i + 1, end);
if (s[i] == '-') return polynom_make_int(s, start, i) - polynom_make_int(s, i + 1, end);
}
}
//*
balance = 0;
for (int i = end - 1; i >= start; i--) {
if (s[i] == '(') balance++;
if (s[i] == ')') balance--;
if (balance == 0) {
if (s[i] == '*') return polynom_make_int(s, start, i) * polynom_make_int(s, i + 1, end);
}
}
//()
if (s[start] == '(' || s[end - 1] == ')') {
if (s[start] == '(') start++;
if (s[end - 1] == ')') end--;
return polynom_make_int(s, start, end);
}
//number
std::string number = s.substr(start, end - start);
return string_to_real(number);
}
long double string_to_real(std::string& s) {
std::stringstream sstr;
long double answer;
sstr.str(s);
sstr >> answer;
return answer;
}
| e8019dc50d8be7b2af4b1777a2362eef4718dda0 | [
"Markdown",
"Makefile",
"C++"
] | 6 | Markdown | spbsu-student-projects/permanent | 86e8d9c185fa075d910e4fe76a8236297d838ae1 | dad2a39d797434b1f7afed05d26933f13f10faf9 |
refs/heads/master | <file_sep>import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import { faTrashAlt } from "@fortawesome/free-regular-svg-icons";
import { faPlusSquare } from "@fortawesome/free-solid-svg-icons";
import { icollection } from 'src/app/interfaces/icollection';
import { idocument } from 'src/app/interfaces/idocument';
import { ifield } from 'src/app/interfaces/ifield';
import { UiService } from 'src/app/services/ui.service';
@Component({
selector: 'app-add-document',
templateUrl: './add-document.component.html',
styleUrls: ['./add-document.component.scss']
})
export class AddDocumentComponent implements OnInit {
error = "Please enter a proper name"; // display document name errors
@Input() ShowAddDocument: Boolean = false
@Input() collection: icollection = {
name: "",
documents: []
}; // to show parent path
faTrashAlt = faTrashAlt;
faPlusSquare = faPlusSquare;
@Input() document: idocument = {
name: "",
fields: []
}
fields: ifield[] = [
{ fieldName: "", fieldType: "String", fieldValue: "" },
];
/**
* Event Handlers
*/
@Output() CancelClicked = new EventEmitter();
@Output() SaveClicked = new EventEmitter();
document_name_error: boolean = false;
constructor(private uiService: UiService) { }
ngOnInit(): void {
}
AddField() {
this.fields.push({ fieldName: "", fieldType: "String", fieldValue: "" });
}
RemoveField(index: number) {
// console.log(index);
this.fields.splice(index, 1);
}
trackByIndex(index: number, obj: any): any {
return index;
}
Save(doClose: boolean) {
/**
* check if document name is duplicate
*/
let _documentNames = this.collection.documents.map(doc => doc.name);
let index = _documentNames.findIndex(name => {
return name == this.document.name;
})
console.log(_documentNames, index);
if (index !== -1) {
this.document_name_error = true;
this.error = "document name must be unique";
return;
} else {
this.document_name_error = false;
}
/**
* check if document name is proper
*/
if ((/[\s\&*()^%$#@!-\/\'\"\;\+]+/gmi.test(this.document.name) || this.document.name == "")) {
this.document_name_error = true;
this.error = "Please enter a proper name";
return;
} else {
this.document_name_error = false;
}
/**
* check if field names is duplicate
*/
let fieldNames = this.fields.map(field => field.fieldName);
if ((new Set(fieldNames)).size != fieldNames.length) {
// field names have duplicate values
this.uiService.showAlert({ title: 'Error', message: "<p class='alert-danger'>Field names of a document must be unique</p>" })
return;
}
/**
* check if fields are added
*/
if (this.fields.length < 1) {
this.uiService.showAlert({ title: "Warning", message: "Add at leat one field" });
} else {
/**
* check if field data is set completely
*/
if (!this.checkFields()) {
this.uiService.showAlert({ title: 'Wrong Data', message: 'Complete all the fields' })
return;
}
// bind fields to document
this.document.fields = this.fields;
// send data back
this.SaveClicked.emit({ document: this.document, doClose: doClose });
// reset the form
this.reset();
}
}
Cancel() {
// reset
this.document_name_error = false;
this.reset();
this.CancelClicked.emit();
}
reset() {
this.document = {
name: "",
fields: []
}
this.fields = [{ fieldName: "", fieldType: "String", fieldValue: "" }];
}
checkFields() {
// check all the entered fields
let fields_status: boolean = true; // true for all fields are set properly false otherwise
this.fields.forEach((val: ifield, index) => {
if ((/[\s\&*()^%$#@!-\/\'\"\;\+]+/gmi.test(val.fieldName) || val.fieldName == "") || ((/[\s\&*()^%$#@!-\/\'\"\;\+]+/gmi.test(val.fieldType) || val.fieldType == "")) || ((/[\s\&*()^%$#@!-\/\'\"\;\+]+/gmi.test(val.fieldValue) || val.fieldValue == ""))) {
fields_status = false;
}
});
return fields_status;
}
}
<file_sep>export interface iAlertData{
title:string;
message : string;
}<file_sep>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddDocumentComponent } from './components/add-document/add-document.component';
import { AddFieldDialogComponent } from './components/add-field-dialog/add-field-dialog.component';
import { MainComponent } from './components/main/main.component';
import { SingleFieldComponent } from './components/single-field/single-field.component';
const routes: Routes = [
{path: '' , component:MainComponent},
{path: 'document' , component:AddDocumentComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { idocument } from "./idocument";
export interface icollection{
name:string;
documents : idocument[]
}<file_sep>import { Component, Input, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ifield } from "../../interfaces/ifield";
@Component({
selector: 'app-single-field',
templateUrl: './single-field.component.html',
styleUrls: ['./single-field.component.scss'],
providers:[
{
provide:NG_VALUE_ACCESSOR,
useExisting:SingleFieldComponent,
multi:true
}
]
})
export class SingleFieldComponent implements OnInit ,ControlValueAccessor {
field: ifield = {
fieldName: "",
fieldType: "String",
fieldValue: ""
};
onChange: any = (value : ifield) => {}
onTouch: any = (value : ifield) => {}
constructor() { }
writeValue(obj: ifield): void {
this.field = obj;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
ngOnInit(): void {
}
}
<file_sep>import { idocument } from "./idocument";
export interface iAddDocumentResult{
document : idocument;
doClose : boolean;
}<file_sep>import { Component, Inject, Input, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { icollection } from 'src/app/interfaces/icollection';
import { UiService } from 'src/app/services/ui.service';
@Component({
selector: 'app-add-collection-dialog',
templateUrl: './add-collection-dialog.component.html',
styleUrls: ['./add-collection-dialog.component.scss']
})
export class AddCollectionDialogComponent implements OnInit {
new_name :string = "";
hasError:boolean = false;
error :string = "";
constructor(private dialogRef: MatDialogRef<AddCollectionDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: {collection_names:string[];}, private uiService: UiService
) { }
ngOnInit(): void {
}
closeDialog() {
this.dialogRef.close();
}
Save() {
// check if collection name is uique
let index = this.data.collection_names.findIndex(name =>{
return name == this.new_name
});
if(index !== -1){
// collection name is duplicate
this.hasError = true;
this.error = "collection name must be unique";
return;
}
// check if name is valid
if (!(/[\s\&*()^%$#@!-\/\'\"\;\+]+/gmi.test(this.new_name) || this.new_name == ''))
this.dialogRef.close(this.new_name);
else{
this.error = "Entered value is not a propper collection name";
this.hasError = true;
}
}
}
<file_sep>export interface ifield{
fieldName:string;
fieldType:string;
fieldValue:any; // there is multiple types for field
}<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ifield } from 'src/app/interfaces/ifield';
import { UiService } from '../../services/ui.service';
import { faTrashAlt } from "@fortawesome/free-regular-svg-icons";
@Component({
selector: 'app-field',
templateUrl: './field.component.html',
styleUrls: ['./field.component.scss']
})
export class FieldComponent implements OnInit {
// declares which button is clicked
@Input() fields: ifield[] = []
@Output() OnAddField = new EventEmitter();
@Output() OnAddCollection = new EventEmitter(); // because Start collection is repeated in fields box we should emit its function on main Component so we need a emitter
@Output() OnRemoveField = new EventEmitter();
faTrashAlt = faTrashAlt;
constructor(private uiService: UiService) { }
ngOnInit(): void {
}
onAddFieldClicked() {
this.OnAddField.emit();
}
onAddCollectionClicked() {
this.OnAddCollection.emit();
}
RemoveField(field:ifield){
this.OnRemoveField.emit(field);
}
}
<file_sep>import { Component, OnInit,Input , Output , EventEmitter } from '@angular/core';
import { faPlus , faMinusCircle } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-icon-button',
templateUrl: './icon-button.component.html',
styleUrls: ['./icon-button.component.scss']
})
export class IconButtonComponent implements OnInit {
@Input() text:string = "Click"; // default text
@Input() icon:string = "";
@Input() extra_class= "btn-icon";
@Input() uppercase:boolean = true; // by default make text uppercase
@Output() OnButtonClicked = new EventEmitter();
faPlus = faPlus;
faMinusCircle = faMinusCircle;
constructor() { }
ngOnInit(): void {
}
OnClick() {
this.OnButtonClicked.emit();
}
}
<file_sep>import { Component, Input, OnInit, Output,EventEmitter } from '@angular/core';
import { idocument } from 'src/app/interfaces/idocument';
import {UiService} from "../../services/ui.service";
import { faEllipsisV } from '@fortawesome/free-solid-svg-icons';
import { faAngleRight } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-document',
templateUrl: './document.component.html',
styleUrls: ['./document.component.scss']
})
export class DocumentComponent implements OnInit {
@Input() documents:idocument[] = []; // documents to list
@Input() selected_index : number = -1;
@Output() OnDocumentClicked = new EventEmitter(); // called when single document clicked
@Output() OnAddDocumet = new EventEmitter(); // called when add document button clicked
@Output() OnRemoveDocumet = new EventEmitter(); // called when remove document button clicked
faEllipsisV = faEllipsisV;
faAngleRight = faAngleRight;
constructor(private uiService : UiService ) { }
ngOnInit(): void {
}
onAddDocumentClicked(){
this.OnAddDocumet.emit();
}
documentSelected(document:idocument){
this.OnDocumentClicked.emit(document);
}
RemoveDocument(document:idocument){
this.OnRemoveDocumet.emit(document);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import {FormsModule} from "@angular/forms";
// angular material components
import {MatInputModule} from '@angular/material/input';
import {MatSelectModule} from '@angular/material/select';
import {MatDialog , MatDialogModule, MatDialogRef , MAT_DIALOG_DATA} from '@angular/material/dialog';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component';
import { MainComponent } from './components/main/main.component';
import { CollectionComponent } from './components/collection/collection.component';
import { DocumentComponent } from './components/document/document.component';
import { FieldComponent } from './components/field/field.component';
import { IconButtonComponent } from './components/icon-button/icon-button.component';
import { AddDocumentComponent } from './components/add-document/add-document.component';
import { SingleFieldComponent } from './components/single-field/single-field.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AddFieldDialogComponent } from './components/add-field-dialog/add-field-dialog.component';
import { AddCollectionDialogComponent } from './components/add-collection-dialog/add-collection-dialog.component';
import { AlertDialogComponent } from './components/alert-dialog/alert-dialog.component';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
MainComponent,
CollectionComponent,
DocumentComponent,
FieldComponent,
IconButtonComponent,
AddDocumentComponent,
SingleFieldComponent,
AddFieldDialogComponent,
AddCollectionDialogComponent,
AlertDialogComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FontAwesomeModule,
FormsModule,
BrowserAnimationsModule,
MatInputModule,
MatSelectModule,
MatDialogModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Observable } from 'rxjs';
import { AddCollectionDialogComponent } from '../components/add-collection-dialog/add-collection-dialog.component';
import { AddFieldDialogComponent } from '../components/add-field-dialog/add-field-dialog.component';
import { AlertDialogComponent } from '../components/alert-dialog/alert-dialog.component';
import { iAlertData } from '../interfaces/iAlertData';
import { icollection } from '../interfaces/icollection';
import { idocument } from '../interfaces/idocument';
import { ifield } from '../interfaces/ifield';
@Injectable({
providedIn: 'root'
})
export class UiService {
constructor(private dialog: MatDialog) { }
/**
* opens add collection dialog
*
* @param collections string array of collection names to check if the collection name is duplicate
* @returns the observable of string name of new collection
*/
openAddCollectionDialog(collections:string[]): Observable<string> {
const dialogRef = this.dialog.open(AddCollectionDialogComponent, {
data: {collection_names : collections},
});
return dialogRef.afterClosed();
}
/**
* opens add Field name
* @param fieldnames string name of field names to check if field name is duplicate
* @returns observale of field in ifield interface
*/
openAddFieldDialog(fieldnames:string[]): Observable<ifield> {
const dialogRef = this.dialog.open(AddFieldDialogComponent, {
width: 'auto',
data: {fieldnames : fieldnames}
});
return dialogRef.afterClosed();
}
/**
*
* @param data the title and message to show in iAlertData interface {title:'YOUR TITLE', message:'YOUR MESSAGE'}
*
*/
showAlert(data: iAlertData) {
const dialogRef = this.dialog.open(AlertDialogComponent, {
width: "auto",
data: data
});
}
}
<file_sep>import { ifield } from "./ifield";
export interface idocument{
name : string;
fields:ifield[]
}<file_sep>import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { iAlertData } from 'src/app/interfaces/iAlertData';
@Component({
selector: 'app-alert-dialog',
templateUrl: './alert-dialog.component.html',
styleUrls: ['./alert-dialog.component.scss']
})
export class AlertDialogComponent implements OnInit {
constructor(private dialogRef:MatDialogRef<AlertDialogComponent> ,
@Inject(MAT_DIALOG_DATA) public data : iAlertData
) { }
ngOnInit(): void {
}
closeDialog(){
this.dialogRef.close();
}
}
<file_sep># The Angular test task
this project is a test task of **<NAME>** software development company. the framework used is **Angular**.
<br><br>
## Table of Contents
- [Components](#components)
- [3 main components](#3-main-components)
- [Tree view of the connections](#tree-view-of-the-connections)
- [Main Component](#main-component)
- [Collection](#collection)
- [Document](#document)
- [Field](#field)
- [Other Components](#other-components)
- [AddCollectionDialogComponent](#AddCollectionDialogComponent)
- [AddDocumentComponent](#AddDocumentComponent)
- [AddFieldDialogComponent](#AddFieldDialogComponent)
- [AlertDialogComponent](#AlertDialogComponent)
- [HeaderComponent](#HeaderComponent)
- [IconButtonComponent](#IconButtonComponent)
- [SingleFieldComponent](#SingleFieldComponent)
- [Interfaces](#Interfaces)
- [icollection](#icollection)
- [idocument](#idocument)
- [ifield](#ifield)
- [iAlertData](#iAlertData)
- [iAddDocumentResult](#iAddDocumentResult)
- [Services](#Services)
- [UI Services](#UI-Services)
<br><br>
## Components
### 3 main components
the whole project environment is built on main 3 components
- [Collections](#collection)
- [Documents](#document)
- [Fields](#field)
<br>
to handle the connections between these components there is a component called **Main Component**
<br>
#### Tree view of the connections
```
|-- Collection 1
| |-- document1
| | |-- field 1
| | |-- field 2
| | |-- ...
| |-- document2
| | |-- field 1
| | |-- field 2
| | |-- ...
|-- Collection 2
| |-- document1
| | |-- field 1
| | |-- field 2
| | |-- ...
| |-- document2
| | |-- field 1
| | |-- field 2
| | |-- ...
```
<br>
### Main Component
this is the base route of project and the app start from this component. it handles the connection between the 3 main components.
<br><br>
### Collection
Collection is a data structure that represents a *name* and array of documents.
### Document
Document is a data structure that represent a *name* and array of fields.
### Field
Field is a data structure that contains a *field name*, *field type* and *field value*.
<br><br><br>
### Other Components
#### AddCollectionDialogComponent
a dialog to add new collection which gets only the name of new collection and checks if the name is duplicate and if the entered string has special characters which is not allowed.
<br><br>
#### AddDocumentComponent
a component to add new document with corresponding fields. the component check if name of entered document is duplicate or names of entered fields are duplicate. if the entered strings have special characters which is not allowed.
<br><br>
#### AddFieldDialogComponent
a dialog which contains a [SingleFieldComponent](#SingleFieldComponent) to add new field that checks if the name of new field is duplicate and has special characters
<br><br>
#### AlertDialogComponent
a dialog to show message to user. the data to show implements [iAlertData](#ialertdata) interface
<br><br>
#### HeaderComponent
component to show the header of the final UI that only contains a title.
<br><br>
#### IconButtonComponent
a button which shows two icons : plus icon or minus icon. this component is used as start collection button, add document button and add field button
<br><br>
#### SingleFieldComponent
as mentioned the [fields](#field) has 3 variables which implements [ifield](#ifield) interface. this component is a form of 3 inputs of the fields data structure which is used in multiple parts of project. this component makes it easy to handle the form of adding field.
<br><br>
<br>
## Interfaces
for the data structures in this project there are some interface :
<br>
### icollection
represents data structure for [collection](#collection).
### idocument
represents data structure for [document](#document).
### ifield
represents data structure for [field](#field).
<br><br><br>
### iAlertData
data structure send for show alert function in [UI Service](#ui-services). contains a string title and a string message. the message also could be html code.
<br>
### iAddDocumentResult
data structure for data send back from add document component which contains the new document data and a boolean which indicates whether Save button or Save and add an other button on add document panel clicked.
<br><br><br>
## Services
there is one service in this project.
<br>
### UI Services
this service handles the dialogs interactions and also [add document](#AddDocumentComponent) panel
<br>
<file_sep>import { Component, OnInit , Inject } from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import { ifield } from 'src/app/interfaces/ifield';
@Component({
selector: 'app-add-field-dialog',
templateUrl: './add-field-dialog.component.html',
styleUrls: ['./add-field-dialog.component.scss']
})
export class AddFieldDialogComponent implements OnInit {
field:ifield = {
fieldName :"",
fieldType :"String",
fieldValue : null
}
error :string = "";
has_error : boolean = false;
constructor(
public dialogRef: MatDialogRef<AddFieldDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: {fieldnames : string[]}) {}
ngOnInit(): void {
}
closeDialog(){
this.dialogRef.close();
}
Save(){
// reset error
this.has_error = false;
/**
* check if field name is unique
*/
let index = this.data.fieldnames.findIndex(name =>{
return name == this.field.fieldName
})
if(index !== -1){
this.has_error = true;
this.error = "field names must be unique";
return;
}
/**
* check if field name is proper
*/
if ((/[\s\&*()^%$#@!-\/\'\"\;\+]+/gmi.test(this.field.fieldName) || this.field.fieldName == "")) {
this.has_error=true;
this.error = "Please enter a proper field name";
return;
}
this.dialogRef.close(this.field);
}
}
<file_sep>import { Component, OnInit, Input, Output,EventEmitter } from '@angular/core';
import { icollection } from 'src/app/interfaces/icollection';
import { UiService } from '../../services/ui.service';
import { faEllipsisV } from '@fortawesome/free-solid-svg-icons';
import { faAngleRight } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-collection',
templateUrl: './collection.component.html',
styleUrls: ['./collection.component.scss']
})
export class CollectionComponent implements OnInit {
// declares which button is clicked
@Input() collections: icollection[] = [
];
@Input() selected_index : number = -1;
@Output() OnCollectionSelected = new EventEmitter() ; // called when single collection clicked
@Output() OnAddCollection =new EventEmitter(); // called when start collection clicked
@Output() OnRemoveCollection = new EventEmitter(); // called when remove collection clicked
faEllipsisV = faEllipsisV;
faAngleRight = faAngleRight;
constructor(private uiService: UiService) { }
ngOnInit(): void {
}
onAddCollectionClicked() {
this.OnAddCollection.emit();
}
collectionSelected(collection:icollection){
this.OnCollectionSelected.emit(collection);
}
RemoveCollection(collection:icollection){
this.OnRemoveCollection.emit(collection);
}
}
<file_sep>/**
* Main Component
* this component is the base route of this project
* the component contains the main 3 components collections, documents and fields
*
*
*/
import { Component, Input, OnInit } from '@angular/core';
import { iAddDocumentResult } from 'src/app/interfaces/iAddDocumentResult';
import { icollection } from 'src/app/interfaces/icollection';
import { idocument } from 'src/app/interfaces/idocument';
import { ifield } from 'src/app/interfaces/ifield';
import { UiService } from 'src/app/services/ui.service';
import { faAngleRight } from "@fortawesome/free-solid-svg-icons";
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit {
ShowAddDocument: Boolean = false; // used to toggle the add document panel
selected_collection_index: number = -1; // used to add css classes to html
selected_document_index: number = -1;
// used to identify the selected collection to show the documents and fields
@Input() __collection: icollection = {
name: "",
documents: []
};
// the current selected document to show the fields ro remove
@Input() __document: idocument = {
name: "",
fields : []
}
/**
* all the collection is stored here
* to init the project i've added some fake data
*/
@Input() collections: icollection[] = [
{
name: "collection1",
documents: [
{ name: "c1doc1", fields: [{ fieldName: "f11", fieldType: "String", fieldValue: "v11" }] },
{ name: "c1doc2", fields: [{ fieldName: "f21", fieldType: "String", fieldValue: "v21" }] },
]
},
{
name: "collection2",
documents: [
{ name: "c2doc1", fields: [{ fieldName: "f12", fieldType: "String", fieldValue: "v12" }] },
{
name: "c2doc2", fields: [
{ fieldName: "f22", fieldType: "String", fieldValue: "v22" },
{ fieldName: "f62", fieldType: "String", fieldValue: "v22" },
{ fieldName: "f72", fieldType: "String", fieldValue: "v22" },
]
},
]
}
];
// font awesome inits
faAngleRight = faAngleRight;
// init ui service
constructor(private uiService: UiService) { }
ngOnInit(): void {
}
/**
* when user clicks on single collection the collection is stored in __collection variable
* @param collection
*/
CollectionSelected(collection: icollection) {
this.__document = { // reset the selected document
name: "",
fields : []
}
this.__collection = collection;
this.selected_collection_index = this.FindCollectionByName(collection.name);
this.selected_document_index = -1; // reset selected document index to remove correspoing css classes
}
/**
*
* @param document
*/
DoucmentSelected(document: idocument) {
this.__document = document;
this.selected_document_index = this.FindDocumentByName(document.name);
}
/**
* Called when Start collection button clicked
*/
AddCollection() {
// call add collection dialog to get the name of new collection
this.uiService.openAddCollectionDialog(this.collections.map(collection=>collection.name)).subscribe(name => {
if (name == '' || name == undefined)
return;
// check if name is unique
if (this.FindCollectionByName(name) !== -1) {
this.uiService.showAlert({ title: "warning", message: "<p class='alert-danger'> Collection name must be unique </p>" });
return;
}
// if is unique add to collections
this.collections.push({
name: name,
documents: []
});
});
}
/**
* removes a collection
* @param collection the collection to remove
*/
RemoveCollection(collection: icollection) {
// find index to remove
let index = this.FindCollectionByName(collection.name);
this.collections.splice(index, 1);
// reset the selected collection and document
this.__collection = {
name: "",
documents: []
}
this.__document = {
name: "",
fields: []
}
}
/**
* Open Add Document panel to add a document to current collection
*/
AddDocument() {
if (this.__collection.name == "")
this.uiService.showAlert({ title: "Warning", message: "No collection selected" });
else
this.ShowAddDocument = true;
}
/**
* removes a document
* @param document the document to remove
*/
RemoveDocument(document: idocument) {
// get the index to remove
let index = this.FindDocumentByName(document.name);
this.__collection.documents?.splice(index, 1);
// update the current collection
this.updateCollection();
// reset the selected document
this.__document = {
name: "",
fields: []
}
}
/**
* called when save button in add document panel clicked
* there is two status to save
* 1. save and close
* 2. save only
* @param params the data of new document and panel closing status in iAddDocumentResult interface {doClose , document}
*/
AddDocumentSaveClicked(params: iAddDocumentResult) {
// get the document and add to collection
// params = {document , doClose}
if (params.doClose)
this.ShowAddDocument = false; // close the add document
// add to current collection
this.__collection.documents?.push(params.document);
this.updateCollection();
}
AddDocumentCancelClicked() {
this.ShowAddDocument = false;
}
/**
* opens add field dialog
* the field is added to current document
*/
AddField() {
if (this.__document.name == "")
this.uiService.showAlert({ title: "Warning", message: "No document selected" });
else
this.uiService.openAddFieldDialog(this.__document.fields?.map(field=>field.fieldName)).subscribe(field => {
if (field.fieldName != "") {
this.__document.fields.push(field);
this.updateDocument();
}
});
}
/**
* removes a field
* @param field the field to remove
*/
RemoveField(field: ifield) {
// find the index to remove
let index = this.FindFieldByName(field.fieldName);
this.__document.fields.splice(index, 1);
// update the document
this.updateDocument();
}
/**
*
* @param name the name of collection to find
* @returns index number
*/
FindCollectionByName(name: string): number {
return this.collections.findIndex(col=>{
return col.name == name;
})
}
/**
*
* @param name the name of document to find
* @returns index number
*/
FindDocumentByName(name: string): number {
return this.__collection.documents.findIndex(doc=>{
return doc.name == name;
});
}
/**
*
* @param name the name of field to find
* @returns index number
*/
FindFieldByName(name: string): number {
return this.__document.fields.findIndex(field=>{
return field.fieldName == name;
})
}
/**
* each time the __collection and its data changed -> update the collections
*/
updateCollection() {
let index: number = this.FindCollectionByName(this.__collection.name);
this.collections[index] = this.__collection;
}
/**
* each time the __document and its data changed -> update the documents an collections
*/
updateDocument() {
let Col_index: number = this.FindCollectionByName(this.__collection.name);
let Doc_index: number = this.FindDocumentByName(this.__document.name);
if (this.__collection.documents !== undefined) {
this.__collection.documents[Doc_index] = this.__document;
this.collections[Col_index] = this.__collection;
}
}
}
| 57330df27d4f2f6611b9ffa9f463429f9d358e87 | [
"Markdown",
"TypeScript"
] | 19 | TypeScript | HNematiMovil/test_task | 3d7a13abcd26c6d95a3b39561e5c14d64bfab9d8 | c4200fdafbbd61a3085d6bdffc7ebe677596a869 |
refs/heads/master | <file_sep>package com.yhwxd.suguoqing.securitysetting2.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.yhwxd.suguoqing.securitysetting2.R;
import com.yhwxd.suguoqing.securitysetting2.bean.MainMenuItem;
import java.util.List;
public class MainMenuAdapter extends RecyclerView.Adapter<MainMenuAdapter.ViewHolder> {
private List<MainMenuItem> data;
private Context context;
private OnItemClickListener listener;
public void setListener(OnItemClickListener listener) {
this.listener = listener;
}
public MainMenuAdapter(List<MainMenuItem> data, Context context) {
super();
this.context = context;
this.data = data;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
if(context == null){
context = viewGroup.getContext();
}
View view = LayoutInflater.from(context).inflate(R.layout.main_menu,viewGroup,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder viewHolder, int i) {
viewHolder.imageView.setImageBitmap(data.get(i).getItemImg());
viewHolder.textView.setText(data.get(i).getItemText());
viewHolder.item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onItemClick(v,viewHolder.getAdapterPosition());
}
});
}
@Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView textView;
View item;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
textView = itemView.findViewById(R.id.menu);
item = itemView;
}
}
public interface OnItemClickListener{
void onItemClick(View view,int postion);
}
}
<file_sep>package com.yhwxd.suguoqing.securitysetting2.activity;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;
import android.widget.Toast;
import com.yhwxd.suguoqing.securitysetting2.R;
import com.yhwxd.suguoqing.securitysetting2.utils.SystemUtils;
public class InfoActivity extends AppCompatActivity {
private TextView model;
private TextView imei;
private TextView version;
private TextView version_soft;
private TextView blue_address;
private TextView wifi_address;
private TextView number;
private TextView rom;
private TextView ram;
private TextView level;
String Model = "";
String Imei = "";
String soft_version = "";
String phone_number = "";
static int levels;
TelephonyManager telephonyManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
initView();
}
private void initView() {
model = findViewById(R.id.model);
imei = findViewById(R.id.imei);
version = findViewById(R.id.version);
version_soft = findViewById(R.id.version_soft);
blue_address = findViewById(R.id.blue_address);
wifi_address = findViewById(R.id.wifi_address);
number = findViewById(R.id.number);
rom = findViewById(R.id.rom);
ram = findViewById(R.id.ram);
level = findViewById(R.id.level);
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
Model = Build.MODEL;
model.setText("机器型号 :" + Model);
//Imei = getImei();
checkPremission();
imei.setText("IMEI :"+Imei);
version.setText("操作系统 Android:"+Build.VERSION.RELEASE);
version_soft.setText("软件版本号:"+soft_version);
blue_address.setText("蓝牙地址 :"+ SystemUtils.GetLocalMacAddress());
wifi_address.setText("wifi MAC地址 :"+SystemUtils.getWifiMacAddress(this)[0]);
number.setText("电话号码:"+phone_number);
long TotalMemory = SystemUtils.getTotalMemory(this);
long AvailMemory = SystemUtils.getAvailMemory(this);
ram.setText("RAM:" + SystemUtils.formatSize(AvailMemory) + "/" + SystemUtils.formatSize(TotalMemory));
long[] RomMemroy = SystemUtils.getRomMemroy();
long totalyRom = SystemUtils.getTotalInternalMemorySize();
rom.setText("ROM:" + SystemUtils.formatSize(RomMemroy[1]) + "/" + SystemUtils.formatSize(totalyRom));
registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
level.setText("当前电量:"+levels);
/**
* 获取数据连接状态
*
* DATA_CONNECTED 数据连接状态:已连接
* DATA_CONNECTING 数据连接状态:正在连接
* DATA_DISCONNECTED 数据连接状态:断开
* DATA_SUSPENDED 数据连接状态:暂停
*/
// Button button = findViewById(R.id.data);
/*button.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onClick(View v) {
if(telephonyManager.getDataState() == TelephonyManager.DATA_DISCONNECTED){
telephonyManager.setDataEnabled(true);
}else {
telephonyManager.setDataEnabled(false);
}
}
});*/
}
public void checkPremission(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
} else {
Imei = telephonyManager.getDeviceId();// api 26 之前用getDeviceId,之后用getImei
if(Imei == null){
Imei = "设备不可用";
}
soft_version = telephonyManager.getDeviceSoftwareVersion();
if(soft_version == null){
soft_version = "软件版本不可用";
}
phone_number = telephonyManager.getLine1Number();
if(phone_number == null){
phone_number = "无";
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 1:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Imei = getImei();
checkPremission();
}else {
Toast.makeText(this, "没有权限", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
/**
* 电池电量
*/
public static BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
levels = intent.getIntExtra("level", 0);
// levels加%就是当前电量了
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(batteryReceiver);
}
}
<file_sep>package com.yhwxd.suguoqing.securitysetting2.adapter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.yhwxd.suguoqing.securitysetting2.R;
import com.yhwxd.suguoqing.securitysetting2.bean.AppInfo;
import java.util.List;
public class AppAdapter extends RecyclerView.Adapter<AppAdapter.ViewHolder> {
private static final String TAG = "AppAdapter";
private List<AppInfo> data;
private Context context;
private onItemClickListener listener;
// private View.OnClickListener moreListener;
private onMoreClickListner moreListener;
public AppAdapter(List<AppInfo> data, Context context) {
super();
this.data = data;
this.context = context;
}
public void setListener(onItemClickListener listener,onMoreClickListner moreListener) {
this.listener = listener;
this.moreListener = moreListener;
}
public interface onItemClickListener {
void onItemClick(String packageName);
}
public interface onMoreClickListner{
void onMoreClick(String packageName);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
if(context == null){
context = viewGroup.getContext();
}
View view = LayoutInflater.from(context).inflate(R.layout.app_item,viewGroup,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
viewHolder.icon.setImageBitmap(data.get(i).getIcon());
viewHolder.name.setText(data.get(i).getName());
viewHolder.isHide.setChecked(data.get(i).isHide());
viewHolder.isHide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String packageName = data.get(i).getPackageName();
listener.onItemClick(packageName);
}
});
viewHolder.more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String packageName = data.get(i).getPackageName();
moreListener.onMoreClick(packageName);
}
});
}
@Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView icon;
TextView name;
CheckBox isHide;
ImageButton more;
View item;
public ViewHolder(@NonNull View itemView) {
super(itemView);
item = itemView;
icon = itemView.findViewById(R.id.icon);
name = itemView.findViewById(R.id.name);
isHide = itemView.findViewById(R.id.checkbox);
more = itemView.findViewById(R.id.more);
}
}
}
<file_sep># SecuritySetting
======<br/>
控制设备,软件可否卸载,应用加锁,相机,各类开关,锁屏,截屏,状态栏,基本信息等<br/>
<img src = "https://github.com/Suguohei/SecuritySetting/blob/master/Screenshot_19700102-044733.png" width = "30%" hight = "30%"/>
<br/>
功能1.控制各类开关,锁屏等<br/>
<img src = "https://github.com/Suguohei/SecuritySetting/blob/master/Screenshot_19700102-045152.png" width = "30%" hight = "30%"/>
<br/>
功能2.开机密码,静音,状态栏下拉,重启,截图等<br/>
<img src = "https://github.com/Suguohei/SecuritySetting/blob/master/Screenshot_19700102-045302.png" width = "30%" hight = "30%"/>
<br/>
功能3.应用锁,应用可否卸载,应用可否隐藏<br/>
<img src = "https://github.com/Suguohei/SecuritySetting/blob/master/Screenshot_19700102-045316.png" width = "30%" hight = "30%"/>
<br/>
<img src = "https://github.com/Suguohei/SecuritySetting/blob/master/Screenshot_19700102-045324.png" width = "30%" hight = "30%"/>
<br/>
<img src = "https://github.com/Suguohei/SecuritySetting/blob/master/Screenshot_19700102-045343.png" width = "30%" hight = "30%"/>
<br/>
功能4.查看一些参数信息<br/>
<img src = "https://github.com/Suguohei/SecuritySetting/blob/master/Screenshot_19700102-045405.png" width = "30%" hight = "30%"/>
<br/>
功能5 设备恢复出产设置<br/>
<img src = "https://github.com/Suguohei/SecuritySetting/blob/master/Screenshot_19700102-045349.png" width = "30%" hight = "30%"/>
<br/>
功能1,其实只要在应用中获取DeviceAdmin就可以控制这些开关,但是,功能2,应用可否卸载,恢复出产设置,等,都需要设备为,DeviceOwner<br/>
所以,设置DeviceOwner的方法,我只知道可以用 adb 命令来实现,<br/>
adb shell dpm remove-active-admin com.yhwxd.suguoqing.securitysetting2/com.yhwxd.suguoqing.securitysetting2.bean.DeviceAdmin 移除<br/>
adb shell dpm set-device-owner com.yhwxd.suguoqing.securitysetting2/com.yhwxd.suguoqing.securitysetting2.bean.DeviceAdmin 添加<br/>
应用锁功能,是通过,UsageStatsManager 来判断,某个应用是否正在被打开。还有其他方法也可以判断应用是否处于前台,还是后台,我们给他记录下来<br/>
https://github.com/wenmingvs/AndroidProcess<br/>
<file_sep>package com.yhwxd.suguoqing.securitysetting2.bean;
import android.content.pm.ApplicationInfo;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.Parcelable;
import org.litepal.crud.DataSupport;
public class AppInfo extends DataSupport implements Parcelable {
private String packageName;
private Bitmap icon;
private ApplicationInfo applicationInfo;
private String name;
private boolean isHide;
private boolean isLock;
private boolean isUninstall;
public AppInfo() {
}
protected AppInfo(Parcel in) {
packageName = in.readString();
icon = in.readParcelable(Bitmap.class.getClassLoader());
applicationInfo = in.readParcelable(ApplicationInfo.class.getClassLoader());
name = in.readString();
isHide = in.readByte() != 0;
isLock = in.readByte() != 0;
isUninstall = in.readByte() != 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(packageName);
dest.writeParcelable(icon, flags);
dest.writeParcelable(applicationInfo, flags);
dest.writeString(name);
dest.writeByte((byte) (isHide ? 1 : 0));
dest.writeByte((byte) (isLock ? 1 : 0));
dest.writeByte((byte) (isUninstall ? 1 : 0));
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<AppInfo> CREATOR = new Creator<AppInfo>() {
@Override
public AppInfo createFromParcel(Parcel in) {
return new AppInfo(in);
}
@Override
public AppInfo[] newArray(int size) {
return new AppInfo[size];
}
};
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public Bitmap getIcon() {
return icon;
}
public void setIcon(Bitmap icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isHide() {
return isHide;
}
public void setHide(boolean hide) {
isHide = hide;
}
public boolean isLock() {
return isLock;
}
public void setLock(boolean lock) {
isLock = lock;
}
public boolean isUninstall() {
return isUninstall;
}
public void setUninstall(boolean uninstall) {
isUninstall = uninstall;
}
public ApplicationInfo getApplicationInfo() {
return applicationInfo;
}
public void setApplicationInfo(ApplicationInfo applicationInfo) {
this.applicationInfo = applicationInfo;
}
}
<file_sep>package com.yhwxd.suguoqing.securitysetting2;
import android.app.ActivityManager;
import android.app.Service;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import com.yhwxd.suguoqing.securitysetting2.activity.ScreetActivity;
import com.yhwxd.suguoqing.securitysetting2.utils.LockUtil;
import com.yhwxd.suguoqing.securitysetting2.utils.SpUtil;
import java.util.ArrayList;
import java.util.List;
public class LockService extends Service {
private static final String TAG = "LockService";
private Mybind mybind = new Mybind();
public LockService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
return mybind;
}
@Override
public void onCreate() {
super.onCreate();
mybind.startQuerryCurrentPackageName();
}
public class Mybind extends Binder{
public void startQuerryCurrentPackageName(){
//开启一个线程来不停获取包名
new Thread(new Mythread()).start();
}
}
public class Mythread implements Runnable {
@Override
public void run() {
while (true){
try{
Thread.sleep(500);
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}catch (Exception e){
}
}
}
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
//
if(msg.what == 1){
SpUtil spUtil = SpUtil.getInstance();
spUtil.init(LockService.this);
String lockAppPackageName = spUtil.getString("lockAppPackageName");
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
String packageName = getCurrentPackageName(LockService.this, activityManager);
boolean isLock = LockUtil.isLock(packageName);
if (!TextUtils.isEmpty(lockAppPackageName)) {
if (!TextUtils.isEmpty(packageName)) {
if (!lockAppPackageName.equals(packageName)) {
//再加多层判断,更加准确,如果返回了桌面,或者后台切换的时候
if (getHomes().contains(packageName) || packageName.contains("launcher") ) {
//这个包是自己不行,因为dialog界面packagename就是自己
if(!packageName.contains("securitysetting2")){
//这是设置相关的代码,表示是否设置了不锁这个应用,可忽略
if (!isLock) {
//加锁
LockUtil.setLock(lockAppPackageName,true);
}
}
}
}
}
}
if(packageName != null && packageName != ""){
if(isLock){//表示这个包名上锁了,那么弹出dialog输入密码
spUtil.putString("lockAppPackageName",packageName);
Intent intent = new Intent(LockService.this, ScreetActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
LockService.this.startActivity(intent);
}
}
}
}
};
public String getCurrentPackageName(Context context, ActivityManager activityManager){
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
List<ActivityManager.RunningTaskInfo> appTasks = activityManager.getRunningTasks(1);
if (null != appTasks && !appTasks.isEmpty()) {
return appTasks.get(0).topActivity.getPackageName();
}
} else {
//5.0以后需要用这方法
UsageStatsManager sUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long endTime = System.currentTimeMillis();
long beginTime = endTime - 10000;
String result = "";
UsageEvents.Event event = new UsageEvents.Event();
UsageEvents usageEvents = sUsageStatsManager.queryEvents(beginTime, endTime);
while (usageEvents.hasNextEvent()) {
usageEvents.getNextEvent(event);
if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
result = event.getPackageName();
}
}
if (!android.text.TextUtils.isEmpty(result)) {
return result;
}
}
return "";
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy: LockService I will be destoryed");
startService(new Intent(this,LockService.class));
super.onDestroy();
}
/**
* 获得属于桌面的应用的应用包名称
*/
private List<String> getHomes() {
List<String> names = new ArrayList<>();
PackageManager packageManager = this.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo ri : resolveInfo) {
names.add(ri.activityInfo.packageName);
}
return names;
}
}
| ce59c7b3d7622d1a17416031959638d767fd1342 | [
"Markdown",
"Java"
] | 6 | Java | Suguohei/SecuritySetting | 67447b300517823d6e413fbb9818ca1ae60a3a00 | c43c8d461fa52931364dfeaf8236edb4220d1690 |
refs/heads/master | <repo_name>WPPlugins/invit0r<file_sep>/uninstall.php
<?php
// *sighs* :(
if ( function_exists('register_uninstall_hook') ) {
register_uninstall_hook(__FILE__, 'invit0r_uninstall_hook');
}
/**
* Remove the table and all the options from the database and delete the scheduled cron.
*/
function invit0r_uninstall_hook()
{
global $wpdb;
$invitees_table_name = $wpdb->prefix . 'invit0r_invitees';
$wpdb->query("DROP TABLE IF EXISTS " . $invitees_table_name);
delete_option('invit0r_db_version');
delete_option('invit0r_oauth_consumer_key');
delete_option('invit0r_oauth_consumer_secret');
delete_option('invit0r_oauth_domain');
delete_option('invit0r_oauth_app_id');
delete_option('invit0r_use_wp_cron');
delete_option('invit0r_wp_cron_interval');
delete_option('invit0r_secret_key');
delete_option('invit0r_emails_per_batch');
delete_option('invit0r_reminders_per_batch');
delete_option('invit0r_remind_after');
delete_option('invit0r_reminders_limit');
delete_option('invit0r_sender_name');
delete_option('invit0r_sender_email');
delete_option('invit0r_subject');
delete_option('invit0r_body');
wp_clear_scheduled_hook('invit0r_cron_hook');
}
<file_sep>/cron.php
<?php
if ( isset($_GET['secret_key']) && strlen($_GET['secret_key']) == 32 ) {
$secret_key = $_GET['secret_key'];
} else if (isset($argv[1])) {
list(,$secret_key) = explode('=', $argv[1]);
}
if (isset($secret_key) && !empty($secret_key)) {
require_once('../../../wp-load.php');
if ($secret_key != get_option('invit0r_secret_key') || get_option('invit0r_use_wp_cron') == 1) {
die();
}
invit0r_cron();
}
<file_sep>/stats-data-file.php
<?php
require_once('../../../wp-load.php');
require_once('lib/php-ofc-library/open-flash-chart.php');
if ( !current_user_can('manage_options') ) {
wp_die( __('You are not allowed to access this part of the site.') );
}
$unit = isset($_GET['unit']) ? $_GET['unit'] : 1;
if (!in_array($unit, array(1, 7, 31))) {
$unit = 1;
}
$data = array();
$labels = array();
$max = 100;
$now = time();
switch ($unit) {
# days
case 1:
$start_time = $now - 2592000;
list($day_today, $this_month) = explode(' ', date('j n'));
list($start_day, $start_month, $days_last_month, $start_year) = explode(' ', date('d m t Y', $start_time));
for ($i = $start_day; $i <= $days_last_month; $i++) {
$labels[] = $start_month . '-' . $i;
}
if (count($labels) < 31) {
for ($i = 1; $i <= $day_today; $i++) {
$labels[] = $this_month . '-' . $i;
}
}
$query = "SELECT MONTH(FROM_UNIXTIME(`time_added`)) as `month`, DAY(FROM_UNIXTIME(`time_added`)) AS `day`, YEAR(FROM_UNIXTIME(`time_added`)) as `year`, COUNT(`id`) as `count`
FROM `" . $wpdb->prefix . "invit0r_invitees`
WHERE `time_added` >= UNIX_TIMESTAMP(" . $start_year . $start_month . $start_day . ")
GROUP BY `year`, `month`, `day`
ORDER BY `time_added` ASC";
// echo $query;
// die();
$results = $wpdb->get_results($query);
foreach ($labels as $index => $label) {
$continue = false;
foreach ($results as $result) {
if ($result->count > $max) {
$max = $result->count;
}
if ($label == $result->month . '-' . $result->day) {
$data[$index] = (int)$result->count;
$continue = true;
break;
}
}
if (!$continue) {
$data[$index] = 0;
}
}
break;
# weeks
case 7:
$start_time = $now - 15724800;
list($this_week, $this_year) = explode(' ', date('W Y'));
list($start_day, $start_month, $start_week, $start_year) = explode(' ', date('d m W Y', $start_time));
for ($year = $start_year; $year <= $this_year; $year++) {
$w = $year == $start_year ? $start_week : 1;
for ($week = $w; $week <= 53; $week++) {
$labels[] = $year . '-' . $week;
if ($year == $this_year && $week == $this_week) {
break;
}
}
}
$query = "SELECT YEAR(FROM_UNIXTIME(`time_added`)) as `year`, WEEK(FROM_UNIXTIME(`time_added`)) AS `week`, COUNT(`id`) as `count`
FROM `" . $wpdb->prefix . "invit0r_invitees`
WHERE `time_added` >= UNIX_TIMESTAMP(" . $start_year . $start_month . $start_day . ")
GROUP BY `year`, `week`
ORDER BY `time_added` ASC";
$results = $wpdb->get_results($query);
foreach ($labels as $index => $label) {
$continue = false;
foreach ($results as $result) {
if ($result->count > $max) {
$max = $result->count;
}
if ($label == $result->year . '-' . $result->week) {
$data[$index] = (int)$result->count;
$continue = true;
break;
}
}
if (!$continue) {
$data[$index] = 0;
}
}
break;
# months
case 31:
$start_time = $now - 31536000;
list($this_month, $this_year) = explode(' ', date('n Y'));
list($start_day, $start_month, $start_year) = explode(' ', date('d m Y', $start_time));
for ($year = $start_year; $year <= $this_year; $year++) {
$m = $year == $start_year ? $start_month : 1;
for ($month = $m; $month <= 12; $month++) {
$labels[] = $year . '-' . $month;
if ($year == $this_year && $month == $this_month) {
break;
}
}
}
$query = "SELECT YEAR(FROM_UNIXTIME(`time_added`)) as `year`, MONTH(FROM_UNIXTIME(`time_added`)) AS `month`, COUNT(`id`) as `count`
FROM `" . $wpdb->prefix . "invit0r_invitees`
WHERE `time_added` >= UNIX_TIMESTAMP(" . $start_year . $start_month . $start_day . ")
GROUP BY `year`, `month`
ORDER BY `time_added` ASC";
$results = $wpdb->get_results($query);
foreach ($labels as $index => $label) {
$continue = false;
foreach ($results as $result) {
if ($result->count > $max) {
$max = $result->count;
}
if ($label == $result->year . '-' . $result->month) {
$data[$index] = (int)$result->count;
$continue = true;
break;
}
}
if (!$continue) {
$data[$index] = 0;
}
}
break;
}
$title = new title(' ');
$d = new hollow_dot();
$d->size(5)->halo_size(0)->colour('#3D5C56');
$line = new line();
$line->set_default_dot_style($d);
$line->set_values( $data );
$line->set_width( 2 );
$line->set_colour( '#3D5C56' );
$x_labels = new x_axis_labels();
$x_labels->rotate(300);
$x_labels->set_labels( $labels );
$x = new x_axis();
$x->set_labels( $x_labels );
$step = $max > 0 ? ceil($max / 5) : 0;
$y = new y_axis();
$y->set_range( 0, $step * 5, $step);
$chart = new open_flash_chart();
$chart->set_title( $title );
$chart->add_element( $line );
$chart->set_x_axis( $x );
$chart->set_y_axis( $y );
echo $chart->toPrettyString();
<file_sep>/stats.php
<?php
// Restrict the access to the plugin's option page only to administrators
invit0r_restrict_admin();
?>
<div class="wrap">
<h2>Invit0r Stats</h2>
<p>This includes both invited and imported contacts.</p>
<p>
Invited: <strong><?php echo $wpdb->get_var("SELECT COUNT(`id`) FROM `" . $wpdb->prefix . "invit0r_invitees` WHERE `is_imported` = '0'");?></strong> |
Imported: <strong><?php echo $wpdb->get_var("SELECT COUNT(`id`) FROM `" . $wpdb->prefix . "invit0r_invitees` WHERE `is_imported` = '1'");?></strong> |
Unsubscribed: <strong><?php echo $wpdb->get_var("SELECT COUNT(`id`) FROM `" . $wpdb->prefix . "invit0r_invitees` WHERE `unsubscribe` = '1'");?></strong> |
Total: <strong><?php echo $wpdb->get_var("SELECT COUNT(`id`) FROM `" . $wpdb->prefix . "invit0r_invitees`");?></strong>
</p>
<div id="invit0r_chart_wrap">
<div id="invit0r_chart_switch">
<a id="invit0r_chart_switch_1" class="invit0r_chart_switch_active" href="#">Days</a>
<a id="invit0r_chart_switch_7" href="#">Weeks</a>
<a id="invit0r_chart_switch_31" href="#">Months</a>
</div>
<div class="invit0r_chart">
<div id="invit0r_chart_1"></div>
</div>
<div class="invit0r_chart" style="display:none;">
<div id="invit0r_chart_7"></div>
</div>
<div class="invit0r_chart" style="display:none;">
<div id="invit0r_chart_31"></div>
</div>
</div>
</div>
<file_sep>/invit0r.php
<?php
/*
Plugin Name: Invit0r
Plugin URI: http://marianbucur.com/wordpress-projects/invit0r.html
Description: This plugin enables your users to invite their friends to your website. Only Yahoo! Mail accounts currently work.
Author: <NAME>
Version: 0.22
Author URI: http://marianbucur.com/
*/
/*
* Copyright 2011 Invit0r (email : <EMAIL>)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
global $invit0r_version;
global $invit0r_db_version;
$invit0r_version = '0.22';
$invit0r_db_version = '0.2';
/**
* Generates a random hash.
*
* @param int $len What length should the hash string have? Default: 32.
* @return string
*/
function invit0r_generate_random_hash($len = 32)
{
if (!function_exists('mt_rand')) {
function mt_rand($min, $max)
{
return rand($min, $max);
}
}
$str = 'abcdefghijklmnopqrstuvwxyz0123456789';
$str_len = strlen($str);
$secret_key = '';
for ($i = 0; $i < $len; $i++) {
$secret_key .= $str[ mt_rand( 0, $str_len - 1 ) ];
}
return $secret_key;
}
/**
* The function responsible with restricting the use of the plugin only to admins
*/
function invit0r_restrict_admin()
{
if ( !current_user_can('manage_options') ) {
wp_die( __('You are not allowed to access this part of the site.') );
}
}
/**
* Verifies if the input is numeric and returns 0 otherwise.
* If the input is numeric, it rounds it down,
* returning 0 if the number is smaller than 0 and
* the actuall number if it greater than 0.
*
* @param int $input input
* @return int
*/
function invit0r_int_not_negative($input)
{
if (is_numeric($input)) {
$input = floor($input);
if ($input < 0) {
return 0;
}
return $input;
}
return 0;
}
/**
* Trims the input and shortens it to 32 characters.
*
* @param string $input input
* @return string
*/
function invit0r_max_len_32($input)
{
return substr(trim($input), 0, 32);
}
/**
* Returns 0 or 1.
*
* @param int $input input
* @return int
*/
function invit0r_one_or_zero($input)
{
return $input == 1 ? 1 : 0;
}
/**
* Checks if the input is a valid value and sets it, by default,
* to "every_five_minutes" if it is not.
* It also reschedules or removes the cron based on the user's options.
*
* @param string $input input
* @return string
*/
function invit0r_cron_internvals($input)
{
// Valid values
$valid = array('every_minute', 'every_five_minutes', 'every_ten_minutes', 'every_fifteen_minutes', 'every_half_an_hour');
// Check to see if the input is valid and gets the value from the database if it is not
if (!in_array($input, $valid)) {
$input = get_option('invit0r_wp_cron_interval');
}
// If there is no value in the database, it just sets the value to the default "every_five_minutes"
if (!in_array($input, $valid)) {
$input = 'every_five_minutes';
}
return $input;
}
/**
* Checks to see if the provided element is in an array or not.
*
* @param mixed $elem Needle
* @param mixed $array Haystack
* @return bool
*/
function invit0r_in_multiarray($elem, $array)
{
// if the $array is an array or is an object
if( is_array( $array ) || is_object( $array ) ) {
// if $elem is in $array object
if( is_object( $array ) ) {
$temp_array = get_object_vars( $array );
if( in_array( $elem, $temp_array ) )
return true;
}
// if $elem is in $array return true
if( is_array( $array ) && in_array( $elem, $array ) )
return true;
// if $elem isn't in $array, then check foreach element
foreach ( $array as $array_element ) {
// if $array_element is an array or is an object call the invit0r_in_multiarray function to this element
// if invit0r_in_multiarray returns TRUE, than return is in array, else check next element
if( ( is_array( $array_element ) || is_object( $array_element ) ) && invit0r_in_multiarray( $elem, $array_element ) ) {
return true;
exit;
}
}
}
// if isn't in array return FALSE
return false;
}
/**
* The function called when installing the plugin.
*/
function invit0r_install()
{
global $wpdb, $invit0r_db_version, $invit0r_version;
$invitees_table_name = $wpdb->prefix . 'invit0r_invitees';
// Create or update the database table
if($wpdb->get_var('SHOW TABLES LIKE ' . $invitees_table_name) != $invitees_table_name) {
$sql = 'CREATE TABLE `' . $invitees_table_name . '` (
`id` bigint(20) unsigned NOT NULL auto_increment,
`hash` varchar(32) NOT NULL,
`email_address` varchar(255) NOT NULL,
`given_name` varchar(255) NOT NULL,
`middle_name` varchar(255) NOT NULL,
`family_name` varchar(255) NOT NULL,
`nickname` varchar(255) NOT NULL,
`time_added` int(11) unsigned NOT NULL,
`time_resent` int(11) unsigned NOT NULL,
`invites_sent` int(11) unsigned NOT NULL default \'0\',
`unsubscribe` enum(\'0\',\'1\') NOT NULL default \'0\',
`is_imported` ENUM(\'0\',\'1\') NOT NULL DEFAULT \'0\',
PRIMARY KEY (`id`),
UNIQUE KEY `email_address` (`email_address`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;';
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
// Add the critical options
add_option('invit0r_version', $invit0r_version);
add_option('invit0r_db_version', $invit0r_db_version);
add_option('invit0r_emails_per_batch', 10);
add_option('invit0r_reminders_per_batch', 0);
add_option('invit0r_remind_after', 0);
add_option('invit0r_reminders_limit', 0);
add_option('invit0r_use_wp_cron', 1);
add_option('invit0r_wp_cron_interval', 'every_minute');
add_option('invit0r_secret_key', invit0r_generate_random_hash());
// Schedule the Wordpress cron job if it isn't already scheduled and if the user chose to
if ( !wp_next_scheduled('invit0r_cron_hook') && get_option('invit0r_use_wp_cron') == 1 ) {
wp_schedule_event( time(), 'every_five_minutes', 'invit0r_cron_hook' );
}
}
// Register the activation function
register_activation_hook( __FILE__, 'invit0r_install' );
/**
* The function called when deactivating the plugin.
*/
function invit0r_deactivate()
{
wp_clear_scheduled_hook('invit0r_cron_hook');
}
// Register the deactivation function
register_deactivation_hook( __FILE__, 'invit0r_deactivate' );
if (is_admin()) {
/**
* Add some more links to the plugin row meta.
*
* @param array $links Already defined links
* @param string $file File path
* @return array
*/
function invit0r_more_plugin_links($links, $file)
{
$base = plugin_basename(__FILE__);
if ($file == $base) {
$links[] = '<a href="admin.php?page=invit0r/main.php">' . __('Configuration') . '</a>';
}
return $links;
}
//Additional links on the plugin page
add_filter('plugin_row_meta', 'invit0r_more_plugin_links', 10, 2);
/**
* The function responsible with adding the menus.
*/
function invit0r_admin_menu()
{
if (function_exists('add_menu_page')) {
add_menu_page('Invit0r', 'Invit0r', 'manage_options', 'invit0r/main.php');
}
if (function_exists('add_submenu_page')) {
add_submenu_page('invit0r/main.php', 'Invit0r Configuration', 'Configuration', 'manage_options', 'invit0r/main.php');
add_submenu_page('invit0r/main.php', 'Invit0r Export contacts', 'Export contacts', 'manage_options', 'invit0r/export-contacts.php');
add_submenu_page('invit0r/main.php', 'Invit0r Import contacts', 'Import contacts', 'manage_options', 'invit0r/import-contacts.php');
add_submenu_page('invit0r/main.php', 'Invit0r Stats', 'Stats', 'manage_options', 'invit0r/stats.php');
}
}
// Add admin menu
add_action( 'admin_menu', 'invit0r_admin_menu' );
/**
* Custom intervals used for Wordpress' cron system.
*
* @param array $schedules Already defined intervals
* @return array
*/
function invit0r_filter_cron_schedules($schedules)
{
$schedules['every_minute'] = array(
'interval' => 60,
'display' => __( 'Once per minute' )
);
$schedules['every_five_minutes'] = array(
'interval' => 300,
'display' => __( 'Once five minutes' )
);
$schedules['every_ten_minutes'] = array(
'interval' => 600,
'display' => __( 'Once ten minutes' )
);
$schedules['every_fifteen_minutes'] = array(
'interval' => 900,
'display' => __( 'Once fifteen minutes' )
);
$schedules['every_half_an_hour'] = array(
'interval' => 1800,
'display' => __( 'Once half an hour' )
);
return $schedules;
}
// Add custom intervals for Wordpress' cron system
add_filter( 'cron_schedules', 'invit0r_filter_cron_schedules' );
}
/**
* The function used by both Wordpress' cron system and Invit0r's cron.php file
* for sending invites and reminders.
*/
function invit0r_cron()
{
global $wpdb;
// Change the content type of the email from plain text to html
add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '));
$sender_email = get_option('invit0r_sender_email');
$subject = stripslashes(get_option('invit0r_subject'));
$body = stripslashes(get_option('invit0r_body'));
// Verify if the sender email, subject and body are not blank
if (trim($sender_email) != '' && trim($subject) != '' && trim($body) != '') {
$emails_per_batch = get_option('invit0r_emails_per_batch');
$reminders_per_batch = get_option('invit0r_reminders_per_batch');
$reminders_limit = get_option('invit0r_reminders_limit');
$remind_after = get_option('invit0r_remind_after') * 24 * 3600;
// $remind_after = 1;
$unsubscribe_url = plugins_url('unsubscribe.php', __FILE__);
// Get the email addresses where the invites will be sent
if ($emails_per_batch > 0) {
$results = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "invit0r_invitees` WHERE `invites_sent` = 0 LIMIT " . $emails_per_batch);
} else {
$results = null;
}
// If reminders are active, get the email addresses where the reminders will be sent
if ($reminders_per_batch && $remind_after > 0) {
$results_reminders = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "invit0r_invitees` WHERE `invites_sent` > 0 " . ( $reminders_limit != 0 ? "AND `invites_sent` <= " . $reminders_limit : '' ) . " AND `unsubscribe` = '0' AND `time_resent` + " . $remind_after . " < " . time() . " LIMIT " . $reminders_per_batch);
} else {
$results_reminders = null;
}
// Check to see if there are any emails to be sent and execute the rest of the code if there are
if ($results || $results_reminders) {
$sender_name = stripslashes(get_option('invit0r_sender_name'));
// Set the wp_mail headers, determined by the sender name
if ($sender_name != '') {
$headers = 'From: ' . $sender_name . ' <' . $sender_email . '>' . PHP_EOL;
} else if ( ($blog_name = get_bloginfo('name')) != '' ) {
$headers = 'From: ' . $blog_name . ' <' . $sender_email . '>' . PHP_EOL;
} else {
$headers = 'From: ' . $sender_email . ' <' . $sender_email . '>' . PHP_EOL;
}
// Send 1st time invite
if (is_array($results)) {
$ids = array();
foreach ($results as $result) {
$ids[] = '`id` = ' . $result->id;
$body_aux = str_replace('%unsubscribe_url%', $unsubscribe_url . '?email=' . $result->email_address . '&hash=' . $result->hash, $body);
wp_mail($result->email_address, $subject, $body_aux, $headers);
}
}
// Send reminders
if (is_array($results_reminders)) {
if (!isset($ids)) {
$ids = array();
}
foreach ($results_reminders as $result) {
$ids[] = '`id` = ' . $result->id;
$body_aux = str_replace('%unsubscribe_url%', $unsubscribe_url . '?email=' . $result->email_address . '&hash=' . $result->hash, $body);
wp_mail($result->email_address, $subject, $body_aux, $headers);
}
}
// If any emails were sent, update the number of invites sent to that address and the time when it was (re)sent
if (!empty($ids)) {
$wpdb->query("UPDATE `" . $wpdb->prefix . "invit0r_invitees` SET `invites_sent` = `invites_sent` + 1, `time_resent` = " . time() . " WHERE " . implode(' OR ', $ids));
}
}
}
}
// Schedule the Wordpress cron job
add_action( 'invit0r_cron_hook', 'invit0r_cron' );
/**
* Admin css
*/
function invit0r_admin_css()
{
echo '<style type="text/css">.show{display:table-row}.hidden{display:none}#invit0r_chart_wrap{text-align:center}#invit0r_chart_switch{width:200px;margin:0 auto}#invit0r_chart_switch a{float:left;padding:7px;margin-right:5px;border:1px solid #ddd;border-bottom:none;border-top-left-radius:3px;border-top-right-radius:3px}.invit0r_chart{clear:left}.invit0r_chart_switch_active{font-weight:bold}</style>';
}
// Print the admin css
add_action('admin_print_styles-invit0r/main.php', 'invit0r_admin_css');
add_action('admin_print_styles-invit0r/stats.php', 'invit0r_admin_css');
/**
* Admin js
*/
function invit0r_admin_js()
{
wp_enqueue_script('invit0r_admin', plugins_url('js/invit0r-admin.js', __FILE__), array('jquery', 'swfobject'), null);
}
// Print the admin js
add_action('admin_print_scripts-invit0r/main.php', 'invit0r_admin_js');
add_action('admin_print_scripts-invit0r/stats.php', 'invit0r_admin_js');
/**
* User js
*/
function invit0r_enqueue_scripts()
{
wp_enqueue_script('invit0r', plugins_url('js/invit0r.js', __FILE__), array('jquery'), null);
echo "<script type='text/javascript'>\nvar select_cotacts_url = '" , plugins_url('select-contacts.php', __FILE__) , "'\nvar admin_ajax_url = '" . get_bloginfo('url') . "/wp-admin/admin-ajax.php'\n</script>\n";
}
add_action('wp_enqueue_scripts', 'invit0r_enqueue_scripts');
// Require the Yahoo library
require_once('lib/Invit0r_Yahoo.inc');
// Load the OAuth authentication data
$invit0r_oauth_consumer_key = get_option('invit0r_oauth_consumer_key');
$invit0r_oauth_consumer_secret = get_option('invit0r_oauth_consumer_secret');
$invit0r_oauth_app_id = get_option('invit0r_oauth_app_id');
// Get the session status
$invit0r_hasSession = Invit0r_YahooSession::hasSession($invit0r_oauth_consumer_key, $invit0r_oauth_consumer_secret, $invit0r_oauth_app_id);
// Check the session status
if ($invit0r_hasSession) {
// pass the credentials to initiate a session
$invit0r_session = Invit0r_YahooSession::requireSession($invit0r_oauth_consumer_key, $invit0r_oauth_consumer_secret, $invit0r_oauth_app_id);
$invit0r_user = $invit0r_session->getSessionedUser();
}
// Set the yahoo logo
$invit0r_yahoo_logo = '<img src="' . plugins_url('images/yahoo_logo.png', __FILE__) . '" width="168" height="44" alt="yahoo logo" />';
// if a session exists and the logout flag is detected clear the session tokens and redirect to the main page
if(isset($_GET['invit0r_logout'])) {
invit0r_logout();
wp_redirect(get_bloginfo('url'));
}
/**
* Clear the session tokens.
*/
function invit0r_logout()
{
global $invit0r_hasSession;
Invit0r_YahooSession::clearSession();
$invit0r_hasSession = false;
}
/**
* The function used to display the invite link on the user area.
*
* @param string|null $display_element You can specify a html tag, text or null (nothing will be displayed inside the link)
*/
function invit0r_display($display_element = '')
{
global $invit0r_hasSession, $invit0r_yahoo_logo;
if (!is_null($display_element)) {
// If display_element is blank, display the default image
if ($display_element == '') {
$display_element = $invit0r_yahoo_logo;
}
} else {
// If display_element is null, don't display anything inside the link
$display_element = '';
}
// Store display_element for displaying the invite link using ajax
$_SESSION['invit0r_display'] = $display_element;
echo '<div id="invit0r">';
if ($invit0r_hasSession == false) {
// If there is no session established yet, display the auth link
$auth_url = invit0r_auth_url();
if (trim($auth_url) != '') {
echo '<a id="invit0r_link" href="' . $auth_url . '">' , $display_element , '</a>';
}
} else {
// If there is a session established, display the invite contacts and logout links
echo 'Invite more contacts <br /><br /> <a id="invit0r_link" href="' , plugins_url('select-contacts.php', __FILE__) , '">' , $display_element , '</a> <br /><br /> or <a href="' . Invit0r_YahooUtil::current_url() . '?invit0r_logout" id="invit0r_logout">logout</a>';
}
echo '</div>';
}
/**
* Get user's contacts from Yahoo between the limits supplied as arguments.
*
* @param int $from from
* @param int $to to
* @return List of contacts for the current user
* @see Invit0r_YahooUser::getContacts()
*/
function invit0r_get_contacts($from, $to)
{
global $invit0r_user;
return $invit0r_user -> getContacts($from, $to);
}
/**
* Returns the auth url based on the session status.
*
* @return str
* @see Invit0r_YahooSession::createAuthorizationUrl()
*/
function invit0r_auth_url()
{
global $invit0r_oauth_consumer_key, $invit0r_oauth_consumer_secret;
return Invit0r_YahooSession::createAuthorizationUrl($invit0r_oauth_consumer_key, $invit0r_oauth_consumer_secret, plugins_url('select-contacts.php', __FILE__));
}
/**
* Check to see if the user established a session or not
*
* @return int
* @access public
*/
function invit0r_check_session()
{
global $invit0r_hasSession;
if($invit0r_hasSession == false) {
return 0;
}
return 1;
}
/**
* Display the invite link, using ajax
*/
function invit0r_display_ajax()
{
invit0r_display($_SESSION['invit0r_display']);
die();
}
add_action( 'wp_ajax_nopriv_invit0r_display', 'invit0r_display_ajax' );
add_action( 'wp_ajax_invit0r_display', 'invit0r_display_ajax' );
/**
* Logout using ajax and refresh the invite link.
*/
function invit0r_logout_ajax()
{
global $invit0r;
invit0r_logout();
invit0r_display_ajax();
}
add_action( 'wp_ajax_nopriv_invit0r_logout', 'invit0r_logout_ajax' );
add_action( 'wp_ajax_invit0r_logout', 'invit0r_logout_ajax' );
<file_sep>/import-contacts.php
<?php
// Restrict the access to the plugin's option page only to administrators
invit0r_restrict_admin();
// handle the contacts import
if (isset($_POST['submit_import'])) {
check_admin_referer( 'invit0r-nonce' );
if ( ($handle = fopen($_FILES['imported_contacts']['tmp_name'], 'r')) !== false ) {
// Get the email addresses of current users to avoid sending them useless emails
$results = $wpdb->get_results("SELECT `user_email` FROM `" . $wpdb->prefix . "wp_users`");
$emails = array();
foreach ($results as $result) {
$emails[] = $result->user_email;
}
$query = "INSERT IGNORE INTO `" . $wpdb->prefix . "invit0r_invitees` (`hash`, `email_address`, `given_name`, `middle_name`, `family_name`, `nickname`, `time_added`, `time_resent`, `is_imported`) VALUES ";
$values = array();
$limit = 0;
$count = 0;
while ( ($data = fgetcsv($handle, 1000, ',')) !== false ) {
// Check if the imported email is valid and it is not already in the users table
if ( is_email($data[0]) && !in_array($data[0], $emails) ) {
if (count($data) < 5) {
for ($i = count($data); $i < 5; $i++) {
$data[] = '';
}
}
$values_str = "('" . invit0r_generate_random_hash() . "'" ;
foreach ($data as $index => $value) {
$values_str .= ",'" . $wpdb->escape(trim($value)) ."'" ;
}
$values_str .= "," . time() . "," . time() . ",'1')";
$values[] = $values_str;
$limit++;
}
if ($limit == 1000) {
// Insert the contacts in the database
$wpdb->query($query . implode(',', $values));
$count += mysql_affected_rows();
$values = array();
$limit = 0;
}
}
if (!empty($values)) {
// Insert the contacts in the database if there are any remaining in the queue
$wpdb->query($query . implode(',', $values));
$count += mysql_affected_rows();
}
// close the file
fclose($handle);
// delete the file
unlink($_FILES['imported_contacts']['tmp_name']);
$suc = ($count > 0 ? $count : 'No') . ' contacts have been imported';
} else {
$error = 'There was an error opening the file.';
}
}
?>
<div class="wrap">
<?php
// If there is an error message set, display it
if (isset($error)) {
echo '<div class="error"><p>' , $error , '</p></div>';
}
// If it is a success message set, display it
if (isset($suc)) {
echo '<div class="updated settings-error"><p>' , $suc , '</p></div>';
}
?>
<h2>Invit0r Import Contacts</h2>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI'];?>" enctype="multipart/form-data">
<?php wp_nonce_field( 'invit0r-nonce' ); ?>
<table class="form-table">
<tr valign="top">
<th scope="row">File</th>
<td>
<input type="file" size="60" name="imported_contacts" /> <br />
Format: email_address[[[[,given_name],middle_name],family_name],nickname]
</td>
</tr>
</table>
<p class="submit">
<input type="submit" name="submit_import" class="button-primary" value="<?php _e('Upload') ?>" />
</p>
</form>
</div>
<file_sep>/main.php
<?php
// Restrict the access to the plugin's option page only to administrators
invit0r_restrict_admin();
if (!empty($_POST)) {
check_admin_referer( 'invit0r-nonce' );
$invit0r_oauth_consumer_key = strip_tags(trim($_POST['invit0r_oauth_consumer_key']));
$invit0r_oauth_consumer_secret = strip_tags(trim($_POST['invit0r_oauth_consumer_secret']));
$invit0r_oauth_domain = strip_tags(trim($_POST['invit0r_oauth_domain']));
$invit0r_oauth_app_id = strip_tags(trim($_POST['invit0r_oauth_app_id']));
$invit0r_use_wp_cron = invit0r_one_or_zero(strip_tags(trim($_POST['invit0r_use_wp_cron'])));
$invit0r_wp_cron_interval = invit0r_cron_internvals(strip_tags(trim($_POST['invit0r_wp_cron_interval'])));
$invit0r_secret_key = invit0r_max_len_32(strip_tags(trim($_POST['invit0r_secret_key'])));
$invit0r_emails_per_batch = invit0r_int_not_negative(strip_tags(trim($_POST['invit0r_emails_per_batch'])));
$invit0r_reminders_per_batch = invit0r_int_not_negative(strip_tags(trim($_POST['invit0r_reminders_per_batch'])));
$invit0r_remind_after = invit0r_int_not_negative(strip_tags(trim($_POST['invit0r_remind_after'])));
$invit0r_reminders_limit = invit0r_int_not_negative(strip_tags(trim($_POST['invit0r_reminders_limit'])));
$invit0r_sender_name = strip_tags(trim($_POST['invit0r_sender_name']));
$invit0r_sender_email = strip_tags(trim($_POST['invit0r_sender_email']));
$invit0r_subject = strip_tags(trim($_POST['invit0r_subject']));
$invit0r_body = trim($_POST['invit0r_body']);
} else {
$invit0r_oauth_consumer_key = get_option('invit0r_oauth_consumer_key');
$invit0r_oauth_consumer_secret = get_option('invit0r_oauth_consumer_secret');
$invit0r_oauth_domain = get_option('invit0r_oauth_domain');
$invit0r_oauth_app_id = get_option('invit0r_oauth_app_id');
$invit0r_use_wp_cron = get_option('invit0r_use_wp_cron');
$invit0r_wp_cron_interval = get_option('invit0r_wp_cron_interval');
$invit0r_secret_key = get_option('invit0r_secret_key');
$invit0r_emails_per_batch = get_option('invit0r_emails_per_batch');
$invit0r_reminders_per_batch = get_option('invit0r_reminders_per_batch');
$invit0r_remind_after = get_option('invit0r_remind_after');
$invit0r_reminders_limit = get_option('invit0r_reminders_limit');
$invit0r_sender_name = get_option('invit0r_sender_name');
$invit0r_sender_email = get_option('invit0r_sender_email');
$invit0r_subject = get_option('invit0r_subject');
$invit0r_body = get_option('invit0r_body');
}
if ($invit0r_oauth_consumer_key == '' || $invit0r_oauth_consumer_secret == '' || $invit0r_oauth_domain == '' || $invit0r_oauth_app_id == '') {
$error = 'Please setup the OAuth details or the script will not work.';
} else if (strlen($invit0r_secret_key) != 32) {
$error = 'You need to provide a 32 long string for the \'Secret key\' in order for the cron file to work. It is for your own safety.';
} else if (!is_email($invit0r_sender_email)) {
$error = 'Please enter a valid \'Sender email\'';
} else if ($invit0r_sender_email == '' || $invit0r_subject == '' || $invit0r_body == '') {
$error = 'The \'Sender email\', \'Subject\' or/and \'Body\' fields are empty. The plugin will not send invitations, reminders and test emails until you fix this problem.';
}
// Send a test email if the "Test" button has been pressed
if (isset($_POST['test'])) {
// Change the content type of the email from plain text to html
add_filter('wp_mail_content_type', create_function('', 'return "text/html"; '));
// Verify if the sender email, subject and body are not blank
if ($invit0r_sender_email != '' && $invit0r_subject != '' && $invit0r_body != '') {
$unsubscribe_url = plugins_url('unsubscribe.php', __FILE__);
// Set the wp_mail headers, determined by the sender name
if ($invit0r_sender_name != '') {
$headers = 'From: ' . $invit0r_sender_name . ' <' . $invit0r_sender_email . '>' . PHP_EOL;
} else if ( ($blog_name = get_bloginfo('name')) != '' ) {
$headers = 'From: ' . $blog_name . ' <' . $invit0r_sender_email . '>' . PHP_EOL;
} else {
$headers = 'From: ' . $invit0r_sender_email . ' <' . $invit0r_sender_email . '>' . PHP_EOL;
}
// Replace the %unsubscribe_url% tag with a dummy link (dummy because the admin doesn't need to unsubscribe)
$body_aux = str_replace('%unsubscribe_url%', $unsubscribe_url . '?email=test_email&hash=test_hash', $invit0r_body);
// Send the email
wp_mail($invit0r_sender_email, $invit0r_subject, $body_aux, $headers);
// Success message
$suc = 'A test email has been sent to the provided \'Sender email\'';
}
}
// Save the options
if (!isset($error) && isset($_POST['save'])) {
update_option('invit0r_oauth_consumer_key', $invit0r_oauth_consumer_key);
update_option('invit0r_oauth_consumer_secret', $invit0r_oauth_consumer_secret);
update_option('invit0r_oauth_domain', $invit0r_oauth_domain);
update_option('invit0r_oauth_app_id', $invit0r_oauth_app_id);
update_option('invit0r_use_wp_cron', $invit0r_use_wp_cron);
update_option('invit0r_wp_cron_interval', $invit0r_wp_cron_interval);
update_option('invit0r_secret_key', $invit0r_secret_key);
update_option('invit0r_emails_per_batch', $invit0r_emails_per_batch);
update_option('invit0r_reminders_per_batch', $invit0r_reminders_per_batch);
update_option('invit0r_remind_after', $invit0r_remind_after);
update_option('invit0r_reminders_limit', $invit0r_reminders_limit);
update_option('invit0r_sender_name', $invit0r_sender_name);
update_option('invit0r_sender_email', $invit0r_sender_email);
update_option('invit0r_subject', $invit0r_subject);
update_option('invit0r_body', $invit0r_body);
// Check to see if the user opted for using Wordpress' cron system
if ($invit0r_use_wp_cron == 1) {
// Clear the scheduled cron and schedule it again
wp_clear_scheduled_hook('invit0r_cron_hook');
wp_schedule_event( time(), $invit0r_use_wp_cron, 'invit0r_cron_hook' );
} else {
// Clear the scheduled cron if the user opted to use a proper cron system
wp_clear_scheduled_hook('invit0r_cron_hook');
}
// Success message
$suc = 'Configuration successfully saved';
}
?>
<div class="wrap">
<div class="icon32" id="icon-options-general"><br /></div>
<h2>Invit0r Configuration</h2>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI'];?>">
<?php wp_nonce_field( 'invit0r-nonce' ); ?>
<?php
// If there is an error message set, display it
if (isset($error)) {
echo '<div class="error"><p>' , $error , '</p></div>';
}
// If it is a success message set, display it
if (isset($suc)) {
echo '<div class="updated settings-error"><p>' , $suc , '</p></div>';
}
?>
<h3>OAuth Settings</h3>
<p><a href="https://developer.apps.yahoo.com/dashboard/createKey.html">Create Key</a></p>
<table class="form-table">
<tr valign="top">
<th scope="row">OAuth Consumer Key</th>
<td><input type="text" size="100" name="invit0r_oauth_consumer_key" value="<?php echo stripslashes($invit0r_oauth_consumer_key); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">OAuth Consumer Secret</th>
<td><input type="text" size="50" name="invit0r_oauth_consumer_secret" value="<?php echo stripslashes($invit0r_oauth_consumer_secret); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">OAuth Domain</th>
<td><input type="text" size="50" name="invit0r_oauth_domain" value="<?php echo stripslashes($invit0r_oauth_domain); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">OAuth App ID</th>
<td><input type="text" size="10" name="invit0r_oauth_app_id" value="<?php echo stripslashes($invit0r_oauth_app_id); ?>" /></td>
</tr>
</table>
<h3>Cron Settings</h3>
<table class="form-table">
<tr valign="top">
<th scope="row">Use Wordpress cron</th>
<td>
<label><input type="radio" name="invit0r_use_wp_cron" value="1"<?php echo $invit0r_use_wp_cron == 1 ? ' checked="checked"' : '';?> /> Yes</label>
<label><input type="radio" name="invit0r_use_wp_cron" value="0"<?php echo $invit0r_use_wp_cron == 0 ? ' checked="checked"' : '';?> /> No</label>
</td>
</tr>
<tr class="yes <?php echo $invit0r_use_wp_cron == 1 ? 'show' : 'hidden';?>">
<th scope="row">Wordpress cron inverval</th>
<td>
<select name="invit0r_wp_cron_interval">
<option value="every_minute"<?php echo $invit0r_wp_cron_interval == 'every_minute' ? ' selected="selected"' : '';?>>Once per minute</option>
<option value="every_five_minutes"<?php echo $invit0r_wp_cron_interval == 'every_five_minutes' ? ' selected="selected"' : '';?>>Once five minutes</option>
<option value="every_ten_minutes"<?php echo $invit0r_wp_cron_interval == 'every_ten_minutes' ? ' selected="selected"' : '';?>>Once ten minutes</option>
<option value="every_fifteen_minutes"<?php echo $invit0r_wp_cron_interval == 'every_fifteen_minutes' ? ' selected="selected"' : '';?>>Once fifteen minutes</option>
<option value="every_half_an_hour"<?php echo $invit0r_wp_cron_interval == 'every_half_an_hour' ? ' selected="selected"' : '';?>>Once half an hour</option>
</select>
</td>
</tr>
<tr class="no <?php echo $invit0r_use_wp_cron == 0 ? 'show' : 'hidden';?>">
<th scope="row">Secret key</th>
<td>
<input type="text" size="42" name="invit0r_secret_key" maxlength="32" value="<?php echo $invit0r_secret_key; ?>" />
</td>
</tr>
<tr class="no <?php echo $invit0r_use_wp_cron == 0 ? 'show' : 'hidden';?>">
<th scope="row">Cron command</th>
<td>
<input type="text" size="100" readonly="readonly" value="php <?php echo __DIR__;?>/cron.php secret_key=<?php echo $invit0r_secret_key;?> >/dev/null 2>&1" /> <br />
</td>
</tr>
<tr valign="top">
<th scope="row">1st time emails per batch</th>
<td>
<input type="text" size="5" name="invit0r_emails_per_batch" value="<?php echo $invit0r_emails_per_batch; ?>" /> <br />
The emails which are sent for the 1st time; 0 means it will send no 1st time emails.
</td>
</tr>
<tr valign="top">
<th scope="row">Reminders per batch</th>
<td>
<input type="text" size="5" name="invit0r_reminders_per_batch" value="<?php echo $invit0r_reminders_per_batch; ?>" /> <br />
0 means it will send no reminders.
</td>
</tr>
<tr valign="top">
<th scope="row">Send reminders once every x days</th>
<td>
<input type="text" size="5" name="invit0r_remind_after" value="<?php echo $invit0r_remind_after; ?>" /> <br />
0 means it will send no reminders.
</td>
</tr>
<tr valign="top">
<th scope="row">Reminders limit</th>
<td>
<input type="text" size="5" name="invit0r_reminders_limit" value="<?php echo $invit0r_reminders_limit; ?>" /> <br />
Don't send any reminder beyond this limit; 0 means no limit.
</td>
</tr>
<tr valign="top">
<th scope="row">Sender name</th>
<td>
<input type="text" size="100" name="invit0r_sender_name" value="<?php echo stripslashes($invit0r_sender_name); ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row">Sender email</th>
<td>
<input type="text" size="100" name="invit0r_sender_email" value="<?php echo $invit0r_sender_email; ?>" /> <br />
</td>
</tr>
<tr valign="top">
<th scope="row">Subject</th>
<td>
<input type="text" size="100" name="invit0r_subject" value="<?php echo stripslashes($invit0r_subject); ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row">Body</th>
<td>
<textarea cols="83" rows="20" name="invit0r_body"><?php echo stripslashes($invit0r_body); ?></textarea> <br />
You can use XHTML code. Also, you can use the %unsubscribe_url% tag in the href of your unsubscribe link.
</td>
</tr>
</table>
<p class="submit">
<input type="submit" class="button-primary" name="save" value="<?php _e('Save Changes') ?>" />
<input type="submit" value="<?php _e('Test') ?>" name="test" title="Send a test email to the provided 'Sender email'" />
</p>
</form>
</div>
<file_sep>/js/invit0r-admin.js
var $invit0r = jQuery.noConflict();
$invit0r(document).ready(function($){
$('input[name=invit0r_use_wp_cron]').click(function(){
if ($('.yes').hasClass('show')) {
$('.yes').fadeOut('slow', function(){$(this).removeClass('show').addClass('hidden');});
} else {
$('.yes').fadeIn('slow', function(){$(this).removeClass('hidden').addClass('show');});
}
if ($('.no').hasClass('show')) {
$('.no').fadeOut('slow', function(){$(this).removeClass('show').addClass('hidden');});
} else {
$('.no').fadeIn('slow', function(){$(this).removeClass('hidden').addClass('show');});
}
});
$('#invit0r_chart_switch_1').click(function(){
$('#invit0r_chart_switch a').removeClass('invit0r_chart_switch_active');
$(this).addClass('invit0r_chart_switch_active');
$('.invit0r_chart').hide();
$('#invit0r_chart_1').parents('div').show();
return false;
});
$('#invit0r_chart_switch_7').click(function(){
$('#invit0r_chart_switch a').removeClass('invit0r_chart_switch_active');
$(this).addClass('invit0r_chart_switch_active');
$('.invit0r_chart').hide();
$('#invit0r_chart_7').parents('div').show();
return false;
});
$('#invit0r_chart_switch_31').click(function(){
$('#invit0r_chart_switch a').removeClass('invit0r_chart_switch_active');
$(this).addClass('invit0r_chart_switch_active');
$('.invit0r_chart').hide();
$('#invit0r_chart_31').parents('div').show();
return false;
});
});
var scriptSource = (function(scripts) {
var scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1];
if (script.getAttribute.length !== undefined) {
return script.src
}
return script.getAttribute('src', -1)
}());
var invit0r_dir = scriptSource.replace('js/invit0r-admin.js', '')
swfobject.embedSWF(
invit0r_dir + "open-flash-chart.swf", "invit0r_chart_1", "700", "200",
"9.0.0", "expressInstall.swf",
{"data-file": invit0r_dir + "stats-data-file.php"} );
swfobject.embedSWF(
invit0r_dir + "open-flash-chart.swf", "invit0r_chart_7", "700", "200",
"9.0.0", "expressInstall.swf",
{"data-file": invit0r_dir + "stats-data-file.php?unit=7"} );
swfobject.embedSWF(
invit0r_dir + "open-flash-chart.swf", "invit0r_chart_31", "700", "200",
"9.0.0", "expressInstall.swf",
{"data-file": invit0r_dir + "stats-data-file.php?unit=31"} );
<file_sep>/select-contacts.php
<?php
require_once('../../../wp-load.php');
// If there is not session established, redirect to Yahoo "Agree" or "Login" page
if (invit0r_check_session() == false) {
wp_redirect( invit0r_auth_url() );
exit;
}
$sep = '[%sep%]';
// Check to see if the "Submit" button was pressed
if (!empty($_POST)) {
// Check to see if any contacts were selected
if (!empty($_POST['contact_this'])) {
// Get the email addresses of the users already in the Wordpress database
$results = $wpdb->get_results("SELECT `user_email` FROM `" . $wpdb->users . "`");
// Start building the insert query
$query = "INSERT IGNORE INTO `" . $wpdb->prefix . "invit0r_invitees` (`hash`, `email_address`, `given_name`, `middle_name`, `family_name`, `nickname`, `time_added`, `time_resent`) VALUES ";
$mysql_values = array();
// Go through every selected contact
foreach ($_POST['contact_this'] as $values_str) {
$values_array = explode($sep, $values_str);
if (count($values_array) == 5) {
if (is_numeric($values_array[4])) {
$email = $_POST['contact_email' . $values_array[4]];
} else {
$email = $values_array[4];
}
// If the email is a valid one and is not already present in the Wordpress database, add it to the insert query
if ( is_email($email) && !invit0r_in_multiarray($email, $results) ) {
$mysql_values[] = "('" . $wpdb->escape(invit0r_generate_random_hash(32)) . "',
'" . $wpdb->escape($email) . "',
'" . $wpdb->escape($values_array[0]) . "',
'" . $wpdb->escape($values_array[1]) . "',
'" . $wpdb->escape($values_array[2]) . "',
'" . $wpdb->escape($values_array[3]) . "',
" . time() . ",
" . time() . ")";
}
}
}
// Insert the contacts in the database
$wpdb->query($query . implode(', ', $mysql_values));
wp_redirect( plugins_url('select-contacts.php?suc=1', __FILE__) );
exit;
} else {
$error = 'You haven`t selected any contacts';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Select contacts</title>
<style type="text/css">
body {
font-family: arial;
font-size:12px;
background-color:#fff;
}
.row {
height:18px;
padding:8px 0;
clear:both;
cursor:pointer;
}
.row div {
float:left;
overflow:hidden;
height:18px;
}
.number {
width:30px;
padding-left:5px;
}
.name {
width:120px;
}
.nickname {
width:100px;
}
.email {
width:220px;
}
.table-header {
font-weight:bold;
background:transparent url('images/headerGd.png') repeat-x left top;
height:35px;
line-height:35px;
padding:0;
}
.table-header div {
overflow:visible;
}
.error {
padding:5px;
color:#E55908;
border:1px solid #E55908;
font-weight:bold;
}
.suc {
padding:5px;
color:#64A01E;
border:1px solid #64A01E;
font-weight:bold;
}
.alt {
background-color:#f6f8d9;
}
select {
width:200px;
}
</style>
<script type="text/javascript">
window.onload = function() {
var elements = document.getElementsByTagName('input'); // This is used to fix a little bug in the script
for (var i in elements)
elements[i].onclick = function(e){
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
document.getElementById('select_all').onclick = function(e) { // The select all feature
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
var elements = document.getElementsByTagName('input');
for (var i in elements)
elements[i].checked = this.checked;
}
var divs = document.getElementsByTagName('div');
for (var i in divs) {
if (typeof(divs[i].className) != "undefined" && divs[i].className.search(/row/) != -1) {
divs[i].onclick = function(){ // Used for checking and unchecking the input filed
this.getElementsByTagName('input')[0].click();
}
divs[i].onmouseover = function(){ // Used for highlighting the row
this.style.backgroundColor = '#f5e0ad';
}
divs[i].onmouseout = function(){ // Used for unhighlighting the row
if (this.className.search(/alt/) != -1) {
this.style.backgroundColor = '#f6f8d9';
} else {
this.style.backgroundColor = '#ffffff';
}
}
}
}
}
</script>
</head>
<body>
<div id="wrap">
<?php
if (isset($_GET['suc'])) {
echo '<p class="suc">Your friends have been invited. Thank you!</p>';
} else {
if (isset($error)) {
echo '<p class="error">' , $error , '</p>';
}
?>
<form action="<?php echo plugins_url('select-contacts.php', __FILE__);?>" method="POST">
<?php
// Get the contacts from Yahoo
$contacts = invit0r_get_contacts(0, 1000)->contacts;
echo '<div class="row table-header">
<div class="number">#</div>
<div class="name">Name</div>
<div class="nickname">Nickname</div>
<div class="email">
<span style="float:right;">
Select all / none
</span>
Email
</div>
<div>
<input type="checkbox" id="select_all" />
</div>
</div>';
if (!empty($contacts) && is_object($contacts)) {
foreach ($contacts->contact as $index => $contact) {
$emails = array();
$yahooid = '';
$givenName = '';
$middleName = '';
$familyName = '';
$nickname = '';
// Go through every contact
foreach ($contact->fields as $field) {
if ($field->type == 'yahooid') {
$yahooid = $field->value;
if (strpos($yahooid, '@') === false) {
$yahooid .= '@yahoo.com';
}
if (!in_array($yahooid, $emails)) {
$emails[] = $yahooid;
}
}
if ($field->type == 'name') {
$givenName = esc_attr($field->value->givenName);
$middleName = esc_attr($field->value->middleName);
$familyName = esc_attr($field->value->familyName);
}
if($field->type =='nickname') {
$nickname = esc_attr($field->value);
}
if ($field->type == 'email' && !in_array($field->value, $emails)) {
$emails[] = $field->value;
}
if ($field->type == 'otherid') {
if (strpos($field->value, '@') !== false && !in_array($field->value, $emails)) {
$emails[] = $field->value;
}
}
}
// If the contact has an email, display the row
if (!empty($emails)) {
$name = $givenName . ' ' . $middleName . ' ' . $familyName;
echo '<div class="row' , $index % 2 == 1 ? ' alt' : '' , '">
<div class="number">' , $index + 1 , '</div>
<div class="name" title="' , $name , '">' , $name , ' </div>
<div class="nickname" title="' , $nickname , '">' , $nickname , ' </div>
<div class="email">';
$values = "$givenName$sep$middleName$sep$familyName$sep$nickname$sep";
if (count($emails) > 1) {
// Use a select if the contact has multiple email addresses
echo '<select name="contact_email' , $index , '">';
foreach ($emails as $email) {
echo '<option value="' , $email , '">' , $email , '</option>';
}
echo '</select>';
$values .= $index;
} else {
echo '<div title="' , $emails[0] , '">' , $emails[0] , '</div>';
$values .= $emails[0];
}
echo '</div>
<div>
<input type="checkbox" name="contact_this[]" id="id' , $index , '" value="' , $values , '" />
</div>
</div>';
}
}
} else {
echo '<p class="error">There was an error fetching your contacts, please try again later.</p>';
}
?>
<br /><br />
<button type="submit" name="submit">Submit</button>
</form>
<?php
}
?>
</div>
</body>
</html>
<file_sep>/unsubscribe.php
<?php
require_once('../../../wp-load.php');
if (!isset($_GET['suc'])) {
// Check to see if email and hash are set
if (isset($_GET['email'], $_GET['hash'])) {
// Check to see if this is just a test
if ($_GET['email'] == 'test_email' && $_GET['hash'] == 'test_hash') {
$suc = 'Nothing happened, but everything\'s ok :)';
} else if (is_email($_GET['email'])) { // If a valid email was provided, execute code
// Check to see if the email is in the database
$row = $wpdb->get_row("SELECT `id`, `unsubscribe` FROM `" . $wpdb->prefix . "invit0r_invitees` WHERE
`email_address` = '" . $wpdb->escape($_GET['email']) . "' AND `hash` = '" . $wpdb->escape($_GET['hash']) . "'");
// If the email is in the database, unsubscribe the user
if ($row) {
if ($row->unsubscribe == 1) {
$error = 'You already have been unsubscribed from our invitation list';
} else {
$wpdb->query("UPDATE `" . $wpdb->prefix . "invit0r_invitees` SET `unsubscribe` = '1' WHERE `id` = " . $row->id);
wp_redirect(plugins_url('unsubscribe.php?suc=1', __FILE__));
}
} else {
$error = 'The provided email address was not found in our database..';
}
} else {
$error = 'Authentification failed! Invalid data provided...';
}
} else {
$error = 'Authentification failed! Invalid data provided...';
}
} else {
$suc = 'You have been successfully unsubscribed from our invitation list';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Unsubscribe</title>
<style type="text/css">
.error {
padding:5px;
color:#E55908;
border:1px solid #E55908;
font-weight:bold;
}
.suc {
padding:5px;
color:#64A01E;
border:1px solid #64A01E;
font-weight:bold;
}
</style>
</head>
<body>
<?php
// If there is a success message, display it
if (isset($_GET['suc'])) {
echo '<p class="suc">' , $suc , '</p>';
}
// If there is an error, display it
if (isset($error)) {
echo '<p class="error">' , $error , '</p>';
}
?>
<p>Click here to proceed to our <a href="<?php echo get_bloginfo('url');?>">homapge</a>.</p>
</body>
</html>
<file_sep>/export-contacts.php
<?php
// Restrict the access to the plugin's option page only to administrators
invit0r_restrict_admin();
?>
<div class="wrap">
<h2>Invit0r Export Contacts</h2>
<br /> <a class="button" href="<?php echo plugins_url('export-contacts-data-file.php', __FILE__); ?>">Export</a>
</div>
<file_sep>/readme.txt
=== Plugin Name ===
Contributors: G0dLik3
Tags: invite, Yahoo, contacts, email, non-BuddyPress
Requires at least: 2.8.6
Tested up to: 3.2.1
Stable tag: 0.22
This plugin enables your users to invite their friends to your website. Only Yahoo! Mail accounts currently work.
== Description ==
This plugin enables your users to invite their friends to your website. You have comprehensive control over the appearance of the invitation, using your own design. Admins can opt to send out reminders for the invitations. It works only with Yahoo! Mail accounts. Users can select which friends to invite. The recipients can unsubscribe from further invitations. Also, registered users on your website will not receive the invitation.
== Installation ==
1. Upload the invit0r folder to the /wp-content/plugins/ directory.
2. Activate Invit0r through the 'Plugins' menu in WordPress.
3. Get your Api key from https://developer.apps.yahoo.com/dashboard/createKey.html and fill in the fields under 'OAuth Settings'.
4. Fill in the 'Sender name' (optional), 'Sender email'*, 'Subject'* and 'Body'* fields, and modify the rest of them if you want to.
5. Add `<?php invit0r_display();?>` where you want the invite link to show up.
6. Enjoy and may you get a lot of new visitors!
* 'Sender email', 'Subject' and 'Body' are required in order for the plugin to send invites, reminders and test emails.
* If you have a version >= 0.20, you can safely delete `invit0r/select_contacts.php` and `invit0r/js/invit0r_admin.js` as I have replaced them with `invit0r/select-contacts.php` and `invit0r/js/invit0r-admin.js`.
== How it works ==
After you have successfully installed and configured the plugin, and placed `<?php invit0r_display();?>` somewhere on your site, when a visitor invites his Yahoo! contacts, they (the contacts) will be placed in the database and an email with the details written in the 'Sender name', 'Sender email', 'Subject' and 'Body' fields will be sent to each one of them (limiting the number of emails sent at a time to the number written in the '1st time emails per batch' field). Note that the cron job will also try to send reminders (if enabled) at the same time with 1st time emails. You can controll the limit from the configuration page. That's all folks.
== Frequently Asked Questions ==
= invit0r_display() is not displaying anything! What's wrong? =
You probably didn't fill in the fields under the 'OAuth Settings' section with the corret values.
Or you called the display function passing null as parameter.
= I hate that 'Yahoo!' icon. Is there a way to change that? =
Sure! You can specify an image that you want (needs to be the whole <img> tag) or any other html tag that can go in an anchor tag.
You can also specify plain text, or if you don't want to display anything in the invite link just call the display function with null.
Examples:
`<?php invit0r_display('<img src="my-image.jpg" alt="" width="100" height="50" />');?>
<?php invit0r_display('<span class="my-custom-span">Some text</span>');?>
<?php invit0r_display(null);?>`
= Do I need BuddyPress? =
NO, you do not need BuddyPress.
= My question is not in this FAQ. Help! =
Just send me the question and I'll see what I can do.
== Screenshots ==
1. Invit0r submenu
2. Invit0r configuration page
3. Invit0r configuration continued
4. Invit0r export page
5. Invit0r import page
6. Invit0r stats page
7. The invite link + logout
8. The contacts select page
== Changelog ==
= 0.22 =
* Fixed a few bugs
= 0.21 =
* Fixed a few bugs
= 0.2 =
* Moved Invit0r in its own submenu
* Added 'Reminders per batch'
* Added 'Reminders limit'
* Added a simple csv export page
* Added a simple stats page
* Added a new field in the database table, 'is_imported', which indicates whether the contacts were invited or imported (imported contacts prior to this update will be counted as invited)
* Added and replaced a few screenshots
* Changed 'Email per batch' to '1st time emails per batch'
* Changed the importer so it doesn't import emails which already are in the 'wp_users' table
* Renamed js/invit0r_admin.js to js/invit0r-admin.js
* Renamed select_contacts.php to select-contacts.php
= 0.12 =
* Added contacts import
= 0.11 =
* Fixed a bug causing the admin area to deny access to any non-admin users
* Fixed a bug causing the invit0r_link to vanish after closing the popup and quickly refreshing the page
<file_sep>/export-contacts-data-file.php
<?php
ob_start();
require_once('../../../wp-load.php');
ob_end_clean();
if ( !current_user_can('manage_options') ) {
wp_die( __('You are not allowed to access this part of the site.') );
}
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=invit0r-contacts.csv');
header('Pragma: no-cache');
$query = "SELECT `id`, `email_address`, `given_name`, `middle_name`, `family_name`, `nickname`, DATE(FROM_UNIXTIME(`time_added`)) AS `date_added`, DATE(FROM_UNIXTIME(`time_resent`)) AS `date_resent`, `invites_sent`, `unsubscribe`, `is_imported` FROM `" . $wpdb->prefix . "invit0r_invitees` ORDER BY `time_added` DESC";
$results = $wpdb->get_results($query, ARRAY_A);
echo "id,email_address,given_name,middle_name,family_name,nickname,date_added,date_resent,invites_sent,unsubscribe,is_imported\r\n";
foreach ($results as $result) {
foreach ($result as $index => $value) {
$result[$index] = preg_replace('/[,\r\n\t]+/', ' ', $value);
}
echo $result['id'] , ',',
$result['email_address'] , ',' ,
$result['given_name'] , ',' ,
$result['middle_name'] , ',' ,
$result['family_name'] , ',' ,
$result['nickname'] , ',' ,
$result['date_added'] , ',' ,
$result['date_resent'] , ',' ,
$result['invites_sent'] , ',' ,
$result['unsubscribe'] , ',' ,
$result['is_imported'] , "\r\n";
}
| 93b3916e2f7bb92ebc6e2f7811bbc65e0fc8c0cb | [
"JavaScript",
"Text",
"PHP"
] | 13 | PHP | WPPlugins/invit0r | 588b34d1b6ae94c78dbb53613ad89605d1b13b9d | ddc915a0eced2530956391b5f16ed11fd001d7fa |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.